From 63184901f4348400dfc37ca7bb2e96f1abe9bf07 Mon Sep 17 00:00:00 2001 From: Bryan Date: Sat, 14 Nov 2026 20:45:05 +0800 Subject: [PATCH 1/6] Reject stale DAG snapshots atomically and bound incremental storage work --- src/dag/store.ts | 158 +++++++++++++++++++++++++++---- src/database.ts | 11 +++ src/keyed-lock.ts | 35 +++++++ tests/dag-store.test.ts | 203 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 387 insertions(+), 20 deletions(-) create mode 100644 src/keyed-lock.ts create mode 100644 tests/dag-store.test.ts diff --git a/src/dag/store.ts b/src/dag/store.ts index 987ca89..826a6d3 100644 --- a/src/dag/store.ts +++ b/src/dag/store.ts @@ -6,8 +6,18 @@ import type { DagAction, DagDefinition, DagEvent, DagNodeRecord, DagNotice, DagR import { noticeFor } from "./notices" type RunRow = { run_id: string; owner_session_id: string; name: string; definition_json: string; fingerprint: string; generation: number; status: DagRunRecord["status"]; created_at: number; updated_at: number } +export interface ListRunsOptions { + /** Only runs that are still going; a finished run can never change again. */ + readonly open?: boolean + readonly limit?: number +} type NodeRow = { run_id: string; node_id: string; node_json: string; fingerprint: string; status: DagNodeRecord["status"]; attempt: number; result_json: string | null; error: string | null; execution_json: string | null; created_at: number; updated_at: number } +/** Runs that can still change; only these are tracked for incremental saves. */ +const OPEN = new Set(["running", "paused"]) +const BASE_REVISION = Symbol("dag.baseRevision") +type PersistedRun = DagRunRecord & { [BASE_REVISION]?: number } + function parse(value: string): T { return JSON.parse(value) as T } @@ -20,6 +30,16 @@ export class DagStore { readonly path: string readonly project: string private readonly db: Database + /** + * What this connection knows the database holds for each open run: one stamp per stored row, and the same + * stamp on the record object that was read from or written to it. A record carrying its row's current stamp is + * already stored, so a save skips it. Stamps are trusted only while + * `PRAGMA data_version` is unchanged, which is until another connection commits. + */ + private readonly rows = new Map }>() + private readonly stamps = new WeakMap() + private clock = 0 + private version = -1 constructor(path: string, project: string) { this.path = path @@ -35,16 +55,38 @@ export class DagStore { if (run.authorizedPlan && run.authorizedAtlasNodes) this.db.run("INSERT INTO dag_authorizations VALUES (?, ?, ?)", [run.runID, run.authorizedPlan, canonicalJson(run.authorizedAtlasNodes)]) for (const node of run.nodes) this.writeNode(run.runID, node) }) + ;(run as PersistedRun)[BASE_REVISION] = 0 + this.remember(run, true, run.nodes) } saveRun(run: DagRunRecord, events: readonly Omit[] = [], steering: readonly DagSteerRequest[] = [], notices = false): readonly DagEvent[] { if (!this.owns(run.runID)) throw new Error("Unknown DAG run in this project") const committed: DagEvent[] = [] + const written: DagNodeRecord[] = [] + let fresh = true this.transaction(() => { - this.db.run("UPDATE dag_runs SET definition_json = ?, fingerprint = ?, generation = ?, status = ?, updated_at = ? WHERE run_id = ? AND project = ?", [canonicalJson(run.definition), run.fingerprint, run.generation, run.status, run.updatedAt, run.runID, this.project]) - this.db.run("DELETE FROM dag_nodes WHERE run_id = ?", [run.runID]) - this.db.run("DELETE FROM dag_node_runtime WHERE run_id = ?", [run.runID]) - for (const node of run.nodes) this.writeNode(run.runID, node) + // Inside the write transaction nobody else can commit, so what is known now stays true until this commits. + this.sync() + const base = (run as PersistedRun)[BASE_REVISION] + const changed = base === undefined ? 0 : this.db.run("UPDATE dag_run_revisions SET revision = revision + 1 WHERE run_id = ? AND revision = ?", [run.runID, base]).changes + if (changed !== 1) throw new Error("Stale DAG run: read the current run before saving") + const known = this.rows.get(run.runID) + fresh = known?.definition === undefined || this.stamps.get(run.definition) !== known.definition + if (fresh) { + this.db.run("UPDATE dag_runs SET definition_json = ?, fingerprint = ?, generation = ?, status = ?, updated_at = ? WHERE run_id = ? AND project = ?", [canonicalJson(run.definition), run.fingerprint, run.generation, run.status, run.updatedAt, run.runID, this.project]) + // Removing a node is the definition's business; an unchanged definition keeps the same node ids. + const ids = canonicalJson(run.nodes.map((node) => node.definition.id)) + this.db.run("DELETE FROM dag_nodes WHERE run_id = ? AND node_id NOT IN (SELECT value FROM json_each(?))", [run.runID, ids]) + this.db.run("DELETE FROM dag_node_runtime WHERE run_id = ? AND node_id NOT IN (SELECT value FROM json_each(?))", [run.runID, ids]) + } else { + this.db.run("UPDATE dag_runs SET fingerprint = ?, generation = ?, status = ?, updated_at = ? WHERE run_id = ? AND project = ?", [run.fingerprint, run.generation, run.status, run.updatedAt, run.runID, this.project]) + } + for (const node of run.nodes) { + const stamp = this.stamps.get(node) + if (stamp !== undefined && stamp === known?.nodes.get(node.definition.id)) continue + this.writeNode(run.runID, node) + written.push(node) + } for (const request of steering) this.saveSteering(request) for (const event of events) { const entry = this.appendEvent(event) @@ -55,13 +97,21 @@ export class DagStore { committed.push(entry) } }) + ;(run as PersistedRun)[BASE_REVISION] = (run as PersistedRun)[BASE_REVISION]! + 1 + this.remember(run, fresh, written) return committed } /** `anyProject` reads a run another project's controller owns; only lineage uses it, for runs working in this project. */ getRun(runID: string, anyProject = false): DagRunRecord | undefined { + return this.db.transaction(() => this.readRun(runID, anyProject))() + } + + private readRun(runID: string, anyProject: boolean): PersistedRun | undefined { + const version = this.dataVersion() const row = (anyProject ? this.db.query("SELECT * FROM dag_runs WHERE run_id = ?").get(runID) : this.db.query("SELECT * FROM dag_runs WHERE run_id = ? AND project = ?").get(runID, this.project)) as RunRow | null if (!row) return undefined + const revision = this.db.query("SELECT revision FROM dag_run_revisions WHERE run_id = ?").get(runID) as { revision: number } const nodeRows = this.db.query("SELECT * FROM dag_nodes WHERE run_id = ? ORDER BY node_id").all(runID) as NodeRow[] const definition = parse(row.definition_json) const positions = new Map(definition.nodes.map((node, index) => [node.id, index])) @@ -71,31 +121,56 @@ export class DagStore { const recoveryRows = this.db.query("SELECT node_id, value_json FROM dag_node_recovery WHERE run_id = ?").all(runID) as Array<{ node_id: string; value_json: string }> const recovery = new Map(recoveryRows.map((row) => [row.node_id, parse>(row.value_json)])) const authorization = this.db.query("SELECT plan, atlas_nodes_json FROM dag_authorizations WHERE run_id = ?").get(runID) as { plan: string; atlas_nodes_json: string } | null + const nodes = nodeRows.map((node) => ({ + definition: parse(node.node_json), fingerprint: node.fingerprint, + status: node.status, attempt: node.attempt, + ...(runtime.has(node.node_id) ? { runtime: runtime.get(node.node_id)! } : {}), + ...(recovery.has(node.node_id) ? { recovery: recovery.get(node.node_id)! } : {}), + ...(node.result_json ? { result: parse>(node.result_json) } : {}), + ...(node.error ? { error: node.error } : {}), + ...(node.execution_json ? { execution: parse>(node.execution_json) } : {}), + createdAt: node.created_at, updatedAt: node.updated_at, + })) + // These records are what the database holds, unless another connection committed while the rows were read. + if (!anyProject && OPEN.has(row.status) && this.dataVersion() === version) { + this.sync() + const known = this.rows.get(runID) ?? { nodes: new Map() } + this.rows.set(runID, known) + this.stamps.set(definition, known.definition ??= ++this.clock) + for (const node of nodes) { + const stamp = known.nodes.get(node.definition.id) ?? ++this.clock + known.nodes.set(node.definition.id, stamp) + this.stamps.set(node, stamp) + } + } return { + [BASE_REVISION]: revision.revision, runID: row.run_id, ownerSessionID: row.owner_session_id, name: row.name, ...(authorization ? { authorizedPlan: authorization.plan, authorizedAtlasNodes: parse>(authorization.atlas_nodes_json) } : {}), definition, fingerprint: row.fingerprint, generation: row.generation, status: row.status, createdAt: row.created_at, updatedAt: row.updated_at, - nodes: nodeRows.map((node) => ({ - definition: parse(node.node_json), fingerprint: node.fingerprint, - status: node.status, attempt: node.attempt, - ...(runtime.has(node.node_id) ? { runtime: runtime.get(node.node_id)! } : {}), - ...(recovery.has(node.node_id) ? { recovery: recovery.get(node.node_id)! } : {}), - ...(node.result_json ? { result: parse>(node.result_json) } : {}), - ...(node.error ? { error: node.error } : {}), - ...(node.execution_json ? { execution: parse>(node.execution_json) } : {}), - createdAt: node.created_at, updatedAt: node.updated_at, - })), + nodes, } } - listRuns(ownerSessionID?: string): readonly DagRunRecord[] { - const rows = ownerSessionID === undefined - ? this.db.query("SELECT run_id FROM dag_runs WHERE project = ? ORDER BY updated_at DESC").all(this.project) as Array<{ run_id: string }> - : this.db.query("SELECT run_id FROM dag_runs WHERE project = ? AND owner_session_id = ? ORDER BY updated_at DESC").all(this.project, ownerSessionID) as Array<{ run_id: string }> + listRuns(ownerSessionID?: string, options: ListRunsOptions = {}): readonly DagRunRecord[] { + const conditions = ["project = ?", ...(ownerSessionID === undefined ? [] : ["owner_session_id = ?"]), ...(options.open ? ["status NOT IN ('completed', 'failed', 'cancelled')"] : [])] + const params: Array = [this.project, ...(ownerSessionID === undefined ? [] : [ownerSessionID])] + // A terminal run can never change again, so an open listing is also the newest part of the history. + const limit = options.limit === undefined ? "" : " LIMIT ?" + if (options.limit !== undefined) params.push(options.limit) + const rows = this.db.query(`SELECT run_id FROM dag_runs WHERE ${conditions.join(" AND ")} ORDER BY updated_at DESC${limit}`).all(...params) as Array<{ run_id: string }> return rows.map((row) => this.getRun(row.run_id)).filter((run): run is DagRunRecord => run !== undefined) } + /** The observed run an owner already records for an observed batch, if one exists. */ + observedRun(ownerSessionID: string, batch: { readonly kind: string; readonly id: string }): DagRunRecord | undefined { + const row = this.db.query(`SELECT run_id FROM dag_runs WHERE project = ? AND owner_session_id = ? AND json_extract(definition_json, '$.observed') = 1 + AND json_extract(definition_json, '$.observedBatch.kind') = ? AND json_extract(definition_json, '$.observedBatch.id') = ? + ORDER BY updated_at DESC LIMIT 1`).get(this.project, ownerSessionID, batch.kind, batch.id) as { run_id: string } | null + return row ? this.getRun(row.run_id) : undefined + } + recovery(runID: string, nodeID: string): DagNodeRecord["recovery"] { if (!this.owns(runID)) return undefined const row = this.db.query("SELECT value_json FROM dag_node_recovery WHERE run_id = ? AND node_id = ?").get(runID, nodeID) as { value_json: string } | null @@ -119,6 +194,18 @@ export class DagStore { return rows.map((row) => parse(row.value_json)) } + notice(eventID: string): DagNotice | undefined { + const row = this.db.query("SELECT n.value_json FROM dag_notices n JOIN dag_runs r ON r.run_id = n.run_id WHERE r.project = ? AND n.event_id = ?").get(this.project, eventID) as { value_json: string } | null + return row ? parse(row.value_json) : undefined + } + + /** Notices a restart still has to deliver or reconcile. */ + undeliveredNotices(): readonly DagNotice[] { + const rows = this.db.query(`SELECT n.value_json FROM dag_notices n JOIN dag_runs r ON r.run_id = n.run_id + WHERE r.project = ? AND json_extract(n.value_json, '$.state') <> 'admitted' ORDER BY n.rowid`).all(this.project) as Array<{ value_json: string }> + return rows.map((row) => parse(row.value_json)) + } + saveNotice(notice: DagNotice): void { if (!this.owns(notice.runID)) throw new Error("Unknown DAG run in this project") this.db.run("INSERT INTO dag_notices VALUES (?, ?, ?) ON CONFLICT(event_id) DO UPDATE SET value_json = excluded.value_json", [notice.eventID, notice.runID, canonicalJson(notice)]) @@ -160,8 +247,39 @@ export class DagStore { private writeNode(runID: string, node: DagNodeRecord): void { if (node.recovery) this.db.run("INSERT INTO dag_node_recovery VALUES (?, ?, ?) ON CONFLICT(run_id, node_id) DO UPDATE SET value_json = excluded.value_json", [runID, node.definition.id, canonicalJson(node.recovery)]) - if (node.runtime) this.db.run("INSERT INTO dag_node_runtime VALUES (?, ?, ?)", [runID, node.definition.id, canonicalJson(node.runtime)]) - this.db.run("INSERT INTO dag_nodes VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", [runID, node.definition.id, canonicalJson(node.definition), node.fingerprint, node.status, node.attempt, node.result ? canonicalJson(node.result) : null, node.error ?? null, node.execution ? canonicalJson(node.execution) : null, node.createdAt ?? Date.now(), node.updatedAt ?? Date.now()]) + if (node.runtime) this.db.run("INSERT INTO dag_node_runtime VALUES (?, ?, ?) ON CONFLICT(run_id, node_id) DO UPDATE SET value_json = excluded.value_json", [runID, node.definition.id, canonicalJson(node.runtime)]) + else this.db.run("DELETE FROM dag_node_runtime WHERE run_id = ? AND node_id = ?", [runID, node.definition.id]) + this.db.run("INSERT INTO dag_nodes VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(run_id, node_id) DO UPDATE SET node_json = excluded.node_json, fingerprint = excluded.fingerprint, status = excluded.status, attempt = excluded.attempt, result_json = excluded.result_json, error = excluded.error, execution_json = excluded.execution_json, updated_at = excluded.updated_at", + [runID, node.definition.id, canonicalJson(node.definition), node.fingerprint, node.status, node.attempt, node.result ? canonicalJson(node.result) : null, node.error ?? null, node.execution ? canonicalJson(node.execution) : null, node.createdAt ?? Date.now(), node.updatedAt ?? Date.now()]) + } + + private dataVersion(): number { + return (this.db.query("PRAGMA data_version").get() as { data_version: number }).data_version + } + + /** Forgets every stamp once another connection has committed: its rows are no longer what this one wrote. */ + private sync(): void { + const version = this.dataVersion() + if (version === this.version) return + this.version = version + this.rows.clear() + } + + /** Stamps what a committed write stored. A finished run is forgotten: its next save, if any, writes it whole. */ + private remember(run: DagRunRecord, definition: boolean, written: readonly DagNodeRecord[]): void { + if (!OPEN.has(run.status)) { this.rows.delete(run.runID); return } + const known = this.rows.get(run.runID) ?? { nodes: new Map() } + this.rows.set(run.runID, known) + if (definition) { + this.stamps.set(run.definition, known.definition = ++this.clock) + const kept = new Set(run.nodes.map((node) => node.definition.id)) + for (const id of known.nodes.keys()) if (!kept.has(id)) known.nodes.delete(id) + } + for (const node of written) { + const stamp = ++this.clock + known.nodes.set(node.definition.id, stamp) + this.stamps.set(node, stamp) + } } private transaction(fn: () => void): void { diff --git a/src/database.ts b/src/database.ts index ffa36f3..f95bf97 100644 --- a/src/database.ts +++ b/src/database.ts @@ -32,6 +32,13 @@ export function openDatabase(path: string): Database { created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, PRIMARY KEY (run_id, node_id), FOREIGN KEY (run_id) REFERENCES dag_runs(run_id) ON DELETE CASCADE ); + CREATE TABLE IF NOT EXISTS dag_run_revisions ( + run_id TEXT PRIMARY KEY REFERENCES dag_runs(run_id) ON DELETE CASCADE, + revision INTEGER NOT NULL DEFAULT 0 + ); + INSERT OR IGNORE INTO dag_run_revisions (run_id) SELECT run_id FROM dag_runs; + CREATE TRIGGER IF NOT EXISTS dag_run_revision_insert AFTER INSERT ON dag_runs + BEGIN INSERT INTO dag_run_revisions (run_id) VALUES (NEW.run_id); END; CREATE TABLE IF NOT EXISTS dag_authorizations ( run_id TEXT PRIMARY KEY REFERENCES dag_runs(run_id) ON DELETE CASCADE, plan TEXT NOT NULL, atlas_nodes_json TEXT NOT NULL @@ -89,4 +96,8 @@ export class SessionStateStore { this.onSave?.(sessionID) } close(): void { this.db.close() } + delete(kind: "role" | "goal", sessionID: string): void { + this.db.run("DELETE FROM session_state WHERE session_id = ? AND kind = ?", [sessionID, kind]) + this.onSave?.(sessionID) + } } diff --git a/src/keyed-lock.ts b/src/keyed-lock.ts new file mode 100644 index 0000000..3147155 --- /dev/null +++ b/src/keyed-lock.ts @@ -0,0 +1,35 @@ +import { Effect, Semaphore } from "effect" + +export interface KeyedLock { + /** Runs `task` while holding the one permit of `key`; other keys run concurrently. */ + readonly withLock: (key: string, task: Effect.Effect) => Effect.Effect + /** Keys currently held or waited on. Zero when nothing uses the lock. */ + readonly size: () => number +} + +/** + * One permit per key, created when a task uses the key and dropped once nothing holds or waits on + * it, so a long-lived process that touches a key per run, notice or session does not keep every + * semaphore it ever needed. + */ +export function createKeyedLock(): KeyedLock { + const entries = new Map() + return { + // The key is registered and its release installed with interruption masked, so a caller interrupted the + // moment it has registered still releases the key; waiting for the permit and the task stay interruptible. + withLock: (key, task) => Effect.uninterruptibleMask((restore) => Effect.suspend(() => { + let entry = entries.get(key) + if (!entry) { + entry = { permit: Semaphore.makeUnsafe(1), users: 0 } + entries.set(key, entry) + } + const current = entry + current.users += 1 + return restore(current.permit.withPermit(task)).pipe(Effect.ensuring(Effect.sync(() => { + current.users -= 1 + if (current.users === 0 && entries.get(key) === current) entries.delete(key) + }))) + })), + size: () => entries.size, + } +} diff --git a/tests/dag-store.test.ts b/tests/dag-store.test.ts new file mode 100644 index 0000000..e8298ed --- /dev/null +++ b/tests/dag-store.test.ts @@ -0,0 +1,203 @@ +import { Database } from "bun:sqlite" +import { afterEach, expect, test } from "bun:test" +import { Context, Effect, Fiber, Scheduler } from "effect" +import { mkdtempSync, realpathSync, rmSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { DagStore } from "../src/dag/store" +import { createKeyedLock } from "../src/keyed-lock" +import type { DagNodeRecord, DagRunRecord } from "../src/dag/types" + +let directory: string | undefined +afterEach(() => { if (directory) rmSync(directory, { recursive: true, force: true }); directory = undefined }) + +const record = (id: string, extra: Partial = {}): DagNodeRecord => + ({ definition: { id, agent: "quick", model: "o/m", prompt: id, dependsOn: [] }, fingerprint: id, status: "pending", attempt: 0, createdAt: 1, updatedAt: 1, ...extra }) +const runOf = (runID: string, owner: string, nodes: readonly DagNodeRecord[], extra: Partial = {}): DagRunRecord => + ({ runID, ownerSessionID: owner, name: runID, definition: { schemaVersion: 1, name: runID, nodes: nodes.map((node) => node.definition) }, fingerprint: "f", generation: 1, status: "running", nodes, createdAt: 1, updatedAt: 1, ...extra }) + +test("a save rewrites only the records that changed while the database is as this connection left it", () => { + directory = mkdtempSync(join(tmpdir(), "iolaus-store-")) + const path = join(directory, "iolaus.db") + const store = new DagStore(path, directory) + store.createRun(runOf("r", "owner", [record("a"), record("b"), record("c")])) + // Another connection logs every node row the store writes. + const raw = new Database(path) + raw.exec(`CREATE TABLE write_log (node_id TEXT); + CREATE TRIGGER log_insert AFTER INSERT ON dag_nodes BEGIN INSERT INTO write_log VALUES (NEW.node_id); END; + CREATE TRIGGER log_update AFTER UPDATE ON dag_nodes BEGIN INSERT INTO write_log VALUES (NEW.node_id); END;`) + const written = () => (raw.query("SELECT node_id FROM write_log ORDER BY rowid").all() as Array<{ node_id: string }>).map((row) => row.node_id) + const stored = () => store.getRun("r")!.nodes.map((node) => [node.definition.id, node.status]) + + const seen = store.getRun("r")! + const a: DagNodeRecord = { ...seen.nodes[0]!, status: "completed" } + const first = { ...seen, nodes: [a, seen.nodes[1]!, seen.nodes[2]!] } + store.saveRun(first) + expect(written()).toEqual(["a"]) + // A read in between returns new objects for the same rows; a record derived from the earlier read still skips them. + store.getRun("r") + const paused: DagRunRecord = { ...first, status: "paused" } + store.saveRun(paused, [{ schemaVersion: 1, runID: "r", generation: 1, type: "run.paused", createdAt: 2 }]) + expect(written()).toEqual(["a"]) + expect(store.getRun("r")!.status).toBe("paused") + + const d = record("d") + const grown = { ...paused, definition: { ...first.definition, nodes: [a.definition, seen.nodes[1]!.definition, d.definition] }, nodes: [a, seen.nodes[1]!, d] } + store.saveRun(grown) + expect(written()).toEqual(["a", "d"]) + expect(stored()).toEqual([["a", "completed"], ["b", "pending"], ["d", "pending"]]) + + // Once another connection has written, the record is saved whole: never this writer's header over that writer's rows. + raw.exec("UPDATE dag_nodes SET status = 'completed' WHERE node_id = 'b'") + store.saveRun({ ...grown, generation: 2 }) + expect(written().slice(3).sort()).toEqual(["a", "b", "d"]) + expect(stored()).toEqual([["a", "completed"], ["b", "pending"], ["d", "pending"]]) + raw.close(); store.close() +}) + +test("a stale snapshot cannot roll back a newer generation or append events", () => { + directory = mkdtempSync(join(tmpdir(), "iolaus-store-")) + const store = new DagStore(join(directory, "iolaus.db"), directory) + store.createRun(runOf("r", "owner", [record("a")], { fingerprint: "f1" })) + const old = store.getRun("r")! + const b = record("b") + store.saveRun({ ...old, definition: { ...old.definition, nodes: [b.definition] }, fingerprint: "f2", generation: 2, nodes: [b] }) + expect(store.getRun("r")!.nodes.map((node) => node.definition.id)).toEqual(["b"]) + + const before = store.getRun("r")! + expect(() => store.saveRun(old, [{ schemaVersion: 1, runID: "r", generation: 1, type: "run.paused", createdAt: 3 }])).toThrow("Stale DAG run") + const back = store.getRun("r")! + expect(back).toEqual(before) + expect([back.generation, back.fingerprint, back.definition.nodes.map((node) => node.id), back.nodes.map((node) => node.definition.id)]).toEqual([2, "f2", ["b"], ["b"]]) + expect(store.events("r")).toEqual([]) + store.close() +}) + +test.each([false, true])("same-generation stale saves are rejected with a second connection: %s", (separate) => { + directory = mkdtempSync(join(tmpdir(), "iolaus-store-")) + const path = join(directory, "iolaus.db") + const store = new DagStore(path, directory) + const other = separate ? new DagStore(path, directory) : store + store.createRun(runOf("r", "owner", [record("a")])) + store.createRun(runOf("unrelated", "owner", [record("b")])) + const stale = other.getRun("r")! + const latest = store.getRun("r")! + const updated: DagRunRecord = { ...latest, status: "paused", nodes: [{ ...latest.nodes[0]!, status: "completed" }] } + store.saveRun(updated) + const before = store.getRun("r")! + const request = { runID: "r", nodeID: "a", requestID: "supplement", text: "keep this", execution: { nodeID: "a", attempt: 1, sessionID: "child" }, generation: 1, revision: 1, messageID: "msg_1", state: "delivered", createdAt: 2 } as const + store.saveSteering(request) + expect(() => other.saveRun({ ...stale, status: "failed" }, [{ schemaVersion: 1, runID: "r", generation: 1, type: "run.failed", createdAt: 2 }], [{ ...request, state: "unresolved" }], true)).toThrow("Stale DAG run") + expect(store.getRun("r")).toEqual(before) + expect(store.events("r")).toEqual([]) + expect(store.notices("r")).toEqual([]) + expect(store.steering("r")).toEqual([request]) + + const fresh = other.getRun("r")! + store.saveRun({ ...store.getRun("unrelated")!, status: "paused" }) + other.saveRun(fresh) + other.saveRun(fresh, [{ schemaVersion: 1, runID: "r", generation: 1, type: "run.paused", createdAt: 3 }]) + other.saveRun({ ...fresh, status: "running" }) + expect(store.getRun("r")!.status).toBe("running") + expect(store.events("r")).toHaveLength(1) + if (separate) other.close() + store.close() +}) + +test("a failed transaction rolls back its revision, nodes, header and side effects", () => { + directory = mkdtempSync(join(tmpdir(), "iolaus-store-")) + const path = join(directory, "iolaus.db") + const store = new DagStore(path, directory) + const original = runOf("r", "owner", [record("a")]) + store.createRun(original) + const before = store.getRun("r")! + const updated: DagRunRecord = { ...before, status: "failed", nodes: [{ ...before.nodes[0]!, status: "failed" }] } + const raw = new Database(path) + raw.exec("CREATE TRIGGER reject_notice AFTER INSERT ON dag_notices BEGIN SELECT RAISE(ABORT, 'notice refused'); END") + const event = { schemaVersion: 1, runID: "r", generation: 1, type: "run.failed", createdAt: 2 } as const + expect(() => store.saveRun(updated, [event], [], true)).toThrow("notice refused") + expect(store.getRun("r")).toEqual(before) + expect(store.events("r")).toEqual([]) + expect(store.notices("r")).toEqual([]) + expect(raw.query("SELECT * FROM dag_actions").all()).toEqual([]) + raw.exec("DROP TRIGGER reject_notice") + store.saveRun(updated, [event], [], true) + expect(store.getRun("r")!.nodes[0]!.status).toBe("failed") + expect(store.events("r")).toHaveLength(1) + expect(store.notices("r")).toHaveLength(1) + raw.close(); store.close() +}) + +test("legacy databases gain revisions without changing positional run inserts", () => { + directory = mkdtempSync(join(tmpdir(), "iolaus-store-")) + const path = join(directory, "iolaus.db") + const raw = new Database(path) + raw.exec(`CREATE TABLE dag_runs ( + run_id TEXT PRIMARY KEY, project TEXT NOT NULL, owner_session_id TEXT NOT NULL, name TEXT NOT NULL, + definition_json TEXT NOT NULL, fingerprint TEXT NOT NULL, generation INTEGER NOT NULL, + status TEXT NOT NULL, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL + )`) + const definition = JSON.stringify({ schemaVersion: 1, name: "legacy", nodes: [] }) + raw.run("INSERT INTO dag_runs VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ["legacy", realpathSync(directory), "owner", "legacy", definition, "f", 1, "running", 1, 1]) + const store = new DagStore(path, directory) + const old = store.getRun("legacy")! + store.saveRun({ ...old, status: "paused" }) + expect(() => store.saveRun(old)).toThrow("Stale DAG run") + raw.exec("INSERT INTO dag_runs SELECT 'copied',project,owner_session_id,name,definition_json,fingerprint,generation,status,created_at,updated_at FROM dag_runs WHERE run_id='legacy'") + store.saveRun({ ...store.getRun("copied")!, status: "running" }) + expect(store.getRun("copied")!.status).toBe("running") + raw.close(); store.close() +}) + +test("runs are listed open-only or newest-first up to a limit, and a batch or notice is found without reading the rest", () => { + directory = mkdtempSync(join(tmpdir(), "iolaus-store-")) + const store = new DagStore(join(directory, "iolaus.db"), directory) + store.createRun(runOf("done", "o", [record("a", { status: "completed" })], { status: "completed", updatedAt: 1 })) + store.createRun(runOf("live", "o", [record("a")], { updatedAt: 2 })) + store.createRun(runOf("held", "o", [record("a", { status: "waiting_approval" })], { status: "paused", updatedAt: 3 })) + store.createRun(runOf("theirs", "x", [record("a")], { updatedAt: 4 })) + const batch = runOf("calls", "o", [record("1-scan", { status: "completed" })], { status: "completed", updatedAt: 5 }) + store.createRun({ ...batch, definition: { ...batch.definition, observed: true, observedBatch: { kind: "request", id: "msg_1" } } }) + const ids = (runs: readonly DagRunRecord[]) => runs.map((run) => run.runID) + expect(ids(store.listRuns("o"))).toEqual(["calls", "held", "live", "done"]) + expect(ids(store.listRuns("o", { open: true }))).toEqual(["held", "live"]) + expect(ids(store.listRuns("o", { limit: 2 }))).toEqual(["calls", "held"]) + expect(ids(store.listRuns(undefined, { open: true }))).toEqual(["theirs", "held", "live"]) + expect(store.observedRun("o", { kind: "request", id: "msg_1" })?.runID).toBe("calls") + expect(store.observedRun("x", { kind: "request", id: "msg_1" })).toBeUndefined() + expect(store.observedRun("o", { kind: "flow", id: "msg_1" })).toBeUndefined() + + const notice = (eventID: string, state: "pending" | "admitted") => ({ eventID, runID: "live", ownerSessionID: "o", messageID: `msg_${eventID}`, text: eventID, state }) + store.saveNotice(notice("e1", "admitted")); store.saveNotice(notice("e2", "pending")) + expect(store.notice("e2")?.state).toBe("pending") + expect(store.notice("nope")).toBeUndefined() + expect(store.undeliveredNotices().map((value) => value.eventID)).toEqual(["e2"]) + store.close() +}) + +test("a keyed lock serializes one key, lets other keys run, and keeps no key once nothing uses it", async () => { + const locks = createKeyedLock() + const order: string[] = [] + const task = (name: string, ms: number) => locks.withLock("run", Effect.promise(async () => { + order.push(`${name}:start`); await new Promise((done) => setTimeout(done, ms)); order.push(`${name}:end`) + })) + await Promise.all([Effect.runPromise(task("a", 15)), Effect.runPromise(task("b", 1)), Effect.runPromise(locks.withLock("other", Effect.sync(() => { order.push("other") })))]) + expect(order.filter((entry) => entry !== "other")).toEqual(["a:start", "a:end", "b:start", "b:end"]) + expect(order.indexOf("other")).toBeLessThan(order.indexOf("a:end")) + expect(locks.size()).toBe(0) + await Effect.runPromise(Effect.exit(locks.withLock("run", Effect.fail("boom")))) + expect(locks.size()).toBe(0) +}) + +test("a keyed lock drops its key when the caller is interrupted the moment it has registered", async () => { + const locks = createKeyedLock() + // Yield once, right after the key exists, so the interrupt lands between registering and running the task. + const base = new Scheduler.MixedScheduler() + let yielded = false + const once: Scheduler.Scheduler = { executionMode: base.executionMode, makeDispatcher: () => base.makeDispatcher(), + shouldYield: () => { if (yielded || locks.size() !== 1) return false; yielded = true; return true } } + const fiber = Effect.runForkWith(Context.make(Scheduler.Scheduler, once))(locks.withLock("run", Effect.never)) + expect([yielded, locks.size()]).toEqual([true, 1]) + await Effect.runPromise(Fiber.interrupt(fiber)) + expect(locks.size()).toBe(0) +}) From afb0f97a9c8600310dade1f0837f6f79b224e3f9 Mon Sep 17 00:00:00 2001 From: Bryan Date: Sat, 14 Nov 2026 20:45:05 +0800 Subject: [PATCH 2/6] Run Hephaestus goals on host idle and respect pause, resume and clear --- script/qa-roles.mjs | 49 +++++++ src/roles/goal.ts | 202 ++++++++++++++++------------- src/roles/register.ts | 49 +++++-- tests/background-subagents.test.ts | 19 ++- tests/roles.test.ts | 171 ++++++++++++++++++++++-- 5 files changed, 369 insertions(+), 121 deletions(-) diff --git a/script/qa-roles.mjs b/script/qa-roles.mjs index bd2127a..c72ca18 100644 --- a/script/qa-roles.mjs +++ b/script/qa-roles.mjs @@ -195,6 +195,13 @@ async function reply(body, instructions, input, session) { if (rounds === 0) return outs.length ? { text: "STEP_ONE" } : { call: { name: "read", args: { path: "fixture.txt" } } } return /^(function|custom_tool)_call_output$/.test(last?.type) ? { text: "GOAL_DONE" } : { call: { name: "update_goal", args: { status: "complete" } } } } + case "goal-control": { + // One tool call, then one reply, per turn: every round counts as progress, so only the user's commands change the goal. + await sleep(300) + const turn = items.findLastIndex((item) => item?.type === "message" && (item.role === "user" || JSON.stringify(item).includes("Continue working toward the active session goal"))) + const acted = items.slice(turn + 1).some((item) => /^(function|custom_tool)_call_output$/.test(item?.type)) + return acted ? { text: "CONTROL_STEP" } : { call: { name: "read", args: { path: "fixture.txt" } } } + } case "goal-wait": { if (first.includes("GOAL_SUB_SCAN")) { await sleep(2500); return { text: "GOAL_SUB_DONE" } } const rounds = input.split("Continue working toward the active session goal").length - 1 @@ -512,6 +519,48 @@ try { assert.ok(of(id).find((r) => r.call?.name === "update_goal").input.includes("GOAL_SUB_DONE"), "the loop continued before the subagent reported") }) + await check("/goal accepts the host's pause, resume and clear", async () => { + active = "goal-control" + const id = await create("hephaestus") + const goalRow = () => JSON.parse(execFileSync("sqlite3", ["-readonly", join(home, ".iolaus/iolaus.db"), `SELECT value_json FROM session_state WHERE session_id = '${id}' AND kind = 'goal'`], { encoding: "utf8" }).trim() || "null") + await api("POST", `/api/session/${id}/command`, { name: "goal", text: "IOLAUS_CONTROL_TASK keep reading the fixture" }) + await until(() => traces().some((t) => t.event === "iolaus.goal.continued" && t.sessionID === id), "first continuation") + await api("POST", `/api/session/${id}/command`, { name: "goal", text: "pause" }) + const paused = await until(() => { const goal = goalRow(); return goal.status === "paused" ? goal : undefined }, "paused goal") + assert.equal(paused.reason, "Paused by the user") + // The round in flight and the reply to the pause itself still finish; after that nothing may continue the session. + const quiet = async () => { + const deadline = Date.now() + 30000 + while (Date.now() < deadline) { + const seen = of(id).length + await sleep(2000) + if (seen === of(id).length) return seen + } + throw new Error("goal control did not become quiet within 30 seconds") + } + const rounds = () => traces().filter((t) => t.event === "iolaus.goal.continued" && t.sessionID === id).length + const settled = await quiet(), continued = rounds() + await sleep(2500) + assert.equal(of(id).length, settled, "the loop kept going after /goal pause") + assert.equal(rounds(), continued, "a continuation was queued after /goal pause") + assert.equal(goalRow().status, "paused") + await api("POST", `/api/session/${id}/command`, { name: "goal", text: "resume" }) + const resumed = await until(() => { const goal = goalRow(); return goal.status === "active" && goal.continuations > 0 ? goal : undefined }, "resumed goal") + assert.equal(resumed.stagnant, 0) + await api("POST", `/api/session/${id}/command`, { name: "goal", text: "clear" }) + await until(() => goalRow() === null, "cleared goal") + const ended = await quiet() + await sleep(2500) + assert.equal(of(id).length, ended, "the loop kept going after /goal clear") + for (const text of ["resume", ""]) { + await api("POST", `/api/session/${id}/command`, { name: "goal", text }) + await quiet() + assert.equal(goalRow(), null, "/goal resurrected a cleared goal") + } + const updates = traces().filter((t) => t.sessionID === id && t.event === "iolaus.goal.updated" && t.via === "command") + assert.deepEqual(updates.map((t) => t.status), ["paused", null]) + }) + await check("a goal that makes no progress pauses after three idle turns", async () => { active = "stall" const id = await create("hephaestus") diff --git a/src/roles/goal.ts b/src/roles/goal.ts index 41c2204..b1172e9 100644 --- a/src/roles/goal.ts +++ b/src/roles/goal.ts @@ -1,20 +1,20 @@ -import { Effect } from "effect" +import { Cause, Effect, Exit } from "effect" import type { Tool } from "@opencode/schema/tool" import type { SessionStateStore } from "../database" +import { randomUUID } from "node:crypto" /** * Hephaestus goal loop, after OMO's goal hook (oh-my-openagent, OpenCode 2 - * adapter, hooks/goal): the session goal is persisted in the shared database, - * and when the session goes idle with the goal still active the - * plugin queues a continuation prompt until the agent calls `update_goal` with - * `complete`. The runaway stops come from OMO's todo-continuation enforcer: a cap on - * continuations and a stop after consecutive turns that made no tool call. + * adapter, hooks/goal) and the host's own `opencode.goal` plugin: the session goal is persisted in + * the shared database, and when the host is about to let the session go idle with the goal still + * active, a continuation prompt is admitted so the same execution keeps working. The host's + * `experimental.idle` hook is the trigger, so nothing polls and a turn that delegated to subagents + * resumes when their reports wake the session. The runaway stops are a cap on continuations and a + * stop after consecutive turns that made no tool call. */ export const GOAL_MAX_CONTINUATIONS = 50 export const GOAL_STAGNATION_LIMIT = 3 const MAX_OBJECTIVE = 2000 -/** A queued continuation that never starts (host dropped it) stops being waited for after this. */ -const START_TIMEOUT_MS = 15000 /** Direct tools are hidden per agent by their own name, so registration denies these to every lane but Hephaestus. */ export const GOAL_TOOL_NAMES = ["get_goal", "create_goal", "update_goal"] as const @@ -31,6 +31,7 @@ export interface Goal { readonly reason?: string readonly createdAt: number readonly updatedAt: number + readonly revision?: string } export function readGoal(state: SessionStateStore, sessionID: string): Goal | null { @@ -39,7 +40,7 @@ export function readGoal(state: SessionStateStore, sessionID: string): Goal | nu } export function saveGoal(state: SessionStateStore, goal: Goal): void { - state.save("goal", goal.sessionID, goal) + state.save("goal", goal.sessionID, { ...goal, revision: randomUUID() }) } export function setGoal(state: SessionStateStore, sessionID: string, objective: string, now = Date.now()): Goal { @@ -58,6 +59,25 @@ export function extendGoal(state: SessionStateStore, sessionID: string, request: return next } +/** The host's `/goal pause | resume | clear` spellings, which Iolaus's `/goal` accepts too. */ +export const GOAL_CONTROLS = ["pause", "resume", "clear"] as const +export type GoalControl = typeof GOAL_CONTROLS[number] + +/** A user resume starts a fresh continuation budget, as the host's `/goal resume` does. */ +export function resumeGoal(state: SessionStateStore, sessionID: string, now = Date.now()): Goal | null { + const goal = readGoal(state, sessionID) + if (!goal || goal.status !== "paused") return null + const next: Goal = { sessionID: goal.sessionID, objective: goal.objective, status: "active", continuations: 0, stagnant: 0, createdAt: goal.createdAt, updatedAt: now } + saveGoal(state, next) + return next +} + +export function clearGoal(state: SessionStateStore, sessionID: string): Goal | null { + const goal = readGoal(state, sessionID) + state.delete("goal", sessionID) + return goal +} + export function updateGoal(state: SessionStateStore, sessionID: string, status: GoalStatus, reason?: string, now = Date.now()): Goal | null { const goal = readGoal(state, sessionID) if (!goal) return null @@ -97,103 +117,109 @@ export function continuationPrompt(goal: Goal): string { ].join("\n") } +/** + * The part of the host's `experimental.idle` background list the loop reads: a `subagent` or `image` job + * owned by the session itself wakes it when it finishes. Other fields are the host's and are not read. + */ +export interface IdleBackground { + readonly kind: string + readonly sessionID: string + readonly childSessionID?: string + readonly agent?: string + readonly description?: string + readonly model?: string + readonly path?: string + readonly shellID?: string + readonly command?: string +} + export interface GoalRuntimePorts { readonly read: (sessionID: string) => Goal | null readonly save: (goal: Goal) => void /** A top-level Hephaestus session; DAG children and subagent sessions never loop. */ - readonly isGoalSession: (sessionID: string) => Promise - readonly dispatch: (sessionID: string, text: string) => Promise - readonly settle: () => Promise - /** Subagents of the session are still working; their report wakes it, and the loop decides at that turn's end. */ - readonly waiting?: (sessionID: string) => Promise + readonly isGoalSession: (sessionID: string) => Effect.Effect + /** Admits the continuation into the session that is about to go idle. */ + readonly dispatch: (sessionID: string, text: string) => Effect.Effect readonly now?: () => number readonly trace?: (event: string, data: Record) => void } export type GoalRuntime = ReturnType -/** The host events `handle` switches on; the plugin subscribes to these only. */ -export const GOAL_EVENT_TYPES = ["session.execution.started", "session.execution.succeeded", "session.idle", "session.execution.failed", "session.execution.interrupted", "session.deleted"] as const - -function sessionOf(event: unknown): { readonly type: string; readonly sessionID?: string } { - const record = typeof event === "object" && event !== null ? event as { type?: unknown; data?: { sessionID?: unknown } } : {} - const sessionID = record.data?.sessionID - return { type: typeof record.type === "string" ? record.type : "", ...(typeof sessionID === "string" ? { sessionID } : {}) } -} - export function createGoalRuntime(ports: GoalRuntimePorts) { const now = ports.now ?? Date.now - const activity = new Map() - const calls = new Map() - /** Sessions whose continuation was queued but has not started; their late idle edges are the previous turn's. */ - const awaiting = new Map() + /** Tool calls since the loop's last decision; a round that made none is a stagnant turn. */ + const calls = new Map() const inflight = new Set() - /** Sessions whose last turn ended waiting on subagents; the turn their report starts continues that turn's tool count. */ - const waited = new Set() - - const continueGoal = async (sessionID: string): Promise => { - const goal = ports.read(sessionID) - if (!goal || goal.status !== "active" || inflight.has(sessionID)) return - if ((awaiting.get(sessionID) ?? 0) > now()) return - inflight.add(sessionID) - try { - await ports.settle() - if (activity.get(sessionID) !== "idle" || !(await ports.isGoalSession(sessionID))) return - const current = ports.read(sessionID) - if (!current || current.status !== "active") return - if (await ports.waiting?.(sessionID)) { - waited.add(sessionID) - ports.trace?.("iolaus.goal.waiting", { sessionID }) - return - } - waited.delete(sessionID) - const stagnant = (calls.get(sessionID) ?? 0) === 0 ? current.stagnant + 1 : 0 - const stop = stagnant >= GOAL_STAGNATION_LIMIT ? "stagnated" : current.continuations >= GOAL_MAX_CONTINUATIONS ? "continuation limit" : undefined - if (stop) { - ports.save({ ...current, status: "paused", stagnant, reason: stop, updatedAt: now() }) - ports.trace?.("iolaus.goal.paused", { sessionID, reason: stop, continuations: current.continuations }) - return - } - const next: Goal = { ...current, stagnant, continuations: current.continuations + 1, updatedAt: now() } + const fingerprint = (goal: Goal | null) => JSON.stringify(goal) + + const decide = (sessionID: string, background: readonly IdleBackground[]) => Effect.gen(function* () { + if (!(yield* ports.isGoalSession(sessionID))) { + calls.delete(sessionID) + return + } + const current = ports.read(sessionID) + if (!current || current.status !== "active") { + calls.delete(sessionID) + return + } + if (background.some((work) => (work.kind === "subagent" || work.kind === "image") && work.sessionID === sessionID)) { + ports.trace?.("iolaus.goal.waiting", { sessionID }) + return + } + const round = calls.get(sessionID) + const stagnant = round?.goal === fingerprint(current) && round.count > 0 ? 0 : current.stagnant + 1 + calls.delete(sessionID) + const stop = stagnant >= GOAL_STAGNATION_LIMIT ? "stagnated" : current.continuations >= GOAL_MAX_CONTINUATIONS ? "continuation limit" : undefined + if (stop) { + ports.save({ ...current, status: "paused", stagnant, reason: stop, updatedAt: now() }) + ports.trace?.("iolaus.goal.paused", { sessionID, reason: stop, continuations: current.continuations }) + return + } + const next: Goal = { ...current, stagnant, continuations: current.continuations + 1, updatedAt: now() } + const dispatched = yield* Effect.exit(Effect.suspend(() => ports.dispatch(sessionID, continuationPrompt(next)))) + if (fingerprint(ports.read(sessionID)) !== fingerprint(current)) return + if (Exit.isSuccess(dispatched)) { ports.save(next) - activity.set(sessionID, "busy") - awaiting.set(sessionID, now() + START_TIMEOUT_MS) - await ports.dispatch(sessionID, continuationPrompt(next)) ports.trace?.("iolaus.goal.continued", { sessionID, continuations: next.continuations, stagnant }) - } catch (error) { - awaiting.delete(sessionID) - ports.trace?.("iolaus.goal.continuation-failed", { sessionID, error: error instanceof Error ? error.message : String(error) }) - } finally { - inflight.delete(sessionID) + } else { + const error = String(Cause.squash(dispatched.cause)).slice(0, 300) + ports.save({ ...current, status: "paused", reason: `Continuation dispatch failed: ${error}. Fix the error and use /goal resume.`, updatedAt: now() }) + ports.trace?.("iolaus.goal.continuation-failed", { sessionID, error }) } - } + }) return { - toolCalled(sessionID: string): void { - calls.set(sessionID, (calls.get(sessionID) ?? 0) + 1) + reset(sessionID: string): void { + calls.delete(sessionID) + }, + toolCalled(sessionID: string): Effect.Effect { + return Effect.gen(function* () { + const goal = ports.read(sessionID) + if (!goal || goal.status !== "active") { calls.delete(sessionID); return } + if (!(yield* ports.isGoalSession(sessionID))) { calls.delete(sessionID); return } + const key = fingerprint(goal) + if (fingerprint(ports.read(sessionID)) !== key) return + const previous = calls.get(sessionID) + calls.set(sessionID, { goal: key, count: previous?.goal === key ? previous.count + 1 : 1 }) + }) }, - async handle(event: unknown): Promise { - const { type, sessionID } = sessionOf(event) - if (!sessionID) return - switch (type) { - case "session.execution.started": - activity.set(sessionID, "busy") - awaiting.delete(sessionID) - if (!waited.has(sessionID)) calls.set(sessionID, 0) - return - case "session.execution.succeeded": - case "session.idle": - activity.set(sessionID, "idle") - await continueGoal(sessionID) - return - case "session.execution.failed": - case "session.execution.interrupted": - activity.set(sessionID, "idle") - return - case "session.deleted": - activity.delete(sessionID); calls.delete(sessionID); awaiting.delete(sessionID); waited.delete(sessionID) - return - } + /** + * Runs when the host would let the session go idle. The session's own running subagent or image job + * wakes it with a report, so the loop leaves the decision to that turn instead of continuing now. + */ + idle(sessionID: string, background: readonly IdleBackground[] = []): Effect.Effect { + return Effect.suspend(() => { + if (inflight.has(sessionID)) return Effect.void + const goal = fingerprint(ports.read(sessionID)) + return Effect.acquireUseRelease( + Effect.sync(() => { inflight.add(sessionID) }), + () => decide(sessionID, background).pipe(Effect.onExit((exit) => Effect.sync(() => { + if (Exit.isFailure(exit) && calls.get(sessionID)?.goal === goal) calls.delete(sessionID) + }))), + () => Effect.sync(() => { inflight.delete(sessionID) }), + ) + }) }, } } @@ -243,7 +269,7 @@ export function createGoalTools(state: SessionStateStore, isGoalSession: (sessio if (status !== "complete" && status !== "paused" && status !== "active") return Effect.succeed(reply({ error: 'status must be "complete", "paused" or "active"' })) const sessionID = String(context.sessionID) return guarded(sessionID, () => { - const goal = updateGoal(state, sessionID, status, typeof record.reason === "string" ? record.reason : undefined) + const goal = status === "active" ? resumeGoal(state, sessionID) : updateGoal(state, sessionID, status, typeof record.reason === "string" ? record.reason : undefined) if (goal) trace?.(status === "complete" ? "iolaus.goal.completed" : "iolaus.goal.updated", { sessionID, status, continuations: goal.continuations }) return goal }) diff --git a/src/roles/register.ts b/src/roles/register.ts index 1073296..8c792ee 100644 --- a/src/roles/register.ts +++ b/src/roles/register.ts @@ -7,7 +7,7 @@ import type { DagController } from "../dag/controller" import { DAG_CHILD_MARKER } from "../prompts/mode-dag" import { agentName, categoryName, explicitMode } from "../prompts/catalog" import { COMMAND_OWNERS, commandMarker, commandOwner, parseCommand } from "./command" -import { createGoalRuntime, createGoalTools, extendGoal, GOAL_EVENT_TYPES, readGoal, saveGoal, setGoal, updateGoal } from "./goal" +import { clearGoal, createGoalRuntime, createGoalTools, extendGoal, GOAL_CONTROLS, readGoal, resumeGoal, saveGoal, setGoal, updateGoal } from "./goal" import { denial, inheritPlanning, resolvePolicy, type RoleRecord } from "./guard" import { loadPlan, PLANNING_MARKER, PLANS_DIR, resolvePlan } from "./plan" import { compilePlan, gitHead, parseStartWork, type Delivery } from "./startwork" @@ -16,7 +16,6 @@ import { homedir } from "node:os" import { resolve } from "node:path" import { isTopLevel, subagentTargets, tierDenial, type TierSource } from "./tier" import { DagValidationError } from "../dag/errors" -import { createQuiescence } from "../dag/quiesce" type Trace = (event: string, data?: Record) => void @@ -130,9 +129,32 @@ export function registerRoles(ctx: Context, options: Options, host: RoleHost): E return } if (agent !== "hephaestus" || !isGoalSessionInfo({ ...session, agent })) return + runtime.reset(sessionID) if (command?.name === "goal") { - const goal = command.args ? setGoal(state, sessionID, command.args) : readGoal(state, sessionID) ? updateGoal(state, sessionID, "active") : null + // The host's own `/goal pause | resume | clear` grammar, so the shared command name is not a defect. + const control = (GOAL_CONTROLS as readonly string[]).includes(command.args.toLowerCase()) ? command.args.toLowerCase() : undefined + if (control === "pause") { + const goal = readGoal(state, sessionID)?.status === "active" ? updateGoal(state, sessionID, "paused", "Paused by the user") : null + trace("iolaus.goal.updated", { sessionID, via: "command", status: goal?.status ?? null }) + event.prompt.text = `${commandMarker("goal")}\n${goal ? 'The user paused the goal. Tell them it is paused and stop working; only a new request resumes it.' : 'There is no active goal to pause. Say so and stop.'}` + return + } + if (control === "clear") { + const goal = clearGoal(state, sessionID) + trace("iolaus.goal.updated", { sessionID, via: "command", status: null }) + event.prompt.text = `${commandMarker("goal")}\n${goal ? 'The user cleared the goal. Confirm it is cleared and stop working.' : 'There is no goal to clear. Say so and stop.'}` + return + } + if (control === "resume") { + const goal = resumeGoal(state, sessionID) + trace("iolaus.goal.set", { sessionID, via: "command", active: goal?.status === "active" }) + event.prompt.text = `${commandMarker("goal")}\n${goal ? 'The user resumed the goal. Continue working toward it until update_goal reports it complete.' : 'There is no goal to resume. Say so and stop.'}` + return + } + const current = readGoal(state, sessionID) + const goal = command.args ? setGoal(state, sessionID, command.args) : current?.status === "active" ? current : resumeGoal(state, sessionID) trace("iolaus.goal.set", { sessionID, via: "command", active: goal?.status === "active" }) + if (!goal) event.prompt.text = `${commandMarker("goal")}\n/goal needs an objective or an existing goal. Ask the user what to pursue and stop.` return } if (command) return @@ -140,20 +162,17 @@ export function registerRoles(ctx: Context, options: Options, host: RoleHost): E trace("iolaus.goal.set", { sessionID, via: "prompt" }) })) - const quiescence = createQuiescence(ctx.session) const runtime = createGoalRuntime({ read: (sessionID) => readGoal(state, sessionID), save: (goal) => saveGoal(state, goal), - isGoalSession: (sessionID) => Effect.runPromise(isGoalSession(sessionID)), - dispatch: (sessionID, text) => Effect.runPromise(ctx.session.synthetic({ sessionID: sessionID as never, text, delivery: "queue", resume: true }).pipe(Effect.asVoid)), - settle: () => new Promise((done) => setTimeout(done, 150)), - waiting: (sessionID) => Effect.runPromise(quiescence.busy(sessionID).pipe(Effect.catchCause(() => Effect.succeed(false)))), + isGoalSession: (sessionID) => isGoalSession(sessionID), + dispatch: (sessionID, text) => ctx.session.synthetic({ sessionID: sessionID as never, text }).pipe(Effect.asVoid), trace, }) yield* ctx.tool.hook("execute.before", (event) => Effect.gen(function* () { const sessionID = String(event.sessionID) - runtime.toolCalled(sessionID) + yield* runtime.toolCalled(sessionID) const agent = String(event.agent) const role = readRole(state, sessionID) if (event.tool === "subagent") { @@ -182,12 +201,16 @@ export function registerRoles(ctx: Context, options: Options, host: RoleHost): E })) if (options.agents.includes("hephaestus")) { + yield* Effect.forkScoped(Stream.runForEach(ctx.event.subscribe({ types: ["session.execution.failed", "session.execution.interrupted"] }), (event) => Effect.sync(() => { + const data = (event as unknown as { data: { sessionID?: string } }).data + if (data.sessionID) runtime.reset(data.sessionID) + }))) const tools = createGoalTools(state, isGoalSession, trace) yield* ctx.tool.transform((editor) => { for (const tool of tools) editor.add(tool) }) - // Only the edges the goal runtime switches on; the default stream carries every text and reasoning delta. - yield* Effect.forkScoped(Stream.runForEach(ctx.event.subscribe({ types: GOAL_EVENT_TYPES }), (event) => - Effect.forkScoped(Effect.promise(() => runtime.handle(event))).pipe(Effect.asVoid)).pipe( - Effect.catchCause((cause) => Effect.sync(() => trace("iolaus.goal.events-stopped", { cause: String(cause) }))))) + // The host runs this hook when the session would go idle with nothing pending; input admitted here continues + // the same execution, which is what a goal continuation is. + yield* ctx.session.hook("experimental.idle", (event) => runtime.idle(String(event.sessionID), event.background).pipe( + Effect.catchCause((cause) => Effect.sync(() => trace("iolaus.goal.failed", { sessionID: String(event.sessionID), cause: String(cause).slice(0, 300) }))))) } trace("iolaus.roles.registered", { goal: options.agents.includes("hephaestus"), startWork: options.agents.includes("atlas") }) }) diff --git a/tests/background-subagents.test.ts b/tests/background-subagents.test.ts index a556919..9cbd15b 100644 --- a/tests/background-subagents.test.ts +++ b/tests/background-subagents.test.ts @@ -157,22 +157,19 @@ test("the goal loop waits for running subagents and counts the delegating turn's directory = mkdtempSync(join(tmpdir(), "iolaus-goal-wait-")) const state = new SessionStateStore(join(directory, "iolaus.db")) const dispatched: string[] = [] - let waiting = true const runtime = createGoalRuntime({ - read: (s) => readGoal(state, s), save: (g) => saveGoal(state, g), isGoalSession: async () => true, - dispatch: async (s) => { dispatched.push(s) }, settle: async () => {}, waiting: async () => waiting, + read: (s) => readGoal(state, s), save: (g) => saveGoal(state, g), isGoalSession: () => Effect.succeed(true), + dispatch: (s) => Effect.sync(() => { dispatched.push(s) }), }) + const idle = (background: NonNullable[1]>) => Effect.runPromise(runtime.idle("s", background)) setGoal(state, "s", "ship it") for (let round = 1; round <= 4; round++) { - waiting = true - await runtime.handle({ type: "session.execution.started", data: { sessionID: "s" } }) - runtime.toolCalled("s") - await runtime.handle({ type: "session.execution.succeeded", data: { sessionID: "s" } }) + // A turn that delegated and went idle: the subagent is still running, so nothing continues yet. + await Effect.runPromise(runtime.toolCalled("s")) + await idle([{ kind: "subagent", sessionID: "s", childSessionID: "ses_child", agent: "explore", description: "scan" }]) expect(dispatched).toHaveLength(round - 1) - // The subagent's report starts a turn that only reads it. - waiting = false - await runtime.handle({ type: "session.execution.started", data: { sessionID: "s" } }) - await runtime.handle({ type: "session.execution.succeeded", data: { sessionID: "s" } }) + // Its report wakes the session; that turn only reads the report, but the delegating turn's call still counts. + await idle([]) expect(dispatched).toHaveLength(round) } expect(readGoal(state, "s")).toMatchObject({ status: "active", continuations: 4, stagnant: 0 }) diff --git a/tests/roles.test.ts b/tests/roles.test.ts index 4281c3f..767e3f2 100644 --- a/tests/roles.test.ts +++ b/tests/roles.test.ts @@ -2,15 +2,16 @@ import { afterEach, expect, test } from "bun:test" import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs" import { tmpdir } from "node:os" import { join } from "node:path" -import { Effect } from "effect" +import { Deferred, Effect, Fiber, Queue, Stream } from "effect" +import type { Context } from "@opencode/plugin/effect/plugin" import { Agent } from "@opencode/plugin" import type { AgentEditor } from "@opencode/plugin/effect/agent" import { loadPlan, resolvePlan, PLANNING_MARKER, ticketMarker } from "../src/roles/plan" import { compilePlan } from "../src/roles/startwork" import { denial, inheritPlanning, resolvePolicy } from "../src/roles/guard" import { parseCommand, COMMAND_OWNERS } from "../src/roles/command" -import { createGoalRuntime, extendGoal, readGoal, saveGoal, setGoal, GOAL_MAX_CONTINUATIONS, GOAL_STAGNATION_LIMIT, GOAL_TOOL_NAMES, type Goal } from "../src/roles/goal" -import { isGoalSessionInfo } from "../src/roles/register" +import { clearGoal, createGoalRuntime, extendGoal, readGoal, resumeGoal, saveGoal, setGoal, updateGoal, GOAL_MAX_CONTINUATIONS, GOAL_STAGNATION_LIMIT, GOAL_TOOL_NAMES, type Goal } from "../src/roles/goal" +import { isGoalSessionInfo, registerRoles } from "../src/roles/register" import { validateDefinition } from "../src/dag/graph" import { applyDefaultModels } from "../src/dag/controller" import { REVIEW_VERDICT_FAIL } from "../src/dag/templates" @@ -144,20 +145,21 @@ test("goal loop continues an idle active goal, stops on completion, stagnation a const dispatched: string[] = [] const runtime = createGoalRuntime({ read: (s) => readGoal(dir, s), save: (g) => saveGoal(dir, g), - isGoalSession: async (s) => s !== "child", dispatch: async (s) => { dispatched.push(s) }, settle: async () => {}, + isGoalSession: (s) => Effect.succeed(s !== "child"), dispatch: (s) => Effect.sync(() => { dispatched.push(s) }), }) const turn = async (sessionID: string, toolCalls: number) => { - await runtime.handle({ type: "session.execution.started", data: { sessionID } }) - for (let i = 0; i < toolCalls; i++) runtime.toolCalled(sessionID) - await runtime.handle({ type: "session.execution.succeeded", data: { sessionID } }) + for (let i = 0; i < toolCalls; i++) await Effect.runPromise(runtime.toolCalled(sessionID)) + await Effect.runPromise(runtime.idle(sessionID)) } setGoal(dir, "s", "make tests green") await turn("s", 2) expect(dispatched).toEqual(["s"]) expect(readGoal(dir, "s")?.continuations).toBe(1) - // A late idle edge from the same turn does not dispatch twice. - await runtime.handle({ type: "session.idle", data: { sessionID: "s" } }) + expect(readGoal(dir, "s")?.stagnant).toBe(0) + // A subagent still running in the session wakes it with a report; the loop decides on that turn instead. + await Effect.runPromise(runtime.idle("s", [{ kind: "subagent", sessionID: "s" }])) expect(dispatched).toEqual(["s"]) + expect(readGoal(dir, "s")?.continuations).toBe(1) saveGoal(dir, { ...readGoal(dir, "s")!, status: "complete" }) await turn("s", 1) expect(dispatched).toEqual(["s"]) @@ -182,6 +184,157 @@ test("goal loop continues an idle active goal, stops on completion, stagnation a dir.close() }) +test("/goal accepts the host's pause, resume and clear, and a resume starts a fresh budget", () => { + directory = mkdtempSync(join(tmpdir(), "iolaus-goal-control-")) + const dir = new SessionStateStore(join(directory, "iolaus.db")) + setGoal(dir, "s", "ship it") + saveGoal(dir, { ...readGoal(dir, "s")!, continuations: GOAL_MAX_CONTINUATIONS, stagnant: 2 }) + expect(updateGoal(dir, "s", "paused", "Paused by the user")?.status).toBe("paused") + const resumed = resumeGoal(dir, "s") + expect(resumed).toMatchObject({ status: "active", continuations: 0, stagnant: 0 }) + expect(readGoal(dir, "s")?.objective).toBe("ship it") + expect(resumeGoal(dir, "s")).toBeNull() + expect(clearGoal(dir, "s")?.objective).toBe("ship it") + expect(readGoal(dir, "s")).toBeNull() + expect(resumeGoal(dir, "s")).toBeNull() + setGoal(dir, "done", "done") + updateGoal(dir, "done", "complete") + expect(resumeGoal(dir, "done")).toBeNull() + expect(resumeGoal(dir, "none")).toBeNull() + expect(clearGoal(dir, "none")).toBeNull() + dir.close() +}) + +test("goal dispatch is lazy, charges only success, and preserves racing user controls", async () => { + directory = mkdtempSync(join(tmpdir(), "iolaus-goal-dispatch-")) + const state = new SessionStateStore(join(directory, "iolaus.db")) + let dispatch = () => Effect.void as Effect.Effect + const runtime = createGoalRuntime({ + read: (s) => readGoal(state, s), save: (g) => saveGoal(state, g), + isGoalSession: () => Effect.succeed(true), dispatch: () => dispatch(), + }) + try { + setGoal(state, "s", "ship") + runtime.idle("s") + await Effect.runPromise(runtime.idle("s")) + expect(readGoal(state, "s")?.continuations).toBe(1) + dispatch = () => Effect.fail(new Error("admission unavailable")) + await Effect.runPromise(runtime.idle("s")) + expect(readGoal(state, "s")).toMatchObject({ status: "paused", continuations: 1 }) + expect(readGoal(state, "s")?.reason).toMatch(/admission unavailable.*\/goal resume/) + for (const [control, fails] of [["pause", false], ["clear", false], ["pause", true], ["clear", true]] as const) { + setGoal(state, "s", "ship") + const entered = Deferred.makeUnsafe() + const release = Deferred.makeUnsafe() + dispatch = () => Effect.gen(function* () { + yield* Deferred.succeed(entered, undefined) + yield* Deferred.await(release) + if (fails) yield* Effect.fail(new Error("admission unavailable")) + }) + const fiber = Effect.runFork(runtime.idle("s")) + await Effect.runPromise(Deferred.await(entered)) + expect(readGoal(state, "s")?.continuations).toBe(0) + if (control === "clear") clearGoal(state, "s") + else updateGoal(state, "s", "paused", "Paused by the user") + await Effect.runPromise(Deferred.succeed(release, undefined)) + await Effect.runPromise(Fiber.join(fiber)) + expect(readGoal(state, "s")?.status ?? null).toBe(control === "clear" ? null : "paused") + } + setGoal(state, "s", "ship") + dispatch = () => Effect.never + const fiber = Effect.runFork(runtime.idle("s")) + await Effect.runPromise(Effect.yieldNow) + await Effect.runPromise(Fiber.interrupt(fiber)) + expect(readGoal(state, "s")?.continuations).toBe(0) + dispatch = () => Effect.void + await Effect.runPromise(runtime.idle("s")) + expect(readGoal(state, "s")?.continuations).toBe(1) + expect(readGoal(state, "s")?.stagnant).toBe(1) + } finally { state.close() } +}) + +test("goal accounting belongs only to the current eligible goal and successful round", async () => { + directory = mkdtempSync(join(tmpdir(), "iolaus-goal-round-")) + const state = new SessionStateStore(join(directory, "iolaus.db")) + let eligibility = Effect.succeed(false) as Effect.Effect + const runtime = createGoalRuntime({ + read: (s) => readGoal(state, s), save: (g) => saveGoal(state, g), + isGoalSession: () => eligibility, dispatch: () => Effect.void, + }) + try { + setGoal(state, "s", "ship") + await Effect.runPromise(runtime.toolCalled("s")) + eligibility = Effect.succeed(true) + await Effect.runPromise(runtime.idle("s")) + expect(readGoal(state, "s")?.stagnant).toBe(1) + await Effect.runPromise(runtime.toolCalled("s")) + setGoal(state, "s", "replacement") + await Effect.runPromise(runtime.idle("s")) + expect(readGoal(state, "s")?.stagnant).toBe(1) + await Effect.runPromise(runtime.toolCalled("s")) + updateGoal(state, "s", "paused") + await Effect.runPromise(runtime.toolCalled("s")) + resumeGoal(state, "s") + await Effect.runPromise(runtime.idle("s")) + expect(readGoal(state, "s")?.stagnant).toBe(1) + await Effect.runPromise(runtime.toolCalled("s")) + const entered = Deferred.makeUnsafe() + eligibility = Deferred.succeed(entered, undefined).pipe(Effect.andThen(Effect.never)) + const fiber = Effect.runFork(runtime.idle("s")) + await Effect.runPromise(Deferred.await(entered)) + await Effect.runPromise(Fiber.interrupt(fiber)) + eligibility = Effect.succeed(true) + await Effect.runPromise(runtime.idle("s")) + expect(readGoal(state, "s")?.stagnant).toBe(2) + } finally { state.close() } +}) + +test("goal hooks remove cleared goals and discard failed or interrupted round accounting", async () => { + directory = mkdtempSync(join(tmpdir(), "iolaus-goal-hooks-")) + const state = new SessionStateStore(join(directory, "iolaus.db")) + type Hook = (event: unknown) => Effect.Effect + const hooks = new Map() + const events = Effect.runSync(Queue.unbounded<{ type: string; data: { sessionID: string } }>()) + const ctx = { + session: { + get: () => Effect.succeed({ agent: "hephaestus" }), + hook: (name: string, hook: Hook) => Effect.sync(() => { hooks.set(name, hook) }), + synthetic: () => Effect.void, + }, + tool: { + hook: (name: string, hook: Hook) => Effect.sync(() => { hooks.set(name, hook) }), + transform: () => Effect.void, + }, + event: { subscribe: () => Stream.fromQueue(events) }, + } as unknown as Context + try { + await Effect.runPromise(Effect.scoped(Effect.gen(function* () { + yield* registerRoles(ctx, parseOptions({ agents: ["hephaestus"] }), { + state, trace: () => {}, directory: () => Effect.succeed(directory!), controller: {} as never, source: () => Effect.die("not used"), + }) + for (const type of ["session.execution.failed", "session.execution.interrupted"]) { + setGoal(state, "s", "ship") + yield* hooks.get("execute.before")!({ sessionID: "s", agent: "hephaestus", tool: "read", input: {} }) + yield* Queue.offer(events, { type, data: { sessionID: "s" } }) + yield* Effect.yieldNow + yield* hooks.get("experimental.idle")!({ sessionID: "s", background: [] }) + expect(readGoal(state, "s")?.stagnant).toBe(1) + } + for (const text of ["/goal clear", "/goal resume", "/goal", "\nresume", "\n"]) { + yield* hooks.get("prompt")!({ sessionID: "s", prompt: { text } }) + expect(readGoal(state, "s")).toBeNull() + } + setGoal(state, "s", "ship") + saveGoal(state, { ...readGoal(state, "s")!, continuations: 7 }) + yield* hooks.get("prompt")!({ sessionID: "s", prompt: { text: "/goal resume" } }) + expect(readGoal(state, "s")?.continuations).toBe(7) + updateGoal(state, "s", "complete") + yield* hooks.get("prompt")!({ sessionID: "s", prompt: { text: "/goal resume" } }) + expect(readGoal(state, "s")?.status).toBe("complete") + }))) + } finally { state.close() } +}) + test("roles and goals round-trip in one database without project JSON files", () => { directory = mkdtempSync(join(tmpdir(), "iolaus-state-")) const path = join(directory, "iolaus.db") From 78f660b8a79659a13a38865b184d4ecf542b765d Mon Sep 17 00:00:00 2001 From: Bryan Date: Sat, 14 Nov 2026 20:47:35 +0800 Subject: [PATCH 3/6] Fence recovery and steering; invalidate stale descendants on retries --- script/qa-borrows.mjs | 14 ++- script/qa-flow-steering.mjs | 6 +- src/dag/controller.ts | 210 +++++++++++++++++++++++++----------- src/dag/graph.ts | 16 +++ src/dag/loop.ts | 33 +++++- src/dag/promise.ts | 5 +- src/dag/register-rpc.ts | 2 +- src/dag/tool.ts | 4 +- src/plugin.ts | 14 +-- src/session-state.ts | 15 ++- tests/dag-steering.test.ts | 122 +++++++++++++++++++++ tests/dag-templates.test.ts | 41 +++++++ tests/dag.test.ts | 197 ++++++++++++++++++++++++++++++++- 13 files changed, 594 insertions(+), 85 deletions(-) diff --git a/script/qa-borrows.mjs b/script/qa-borrows.mjs index e94656c..c2f8f3a 100644 --- a/script/qa-borrows.mjs +++ b/script/qa-borrows.mjs @@ -117,7 +117,10 @@ const mock = http.createServer(async (req, res) => { first: JSON.stringify((body.input ?? []).find((i) => i?.type === "message" && i.role === "user") ?? "").slice(0, 3000), last: JSON.stringify((body.input ?? []).findLast((i) => i?.type === "message" && i.role === "user") ?? "").slice(0, 3000), outputs: (body.input ?? []).filter((i) => i?.type === "function_call_output").map((i) => String(i.output).slice(0, 400)), - state: stateBlock(instructions + JSON.stringify(body.input ?? [])) } + // What the current instruction block says, and whether the host has told the model it no longer applies. + state: stateBlock(instructions + JSON.stringify(body.input ?? [])), + removal: (body.input ?? []).some((item) => Array.isArray(item.content) && item.content.some((part) => + typeof part.text === "string" && part.text.includes('The context under "iolaus.state" no longer applies. Disregard it.'))) } requests.push(record) appendFileSync(join(evidence, "requests.ndjson"), `${JSON.stringify(record)}\n`) assert.ok(requests.length < 300, "Unexpected model loop") @@ -280,6 +283,15 @@ try { assert.match(request.state, /Session role: orchestrator for plan "cache"/) }) + await check("a fork does not inherit the parent's session state", async () => { + const forked = (await api("POST", `/api/session/${orchestrator}/fork`, {})).data.id + await api("POST", `/api/session/${forked}/prompt`, { text: "QA_FORK_PROBE" }) + const request = await until(() => requests.find((r) => r.last.includes("QA_FORK_PROBE")), "fork request") + // A fork adopts the parent's instruction values as its baseline and cannot unsee them, so Iolaus recomputes the + // fork's own state (normally nothing) and has the host announce that the inherited block no longer applies. + assert.ok(request.removal, "the fork was not told the inherited state no longer applies") + }) + await check("approving the gate runs the PR node in the worktree", async () => { const worktree = `${project}-wt/cache` const done = (await rpc("action", { sessionID: orchestrator, action: "approve", runID: startRun.runID, generation: startRun.generation, nodeID: "accept", note: "QA" })).output.runs.find((r) => r.runID === startRun.runID) diff --git a/script/qa-flow-steering.mjs b/script/qa-flow-steering.mjs index 3537ab2..6b39bd7 100644 --- a/script/qa-flow-steering.mjs +++ b/script/qa-flow-steering.mjs @@ -193,7 +193,7 @@ try { const terminalCount = requests.length; await sleep(250); assert.equal(requests.length, terminalCount) passed("terminal notice present in inbox without an owner provider turn") await reject("settled target", () => steer(first.runID, "implement", "settled"), /active flow|running node/) - const gate = await create("human gate", [node("before", "gate-before"), { id: "gate", title: "human decision", kind: "gate", prompt: "Do not approve automatically", dependsOn: ["before"] }, node("pending", "pending", ["gate"])]) + const gate = await create("human gate", [node("before", "gate-before"), { id: "gate", title: "human decision", kind: "gate", prompt: "Do not approve automatically", dependsOn: ["before"] }, node("pending", "pending", ["gate"]), node("tail", "must-not-run", ["pending"])]) await until(() => holds.has("gate-before:old"), "before gate child"); release("gate-before:old") await until(async () => (await run(gate.runID)).status === "paused", "gate") await until(async () => (await inbox(owner)).some((item) => item.payload?.metadata?.iolaus_dag_run === gate.runID), "queued gate notice") @@ -209,6 +209,10 @@ try { await reject("gate target", () => steer(gate.runID, "gate", "gate"), /gate or judge/) await reject("pending initial target", () => steer(gate.runID, "pending", "pending"), /pending/) await command(owner, { action: "reject", run_id: gate.runID, node_id: "gate", note: "explicit QA human rejection" }) + const rejected = await run(gate.runID) + assert.equal(rejected.status, "failed") + assert.equal(rejected.nodes.find((n) => n.id === "tail").status, "blocked") + passed("gate rejection blocks the transitive tail and settles the flow") const foreign = await session() const active = await create("refusals", [node("implement", "refusals")]) await until(() => holds.has("refusals:old"), "refusal child") diff --git a/src/dag/controller.ts b/src/dag/controller.ts index c00ab78..961fea5 100644 --- a/src/dag/controller.ts +++ b/src/dag/controller.ts @@ -1,17 +1,18 @@ import { randomUUID } from "node:crypto" -import { Cause, Deferred, Effect, Exit, Fiber, Scope, Semaphore } from "effect" +import { Cause, Deferred, Effect, Exit, Fiber, Scope } from "effect" import { evaluateCondition } from "./condition" import { DagRunnerError, DagValidationError, errorMessage } from "./errors" import { dependencyState, isGate, validateDefinition } from "./graph" -import { growLoop } from "./loop" +import { growLoop, shrinkLoop } from "./loop" import { fingerprint, graphFingerprint, nodeFingerprint } from "./fingerprint" import type { DagRunner } from "./runner" -import { DagStore, resolveDagDatabasePath } from "./store" +import { DagStore, resolveDagDatabasePath, type ListRunsOptions } from "./store" +import { createKeyedLock } from "../keyed-lock" import { sameRepository } from "./worktree" import { canonicalProject } from "../database" import type { DagNotifier } from "./notices" import { normalizedModel, type NodeRecovery } from "./rescue" -import type { DagDefinition, DagEvent, DagNodeDefinition, DagNodeRecord, DagObservedStart, DagObservedUpdate, DagResolvedInput, DagResultEnvelope, DagRunRecord, DagSnapshot, DagSteerRequest, JsonValue } from "./types" +import type { DagDefinition, DagEvent, DagExecutionRef, DagNodeDefinition, DagNodeRecord, DagObservedStart, DagObservedUpdate, DagResolvedInput, DagResultEnvelope, DagRunRecord, DagSnapshot, DagSteerRequest, JsonValue } from "./types" export { DagValidationError } @@ -22,7 +23,8 @@ export { DagValidationError } export interface DagController { readonly lineage: (runID: string, nodeID: string, sessionID: string) => Effect.Effect readonly create: (definition: DagDefinition, ownerSessionID: string, authorizedPlan?: string) => Effect.Effect - readonly list: (ownerSessionID?: string) => Effect.Effect + /** Newest first. `open` leaves out finished runs; `limit` bounds how much history is read. */ + readonly list: (ownerSessionID?: string, options?: ListRunsOptions) => Effect.Effect readonly snapshot: (runID: string, ownerSessionID: string) => Effect.Effect readonly node: (runID: string, ownerSessionID: string, nodeID: string) => Effect.Effect readonly wait: (runID: string, ownerSessionID: string) => Effect.Effect @@ -48,7 +50,7 @@ export interface DagControllerOptions { readonly runner: DagRunner /** Global opt-in: after a node's fallbacks and attempts are spent on model failures, continue it once on the owner's model. */ readonly rescue?: { readonly ownerModel: boolean } - /** Restart recovery waits for this, so reattached children see a fully loaded host. */ + /** Restart recovery starts after this, so the nodes it settles and launches see every hook, tool and RPC the plugin registers. */ readonly recoveryReady?: Effect.Effect /** Returns the configured "provider/model[#variant]" for an agent ID, or undefined. */ readonly defaultModel?: (agent: string) => string | undefined @@ -154,7 +156,7 @@ export function createDagController(options: DagControllerOptions): DagControlle const runner = options.runner const now = options.now ?? Date.now const maxParallel = options.maxParallel ?? 5 - const locks = new Map() + const locks = createKeyedLock() const waiters = new Map>>() // Every launch fiber lives in this scope; closing the controller interrupts them. const scope = Scope.makeUnsafe() @@ -181,15 +183,11 @@ export function createDagController(options: DagControllerOptions): DagControlle if (options.notifier) Effect.runFork(Effect.forkIn(deliverNotice(created.eventID), scope)) } /** Per-run critical section. Each run has one permit, so state transitions never interleave. */ - const locked = (runID: string, task: Effect.Effect): Effect.Effect => { - let lock = locks.get(runID) - if (!lock) { lock = Semaphore.makeUnsafe(1); locks.set(runID, lock) } - return lock.withPermit(task) - } + const locked = (runID: string, task: Effect.Effect): Effect.Effect => locks.withLock(runID, task) const operating = (runID: string, task: Effect.Effect): Effect.Effect => locked(`operation:${runID}`, task) const deliverNotice = (eventID: string): Effect.Effect => locked(`notice:${eventID}`, Effect.gen(function* () { if (closed || !options.notifier) return - const notice = store.notices().find((value) => value.eventID === eventID) + const notice = store.notice(eventID) if (!notice || notice.state === "admitted") return const fresh = notice.state === "pending" store.saveNotice({ ...notice, state: "reserved" }) @@ -213,6 +211,14 @@ export function createDagController(options: DagControllerOptions): DagControlle for (const waiter of pending) Deferred.doneUnsafe(waiter, Exit.succeed(run)) } const save = (run: DagRunRecord): DagRunRecord => { store.saveRun(run); return run } + /** The run is cancelled either way, but a child that kept running is still editing and spending: say so on its node. */ + const cancelFailed = (run: DagRunRecord, ref: DagExecutionRef, cause: Cause.Cause): DagRunRecord => { + const message = `Cancelled, but its session could not be stopped: ${errorMessage(Cause.squash(cause))}` + trace("iolaus.dag.cancel-failed", { runID: run.runID, nodeID: ref.nodeID, sessionID: ref.sessionID, error: message }) + const updated = updateNode(run, ref.nodeID, (value) => ({ ...value, error: message, updatedAt: now() })) + event(updated, "node.failed", ref.nodeID, { message, status: "cancelled" }) + return updated + } const activeCount = (run: DagRunRecord): number => run.nodes.filter((node) => node.status === "starting" || node.status === "running").length const updateNode = (run: DagRunRecord, nodeID: string, update: (node: DagNodeRecord) => DagNodeRecord): DagRunRecord => ({ ...run, @@ -309,6 +315,7 @@ export function createDagController(options: DagControllerOptions): DagControlle if (!live || (live.status !== "starting" && live.status !== "running") || live.attempt !== node.attempt || live.runtime?.identity.token !== node.runtime?.identity.token) return if ((live.runtime?.inputRevision ?? 0) !== (node.runtime?.inputRevision ?? 0)) return const requests = executionRequests(runID, live) + const steered = store.steering(runID).some((request) => request.nodeID === nodeID) if (requests.some((request) => request.state === "reserved" || request.state === "unresolved")) return if (live.execution && runner.verify) { const checked = yield* Effect.exit(runner.verify(live.execution)) @@ -330,7 +337,7 @@ export function createDagController(options: DagControllerOptions): DagControlle const { ref, payload } = outcome.value const text = replyText(payload) const escalated = live.definition.agent === "deep-low" && text !== undefined && ESCALATE_LINE.test(text) ? options.defaultModel?.("deep-high") : undefined - if (escalated && requests.length === 0 && !rescued) { + if (escalated && !steered && !rescued) { // The goal's central decision needs the escalation lane: rerun it there with the findings so far. const fallbacks = options.fallbackModels?.("deep-high") ?? [] const definition: DagNodeDefinition = { ...live.definition, agent: "deep-high", model: escalated, fallbackModels: fallbacks.length ? fallbacks : undefined, @@ -360,7 +367,7 @@ export function createDagController(options: DagControllerOptions): DagControlle // taking the session over (the model switch itself failed), the one it was meant to continue. const session = (live.definition.kind ?? "agent") === "agent" && runner.continues ? live.execution && live.runtime?.initial === "admitted" ? live.execution : live.recovery?.continueFrom : undefined - const continuable = modelFailure && !nonRetryable && delivered && (session !== undefined || !store.steering(runID).some((request) => request.nodeID === nodeID)) + const continuable = modelFailure && !nonRetryable && delivered && (session !== undefined || !steered) const failedModels = live.definition.model ? [...new Set([...(live.recovery?.failedModels ?? []), normalizedModel(live.definition.model)])] : live.recovery?.failedModels ?? [] const retryRecovery: NodeRecovery = { failedModels, ...(session ? { continueFrom: session } : {}), ...(rescue ? { rescue } : {}) } const retry = (definition: DagNodeDefinition, type: "node.fallback" | "node.rescued", payload: JsonValue, recovery: NodeRecovery = retryRecovery) => { @@ -400,7 +407,7 @@ export function createDagController(options: DagControllerOptions): DagControlle event(current, "node.rescue-skipped", nodeID, { reason: errorMessage(Cause.squash(decision.cause)) }) } const status: DagNodeRecord["status"] = requests.length && !delivered ? "interrupted" - : !modelFailure && !nonRetryable && requests.length === 0 && live.attempt < maxAttempts ? "needs_retry" : "failed" + : !modelFailure && !nonRetryable && !steered && live.attempt < maxAttempts ? "needs_retry" : "failed" const recovery = live.recovery || failedModels.length ? { ...closedRecovery(live.recovery ?? { failedModels }), failedModels } : undefined const updated = updateNode(current, nodeID, (value) => ({ ...value, status, error: message, ...(recovery ? { recovery } : {}), updatedAt: now() })) event(updated, "node.failed", nodeID, { message, status }) @@ -431,7 +438,15 @@ export function createDagController(options: DagControllerOptions): DagControlle return true })) if (!published) { - yield* runner.cancel(ref) + // The child was created after the run stopped waiting for it, so nobody else knows its session. + const stopped = yield* Effect.exit(runner.cancel(ref)) + if (Exit.isFailure(stopped)) yield* locked(runID, Effect.sync(() => { + const current = store.getRun(runID) + const live = current?.nodes.find((value) => value.definition.id === nodeID) + // Only the attempt that was cancelled is marked; a retry since then owns the node's state. + if (current && live?.status === "cancelled" && live.attempt === node.attempt && live.runtime?.identity.token === node.runtime?.identity.token) cancelFailed(current, ref, stopped.cause) + else trace("iolaus.dag.cancel-failed", { runID, nodeID, sessionID: ref.sessionID, error: errorMessage(Cause.squash(stopped.cause)) }) + })) return yield* new DagRunnerError({ message: "Execution was cancelled before initial admission", nodeID }) } yield* operating(runID, Effect.gen(function* () { @@ -481,32 +496,49 @@ export function createDagController(options: DagControllerOptions): DagControlle const current = store.getRun(runID) const live = current?.nodes.find((candidate) => candidate.definition.id === node.definition.id) if (!current || terminal(current.status) || !live || (live.status !== "starting" && live.status !== "running") || live.attempt !== node.attempt || live.runtime?.identity.token !== node.runtime?.identity.token) return + if ((live.runtime?.inputRevision ?? 0) !== (node.runtime?.inputRevision ?? 0) || live.execution?.sessionID !== node.execution?.sessionID) return const updated = updateNode(current, node.definition.id, (value) => ({ ...value, status: "interrupted", error: message, updatedAt: now() })) event(updated, "node.failed", node.definition.id, { message, status: "interrupted" }) save(updateRunStatus(updated)) })) + /** + * Whether a node read when the controller was built is still that same stranded execution. Recovery runs later + * (it waits for the plugin to finish registering) and its reattach later still, so everything it writes is + * fenced by the node's status, attempt and execution identity as they were then. + */ + const stranded = (runID: string, node: DagNodeRecord): boolean => { + const run = store.getRun(runID) + if (!run || terminal(run.status)) return false + const live = run.nodes.find((candidate) => candidate.definition.id === node.definition.id) + return live !== undefined && live.status === node.status && live.attempt === node.attempt + && live.runtime?.inputRevision === node.runtime?.inputRevision + && live.runtime?.identity.token === node.runtime?.identity.token && live.execution?.sessionID === node.execution?.sessionID + } + /** * An observed run's correlation with its subagent sessions lives in the observer's memory, so after a reload the * child's completion never reaches the node. Wait on the recorded session again and record its own outcome. */ const recoverObserved = (run: DagRunRecord): Effect.Effect => Effect.gen(function* () { for (const node of run.nodes) { - if (node.status !== "running") continue + if (node.status !== "running" || !stranded(run.runID, node)) continue + // The live observer may follow the call up while recovery waits; its newer state wins over the stranded one. + const settle = (update: DagObservedUpdate) => Effect.sync(() => { if (stranded(run.runID, node)) observed(run.runID, node.definition.id, update) }) const ref = node.execution if (!ref) { trace("iolaus.dag.recovered", { runID: run.runID, nodeID: node.definition.id, outcome: "interrupted" }) - yield* controller.observed(run.runID, node.definition.id, { status: "interrupted", error: "The controller stopped before the subagent session was known" }) + yield* settle({ status: "interrupted", error: "The controller stopped before the subagent session was known" }) continue } trace("iolaus.dag.recovered", { runID: run.runID, nodeID: node.definition.id, outcome: "reattached", sessionID: ref.sessionID }) yield* Effect.forkIn(Effect.gen(function* () { const outcome = yield* Effect.exit(runner.reattach(ref)) - if (!Exit.isSuccess(outcome)) return yield* controller.observed(run.runID, node.definition.id, { status: "failed", error: errorMessage(Cause.squash(outcome.cause)) }) - if (outcome.value === undefined) return yield* controller.observed(run.runID, node.definition.id, { status: "interrupted", error: "The controller stopped before the subagent session received its prompt" }) + if (!Exit.isSuccess(outcome)) return yield* settle({ status: "failed", error: errorMessage(Cause.squash(outcome.cause)) }) + if (outcome.value === undefined) return yield* settle({ status: "interrupted", error: "The controller stopped before the subagent session received its prompt" }) const payload = outcome.value.payload const text = payload !== null && typeof payload === "object" && !Array.isArray(payload) && typeof payload.text === "string" ? payload.text : "" - yield* controller.observed(run.runID, node.definition.id, { status: "completed", text }) + yield* settle({ status: "completed", text }) }), scope) } }) @@ -519,7 +551,7 @@ export function createDagController(options: DagControllerOptions): DagControlle const recover = (run: DagRunRecord): Effect.Effect => Effect.gen(function* () { if (run.definition.observed) return yield* recoverObserved(run) for (const node of run.nodes) { - if (node.status !== "starting" && node.status !== "running") continue + if ((node.status !== "starting" && node.status !== "running") || !stranded(run.runID, node)) continue const ref = node.execution if (!ref) { trace("iolaus.dag.recovered", { runID: run.runID, nodeID: node.definition.id, outcome: "interrupted" }) @@ -532,10 +564,13 @@ export function createDagController(options: DagControllerOptions): DagControlle const outcome = yield* Effect.exit(runner.reattach(ref, requests)) if (requests.length) { const recovered = Exit.isSuccess(outcome) && outcome.value !== undefined - yield* locked(run.runID, Effect.sync(() => { + const current = yield* locked(run.runID, Effect.sync(() => { + if (!stranded(run.runID, node)) return false for (const request of requests) store.saveSteering({ ...request, state: recovered ? "admitted" : "unresolved", ...(recovered ? { receipt: request.receipt ?? { messageID: request.messageID } } : { error: "Host delivery or resulting execution could not be reconciled; nothing was replayed" }) }) + return true })) + if (!current) return if (!recovered) { yield* interrupt(run.runID, node, "Steering delivery unresolved after recovery; nothing was replayed") return yield* schedule(run.runID) @@ -545,7 +580,7 @@ export function createDagController(options: DagControllerOptions): DagControlle if (node.runtime?.initial === "pending") yield* locked(run.runID, Effect.sync(() => { const current = store.getRun(run.runID)! const live = current.nodes.find((value) => value.definition.id === node.definition.id) - if (live?.runtime?.identity.token === node.runtime?.identity.token) save(updateNode(current, node.definition.id, (value) => ({ ...value, runtime: { ...value.runtime!, initial: "unresolved" } }))) + if (live?.runtime?.initial === "pending" && stranded(run.runID, node)) save(updateNode(current, node.definition.id, (value) => ({ ...value, runtime: { ...value.runtime!, initial: "unresolved" } }))) })) yield* interrupt(run.runID, node, node.runtime?.initial === "pending" ? "Initial prompt admission is unresolved after recovery; nothing was replayed" @@ -581,9 +616,19 @@ export function createDagController(options: DagControllerOptions): DagControlle event(grown, "loop.grown", nodeID, { round: definition.nodes.filter((node) => node.id.startsWith(`${run.definition.loop!.fix}`)).length }) })) + /** A node's fingerprint covers everything upstream of it, wherever its dependencies sit in the node list. */ const fingerprintNodes = (definition: DagDefinition): Map => { + const nodes = new Map(definition.nodes.map((node) => [node.id, node])) const fingerprints = new Map() - for (const node of definition.nodes) fingerprints.set(node.id, nodeFingerprint(node, node.dependsOn.map((dependency) => fingerprints.get(dependency) ?? ""))) + const of = (id: string): string => { + const known = fingerprints.get(id) + if (known !== undefined) return known + const node = nodes.get(id)! + const computed = nodeFingerprint(node, node.dependsOn.map(of)) + fingerprints.set(id, computed) + return computed + } + for (const node of definition.nodes) of(node.id) return fingerprints } @@ -657,20 +702,25 @@ export function createDagController(options: DagControllerOptions): DagControlle yield* schedule(runID) return yield* current(runID) }), - list: (ownerSessionID) => Effect.sync(() => store.listRuns(ownerSessionID)), + list: (ownerSessionID, listing) => Effect.sync(() => store.listRuns(ownerSessionID, listing)), snapshot: (runID, ownerSessionID) => owned(runID, ownerSessionID).pipe(Effect.map((run) => ({ run, events: store.events(runID), steering: store.steering(runID), notices: store.notices(runID) }))), node: (runID, ownerSessionID, nodeID) => owned(runID, ownerSessionID).pipe(Effect.flatMap((run) => { const record = run.nodes.find((candidate) => candidate.definition.id === nodeID) return record ? Effect.succeed(record) : Effect.fail(new DagValidationError(`Unknown DAG node: ${nodeID}`)) })), - wait: (runID, ownerSessionID) => Effect.gen(function* () { + // The waiter is registered and its removal installed with interruption masked: a caller that stops waiting, + // even the moment it registered, leaves nothing behind for a run that may never finish. + wait: (runID, ownerSessionID) => Effect.uninterruptibleMask((restore) => Effect.gen(function* () { const run = yield* owned(runID, ownerSessionID) if (terminal(run.status)) return run const waiter = yield* Deferred.make() const set = waiters.get(runID) ?? new Set>() set.add(waiter); waiters.set(runID, set) - return yield* Deferred.await(waiter) - }), + return yield* restore(Deferred.await(waiter)).pipe(Effect.ensuring(Effect.sync(() => { + set.delete(waiter) + if (set.size === 0 && waiters.get(runID) === set) waiters.delete(runID) + }))) + })), cancel: (runID, ownerSessionID, expectedGeneration) => operating(runID, locked(runID, Effect.gen(function* () { let run = yield* owned(runID, ownerSessionID) yield* checkGeneration(run, expectedGeneration) @@ -680,7 +730,10 @@ export function createDagController(options: DagControllerOptions): DagControlle run = { ...run, status: "cancelled", updatedAt: now(), nodes: run.nodes.map((node) => node.status === "pending" || node.status === "ready" || node.status === "starting" || node.status === "running" || node.status === "needs_retry" || node.status === "waiting_approval" ? { ...node, status: "cancelled", ...(node.recovery ? { recovery: closedRecovery(node.recovery) } : {}), updatedAt: now() } : node) } save(run); event(run, "run.cancelled") - yield* Effect.forEach(refs, (ref) => Effect.ignore(runner.cancel(ref)), { discard: true }) + for (const ref of refs) { + const stopped = yield* Effect.exit(runner.cancel(ref)) + if (Exit.isFailure(stopped)) run = cancelFailed(run, ref, stopped.cause) + } notify(run) return run }))), @@ -691,14 +744,37 @@ export function createDagController(options: DagControllerOptions): DagControlle yield* checkAtlas(run, run.definition) if (options.admit) yield* options.admit(ownerSessionID, run.definition, run.authorizedPlan) yield* checkGeneration(run, expectedGeneration) + if (nodeID !== undefined && !run.nodes.some((node) => node.definition.id === nodeID)) return yield* Effect.fail(new DagValidationError(`Unknown DAG node: ${nodeID}`)) if (!terminal(run.status) && !run.nodes.some((node) => node.status === "needs_retry" || node.status === "interrupted")) return yield* Effect.fail(new DagValidationError("Retry requires a terminal run or a node needing retry")) - const selected = nodeID ? new Set([nodeID]) : new Set(run.nodes.filter((node) => node.status === "failed" || node.status === "interrupted" || node.status === "needs_retry").map((node) => node.definition.id)) + // Without a node id: whatever did not finish, which for a cancelled run is what the cancel stopped. + const unfinished = (node: DagNodeRecord) => node.status === "failed" || node.status === "interrupted" || node.status === "needs_retry" || (run.status === "cancelled" && node.status === "cancelled") + const selected = nodeID !== undefined ? new Set([nodeID]) : new Set(run.nodes.filter(unfinished).map((node) => node.definition.id)) + if (!selected.size) return yield* Effect.fail(new DagValidationError("Nothing to retry: no node of this run failed, was interrupted or was cancelled")) + // Whatever ran on a retried node's previous result is stale, so everything downstream of it runs again too. + for (let grew = true; grew;) { + grew = false + for (const node of run.nodes) { + if (selected.has(node.definition.id) || !node.definition.dependsOn.some((id) => selected.has(id))) continue + selected.add(node.definition.id); grew = true + } + } if (run.nodes.some((node) => selected.has(node.definition.id) && (node.status === "starting" || node.status === "running"))) return yield* Effect.fail(new DagValidationError("Cannot retry a live execution")) - if (run.nodes.some((node) => (selected.has(node.definition.id) || (!nodeID && node.status === "cancelled")) && executionRequests(runID, node).length)) return yield* Effect.fail(new DagValidationError("Cannot retry a steered execution: reconcile its delivery or create a new flow with the complete task")) - if (run.nodes.some((node) => selected.has(node.definition.id) && node.runtime?.initial === "unresolved")) return yield* Effect.fail(new DagValidationError("Initial prompt admission is unresolved; refusing to replay the original task")) + // Fix rounds grown for a review that runs again answered a verdict that no longer exists; its new verdict decides. + const shrunk = shrinkLoop(run.definition, selected) + const definition = shrunk ? yield* validated(() => prepare(shrunk)) : run.definition + const kept = new Set(definition.nodes.map((node) => node.id)) + // A restarted node runs in a fresh session, which would not have the supplements an earlier execution of it was + // given: any steering in the node's history refuses the retry, whichever execution finished it. + const restarted = (node: DagNodeRecord) => kept.has(node.definition.id) && (selected.has(node.definition.id) || node.status === "blocked") + const steered = new Set(store.steering(runID).map((request) => request.nodeID)) + // A dropped review round may be grown again under the same ID. Dropping it must not bypass the replay guard. + const invalidated = (node: DagNodeRecord) => selected.has(node.definition.id) || restarted(node) + if (run.nodes.some((node) => invalidated(node) && steered.has(node.definition.id))) return yield* Effect.fail(new DagValidationError("Cannot retry a steered execution: reconcile its delivery or create a new flow with the complete task")) + if (run.nodes.some((node) => invalidated(node) && node.runtime?.initial === "unresolved")) return yield* Effect.fail(new DagValidationError("Initial prompt admission is unresolved; refusing to replay the original task")) // Blocked nodes return to pending too; the frontier blocks them again if another dependency still failed. // A retried node starts again from its planned model chain; an escalated node stays on its escalation lane. - const planned = new Map(run.definition.nodes.map((node) => [node.id, node])) + const planned = new Map(definition.nodes.map((node) => [node.id, node])) + const fingerprints = shrunk ? fingerprintNodes(definition) : undefined // An explicit retry is a fresh session: it continues nothing, and a spent rescue stays spent. const restart = (node: DagNodeRecord): DagNodeDefinition => { const original = planned.get(node.definition.id) @@ -706,8 +782,11 @@ export function createDagController(options: DagControllerOptions): DagControlle const rescue = node.recovery?.rescue return rescue && normalizedModel(node.definition.model ?? "") === rescue.model ? rescue.preRescueDefinition : node.definition } - run = { ...run, generation: run.generation + 1, status: "running", updatedAt: now(), nodes: run.nodes.map((node) => selected.has(node.definition.id) || node.status === "blocked" - ? { ...node, definition: restart(node), ...(node.recovery ? { recovery: { ...closedRecovery(node.recovery)!, failedModels: [] } } : {}), status: "pending", error: undefined, execution: undefined, updatedAt: now() } : node) } + // A restarted node keeps nothing of its earlier run: a result left on it would be read as current if it is skipped this time. + run = { ...run, definition, ...(shrunk ? { fingerprint: graphFingerprint(definition) } : {}), generation: run.generation + 1, status: "running", updatedAt: now(), + nodes: run.nodes.filter((node) => kept.has(node.definition.id)).map((node) => restarted(node) + ? { ...node, definition: restart(node), ...(fingerprints ? { fingerprint: fingerprints.get(node.definition.id)! } : {}), ...(node.recovery ? { recovery: { ...closedRecovery(node.recovery)!, failedModels: [] } } : {}), + status: "pending", error: undefined, execution: undefined, result: undefined, runtime: undefined, updatedAt: now() } : node) } save(run); event(run, "node.retrying", nodeID) }))) yield* schedule(runID) @@ -735,12 +814,18 @@ export function createDagController(options: DagControllerOptions): DagControlle const message = note?.trim() ? `Rejected by approver: ${note.trim()}` : "Rejected by approver" let updated = updateNode(run, nodeID, (value) => ({ ...value, status: "failed", error: message, updatedAt: now() })) event(updated, "node.rejected", nodeID, { decision: "rejected", ...(note === undefined ? {} : { note }) }) + // Everything downstream of the rejected gate is blocked, not only its direct dependents: a node left pending keeps the run open forever. const records = new Map(updated.nodes.map((node) => [node.definition.id, node])) - for (const node of updated.nodes) { - if (node.status !== "pending" && node.status !== "needs_retry") continue - if (dependencyState(node.definition, records) !== "blocked") continue - updated = updateNode(updated, node.definition.id, (value) => ({ ...value, status: "blocked", error: "A dependency did not complete successfully", updatedAt: now() })) - event(updated, "node.blocked", node.definition.id) + for (let settled = false; !settled;) { + settled = true + for (const node of updated.nodes) { + if (node.status !== "pending" && node.status !== "needs_retry") continue + if (dependencyState(node.definition, records) !== "blocked") continue + updated = updateNode(updated, node.definition.id, (value) => ({ ...value, status: "blocked", error: "A dependency did not complete successfully", updatedAt: now() })) + event(updated, "node.blocked", node.definition.id) + records.set(node.definition.id, updated.nodes.find((candidate) => candidate.definition.id === node.definition.id)!) + settled = false + } } return save(updateRunStatus(updated)) })), @@ -764,9 +849,11 @@ export function createDagController(options: DagControllerOptions): DagControlle if (!affected.has(node.id) && node.dependsOn.some((id) => affected.has(id))) { affected.add(node.id); changed = true } } } + // A result produced in another directory is not this run's result. + const moved = previous.definition.directory !== definition.directory const nextNodes = definition.nodes.map((node) => { const old = previousByID.get(node.id) - const same = old && !affected.has(node.id) && old.fingerprint === fingerprints.get(node.id) && (old.status === "completed" || old.status === "reused") + const same = old && !moved && !affected.has(node.id) && old.fingerprint === fingerprints.get(node.id) && (old.status === "completed" || old.status === "reused") // A removed and re-added node keeps its spent rescue; an amended node continues nothing. const recovery = closedRecovery(old?.recovery ?? store.recovery(runID, node.id)) return { definition: node, fingerprint: fingerprints.get(node.id)!, status: same ? "reused" as const : "pending" as const, attempt: same ? old.attempt : 0, ...(recovery ? { recovery } : {}), ...(same && old.result ? { result: old.result } : {}), createdAt: old?.createdAt ?? now(), updatedAt: now() } @@ -843,8 +930,7 @@ export function createDagController(options: DagControllerOptions): DagControlle observe: (input) => Effect.sync(() => { const at = now() const batch = input.batch ?? { kind: "call" as const, id: randomUUID() } - const run = input.runID ? store.getRun(input.runID) : store.listRuns(input.ownerSessionID).find((candidate) => - candidate.definition.observed && candidate.definition.observedBatch?.kind === batch.kind && candidate.definition.observedBatch.id === batch.id) + const run = input.runID ? store.getRun(input.runID) : store.observedRun(input.ownerSessionID, batch) if (input.runID && (!run?.definition.observed || run.ownerSessionID !== input.ownerSessionID)) throw new Error("Unknown observed batch") if (input.parentNodeID && !run?.nodes.some((node) => node.definition.id === input.parentNodeID)) throw new Error("Parent must belong to the observed batch") const nodeID = `${(run?.nodes.length ?? 0) + 1}-${slug(input.title)}` @@ -861,7 +947,20 @@ export function createDagController(options: DagControllerOptions): DagControlle save(next); event(next, "node.started", nodeID) return { runID: run.runID, nodeID } }), - observed: (runID, nodeID, update) => Effect.sync(() => { + observed: (runID, nodeID, update) => Effect.sync(() => observed(runID, nodeID, update)), + observedChild: (sessionID) => Effect.sync(() => { + const found = store.observedNode(sessionID) + return found ? { runID: found.runID, nodeID: found.nodeID, owner: found.ownerSessionID } : undefined + }), + close: Effect.sync(() => { + closed = true + Effect.runFork(Scope.close(scope, Exit.void)) + for (const set of waiters.values()) for (const waiter of set) Deferred.doneUnsafe(waiter, Exit.fail(new DagValidationError("Iolaus DAG controller closed")) as never) + waiters.clear() + store.close() + }), + } + function observed(runID: string, nodeID: string, update: DagObservedUpdate): void { const run = store.getRun(runID) const node = run?.nodes.find((candidate) => candidate.definition.id === nodeID) if (!run || !node || !run.definition.observed) return @@ -904,23 +1003,14 @@ export function createDagController(options: DagControllerOptions): DagControlle update.status === "completed" ? { text: update.text } : update.status === "running" ? undefined : { message: update.error, status: update.status }) if (status !== run.status && (status === "completed" || status === "failed")) event(updated, status === "completed" ? "run.completed" : "run.failed") notify(updated) - }), - observedChild: (sessionID) => Effect.sync(() => { - const found = store.observedNode(sessionID) - return found ? { runID: found.runID, nodeID: found.nodeID, owner: found.ownerSessionID } : undefined - }), - close: Effect.sync(() => { - closed = true - Effect.runFork(Scope.close(scope, Exit.void)) - for (const set of waiters.values()) for (const waiter of set) Deferred.doneUnsafe(waiter, Exit.fail(new DagValidationError("Iolaus DAG controller closed")) as never) - waiters.clear() - store.close() - }), } const shared: SharedController = { controller, refs: 1 } sharedControllers.set(key, shared) - if (options.notifier) Effect.runFork(Effect.forkIn(Effect.forEach(store.notices(), (notice) => deliverNotice(notice.eventID), { discard: true }), scope)) - Effect.runFork(Effect.forkIn(Effect.forEach(store.listRuns().filter((run) => !terminal(run.status)), recover, { discard: true }), scope)) + if (options.notifier) Effect.runFork(Effect.forkIn(Effect.forEach(store.undeliveredNotices(), (notice) => deliverNotice(notice.eventID), { discard: true }), scope)) + // Read now, recovered later: a run created while recovery waits is this controller's own live work, not a stray, + // and `stranded` leaves alone any node that changed in the meantime. + const open = store.listRuns(undefined, { open: true }) + Effect.runFork(Effect.forkIn(Effect.andThen(options.recoveryReady ?? Effect.void, Effect.forEach(open, recover, { discard: true })), scope)) return { ...controller, close: Effect.sync(() => releaseSharedController(key, shared)) } } diff --git a/src/dag/graph.ts b/src/dag/graph.ts index f185fb1..dff8ec7 100644 --- a/src/dag/graph.ts +++ b/src/dag/graph.ts @@ -78,6 +78,22 @@ export function validateDefinition(definition: DagDefinition): void { visited.add(id) } for (const node of definition.nodes) visit(node.id) + // A bound result must be settled before its consumer runs, so the node it names has to be upstream of the consumer. + const upstream = new Map>() + const above = (id: string): ReadonlySet => { + const known = upstream.get(id) + if (known) return known + const found = new Set() + for (const dependency of nodes.get(id)?.dependsOn ?? []) { + found.add(dependency) + for (const further of above(dependency)) found.add(further) + } + upstream.set(id, found) + return found + } + for (const node of definition.nodes) for (const input of node.inputs ?? []) { + if (input.node !== "*" && !above(node.id).has(input.node)) throw new DagValidationError(`Input node ${input.node} is not upstream of ${node.id}: add it to dependsOn`) + } } /** diff --git a/src/dag/loop.ts b/src/dag/loop.ts index 7ab5565..2c9bfa5 100644 --- a/src/dag/loop.ts +++ b/src/dag/loop.ts @@ -1,4 +1,4 @@ -import type { DagDefinition, DagLoop, DagNodeDefinition, DagRunRecord } from "./types" +import type { DagCondition, DagDefinition, DagLoop, DagNodeDefinition, DagRunRecord } from "./types" function roundOf(id: string, base: string): number | undefined { if (id === base) return 0 @@ -63,6 +63,37 @@ export function growLoop(run: DagRunRecord, settled: string): DagDefinition | un return { ...run.definition, nodes: [...nodes.filter((node) => !tail.has(node.id)), fix, review, ...nodes.filter((node) => tail.has(node.id))] } } +function renamed(condition: DagCondition, rename: (id: string) => string): DagCondition { + if ("all" in condition) return { all: condition.all.map((value) => renamed(value, rename)) } + if ("any" in condition) return { any: condition.any.map((value) => renamed(value, rename)) } + if ("not" in condition) return { not: renamed(condition.not, rename) } + return { ...condition, node: rename(condition.node) } +} + +/** + * The inverse of `growLoop`: when the reviews in `rerun` are about to run again, the rounds grown after the + * earliest of them answered a verdict that no longer exists. Returns the definition without those rounds and + * with the tail following that review again, or undefined when no grown round is affected. + */ +export function shrinkLoop(definition: DagDefinition, rerun: ReadonlySet): DagDefinition | undefined { + const loop = definition.loop + if (!loop) return undefined + const rounds = definition.nodes.flatMap((node) => { const round = rerun.has(node.id) ? roundOf(node.id, loop.review) : undefined; return round === undefined ? [] : [round] }) + if (!rounds.length) return undefined + const keep = Math.min(...rounds) + const later = (id: string, base: string) => { const round = roundOf(id, base); return round !== undefined && round > keep } + const dropped = new Set(definition.nodes.filter((node) => later(node.id, loop.fix) || later(node.id, loop.review)).map((node) => node.id)) + if (!dropped.size) return undefined + const at = (base: string) => keep === 0 ? base : `${base}${keep}` + const rename = (id: string) => !dropped.has(id) ? id : later(id, loop.review) ? at(loop.review) : at(loop.fix) + return { ...definition, nodes: definition.nodes.filter((node) => !dropped.has(node.id)).map((node) => (loop.tail ?? []).includes(node.id) ? { + ...node, + dependsOn: [...new Set(node.dependsOn.map(rename))], + ...(node.when ? { when: renamed(node.when, rename) } : {}), + ...(node.inputs ? { inputs: node.inputs.map((input) => ({ ...input, node: rename(input.node) })) } : {}), + } : node) } +} + export function buildLoop(input: Omit & { readonly tail?: readonly string[] }): DagLoop { return input } diff --git a/src/dag/promise.ts b/src/dag/promise.ts index 875df46..babb348 100644 --- a/src/dag/promise.ts +++ b/src/dag/promise.ts @@ -1,11 +1,12 @@ import { Effect } from "effect" import type { DagController } from "./controller" +import type { ListRunsOptions } from "./store" import type { DagDefinition, DagNodeRecord, DagRunRecord, DagSnapshot, DagSteerRequest } from "./types" /** Promise view of a DagController for tests, QA scripts and non-Effect callers. Errors reject with the typed error instance. */ export interface DagControllerPromise { readonly create: (definition: DagDefinition, ownerSessionID: string) => Promise - readonly list: (ownerSessionID?: string) => Promise + readonly list: (ownerSessionID?: string, options?: ListRunsOptions) => Promise readonly snapshot: (runID: string, ownerSessionID: string) => Promise readonly node: (runID: string, ownerSessionID: string, nodeID: string) => Promise readonly wait: (runID: string, ownerSessionID: string) => Promise @@ -23,7 +24,7 @@ export function promiseController(controller: DagController): DagControllerPromi const run = (effect: Effect.Effect): Promise => Effect.runPromise(effect) return { create: (d, o) => run(controller.create(d, o)), - list: (o) => run(controller.list(o)), + list: (o, options) => run(controller.list(o, options)), snapshot: (r, o) => run(controller.snapshot(r, o)), node: (r, o, n) => run(controller.node(r, o, n)), wait: (r, o) => run(controller.wait(r, o)), diff --git a/src/dag/register-rpc.ts b/src/dag/register-rpc.ts index 079a0b4..73a47c0 100644 --- a/src/dag/register-rpc.ts +++ b/src/dag/register-rpc.ts @@ -34,7 +34,7 @@ export function nodeSummary(title: string | undefined, prompt: string): string | } export function dagView(controller: DagController, sessionID: string): Effect.Effect { - return controller.list(sessionID).pipe(Effect.map((runs) => ({ runs: runs.slice(0, 50).map((run) => ({ + return controller.list(sessionID, { limit: 50 }).pipe(Effect.map((runs) => ({ runs: runs.map((run) => ({ runID: run.runID, name: run.name, generation: run.generation, status: run.status, createdAt: run.createdAt, updatedAt: run.updatedAt, ...(run.definition.observed ? { observed: true } : {}), diff --git a/src/dag/tool.ts b/src/dag/tool.ts index 50bd9e8..cf89570 100644 --- a/src/dag/tool.ts +++ b/src/dag/tool.ts @@ -58,7 +58,7 @@ const nodeSchema = { inputs: { type: "array", items: { type: "object", properties: { node: { type: "string" }, field: { type: "string" } }, required: ["node"], additionalProperties: false }, - description: "Upstream results bound into this node's prompt inside . node: \"*\" fans in every dependency.", + description: "Upstream results bound into this node's prompt inside . Each named node must be upstream of this one (in dependsOn, or above a node that is). node: \"*\" fans in every dependency.", }, when: conditionSchema, maxAttempts: { type: "integer", minimum: 1 }, @@ -172,7 +172,7 @@ export function createDagTool(controller: DagController): Tool.Info { case "node": return controller.node(runID(), sessionID, nodeID()) case "wait": return controller.wait(runID(), sessionID) case "cancel": return controller.cancel(runID(), sessionID) - case "retry": return controller.retry(runID(), sessionID, typeof input.node_id === "string" ? input.node_id : undefined) + case "retry": return controller.retry(runID(), sessionID, input.node_id === undefined ? undefined : nodeID()) case "resume": return controller.resume(runID(), sessionID) case "approve": return controller.approve(runID(), sessionID, nodeID(), note) case "reject": return controller.reject(runID(), sessionID, nodeID(), note) diff --git a/src/plugin.ts b/src/plugin.ts index 2bbee85..29a3f08 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -1,4 +1,4 @@ -import { Deferred, Effect, Stream } from "effect" +import { Deferred, Effect } from "effect" import { Agent, Plugin } from "@opencode/plugin/effect" import type { Context } from "@opencode/plugin/effect/plugin" import { parseOptions } from "./options" @@ -103,6 +103,9 @@ export default Plugin.define({ }) const stateSync = createStateSync(ctx.session.instructions, { controller, state, trace }) state.onSave = (sessionID) => { Effect.runFork(stateSync.refresh(sessionID)) } + // The host copies the parent's instruction entries into a fork, but the goal, role and runs they describe stay + // with the parent: the fork owns none of them, so its entry is recomputed (and normally removed). + yield* ctx.session.hook("fork", (event) => stateSync.refresh(String(event.sessionID))) yield* Effect.addFinalizer(() => controller.close) yield* ctx.tool.transform((editor) => editor.add(createDagTool(controller))) yield* registerRoles(ctx, options, { controller, source, directory: (sessionID) => sessionDirectory(ctx, sessionID), state, trace }) @@ -145,11 +148,8 @@ export default Plugin.define({ const rpc = yield* registerDagRpc(ctx, controller).pipe(Effect.orDie) emit = (sessionID, runID, sequence, type) => rpc.events.emit("updated", { sessionID, runID, sequence, type }) - yield* ctx.event.subscribe({ types: ["plugin.updated"] }).pipe( - Stream.filter((event) => event.location?.directory === ctx.location.directory && event.location.workspaceID === ctx.location.workspaceID), - Stream.take(1), - Stream.runForEach(() => Deferred.succeed(recoveryReady, undefined)), - Effect.forkScoped({ startImmediately: true }), - ) + // Everything is registered: recovery may settle and launch nodes now. The host publishes `plugin.updated` only + // when its plugin inventory changes, which a hot reload of this plugin does not, so that event cannot be the signal. + yield* Deferred.succeed(recoveryReady, undefined) }), }) diff --git a/src/session-state.ts b/src/session-state.ts index 0e793b6..6385b62 100644 --- a/src/session-state.ts +++ b/src/session-state.ts @@ -1,8 +1,9 @@ -import { Effect, Semaphore } from "effect" +import { Effect } from "effect" import type { Context } from "@opencode/plugin/effect/plugin" import type { SessionStateStore } from "./database" import type { DagController } from "./dag/controller" import type { DagRunRecord } from "./dag/types" +import { createKeyedLock } from "./keyed-lock" import { readGoal } from "./roles/goal" import { readRole } from "./roles/register" @@ -43,14 +44,10 @@ type Instructions = Context["session"]["instructions"] * Refreshes of one session are serialized so a stale snapshot never lands last. */ export function createStateSync(instructions: Instructions, host: { readonly controller: DagController; readonly state: SessionStateStore; readonly trace: Trace }) { - const locks = new Map() - const lock = (sessionID: string) => { - let permit = locks.get(sessionID) - if (!permit) locks.set(sessionID, permit = Semaphore.makeUnsafe(1)) - return permit - } - const refresh = (sessionID: string): Effect.Effect => lock(sessionID).withPermits(1)(Effect.gen(function* () { - const runs = yield* host.controller.list(sessionID) + const locks = createKeyedLock() + const refresh = (sessionID: string): Effect.Effect => locks.withLock(sessionID, Effect.gen(function* () { + // Only unfinished runs are announced, so the session's finished history is never read for this. + const runs = yield* host.controller.list(sessionID, { open: true }) const text = sessionState(readGoal(host.state, sessionID), readRole(host.state, sessionID), runs) if (text === undefined) yield* instructions.entry.remove({ sessionID: sessionID as never, key: STATE_ENTRY_KEY }) else yield* instructions.entry.put({ sessionID: sessionID as never, key: STATE_ENTRY_KEY, value: text }) diff --git a/tests/dag-steering.test.ts b/tests/dag-steering.test.ts index a77c252..f2930b2 100644 --- a/tests/dag-steering.test.ts +++ b/tests/dag-steering.test.ts @@ -598,3 +598,125 @@ test("recovery preserves an admitted receipt but stops downstream when host deli expect(done.nodes[0]?.result).toBeUndefined() expect((await restored.snapshot(run.runID, "owner")).steering?.[0]).toEqual(expect.objectContaining({ state: "unresolved", receipt: { messageID: "msg_admitted" } })) }) + +test("retrying a node that was ever steered, or anything upstream of it, is refused even after it finished on a fallback model", async () => { + const waiting = deferred() + const starts: string[] = [] + const { controller } = setup({ + continues: true, + async start(input) { starts.push(`${input.node.id}:${input.node.model}`); return { nodeID: input.node.id, attempt: input.attempt, sessionID: input.continueFrom?.sessionID ?? input.node.id } }, + async admit() {}, async verify() {}, async steer(_ref, request) { return { messageID: request.messageID } }, + async wait(ref, requests) { + if (ref.nodeID !== "implement") return { payload: "done" } + if (ref.identity?.model !== "test/visual") return { payload: "done on the fallback" } + if (!requests?.length) { waiting.resolve(); return new Promise(() => {}) } + throw new DagRunnerError({ message: "provider failed", model: true, deliveredRequests: requests.map((request) => request.requestID) }) + }, async cancel() {}, + }) + const run = await controller.create({ ...graph, nodes: [ + { id: "plan", agent: "quick", model: "test/quick", prompt: "Plan", dependsOn: [] }, + { ...graph.nodes[0]!, dependsOn: ["plan"], fallbackModels: ["test/backup"] }, graph.nodes[1]!, + ] }, "owner") + await waiting.promise + await controller.steer(run.runID, "owner", "implement", "use fontsource", "supplement") + const done = await controller.wait(run.runID, "owner") + expect([done.status, done.nodes[1]?.result?.payload]).toEqual(["completed", "done on the fallback"]) + expect(starts).toEqual(["plan:test/quick", "implement:test/visual", "implement:test/backup", "review:test/review"]) + // A fresh session would run the task without the supplement the user gave. + await expect(controller.retry(run.runID, "owner", "plan")).rejects.toThrow("steered execution") + await expect(controller.retry(run.runID, "owner", "implement")).rejects.toThrow("steered execution") + expect(starts).toHaveLength(4) + expect((await controller.snapshot(run.runID, "owner")).run.generation).toBe(done.generation) +}) + +test.each(["non-model failure", "escalation", "model failure"] as const)("steering history survives fallback before a subsequent %s", async (outcome) => { + const waiting = deferred() + const starts: { attempt: number; agent: string | undefined; session: string | undefined }[] = [] + let supplements = 0 + const { controller } = setup({ + continues: true, + async start(input) { + starts.push({ attempt: input.attempt, agent: input.node.agent, session: input.continueFrom?.sessionID }) + return { nodeID: input.node.id, attempt: input.attempt, sessionID: input.continueFrom?.sessionID ?? `session-${input.attempt}` } + }, + async admit() {}, async verify() {}, + async steer(_ref, request) { supplements++; return { messageID: request.messageID } }, + async wait(ref, requests) { + if (ref.attempt === 1) { + if (!requests?.length) { waiting.resolve(); return new Promise(() => {}) } + throw new DagRunnerError({ message: "provider failed", model: true, deliveredRequests: requests.map((request) => request.requestID) }) + } + if (ref.attempt === 2) { + expect(requests ?? []).toHaveLength(0) + if (outcome === "escalation") return { payload: "Findings\nESCALATE: deep-high" } + throw new DagRunnerError({ message: "second failure", model: outcome === "model failure" }) + } + return { payload: "continued with supplement" } + }, + async cancel() {}, + }, { defaultModel: (agent) => agent === "deep-high" ? "test/high" : undefined }) + const run = await controller.create({ ...graph, nodes: [{ ...graph.nodes[0]!, agent: "deep-low", maxAttempts: 3, fallbackModels: ["test/backup"] }] }, "owner") + await waiting.promise + await controller.steer(run.runID, "owner", "implement", "use fontsource", "supplement") + const done = await controller.wait(run.runID, "owner") + const snapshot = await controller.snapshot(run.runID, "owner") + expect(starts).toEqual([ + { attempt: 1, agent: "deep-low", session: undefined }, + { attempt: 2, agent: "deep-low", session: "session-1" }, + ...(outcome === "model failure" ? [{ attempt: 3, agent: "deep-low", session: "session-1" }] : []), + ]) + expect(supplements).toBe(1) + expect(snapshot.steering?.[0]?.state).toBe("delivered") + expect(snapshot.events.some((event) => event.type === "node.escalated")).toBe(false) + expect(done.status).toBe(outcome === "non-model failure" ? "failed" : "completed") + expect(done.nodes[0]?.result?.payload).toBe(outcome === "non-model failure" ? undefined : outcome === "escalation" ? "Findings\nESCALATE: deep-high" : "continued with supplement") +}) + +test("a stale unprompted reattach cannot interrupt a newly admitted supplement revision", async () => { + const waiting = deferred() + const never = new Promise(() => {}) + const { controller, directory } = setup({ + async start(input) { return { nodeID: input.node.id, attempt: input.attempt, sessionID: "session-1" } }, + async admit() {}, async verify() {}, + async wait() { waiting.resolve(); return never }, async cancel() {}, + }) + const run = await controller.create(graph, "owner") + await waiting.promise + controller.close() + controllers.splice(controllers.indexOf(controller), 1) + const reattaching = deferred() + const stale = deferred() + const steeredWait = deferred() + const result = deferred<{ payload: string }>() + const starts: string[] = [] + const restored = promiseController(createDagController({ directory, databasePath: join(directory, "state.db"), runner: runnerFromPromise({ + async start(input) { starts.push(input.node.id); return { nodeID: input.node.id, attempt: input.attempt, sessionID: input.node.id } }, + async admit() {}, async verify() {}, + async steer(_ref, request) { return { messageID: request.messageID } }, + async reattach(_ref, requests) { expect(requests ?? []).toHaveLength(0); reattaching.resolve(); return stale.promise }, + async wait(ref, requests) { + if (ref.nodeID === "review") return { payload: "reviewed" } + expect(requests?.map((request) => request.requestID)).toEqual(["new-revision"]) + steeredWait.resolve(); return result.promise + }, + async cancel() { throw new Error("must not cancel the newer revision") }, + }) })) + controllers.push(restored) + await reattaching.promise + expect((await restored.steer(run.runID, "owner", "implement", "use fontsource", "new-revision")).state).toBe("admitted") + await steeredWait.promise + stale.resolve(undefined) + await new Promise((resolve) => setImmediate(resolve)) + const snapshot = await restored.snapshot(run.runID, "owner") + expect(snapshot.run.nodes[0]?.status).toBe("running") + expect(snapshot.run.nodes[0]?.runtime?.inputRevision).toBe(1) + expect(snapshot.steering?.[0]?.state).toBe("admitted") + expect(snapshot.events.filter((event) => event.type === "node.failed")).toHaveLength(0) + result.resolve({ payload: "fontsource applied" }) + const done = await restored.wait(run.runID, "owner") + expect(done.status).toBe("completed") + expect(done.nodes[0]?.result?.payload).toBe("fontsource applied") + expect(done.nodes[0]?.result?.inputRevision).toBe(1) + expect((await restored.snapshot(run.runID, "owner")).steering?.[0]?.state).toBe("delivered") + expect(starts).toEqual(["review"]) +}) diff --git a/tests/dag-templates.test.ts b/tests/dag-templates.test.ts index 4fd8c42..94a38c6 100644 --- a/tests/dag-templates.test.ts +++ b/tests/dag-templates.test.ts @@ -233,3 +233,44 @@ test("hyperplan template fans members through analyse, attack, defend, then dist expect(runner.prompts.get("review")).toContain("distill done") controller.close() }) + +test("a node skipped after a retry does not keep the result of its earlier run", async () => { + directory = mkdtempSync(join(tmpdir(), "iolaus-dag-tpl-")) + const runner = scriptedRunner({ decide: ["GO", "STOP"] }) + const controller = createDagController({ directory, runner, defaultModel: lanes }) + const run = await controller.create({ schemaVersion: 1, name: "t", nodes: [ + { id: "decide", agent: "sisyphus", prompt: "decide", dependsOn: [] }, + { id: "act", agent: "sisyphus", prompt: "act", dependsOn: ["decide"], when: { node: "decide", field: "text", includes: "GO" } }, + ] }, "owner") + expect((await controller.wait(run.runID, "owner")).nodes[1]?.result?.payload).toEqual({ text: "act done" }) + await controller.retry(run.runID, "owner", "decide") + const again = await controller.wait(run.runID, "owner") + expect(again.nodes.map((n) => [n.definition.id, n.status, n.result?.payload])).toEqual([["decide", "completed", { text: "STOP" }], ["act", "skipped", undefined]]) + expect(runner.started).toEqual(["decide", "act", "decide"]) + controller.close() +}) + +test("retrying the work of a grown loop drops the rounds its old review asked for", async () => { + directory = mkdtempSync(join(tmpdir(), "iolaus-dag-tpl-")) + const runner = scriptedRunner({ review: [`Nope.\n${REVIEW_VERDICT_FAIL}`, `Fine now.\n${REVIEW_VERDICT_PASS}`], review1: [`Good.\n${REVIEW_VERDICT_PASS}`] }) + const controller = createDagController({ directory, runner, defaultModel: lanes }) + const run = await controller.create(expandTemplate({ template: "goal-review", task: "t" }), "owner") + const paused = async () => { + let record = (await controller.snapshot(run.runID, "owner")).run + for (let i = 0; i < 50 && record.status !== "paused"; i++) { await new Promise((r) => setTimeout(r, 20)); record = (await controller.snapshot(run.runID, "owner")).run } + return record + } + expect((await paused()).definition.nodes.map((n) => n.id)).toEqual(["work", "review", "work1", "review1", "accept"]) + await controller.approve(run.runID, "owner", "accept") + expect((await controller.wait(run.runID, "owner")).status).toBe("completed") + + await controller.retry(run.runID, "owner", "work") + const again = await paused() + // The first review passes this time, so nothing asks for a fix round and the gate follows that review again. + expect(runner.started).toEqual(["work", "review", "work1", "review1", "work", "review"]) + expect(again.definition.nodes.map((n) => n.id)).toEqual(["work", "review", "accept"]) + expect(again.nodes.map((n) => [n.definition.id, n.status])).toEqual([["work", "completed"], ["review", "completed"], ["accept", "waiting_approval"]]) + const accept = again.definition.nodes.find((n) => n.id === "accept") + expect([accept?.dependsOn, accept?.when]).toEqual([["review"], { node: "review", field: "text", includes: REVIEW_VERDICT_PASS }]) + controller.close() +}) diff --git a/tests/dag.test.ts b/tests/dag.test.ts index 8ca35cf..6ab94f9 100644 --- a/tests/dag.test.ts +++ b/tests/dag.test.ts @@ -10,7 +10,8 @@ import { canonicalJson } from "../src/dag/canonical-json" import { fingerprint, graphFingerprint } from "../src/dag/fingerprint" import { DagValidationError, validateDefinition } from "../src/dag/graph" import { DagStore } from "../src/dag/store" -import { Effect } from "effect" +import { createDagTool } from "../src/dag/tool" +import { Deferred, Effect } from "effect" import type { DagDefinition, DagExecutionRef, DagNodeDefinition } from "../src/dag/types" let directory: string | undefined @@ -479,3 +480,197 @@ test("subagent results parse from the structured output, the tagged text and the expect(subagentOutcome({ content: "The subagent is working in the background (sessionID: ses_3). You will be notified" })).toEqual({ sessionID: "ses_3", status: "running" }) expect(subagentOutcome({ content: "nothing" })).toEqual({}) }) + +test("an explicit input must name a node upstream of its consumer", () => { + const stray: DagNodeDefinition = { ...node("report"), inputs: [{ node: "work" }] } + expect(() => validateDefinition(definition([node("work"), stray]))).toThrow(/work is not upstream of report/) + expect(() => validateDefinition(definition([{ ...node("report"), inputs: [{ node: "report" }] }]))).toThrow(/not upstream/) + // Upstream through another dependency is settled before the consumer runs, so it may be bound. + const transitive: DagNodeDefinition = { ...node("report", ["review"]), inputs: [{ node: "work" }, { node: "review" }] } + expect(() => validateDefinition(definition([node("work"), node("review", ["work"]), transitive]))).not.toThrow() +}) + +test("rejecting a gate blocks everything downstream of it and ends the run", async () => { + directory = mkdtempSync(join(tmpdir(), "iolaus-dag-test-")) + const runner = fakeRunner() + const controller = createDagController({ directory, runner }) + const gate: DagNodeDefinition = { id: "gate", kind: "gate", prompt: "Ship it?", dependsOn: [] } + const run = await controller.create(definition([gate, node("build", ["gate"]), node("deploy", ["build"]), node("announce", ["deploy"])]), "owner") + const rejected = await controller.reject(run.runID, "owner", "gate") + expect(rejected.nodes.map((n) => n.status)).toEqual(["failed", "blocked", "blocked", "blocked"]) + expect(rejected.status).toBe("failed") + expect((await controller.wait(run.runID, "owner")).status).toBe("failed") + expect(runner.started).toEqual([]) + controller.close() +}) + +test("retrying a node reruns everything downstream of it, and an unknown node is refused", async () => { + directory = mkdtempSync(join(tmpdir(), "iolaus-dag-test-")) + const runner = fakeRunner() + const controller = createDagController({ directory, runner }) + const gate: DagNodeDefinition = { id: "gate", kind: "gate", prompt: "Accept?", dependsOn: ["test"] } + const run = await controller.create(definition([node("build"), node("test", ["build"]), gate, node("lint")]), "owner") + await new Promise((resolve) => setTimeout(resolve, 50)) + expect((await controller.approve(run.runID, "owner", "gate")).status).toBe("completed") + await expect(controller.retry(run.runID, "owner", "nope")).rejects.toThrow("Unknown DAG node: nope") + expect((await controller.snapshot(run.runID, "owner")).run.generation).toBe(1) + + await controller.retry(run.runID, "owner", "build") + await new Promise((resolve) => setTimeout(resolve, 50)) + const again = (await controller.snapshot(run.runID, "owner")).run + // The approval was given for the old build; lint does not depend on it and keeps its result. + expect(runner.started).toEqual(["build", "lint", "test", "build", "test"]) + expect(again.status).toBe("paused") + expect(Object.fromEntries(again.nodes.map((n) => [n.definition.id, [n.status, n.attempt]]))).toEqual({ build: ["completed", 2], test: ["completed", 2], gate: ["waiting_approval", 2], lint: ["completed", 1] }) + controller.close() +}) + +test("restart recovery starts only once the plugin has finished registering", async () => { + const runID = await stalledRun("wait") + const ready = Deferred.makeUnsafe() + const reattached: string[] = [] + const second = createDagController({ directory: directory!, recoveryReady: Deferred.await(ready), runner: { ...fakeRunner(), async reattach(ref) { reattached.push(ref.sessionID); return { payload: { text: "finished while detached" } } } } }) + await new Promise((resolve) => setTimeout(resolve, 40)) + expect(reattached).toEqual([]) + expect((await second.snapshot(runID, "caller")).run.nodes[0]?.status).toBe("running") + Effect.runSync(Deferred.succeed(ready, undefined)) + expect((await second.wait(runID, "caller")).status).toBe("completed") + expect(reattached).toEqual(["session-a"]) + second.close() +}) + +test("cancelling a run reports a child session that could not be stopped", async () => { + directory = mkdtempSync(join(tmpdir(), "iolaus-dag-test-")) + const traces: string[] = [] + const controller = createDagController({ directory, trace: (event) => { traces.push(event) }, + runner: { ...stalledRunner("wait"), async cancel(ref) { if (ref.nodeID === "a") throw new Error("host refused the interrupt") } } }) + const run = await controller.create(definition([node("a"), node("b")]), "owner") + await new Promise((resolve) => setTimeout(resolve, 20)) + const cancelled = await controller.cancel(run.runID, "owner") + expect(cancelled.status).toBe("cancelled") + expect(cancelled.nodes.map((n) => [n.definition.id, n.status, n.error])).toEqual([ + ["a", "cancelled", "Cancelled, but its session could not be stopped: host refused the interrupt"], + ["b", "cancelled", undefined], + ]) + expect(traces).toContain("iolaus.dag.cancel-failed") + const events = (await controller.snapshot(run.runID, "owner")).events + expect(events.filter((e) => e.type === "node.failed").map((e) => [e.nodeID, e.payload])).toEqual([["a", { message: "Cancelled, but its session could not be stopped: host refused the interrupt", status: "cancelled" }]]) + controller.close() +}) + +test("amend reuses a node only while it and everything upstream of it are unchanged, whatever the node order", async () => { + directory = mkdtempSync(join(tmpdir(), "iolaus-dag-test-")) + const runner = fakeRunner() + const controller = createDagController({ directory, runner, directoryAllowed: () => true }) + // The consumer may be listed before the node it depends on. + const graph = (prompt: string, order: readonly string[]) => definition(order.map((id) => id === "a" ? { ...node("a"), prompt } : node("b", ["a"]))) + const run = await controller.create(graph("build", ["b", "a"]), "owner") + await controller.wait(run.runID, "owner") + expect(runner.started).toEqual(["a", "b"]) + + const reordered = await controller.amend(run.runID, "owner", graph("build", ["a", "b"])) + expect(reordered.nodes.map((n) => n.status)).toEqual(["reused", "reused"]) + expect(runner.started).toEqual(["a", "b"]) + + await controller.amend(run.runID, "owner", graph("build differently", ["b", "a"])) + await controller.wait(run.runID, "owner") + expect(runner.started).toEqual(["a", "b", "a", "b"]) + + // The same nodes in another directory are different work. + await controller.amend(run.runID, "owner", { ...graph("build differently", ["b", "a"]), directory: join(directory, "elsewhere") }) + await controller.wait(run.runID, "owner") + expect(runner.started).toEqual(["a", "b", "a", "b", "a", "b"]) + controller.close() +}) + +test("a session's runs can be listed open-only or up to a limit", async () => { + directory = mkdtempSync(join(tmpdir(), "iolaus-dag-test-")) + const controller = createEffectController({ directory, databasePath: join(directory, "iolaus.db"), runner: runnerFromPromise(fakeRunner()) }) + const run = (effect: Effect.Effect) => Effect.runPromise(effect) + const done = await run(controller.create(definition([node("a")]), "owner")) + await run(controller.wait(done.runID, "owner")) + const held = await run(controller.create(definition([{ id: "gate", kind: "gate", prompt: "Go?", dependsOn: [] }]), "owner")) + expect((await run(controller.list("owner"))).map((value) => value.runID).sort()).toEqual([done.runID, held.runID].sort()) + expect((await run(controller.list("owner", { open: true }))).map((value) => value.runID)).toEqual([held.runID]) + expect(await run(controller.list("owner", { limit: 1 }))).toHaveLength(1) + await run(controller.close) +}) + +test("retry refuses an empty node id and an empty selection, and resume reruns what a cancel stopped", async () => { + directory = mkdtempSync(join(tmpdir(), "iolaus-dag-test-")) + const runner = fakeRunner() + const effect = createEffectController({ directory, databasePath: join(directory, "iolaus.db"), runner: runnerFromPromise(runner) }) + const controller = promiseController(effect) + const done = await controller.create(definition([node("a")]), "owner") + await controller.wait(done.runID, "owner") + await expect(controller.retry(done.runID, "owner", "")).rejects.toThrow("Unknown DAG node") + await expect(controller.retry(done.runID, "owner")).rejects.toThrow("Nothing to retry") + const tool = createDagTool(effect) + const call = async (input: unknown) => JSON.parse(String((await Effect.runPromise(tool.execute(input as never, { sessionID: "owner" } as never))).content)) + expect((await call({ action: "retry", run_id: done.runID, node_id: "" })).error).toMatch(/node_id is required/) + expect((await controller.snapshot(done.runID, "owner")).run.generation).toBe(1) + + const gate: DagNodeDefinition = { id: "gate", kind: "gate", prompt: "Go?", dependsOn: ["a"] } + const held = await controller.create(definition([node("a"), gate, node("b", ["gate"])]), "owner") + await new Promise((resolve) => setTimeout(resolve, 50)) + expect((await controller.cancel(held.runID, "owner")).nodes.map((n) => n.status)).toEqual(["completed", "cancelled", "cancelled"]) + await controller.resume(held.runID, "owner") + await new Promise((resolve) => setTimeout(resolve, 50)) + const again = (await controller.snapshot(held.runID, "owner")).run + expect([again.status, again.nodes.map((n) => n.status)]).toEqual(["paused", ["completed", "waiting_approval", "pending"]]) + expect(runner.started).toEqual(["a", "a"]) + controller.close() +}) + +test("recovery leaves alone a node that changed while it waited to start", async () => { + directory = mkdtempSync(join(tmpdir(), "iolaus-dag-test-")) + const path = join(directory, "iolaus.db") + const run = (effect: Effect.Effect) => Effect.runPromise(effect) + const first = createEffectController({ directory, databasePath: path, runner: runnerFromPromise(fakeRunner()) }) + // One call whose child session was never recorded, and one whose child is known. + const unknown = await run(first.observe({ ownerSessionID: "owner", agent: "explore", title: "Unknown child", prompt: "go" })) + const known = await run(first.observe({ ownerSessionID: "owner", runID: unknown.runID, agent: "explore", title: "Known child", prompt: "go" })) + await run(first.observed(known.runID, known.nodeID, { status: "running", sessionID: "ses_known" })) + Effect.runSync(first.close) + + const ready = Deferred.makeUnsafe() + let release!: (value: { payload: { text: string } }) => void + const reattach = new Promise<{ payload: { text: string } }>((resolve) => { release = resolve }) + const second = createEffectController({ directory, databasePath: path, recoveryReady: Deferred.await(ready), runner: runnerFromPromise({ ...fakeRunner(), reattach: () => reattach }) }) + // The live observer learns the first child's session before recovery starts. + await run(second.observed(unknown.runID, unknown.nodeID, { status: "running", sessionID: "ses_late" })) + Effect.runSync(Deferred.succeed(ready, undefined)) + await new Promise((resolve) => setTimeout(resolve, 30)) + expect((await run(second.node(unknown.runID, "owner", unknown.nodeID))).status).toBe("running") + // The second child answers and is followed up while its reattach still waits; that stale wait must not settle the new attempt. + await run(second.observed(known.runID, known.nodeID, { status: "completed", text: "live answer" })) + await run(second.observed(known.runID, known.nodeID, { status: "running" })) + release({ payload: { text: "stale answer" } }) + await new Promise((resolve) => setTimeout(resolve, 30)) + const followed = await run(second.node(known.runID, "owner", known.nodeID)) + expect([followed.status, followed.attempt, followed.result?.payload]).toEqual(["running", 2, { text: "live answer" }]) + Effect.runSync(second.close) +}) + +test("a child created after its run was cancelled is reported when it cannot be stopped", async () => { + directory = mkdtempSync(join(tmpdir(), "iolaus-dag-test-")) + const traces: string[] = [] + let created!: () => void, release!: () => void + const creating = new Promise((resolve) => { created = resolve }), held = new Promise((resolve) => { release = resolve }) + const controller = createDagController({ directory, trace: (event) => { traces.push(event) }, runner: { + async start(input) { created(); await held; return { nodeID: input.node.id, attempt: input.attempt, sessionID: "late" } }, + wait: () => new Promise(() => {}), + async cancel() { throw new Error("host refused the interrupt") }, + } }) + const run = await controller.create(definition([node("a")]), "owner") + await creating + expect((await controller.cancel(run.runID, "owner")).status).toBe("cancelled") + release() + await new Promise((resolve) => setTimeout(resolve, 30)) + const snapshot = await controller.snapshot(run.runID, "owner") + const message = "Cancelled, but its session could not be stopped: host refused the interrupt" + expect([snapshot.run.status, snapshot.run.nodes[0]?.status, snapshot.run.nodes[0]?.error]).toEqual(["cancelled", "cancelled", message]) + expect(snapshot.events.filter((e) => e.type === "node.failed").map((e) => e.payload)).toEqual([{ message, status: "cancelled" }]) + expect(traces).toContain("iolaus.dag.cancel-failed") + controller.close() +}) From b100cba9ee9211240ed08993771500146f82d106 Mon Sep 17 00:00:00 2001 From: Bryan Date: Sat, 14 Nov 2026 20:47:35 +0800 Subject: [PATCH 4/6] Report checker failures and enforce bounded, interruptible verification --- src/verify/hook.ts | 7 +- src/verify/run.ts | 121 +++++++++++++++------ tests/verify.test.ts | 247 ++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 337 insertions(+), 38 deletions(-) diff --git a/src/verify/hook.ts b/src/verify/hook.ts index 1156fe4..6e3a0e9 100644 --- a/src/verify/hook.ts +++ b/src/verify/hook.ts @@ -22,11 +22,12 @@ type AfterEvent = { * the hook itself never fail the edit. */ export function registerVerifyHook(ctx: { tool: Pick }, host: VerifyHost): Effect.Effect { - return ctx.tool.hook("execute.after", (event) => Effect.promise(async () => { + return ctx.tool.hook("execute.after", (event) => Effect.promise(async (signal) => { const e = event as unknown as AfterEvent if (!MUTATION_TOOLS.has(e.tool) || e.status !== "completed") return try { const directory = await host.directory(e.sessionID) + if (signal.aborted) return const config = loadVerifyConfig(directory, host.config) if (config.source === "disabled") return const paths = mutatedPaths(e.input, directory) @@ -34,7 +35,8 @@ export function registerVerifyHook(ctx: { tool: Pick }, host.trace?.("iolaus.verify.skipped", { tool: e.tool, reason: "no paths in input", keys: typeof e.input === "object" && e.input ? Object.keys(e.input) : [] }) return } - const report = await verify(config, directory, paths) + const report = await verify(config, directory, paths, signal) + if (signal.aborted) return const text = renderReport(report) host.trace?.("iolaus.verify.ran", { tool: e.tool, agent: e.agent, paths: report.paths, source: config.source, @@ -50,6 +52,7 @@ export function registerVerifyHook(ctx: { tool: Pick }, } if (typeof result.output === "string" && result.content === undefined) result.output = `${result.output}${text}` } catch (error) { + if (signal.aborted) return host.trace?.("iolaus.verify.failed", { tool: e.tool, error: String(error) }) } })).pipe(Effect.asVoid) diff --git a/src/verify/run.ts b/src/verify/run.ts index 19af1a9..66eef7d 100644 --- a/src/verify/run.ts +++ b/src/verify/run.ts @@ -1,4 +1,4 @@ -import { execFile } from "node:child_process" +import { execFile, type ExecFileException } from "node:child_process" import { existsSync, readFileSync } from "node:fs" import { isAbsolute, relative, resolve } from "node:path" import type { Checker, VerifyConfig } from "./config" @@ -47,76 +47,127 @@ function inside(directory: string, target: string): boolean { } // tsc: src/a.ts(3,7): error TS2322: ... eslint unix / ruff concise / cargo short / go vet: src/a.ts:3:7 - error ... or ./a.go:3:2: msg -const LOCATION = /^(?\.?\.?\/?[^\s:(]+(?:\/[^\s:(]+)*)(?:\((?\d+),\d+\)|:(?\d+)(?::\d+)?)[\s:-]+(?.*)$/ +const LOCATION = /^(?[^:(]+)(?:\((?\d+),\d+\)|:(?\d+)(?::\d+)?)[\s:-]+(?.*)$/ // biome --reporter=github: ::error title=lint/x,file=src/a.ts,line=3,endLine=3,col=1,endColumn=2::message const GITHUB = /^::(?:error|warning|notice)\b(?[^:]*)::(?.*)$/ -/** Keep lines that locate a diagnostic in one of the changed files. */ -export function filterDiagnostics(output: string, directory: string, changed: readonly string[]): Diagnostic[] { - const wanted = new Set(changed.map((path) => resolve(directory, path))) - const result: Diagnostic[] = [] +/** A diagnostic with its absolute path, before it is narrowed to the changed files. */ +type Located = { readonly path: string; readonly line?: number; readonly message: string } + +function located(output: string, directory: string): Located[] { + const result: Located[] = [] for (const raw of output.split(/\r?\n/)) { const gh = GITHUB.exec(raw.trim()) if (gh?.groups) { const attrs = Object.fromEntries(gh.groups.attrs.split(",").map((pair) => pair.split("=").map((s) => s.trim())).filter((pair) => pair.length === 2)) - if (attrs.file) { - const path = resolve(directory, attrs.file) - if (wanted.has(path)) result.push({ path: relative(directory, path), ...(attrs.line ? { line: Number(attrs.line) } : {}), message: `${attrs.title ? `${attrs.title}: ` : ""}${gh.groups.msg.trim()}` }) - } + if (attrs.file) result.push({ path: resolve(directory, attrs.file), ...(attrs.line ? { line: Number(attrs.line) } : {}), message: `${attrs.title ? `${attrs.title}: ` : ""}${gh.groups.msg.trim()}` }) continue } const match = LOCATION.exec(raw.trim()) if (!match?.groups) continue - const path = resolve(directory, match.groups.path) - if (!wanted.has(path)) continue const line = Number(match.groups.l1 ?? match.groups.l2) - result.push({ path: relative(directory, path), ...(Number.isFinite(line) ? { line } : {}), message: match.groups.msg.trim() }) + result.push({ path: resolve(directory, match.groups.path), ...(Number.isFinite(line) ? { line } : {}), message: match.groups.msg.trim() }) } return result } -/** JSON reporters: an array (or `diagnostics`/`results` array) of objects naming a file and optionally a line and message. */ -export function filterJsonDiagnostics(output: string, directory: string, changed: readonly string[]): Diagnostic[] { - const wanted = new Set(changed.map((path) => resolve(directory, path))) +/** JSON reporters: an array (or `diagnostics`/`results` array) of objects naming a file and optionally a line and message. Undefined for malformed or unsupported reports. */ +function locatedJson(output: string, directory: string): Located[] | undefined { + if (!output.trim()) return [] let parsed: unknown - try { parsed = JSON.parse(output.trim()) } catch { return [] } + try { parsed = JSON.parse(output.trim()) } catch { return undefined } const list = Array.isArray(parsed) ? parsed : parsed && typeof parsed === "object" && Array.isArray((parsed as { diagnostics?: unknown }).diagnostics) ? (parsed as { diagnostics: unknown[] }).diagnostics : parsed && typeof parsed === "object" && Array.isArray((parsed as { results?: unknown }).results) ? (parsed as { results: unknown[] }).results - : [] - const result: Diagnostic[] = [] + : undefined + if (!list) return undefined + const result: Located[] = [] for (const item of list) { - if (!item || typeof item !== "object") continue + if (!item || typeof item !== "object" || Array.isArray(item)) return undefined const record = item as Record // ESLint's JSON groups messages per file. - if (Array.isArray(record.messages) && typeof record.filePath === "string") { + if (Array.isArray(record.messages) && typeof record.filePath === "string" && record.filePath.trim()) { const path = resolve(directory, record.filePath) - if (!wanted.has(path)) continue - for (const m of record.messages as Record[]) result.push({ path: relative(directory, path), ...(typeof m.line === "number" ? { line: m.line } : {}), message: String(m.message ?? m.ruleId ?? "") }) + for (const entry of record.messages) { + if (!entry || typeof entry !== "object" || Array.isArray(entry)) return undefined + const message = entry.message ?? entry.ruleId ?? "" + if (typeof message !== "string" && typeof message !== "number") return undefined + result.push({ path, ...(typeof entry.line === "number" ? { line: entry.line } : {}), message: String(message) }) + } continue } + if (record.messages !== undefined) return undefined const file = record.file ?? record.path ?? record.filename ?? record.filePath ?? (record.location as { file?: unknown } | undefined)?.file - if (typeof file !== "string") continue - const path = resolve(directory, file) - if (!wanted.has(path)) continue + if (typeof file !== "string" || !file.trim()) return undefined const line = record.line ?? (record.location as { line?: unknown; row?: unknown } | undefined)?.line ?? (record.location as { row?: unknown } | undefined)?.row ?? (record.start as { line?: unknown } | undefined)?.line - result.push({ path: relative(directory, path), ...(typeof line === "number" ? { line } : {}), message: String(record.message ?? record.code ?? record.rule ?? "") }) + const message = record.message ?? record.code ?? record.rule ?? "" + if (typeof message !== "string" && typeof message !== "number") return undefined + result.push({ path: resolve(directory, file), ...(typeof line === "number" ? { line } : {}), message: String(message) }) } return result } +function inChanged(all: readonly Located[], directory: string, changed: readonly string[]): Diagnostic[] { + const wanted = new Set(changed.map((path) => resolve(directory, path))) + return all.filter((item) => wanted.has(item.path)).map((item) => ({ ...item, path: relative(directory, item.path) })) +} + +/** Keep lines that locate a diagnostic in one of the changed files. */ +export function filterDiagnostics(output: string, directory: string, changed: readonly string[]): Diagnostic[] { + return inChanged(located(output, directory), directory, changed) +} + +export function filterJsonDiagnostics(output: string, directory: string, changed: readonly string[]): Diagnostic[] { + return inChanged(locatedJson(output, directory) ?? [], directory, changed) +} + function runChecker(checker: Checker, directory: string, changed: readonly string[], timeoutMs: number, signal?: AbortSignal): Promise { const started = Date.now() return new Promise((done) => { const [command, ...args] = checker.argv - execFile(command, args, { cwd: directory, timeout: timeoutMs, maxBuffer: 16 * 1024 * 1024, encoding: "utf8", signal, env: { ...process.env, FORCE_COLOR: "0", NO_COLOR: "1" } }, (error, stdout, stderr) => { + let settled = false + let termination: string | undefined + let timeout: ReturnType | undefined + let grace: ReturnType | undefined + const finish = (error: ExecFileException | null, stdout: string, stderr: string) => { + if (settled || (termination && child.exitCode === null && child.signalCode === null && grace !== undefined)) return + settled = true + clearTimeout(timeout) + clearTimeout(grace) + signal?.removeEventListener("abort", abort) const durationMs = Date.now() - started const output = `${stdout ?? ""}\n${stderr ?? ""}` - const diagnostics = checker.format === "json" ? filterJsonDiagnostics(stdout ?? "", directory, changed) : filterDiagnostics(output, directory, changed) - const failedToRun = error && !("code" in error && typeof error.code === "number") - if (failedToRun) return done({ name: checker.name, ok: false, diagnostics, durationMs, error: String((error as Error).message).split("\n")[0] }) - done({ name: checker.name, ok: diagnostics.length === 0, diagnostics, durationMs }) - }) + const all = checker.format === "json" ? locatedJson(stdout ?? "", directory) : located(output, directory) + const diagnostics = inChanged(all ?? [], directory, changed) + const said = output.split(/\r?\n/).find((line) => line.trim())?.trim().slice(0, 300) ?? "no output" + const code = error && "code" in error && typeof error.code === "number" ? error.code : undefined + // A checker that did not get as far as locating a problem checked nothing: it could not start, was killed, + // printed something unreadable, or exited with an error and no diagnostic. None of that is a pass. + const failure = termination ?? (child.killed || signal?.aborted || error?.killed || error?.signal || (error && code === undefined) ? String(error?.message ?? "checker terminated").split("\n")[0] + : all === undefined ? `output is not JSON: ${said}` + : code !== undefined && all.length === 0 ? `exit code ${code}: ${said}` + : undefined) + done({ name: checker.name, ok: failure === undefined && diagnostics.length === 0, diagnostics, durationMs, ...(failure === undefined ? {} : { error: failure }) }) + } + const terminate = (reason: string) => { + if (settled || termination) return + termination = reason + clearTimeout(timeout) + grace = setTimeout(() => { + grace = undefined + if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL") + child.stdin?.destroy() + child.stdout?.destroy() + child.stderr?.destroy() + finish(null, "", "") + }, 100) + child.kill("SIGTERM") + } + const abort = () => terminate("checker cancelled") + const child = execFile(command, args, { cwd: directory, maxBuffer: 16 * 1024 * 1024, encoding: "utf8", env: { ...process.env, FORCE_COLOR: "0", NO_COLOR: "1" } }, finish) + timeout = setTimeout(() => terminate(`checker timed out after ${timeoutMs}ms`), timeoutMs) + signal?.addEventListener("abort", abort, { once: true }) + if (signal?.aborted) abort() }) } @@ -137,9 +188,11 @@ export function scanComments(paths: readonly string[], directory: string, patter } export async function verify(config: VerifyConfig, directory: string, paths: readonly string[], signal?: AbortSignal): Promise { + signal?.throwIfAborted() const changed = paths.filter((path) => inside(directory, path) && existsSync(path)) const applicable = config.checkers.filter((checker) => !checker.extensions || changed.some((path) => checker.extensions!.some((ext) => path.endsWith(ext)))) const checkers = changed.length ? await Promise.all(applicable.map((checker) => runChecker(checker, directory, changed, config.timeoutMs, signal))) : [] + signal?.throwIfAborted() return { paths: changed.map((path) => relative(directory, path)), checkers, comments: scanComments(changed, directory, config.commentPattern) } } @@ -147,7 +200,7 @@ export async function verify(config: VerifyConfig, directory: string, paths: rea export function renderReport(report: VerifyReport): string { const lines: string[] = [] for (const checker of report.checkers) { - if (checker.error) lines.push(`${checker.name}: could not run (${checker.error})`) + if (checker.error) lines.push(`${checker.name}: check failed (${checker.error})`) for (const d of checker.diagnostics) lines.push(`${checker.name}: ${d.path}${d.line ? `:${d.line}` : ""} ${d.message}`) } for (const d of report.comments) lines.push(`comment-check: ${d.path}:${d.line} ${d.message}`) diff --git a/tests/verify.test.ts b/tests/verify.test.ts index 67bbb18..7d763b6 100644 --- a/tests/verify.test.ts +++ b/tests/verify.test.ts @@ -1,12 +1,12 @@ import { expect, test } from "bun:test" -import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs" +import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs" import { tmpdir } from "node:os" import { join } from "node:path" import { DEFAULT_COMMENT_PATTERN, detectCheckers, loadVerifyConfig, parseVerifyConfig } from "../src/verify/config" import { filterDiagnostics, mutatedPaths, renderReport, scanComments, verify } from "../src/verify/run" import { registerVerifyHook } from "../src/verify/hook" import { parseOptions } from "../src/options" -import { Effect } from "effect" +import { Effect, Fiber } from "effect" function project(files: Record): string { const dir = mkdtempSync(join(tmpdir(), "iolaus-verify-")) @@ -47,6 +47,18 @@ test("comment scan flags request-explaining comments only", () => { rmSync(dir, { recursive: true, force: true }) }) +test("diagnostics preserve spaces in relative and absolute paths", () => { + const directory = "/project with spaces" + expect(filterDiagnostics([ + "src/my file.ts(3,7): error TS2322: bad type", + "/project with spaces/src/my file.ts:9:2: unused", + "src/other file.ts(1,1): error TS1000: ignored", + ].join("\n"), directory, [join(directory, "src/my file.ts")])).toEqual([ + { path: "src/my file.ts", line: 3, message: "error TS2322: bad type" }, + { path: "src/my file.ts", line: 9, message: "unused" }, + ]) +}) + test("config: detection, global section, disabled and validation", () => { const dir = project({ "tsconfig.json": "{}" }) expect(detectCheckers(dir)[0]?.argv.slice(1)).toEqual(["--noEmit", "--pretty", "false"]) @@ -154,3 +166,234 @@ test("json format parses flat arrays, wrapped arrays and eslint's per-file group expect(report.checkers[0].diagnostics).toEqual([{ path: "src/a.ts", line: 1, message: "from json" }]) rmSync(dir, { recursive: true, force: true }) }) + +test("a checker that fails without locating a problem is reported, not passed", async () => { + const dir = project({ "src/a.ts": "export const a = 1\n" }) + const run = (checker: { name: string; argv: string[]; format?: "json" }) => + verify({ checkers: [checker], timeoutMs: 10_000, commentPattern: null, source: "config" }, dir, [join(dir, "src/a.ts")]).then((report) => ({ checker: report.checkers[0], text: renderReport(report) })) + const script = (body: string) => ["node", "-e", body] + + const broken = await run({ name: "tsc", argv: script(`console.log("error TS5083: Cannot read file 'tsconfig.json'."); process.exit(1)`) }) + expect(broken.checker).toMatchObject({ ok: false, diagnostics: [], error: "exit code 1: error TS5083: Cannot read file 'tsconfig.json'." }) + expect(broken.text).toContain("tsc: check failed (exit code 1: error TS5083: Cannot read file 'tsconfig.json'.)") + + // Problems it located in other files are the project's, not this edit's. + const elsewhere = await run({ name: "tsc", argv: script(`console.log("src/b.ts(1,5): error TS2322: bad"); process.exit(2)`) }) + expect(elsewhere.checker).toMatchObject({ ok: true, diagnostics: [] }) + expect(elsewhere.checker.error).toBeUndefined() + expect(elsewhere.text).toBe("") + + const garbled = await run({ name: "lint", format: "json", argv: script(`console.log("Oops, something went wrong")`) }) + expect(garbled.checker).toMatchObject({ ok: false, error: "output is not JSON: Oops, something went wrong" }) + const crashed = await run({ name: "lint", format: "json", argv: script(`console.error("config error"); process.exit(2)`) }) + expect(crashed.checker).toMatchObject({ ok: false, error: "exit code 2: config error" }) + const clean = await run({ name: "lint", format: "json", argv: script(`console.log("[]")`) }) + expect(clean.checker).toMatchObject({ ok: true, diagnostics: [] }) + expect((await run({ name: "lint", format: "json", argv: script("") })).checker.ok).toBe(true) + rmSync(dir, { recursive: true, force: true }) +}) + +test("JSON checker rejects malformed reports without throwing and keeps unrelated diagnostics clean", async () => { + const dir = project({ "a.ts": "export {}\n" }) + try { + const run = (output: string, code = 0) => verify({ + checkers: [{ name: "json", format: "json", argv: ["node", "-e", `process.stdout.write(${JSON.stringify(output)}); process.exit(${code})`] }], + timeoutMs: 10_000, commentPattern: null, source: "config", + }, dir, [join(dir, "a.ts")]) + for (const output of ["{broken", "null", "42", '"text"', "{}", '{"results":{}}', "[null]", '[{"filePath":"a.ts","messages":[null]}]', '[{"filePath":" ","messages":[]}]', '[{"file":"a.ts","message":{"toString":null}}]']) { + const report = await run(output) + expect(report.checkers[0].ok).toBe(false) + expect(renderReport(report)).toContain("json: check failed") + } + const unrelated = await run('[{"filePath":"other file.ts","messages":[{"line":1,"message":"unrelated"}]}]', 1) + expect(unrelated.checkers[0]).toMatchObject({ ok: true, diagnostics: [] }) + expect(renderReport(unrelated)).toBe("") + expect((await run('{"results":[]}')).checkers[0].ok).toBe(true) + expect((await run('[{"filePath":"a.ts","messages":[]}]')).checkers[0].ok).toBe(true) + } finally { + rmSync(dir, { recursive: true, force: true }) + } +}) + +test("checker termination overrides numeric exits and partial unrelated diagnostics", async () => { + const dir = project({ "a.ts": "export {}\n" }) + try { + for (const body of [ + `process.on('SIGTERM', () => process.exit(2)); console.log('other.ts(1,1): error: unrelated'); setInterval(() => {}, 1000)`, + `process.on('SIGTERM', () => process.exit(0)); console.log('other.ts(1,1): error: unrelated'); setInterval(() => {}, 1000)`, + `console.log('other.ts(1,1): error: unrelated'); process.kill(process.pid, 'SIGTERM')`, + ]) { + const report = await verify({ + checkers: [{ name: "terminated", argv: ["node", "-e", body] }], timeoutMs: 250, commentPattern: null, source: "config", + }, dir, [join(dir, "a.ts")]) + expect(report.checkers[0]).toMatchObject({ ok: false, diagnostics: [], error: expect.any(String) }) + expect(renderReport(report)).toContain("terminated: check failed") + } + } finally { + rmSync(dir, { recursive: true, force: true }) + } +}) + +test("timeout kills a checker ignoring TERM within a bounded grace period", async () => { + const dir = project({ "a.ts": "export {}\n" }) + const ready = join(dir, "ready") + const stopped = join(dir, "stopped") + try { + const started = Date.now() + const report = await verify({ + checkers: [{ name: "ignores-term", argv: ["node", "-e", `const fs = require('node:fs'); process.on('SIGTERM', () => fs.writeFileSync(${JSON.stringify(stopped)}, 'TERM')); fs.writeFileSync(${JSON.stringify(ready)}, String(process.pid)); setTimeout(() => process.exit(0), 2500)`] }], + timeoutMs: 250, commentPattern: null, source: "config", + }, dir, [join(dir, "a.ts")]) + expect(Date.now() - started).toBeLessThan(1200) + expect(existsSync(stopped)).toBe(true) + expect(report.checkers[0]).toMatchObject({ ok: false, error: expect.any(String) }) + const pid = Number(readFileSync(ready, "utf8")) + const deadline = Date.now() + 500 + while (Date.now() < deadline) { + try { process.kill(pid, 0) } catch { break } + await new Promise((done) => setTimeout(done, 10)) + } + expect(() => process.kill(pid, 0)).toThrow() + } finally { + if (existsSync(ready)) { + try { process.kill(Number(readFileSync(ready, "utf8")), "SIGKILL") } catch {} + } + rmSync(dir, { recursive: true, force: true }) + } +}) + +test("abort kills a checker ignoring TERM without waiting for its normal timeout", async () => { + const dir = project({ "a.ts": "export {}\n" }) + const ready = join(dir, "ready") + const stopped = join(dir, "stopped") + const controller = new AbortController() + const reason = new Error("cancel checker") + const result = verify({ + checkers: [{ name: "ignores-term", argv: ["node", "-e", `const fs = require('node:fs'); process.on('SIGTERM', () => fs.writeFileSync(${JSON.stringify(stopped)}, 'TERM')); fs.writeFileSync(${JSON.stringify(ready)}, String(process.pid)); setTimeout(() => process.exit(0), 2500)`] }], + timeoutMs: 10_000, commentPattern: null, source: "config", + }, dir, [join(dir, "a.ts")], controller.signal).then(() => undefined, (error: unknown) => error) + try { + const deadline = Date.now() + 1000 + while (!existsSync(ready) && Date.now() < deadline) await new Promise((done) => setTimeout(done, 10)) + expect(existsSync(ready)).toBe(true) + const started = Date.now() + controller.abort(reason) + expect(await result).toBe(reason) + expect(Date.now() - started).toBeLessThan(1200) + expect(existsSync(stopped)).toBe(true) + const pid = Number(readFileSync(ready, "utf8")) + const stoppedDeadline = Date.now() + 500 + while (Date.now() < stoppedDeadline) { + try { process.kill(pid, 0) } catch { break } + await new Promise((done) => setTimeout(done, 10)) + } + expect(() => process.kill(pid, 0)).toThrow() + } finally { + controller.abort(reason) + if (existsSync(ready)) { + try { process.kill(Number(readFileSync(ready, "utf8")), "SIGKILL") } catch {} + } + await result + rmSync(dir, { recursive: true, force: true }) + } +}) + +test("timeout and abort finish even when an exited checker's descendant holds its pipes", async () => { + for (const cancel of [false, true]) { + const dir = project({ "a.ts": "export {}\n" }) + const ready = join(dir, "ready") + const controller = new AbortController() + const reason = new Error("cancel inherited pipes") + const descendant = `require('node:fs').writeFileSync(${JSON.stringify(ready)}, String(process.pid)); setTimeout(() => process.exit(0), 2500)` + const started = Date.now() + const result = verify({ + checkers: [{ name: "inherited-pipes", argv: ["node", "-e", `require('node:child_process').spawn(process.execPath, ['-e', ${JSON.stringify(descendant)}], {stdio: ['ignore', 'inherit', 'inherit']}); process.exit(0)`] }], + timeoutMs: cancel ? 10_000 : 250, commentPattern: null, source: "config", + }, dir, [join(dir, "a.ts")], controller.signal).then((report) => report, (error: unknown) => error) + try { + const deadline = Date.now() + 1000 + while (!existsSync(ready) && Date.now() < deadline) await new Promise((done) => setTimeout(done, 10)) + expect(existsSync(ready)).toBe(true) + if (cancel) controller.abort(reason) + const outcome = await result + expect(Date.now() - started).toBeLessThan(1200) + if (cancel) expect(outcome).toBe(reason) + else expect(outcome).toMatchObject({ checkers: [{ ok: false, error: expect.any(String) }] }) + } finally { + controller.abort(reason) + if (existsSync(ready)) { + try { process.kill(Number(readFileSync(ready, "utf8")), "SIGKILL") } catch {} + } + await result + rmSync(dir, { recursive: true, force: true }) + } + } +}) + +test("interrupting the registered hook stops its checker and suppresses late postprocessing", async () => { + const dir = project({ "a.ts": "// added by AI\n" }) + let handler!: (event: unknown) => Effect.Effect + const traces: string[] = [] + const ready = join(dir, "ready") + const stopped = join(dir, "stopped") + const body = `const fs = require('node:fs'); process.on('SIGTERM', () => { fs.writeFileSync(${JSON.stringify(stopped)}, 'stopped'); process.exit(2) }); fs.writeFileSync(${JSON.stringify(ready)}, String(process.pid)); console.log('other.ts(1,1): error: unrelated'); setInterval(() => {}, 1000)` + await Effect.runPromise(Effect.scoped(registerVerifyHook({ tool: { hook: (_name: string, callback: unknown) => Effect.sync(() => { handler = callback as never; return { dispose: Effect.void } }) } } as never, + { directory: async () => dir, trace: (event) => traces.push(event), config: { checkers: [{ name: "waiting", argv: ["node", "-e", body] }], timeoutMs: 10_000 } }))) + const event = { tool: "patch", status: "completed", sessionID: "ses_cancel", agent: "sisyphus", input: { path: "a.ts" }, result: { content: "Edited." } } + const fiber = Effect.runFork(handler(event)) + const waitFor = async (path: string) => { + const deadline = Date.now() + 1000 + while (!existsSync(path) && Date.now() < deadline) await new Promise((done) => setTimeout(done, 10)) + expect(existsSync(path)).toBe(true) + } + try { + await waitFor(ready) + await Effect.runPromise(Fiber.interrupt(fiber)) + await waitFor(stopped) + await new Promise((done) => setTimeout(done, 50)) + expect(event.result.content).toBe("Edited.") + expect(traces).toEqual([]) + } finally { + await Effect.runPromise(Fiber.interrupt(fiber)) + if (existsSync(ready)) { + try { process.kill(Number(readFileSync(ready, "utf8")), "SIGKILL") } catch {} + } + rmSync(dir, { recursive: true, force: true }) + } +}) + +test("an interrupted hook does not resume after directory lookup finishes", async () => { + const dir = project({ "a.ts": "// added by AI\n" }) + let handler!: (event: unknown) => Effect.Effect + let finishDirectory!: (directory: string) => void + let enteredDirectory!: () => void + const entered = new Promise((done) => { enteredDirectory = done }) + const directory = new Promise((done) => { finishDirectory = done }) + const traces: string[] = [] + await Effect.runPromise(Effect.scoped(registerVerifyHook({ tool: { hook: (_name: string, callback: unknown) => Effect.sync(() => { handler = callback as never; return { dispose: Effect.void } }) } } as never, + { directory: () => { enteredDirectory(); return directory }, trace: (event) => traces.push(event), config: { checkers: [] } }))) + const event = { tool: "write", status: "completed", sessionID: "ses_lookup", agent: "sisyphus", input: { path: "a.ts" }, result: { content: "Written." } } + const fiber = Effect.runFork(handler(event)) + try { + await entered + await Effect.runPromise(Fiber.interrupt(fiber)) + finishDirectory(dir) + await new Promise((done) => setTimeout(done, 20)) + expect(event.result.content).toBe("Written.") + expect(traces).toEqual([]) + } finally { + finishDirectory(dir) + await Effect.runPromise(Fiber.interrupt(fiber)) + rmSync(dir, { recursive: true, force: true }) + } +}) + +test("verify refuses an already cancelled signal before accessing checker configuration", async () => { + const controller = new AbortController() + const reason = new Error("verification cancelled") + controller.abort(reason) + await expect(verify({ + get checkers(): never { throw new Error("checker configuration accessed after cancellation") }, + timeoutMs: 1000, commentPattern: "(", source: "config", + }, "/p", [], controller.signal)).rejects.toBe(reason) +}) From 0844c50b9db6653f8c6a5fa11e45129a59987edb Mon Sep 17 00:00:00 2001 From: Bryan Date: Sat, 14 Nov 2026 20:47:35 +0800 Subject: [PATCH 5/6] Document durable retry, goal control and verification behavior --- AGENTS.md | 69 +++++++++++++++++++++++++++++++++++++++++-------------- README.md | 9 ++++++-- 2 files changed, 59 insertions(+), 19 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index aef1073..dfe616c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -45,9 +45,10 @@ runner, the `ast_grep` and `gh` Code Mode namespaces, and the built-in DAG controller's `close` runs as a scope finalizer. Failures are typed: `DagValidationError` for caller mistakes, `DagRunnerError` for child execution, which the scheduler turns into node retry/failure and never lets - escape. Per-run mutual exclusion is a one-permit `Semaphore`; `wait` is a - `Deferred`; launch fibers are forked into the controller scope so `close` - interrupts them. `src/dag/promise.ts` is a Promise view for tests and QA; + escape. Per-run mutual exclusion is a one-permit `Semaphore` held in a keyed lock + (`src/keyed-lock.ts`) that drops a key once nothing holds or waits on it; `wait` is a + `Deferred` whose waiter is removed when the caller stops waiting; launch fibers are + forked into the controller scope so `close` interrupts them. `src/dag/promise.ts` is a Promise view for tests and QA; `src/effect-bridge.ts` lifts the Promise-authored ast_grep and gh tools into the Effect editor. `effect@4.1.0` is an exact peer and dependency pinned to the host's version and client peer contract, with @@ -59,6 +60,22 @@ runner, the `ast_grep` and `gh` Code Mode namespaces, and the built-in - `src/dag/` is the active Iolaus durable DAG module. It uses shared SQLite WAL state, graph/node fingerprints, dependency-frontier admission, node-level retry, cancellation and JSON-safe result envelopes. +- Graph and state rules the controller enforces. An explicit `inputs: [{node}]` must name + a node upstream of its consumer (in `dependsOn`, or above a node that is), checked in + `validateDefinition`. A node's fingerprint covers everything upstream of it whatever the + node order, and `amend` reuses a result only while that fingerprint and the run + `directory` are unchanged. Rejecting a gate blocks every node downstream of it, so the + run ends `failed` instead of staying open. `retry` refuses an unknown `node_id` and + resets everything downstream of a retried node, completed results and approvals + included, because they were produced from the old result. `cancel` always cancels the + run; a child session that could not be stopped is recorded on its node (`error`, a + `node.failed` event with `status: "cancelled"`, trace `iolaus.dag.cancel-failed`). +- `DagStore.saveRun` checks the snapshot's per-run revision inside the write transaction. + A conflicting save, even within one generation, writes no nodes, events or notices: + reload the run and reconsider the transition instead of replaying the stale snapshot. + Write stamps skip unchanged rows; keep node records and definitions immutable. + `listRuns(owner, {open, limit})` + filters in SQL; session state reads open runs only and the view reads the newest 50. - `src/dag/quiesce.ts` is the one place that knows a host subagent always runs in the background (2.3.0: no `background` input, no inline result, the parent idles and is woken by the child's report). `session.wait` only means "no active execution", so `settle` @@ -66,9 +83,9 @@ runner, the `ast_grep` and `gh` Code Mode namespaces, and the built-in per generation), then on the session again, until `time.busy`/`time.idle` of the subtree stop changing; `busy` reads the same subtree without waiting; `stop` interrupts each generation deepest first and the session last, because the host leaves children running - when their parent is interrupted. The native runner's `finish` and `cancel`, the - subagent observer and the goal loop (`GoalRuntimePorts.waiting`) use it. Background - shells are not followed. Unit coverage: `tests/background-subagents.test.ts`. + when their parent is interrupted. The native runner's `finish` and `cancel` and the + subagent observer use it. Background shells are not followed. Unit coverage: + `tests/background-subagents.test.ts`. - `src/dag/observe.ts` records native `subagent` calls without changing them. The `execute.before` hook (registered after the role guard, so refused calls are not recorded) appends a node to an owner-scoped observed batch @@ -218,8 +235,10 @@ runner, the `ast_grep` and `gh` Code Mode namespaces, and the built-in left, and traces host failures (`iolaus.state.failed`) without raising. The host renders it as ``, announces changes at the next step without an extra turn or a system-prompt change, and keeps it across compaction - and revert, so there is no compaction hook. Event subscriptions name their - `types`. `script/qa-borrows.mjs` is the live QA for fallback, escalation, team, + and revert, so there is no compaction hook. A fork copies the parent's instruction + entries but none of the goal, role or runs they describe (those are keyed by session + ID), so the `fork` session hook recomputes the fork's entry and normally removes it. + Event subscriptions name their `types`. `script/qa-borrows.mjs` is the live QA for fallback, escalation, team, run directories, /start-work delivery and session state across compaction. - `src/ast-grep/` registers `ast_grep.search`, `ast_grep.rewrite` and `ast_grep.scan` as Code Mode tools when an `ast-grep` binary answers @@ -275,7 +294,11 @@ runner, the `ast_grep` and `gh` Code Mode namespaces, and the built-in `file(line,col)`, `file:line:col`, `./file:line:col` or GitHub-reporter `::error file=…,line=…::msg`; a checker with `format: "json"` is parsed as a JSON array (flat, `diagnostics`/`results`, or ESLint per-file groups). `verify: false` - or `{checkers: [], commentPattern: null}` disables it. Hook failures never + or `{checkers: [], commentPattern: null}` disables it. A checker that did not get as + far as locating a problem checked nothing and is reported as `: check failed + (...)`: it could not start, was killed, printed non-JSON under `format: "json"`, or + exited non-zero with no located diagnostic. A non-zero exit whose diagnostics are all + in other files is still a pass for this edit. Hook failures never fail the edit. GPT model IDs get `patch` instead of `edit`/`write`; paths are taken from `*** Update/Add File:` headers as well as `filePath`/`path`. - DAG nodes execute through native OpenCode child sessions using the registered @@ -312,7 +335,10 @@ runner, the `ast_grep` and `gh` Code Mode namespaces, and the built-in built-in default chain). Iolaus does not check provider connectivity or subscription; a lane the config does not name is not registered. A DAG node may omit `model` to run on its lane's configured model. -- Restart recovery never replays a prompt. When a controller starts (plugin +- Restart recovery never replays a prompt. It starts once the plugin has finished + registering (`recoveryReady`, resolved at the end of setup, so settled and launched + nodes see every hook, tool and RPC), on the runs that were open when the controller was + built. When a controller starts (plugin reload or restart) it reattaches every starting/running node whose child session already received its prompt (`runner.reattach`, no new prompt) and settles it with that child's own outcome, even one that finished while no @@ -366,13 +392,22 @@ runner, the `ast_grep` and `gh` Code Mode namespaces, and the built-in `/start-work ` (`plan.ts`, `startwork.ts`: one Atlas node per ticket in `Blocked by` order, `review-standards` and `review-spec` on Momus, `fix` when either says FAIL, `accept` gate) and sets Hephaestus goals. The goal loop - (`goal.ts`, after OMO's goal hook) continues a top-level Hephaestus session on - `session.execution.succeeded` via `session.synthetic` until `update_goal` - complete, pausing after 3 tool-less turns or 50 continuations; DAG nodes and - subagents never loop. A session whose subagents are still working is not continued - (`iolaus.goal.waiting`): their report wakes it, the loop decides at the end of that - turn, and the delegating turn's tool calls count for it. `get_goal`/`create_goal`/`update_goal` are denied by name to - every Iolaus lane but Hephaestus. Hephaestus renders its GPT variant on GPT models + (`goal.ts`, after OMO's goal hook) continues a top-level Hephaestus session from the + host's `experimental.idle` hook via `session.synthetic`, until `update_goal` complete, + pausing after 3 tool-less turns or 50 continuations; DAG nodes and subagents never + loop. No timer drives continuation: the hook runs when the host would + let the session go idle with nothing pending, and input it admits continues the same + execution. A session whose own subagent or image job is still running is not + continued (`iolaus.goal.waiting`): that job's report wakes it, the loop decides at the + end of that turn, and the delegating turn's tool calls count for it. `/goal` takes the + host's `pause`/`resume`/`clear` words as well as an objective (a resume starts a fresh + continuation budget). Iolaus's `/goal` replaces the host's `opencode.goal` command of the + same name (the later registration wins). It operates on Iolaus state, not the host's + goal store; without Hephaestus in `agents` the host's command is untouched. Clear + deletes the goal. Only a paused goal can resume. Failed continuation admission pauses + the goal without spending a round. + `get_goal`/`create_goal`/`update_goal` are denied by name to every Iolaus lane but + Hephaestus. Hephaestus renders its GPT variant on GPT models and the generic GPT body elsewhere. `script/qa-roles.mjs` is the live QA. - `ultrawork` and `hyperplan` are DAG modes (`src/prompts/mode-dag.ts`). The session that received `/ultrawork` or `/hyperplan` gets the OMO diff --git a/README.md b/README.md index 46442d4..412a24c 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ Iolaus has three top-level workflows run by four primary agents. You pick the wo | Workflow | Primary | Command | | --- | --- | --- | | Do anything | Sisyphus | `/ultrawork ` | -| Goal loop | Hephaestus | `/goal ` | +| Goal loop | Hephaestus | `/goal `, `/goal pause`, `/goal resume`, `/goal clear` | | Plan, then implement | Prometheus → Atlas | `/hyperplan `, then `/start-work ` | The slash commands have OMO-style keyword aliases. A leading keyword selects the same mode and hands the session to its owning agent, exactly as the command does: @@ -81,6 +81,8 @@ Each primary has one job, and the plugin enforces it in code rather than in prom Running one of these commands in another agent's top-level session switches the session to the owning agent first; the session keeps its model. Commands act only in top-level sessions: in a subagent or DAG child, `/start-work` or `/goal` is ordinary prompt text. +With Hephaestus enabled, `/goal` controls the Iolaus goal, not OpenCode's native goal store. Resume gives a paused goal a fresh budget; clear deletes it, so resuming cannot bring it back. Without Hephaestus, OpenCode keeps its native command. + ### Who may delegate to whom Everything that is not a primary is a shared lower worker: the specialists (`oracle`, `librarian`, `explore`, `metis`, `momus`, `multimodal-looker`, `sisyphus-junior`) and the category lanes (`quick`, `deep-low`, `deep-high`, ...). The rule is short: @@ -108,7 +110,10 @@ pinned model taken from `IOLAUS_HOME/iolaus.json`; an unconfigured lane is not registered. A DAG node may omit `model` to inherit the lane's model. Fan-in binds every upstream result with provenance through `inputs: [{node: "*"}]`, `when` predicates route conditionally by skipping branches, and `kind: "gate"` nodes -pause the run for a human approve/reject. +pause the run for a human approve/reject. A named input must be upstream of the +node that binds it. Rejecting a gate blocks everything downstream of it and ends +the run. Retrying a node reruns everything downstream of it, since those results +came from the old one. ### Nonblocking flows and notifications From b110045315b92aa180ac77d6bc445a3450f03c8c Mon Sep 17 00:00:00 2001 From: Bryan Date: Sat, 14 Nov 2026 20:52:26 +0800 Subject: [PATCH 6/6] Record final OpenCode 2.3 live acceptance receipts --- .../dag-hardening/final/borrows/receipt.json | 84 +++ .../final/dag-recover/receipt.json | 67 ++ .../final/flow-session-fixes/receipt.json | 65 ++ .../final/flow-steering/receipt.json | 407 +++++++++++ .../dag-hardening/final/live/receipt.json | 630 ++++++++++++++++++ .../final/owner-rescue/receipt.json | 104 +++ .../dag-hardening/final/roles/receipt.json | 224 +++++++ .../final/subagent-batches/receipt.json | 77 +++ script/qa-borrows.mjs | 3 +- 9 files changed, 1659 insertions(+), 2 deletions(-) create mode 100644 .iolaus/evidence/dag-hardening/final/borrows/receipt.json create mode 100644 .iolaus/evidence/dag-hardening/final/dag-recover/receipt.json create mode 100644 .iolaus/evidence/dag-hardening/final/flow-session-fixes/receipt.json create mode 100644 .iolaus/evidence/dag-hardening/final/flow-steering/receipt.json create mode 100644 .iolaus/evidence/dag-hardening/final/live/receipt.json create mode 100644 .iolaus/evidence/dag-hardening/final/owner-rescue/receipt.json create mode 100644 .iolaus/evidence/dag-hardening/final/roles/receipt.json create mode 100644 .iolaus/evidence/dag-hardening/final/subagent-batches/receipt.json diff --git a/.iolaus/evidence/dag-hardening/final/borrows/receipt.json b/.iolaus/evidence/dag-hardening/final/borrows/receipt.json new file mode 100644 index 0000000..5268e08 --- /dev/null +++ b/.iolaus/evidence/dag-hardening/final/borrows/receipt.json @@ -0,0 +1,84 @@ +{ + "verdict": "PASS", + "command": "node script/qa-borrows.mjs /Users/Bryan/Programme/Project/AI/opencode-iolaus-wt/iolaus-dag-hardening/.iolaus/evidence/dag-hardening/final/borrows", + "version": "opencode v2.3.0", + "results": [ + { + "name": "a node whose model fails (provider error or empty reply) moves to the lane's next configured model; a pinned model does not", + "verdict": "PASS" + }, + { + "name": "a deep-low node ending with ESCALATE: deep-high is rerun on deep-high with its findings", + "verdict": "PASS" + }, + { + "name": "team: members build in their own worktrees, the lead integrates on a branch, the user's tree is untouched", + "verdict": "PASS" + }, + { + "name": "a run directory outside the project's repository is refused at create", + "verdict": "PASS" + }, + { + "name": "/start-work rejects an unknown option", + "verdict": "PASS" + }, + { + "name": "/start-work --make-pr works the tickets in a new worktree and opens the PR there after the accept gate", + "verdict": "PASS" + }, + { + "name": "the orchestrator's requests carry its role and paused run as session context", + "verdict": "PASS" + }, + { + "name": "compaction keeps the session context in the summary request", + "verdict": "PASS" + }, + { + "name": "a fork does not inherit the parent's session state", + "verdict": "PASS" + }, + { + "name": "approving the gate runs the PR node in the worktree", + "verdict": "PASS" + }, + { + "name": "host state isolation", + "verdict": "PASS" + }, + { + "name": "cleanup", + "verdict": "PASS" + }, + { + "name": "mock protocol", + "verdict": "PASS" + } + ], + "requestCount": 35, + "before": { + "files": { + "/Users/Bryan/.config/opencode/opencode.json": "dab6d067dab697457eb5184925513f705c0f738d6118aa4e5e62a86263387438", + "/Users/Bryan/.config/opencode/opencode.jsonc": "absent", + "/Users/Bryan/.iolaus/iolaus.json": "22f918dd85505c16c47744bb815c2cf73c84b589c356c6804ffdb6205cf9801a" + }, + "sandboxSessions": { + "session": "0", + "session_v2": "0" + } + }, + "after": { + "files": { + "/Users/Bryan/.config/opencode/opencode.json": "dab6d067dab697457eb5184925513f705c0f738d6118aa4e5e62a86263387438", + "/Users/Bryan/.config/opencode/opencode.jsonc": "absent", + "/Users/Bryan/.iolaus/iolaus.json": "22f918dd85505c16c47744bb815c2cf73c84b589c356c6804ffdb6205cf9801a" + }, + "sandboxSessions": { + "session": "0", + "session_v2": "0" + } + }, + "sandboxRemoved": true, + "omitted": "No user credentials or inherited environment dumps. Local mock only." +} \ No newline at end of file diff --git a/.iolaus/evidence/dag-hardening/final/dag-recover/receipt.json b/.iolaus/evidence/dag-hardening/final/dag-recover/receipt.json new file mode 100644 index 0000000..10c5816 --- /dev/null +++ b/.iolaus/evidence/dag-hardening/final/dag-recover/receipt.json @@ -0,0 +1,67 @@ +{ + "verdict": "PASS", + "binary": "/opt/homebrew/bin/opencode", + "version": "opencode v2.3.0", + "packageRoot": "/Users/Bryan/Programme/Project/AI/opencode-iolaus-wt/iolaus-dag-hardening", + "checks": [ + { + "name": "plugin reloaded mid-run", + "verdict": "PASS", + "loads": 2 + }, + { + "name": "running node reattached and run completed", + "verdict": "PASS" + }, + { + "name": "cancel keybind declines and confirms", + "verdict": "PASS" + }, + { + "name": "observed subagent node reattached after reload", + "verdict": "PASS" + } + ], + "screens": [ + "01-dialog-running", + "02-confirm-shown", + "03-confirm-declined", + "04-confirm-again", + "05-after-confirm" + ], + "requestCount": 14, + "realBefore": { + "config": "dab6d067dab697457eb5184925513f705c0f738d6118aa4e5e62a86263387438", + "database": "7ba6715890120ae41cd93137db5ab82da91386eca3fb1b1c9d3a9a3b70362e0f" + }, + "realAfter": { + "config": "dab6d067dab697457eb5184925513f705c0f738d6118aa4e5e62a86263387438", + "database": "7ba6715890120ae41cd93137db5ab82da91386eca3fb1b1c9d3a9a3b70362e0f" + }, + "hostConfigUnchanged": true, + "realDatabaseDigestChanged": false, + "isolation": { + "databasePaths": [ + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-recover-qa-p8BCqd/data/opencode/opencode.db", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-recover-qa-p8BCqd/data/opencode/opencode.db-shm", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-recover-qa-p8BCqd/data/opencode/opencode.db-wal", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-recover-qa-p8BCqd/home/.iolaus/iolaus.db", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-recover-qa-p8BCqd/home/.iolaus/iolaus.db-shm", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-recover-qa-p8BCqd/home/.iolaus/iolaus.db-wal" + ], + "databasePathsAtEnd": [ + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-recover-qa-p8BCqd/data/opencode/opencode.db", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-recover-qa-p8BCqd/data/opencode/opencode.db-shm", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-recover-qa-p8BCqd/data/opencode/opencode.db-wal", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-recover-qa-p8BCqd/home/.iolaus/iolaus.db", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-recover-qa-p8BCqd/home/.iolaus/iolaus.db-shm", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-recover-qa-p8BCqd/home/.iolaus/iolaus.db-wal" + ] + }, + "cleanup": { + "sandboxRemoved": true, + "mockClosed": true, + "tmuxStopped": true + }, + "omitted": "No provider credentials, auth files or inherited secret-bearing environment values were recorded." +} diff --git a/.iolaus/evidence/dag-hardening/final/flow-session-fixes/receipt.json b/.iolaus/evidence/dag-hardening/final/flow-session-fixes/receipt.json new file mode 100644 index 0000000..2026555 --- /dev/null +++ b/.iolaus/evidence/dag-hardening/final/flow-session-fixes/receipt.json @@ -0,0 +1,65 @@ +{ + "verdict": "PASS", + "version": "opencode v2.3.0", + "checks": [ + "Flow continuation refused before any observed node creation", + "Native followup succeeded and reopened only its existing observed node; repeated Flow misuse left it untouched", + "Failed attempt A ses_e25e3f039ffeqZ2jihLeOLH94z refused after explicit retry B ses_e25e3edd0ffeYxhf6wevoH0c7Q, with no observed-state changes and no unverified ownership claim", + "on-Native-Enter navigated exact session ses_e25e3f85affcAxW1IeqyugmJoH", + "on-Native-o navigated exact session ses_e25e3f85affcAxW1IeqyugmJoH", + "on-Scheduled-Enter navigated exact session ses_e25e3fd94ffeLxthcUhJHW8pn7", + "on-Scheduled-o navigated exact session ses_e25e3fd94ffeLxthcUhJHW8pn7", + "on-Unavailable QA explains unavailable session and stays in details", + "on-Judge QA explains unavailable session and stays in details", + "on-Future QA explains unavailable session and stays in details", + "on-Running-native-Enter navigated exact active child ses_e25e38fceffdsVvvWtssPTyh5Y while its node remained running", + "on-Running-native-o navigated exact active child ses_e25e38fceffdsVvvWtssPTyh5Y while its node remained running", + "off-Native-Enter navigated exact session ses_e25e3f85affcAxW1IeqyugmJoH", + "off-Native-o navigated exact session ses_e25e3f85affcAxW1IeqyugmJoH", + "off-Scheduled-Enter navigated exact session ses_e25e3fd94ffeLxthcUhJHW8pn7", + "off-Scheduled-o navigated exact session ses_e25e3fd94ffeLxthcUhJHW8pn7", + "off-Unavailable QA explains unavailable session and stays in details", + "off-Judge QA explains unavailable session and stays in details", + "off-Future QA explains unavailable session and stays in details", + "off-Running-native-Enter navigated exact active child ses_e25e30fe5ffd5hoGX0zuDXplmM while its node remained running", + "off-Running-native-o navigated exact active child ses_e25e30fe5ffd5hoGX0zuDXplmM while its node remained running" + ], + "owner": "ses_e25e3fde8ffey3xTRcoJfdo8i9", + "native": "ses_e25e3f85affcAxW1IeqyugmJoH", + "scheduled": "ses_e25e3fd94ffeLxthcUhJHW8pn7", + "isolation": [ + { + "mode": "on", + "pids": [ + 1126, + 1152 + ], + "databasePaths": [ + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-session-fixes-Fr575o/data/opencode/opencode.db-shm", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-session-fixes-Fr575o/home/.iolaus/iolaus.db-shm", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-session-fixes-Fr575o/data/opencode/opencode.db", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-session-fixes-Fr575o/data/opencode/opencode.db-wal", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-session-fixes-Fr575o/home/.iolaus/iolaus.db", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-session-fixes-Fr575o/home/.iolaus/iolaus.db-wal" + ] + }, + { + "mode": "off", + "pids": [ + 4749, + 4774 + ], + "databasePaths": [ + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-session-fixes-Fr575o/data/opencode/opencode.db-shm", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-session-fixes-Fr575o/home/.iolaus/iolaus.db-shm", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-session-fixes-Fr575o/data/opencode/opencode.db", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-session-fixes-Fr575o/data/opencode/opencode.db-wal", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-session-fixes-Fr575o/home/.iolaus/iolaus.db", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-session-fixes-Fr575o/home/.iolaus/iolaus.db-wal" + ] + } + ], + "hostConfigUnchanged": true, + "remainingSandboxProcesses": "", + "sandboxRemoved": true +} \ No newline at end of file diff --git a/.iolaus/evidence/dag-hardening/final/flow-steering/receipt.json b/.iolaus/evidence/dag-hardening/final/flow-steering/receipt.json new file mode 100644 index 0000000..b614d85 --- /dev/null +++ b/.iolaus/evidence/dag-hardening/final/flow-steering/receipt.json @@ -0,0 +1,407 @@ +{ + "verdict": "PASS", + "cleanupErrors": [], + "command": "node script/qa-flow-steering.mjs /Users/Bryan/Programme/Project/AI/opencode-iolaus-wt/iolaus-dag-hardening/.iolaus/evidence/dag-hardening/final/flow-steering", + "version": "opencode v2.3.0", + "sdk": "2.3.0", + "checks": [ + { + "name": "owner turn ends, new turn is interactive, interruption leaves child running", + "verdict": "PASS" + }, + { + "name": "request id cannot change text", + "verdict": "PASS", + "receipt": { + "error": "request_id already identifies a different steering request" + }, + "supplementalHostMessages": 1 + }, + { + "name": "same agent/model, one supplement, stale idle/result fenced from downstream", + "verdict": "PASS" + }, + { + "name": "terminal notice present in inbox without an owner provider turn", + "verdict": "PASS" + }, + { + "name": "settled target", + "verdict": "PASS", + "receipt": { + "error": "Steering requires an active flow; this flow is completed" + }, + "supplementalHostMessages": 1 + }, + { + "name": "gate/terminal notices queue without owner wake, reload dedupes, gate stays human-controlled", + "verdict": "PASS", + "noticeIDs": [ + "msg_75a470929ee7487b8ea83cbf1380738d" + ] + }, + { + "name": "gate target", + "verdict": "PASS", + "receipt": { + "error": "Steering requires a session-backed agent node, not a gate or judge" + }, + "supplementalHostMessages": 1 + }, + { + "name": "pending initial target", + "verdict": "PASS", + "receipt": { + "error": "Steering requires an active running node; pending is pending" + }, + "supplementalHostMessages": 1 + }, + { + "name": "gate rejection blocks the transitive tail and settles the flow", + "verdict": "PASS" + }, + { + "name": "foreign owner", + "verdict": "PASS", + "receipt": { + "error": "Iolaus DAG run belongs to another session" + }, + "supplementalHostMessages": 1 + }, + { + "name": "sibling child cannot steer foreign flow", + "verdict": "PASS", + "receipt": { + "error": "Iolaus DAG run belongs to another session" + }, + "supplementalHostMessages": 1 + }, + { + "name": "planning owner", + "verdict": "PASS", + "receipt": { + "error": { + "type": "tool.execution", + "message": "[iolaus planner] Planning sessions cannot steer live executions; steering is delegation, not a read-only operation." + }, + "content": [] + }, + "supplementalHostMessages": 1 + }, + { + "name": "inherited planning role survives switch to worker", + "verdict": "PASS", + "receipt": { + "error": { + "type": "tool.execution", + "message": "[iolaus planning] Planning sessions cannot steer live executions; steering is delegation, not a read-only operation." + }, + "content": [] + }, + "supplementalHostMessages": 1 + }, + { + "name": "observed native target", + "verdict": "PASS", + "receipt": { + "error": "Steering observed native subagent runs is not supported" + }, + "supplementalHostMessages": 1 + }, + { + "name": "judge target", + "verdict": "PASS", + "receipt": { + "error": "Steering requires a session-backed agent node, not a gate or judge" + }, + "supplementalHostMessages": 1 + }, + { + "name": "authorization refusals precede supplemental host/provider admission", + "verdict": "PASS" + }, + { + "name": "lost Flow acknowledgement reconciles real host id after reload without replay", + "verdict": "PASS", + "faultInjection": "sandbox-only steering receipt reset to reserved", + "messageID": "msg_4eb7d7ebd3ad4503b9e7435f21db6bcd" + }, + { + "name": "steered execution cannot retry", + "verdict": "PASS", + "receipt": { + "error": "Cannot retry a steered execution: reconcile its delivery or create a new flow with the complete task" + }, + "supplementalHostMessages": 3 + }, + { + "name": "steered execution cannot resume", + "verdict": "PASS", + "receipt": { + "error": "Cannot retry a steered execution: reconcile its delivery or create a new flow with the complete task" + }, + "supplementalHostMessages": 3 + }, + { + "name": "cancel/admission race and reload cannot publish late result or retry supplement", + "verdict": "PASS" + }, + { + "name": "Atlas-containing flow", + "verdict": "PASS", + "receipt": { + "error": "Steering Atlas or authorized-plan flows is not supported" + }, + "supplementalHostMessages": 3 + }, + { + "name": "authorized-plan owner", + "verdict": "PASS", + "receipt": { + "error": { + "type": "tool.execution", + "message": "[iolaus atlas-orchestrator] This Atlas session orchestrates a /start-work run: each ticket is implemented in its own fresh Atlas session. Operate the background run with iolaus_flow (snapshot, node, retry; optional blocking wait; approve or reject only on the user's word) instead of changing files or steering tickets here." + }, + "content": [] + }, + "supplementalHostMessages": 3 + }, + { + "name": "authorized plan survives owner agent switch", + "verdict": "PASS", + "receipt": { + "error": "Steering Atlas or authorized-plan flows is not supported" + }, + "supplementalHostMessages": 3 + }, + { + "name": "unsteered retry allocates a fresh child and execution token", + "verdict": "PASS", + "before": { + "attempt": 1, + "identity": { + "agent": "visual-engineering", + "model": "openai/gpt-5.5", + "token": "c5dfd1c7-166a-49f3-a531-ca6da74c843d" + }, + "nodeID": "implement", + "sessionID": "ses_e25e50c1affe7OBeiRWs509yg3" + }, + "after": { + "attempt": 2, + "identity": { + "agent": "visual-engineering", + "model": "openai/gpt-5.5", + "token": "c98a6021-a249-43cd-ac3c-27d381e13fe6" + }, + "nodeID": "implement", + "sessionID": "ses_e25e50b76ffeEvTB7EyS0r0661" + } + }, + { + "name": "lost notification acknowledgement reconciles stable host id and never approves gate", + "verdict": "PASS", + "messageID": "msg_044a7d648e704b4a97086145b05343e5", + "faultInjection": "sandbox-only notice state reset to reserved" + }, + { + "name": "direct-child API typing does not change identity; screenshot trigger not reproduced", + "verdict": "PASS" + }, + { + "name": "explicit child agent drift fails closed before supplemental admission and is not silently repaired", + "verdict": "PASS", + "receipt": { + "error": "Execution identity drift for implement; expected visual-engineering on openai/gpt-5.5, got sisyphus on {\"id\":\"gpt-5.5\",\"providerID\":\"openai\",\"variant\":\"default\"} (execution token matches). The session was not changed." + } + }, + { + "name": "running child before initial host admission", + "verdict": "PASS", + "receipt": { + "error": "Steering is unavailable before initial prompt admission or for legacy unpinned executions" + }, + "supplementalHostMessages": 3 + }, + { + "name": "pre-initial refusal does not enter host context", + "verdict": "PASS", + "sessionID": "ses_e25e5084effeePMaX7d6qQb8dJ", + "faultInjection": "pause before initial prompt on sandbox plugin copy" + }, + { + "name": "starting execution", + "verdict": "PASS", + "receipt": { + "error": "Steering requires an active running node; starting-pause is starting" + }, + "supplementalHostMessages": 3 + }, + { + "name": "cancel/retry fences late-created attempt before prompting", + "verdict": "PASS", + "lateID": "ses_e25e50756ffe6niKb5ejIf5L7e", + "faultInjection": "pause after native child creation but before runner ref publication" + }, + { + "name": "accepted supplement while old result captured at idle fences downstream", + "verdict": "PASS", + "faultInjection": "pause after real host context capture before returning old result" + }, + { + "name": "concurrent RPC cancellation serializes behind owner-mediated host admission", + "verdict": "PASS", + "receipt": { + "runID": "3c96a0ca-419a-4769-875b-bae11b087772", + "nodeID": "cancel-pause", + "requestID": "concurrent-request", + "text": "QA_SUPPLEMENT Fontsource", + "execution": { + "attempt": 1, + "identity": { + "agent": "visual-engineering", + "model": "openai/gpt-5.5", + "token": "3645aff5-bd1a-46dc-8d95-95f9b9773b14" + }, + "nodeID": "cancel-pause", + "sessionID": "ses_e25e504b8ffechNLslJOHiGNp5" + }, + "generation": 1, + "revision": 1, + "messageID": "msg_9e6b9a0be5f04e5f8c68087623277efe", + "state": "admitted", + "createdAt": 1794660563841, + "receipt": { + "messageID": "msg_9e6b9a0be5f04e5f8c68087623277efe" + } + }, + "faultInjection": "pause immediately before native synthetic admission on sandbox plugin copy" + }, + { + "name": "owner-before: owner tool interruption preserves admission and result tracking in the same controller", + "verdict": "PASS", + "runID": "8299d688-7266-4a70-aac6-11b257924d3a", + "request": { + "createdAt": 1794660564188, + "execution": { + "attempt": 1, + "identity": { + "agent": "visual-engineering", + "model": "openai/gpt-5.5", + "token": "54172d53-ca62-4619-b533-6d6b7845b7d0" + }, + "nodeID": "owner-before", + "sessionID": "ses_e25e50374ffeq4yp0e1rBSzhzf" + }, + "generation": 1, + "messageID": "msg_3e0153087dc2444484f03a6b8a6d0ac2", + "nodeID": "owner-before", + "receipt": { + "messageID": "msg_3e0153087dc2444484f03a6b8a6d0ac2" + }, + "requestID": "owner-before", + "revision": 1, + "runID": "8299d688-7266-4a70-aac6-11b257924d3a", + "state": "delivered", + "text": "QA_SUPPLEMENT Fontsource" + }, + "faultInjection": "pause before native synthetic admission" + }, + { + "name": "owner-after: owner tool interruption preserves admission and result tracking in the same controller", + "verdict": "PASS", + "runID": "6c34f744-0ff6-4513-85df-7f4b84a3e283", + "request": { + "createdAt": 1794660564521, + "execution": { + "attempt": 1, + "identity": { + "agent": "visual-engineering", + "model": "openai/gpt-5.5", + "token": "b878eecc-837f-43c5-925a-38eba7b7388f" + }, + "nodeID": "owner-after", + "sessionID": "ses_e25e50212ffe4FortR7HGyQKfc" + }, + "generation": 1, + "messageID": "msg_2a69b958099b4eb08f69df5d8250b203", + "nodeID": "owner-after", + "receipt": { + "messageID": "msg_2a69b958099b4eb08f69df5d8250b203" + }, + "requestID": "owner-after", + "revision": 1, + "runID": "6c34f744-0ff6-4513-85df-7f4b84a3e283", + "state": "delivered", + "text": "QA_SUPPLEMENT Fontsource" + }, + "faultInjection": "pause after native synthetic admission before returning receipt" + }, + { + "name": "isolated live host only opened sandbox databases", + "verdict": "PASS", + "databasePaths": [ + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-steering-qa-IQO5bT/data/opencode/opencode.db-shm", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-steering-qa-IQO5bT/home/.iolaus/iolaus.db-shm", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-steering-qa-IQO5bT/data/opencode/opencode.db", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-steering-qa-IQO5bT/data/opencode/opencode.db-wal", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-steering-qa-IQO5bT/data/opencode/opencode.db-shm", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-steering-qa-IQO5bT/home/.iolaus/iolaus.db", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-steering-qa-IQO5bT/home/.iolaus/iolaus.db-wal", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-steering-qa-IQO5bT/home/.iolaus/iolaus.db-shm", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-steering-qa-IQO5bT/home/.iolaus/iolaus.db", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-steering-qa-IQO5bT/home/.iolaus/iolaus.db-wal" + ] + } + ], + "errors": [], + "isolation": { + "env": { + "PATH": "/opt/zerobrew/bin:/Users/Bryan/.sdkman/candidates/maven/current/bin:/Users/Bryan/.sdkman/candidates/java/current/bin:/Users/Bryan/.sdkman/candidates/gradle/current/bin:/Users/Bryan/.local/state/fnm_multishells/59234_1794562343161/bin:/Users/Bryan/Library/pnpm/bin:/opt/homebrew/share/google-cloud-sdk/bin:/Users/Bryan/.local/bin:/Users/Bryan/.bun/bin:/usr/local/bin:/System/Cryptexes/App/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/local/bin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/bin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/appleinternal/bin:/pkg/env/global/bin:/Library/Apple/usr/bin:/usr/local/share/dotnet:~/.dotnet/tools:/opt/homebrew/bin:/opt/zerobrew/bin:/opt/zerobrew/prefix/bin:/Users/Bryan/.cargo/bin:/Users/Bryan/Library/Application Support/JetBrains/Toolbox/scripts:/Applications/Obsidian.app/Contents/MacOS:/Users/Bryan/.orbstack/bin", + "HOME": "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-steering-qa-IQO5bT/home", + "USERPROFILE": "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-steering-qa-IQO5bT/home", + "TMPDIR": "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-steering-qa-IQO5bT", + "IOLAUS_HOME": "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-steering-qa-IQO5bT/home/.iolaus", + "IOLAUS_TRACE": "/Users/Bryan/Programme/Project/AI/opencode-iolaus-wt/iolaus-dag-hardening/.iolaus/evidence/dag-hardening/final/flow-steering/trace.ndjson", + "XDG_CONFIG_HOME": "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-steering-qa-IQO5bT/config", + "XDG_DATA_HOME": "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-steering-qa-IQO5bT/data", + "XDG_CACHE_HOME": "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-steering-qa-IQO5bT/cache", + "XDG_STATE_HOME": "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-steering-qa-IQO5bT/state", + "OPENCODE_TEST_HOME": "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-steering-qa-IQO5bT/home", + "OPENCODE_DISABLE_AUTOUPDATE": "1", + "OPENCODE_DISABLE_MODELS_FETCH": "1" + }, + "databasePaths": [ + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-steering-qa-IQO5bT/data/opencode/opencode.db-shm", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-steering-qa-IQO5bT/home/.iolaus/iolaus.db-shm", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-steering-qa-IQO5bT/data/opencode/opencode.db", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-steering-qa-IQO5bT/data/opencode/opencode.db-wal", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-steering-qa-IQO5bT/data/opencode/opencode.db-shm", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-steering-qa-IQO5bT/home/.iolaus/iolaus.db", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-steering-qa-IQO5bT/home/.iolaus/iolaus.db-wal", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-steering-qa-IQO5bT/home/.iolaus/iolaus.db-shm", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-steering-qa-IQO5bT/home/.iolaus/iolaus.db", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-steering-qa-IQO5bT/home/.iolaus/iolaus.db-wal" + ], + "before": { + "/Users/Bryan/.iolaus/iolaus.json": "22f918dd85505c16c47744bb815c2cf73c84b589c356c6804ffdb6205cf9801a", + "/Users/Bryan/.config/opencode/opencode.json": "dab6d067dab697457eb5184925513f705c0f738d6118aa4e5e62a86263387438", + "/Users/Bryan/.config/opencode/opencode.jsonc": "absent" + }, + "after": { + "/Users/Bryan/.iolaus/iolaus.json": "22f918dd85505c16c47744bb815c2cf73c84b589c356c6804ffdb6205cf9801a", + "/Users/Bryan/.config/opencode/opencode.json": "dab6d067dab697457eb5184925513f705c0f738d6118aa4e5e62a86263387438", + "/Users/Bryan/.config/opencode/opencode.jsonc": "absent" + } + }, + "cleanup": { + "sandboxRemoved": true, + "processGone": true, + "mockClosed": true + }, + "limitations": [ + "No screenshot/direct-child TUI typing reproduced; API sessions only.", + "Initial admission, late creation, idle capture, and owner interruption races use deterministic pauses in the isolated plugin copy; other scenarios run the unmodified build.", + "Lost-ack simulation resets only isolated Flow receipts after actual host admission; it is not a network-loss experiment." + ] +} \ No newline at end of file diff --git a/.iolaus/evidence/dag-hardening/final/live/receipt.json b/.iolaus/evidence/dag-hardening/final/live/receipt.json new file mode 100644 index 0000000..e29e76e --- /dev/null +++ b/.iolaus/evidence/dag-hardening/final/live/receipt.json @@ -0,0 +1,630 @@ +{ + "binary": "/opt/homebrew/bin/opencode", + "hostVersion": "2.3.0", + "sdkPin": "2.3.0", + "results": [ + { + "name": "host version", + "verdict": "PASS" + }, + { + "name": "run help", + "verdict": "PASS" + }, + { + "name": "native: live session", + "verdict": "PASS" + }, + { + "name": "agent: live session", + "verdict": "PASS" + }, + { + "name": "disabled: live session", + "verdict": "PASS" + }, + { + "name": "mode: live session", + "verdict": "PASS" + }, + { + "name": "dag: live session", + "verdict": "PASS" + }, + { + "name": "fanin: live session", + "verdict": "PASS" + }, + { + "name": "fanin-serial: live session", + "verdict": "PASS" + }, + { + "name": "route: live session", + "verdict": "PASS" + }, + { + "name": "template: live session", + "verdict": "PASS" + }, + { + "name": "template-unavailable: live session", + "verdict": "PASS" + }, + { + "name": "ultrawork-dag: live session", + "verdict": "PASS" + }, + { + "name": "lanes: live session", + "verdict": "PASS" + }, + { + "name": "momus: live session", + "verdict": "PASS" + }, + { + "name": "astgrep-explore: live session", + "verdict": "PASS" + }, + { + "name": "astgrep-rewrite: live session", + "verdict": "PASS" + }, + { + "name": "astgrep-deny: live session", + "verdict": "PASS" + }, + { + "name": "mcps-librarian: live session", + "verdict": "PASS" + }, + { + "name": "mcps-off: live session", + "verdict": "PASS" + }, + { + "name": "gh-librarian: live session", + "verdict": "PASS" + }, + { + "name": "gh-explore: live session", + "verdict": "PASS" + }, + { + "name": "gh-off: live session", + "verdict": "PASS" + }, + { + "name": "explore-shell: live session", + "verdict": "PASS" + }, + { + "name": "looker-read-only: live session", + "verdict": "PASS" + }, + { + "name": "verify-edit: live session", + "verdict": "PASS" + }, + { + "name": "verify-off: live session", + "verdict": "PASS" + }, + { + "name": "host state isolation", + "verdict": "PASS" + }, + { + "name": "cleanup", + "verdict": "PASS" + }, + { + "name": "mock protocol", + "verdict": "PASS" + } + ], + "before": { + "files": { + "/Users/Bryan/.config/opencode/opencode.json": "dab6d067dab697457eb5184925513f705c0f738d6118aa4e5e62a86263387438", + "/Users/Bryan/.config/opencode/opencode.jsonc": "absent", + "/Users/Bryan/.local/share/opencode/auth.json": "26ad853c32af5fd92442c34552efea22df03177d9e4d2b8454e5c3b8274e8bc2", + "/Users/Bryan/.omo/opencode2.json": "f4261a0547834d4462b630684aaa1a2c9a0b2683c219229e411b42fc0138a51a", + "/Users/Bryan/.omo/omo.jsonc": "032263b264491d356e21bcd78a9db6deb19d58babc105102716b918f2a178e66" + }, + "sessions": { + "session": "2725", + "session_v2": "3175" + } + }, + "after": { + "files": { + "/Users/Bryan/.config/opencode/opencode.json": "dab6d067dab697457eb5184925513f705c0f738d6118aa4e5e62a86263387438", + "/Users/Bryan/.config/opencode/opencode.jsonc": "absent", + "/Users/Bryan/.local/share/opencode/auth.json": "26ad853c32af5fd92442c34552efea22df03177d9e4d2b8454e5c3b8274e8bc2", + "/Users/Bryan/.omo/opencode2.json": "f4261a0547834d4462b630684aaa1a2c9a0b2683c219229e411b42fc0138a51a", + "/Users/Bryan/.omo/omo.jsonc": "032263b264491d356e21bcd78a9db6deb19d58babc105102716b918f2a178e66" + }, + "sessions": { + "session": "2725", + "session_v2": "3175" + } + }, + "processes": [ + { + "name": "version", + "args": [ + "--version" + ], + "pid": 7708, + "code": 0, + "signal": null, + "closed": true + }, + { + "name": "help", + "args": [ + "run", + "--help" + ], + "pid": 7709, + "code": 0, + "signal": null, + "closed": true + }, + { + "name": "native", + "args": [ + "run", + "--standalone", + "--auto", + "--print-logs", + "--agent", + "build", + "--model", + "openai/gpt-5.5", + "Read fixture.txt and report the result." + ], + "pid": 7710, + "code": 0, + "signal": null, + "closed": true + }, + { + "name": "agent", + "args": [ + "run", + "--standalone", + "--auto", + "--print-logs", + "--agent", + "sisyphus", + "--model", + "openai/gpt-5.5", + "Read fixture.txt and report the result." + ], + "pid": 7715, + "code": 0, + "signal": null, + "closed": true + }, + { + "name": "disabled", + "args": [ + "run", + "--standalone", + "--auto", + "--print-logs", + "--agent", + "build", + "--model", + "openai/gpt-5.5", + "Read fixture.txt and report the result." + ], + "pid": 7721, + "code": 0, + "signal": null, + "closed": true + }, + { + "name": "mode", + "args": [ + "run", + "--standalone", + "--auto", + "--print-logs", + "--agent", + "build", + "--model", + "openai/gpt-5.5", + "/ultrawork Read fixture.txt and report the result." + ], + "pid": 7723, + "code": 0, + "signal": null, + "closed": true + }, + { + "name": "dag", + "args": [ + "run", + "--standalone", + "--auto", + "--print-logs", + "--agent", + "build", + "--model", + "openai/gpt-5.5", + "Run an Iolaus DAG and report the completed node result." + ], + "pid": 7735, + "code": 0, + "signal": null, + "closed": true + }, + { + "name": "fanin", + "args": [ + "run", + "--standalone", + "--auto", + "--print-logs", + "--agent", + "build", + "--model", + "openai/gpt-5.5", + "Run an Iolaus DAG and report the completed node result." + ], + "pid": 7740, + "code": 0, + "signal": null, + "closed": true + }, + { + "name": "fanin-serial", + "args": [ + "run", + "--standalone", + "--auto", + "--print-logs", + "--agent", + "build", + "--model", + "openai/gpt-5.5", + "Run an Iolaus DAG and report the completed node result." + ], + "pid": 7746, + "code": 0, + "signal": null, + "closed": true + }, + { + "name": "route", + "args": [ + "run", + "--standalone", + "--auto", + "--print-logs", + "--agent", + "build", + "--model", + "openai/gpt-5.5", + "Run an Iolaus DAG and report the completed node result." + ], + "pid": 7751, + "code": 0, + "signal": null, + "closed": true + }, + { + "name": "template", + "args": [ + "run", + "--standalone", + "--auto", + "--print-logs", + "--agent", + "build", + "--model", + "openai/gpt-5.5", + "Run an Iolaus DAG and report the completed node result." + ], + "pid": 7757, + "code": 0, + "signal": null, + "closed": true + }, + { + "name": "template-unavailable", + "args": [ + "run", + "--standalone", + "--auto", + "--print-logs", + "--agent", + "build", + "--model", + "openai/gpt-5.5", + "Run an Iolaus DAG and report the completed node result." + ], + "pid": 7781, + "code": 0, + "signal": null, + "closed": true + }, + { + "name": "ultrawork-dag", + "args": [ + "run", + "--standalone", + "--auto", + "--print-logs", + "--agent", + "build", + "--model", + "openai/gpt-5.5", + "/ultrawork IOLAUS_ULTRAWORK_TASK" + ], + "pid": 7786, + "code": 0, + "signal": null, + "closed": true + }, + { + "name": "lanes", + "args": [ + "run", + "--standalone", + "--auto", + "--print-logs", + "--agent", + "build", + "--model", + "openai/gpt-5.5", + "Run an Iolaus DAG and report the completed node result." + ], + "pid": 7821, + "code": 0, + "signal": null, + "closed": true + }, + { + "name": "momus", + "args": [ + "run", + "--standalone", + "--auto", + "--print-logs", + "--agent", + "build", + "--model", + "openai/gpt-5.5", + "Run an Iolaus DAG and report the completed node result." + ], + "pid": 7830, + "code": 0, + "signal": null, + "closed": true + }, + { + "name": "astgrep-explore", + "args": [ + "run", + "--standalone", + "--auto", + "--print-logs", + "--agent", + "explore", + "--model", + "openai/gpt-5.5", + "Return IOLAUS_QA_DONE." + ], + "pid": 7835, + "code": 0, + "signal": null, + "closed": true + }, + { + "name": "astgrep-rewrite", + "args": [ + "run", + "--standalone", + "--auto", + "--print-logs", + "--agent", + "build", + "--model", + "openai/gpt-5.5", + "Return IOLAUS_QA_DONE." + ], + "pid": 7841, + "code": 0, + "signal": null, + "closed": true + }, + { + "name": "astgrep-deny", + "args": [ + "run", + "--standalone", + "--auto", + "--print-logs", + "--agent", + "prometheus", + "--model", + "openai/gpt-5.5", + "Return IOLAUS_QA_DONE." + ], + "pid": 7848, + "code": 0, + "signal": null, + "closed": true + }, + { + "name": "mcps-librarian", + "args": [ + "run", + "--standalone", + "--auto", + "--print-logs", + "--agent", + "librarian", + "--model", + "openai/gpt-5.5", + "Return IOLAUS_QA_DONE." + ], + "pid": 7861, + "code": 0, + "signal": null, + "closed": true + }, + { + "name": "mcps-off", + "args": [ + "run", + "--standalone", + "--auto", + "--print-logs", + "--agent", + "librarian", + "--model", + "openai/gpt-5.5", + "Return IOLAUS_QA_DONE." + ], + "pid": 7877, + "code": 0, + "signal": null, + "closed": true + }, + { + "name": "gh-librarian", + "args": [ + "run", + "--standalone", + "--auto", + "--print-logs", + "--agent", + "librarian", + "--model", + "openai/gpt-5.5", + "Return IOLAUS_QA_DONE." + ], + "pid": 7882, + "code": 0, + "signal": null, + "closed": true + }, + { + "name": "gh-explore", + "args": [ + "run", + "--standalone", + "--auto", + "--print-logs", + "--agent", + "explore", + "--model", + "openai/gpt-5.5", + "Return IOLAUS_QA_DONE." + ], + "pid": 7914, + "code": 0, + "signal": null, + "closed": true + }, + { + "name": "gh-off", + "args": [ + "run", + "--standalone", + "--auto", + "--print-logs", + "--agent", + "librarian", + "--model", + "openai/gpt-5.5", + "Return IOLAUS_QA_DONE." + ], + "pid": 7930, + "code": 0, + "signal": null, + "closed": true + }, + { + "name": "explore-shell", + "args": [ + "run", + "--standalone", + "--auto", + "--print-logs", + "--agent", + "explore", + "--model", + "openai/gpt-5.5", + "Return IOLAUS_QA_DONE." + ], + "pid": 7933, + "code": 0, + "signal": null, + "closed": true + }, + { + "name": "looker-read-only", + "args": [ + "run", + "--standalone", + "--auto", + "--print-logs", + "--agent", + "multimodal-looker", + "--model", + "openai/gpt-5.5", + "Read fixture.txt and report the result." + ], + "pid": 7942, + "code": 0, + "signal": null, + "closed": true + }, + { + "name": "verify-edit", + "args": [ + "run", + "--standalone", + "--auto", + "--print-logs", + "--agent", + "sisyphus", + "--model", + "openai/gpt-5.5", + "Return IOLAUS_QA_DONE." + ], + "pid": 7947, + "code": 0, + "signal": null, + "closed": true + }, + { + "name": "verify-off", + "args": [ + "run", + "--standalone", + "--auto", + "--print-logs", + "--agent", + "sisyphus", + "--model", + "openai/gpt-5.5", + "Return IOLAUS_QA_DONE." + ], + "pid": 7960, + "code": 0, + "signal": null, + "closed": true + } + ], + "sandboxRemoved": true, + "mockClosed": true, + "requestCount": 121, + "omitted": "No user credentials or inherited environment dumps. Local mock only." +} \ No newline at end of file diff --git a/.iolaus/evidence/dag-hardening/final/owner-rescue/receipt.json b/.iolaus/evidence/dag-hardening/final/owner-rescue/receipt.json new file mode 100644 index 0000000..4262f99 --- /dev/null +++ b/.iolaus/evidence/dag-hardening/final/owner-rescue/receipt.json @@ -0,0 +1,104 @@ +{ + "verdict": "PASS", + "version": "opencode v2.3.0", + "checks": [ + { + "name": "host version", + "verdict": "PASS", + "version": "opencode v2.3.0", + "binary": "/opt/homebrew/bin/opencode" + }, + { + "name": "fallback and owner rescue continue one child session after a real tool effect", + "verdict": "PASS", + "sessionID": "ses_e25e4fe00ffe1KAcLf3q0Xuydu", + "events": [ + "run.started", + "node.ready", + "node.started", + "node.fallback", + "node.ready", + "node.started", + "node.rescued", + "node.ready", + "node.started", + "node.completed", + "run.completed" + ], + "models": [ + "gpt-a", + "gpt-b", + "gpt-owner" + ], + "sessionModel": { + "id": "gpt-owner", + "providerID": "openai", + "variant": "default" + }, + "agent": "deep-low", + "progress": "STEP_A (once, not replayed)", + "historyInputs": [ + "user", + "model-switched", + "user", + "model-switched", + "user" + ], + "provenance": { + "agent": "deep-low", + "execution": { + "attempt": 3, + "identity": { + "agent": "deep-low", + "model": "openai/gpt-owner", + "token": "b5b61faa-6619-467b-b8c7-af4bf00200f8" + }, + "nodeID": "work", + "sessionID": "ses_e25e4fe00ffe1KAcLf3q0Xuydu" + }, + "model": "openai/gpt-owner", + "parentNodeIDs": [], + "rescue": { + "decisionID": "9e1d2dc9-7bdc-4e4f-b379-8b4be5726b97", + "from": "openai/gpt-b", + "model": "openai/gpt-owner" + } + } + }, + { + "name": "a steered node falls back in the same session with its supplement delivered once", + "verdict": "PASS", + "sessionID": "ses_e25e4fceeffezTqw26TrwM2A0u", + "events": [ + "run.started", + "node.ready", + "node.started", + "node.steering", + "node.fallback", + "node.ready", + "node.started", + "node.completed", + "run.completed" + ], + "historyInputs": [ + "user", + "synthetic", + "model-switched", + "user" + ], + "steering": [ + "delivered" + ] + } + ], + "errors": [], + "cleanup": { + "sandboxRemoved": true, + "hostUnchanged": true + }, + "command": "node script/qa-owner-rescue.mjs /Users/Bryan/Programme/Project/AI/opencode-iolaus-wt/iolaus-dag-hardening/.iolaus/evidence/dag-hardening/final/owner-rescue", + "limitations": [ + "Mock OpenAI-compatible provider; one provider family, so cross-provider history conversion is covered only by same-session-probe/run3.", + "API sessions only, no TUI." + ] +} \ No newline at end of file diff --git a/.iolaus/evidence/dag-hardening/final/roles/receipt.json b/.iolaus/evidence/dag-hardening/final/roles/receipt.json new file mode 100644 index 0000000..de2270e --- /dev/null +++ b/.iolaus/evidence/dag-hardening/final/roles/receipt.json @@ -0,0 +1,224 @@ +{ + "verdict": "PASS", + "command": "node script/qa-roles.mjs /Users/Bryan/Programme/Project/AI/opencode-iolaus-wt/iolaus-dag-hardening/.iolaus/evidence/dag-hardening/final/roles", + "version": "opencode v2.3.0", + "results": [ + { + "name": "ultrawork from build switches the session to Sisyphus", + "verdict": "PASS" + }, + { + "name": "hyperplan switches to Prometheus; planner writes the plan, is refused code edits and implementing runs, and its consult is read-only", + "verdict": "PASS" + }, + { + "name": "Atlas without a plan is read-only", + "verdict": "PASS" + }, + { + "name": "a subagent call inside a scheduled DAG node joins the owner's observed run, labelled with the node", + "verdict": "PASS" + }, + { + "name": "cancelling a run stops the subagents its node left running", + "verdict": "PASS" + }, + { + "name": "native subagent calls appear as an observed DAG run: parallel, nested, a follow-up and a refused call", + "verdict": "PASS" + }, + { + "name": "other lanes may write plans", + "verdict": "PASS" + }, + { + "name": "start-work with an unknown plan starts nothing", + "verdict": "PASS" + }, + { + "name": "start-work switches to Atlas and runs each ticket in a fresh Atlas session, then both reviews and the accept gate", + "verdict": "PASS" + }, + { + "name": "/goal switches to Hephaestus, keeps the session's non-GPT model, and loops until update_goal complete", + "verdict": "PASS" + }, + { + "name": "the goal loop waits for a running subagent and continues after its report, counting the delegating turn's tool call", + "verdict": "PASS" + }, + { + "name": "/goal accepts the host's pause, resume and clear", + "verdict": "PASS" + }, + { + "name": "a goal that makes no progress pauses after three idle turns", + "verdict": "PASS" + }, + { + "name": "tier: allowed", + "verdict": "PASS" + }, + { + "name": "tier: nested", + "verdict": "PASS" + }, + { + "name": "tier: nested same-primary DAG worker completes", + "verdict": "PASS" + }, + { + "name": "tier: dag-lower", + "verdict": "PASS" + }, + { + "name": "tier: DAG lower worker cannot launch a primary", + "verdict": "PASS" + }, + { + "name": "tier: native-deny-hephaestus", + "verdict": "PASS" + }, + { + "name": "tier: dag-hephaestus", + "verdict": "PASS" + }, + { + "name": "tier: native-deny-prometheus", + "verdict": "PASS" + }, + { + "name": "tier: dag-prometheus", + "verdict": "PASS" + }, + { + "name": "tier: native-deny-atlas", + "verdict": "PASS" + }, + { + "name": "tier: dag-atlas", + "verdict": "PASS" + }, + { + "name": "tier: model", + "verdict": "PASS" + }, + { + "name": "tier: judge", + "verdict": "PASS" + }, + { + "name": "tier: executor", + "verdict": "PASS" + }, + { + "name": "tier: reviewer", + "verdict": "PASS" + }, + { + "name": "tier: member", + "verdict": "PASS" + }, + { + "name": "tier: dag-sisyphus", + "verdict": "PASS" + }, + { + "name": "tier: dag-hephaestus", + "verdict": "PASS" + }, + { + "name": "tier: lower", + "verdict": "PASS" + }, + { + "name": "tier: lower child cannot launch a primary", + "verdict": "PASS" + }, + { + "name": "tier: command", + "verdict": "PASS" + }, + { + "name": "tier: command-goal", + "verdict": "PASS" + }, + { + "name": "tier: child command cannot switch or start work", + "verdict": "PASS" + }, + { + "name": "tier: forge", + "verdict": "PASS" + }, + { + "name": "tier: forged ticket marker leaves Atlas read-only", + "verdict": "PASS" + }, + { + "name": "tier: native", + "verdict": "PASS" + }, + { + "name": "tier: real continuation rejects stored primary and supplied primary mismatch", + "verdict": "PASS" + }, + { + "name": "tier: native lower to general cannot launder a primary DAG", + "verdict": "PASS" + }, + { + "name": "tier: dag lower to general cannot launder a primary DAG", + "verdict": "PASS" + }, + { + "name": "tier: Prometheus hyperplan runs planning nodes", + "verdict": "PASS" + }, + { + "name": "tier: amendment cannot insert a forbidden primary", + "verdict": "PASS" + }, + { + "name": "host state isolation", + "verdict": "PASS" + }, + { + "name": "cleanup", + "verdict": "PASS" + }, + { + "name": "mock protocol", + "verdict": "PASS" + } + ], + "requestCount": 197, + "before": { + "files": { + "/Users/Bryan/.config/opencode/opencode.json": "dab6d067dab697457eb5184925513f705c0f738d6118aa4e5e62a86263387438", + "/Users/Bryan/.config/opencode/opencode.jsonc": "absent", + "/Users/Bryan/.local/share/opencode/auth.json": "26ad853c32af5fd92442c34552efea22df03177d9e4d2b8454e5c3b8274e8bc2" + }, + "sessions": { + "session": "2725", + "session_v2": "3175" + } + }, + "after": { + "files": { + "/Users/Bryan/.config/opencode/opencode.json": "dab6d067dab697457eb5184925513f705c0f738d6118aa4e5e62a86263387438", + "/Users/Bryan/.config/opencode/opencode.jsonc": "absent", + "/Users/Bryan/.local/share/opencode/auth.json": "26ad853c32af5fd92442c34552efea22df03177d9e4d2b8454e5c3b8274e8bc2" + }, + "sessions": { + "session": "2725", + "session_v2": "3175" + } + }, + "sandboxRemoved": true, + "serverExit": { + "code": 143, + "signal": null + }, + "mockClosed": true +} \ No newline at end of file diff --git a/.iolaus/evidence/dag-hardening/final/subagent-batches/receipt.json b/.iolaus/evidence/dag-hardening/final/subagent-batches/receipt.json new file mode 100644 index 0000000..5baa5eb --- /dev/null +++ b/.iolaus/evidence/dag-hardening/final/subagent-batches/receipt.json @@ -0,0 +1,77 @@ +{ + "verdict": "PASS", + "version": "opencode v2.3.0", + "checks": [ + "One real user request: 2 parallel + 10 sequential calls share one request batch; next request isolates old failure/count/time; stable 1..12 definition order", + "Native nesting inherits exact observed run and local parent edge", + "Mixed root/child/root TUI: chronological cards and j/j/k selection; no wave arrows or false sibling links; actual parent/child identities; Enter opens exact nested child", + "Two scheduled flows keep distinct observed batches, including nested descendants; scheduled definitions unchanged; no cross-group edges", + "Host restart/reload: later-request explicit native followup reopens original node, descendant inherits original batch, no new followup batch", + "Scheduled continuation guard still refuses before observation", + "Prompt admitted to queue during current execution does not steal its next sequential call; delivered queued user input creates a separate batch", + "Seeded isolated legacy unkeyed aggregate retained without reassignment or append", + "Real tool hooks expose current assistant in delivered context; persisted user IDs used instead of admission or assistant IDs", + "Real TUI labels historical aggregate and Calls/request details, renders 1..12 order; Enter still navigates exact direct child" + ], + "isolation": [ + { + "pids": [ + 98660, + 98684 + ], + "databasePaths": [ + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-batches-VJYlFT/data/opencode/opencode.db-shm", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-batches-VJYlFT/home/.iolaus/iolaus.db-shm", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-batches-VJYlFT/data/opencode/opencode.db", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-batches-VJYlFT/data/opencode/opencode.db-wal", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-batches-VJYlFT/home/.iolaus/iolaus.db", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-batches-VJYlFT/home/.iolaus/iolaus.db-wal" + ] + }, + { + "pids": [ + 99649, + 99673 + ], + "databasePaths": [ + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-batches-VJYlFT/data/opencode/opencode.db-shm", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-batches-VJYlFT/home/.iolaus/iolaus.db-shm", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-batches-VJYlFT/data/opencode/opencode.db", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-batches-VJYlFT/data/opencode/opencode.db-wal", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-batches-VJYlFT/home/.iolaus/iolaus.db", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-batches-VJYlFT/home/.iolaus/iolaus.db-wal" + ] + }, + { + "pids": [ + 116, + 141 + ], + "databasePaths": [ + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-batches-VJYlFT/data/opencode/opencode.db-shm", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-batches-VJYlFT/home/.iolaus/iolaus.db-shm", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-batches-VJYlFT/data/opencode/opencode.db", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-batches-VJYlFT/data/opencode/opencode.db-wal", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-batches-VJYlFT/home/.iolaus/iolaus.db", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-batches-VJYlFT/home/.iolaus/iolaus.db-wal" + ] + }, + { + "pids": [ + 526, + 557 + ], + "databasePaths": [ + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-batches-VJYlFT/data/opencode/opencode.db-shm", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-batches-VJYlFT/home/.iolaus/iolaus.db-shm", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-batches-VJYlFT/data/opencode/opencode.db", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-batches-VJYlFT/data/opencode/opencode.db-wal", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-batches-VJYlFT/home/.iolaus/iolaus.db", + "/private/var/folders/cy/qc1d9pgd1hq599hhhw_z2l2w0000gn/T/iolaus-batches-VJYlFT/home/.iolaus/iolaus.db-wal" + ] + } + ], + "hostConfigUnchanged": true, + "remainingSandboxProcesses": "", + "sandboxRemoved": true +} \ No newline at end of file diff --git a/script/qa-borrows.mjs b/script/qa-borrows.mjs index c2f8f3a..453ffe7 100644 --- a/script/qa-borrows.mjs +++ b/script/qa-borrows.mjs @@ -119,8 +119,7 @@ const mock = http.createServer(async (req, res) => { outputs: (body.input ?? []).filter((i) => i?.type === "function_call_output").map((i) => String(i.output).slice(0, 400)), // What the current instruction block says, and whether the host has told the model it no longer applies. state: stateBlock(instructions + JSON.stringify(body.input ?? [])), - removal: (body.input ?? []).some((item) => Array.isArray(item.content) && item.content.some((part) => - typeof part.text === "string" && part.text.includes('The context under "iolaus.state" no longer applies. Disregard it.'))) } + removal: JSON.stringify(body.input ?? []).replaceAll('\\"', '"').includes('The context under "iolaus.state" no longer applies. Disregard it.') } requests.push(record) appendFileSync(join(evidence, "requests.ndjson"), `${JSON.stringify(record)}\n`) assert.ok(requests.length < 300, "Unexpected model loop")