From f65f2667171201db43489e33467c17964f21bee1 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 4 Nov 2026 19:50:49 -0500 Subject: [PATCH 01/12] Finish interrupted chat deletions on every server Tombstone replay lived in createCliRemoteChats, so aiden serve --no-remote neither completed a committed deletion nor closed that chat to new turns. The daemon now closes tombstoned chats at construction and recovery runs at serve startup. A failure closes only those chats. Co-Authored-By: Claude Opus 5.5 --- docs/state-machines/serve-daemon.md | 15 +++++++ packages/cli/src/daemon-chats.ts | 20 ++++++++- packages/cli/src/remote-chats.ts | 9 +--- packages/cli/src/serve.ts | 2 + packages/cli/tests/daemon-turns.test.mjs | 53 +++++++++++++++++++++++- 5 files changed, 89 insertions(+), 10 deletions(-) diff --git a/docs/state-machines/serve-daemon.md b/docs/state-machines/serve-daemon.md index 8be2266122..82372abc1f 100644 --- a/docs/state-machines/serve-daemon.md +++ b/docs/state-machines/serve-daemon.md @@ -132,3 +132,18 @@ Owners: `remoteDaemonCommand` (`daemon-control.ts`) and the socket handler in `s **Defect fixed:** both ends parsed their whole buffer, so a frame followed by more bytes in the same chunk failed as bad JSON, while the same bytes in two chunks succeeded. Each end now reads only its first frame, and its ceiling applies to that frame alone. **Defect fixed:** when the chunk that crossed the 8 MiB ceiling also completed the frame, the client destroyed the socket and then parsed and returned the reply anyway, so the ceiling did not hold on the last chunk. + +## C14: interrupted chat deletion + +Owner: `recoverChatDeletions` in `daemon-chats.ts`, over the `daemon-chat-deletions.json` tombstones and `ChatDeletionGate`. The file format is unchanged. + +| Event | Prior | Next | Effect | +|---|---|---|---| +| daemon constructed | tombstone on disk | chat closed | `ChatDeletionGate` held, so `beginChatTurn` refuses | +| recovery | closed | closed | bot history, journal, then chat record removed, each repeatable | +| tombstone removed | closed | gone | gate released | +| any step fails | closed | closed | tombstone kept, retried on the next start | + +Recovery runs in `serve` for every server. A failure there is logged and closes only those chats. `createCliRemoteChats` runs it again and still fails startup, because Remote must not list a chat whose deletion is stuck. + +**Defect fixed:** recovery lived only in `createCliRemoteChats`, so `aiden serve --no-remote` neither finished a committed deletion nor closed the chat to new turns. diff --git a/packages/cli/src/daemon-chats.ts b/packages/cli/src/daemon-chats.ts index 53ef112bad..f5384398d2 100644 --- a/packages/cli/src/daemon-chats.ts +++ b/packages/cli/src/daemon-chats.ts @@ -10,6 +10,7 @@ import type { CliBotGenerationRuntime } from "./bots.ts"; import type { BotRuntimeAuthorityAdmission } from "../../../main/services/bot-runtime-authority.js"; import { assertBotRuntimeProviderSelection } from "../../../main/services/bot-runtime-authority.js"; import { mkdirSync } from "node:fs"; +import { rm } from "node:fs/promises"; import { createHash } from "node:crypto"; import { join } from "node:path"; import { createAgentSession, DefaultResourceLoader, SessionManager, type AgentSession } from "@earendil-works/pi-coding-agent"; @@ -26,7 +27,8 @@ import { ChatTurnAdmission } from "../../../main/services/chat-turn-admission.js import { ChatDeletionGate } from "../../../main/services/chat-deletion-gate.js"; import { parseAttachments, withReadableImages } from "../../../main/services/attachment-contract.js"; import { createCliModelRuntime } from "./providers.ts"; -import { acquireLease } from "./state.ts"; +import { acquireLease, JsonStore, readJson } from "./state.ts"; +import { deleteCliBotSubagentHistory } from "./bot-subagents.ts"; import { DaemonGenerationRun, DaemonTurnOwner } from "./daemon-turn-lifecycle.ts"; import { createDaemonApprovals } from "./daemon-approvals.ts"; import { workspaceStore, accessFor } from "./workspaces.ts"; @@ -68,6 +70,12 @@ export function createDaemonChats(agentDir: string) { const recorders = createHostRunRecorders((_scope, message) => process.stderr.write(`aiden: ${message}\n`)); const admission = new ChatTurnAdmission(); const deletion = new ChatDeletionGate(); + // A journal deletion is a durable roll-forward checkpoint, including after a crash: + // its chat stays closed from here until recoverChatDeletions finishes the job. + const tombstones = new JsonStore(join(agentDir, "daemon-chat-deletions.json"), []); + const interrupted = new Map void>(); + try { for (const id of new Set(readJson(tombstones.file, []))) interrupted.set(id, deletion.begin(id)); } + catch { process.stderr.write("aiden: Could not read unfinished chat deletions.\n"); } const turns = new DaemonTurnOwner>({ admission, isDeleting: (id) => deletion.isDeleting(id) }); const approvals = createDaemonApprovals({ raised: (prompt) => activity.requestAttention(prompt.approvalId, prompt.streamId, "approval"), @@ -307,6 +315,16 @@ export function createDaemonChats(agentDir: string) { } return { chatStore, llmClient, activity, runs, admission, deletion, sessionPath, /** Every activity change (a run began or ended, an approval was raised or settled). */ + /** Finishes deletions a crash interrupted. Repeatable: a failure leaves its tombstone and its chat closed. */ + async recoverChatDeletions() { + for (const [id, reopen] of [...interrupted]) { + await deleteCliBotSubagentHistory(agentDir, id); + await rm(sessionPath(id), { force: true }); + if (await chatStore.get(id)) await chatStore.remove(id); + await tombstones.update((values) => { for (let index = values.indexOf(id); index >= 0; index = values.indexOf(id)) values.splice(index, 1); }); + interrupted.delete(id); reopen(); + } + }, onActivityChange(listener: (snapshot: ChatActivitySnapshot) => void) { activityListeners.add(listener); return () => { activityListeners.delete(listener); }; }, setBots(runtime: CliBotGenerationRuntime) { bots = runtime; }, /** Closes intake before its first await, so no ingress stopping alongside it can begin a turn. */ diff --git a/packages/cli/src/remote-chats.ts b/packages/cli/src/remote-chats.ts index 7e193adfd3..72922b63a5 100644 --- a/packages/cli/src/remote-chats.ts +++ b/packages/cli/src/remote-chats.ts @@ -21,13 +21,8 @@ import { liveRunAttention } from "../../../main/services/chat-pending-attention. export async function createCliRemoteChats(agentDir: string, daemon: ReturnType, workspace: ReturnType, state: AidenRemoteStateRegistry, idempotency: AidenIdempotencyLedger, persistIdempotency: (value: AidenIdempotencySnapshot) => Promise, bots: Awaited>) { const deleting = new JsonStore(join(agentDir, "daemon-chat-deletions.json"), []); - // A journal deletion is a durable roll-forward checkpoint, including after a crash. - for (const id of await deleting.load()) { - await deleteCliBotSubagentHistory(agentDir, id); - await rm(daemon.sessionPath(id), { force: true }); - if (await daemon.chatStore.get(id)) await daemon.chatStore.remove(id); - await deleting.update((values) => { values.splice(values.indexOf(id), 1); }); - } + // Remote must not serve a chat whose deletion could not finish. + await daemon.recoverChatDeletions(); const privateHistory = { async deleteChat(id: string) { await deleting.update((values) => { if (!values.includes(id)) values.push(id); }); await deleteCliBotSubagentHistory(agentDir, id); }, async completeChatDeletion(id: string) { await deleting.update((values) => { const index = values.indexOf(id); if (index >= 0) values.splice(index, 1); }); }, diff --git a/packages/cli/src/serve.ts b/packages/cli/src/serve.ts index ce23bde012..fe933cffd7 100644 --- a/packages/cli/src/serve.ts +++ b/packages/cli/src/serve.ts @@ -42,6 +42,8 @@ export async function serve(agentDir: string, signal: AbortSignal, options: { re async function serveOwned(agentDir: string, signal: AbortSignal, options: { remote?: boolean; onReady?: () => void }) { const runtime = createCliScheduler(agentDir); const chats = createDaemonChats(agentDir); + // Every server finishes these, Remote or not. A failure keeps only those chats closed. + await chats.recoverChatDeletions().catch((error: unknown) => { process.stderr.write(`aiden: Could not finish a chat deletion: ${error instanceof Error ? error.message : String(error)}\n`); }); const workspaceRuntime = createCliWorkspaceApplication(agentDir, { cancelGeneration: async (id) => { for (const chat of await chats.chatStore.list(id)) { await chats.llmClient.cancelChat(chat.id); await chats.llmClient.waitForChatIdle(chat.id); } }, cancelSchedules: (id) => runtime.service.cancelWorkspace(id), resumeSchedules: (id) => runtime.service.resumeWorkspace(id), diff --git a/packages/cli/tests/daemon-turns.test.mjs b/packages/cli/tests/daemon-turns.test.mjs index decfdec7de..89a988de51 100644 --- a/packages/cli/tests/daemon-turns.test.mjs +++ b/packages/cli/tests/daemon-turns.test.mjs @@ -2,10 +2,12 @@ // accepted and refused turns, what a provider and the chat store actually saw, // what a client was told, and which resources stay held. import assert from "node:assert/strict"; -import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import fsPromises from "node:fs/promises"; +import { syncBuiltinESMExports } from "node:module"; import { createServer } from "node:http"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; import test from "node:test"; import * as api from "../dist/parity-test-api.js"; @@ -498,6 +500,53 @@ test("a run whose session lease cannot be removed still reports idle", { skip: p } finally { chmodSync(journals, 0o700); } }); +// C14: a chat deletion that a crash interrupted. + +test("an interrupted chat deletion blocks new turns and finishes when the server starts without Remote", async (t) => { + const f = await fixture(t), { dir, daemon, workspace } = f; + await daemon.chatStore.create({ id: "half-deleted", title: "Half deleted", workspaceId: workspace.id }); + await daemon.chatStore.create({ id: "kept", title: "Kept", workspaceId: workspace.id }); + mkdirSync(dirname(daemon.sessionPath("half-deleted")), { recursive: true }); + writeFileSync(daemon.sessionPath("half-deleted"), "{}\n"); + api.atomicJson(join(dir, "daemon-chat-deletions.json"), ["half-deleted"]); + const restarted = api.createDaemonChats(dir); + t.after(() => restarted.stop()); + assert.equal(restarted.llmClient.beginChatTurn("half-deleted", "stream", "owner"), null, "the deletion already committed"); + const controller = new AbortController(), ready = Promise.withResolvers(); + const serving = api.serve(dir, controller.signal, { onReady: ready.resolve }); + void serving.catch(ready.reject); + await ready.promise; + controller.abort(); await serving; + const after = api.createDaemonChats(dir); + t.after(() => after.stop()); + assert.equal(await after.chatStore.get("half-deleted"), null); + assert.equal(existsSync(after.sessionPath("half-deleted")), false); + assert.deepEqual(JSON.parse(readFileSync(join(dir, "daemon-chat-deletions.json"), "utf8")), []); + assert.ok(await after.chatStore.get("kept")); + const lease = after.llmClient.beginChatTurn("kept", "stream", "owner"); assert.ok(lease); + lease.settleAsyncWork(); lease.release(); +}); + +test("a deletion that cannot finish keeps its chat closed without stopping the rest of the daemon", async (t) => { + const f = await fixture(t), { dir, daemon, workspace } = f; + await daemon.chatStore.create({ id: "stuck", title: "Stuck", workspaceId: workspace.id }); + const { rm } = fsPromises; + fsPromises.rm = async (path, ...rest) => { if (String(path) === daemon.sessionPath("stuck")) throw new Error("disk fault"); return rm(path, ...rest); }; + syncBuiltinESMExports(); + t.after(() => { fsPromises.rm = rm; syncBuiltinESMExports(); }); + api.atomicJson(join(dir, "daemon-chat-deletions.json"), ["stuck"]); + const restarted = api.createDaemonChats(dir); + t.after(() => restarted.stop()); + await assert.rejects(restarted.recoverChatDeletions(), /disk fault/u); + assert.equal(restarted.llmClient.beginChatTurn("stuck", "stream", "owner"), null); + assert.deepEqual(JSON.parse(readFileSync(join(dir, "daemon-chat-deletions.json"), "utf8")), ["stuck"], "the tombstone stays for the next start"); + fsPromises.rm = rm; syncBuiltinESMExports(); + await restarted.recoverChatDeletions(); + assert.equal(await restarted.chatStore.get("stuck"), null); + const lease = restarted.llmClient.beginChatTurn("stuck", "stream", "owner"); assert.ok(lease, "a finished deletion frees the id"); + lease.settleAsyncWork(); lease.release(); +}); + function approvalsFixture(options = {}) { const raised = [], resolved = []; const approvals = api.createDaemonApprovals({ raised: (prompt) => raised.push(prompt.approvalId), resolved: (id, decision) => resolved.push([id, decision]), ...options }); From 7c5a7de6ccb339647108f6475f9c767d11cc8090 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 4 Nov 2026 19:52:42 -0500 Subject: [PATCH 02/12] Give schedule consent one phase and behavioral coverage Co-Authored-By: Claude Opus 5.5 --- packages/cli/package.json | 2 +- packages/cli/src/parity-test-api.ts | 1 + packages/cli/src/schedules.ts | 21 +++--- packages/cli/tests/schedule-consent.test.mjs | 76 ++++++++++++++++++++ 4 files changed, 90 insertions(+), 10 deletions(-) create mode 100644 packages/cli/tests/schedule-consent.test.mjs diff --git a/packages/cli/package.json b/packages/cli/package.json index 6ab72e6b84..84319f969f 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -17,7 +17,7 @@ ], "scripts": { "build": "node scripts/patch-branding.mjs && node scripts/build.mjs", - "test": "node --test tests/bundle.test.mjs tests/runtime.test.mjs tests/extensions.test.mjs tests/parity.test.mjs tests/serve-startup.test.mjs tests/service.test.mjs tests/reachability.test.mjs tests/inbox-host.test.mjs tests/daemon-turns.test.mjs tests/serve-lifetime.test.mjs", + "test": "node --test tests/bundle.test.mjs tests/runtime.test.mjs tests/extensions.test.mjs tests/parity.test.mjs tests/serve-startup.test.mjs tests/service.test.mjs tests/reachability.test.mjs tests/inbox-host.test.mjs tests/daemon-turns.test.mjs tests/serve-lifetime.test.mjs tests/schedule-consent.test.mjs", "type-check": "tsc --noEmit" }, "dependencies": { diff --git a/packages/cli/src/parity-test-api.ts b/packages/cli/src/parity-test-api.ts index eabce8d0c8..7553059d66 100644 --- a/packages/cli/src/parity-test-api.ts +++ b/packages/cli/src/parity-test-api.ts @@ -5,6 +5,7 @@ export * from "./sessions.ts"; export * from "./providers.ts"; export * from "./credentials.ts"; export * from "./schedules.ts"; +export * from "./schedule-tool-approval.ts"; export * from "./serve.ts"; export * from "./serve-lifecycle.ts"; export * from "./serve-lifetime.ts"; diff --git a/packages/cli/src/schedules.ts b/packages/cli/src/schedules.ts index 7439474a71..7e77555d03 100644 --- a/packages/cli/src/schedules.ts +++ b/packages/cli/src/schedules.ts @@ -25,7 +25,9 @@ async function providerFingerprint(agentDir: string, providerId?: string, modelI } export function createCliScheduler(agentDir: string) { - const approvedMutation = new AsyncLocalStorage<{ approval: ScheduleToolApproval; active: boolean; firstWrite: boolean; cancellation: AbortController }>(); + // Consent verifies the task on the first write and only the environment after it. + // `closed` is terminal: a rejected write or a finished command can never use it again. + const approvedMutation = new AsyncLocalStorage<{ approval: ScheduleToolApproval; phase: "first_write" | "follow_on" | "closed"; cancellation: AbortController }>(); const persistence = new JsonStore(join(agentDir, "schedules.json"), []); const tasks = { load: () => persistence.load(), @@ -33,17 +35,17 @@ export function createCliScheduler(agentDir: string) { return persistence.update(mutation, () => { if (isCurrent && !isCurrent()) return false; const current = approvedMutation.getStore(); - if (current?.active) { + if (current && current.phase !== "closed") { try { - assertScheduleApproval(agentDir, current.approval, current.firstWrite); + assertScheduleApproval(agentDir, current.approval, current.phase === "first_write"); } catch (error) { // A rejected mutation may rearm/restore the unchanged task, never reuse its consent. // Aborting lets the shared lifecycle roll back writes this mutation already made. - current.active = false; + current.phase = "closed"; current.cancellation.abort(); throw error; } - current.firstWrite = false; + current.phase = "follow_on"; } return true; }); @@ -113,20 +115,21 @@ export function createCliScheduler(agentDir: string) { const approval = JSON.parse(timezone) as ScheduleToolApproval; if (approval.action !== action) throw new Error("The approved schedule action changed."); assertScheduleApproval(agentDir, approval); - const current = { approval, active: true, firstWrite: true, cancellation: new AbortController() }; + const current = { approval, phase: "first_write" as "first_write" | "follow_on" | "closed", cancellation: new AbortController() }; try { return await approvedMutation.run(current, () => command(args.slice(0, 2))); } finally { // Cron callbacks can inherit this async context, but never its one-shot consent. - current.active = false; + current.phase = "closed"; } } const currentApproval = approvedMutation.getStore(); - const revision = currentApproval?.active + const consentOpen = currentApproval !== undefined && currentApproval.phase !== "closed"; + const revision = consentOpen ? (JSON.parse(currentApproval.approval.snapshot) as { task?: { updatedAt?: number } }).task?.updatedAt : undefined; // A new task has no revision to pin, but its receipt can still be cancelled. - const mutationOptions = currentApproval?.active + const mutationOptions = consentOpen ? { ...(revision === undefined ? {} : { expectedUpdatedAt: revision }), signal: currentApproval.cancellation.signal } : undefined; switch (action) { diff --git a/packages/cli/tests/schedule-consent.test.mjs b/packages/cli/tests/schedule-consent.test.mjs new file mode 100644 index 0000000000..5f7fb4aa60 --- /dev/null +++ b/packages/cli/tests/schedule-consent.test.mjs @@ -0,0 +1,76 @@ +// cli-native C15: a schedule mutation carrying consent is bound to what the +// person reviewed, and is rechecked at the durable write. +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; +import * as api from "../dist/parity-test-api.js"; + +async function fixture(t) { + const dir = mkdtempSync(join(tmpdir(), "aiden-consent-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + const workspace = await api.workspaceCommand(dir, ["add", dir]); + await api.workspaceCommand(dir, ["access", workspace.id, "full"]); + const scheduler = api.createCliScheduler(dir), input = join(dir, "input.json"); + t.after(() => scheduler.service.stopAndSettle()); + writeFileSync(input, JSON.stringify({ name: "Review", mode: "script", script: "true", cron: "0 9 * * *", timezone: "UTC", permission: "full", enabled: true, workspaceId: workspace.id })); + const task = await scheduler.command(["save", input]); + /** Captures consent for `action` the way a confirmation does. */ + const consent = (action, overrides = {}) => { + const approvalFile = join(dir, `receipt-${action}.json`); + const approval = { cwd: dir, action, input: { id: task.id }, expiresAt: Date.now() + 60_000, approvalFile }; + approval.snapshot = api.scheduleApprovalSnapshot(dir, approval); + writeFileSync(approvalFile, JSON.stringify(approval.snapshot)); + return { ...approval, ...overrides }; + }; + const stored = async () => (await scheduler.command(["list"])).find((item) => item.id === task.id); + return { dir, scheduler, workspace, task, consent, stored, run: (action, approval) => scheduler.command([action, task.id, JSON.stringify(approval)]) }; +} + +test("consent for the task as reviewed lets the mutation through once", async (t) => { + const f = await fixture(t), approval = f.consent("pause"); + await f.run("pause", approval); + assert.equal((await f.stored()).enabled, false); + await assert.rejects(f.run("pause", approval), /changed after approval/u, "the same consent no longer matches the task"); +}); + +test("expired, cancelled or mismatched consent changes nothing", async (t) => { + const f = await fixture(t); + await assert.rejects(f.run("pause", f.consent("pause", { expiresAt: Date.now() - 1 })), /expired/u); + const cancelled = f.consent("pause"); + rmSync(cancelled.approvalFile); + await assert.rejects(f.run("pause", cancelled), /cancelled/u); + await assert.rejects(f.run("resume", f.consent("pause")), /action changed/u); + assert.equal((await f.stored()).enabled, true); +}); + +test("consent lapses when the workspace, provider or task changes after review", async (t) => { + const f = await fixture(t); + const access = f.consent("pause"); + await api.workspaceCommand(f.dir, ["access", f.workspace.id, "ask"]); + await assert.rejects(f.run("pause", access), /changed after approval/u); + await api.workspaceCommand(f.dir, ["access", f.workspace.id, "full"]); + const provider = f.consent("pause"); + api.atomicJson(join(f.dir, "models.json"), { providers: {} }); + await assert.rejects(f.run("pause", provider), /changed after approval/u); + const edited = f.consent("pause"); + await f.scheduler.command(["pause", f.task.id]); + await f.scheduler.command(["resume", f.task.id]); + await assert.rejects(f.run("pause", edited), /changed after approval/u); + assert.equal((await f.stored()).enabled, true); +}); + +test("consent revoked at the durable write stops the mutation and is not reused", async (t) => { + const f = await fixture(t), approval = f.consent("pause"); + // The entry check has passed. Revoke between it and the write the mutation publishes. + const update = api.JsonStore.prototype.update; + api.JsonStore.prototype.update = function (mutation, isCurrent, replace) { + if (this.file.endsWith("schedules.json")) rmSync(approval.approvalFile, { force: true }); + return update.call(this, mutation, isCurrent, replace); + }; + t.after(() => { api.JsonStore.prototype.update = update; }); + await assert.rejects(f.run("pause", approval), /cancelled/u); + api.JsonStore.prototype.update = update; + assert.equal((await f.stored()).enabled, true); +}); From 24e47ee31cb6a658d79cf391953f82db50d52797 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 4 Nov 2026 19:56:43 -0500 Subject: [PATCH 03/12] Record C15 and triage the remaining cli-native entries Co-Authored-By: Claude Opus 5.5 --- .memory/explicit-state-machines-lane-d.md | 3 ++ docs/state-machines/serve-daemon.md | 40 +++++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/.memory/explicit-state-machines-lane-d.md b/.memory/explicit-state-machines-lane-d.md index 90e35b6108..3be35deb5b 100644 --- a/.memory/explicit-state-machines-lane-d.md +++ b/.memory/explicit-state-machines-lane-d.md @@ -8,3 +8,6 @@ Started 2026-11-04. Scope: `cli-native` C09, C10, C03, C01, C02, C11, C04, then - `DaemonTurnOwner` (`packages/cli/src/daemon-turn-lifecycle.ts`) is the only writer of chat custody. Lane A's #735 keeps the lease API, so this does not stack on it; its doc home is `docs/state-machines/`. - Never await `cancelChat` from inside a tool_call or before_agent_start hook: `session.abort()` waits for the very hook that called it. - `.memory/` is gitignored but tracked: new files need `git add -f`. +- C15 converted to one `phase`. Triage of the other `C*` entries is at the end of `docs/state-machines/serve-daemon.md`. +- C18 and C19 are blocked on the subagent upgrade branch, which rewrites those files. C05 waits on #733. C12, C16, C28 and C32 are P6. +- No file outside `packages/cli`, `docs/state-machines` and `.memory` changed, so no mobile contract moved. diff --git a/docs/state-machines/serve-daemon.md b/docs/state-machines/serve-daemon.md index 82372abc1f..389f21efc3 100644 --- a/docs/state-machines/serve-daemon.md +++ b/docs/state-machines/serve-daemon.md @@ -147,3 +147,43 @@ Owner: `recoverChatDeletions` in `daemon-chats.ts`, over the `daemon-chat-deleti Recovery runs in `serve` for every server. A failure there is logged and closes only those chats. `createCliRemoteChats` runs it again and still fails startup, because Remote must not list a chat whose deletion is stuck. **Defect fixed:** recovery lived only in `createCliRemoteChats`, so `aiden serve --no-remote` neither finished a committed deletion nor closed the chat to new turns. + +## C15: schedule consent publication + +Owner: `approvedMutation` in `createCliScheduler` (`schedules.ts`) over `assertScheduleApproval` (`schedule-tool-approval.ts`). Two booleans became one `phase`. + +| Event | Prior | Next | Effect | +|---|---|---|---| +| command with consent | none | `first_write` | snapshot, expiry and receipt verified at entry | +| durable write verified | `first_write` | `follow_on` | task checked once; later writes check only the environment | +| verification fails | `first_write` or `follow_on` | `closed` | abort, so the shared lifecycle rolls back | +| command ends | any | `closed` | consent can never be used again | + +No producer of consent remains in `src` since the model-facing tool was retired; only this guard is live. It had no tests, so `tests/schedule-consent.test.mjs` covers valid, reused, expired, cancelled, mismatched, and environment or task changed after review, and revocation between the entry check and the write. + +## Triage of the remaining `cli-native` entries + +"Retained" means already explicit or fenced, with the listed coverage, and no conversion here would add a guarantee. None of these was reproduced as a defect. + +| Entry | On the serve path | Disposition | +|---|---|---| +| C05 service install | No, admin command | Deferred: #733 and the subagent upgrade branch both change `service.ts`. Covered by `tests/service.test.mjs`. | +| C06 pairing presentation | Startup only | Retained: presentation, and #733 changes `serve-command.ts`. | +| C07 Tailscale health wait | Startup only | Retained: single settlement and a byte bound, covered by `tests/reachability.test.mjs`. | +| C08 Linux Bonjour | Yes, Linux | Retained: generation and child identity already fence late callbacks. Not exercised against real avahi here. | +| C12 Bot pause | Yes | Deferred to P6: the shared pause store and durable runtime own it. It reuses `stopChatWork`, which now waits on C09 settlement. | +| C13 durable Bot migration | Admin command | Retained: `preparing` and `enabled` are already an explicit durable marker. | +| C16 scheduled execution | Yes | Deferred to P6: the shared scheduler owns timing and revisions; drain already awaits `stopAndSettle`. | +| C17 inference metering | Yes | Retained: an algorithmic streaming counter, deferred after P6 by the plan. | +| C18, C19 child inference and worker RPC | Yes, through Bot subagents | Blocked: the subagent upgrade branch rewrites `subagent-process.ts` and `subagent-worker.ts`. Revisit after it lands. | +| C20 MCP connection incarnation | Yes | Retained: entry identity fences every await, covered by the MCP pool cases in `tests/parity.test.mjs`. | +| C21 terminal provider auth | No | Skipped: interactive terminal only. | +| C22 speech worker | Yes, through Remote | Retained: worker and client identity already fence late exits, and Remote stop awaits `speech.stop()`. | +| C23 avatar decoder | Yes, through Remote Bots | Retained: bounded slots with `finally` cleanup, deferred after P6 by the plan. | +| C24 lease and JSON publication | Yes | Retained: idempotent release and a failed publication that releases its guard. C03, C14 and C15 rely on it unchanged. | +| C25, C30, C31 credentials | Reads only | Retained: per-file queue plus lease; migrations are explicit transactions outside the daemon's turn path. | +| C26 todo restore | Yes, inside sessions | Retained: `restoreEpoch` fences late restores, covered by the todo cases in `tests/parity.test.mjs`. | +| C27 advisor availability | Yes, inside sessions | Retained: the shared advisor runtime owns attempts, deferred after P6 by the plan. | +| C28 Bot inventory invalidation | Yes | Deferred to P6 with the shared Bot authority owners. | +| C29 MCP config migration | Store construction | Retained: an explicit publish-then-retire transaction. | +| C32 usage accounting | Yes | Deferred to P6: receipt and aggregate already publish together. | From 8678c5a32a663ca577ed3aefd13cbcbda259510d Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 4 Nov 2026 20:01:28 -0500 Subject: [PATCH 04/12] Bind schedule consent to the reviewed input, once A save read its file after consent without comparing it to what was reviewed, and new-task consent stayed valid until expiry because only the retired producer removed its receipt. No caller in src produces consent today, so this hardens the guard that remains. Co-Authored-By: Claude Opus 5.5 --- docs/state-machines/serve-daemon.md | 6 ++++- packages/cli/src/schedule-tool-approval.ts | 6 +++++ packages/cli/src/schedules.ts | 9 ++++++- packages/cli/tests/schedule-consent.test.mjs | 27 ++++++++++++++++++-- 4 files changed, 44 insertions(+), 4 deletions(-) diff --git a/docs/state-machines/serve-daemon.md b/docs/state-machines/serve-daemon.md index 389f21efc3..dd667f3d5f 100644 --- a/docs/state-machines/serve-daemon.md +++ b/docs/state-machines/serve-daemon.md @@ -157,7 +157,11 @@ Owner: `approvedMutation` in `createCliScheduler` (`schedules.ts`) over `assertS | command with consent | none | `first_write` | snapshot, expiry and receipt verified at entry | | durable write verified | `first_write` | `follow_on` | task checked once; later writes check only the environment | | verification fails | `first_write` or `follow_on` | `closed` | abort, so the shared lifecycle rolls back | -| command ends | any | `closed` | consent can never be used again | +| command ends | any | `closed` | this context is finished, and its receipt is spent | + +A receipt is spent as the command starts, in memory, so it works once even if the command fails or the file stays on disk. A `save` must also read back the input that was reviewed, because the file is read after consent. + +**Defects fixed:** a `save` trusted whatever the file held by then, and a new-task consent could be replayed until it expired, since only the retired producer ever removed the receipt. No producer of consent remains in `src` since the model-facing tool was retired; only this guard is live. It had no tests, so `tests/schedule-consent.test.mjs` covers valid, reused, expired, cancelled, mismatched, and environment or task changed after review, and revocation between the entry check and the write. diff --git a/packages/cli/src/schedule-tool-approval.ts b/packages/cli/src/schedule-tool-approval.ts index dac10ae4fd..b25247486e 100644 --- a/packages/cli/src/schedule-tool-approval.ts +++ b/packages/cli/src/schedule-tool-approval.ts @@ -13,6 +13,12 @@ export interface ScheduleToolApproval { approvalFile: string; } +/** What a save was reviewed as: the proposal, without the action naming it. */ +export function reviewedScheduleInput(approval: ScheduleToolApproval): Record { + const { action: _action, ...input } = approval.input as Record; + return input; +} + export const isScheduleMutation = (action: unknown): boolean => action === "save" || action === "pause" || action === "resume" || action === "remove"; diff --git a/packages/cli/src/schedules.ts b/packages/cli/src/schedules.ts index 7e77555d03..b39557eef5 100644 --- a/packages/cli/src/schedules.ts +++ b/packages/cli/src/schedules.ts @@ -4,6 +4,7 @@ import { storeFor } from "./mcp.ts"; import { runScheduledInference } from "./scheduled-inference.ts"; import { join } from "node:path"; import { readFileSync } from "node:fs"; +import { isDeepStrictEqual } from "node:util"; import { remoteDaemonCommand } from "./daemon-control.ts"; import { createHash } from "node:crypto"; import { createScheduleStore, nextScheduledRuns } from "../../../main/services/schedule-store-core.js"; @@ -14,7 +15,7 @@ import { workspaceStore, accessFor } from "./workspaces.ts"; import { resolveScheduledScript, runScheduledScript } from "../../../main/services/schedule-script.js"; import { createCliModelRuntime } from "./providers.ts"; import { AsyncLocalStorage } from "node:async_hooks"; -import { assertScheduleApproval, isScheduleMutation, type ScheduleToolApproval } from "./schedule-tool-approval.ts"; +import { assertScheduleApproval, isScheduleMutation, reviewedScheduleInput, type ScheduleToolApproval } from "./schedule-tool-approval.ts"; async function providerFingerprint(agentDir: string, providerId?: string, modelId?: string): Promise { if (!providerId || !modelId) throw new Error("Select an explicit provider and model for unattended inference."); @@ -27,6 +28,8 @@ async function providerFingerprint(agentDir: string, providerId?: string, modelI export function createCliScheduler(agentDir: string) { // Consent verifies the task on the first write and only the environment after it. // `closed` is terminal: a rejected write or a finished command can never use it again. + // One receipt, one command, even if the command fails: the person reviews again. + const spentApprovals = new Set(); const approvedMutation = new AsyncLocalStorage<{ approval: ScheduleToolApproval; phase: "first_write" | "follow_on" | "closed"; cancellation: AbortController }>(); const persistence = new JsonStore(join(agentDir, "schedules.json"), []); const tasks = { @@ -114,7 +117,9 @@ export function createCliScheduler(agentDir: string) { if (isScheduleMutation(action) && timezone !== undefined) { const approval = JSON.parse(timezone) as ScheduleToolApproval; if (approval.action !== action) throw new Error("The approved schedule action changed."); + if (spentApprovals.has(approval.approvalFile)) throw new Error("Scheduled-task approval was already used. Review the task again."); assertScheduleApproval(agentDir, approval); + spentApprovals.add(approval.approvalFile); const current = { approval, phase: "first_write" as "first_write" | "follow_on" | "closed", cancellation: new AbortController() }; try { return await approvedMutation.run(current, () => command(args.slice(0, 2))); @@ -184,6 +189,8 @@ export function createCliScheduler(agentDir: string) { case "save": { if (!value) throw new Error("Provide a JSON file containing ScheduledTaskInput."); const input = JSON.parse(readFileSync(value, "utf8")) as ScheduledTaskInput; + // The file is read after consent, so what it holds must still be what was reviewed. + if (consentOpen && !isDeepStrictEqual(input, reviewedScheduleInput(currentApproval.approval))) throw new Error("The schedule changed after approval. Review it again."); return saveInput(input, mutationOptions); } case "remove": await service.remove(value, mutationOptions); return { removed: value }; diff --git a/packages/cli/tests/schedule-consent.test.mjs b/packages/cli/tests/schedule-consent.test.mjs index 5f7fb4aa60..e583a1d0a7 100644 --- a/packages/cli/tests/schedule-consent.test.mjs +++ b/packages/cli/tests/schedule-consent.test.mjs @@ -28,11 +28,34 @@ async function fixture(t) { return { dir, scheduler, workspace, task, consent, stored, run: (action, approval) => scheduler.command([action, task.id, JSON.stringify(approval)]) }; } -test("consent for the task as reviewed lets the mutation through once", async (t) => { +test("consent for a new schedule covers the reviewed input, once", async (t) => { + const f = await fixture(t), file = join(f.dir, "new.json"); + const reviewed = { name: "New", mode: "script", script: "true", cron: "0 9 * * *", timezone: "UTC", permission: "full", enabled: false, workspaceId: f.workspace.id }; + const review = (name) => { + const approval = { cwd: f.dir, action: "save", input: reviewed, expiresAt: Date.now() + 60_000, approvalFile: join(f.dir, `${name}.json`) }; + approval.snapshot = api.scheduleApprovalSnapshot(f.dir, approval); + writeFileSync(approval.approvalFile, JSON.stringify(approval.snapshot)); + return approval; + }; + const save = (approval) => f.scheduler.command(["save", file, JSON.stringify(approval)]); + const count = async () => (await f.scheduler.command(["list"])).length; + const before = await count(), swapped = review("swapped"), approved = review("approved"); + writeFileSync(file, JSON.stringify({ ...reviewed, script: "rm -rf ." })); + await assert.rejects(save(swapped), /changed after approval/u); + assert.equal(await count(), before, "a swapped file is not what was reviewed"); + writeFileSync(file, JSON.stringify(reviewed)); + await assert.rejects(save(swapped), /already used/u, "a rejected command spends its consent"); + await save(approved); + assert.equal(await count(), before + 1); + await assert.rejects(save(approved), /already used/u); + assert.equal(await count(), before + 1, "the receipt was left in place, but consent is spent"); +}); + +test("consent for the task as reviewed lets the mutation through", async (t) => { const f = await fixture(t), approval = f.consent("pause"); await f.run("pause", approval); assert.equal((await f.stored()).enabled, false); - await assert.rejects(f.run("pause", approval), /changed after approval/u, "the same consent no longer matches the task"); + await assert.rejects(f.run("pause", approval), /already used/u); }); test("expired, cancelled or mismatched consent changes nothing", async (t) => { From 3bb8964eef768d9678c0c4f5a2f027b14774c876 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 4 Nov 2026 20:06:48 -0500 Subject: [PATCH 05/12] Remove a schedule receipt when its command ends The in-memory spent list covers one scheduler. Separate offline commands build their own, so a receipt left on disk could be replayed through a new one. Co-Authored-By: Claude Opus 5.5 --- docs/state-machines/serve-daemon.md | 2 +- packages/cli/src/schedules.ts | 4 +++- packages/cli/tests/schedule-consent.test.mjs | 3 ++- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/state-machines/serve-daemon.md b/docs/state-machines/serve-daemon.md index dd667f3d5f..aedf202499 100644 --- a/docs/state-machines/serve-daemon.md +++ b/docs/state-machines/serve-daemon.md @@ -159,7 +159,7 @@ Owner: `approvedMutation` in `createCliScheduler` (`schedules.ts`) over `assertS | verification fails | `first_write` or `follow_on` | `closed` | abort, so the shared lifecycle rolls back | | command ends | any | `closed` | this context is finished, and its receipt is spent | -A receipt is spent as the command starts, in memory, so it works once even if the command fails or the file stays on disk. A `save` must also read back the input that was reviewed, because the file is read after consent. +A receipt is spent as the command starts and removed when it ends, so it works once even if the command fails, and another scheduler instance cannot replay it. A `save` must also read back the input that was reviewed, because the file is read after consent. **Defects fixed:** a `save` trusted whatever the file held by then, and a new-task consent could be replayed until it expired, since only the retired producer ever removed the receipt. diff --git a/packages/cli/src/schedules.ts b/packages/cli/src/schedules.ts index b39557eef5..bc882c5355 100644 --- a/packages/cli/src/schedules.ts +++ b/packages/cli/src/schedules.ts @@ -3,7 +3,7 @@ import { scheduledMcpServerBinding } from "../../../main/services/schedule-mcp-b import { storeFor } from "./mcp.ts"; import { runScheduledInference } from "./scheduled-inference.ts"; import { join } from "node:path"; -import { readFileSync } from "node:fs"; +import { readFileSync, rmSync } from "node:fs"; import { isDeepStrictEqual } from "node:util"; import { remoteDaemonCommand } from "./daemon-control.ts"; import { createHash } from "node:crypto"; @@ -126,6 +126,8 @@ export function createCliScheduler(agentDir: string) { } finally { // Cron callbacks can inherit this async context, but never its one-shot consent. current.phase = "closed"; + // Without the receipt no other scheduler can replay it. A leftover file stays spent here. + try { rmSync(approval.approvalFile, { force: true }); } catch { /* The command's own outcome stands. */ } } } const currentApproval = approvedMutation.getStore(); diff --git a/packages/cli/tests/schedule-consent.test.mjs b/packages/cli/tests/schedule-consent.test.mjs index e583a1d0a7..0fe1517d0f 100644 --- a/packages/cli/tests/schedule-consent.test.mjs +++ b/packages/cli/tests/schedule-consent.test.mjs @@ -48,7 +48,8 @@ test("consent for a new schedule covers the reviewed input, once", async (t) => await save(approved); assert.equal(await count(), before + 1); await assert.rejects(save(approved), /already used/u); - assert.equal(await count(), before + 1, "the receipt was left in place, but consent is spent"); + await assert.rejects(api.createCliScheduler(f.dir).command(["save", file, JSON.stringify(approved)]), /cancelled/u, "another scheduler cannot replay it"); + assert.equal(await count(), before + 1); }); test("consent for the task as reviewed lets the mutation through", async (t) => { From 67eaa641067f059337fd4d9e6656dadf95b37c6b Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 4 Nov 2026 20:01:28 -0500 Subject: [PATCH 06/12] Document that every server finishes interrupted deletions Co-Authored-By: Claude Opus 5.5 --- packages/cli/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/cli/README.md b/packages/cli/README.md index cdc7832162..6db295d7bd 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -47,7 +47,7 @@ Every setup step is a short command you run once over SSH. aiden serve ``` -`aiden serve` starts the server in the foreground: the scheduler, configured Telegram polling, Bots and Remote, the authenticated HTTPS/SSE API that phones and Macs use (port 49320 by default). Remote is on by default; `aiden serve --no-remote` runs without it (`--remote` is still accepted). +`aiden serve` starts the server in the foreground: the scheduler, configured Telegram polling, Bots and Remote, the authenticated HTTPS/SSE API that phones and Macs use (port 49320 by default). Remote is on by default; `aiden serve --no-remote` runs without it (`--remote` is still accepted). Either way, the server finishes any chat deletion a crash interrupted, and that chat takes no turns until it has. When `aiden serve` runs in the foreground in an interactive terminal, it prints a pairing QR code and manual code at startup, so you can scan it from the phone app right away. It pairs over the local network by default (over Tailscale when the server is set to Tailscale only, `remote mode tailscale`); `--pair tailscale` pairs over Tailscale instead, and `--no-pair` skips the code. No code is printed under `--daemon` or when output is not a terminal (a log, a pipe, a service manager), because the code is a single-use secret. From 0dadb4757d23f30c684363eec41bc68beb8616ce Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 4 Nov 2026 20:14:36 -0500 Subject: [PATCH 07/12] Record Lane D review lessons Co-Authored-By: Claude Opus 5.5 --- .memory/explicit-state-machines-lane-d.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.memory/explicit-state-machines-lane-d.md b/.memory/explicit-state-machines-lane-d.md index 3be35deb5b..6105c21071 100644 --- a/.memory/explicit-state-machines-lane-d.md +++ b/.memory/explicit-state-machines-lane-d.md @@ -11,3 +11,7 @@ Started 2026-11-04. Scope: `cli-native` C09, C10, C03, C01, C02, C11, C04, then - C15 converted to one `phase`. Triage of the other `C*` entries is at the end of `docs/state-machines/serve-daemon.md`. - C18 and C19 are blocked on the subagent upgrade branch, which rewrites those files. C05 waits on #733. C12, C16, C28 and C32 are P6. - No file outside `packages/cli`, `docs/state-machines` and `.memory` changed, so no mobile contract moved. +- Cleanup hooks in `node:test` (`t.after`) run in registration order here, so stop a daemon before removing its directory. `box.stopServer` in `tests/serve-lifetime.test.mjs` does that; an earlier `t.after(serve stop)` orphaned real daemons. +- The local shell is zsh: an unquoted `$files` is one argument, so a looped `node --test $files` silently runs nothing. Check that a pass count came back. +- Control-socket chunks stop near 64 KiB, so a ceiling test needs a frame near the limit plus a later write, not one big write. +- Shared-owner note: a publish callback that settles its own approval is handled by Lane B's #738, not here. From 50a02d2ea9c7472418be9af41e8decc32ebcf236 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 4 Nov 2026 20:35:15 -0500 Subject: [PATCH 08/12] Refuse to start when the deletion record is unreadable A malformed record was logged and treated as no pending deletions, so a chat whose deletion had committed could reopen. Remote used to reject this state. Every chat now stays closed and no server starts. Co-Authored-By: Claude Opus 5.5 --- docs/state-machines/serve-daemon.md | 1 + packages/cli/src/daemon-chats.ts | 16 +++++++++++++--- packages/cli/src/serve.ts | 1 + packages/cli/tests/daemon-turns.test.mjs | 13 +++++++++++++ 4 files changed, 28 insertions(+), 3 deletions(-) diff --git a/docs/state-machines/serve-daemon.md b/docs/state-machines/serve-daemon.md index 4ac34ebf1d..3dfbb1e368 100644 --- a/docs/state-machines/serve-daemon.md +++ b/docs/state-machines/serve-daemon.md @@ -143,6 +143,7 @@ Owner: `recoverChatDeletions` in `daemon-chats.ts`, over the `daemon-chat-deleti | recovery | closed | closed | bot history, journal, then chat record removed, each repeatable | | tombstone removed | closed | gone | gate released | | any step fails | closed | closed | tombstone kept, retried on the next start | +| record unreadable | unknown | every chat closed | no server starts, Remote or not | Recovery runs in `serve` for every server. A failure there is logged and closes only those chats. `createCliRemoteChats` runs it again and still fails startup, because Remote must not list a chat whose deletion is stuck. diff --git a/packages/cli/src/daemon-chats.ts b/packages/cli/src/daemon-chats.ts index f5384398d2..7731ca41e6 100644 --- a/packages/cli/src/daemon-chats.ts +++ b/packages/cli/src/daemon-chats.ts @@ -74,9 +74,16 @@ export function createDaemonChats(agentDir: string) { // its chat stays closed from here until recoverChatDeletions finishes the job. const tombstones = new JsonStore(join(agentDir, "daemon-chat-deletions.json"), []); const interrupted = new Map void>(); - try { for (const id of new Set(readJson(tombstones.file, []))) interrupted.set(id, deletion.begin(id)); } - catch { process.stderr.write("aiden: Could not read unfinished chat deletions.\n"); } - const turns = new DaemonTurnOwner>({ admission, isDeleting: (id) => deletion.isDeleting(id) }); + // Without this record any chat may be one whose deletion committed, so all of them stay closed. + let deletionRecordFailure: Error | undefined; + try { + const ids = readJson(tombstones.file, []); + if (!Array.isArray(ids)) throw new Error(`${tombstones.file} is not a list.`); + for (const id of new Set(ids)) interrupted.set(id, deletion.begin(id)); + } catch (error) { + deletionRecordFailure = new Error(`Could not read unfinished chat deletions: ${error instanceof Error ? error.message : String(error)}`, { cause: error }); + } + const turns = new DaemonTurnOwner>({ admission, isDeleting: (id) => deletionRecordFailure !== undefined || deletion.isDeleting(id) }); const approvals = createDaemonApprovals({ raised: (prompt) => activity.requestAttention(prompt.approvalId, prompt.streamId, "approval"), resolved: (id, decision) => { recorders.recordRunAttentionResolved(runs, id, { kind: "approval", decision }); activity.resolveAttention(id); }, @@ -316,7 +323,10 @@ export function createDaemonChats(agentDir: string) { return { chatStore, llmClient, activity, runs, admission, deletion, sessionPath, /** Every activity change (a run began or ended, an approval was raised or settled). */ /** Finishes deletions a crash interrupted. Repeatable: a failure leaves its tombstone and its chat closed. */ + /** Unlike a deletion that fails to finish, a lost record cannot be scoped to its chats. */ + assertChatDeletionsReadable() { if (deletionRecordFailure) throw deletionRecordFailure; }, async recoverChatDeletions() { + if (deletionRecordFailure) throw deletionRecordFailure; for (const [id, reopen] of [...interrupted]) { await deleteCliBotSubagentHistory(agentDir, id); await rm(sessionPath(id), { force: true }); diff --git a/packages/cli/src/serve.ts b/packages/cli/src/serve.ts index c5db9e27fb..17b6a9c1f5 100644 --- a/packages/cli/src/serve.ts +++ b/packages/cli/src/serve.ts @@ -42,6 +42,7 @@ export async function serve(agentDir: string, signal: AbortSignal, options: { re async function serveOwned(agentDir: string, signal: AbortSignal, options: { remote?: boolean; onReady?: () => void }) { const runtime = createCliScheduler(agentDir); const chats = createDaemonChats(agentDir); + chats.assertChatDeletionsReadable(); // Every server finishes these, Remote or not. A failure keeps only those chats closed. await chats.recoverChatDeletions().catch((error: unknown) => { process.stderr.write(`aiden: Could not finish a chat deletion: ${error instanceof Error ? error.message : String(error)}\n`); }); const workspaceRuntime = createCliWorkspaceApplication(agentDir, { diff --git a/packages/cli/tests/daemon-turns.test.mjs b/packages/cli/tests/daemon-turns.test.mjs index 89a988de51..6d0b2507d8 100644 --- a/packages/cli/tests/daemon-turns.test.mjs +++ b/packages/cli/tests/daemon-turns.test.mjs @@ -527,6 +527,19 @@ test("an interrupted chat deletion blocks new turns and finishes when the server lease.settleAsyncWork(); lease.release(); }); +test("an unreadable deletion record closes every chat and refuses to start", async (t) => { + const dir = mkdtempSync(join(tmpdir(), "aiden-tombstones-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + writeFileSync(join(dir, "daemon-chat-deletions.json"), "{ not json"); + const daemon = api.createDaemonChats(dir); + t.after(() => daemon.stop()); + assert.equal(daemon.llmClient.beginChatTurn("maybe-deleted", "stream", "owner"), null, "any chat may be one whose deletion committed"); + await assert.rejects(daemon.recoverChatDeletions(), /deletion/u); + const controller = new AbortController(); + await assert.rejects(api.serve(dir, controller.signal, { remote: false }), /deletion/u); + assert.equal(existsSync(join(dir, "serve.lock")), false); +}); + test("a deletion that cannot finish keeps its chat closed without stopping the rest of the daemon", async (t) => { const f = await fixture(t), { dir, daemon, workspace } = f; await daemon.chatStore.create({ id: "stuck", title: "Stuck", workspaceId: workspace.id }); From 37fd8a80f805b3ef8712cc93ccac4377d7c4b68a Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 4 Nov 2026 20:44:32 -0500 Subject: [PATCH 09/12] Update the Lane D approval note Co-Authored-By: Claude Opus 5.5 --- .memory/explicit-state-machines-lane-d.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.memory/explicit-state-machines-lane-d.md b/.memory/explicit-state-machines-lane-d.md index 6105c21071..db40849988 100644 --- a/.memory/explicit-state-machines-lane-d.md +++ b/.memory/explicit-state-machines-lane-d.md @@ -14,4 +14,4 @@ Started 2026-11-04. Scope: `cli-native` C09, C10, C03, C01, C02, C11, C04, then - Cleanup hooks in `node:test` (`t.after`) run in registration order here, so stop a daemon before removing its directory. `box.stopServer` in `tests/serve-lifetime.test.mjs` does that; an earlier `t.after(serve stop)` orphaned real daemons. - The local shell is zsh: an unquoted `$files` is one argument, so a looped `node --test $files` silently runs nothing. Check that a pass count came back. - Control-socket chunks stop near 64 KiB, so a ceiling test needs a frame near the limit plus a later write, not one big write. -- Shared-owner note: a publish callback that settles its own approval is handled by Lane B's #738, not here. +- `createDaemonApprovals` reports each raised prompt once from the settled outcome, so it does not rely on the coordinator's published flag, on `main` or after Lane B's #738. From 0138204135831e1bad8c95f1376a7a4a388e6cc5 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 4 Nov 2026 20:48:23 -0500 Subject: [PATCH 10/12] Consume schedule consent at its first write The receipt survived until the command returned, so a process that died after publishing left it for a new scheduler to replay. It is now removed just before the first write publishes. Adds coverage of the follow-on phase. Co-Authored-By: Claude Opus 5.5 --- docs/state-machines/serve-daemon.md | 4 +- packages/cli/src/schedule-tool-approval.ts | 3 +- packages/cli/src/schedules.ts | 2 + packages/cli/tests/schedule-consent.test.mjs | 47 ++++++++++++++++++++ 4 files changed, 53 insertions(+), 3 deletions(-) diff --git a/docs/state-machines/serve-daemon.md b/docs/state-machines/serve-daemon.md index 5b81b10820..aa4f9d5e8f 100644 --- a/docs/state-machines/serve-daemon.md +++ b/docs/state-machines/serve-daemon.md @@ -155,11 +155,11 @@ Owner: `approvedMutation` in `createCliScheduler` (`schedules.ts`) over `assertS | Event | Prior | Next | Effect | |---|---|---|---| | command with consent | none | `first_write` | snapshot, expiry and receipt verified at entry | -| durable write verified | `first_write` | `follow_on` | task checked once; later writes check only the environment | +| durable write verified | `first_write` | `follow_on` | receipt consumed just before the write publishes, task checked once; later writes check only expiry and the environment | | verification fails | `first_write` or `follow_on` | `closed` | abort, so the shared lifecycle rolls back | | command ends | any | `closed` | this context is finished, and its receipt is spent | -A receipt is spent as the command starts and removed when it ends, so it works once even if the command fails, and another scheduler instance cannot replay it. A `save` must also read back the input that was reviewed, because the file is read after consent. +A receipt is spent in memory as the command starts, removed at the first write, and removed when the command ends if no write happened. It works once even if the command fails, and neither another scheduler nor a restart after a crash can replay it. A crash between that removal and the write loses the consent, so the person reviews again. Revocation holds up to the first write. A `save` must also read back the input that was reviewed, because the file is read after consent. **Defects fixed:** a `save` trusted whatever the file held by then, and a new-task consent could be replayed until it expired, since only the retired producer ever removed the receipt. diff --git a/packages/cli/src/schedule-tool-approval.ts b/packages/cli/src/schedule-tool-approval.ts index b25247486e..9a00cb7974 100644 --- a/packages/cli/src/schedule-tool-approval.ts +++ b/packages/cli/src/schedule-tool-approval.ts @@ -49,7 +49,8 @@ export function assertScheduleApproval(agentDir: string, approval: ScheduleToolA if (!Number.isFinite(approval.expiresAt) || Date.now() >= approval.expiresAt || !isScheduleMutation(approval.action)) { throw new Error("Scheduled-task approval expired. Review the task again."); } - if (!approval.approvalFile || readJson(approval.approvalFile, null) !== approval.snapshot) { + // The first write consumes the receipt, so it can only be checked up to there. + if (firstWrite && (!approval.approvalFile || readJson(approval.approvalFile, null) !== approval.snapshot)) { throw new Error("Scheduled-task approval was cancelled. Review the task again."); } const expected = JSON.parse(approval.snapshot) as Record; diff --git a/packages/cli/src/schedules.ts b/packages/cli/src/schedules.ts index bc882c5355..20dbe014a2 100644 --- a/packages/cli/src/schedules.ts +++ b/packages/cli/src/schedules.ts @@ -41,6 +41,8 @@ export function createCliScheduler(agentDir: string) { if (current && current.phase !== "closed") { try { assertScheduleApproval(agentDir, current.approval, current.phase === "first_write"); + // Consumed just before the write publishes: a crash after it cannot leave consent to replay. + if (current.phase === "first_write") rmSync(current.approval.approvalFile, { force: true }); } catch (error) { // A rejected mutation may rearm/restore the unchanged task, never reuse its consent. // Aborting lets the shared lifecycle roll back writes this mutation already made. diff --git a/packages/cli/tests/schedule-consent.test.mjs b/packages/cli/tests/schedule-consent.test.mjs index 0fe1517d0f..6355eda4db 100644 --- a/packages/cli/tests/schedule-consent.test.mjs +++ b/packages/cli/tests/schedule-consent.test.mjs @@ -98,3 +98,50 @@ test("consent revoked at the durable write stops the mutation and is not reused" api.JsonStore.prototype.update = update; assert.equal((await f.stored()).enabled, true); }); + +/** Runs `afterFirstWrite` inside the command, as soon as its first durable write has landed. */ +function afterFirstWrite(t, inspect) { + const update = api.JsonStore.prototype.update; + let done = false; + api.JsonStore.prototype.update = async function (mutation, isCurrent, replace) { + const result = await update.call(this, mutation, isCurrent, replace); + if (!done && this.file.endsWith("schedules.json")) { + done = true; + await inspect((nextIsCurrent = isCurrent) => update.call(this, () => {}, nextIsCurrent)); + } + return result; + }; + t.after(() => { api.JsonStore.prototype.update = update; }); +} + +test("a crash after the first write cannot leave consent to replay", async (t) => { + const f = await fixture(t), file = join(f.dir, "new.json"); + const reviewed = { name: "New", mode: "script", script: "true", cron: "0 9 * * *", timezone: "UTC", permission: "full", enabled: false, workspaceId: f.workspace.id }; + writeFileSync(file, JSON.stringify(reviewed)); + const approval = { cwd: f.dir, action: "save", input: reviewed, expiresAt: Date.now() + 60_000, approvalFile: join(f.dir, "crash.json") }; + approval.snapshot = api.scheduleApprovalSnapshot(f.dir, approval); + writeFileSync(approval.approvalFile, JSON.stringify(approval.snapshot)); + let replay; + afterFirstWrite(t, async () => { + // Everything a process that died here left on disk, seen by a new one. + replay = await api.createCliScheduler(f.dir).command(["save", file, JSON.stringify(approval)]).then(() => "saved", (error) => error.message); + }); + await f.scheduler.command(["save", file, JSON.stringify(approval)]); + assert.match(replay, /cancelled/u); + assert.equal((await f.scheduler.command(["list"])).filter((task) => task.name === "New").length, 1); +}); + +test("follow-on writes skip the task check but still lapse with the environment", async (t) => { + const f = await fixture(t), approval = f.consent("pause"); + let followOn, afterChange; + afterFirstWrite(t, async (write) => { + // The first write changed the task itself, which must not end the command's own consent. + followOn = await write().then(() => "written", (error) => error.message); + await api.workspaceCommand(f.dir, ["access", f.workspace.id, "ask"]); + afterChange = await write().then(() => "written", (error) => error.message); + }); + await f.run("pause", approval).catch(() => {}); + assert.equal(followOn, "written"); + assert.match(afterChange, /changed after approval/u); +}); + From 89590a8c9784200e72564fe96cb7404d8db9f496 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 4 Nov 2026 20:51:45 -0500 Subject: [PATCH 11/12] Treat a deletion record of non-ids as unreadable Co-Authored-By: Claude Opus 5.5 --- packages/cli/src/daemon-chats.ts | 2 +- packages/cli/tests/daemon-turns.test.mjs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/cli/src/daemon-chats.ts b/packages/cli/src/daemon-chats.ts index 1d1e650447..c4f238d6b7 100644 --- a/packages/cli/src/daemon-chats.ts +++ b/packages/cli/src/daemon-chats.ts @@ -78,7 +78,7 @@ export function createDaemonChats(agentDir: string) { let deletionRecordFailure: Error | undefined; try { const ids = readJson(tombstones.file, []); - if (!Array.isArray(ids)) throw new Error(`${tombstones.file} is not a list.`); + if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string")) throw new Error(`${tombstones.file} is not a list of chat ids.`); for (const id of new Set(ids)) interrupted.set(id, deletion.begin(id)); } catch (error) { deletionRecordFailure = new Error(`Could not read unfinished chat deletions: ${error instanceof Error ? error.message : String(error)}`, { cause: error }); diff --git a/packages/cli/tests/daemon-turns.test.mjs b/packages/cli/tests/daemon-turns.test.mjs index d8b913ac4d..1070e7c43d 100644 --- a/packages/cli/tests/daemon-turns.test.mjs +++ b/packages/cli/tests/daemon-turns.test.mjs @@ -548,10 +548,10 @@ test("an interrupted chat deletion blocks new turns and finishes when the server lease.settleAsyncWork(); lease.release(); }); -test("an unreadable deletion record closes every chat and refuses to start", async (t) => { +for (const [name, record] of [["malformed", "{ not json"], ["a non-list", "{}"], ["a list of non-ids", "[123]"]]) test(`a deletion record that is ${name} closes every chat and refuses to start`, async (t) => { const dir = mkdtempSync(join(tmpdir(), "aiden-tombstones-")); t.after(() => rmSync(dir, { recursive: true, force: true })); - writeFileSync(join(dir, "daemon-chat-deletions.json"), "{ not json"); + writeFileSync(join(dir, "daemon-chat-deletions.json"), record); const daemon = api.createDaemonChats(dir); t.after(() => daemon.stop()); assert.equal(daemon.llmClient.beginChatTurn("maybe-deleted", "stream", "owner"), null, "any chat may be one whose deletion committed"); From 09f48d701b89a8c71b97f938585c2baeb0e067ca Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 4 Nov 2026 21:00:32 -0500 Subject: [PATCH 12/12] Let a revocation win the race for the receipt Forced removal hid a receipt deleted just after the last check, so the write still published. A missing receipt now stops it. Co-Authored-By: Claude Opus 5.5 --- packages/cli/src/schedules.ts | 11 ++++++++-- packages/cli/tests/schedule-consent.test.mjs | 23 +++++++++++++++++++- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/packages/cli/src/schedules.ts b/packages/cli/src/schedules.ts index 20dbe014a2..71141c0e27 100644 --- a/packages/cli/src/schedules.ts +++ b/packages/cli/src/schedules.ts @@ -3,7 +3,7 @@ import { scheduledMcpServerBinding } from "../../../main/services/schedule-mcp-b import { storeFor } from "./mcp.ts"; import { runScheduledInference } from "./scheduled-inference.ts"; import { join } from "node:path"; -import { readFileSync, rmSync } from "node:fs"; +import { readFileSync, rmSync, unlinkSync } from "node:fs"; import { isDeepStrictEqual } from "node:util"; import { remoteDaemonCommand } from "./daemon-control.ts"; import { createHash } from "node:crypto"; @@ -42,7 +42,14 @@ export function createCliScheduler(agentDir: string) { try { assertScheduleApproval(agentDir, current.approval, current.phase === "first_write"); // Consumed just before the write publishes: a crash after it cannot leave consent to replay. - if (current.phase === "first_write") rmSync(current.approval.approvalFile, { force: true }); + // A receipt already gone was revoked since the check above, so this write may not publish. + if (current.phase === "first_write") { + try { unlinkSync(current.approval.approvalFile); } + catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") throw new Error("Scheduled-task approval was cancelled. Review the task again.", { cause: error }); + throw error; + } + } } catch (error) { // A rejected mutation may rearm/restore the unchanged task, never reuse its consent. // Aborting lets the shared lifecycle roll back writes this mutation already made. diff --git a/packages/cli/tests/schedule-consent.test.mjs b/packages/cli/tests/schedule-consent.test.mjs index 6355eda4db..3a8be64e28 100644 --- a/packages/cli/tests/schedule-consent.test.mjs +++ b/packages/cli/tests/schedule-consent.test.mjs @@ -1,7 +1,8 @@ // cli-native C15: a schedule mutation carrying consent is bound to what the // person reviewed, and is rechecked at the durable write. import assert from "node:assert/strict"; -import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import fs, { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { syncBuiltinESMExports } from "node:module"; import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; @@ -99,6 +100,26 @@ test("consent revoked at the durable write stops the mutation and is not reused" assert.equal((await f.stored()).enabled, true); }); +test("a revocation between the last check and consuming the receipt still stops the write", async (t) => { + const f = await fixture(t), approval = f.consent("pause"); + const { readFileSync } = fs, { update } = api.JsonStore.prototype; + let armed = false; + api.JsonStore.prototype.update = function (...args) { + if (this.file.endsWith("schedules.json")) armed = true; + return update.apply(this, args); + }; + fs.readFileSync = (path, ...args) => { + const value = readFileSync(path, ...args); + if (armed && path === approval.approvalFile) rmSync(path); + return value; + }; + syncBuiltinESMExports(); + t.after(() => { fs.readFileSync = readFileSync; api.JsonStore.prototype.update = update; syncBuiltinESMExports(); }); + await assert.rejects(f.run("pause", approval), /cancelled/u); + armed = false; + assert.equal((await f.stored()).enabled, true); +}); + /** Runs `afterFirstWrite` inside the command, as soon as its first durable write has landed. */ function afterFirstWrite(t, inspect) { const update = api.JsonStore.prototype.update;