diff --git a/.memory/explicit-state-machines-lane-d.md b/.memory/explicit-state-machines-lane-d.md index 90e35b6108..db40849988 100644 --- a/.memory/explicit-state-machines-lane-d.md +++ b/.memory/explicit-state-machines-lane-d.md @@ -8,3 +8,10 @@ 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. +- 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. +- `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. diff --git a/docs/state-machines/serve-daemon.md b/docs/state-machines/serve-daemon.md index c9560cf18d..aa4f9d5e8f 100644 --- a/docs/state-machines/serve-daemon.md +++ b/docs/state-machines/serve-daemon.md @@ -131,3 +131,63 @@ 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. The client closes on that frame, so a peer that keeps writing can neither grow its buffer nor keep it alive. **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 | +| 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. + +**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` | 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 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. + +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. | 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. 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/daemon-chats.ts b/packages/cli/src/daemon-chats.ts index 6396c86535..c4f238d6b7 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,7 +70,20 @@ export function createDaemonChats(agentDir: string) { const recorders = createHostRunRecorders((_scope, message) => process.stderr.write(`aiden: ${message}\n`)); const admission = new ChatTurnAdmission(); const deletion = new ChatDeletionGate(); - const turns = new DaemonTurnOwner>({ admission, isDeleting: (id) => deletion.isDeleting(id) }); + // 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>(); + // 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) || !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 }); + } + 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); }, @@ -310,6 +325,19 @@ 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 }); + 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/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/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/schedule-tool-approval.ts b/packages/cli/src/schedule-tool-approval.ts index dac10ae4fd..9a00cb7974 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"; @@ -43,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 7439474a71..71141c0e27 100644 --- a/packages/cli/src/schedules.ts +++ b/packages/cli/src/schedules.ts @@ -3,7 +3,8 @@ 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, unlinkSync } 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."); @@ -25,7 +26,11 @@ 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. + // 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 = { load: () => persistence.load(), @@ -33,17 +38,26 @@ 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"); + // Consumed just before the write publishes: a crash after it cannot leave consent to replay. + // 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. - current.active = false; + current.phase = "closed"; current.cancellation.abort(); throw error; } - current.firstWrite = false; + current.phase = "follow_on"; } return true; }); @@ -112,21 +126,26 @@ 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); - const current = { approval, active: true, firstWrite: true, cancellation: new AbortController() }; + 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))); } finally { // Cron callbacks can inherit this async context, but never its one-shot consent. - current.active = false; + 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(); - 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) { @@ -181,6 +200,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/src/serve.ts b/packages/cli/src/serve.ts index 97ffbd1d27..17b6a9c1f5 100644 --- a/packages/cli/src/serve.ts +++ b/packages/cli/src/serve.ts @@ -42,6 +42,9 @@ 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, { 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 4d435cd7d8..1070e7c43d 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"; @@ -519,6 +521,66 @@ 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(); +}); + +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"), 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"); + 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 }); + 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 }); diff --git a/packages/cli/tests/schedule-consent.test.mjs b/packages/cli/tests/schedule-consent.test.mjs new file mode 100644 index 0000000000..3a8be64e28 --- /dev/null +++ b/packages/cli/tests/schedule-consent.test.mjs @@ -0,0 +1,168 @@ +// 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 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"; +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 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); + 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) => { + 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), /already used/u); +}); + +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); +}); + +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; + 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); +}); +