diff --git a/.memory/explicit-state-machines-lane-d.md b/.memory/explicit-state-machines-lane-d.md new file mode 100644 index 0000000000..2119194d6d --- /dev/null +++ b/.memory/explicit-state-machines-lane-d.md @@ -0,0 +1,19 @@ +# Explicit state machines, Lane D: `aiden serve` owners + +Started 2026-11-04. Scope: `cli-native` C09, C10, C03, C01, C02, C11, C04, then triage of the other C entries. Worksheets: `docs/state-machines/serve-daemon.md`. + +- `feature/subagent-desktop-serve-upgrade` (uncommitted and local-only in `~/projects/aiden-agent`) rewrites `serve.ts`, `daemon-chats.ts` and `serve-lifecycle.ts`, and replaces the daemon approval map with `HeadlessInteractionHub`. Keep extracted logic in new files with small adapter edits so that branch merges cleanly. +- Pi's `extensionRunner.emit` catches handler errors, so a throwing `session_shutdown` handler cannot skip closers or usage in `perform`. +- A fresh worktree needs `build/native` for `tests/extensions.test.mjs`: copy `packages/cli/dist/app/native` after a CLI build. +- `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. +- The two `JsonStore` instances on `daemon-chat-deletions.json` (daemon `tombstones`, remote `deleting`) do not share a queue, and `acquireLease` throws on contention rather than waiting. That is safe only because daemon recovery finishes before Remote serves its first delete; keep that order. +- Under heavy host load `durable CLI Bots can message each other` in `tests/parity.test.mjs` can miss its 10-second reply deadline (seen 2026-11-06 at load 14, passes alone). The ledger showed the reply on its way, not lost. diff --git a/docs/state-machines/serve-daemon.md b/docs/state-machines/serve-daemon.md new file mode 100644 index 0000000000..aa4f9d5e8f --- /dev/null +++ b/docs/state-machines/serve-daemon.md @@ -0,0 +1,193 @@ +# `aiden serve` daemon state machines: transition worksheets + +Lane D of the explicit state-machine migration. These worksheets record how the `aiden serve` owners behave at this baseline so an extraction can be checked against them. IDs are `cli-native:Cnn` from the state-machine inventory. A ranking there is architectural priority, not a confirmed defect. A defect is named here only when a test reproduces it. + +Baseline: `bc663001f`. Oracles live in `packages/cli/tests/daemon-turns.test.mjs` (C09, C10, C11) and `packages/cli/tests/serve-lifetime.test.mjs` (C03, C04, real processes), plus the existing `tests/parity.test.mjs` lifecycle cases and `tests/runtime.test.mjs`. + +Local baseline before any extraction: every CLI suite passes. A fresh worktree first fails one `tests/extensions.test.mjs` case that evaluates `src/` directly, because `build/native/aiden-lease-flock` does not exist until the native helpers are built. That is checkout state, not a product failure. + +## C09: daemon turn admission and handoff + +Owner: `DaemonTurnOwner` in `packages/cli/src/daemon-turn-lifecycle.ts`, over the shared `ChatTurnAdmission`, whose axes (authority, preparation) it reuses. It is the single writer of per-chat custody. `isChatBusy`, capacity, idle waits and shutdown all read that one map. + +Custody is `lease` (with preparation `pending` or `settled`), `settling` (revoked, admitted work still running), `generation`, or idle. Intake is `open` or `closed`. + +| Event | Prior custody | Guard | Next | Effect | Linearization point | Visible result | +|---|---|---|---|---|---|---| +| `beginChatTurn` | idle | intake open, chat not deleting, fewer than 3 chats in `lease` or `generation`, admission accepts | `lease`, `pending` | lease with 60 s expiry | `admission.tryBegin` | lease | +| `beginChatTurn` | anything else, or a guard fails | | unchanged | none | | `null` | +| `settleAsyncWork` | `lease`, `pending` | same lease | `lease`, `settled` | wakes idle waiters | | | +| `settleAsyncWork` | `settling` | same lease | idle | wakes idle waiters | | | +| lease release or expiry, `cancelChat` | `lease`, `settled` | same lease | idle | frees the slot | `lease.release` | | +| lease release or expiry, `cancelChat` | `lease`, `pending` | same lease | `settling`: no capacity, chat still busy, shutdown waits | | `lease.release` | later `start` refuses | +| `start` | `lease`, `settled` | intake open, owner live, same chat, turn and owner | `generation` | session-file lease, then `handoff` registers custody, activity and run journal, then releases the lease | `admission.handoff`, one synchronous step | `true` | +| `start` | anything else | | unchanged | session-file lease released if taken | | `false`, no event | +| generation released | `generation` | same run | idle | run's `settled` resolves | `turns.release` | | +| `stop` | any | | intake closed | revokes every lease, cancels with `application_shutdown`, waits for every held chat | `closeIntake`, before the first await | `beginChatTurn` and `start` refuse | + +A lease or run whose chat has moved on to a newer entry changes nothing. Stale events are dropped by entry identity. + +Capacity stays as it was: a `settling` chat takes no slot, because it can start nothing. Its bytes stay charged in `ChatTurnAdmission`. + +Retained: `ChatTurnAdmission` and `ChatDeletionGate` are the shared owners. Lane A owns their internals. + +## C10: daemon generation execution and persistence + +Owner: `DaemonGenerationRun` in `daemon-turn-lifecycle.ts`, driven by `perform` in `daemon-chats.ts`. + +| Stage | Entered by | Stop request | Failure | Terminal | +|---|---|---|---|---| +| preparing (chat, Bot authority, workspace, runtime, extensions) | `start` | seen at the next `assertAuthority` | `chat:error`, no answer saved | `failed` or `cancelled` | +| session bound | `createAgentSession` | session abort | same | same | +| prompting and tools | `session.prompt` | session abort, approval lapses | partial answer saved once when any text or message exists | same | +| final save | prompt ended with a final assistant message | not observed, the save completes | save failure: `chat:error`, then one retry as the partial answer | `completed` only once `appendMessage` returned | +| cleanup | always | | handler errors stay contained: Pi's `emit` catches them | `session_shutdown`, dispose, closers, usage | +| released | `perform` settled | | each cleanup step runs whatever an earlier one threw | custody cleared, activity settled, run journal settled, session-file lease released, `settled` resolved | + +Independent axes: stop request (`requestStop`, with its first origin), terminal persistence (`none`, `final_saved`, `partial_saved`, `partial_lost`), client delivery, physical release. `chat:done` is sent after the durable save and before cleanup, so a chat stays busy briefly after `chat:done`. A timeout or lost owner is a stop with no origin. + +## Defects fixed during extraction + +Each has a reproduction in `packages/cli/tests/daemon-turns.test.mjs` that failed before its fix. + +- **Shutdown did not wait for revoked work.** `stop()` listed only live leases and running generations. A cancelled or expired reservation whose append was still in flight was dropped from the list, so the process could exit under the write. +- **A stop during a Bot authority check did not stop the prompt.** The Bot branch of `assertAuthority` returned straight after its awaited revalidation. A stop landing there let `session.prompt` run: the session abort had already come and gone, and Pi contains the `before_agent_start` rejection, so a provider request went out. The tool path had the same gap. +- **A failed session-lease removal hung idle waiters.** An exception in `release` skipped resolving `settled`, so `waitForChatIdle` and shutdown never returned. +- **A throwing activity listener reported idle with the session lease held.** One `try` covered activity, run journal and lease removal, so a listener that threw skipped the other two while `settled` still resolved. The next turn on that chat then failed to take its lease. Each step now runs on its own. +- **A run that failed to register held the chat forever.** If `activity.begin` or the run journal threw inside `handoff`, custody stayed `generation` with a run that nothing would ever start or release, so the chat stayed busy and `stop()` hung. `start` now returns the chat and rethrows. +- **A failed final save was recorded as completed.** The projector had already closed as `completed`, so `finish("failed")` changed nothing, and both `chat:error` and the retried message carried a `completed` timeline. Both now say `failed`. The transient `chat:timeline` event sent as the projector closed still says `completed`, because the projector is a shared owner. + +## C11: daemon tool approval + +Owner: the shared `ToolApprovalCoordinator` (`main/services/tool-approval.ts`, Lane B's), which holds one-shot settlement, owner scoping and abort. `packages/cli/src/daemon-approvals.ts` adapts it and adds only the 300 s expiry, the `approval_` id and the journal decision. The `tool_call` handler in `daemon-chats.ts` keeps the grant recheck. `full` runs with no prompt, `none` blocks, `ask` prompts. Bot tools follow the capability grant instead. + +| Event | Prior | Guard | Next | Effect | Visible result | +|---|---|---|---|---|---| +| tool call, `ask` | | arguments at most 1,700 bytes, run not stopping | pending | registered, expiry armed, attention raised | `chat:approval` | +| publish throws | pending | | unavailable | attention withdrawn | tool blocked | +| owner answer | pending | same owner | allowed or denied | journal records the decision, attention withdrawn | `approve` returns `true` | +| host answer | pending | `runs:control` at the caller | allowed or denied | same | `approveAsHost` returns `true` | +| any answer | not pending, or another owner | | unchanged | none | `false` | +| expiry | pending | | expired | journal records `expired` | tool blocked | +| turn abort | pending | | cancelled | journal records `cancelled` | tool blocked | +| grant recheck | allowed | authority current, arguments unchanged, access not `none` | dispatched | tool runs | `chat:tool` result | +| grant recheck | allowed | any check fails | blocked | none | model hears the refusal | + +The adapter reports each raised prompt once, from the outcome the coordinator settled it with, so it does not depend on the coordinator having seen the publish finish. That covers a publish that settles its own prompt, a publish that then throws, and a `raised` that throws. + +Linearization: the grant is checked again after the wait, so a late `allow` cannot outrun a revocation. The generation's own 300 s timer starts first, so in practice it ends a waiting prompt as `cancelled` before that prompt's expiry can fire. + +## C03: serve admission and resource lifetime + +Owners: `ServeLifetime` in `packages/cli/src/serve-lifetime.ts` for the control socket's phase and accepted commands, driven by `serve` and `serveOwned` in `packages/cli/src/serve.ts`. + +| Phase | Entered by | Control socket | Chat admission | Leaves when | +|---|---|---|---|---| +| lease held | `acquireLease` | absent | none yet | a throw releases the lease | +| `starting` | Remote, socket, scheduler, Telegram | answers once bound | open | ready, failure or a signal, into draining | +| `serving` | `markServing`, before `onReady` | answers | open | signal | +| `draining`: ingress closed | `beginDrain` | refuses new connections and commands | `chats.stop()` closes it synchronously | | +| `draining`: services | `Promise.allSettled` of chats, Bots, Telegram, Remote, scheduler | accepted commands keep running | closed | all settled | +| `draining`: commands | `settleCommands` | clients destroyed only afterwards | closed | every accepted command answered and its reply flushed, or its client gone | +| released | socket removed, MCP recording stopped, lease released | absent | closed | process exit | + +Order matters in two places: `chats.stop()` runs first so no other stopping ingress can begin a turn, and every accepted command settles before the lease is released. A hung command therefore holds shutdown: `aiden serve stop` escalates to KILL at its deadline, and a second signal ends a foreground server. + +A signal in `starting` drains the socket at once and skips every later startup step, without reporting ready. A step already running finishes first, so one that never settles is ended by `aiden serve stop` at its deadline. + +**Defect fixed:** a signal during startup was not seen until all of startup had finished. The socket kept taking commands, the scheduler and Telegram still started, and `onReady` still fired. + +**Defect fixed:** an accepted command was not tracked, so shutdown destroyed its client and released the lease while it was still changing state. The client saw `Daemon closed without a response`, and the write could land with no owner. Reproduced in `tests/serve-lifetime.test.mjs`. + +## C01 and C02: daemon ownership, startup, shutdown and stale recovery + +Owner: `packages/cli/src/serve-lifecycle.ts`, over `acquireLease` (`state.ts`). Covered by the `tests/parity.test.mjs` lifecycle cases: stale `flock-v1` metadata, legacy live owners, recycled PIDs, lease replacement during stop, forced stop with and without a detached group, recorded MCP groups, and failed startup. + +Start: start lease, recover stale lease, refuse when running, spawn, poll until the socket answers and `owner.pid` is the spawned PID, or TERM, wait 2 s, KILL the group. + +Stop decisions are pure tables in `packages/cli/src/serve-ownership.ts`. Signals, polling and cleanup stay in `serve-lifecycle.ts`. Startup stays there too: it is one linear path under its start lease, so a machine would add nothing. + +| When | Observed | Decision | +|---|---|---| +| Before signalling | `daemon` | TERM, then poll | +| | `gone` or `foreign` | clear artifacts under the guard, report `not running` | +| | `aiden` | refuse: a one-shot command holds the lock | +| | `unknown` | refuse: nothing can verify it | +| While polling | lease gone or owner changed | stopped | +| | PID gone, or `foreign` on the periodic check | clear artifacts, stopped | +| At the deadline | owner changed | stopped: a replacement is not the daemon asked to stop | +| | same owner, `daemon` | KILL (its group only when `detached` and it leads the group) plus recorded MCP groups, then wait for `pidAlive` to confirm exit | +| | same owner, `gone` or `foreign` | clear artifacts, stopped | +| | same owner, `aiden` or `unknown` | report that the stop is unconfirmed, keep the lock, and advise no signal | + +Evidence of exit is `pidAlive`, never the signal. + +**Defect fixed:** the periodic `foreign` check ran only every tenth poll, so a PID that stopped being ours just before the deadline fell through to `did not stop ... try kill -9 `, sending the person to kill an unrelated process. Reproduced in `tests/serve-lifetime.test.mjs` with a process that `exec`s into something else. + +## C04: local daemon command framing + +Owners: `remoteDaemonCommand` (`daemon-control.ts`) and the socket handler in `serve.ts`. One request per connection, framed by a newline, 64 KiB request ceiling, 8 MiB response ceiling, UTF-8 decoded across chunks. The client settles once for result, error, closed without a frame, oversized reply and transport error. It is a stream parser, not a product mode. Retained as it was, with no state model: that would add nothing to a one-shot parser. + +**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 428d81087f..cbf3e424c3 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. @@ -62,7 +62,7 @@ When `aiden serve` runs in the foreground in an interactive terminal, it prints | `aiden remote devices`, `remote revoke ` | List or revoke paired devices. Revoking a device closes its open Bot session streams before the command returns. | | `aiden remote roots`, `remote approve-root ` | Folders that paired devices may open | -**Stopping.** Once shutdown starts, the server takes no new connections, requests or chat turns, cancels running ones and drains. `aiden serve stop` force-kills a server still running 15 seconds after SIGTERM, after checking the PID is still that server: a `--daemon` server together with its process group (its Remote advertiser), a foreground `aiden serve` on its own so the rest of its shell job (`aiden serve | tee`) survives. Either way, its stdio MCP servers (each in a process group of its own, recorded in the lease directory) are killed too, but only groups that still contain a process the server started. A foreground server logs a stray unhandled rejection instead of exiting. Aiden commands exit 0 quietly when their reader closes early (`aiden schedule list | head -1`). +**Stopping.** Once shutdown starts, the server takes no new connections, requests or chat turns, cancels running ones and drains. Control commands it already accepted finish and get their reply first. A stop during startup ends startup at the next step. `aiden serve stop` force-kills a server still running 15 seconds after SIGTERM, after checking the PID is still that server: a `--daemon` server together with its process group (its Remote advertiser), a foreground `aiden serve` on its own so the rest of its shell job (`aiden serve | tee`) survives. Either way, its stdio MCP servers (each in a process group of its own, recorded in the lease directory) are killed too, but only groups that still contain a process the server started. A foreground server logs a stray unhandled rejection instead of exiting. Aiden commands exit 0 quietly when their reader closes early (`aiden schedule list | head -1`). `remote` and `bots` commands talk to the running server over its control socket and fail if it is not running. `schedule` and `workspace` commands also work without the server, through a one-shot lease. `telegram status` works anytime; `telegram connect|configure|disable|disconnect` take the server's lease, so stop `aiden serve` before changing Telegram configuration. diff --git a/packages/cli/package.json b/packages/cli/package.json index 514108118c..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", + "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-approvals.ts b/packages/cli/src/daemon-approvals.ts new file mode 100644 index 0000000000..515b2af362 --- /dev/null +++ b/packages/cli/src/daemon-approvals.ts @@ -0,0 +1,68 @@ +/** + * The daemon's tool approvals, on the shared `ToolApprovalCoordinator` that owns + * one-shot settlement, owner scoping and abort. This adds what is the daemon's: + * the prompt's expiry and the decision its run journal records. + * See docs/state-machines/serve-daemon.md. + */ +import { randomUUID } from "node:crypto"; +import { ToolApprovalCoordinator, type ToolApprovalOutcome, type ToolApprovalPrompt } from "../../../main/services/tool-approval.js"; + +export type DaemonApprovalDecision = "allow" | "deny" | "expired" | "cancelled"; + +interface OpenPrompt { + publish(prompt: ToolApprovalPrompt): void; + expiry: AbortController; + raised: boolean; + reported: boolean; +} + +export interface DaemonApprovalsOptions { + /** A prompt is about to reach its owner. */ + raised(prompt: ToolApprovalPrompt): void; + /** A raised prompt ended, however it ended. */ + resolved(approvalId: string, decision: DaemonApprovalDecision): void; + expiryMs?: number; +} + +export function createDaemonApprovals(options: DaemonApprovalsOptions) { + const open = new Map(); + const decisionFor = (outcome: ToolApprovalOutcome, prompt?: OpenPrompt): DaemonApprovalDecision => { + if (outcome === "allowed") return "allow"; + if (outcome === "denied") return "deny"; + return prompt?.expiry.signal.aborted ? "expired" : "cancelled"; + }; + /** One report per raised prompt, from the outcome that settled it. */ + const report = (approvalId: string, outcome: ToolApprovalOutcome, prompt?: OpenPrompt) => { + if (!prompt?.raised || prompt.reported) return; + prompt.reported = true; + options.resolved(approvalId, decisionFor(outcome, prompt)); + }; + const coordinator = new ToolApprovalCoordinator( + (prompt) => { + const entry = open.get(prompt.approvalId); + // Marked first: a `raised` that throws may already have changed attention. + if (entry) entry.raised = true; + options.raised(prompt); + entry?.publish(prompt); + }, + (approvalId, outcome) => { report(approvalId, outcome, open.get(approvalId)); }, + ); + return { + /** Waits for one answer. `publish` delivers the prompt to this run's owner. */ + async request(descriptor: Omit, signal: AbortSignal, ownerId: string, publish: OpenPrompt["publish"]): Promise { + const approvalId = `approval_${randomUUID()}`, expiry = new AbortController(); + const timer = setTimeout(() => expiry.abort(), options.expiryMs ?? 300_000); + const prompt: OpenPrompt = { publish, expiry, raised: false, reported: false }; + open.set(approvalId, prompt); + try { + const outcome = await coordinator.request({ ...descriptor, approvalId }, AbortSignal.any([signal, expiry.signal]), ownerId); + // The coordinator withdraws only what it saw published, so a failed or re-entrant publish lands here. + report(approvalId, outcome, prompt); + return outcome; + } finally { clearTimeout(timer); open.delete(approvalId); } + }, + approve: (id: string, decision: "allow" | "deny", ownerId: string) => coordinator.decide(id, decision === "allow", ownerId), + /** A paired desktop holding `runs:control` answers any run's approval, as the desktop host's own controls do. */ + approveAsHost: (id: string, decision: "allow" | "deny") => coordinator.decideAsHost(id, decision === "allow"), + }; +} diff --git a/packages/cli/src/daemon-chats.ts b/packages/cli/src/daemon-chats.ts index a538f31c59..cd8f0eb023 100644 --- a/packages/cli/src/daemon-chats.ts +++ b/packages/cli/src/daemon-chats.ts @@ -10,7 +10,8 @@ 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 { createHash, randomUUID } from "node:crypto"; +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"; import type { AssistantMessage } from "@earendil-works/pi-ai"; @@ -26,7 +27,10 @@ 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"; import { recordUsage } from "./usage-ledger.ts"; import { messageText } from "./sessions.ts"; @@ -66,93 +70,91 @@ 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 active = new Map; finish(): void; release(): void }>(); - const reserved = new Set(); - const idleWaiters = new Map void>>(); - const wakeIdle = (id: string) => { for (const wake of idleWaiters.get(id) ?? []) wake(); idleWaiters.delete(id); }; - const approvals = new Map(); - const settleApproval = (id: string, decision: "allow" | "deny", ownerId?: string) => { - const pending = approvals.get(id); if (!pending || (ownerId !== undefined && pending.ownerId !== ownerId)) return false; - recorders.recordRunAttentionResolved(runs, id, { kind: "approval", decision }); - approvals.delete(id); pending.resolve(decision === "allow"); return true; - }; - // Set once shutdown begins: no ingress (phone, Telegram, socket, Bot) may start a turn while it drains. - let closed = false; + // 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); }, + }); const sessionPath = (id: string) => join(root, "journals", `${createHash("sha256").update(id).digest("hex")}.jsonl`); const llmClient = { - beginChatTurn(chatId: string, streamId: string, ownerId: string) { - if (closed || deletion.isDeleting(chatId) || new Set([...reserved, ...active.keys()]).size >= 3) return null; - const lease = admission.tryBegin(chatId, streamId, ownerId, active.has(chatId)); - if (lease) { - reserved.add(chatId); - lease.onReleased(() => { reserved.delete(chatId); queueMicrotask(() => wakeIdle(chatId)); }); - const settle = lease.settleAsyncWork; - lease.settleAsyncWork = () => { settle(); wakeIdle(chatId); }; - } - return lease; - }, - isChatBusy: (id: string) => active.has(id) || admission.isAdmitted(id), - async waitForChatIdle(id: string) { - while (active.has(id) || admission.isAdmitted(id)) { - const running = active.get(id); - if (running) await running.settled; - else await new Promise((resolve) => { - const waiters = idleWaiters.get(id) ?? new Set(); waiters.add(resolve); idleWaiters.set(id, waiters); - }); - } - return true; - }, + beginChatTurn: (chatId: string, streamId: string, ownerId: string) => turns.begin(chatId, streamId, ownerId), + isChatBusy: (id: string) => turns.isBusy(id), + async waitForChatIdle(id: string) { await turns.waitForIdle(id); return true; }, /** Stops the chat's turn; the first stop's origin is what its timeline records, as on the desktop. */ async cancelChat(id: string, origin: GenerationCancellationOrigin = "chat_deletion") { - admission.releaseChat(id); const entry = active.get(id); - if (entry && !entry.abort.signal.aborted) entry.cancellationOrigin ??= origin; - entry?.abort.abort(); await entry?.session?.abort(); + admission.releaseChat(id); await turns.run(id)?.requestStop(origin); }, /** A Bot the person paused: its reply ends as their Stop, and the chat is kept. */ async stopChatWork(id: string) { await llmClient.cancelChat(id, "user_stop"); return llmClient.waitForChatIdle(id); }, - approve: (id: string, decision: "allow" | "deny", ownerId: string) => settleApproval(id, decision, ownerId), - /** A paired desktop holding `runs:control` answers any run's approval, as the desktop host's own controls do. */ - approveAsHost: (id: string, decision: "allow" | "deny") => settleApproval(id, decision), + approve: approvals.approve, + approveAsHost: approvals.approveAsHost, cancel(streamId: string, ownerId: string) { - const pair = [...active.entries()].find(([, entry]) => entry.streamId === streamId && entry.ownerId === ownerId); - if (!pair) return false; - void llmClient.cancelChat(pair[0], "user_stop").catch(() => {}); return true; + const found = turns.findRun((run) => run.streamId === streamId && run.ownerId === ownerId); + if (!found) return false; + void llmClient.cancelChat(found.chatId, "user_stop").catch(() => {}); return true; }, /** Stop a run by its stream id whoever started it (`runs:control`). */ cancelRun(streamId: string) { - const pair = [...active.entries()].find(([, entry]) => entry.streamId === streamId); - if (!pair) return false; - void llmClient.cancelChat(pair[0], "user_stop").catch(() => {}); return true; + const found = turns.findRun((run) => run.streamId === streamId); + if (!found) return false; + void llmClient.cancelChat(found.chatId, "user_stop").catch(() => {}); return true; }, async start(streamId: string, params: ChatStartParams, owner: ChatGenerationOwner, options: { usageSource: UsageRequestSource; turnId?: string; botAudienceId?: string; onTurnAccepted?(): void }) { - if (closed || owner.isDestroyed() || !admission.owns(params.chatId, options.turnId ?? streamId, owner.documentId)) return false; - let finish!: () => void; - const settled = new Promise((resolve) => { finish = resolve; }); + if (!turns.accepting || owner.isDestroyed() || !admission.owns(params.chatId, options.turnId ?? streamId, owner.documentId)) return false; let releaseFile: () => void; try { releaseFile = acquireLease(sessionPath(params.chatId)); } catch (error) { admission.releaseMatching(params.chatId, options.turnId ?? streamId, owner.documentId); throw error; } - const entry = { streamId, ownerId: owner.documentId, workspaceId: params.workspaceId, abort: new AbortController(), settled, finish, - session: undefined as AgentSession | undefined, - release() { if (active.get(params.chatId) !== entry) return; active.delete(params.chatId); activity.settle(streamId); recorders.recordRunSettled(runs, streamId); releaseFile(); finish(); wakeIdle(params.chatId); }, + const entry = new DaemonGenerationRun({ streamId, ownerId: owner.documentId, workspaceId: params.workspaceId }); + // Each step runs whatever an earlier one threw: idle waiters and shutdown read `settled` as all of them. + const cleanUp = () => { + const failures: unknown[] = []; + for (const step of [() => activity.settle(streamId), () => recorders.recordRunSettled(runs, streamId), releaseFile]) { + try { step(); } catch (error) { failures.push(error); } + } + entry.markReleased(); + if (failures.length) throw failures[0]; }; - const handedOff = admission.handoff(params.chatId, options.turnId ?? streamId, owner.documentId, () => { active.set(params.chatId, entry); activity.begin(streamId, params.chatId); recorders.recordRunBegin(runs, streamId, params.chatId, owner); }); + const release = () => { if (turns.release(params.chatId, entry)) cleanUp(); }; + let handedOff: boolean; + try { + handedOff = turns.handoff(params.chatId, options.turnId ?? streamId, owner.documentId, entry, () => { activity.begin(streamId, params.chatId); recorders.recordRunBegin(runs, streamId, params.chatId, owner); }); + } catch (error) { + // Registration failed partway, so nothing will ever run or release this entry. + turns.release(params.chatId, entry); + admission.releaseMatching(params.chatId, options.turnId ?? streamId, owner.documentId); + try { cleanUp(); } catch { /* The registration failure is the one to report. */ } + throw error; + } if (!handedOff) { releaseFile(); return false; } - void perform(streamId, params, owner, options, entry).finally(entry.release).catch(() => { + void perform(streamId, params, owner, options, entry).finally(release).catch(() => { process.stderr.write("aiden: Could not deliver the terminal generation event.\n"); }); return true; }, }; - async function perform(streamId: string, params: ChatStartParams, owner: ChatGenerationOwner, options: { usageSource: UsageRequestSource; turnId?: string; botAudienceId?: string; onTurnAccepted?(): void }, entry: NonNullable>) { + async function perform(streamId: string, params: ChatStartParams, owner: ChatGenerationOwner, options: { usageSource: UsageRequestSource; turnId?: string; botAudienceId?: string; onTurnAccepted?(): void }, entry: DaemonGenerationRun) { let unsubscribe = () => {}; let botAdmission: BotRuntimeAuthorityAdmission | undefined; let removeBotAbort = () => {}; - const disposeOwner = owner.onInvalidated(() => { entry.abort.abort(); void entry.session?.abort().catch(() => {}); }); - const timer = setTimeout(() => { entry.abort.abort(); void entry.session?.abort().catch(() => {}); }, 300_000); + const disposeOwner = owner.onInvalidated(() => entry.requestStopQuietly()); + const timer = setTimeout(() => entry.requestStopQuietly(), 300_000); // Every event also feeds the run journal, so a paired desktop sees the run even after its owner leaves. const send: typeof owner.send = (channel, payload) => { recorders.recordRunNotification(runs, streamId, channel, payload); if (!owner.isDestroyed()) owner.send(channel, payload); }; const produced: AssistantMessage[] = []; - let content = "", separator = false, persisted = false; + let content = "", separator = false; const timeline = new GenerationTimelineProjector(streamId, (value) => send("chat:timeline", { streamId, timeline: value })); // Extensions open their resources (MCP pool, memory store) before the session exists; a turn that // fails before then still runs their shutdown handlers and closers. @@ -167,7 +169,7 @@ export function createDaemonChats(agentDir: string) { await bots.assertNotPaused(chat.botId); botAdmission = await bots.authority.admit({ audienceId: options.botAudienceId, botId: chat.botId, chatId: chat.id }); assertBotRuntimeProviderSelection(botAdmission.authority.provider, { providerId: params.providerId, model: params.model }); - const cancel = () => { entry.abort.abort(); void entry.session?.abort().catch(() => {}); }; + const cancel = () => entry.requestStopQuietly(); botAdmission.signal.addEventListener("abort", cancel, { once: true }); removeBotAbort = () => botAdmission?.signal.removeEventListener("abort", cancel); if (botAdmission.signal.aborted) cancel(); @@ -178,10 +180,12 @@ export function createDaemonChats(agentDir: string) { if (unattended && (!workspace.folderPath || accessFor(agentDir, workspace.folderPath) !== "full")) throw new Error("Unattended generation requires explicitly granted full workspace access."); const cwd = workspace.folderPath || root; const assertAuthority = async () => { - if (entry.abort.signal.aborted || owner.isDestroyed()) throw new Error("Generation authority was revoked."); - if (botAdmission) { await botAdmission.revalidateBeforeEffect(); return; } + const assertNotStopped = () => { if (entry.stopRequested || owner.isDestroyed()) throw new Error("Generation authority was revoked."); }; + assertNotStopped(); + // A stop can land during this await, and the next step may be the provider request. + if (botAdmission) { await botAdmission.revalidateBeforeEffect(); assertNotStopped(); return; } const current = (await workspaceStore(agentDir).load()).find((item) => item.id === workspace.id); - if (entry.abort.signal.aborted || owner.isDestroyed() || current?.folderPath !== workspace.folderPath || (unattended && accessFor(agentDir, cwd) !== "full")) throw new Error("The unattended workspace authority was revoked."); + if (entry.stopRequested || owner.isDestroyed() || current?.folderPath !== workspace.folderPath || (unattended && accessFor(agentDir, cwd) !== "full")) throw new Error("The unattended workspace authority was revoked."); }; const runtime = await createCliModelRuntime(agentDir); const model = runtime.getModel(params.providerId, params.model); @@ -243,22 +247,10 @@ export function createDaemonChats(agentDir: string) { const original = JSON.stringify(event.input); if (Buffer.byteLength(original) > 1_700) return { block: true, reason: "The tool request exceeds the remote approval display budget." }; timeline.toolAwaitingApproval(event.toolCallId); - const approvalId = `approval_${randomUUID()}`; - const allowed = await new Promise((resolve) => { - const settle = (result: boolean) => { clearTimeout(expiry); entry.abort.signal.removeEventListener("abort", cancel); approvals.delete(approvalId); activity.resolveAttention(approvalId); resolve(result); }; - const lapse = (decision: "expired" | "cancelled") => { if (approvals.has(approvalId)) recorders.recordRunAttentionResolved(runs, approvalId, { kind: "approval", decision }); settle(false); }; - const cancel = () => lapse("cancelled"); - const expiry = setTimeout(() => lapse("expired"), 300_000); - approvals.set(approvalId, { ownerId: owner.documentId, resolve: settle }); - entry.abort.signal.addEventListener("abort", cancel, { once: true }); - if (entry.abort.signal.aborted) cancel(); - else { - activity.requestAttention(approvalId, streamId, "approval"); - send("chat:approval", { streamId, approvalId, toolCallId: event.toolCallId, toolName: event.toolName, summary: daemonApprovalSummary(event.toolName, event.input) }); - } - }); + const outcome = await approvals.request({ streamId, toolCallId: event.toolCallId, toolName: event.toolName, summary: daemonApprovalSummary(event.toolName, event.input) }, entry.abort.signal, owner.documentId, + ({ approvalId, toolCallId, toolName, summary }) => send("chat:approval", { streamId, approvalId, toolCallId, toolName, summary })); await assertAuthority(); - if (!allowed || JSON.stringify(event.input) !== original || accessFor(agentDir, cwd) === "none") return { block: true, reason: "The tool request was denied, changed or expired." }; + if (outcome !== "allowed" || JSON.stringify(event.input) !== original || accessFor(agentDir, cwd) === "none") return { block: true, reason: "The tool request was denied, changed or expired." }; } catch (error) { return { block: true, reason: error instanceof Error ? error.message : String(error) }; } }); } }], @@ -298,20 +290,24 @@ export function createDaemonChats(agentDir: string) { const text = [input.content, ...attachments.filter((item) => item.kind === "image" && !model.input.includes("image")).map((item) => `Attached image: ${visionAttachmentAlias(item)} (${item.name}). Use inspect_image to analyze it.`), ...attachments.filter((item) => item.kind === "text").map((item) => `Attachment: ${item.name}\n${item.text ?? ""}`)].join("\n\n"); await assertAuthority(); await session.prompt(text, { expandPromptTemplates: false, preflightResult: (accepted) => { if (accepted) options.onTurnAccepted?.(); }, images: (model.input.includes("image") ? attachments : []).flatMap((item) => item.kind === "image" && item.data ? [{ type: "image" as const, data: item.data, mimeType: item.mimeType }] : []) }); - if (entry.abort.signal.aborted) throw new Error("Generation cancelled."); + if (entry.stopRequested) throw new Error("Generation cancelled."); const last = produced.at(-1); if (!last || last.stopReason === "error" || last.stopReason === "aborted") throw new Error(last?.errorMessage ?? "Generation returned no final answer."); content ||= produced.map((message) => messageText(message.content)).filter(Boolean).join("\n"); const finalTimeline = timeline.finish("completed"); const updated = await chatStore.appendMessage(params.chatId, { role: "assistant", content, timeline: finalTimeline }, { providerId: model.provider, model: model.id }); - persisted = true; + entry.persistence = "final_saved"; send("chat:done", { streamId, content, chat: updated, timeline: finalTimeline }); return true; } catch (error) { - const cancelled = entry.abort.signal.aborted; - const finalTimeline = cancelled ? timeline.finish("cancelled", entry.cancellationOrigin) : timeline.finish("failed"); - if (!persisted && (content || produced.length)) { - await chatStore.appendMessage(params.chatId, { role: "assistant", content, timeline: finalTimeline }).catch(() => { + const cancelled = entry.stopRequested; + const finished = cancelled ? timeline.finish("cancelled", entry.cancellationOrigin) : timeline.finish("failed"); + // A failed final save already closed the projector as completed, but this turn did not complete. + const finalTimeline = finished.status !== "completed" ? finished + : { ...finished, status: cancelled ? "cancelled" as const : "failed" as const, ...(cancelled && entry.cancellationOrigin ? { cancellationOrigin: entry.cancellationOrigin } : {}) }; + if (entry.persistence === "none" && (content || produced.length)) { + entry.persistence = await chatStore.appendMessage(params.chatId, { role: "assistant", content, timeline: finalTimeline }).then(() => "partial_saved" as const, () => { process.stderr.write("aiden: Could not persist the partial response.\n"); + return "partial_lost" as const; }); } send("chat:error", { streamId, message: error instanceof Error ? error.message : String(error), cancelled, timeline: finalTimeline }); return true; @@ -328,9 +324,23 @@ export function createDaemonChats(agentDir: string) { } } return { chatStore, llmClient, activity, runs, admission, deletion, sessionPath, + /** Unlike a deletion that fails to finish, a lost record cannot be scoped to its chats. */ + assertChatDeletionsReadable() { if (deletionRecordFailure) throw deletionRecordFailure; }, + /** Finishes deletions a crash interrupted. Repeatable: a failure leaves its tombstone and its chat closed. */ + 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(); + } + }, /** Every activity change (a run began or ended, an approval was raised or settled). */ onActivityChange(listener: (snapshot: ChatActivitySnapshot) => void) { activityListeners.add(listener); return () => { activityListeners.delete(listener); }; }, setBots(runtime: CliBotGenerationRuntime) { bots = runtime; }, - async stop() { closed = true; const ids = new Set([...reserved, ...active.keys()]); admission.releaseAll(); await Promise.allSettled([...ids].map((id) => llmClient.cancelChat(id, "application_shutdown"))); await Promise.all([...ids].map((id) => llmClient.waitForChatIdle(id))); }, + /** Closes intake before its first await, so no ingress stopping alongside it can begin a turn. */ + async stop() { const ids = turns.closeIntake(); admission.releaseAll(); await Promise.allSettled(ids.map((id) => llmClient.cancelChat(id, "application_shutdown"))); await Promise.all(ids.map((id) => llmClient.waitForChatIdle(id))); }, }; } diff --git a/packages/cli/src/daemon-control.ts b/packages/cli/src/daemon-control.ts index 73aa5b272f..8edadba5dc 100644 --- a/packages/cli/src/daemon-control.ts +++ b/packages/cli/src/daemon-control.ts @@ -8,7 +8,7 @@ export async function remoteDaemonCommand(agentDir: string, command: string, arg const socket = createConnection(daemonSocket(agentDir)); // Decode across chunk boundaries so a multi-byte character split by the kernel is not mangled. socket.setEncoding("utf8"); - let buffer = ""; + let buffer = "", framed = false; socket.setTimeout(610_000, () => socket.destroy(new Error("Daemon response timed out."))); socket.on("connect", () => socket.write(JSON.stringify({ command, args }) + "\n")); socket.on("error", (error) => { @@ -22,11 +22,16 @@ export async function remoteDaemonCommand(agentDir: string, command: string, arg reject(error); }); socket.on("data", (data) => { + if (framed) return; buffer += data; - if (Buffer.byteLength(buffer) > 8 * 1024 * 1024) socket.destroy(new Error("Daemon response is too large.")); - if (!buffer.includes("\n")) return; - socket.end(); - try { const response = JSON.parse(buffer); if (response.error) reject(new Error(response.error)); else resolve(response.result); } + const end = buffer.indexOf("\n"); + // The ceiling is on the frame: bytes after its newline are ignored, not counted. + if (Buffer.byteLength(end < 0 ? buffer : buffer.slice(0, end)) > 8 * 1024 * 1024) { socket.destroy(new Error("Daemon response is too large.")); return; } + if (end < 0) return; + // The first frame is the whole answer, so nothing a peer sends after it is read. + framed = true; + socket.destroy(); + try { const response = JSON.parse(buffer.slice(0, end)); if (response.error) reject(new Error(response.error)); else resolve(response.result); } catch (error) { reject(error); } }); socket.on("end", () => { if (!buffer.includes("\n")) reject(new Error("Daemon closed without a response.")); }); diff --git a/packages/cli/src/daemon-turn-lifecycle.ts b/packages/cli/src/daemon-turn-lifecycle.ts new file mode 100644 index 0000000000..d6aa568d73 --- /dev/null +++ b/packages/cli/src/daemon-turn-lifecycle.ts @@ -0,0 +1,203 @@ +/** + * Who holds each daemon chat, and whether the daemon still takes new turns. + * `ChatTurnAdmission` stays the owner of a lease's own lifecycle. This layer adds + * what only the daemon knows: its intake, its chat capacity, and the generation a + * lease hands off to. See docs/state-machines/serve-daemon.md. + */ +import type { ChatTurnAdmission, ChatTurnLease } from "../../../main/services/chat-turn-admission.js"; +import type { GenerationCancellationOrigin } from "../../../renderer/shared/generation-timeline.js"; + +/** + * - `lease`: a live reservation. It counts against capacity. + * - `settling`: authority was revoked but admitted work still runs. It holds the + * chat and blocks shutdown, but takes no capacity because it can start nothing. + * - `generation`: a registered run, until it has physically released its resources. + * A chat with no custody is idle. + */ +export type DaemonChatCustody = + | { readonly holder: "lease"; readonly preparation: "pending" | "settled" } + | { readonly holder: "settling" } + | { readonly holder: "generation" }; + +export type DaemonChatEvent = + | { readonly type: "reserved" } + | { readonly type: "preparation_settled" } + | { readonly type: "lease_revoked" } + | { readonly type: "generation_registered" } + | { readonly type: "generation_released" }; + +/** `undefined` is idle. An event that does not apply leaves custody unchanged. */ +export function transitionDaemonChat(custody: DaemonChatCustody | undefined, event: DaemonChatEvent): DaemonChatCustody | undefined { + switch (event.type) { + case "reserved": + return custody ?? { holder: "lease", preparation: "pending" }; + case "preparation_settled": + if (custody?.holder === "lease") return { holder: "lease", preparation: "settled" }; + return custody?.holder === "settling" ? undefined : custody; + case "lease_revoked": + if (custody?.holder !== "lease") return custody; + return custody.preparation === "settled" ? undefined : { holder: "settling" }; + case "generation_registered": + return custody?.holder === "lease" && custody.preparation === "settled" ? { holder: "generation" } : custody; + case "generation_released": + return custody?.holder === "generation" ? undefined : custody; + } +} + +/** Live reservations and generations share one limit. Settling work starts nothing. */ +export const takesDaemonCapacity = (custody: DaemonChatCustody): boolean => custody.holder !== "settling"; + +/** How a turn's answer ended up on disk. A terminal event alone never proves this. */ +export type DaemonGenerationPersistence = "none" | "final_saved" | "partial_saved" | "partial_lost"; + +/** + * One registered generation. Stop request, persistence and physical release are + * independent: a stopped run still owns its session until `settled` resolves. + */ +export class DaemonGenerationRun } = { abort(): Promise }> { + readonly abort = new AbortController(); + session?: Session; + /** Set by the first stop that names one. A timeout or a lost owner names none. */ + cancellationOrigin?: GenerationCancellationOrigin; + persistence: DaemonGenerationPersistence = "none"; + readonly settled: Promise; + private markSettled!: () => void; + readonly streamId: string; + readonly ownerId: string; + readonly workspaceId?: string; + + constructor(identity: { streamId: string; ownerId: string; workspaceId?: string }) { + this.streamId = identity.streamId; + this.ownerId = identity.ownerId; + this.workspaceId = identity.workspaceId; + this.settled = new Promise((resolve) => { this.markSettled = resolve; }); + } + + get stopRequested(): boolean { return this.abort.signal.aborted; } + + /** Withdraws authority first, so any awaited check that resumes afterwards sees the stop. */ + async requestStop(origin?: GenerationCancellationOrigin): Promise { + if (origin && !this.stopRequested) this.cancellationOrigin ??= origin; + this.abort.abort(); + await this.session?.abort(); + } + + /** For a caller with nowhere to report a failed session abort. */ + requestStopQuietly(origin?: GenerationCancellationOrigin): void { void this.requestStop(origin).catch(() => {}); } + + /** Physical release is complete. Only the turn owner calls this. */ + markReleased(): void { this.markSettled(); } +} + +interface ChatEntry { + custody: DaemonChatCustody; + run?: Run; +} + +export interface DaemonTurnOwnerOptions { + admission: ChatTurnAdmission; + /** Refuses a chat with an unfinished deletion. */ + isDeleting(chatId: string): boolean; + maxChats?: number; +} + +/** The single writer of daemon chat custody. Every busy, capacity and idle answer reads it. */ +export class DaemonTurnOwner }> { + private readonly chats = new Map>(); + private readonly idleWaiters = new Map void>>(); + private readonly options: DaemonTurnOwnerOptions; + private intake: "open" | "closed" = "open"; + + constructor(options: DaemonTurnOwnerOptions) { this.options = options; } + + get accepting(): boolean { return this.intake === "open"; } + + isBusy(chatId: string): boolean { return this.chats.has(chatId); } + + run(chatId: string): Run | undefined { return this.chats.get(chatId)?.run; } + + findRun(matches: (run: Run) => boolean): { chatId: string; run: Run } | undefined { + for (const [chatId, { run }] of this.chats) if (run && matches(run)) return { chatId, run }; + return undefined; + } + + private commit(chatId: string, entry: ChatEntry, event: DaemonChatEvent): void { + // A lease that lost the chat to a newer entry keeps calling back; only the current entry moves. + if (this.chats.get(chatId) !== entry) return; + const next = transitionDaemonChat(entry.custody, event); + if (next) { entry.custody = next; return; } + this.chats.delete(chatId); + this.wake(chatId); + } + + private wake(chatId: string): void { + const waiters = this.idleWaiters.get(chatId); + this.idleWaiters.delete(chatId); + for (const wake of waiters ?? []) wake(); + } + + private held(): number { + let count = 0; + for (const { custody } of this.chats.values()) if (takesDaemonCapacity(custody)) count += 1; + return count; + } + + begin(chatId: string, turnId: string, ownerId: string): ChatTurnLease | null { + if (!this.accepting || this.options.isDeleting(chatId) || this.held() >= (this.options.maxChats ?? 3)) return null; + const lease = this.options.admission.tryBegin(chatId, turnId, ownerId, this.run(chatId) !== undefined); + if (!lease) return null; + const entry: ChatEntry = { custody: transitionDaemonChat(undefined, { type: "reserved" })! }; + this.chats.set(chatId, entry); + lease.onReleased(() => { this.commit(chatId, entry, { type: "lease_revoked" }); }); + const settle = lease.settleAsyncWork; + lease.settleAsyncWork = (options) => { + settle(options); + this.commit(chatId, entry, { type: "preparation_settled" }); + // A settled lease may still hand off, but a waiter reads the new state itself. + this.wake(chatId); + }; + return lease; + } + + /** + * Registers `run` and releases the matching lease as one synchronous step, so + * nothing can observe the chat as free between them. `register` runs inside it. + */ + handoff(chatId: string, turnId: string, ownerId: string, run: Run, register: () => void): boolean { + return this.options.admission.handoff(chatId, turnId, ownerId, () => { + const entry = this.chats.get(chatId); + if (!entry) throw new Error("The chat's reservation is unavailable."); + this.commit(chatId, entry, { type: "generation_registered" }); + entry.run = run; + register(); + }); + } + + /** Clears custody once `run` has physically released. A stale run changes nothing. */ + release(chatId: string, run: Run): boolean { + const entry = this.chats.get(chatId); + if (entry?.run !== run) return false; + this.commit(chatId, entry, { type: "generation_released" }); + return true; + } + + async waitForIdle(chatId: string): Promise { + while (this.isBusy(chatId)) { + const running = this.run(chatId); + if (running) await running.settled; + else await new Promise((resolve) => { + const waiters = this.idleWaiters.get(chatId) ?? new Set(); + waiters.add(resolve); this.idleWaiters.set(chatId, waiters); + }); + } + } + + /** + * Refuses every new turn from here on and returns each chat something still + * holds, including revoked work that has not settled: all of it can write. + */ + closeIntake(): string[] { + this.intake = "closed"; + return [...this.chats.keys()]; + } +} diff --git a/packages/cli/src/parity-test-api.ts b/packages/cli/src/parity-test-api.ts index 4e321e1b1d..28a497edcc 100644 --- a/packages/cli/src/parity-test-api.ts +++ b/packages/cli/src/parity-test-api.ts @@ -5,10 +5,15 @@ 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"; +export * from "./serve-ownership.ts"; export * from "./telegram.ts"; export * from "./daemon-chats.ts"; +export * from "./daemon-turn-lifecycle.ts"; +export * from "./daemon-approvals.ts"; export * from "./speech.ts"; export * from "./remote.ts"; export { daemonRemoteSummary, showStartupPairing } from "./serve-command.ts"; diff --git a/packages/cli/src/remote-chats.ts b/packages/cli/src/remote-chats.ts index 97086fe861..f6d706de78 100644 --- a/packages/cli/src/remote-chats.ts +++ b/packages/cli/src/remote-chats.ts @@ -22,13 +22,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-lifecycle.ts b/packages/cli/src/serve-lifecycle.ts index 86e5557558..b891104a16 100644 --- a/packages/cli/src/serve-lifecycle.ts +++ b/packages/cli/src/serve-lifecycle.ts @@ -19,6 +19,7 @@ import { daemonSocket } from "./daemon-control.ts"; import { acquireLease, atomicJson, cliLeaseHelperPath, leaseGuardPath, readJson } from "./state.ts"; import { tryAcquireProcessLifetimeLock } from "../../../main/services/process-lifetime-lock.ts"; import { watchMcpProcessGroups } from "../../../main/services/mcp-stdio-transport.js"; +import { decideServeStopDeadline, decideServeStopStart, type ServeOwnerObservation, type ServeProcessClass } from "./serve-ownership.ts"; const SERVE_LOCK = "serve.lock"; const SERVE_LOG = "serve.log"; @@ -144,8 +145,6 @@ function cliEntryCandidates(): string[] { return [...candidates]; } -type PidClass = "daemon" | "aiden" | "foreign" | "unknown"; - function escapeRegExp(value: string): string { return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } @@ -161,7 +160,7 @@ const RUNTIME_ARGV0 = /(?:^|[/\\])(?:node(?:js)?|bun|deno|tsx|aiden(?:-cli)?)(?: * - "foreign": cmdline inspectable and is not our CLI at all — a recycled PID. * - "unknown": cmdline cannot be inspected on this platform. */ -function classifyPid(pid: number, owner?: ServeOwner): PidClass { +function classifyPid(pid: number, owner?: ServeOwner): ServeProcessClass { const command = processCommandLine(pid)?.trim(); if (command === undefined) return "unknown"; // Strongest check: acquireLease records the owner's argv, so matching the @@ -359,24 +358,20 @@ export async function stopDaemon(agentDir: string, timeoutMs = 15_000): Promise< throw new Error("The Aiden daemon is not running."); } const pid = owner.pid; - if (!pidAlive(pid)) { - clearServeArtifacts(agentDir, owner); - throw new Error(`The Aiden daemon was not running; cleared the stale lock left by PID ${pid}.`); - } - const klass = classifyPid(pid, owner); - if (klass === "foreign") { - // The PID was recycled by an unrelated process — never signal it. - clearServeArtifacts(agentDir, owner); - throw new Error(`The Aiden daemon was not running; cleared the stale lock left by PID ${pid}.`); - } - if (klass === "aiden") { - throw new Error(`PID ${pid} is a running Aiden command, not the daemon — its lock releases when the command exits.`); - } - if (klass === "unknown") { - throw new Error( - `Cannot verify that PID ${pid} is the Aiden daemon; refusing to signal it. ` + - `If it is, run kill ${pid} and remove ${join(agentDir, SERVE_LOCK)}.`, - ); + const observe = (): ServeOwnerObservation => (pidAlive(pid) ? classifyPid(pid, owner) : "gone"); + switch (decideServeStopStart(observe())) { + case "clear_stale": + // A dead owner, or a PID recycled by an unrelated process that is never signalled. + clearServeArtifacts(agentDir, owner); + throw new Error(`The Aiden daemon was not running; cleared the stale lock left by PID ${pid}.`); + case "refuse_aiden": + throw new Error(`PID ${pid} is a running Aiden command, not the daemon — its lock releases when the command exits.`); + case "refuse_unverified": + throw new Error( + `Cannot verify that PID ${pid} is the Aiden daemon; refusing to signal it. ` + + `If it is, run kill ${pid} and remove ${join(agentDir, SERVE_LOCK)}.`, + ); + case "signal": } try { process.kill(pid, "SIGTERM"); @@ -400,8 +395,18 @@ export async function stopDaemon(agentDir: string, timeoutMs = 15_000): Promise< polls += 1; await new Promise((resolveWait) => setTimeout(resolveWait, 150)); } - // Re-verify the PID before the forced kill: it must still be this daemon. - if (pidAlive(pid) && classifyPid(pid, owner) === "daemon") { + // Re-verify the owner and PID before the forced kill: both must still be this daemon. + const atDeadline = decideServeStopDeadline(observe(), sameOwner(serveOwner(agentDir), owner)); + if (atDeadline === "stopped") return { stopped: true, pid }; + if (atDeadline === "clear_stale") { + clearServeArtifacts(agentDir, owner); + return { stopped: true, pid }; + } + if (atDeadline === "unconfirmed") { + // The PID is alive but cannot be shown to be this daemon, so nothing may suggest signalling it. + throw new Error(`Could not confirm that PID ${pid} is still the Aiden daemon ${Math.round(timeoutMs / 1000)}s after asking it to stop. Check what that process is before acting on it; its lock stays at ${join(agentDir, SERVE_LOCK)}.`); + } + if (atDeadline === "force") { // A background daemon leads its own process group; killing the group also // takes its Remote advertiser instead of orphaning it. A foreground serve // shares its group with the shell job (`aiden serve | tee`), so only the diff --git a/packages/cli/src/serve-lifetime.ts b/packages/cli/src/serve-lifetime.ts new file mode 100644 index 0000000000..11398adb41 --- /dev/null +++ b/packages/cli/src/serve-lifetime.ts @@ -0,0 +1,32 @@ +/** + * Control-socket lifetime for one `aiden serve` run: whether new commands are + * taken, and which accepted ones still run. See docs/state-machines/serve-daemon.md. + */ +export type ServePhase = "starting" | "serving" | "draining"; + +export class ServeLifetime { + private current: ServePhase = "starting"; + private readonly commands = new Set>(); + + get phase(): ServePhase { return this.current; } + + get acceptsCommands(): boolean { return this.current !== "draining"; } + + /** Draining is terminal: a late ready report cannot reopen the socket. */ + markServing(): void { if (this.current === "starting") this.current = "serving"; } + + /** Refuses new commands. The ones already accepted keep running. */ + beginDrain(): void { this.current = "draining"; } + + /** The command owns the serve lease until it settles. */ + track(command: Promise): void { + this.commands.add(command); + const settled = () => { this.commands.delete(command); }; + void command.then(settled, settled); + } + + /** Resolves once no accepted command runs. Their own failures were already answered. */ + async settleCommands(): Promise { + while (this.commands.size) await Promise.allSettled([...this.commands]); + } +} diff --git a/packages/cli/src/serve-ownership.ts b/packages/cli/src/serve-ownership.ts new file mode 100644 index 0000000000..a554c2b4a0 --- /dev/null +++ b/packages/cli/src/serve-ownership.ts @@ -0,0 +1,40 @@ +/** + * What `aiden serve stop` may do to the process a serve lease names. These are + * pure decisions over what the caller observed. Signals, polling and artifact + * cleanup stay in serve-lifecycle.ts. See docs/state-machines/serve-daemon.md. + */ + +/** + * - `daemon`: the recorded ` serve`. + * - `aiden`: a live one-shot command holding the lock legitimately. + * - `foreign`: inspectable and not ours, so a recycled PID. + * - `unknown`: the platform cannot show its command line. + */ +export type ServeProcessClass = "daemon" | "aiden" | "foreign" | "unknown"; + +/** `gone` is a PID with no process behind it. */ +export type ServeOwnerObservation = ServeProcessClass | "gone"; + +export type ServeStopStart = "signal" | "clear_stale" | "refuse_aiden" | "refuse_unverified"; + +/** Only a verified daemon is ever signalled. */ +export function decideServeStopStart(owner: ServeOwnerObservation): ServeStopStart { + switch (owner) { + case "daemon": return "signal"; + case "gone": case "foreign": return "clear_stale"; + case "aiden": return "refuse_aiden"; + case "unknown": return "refuse_unverified"; + } +} + +export type ServeStopDeadline = "stopped" | "clear_stale" | "force" | "unconfirmed"; + +/** + * The grace period ended. Force needs the same owner and a verified daemon, because + * the PID may no longer be ours. A failed check here proves nothing about exit. + */ +export function decideServeStopDeadline(owner: ServeOwnerObservation, sameOwner: boolean): ServeStopDeadline { + if (!sameOwner) return "stopped"; + if (owner === "daemon") return "force"; + return owner === "gone" || owner === "foreign" ? "clear_stale" : "unconfirmed"; +} diff --git a/packages/cli/src/serve.ts b/packages/cli/src/serve.ts index 4c70752b3f..17b6a9c1f5 100644 --- a/packages/cli/src/serve.ts +++ b/packages/cli/src/serve.ts @@ -11,6 +11,7 @@ import { workspaceCommand } from "./workspaces.ts"; import { createCliWorkspaceApplication } from "./workspace-application.ts"; import { createCliBots } from "./bots.ts"; import { createCliRemote } from "./remote.ts"; +import { ServeLifetime } from "./serve-lifetime.ts"; type CliRemote = Awaited>; @@ -41,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), @@ -50,9 +54,12 @@ async function serveOwned(agentDir: string, signal: AbortSignal, options: { remo let remote: CliRemote | undefined; const path = daemonSocket(agentDir); const clients = new Set(); - let closing = false; + const lifetime = new ServeLifetime(); + // A stop during startup closes the socket to new commands at once, not when startup ends. + if (signal.aborted) lifetime.beginDrain(); + else signal.addEventListener("abort", () => lifetime.beginDrain(), { once: true }); const server = createServer((socket) => { - if (closing || clients.size >= 64) { socket.destroy(); return; } + if (!lifetime.acceptsCommands || clients.size >= 64) { socket.destroy(); return; } clients.add(socket); socket.on("close", () => clients.delete(socket)); socket.on("error", () => {}); let buffer = "", handled = false; socket.setEncoding("utf8"); @@ -60,47 +67,64 @@ async function serveOwned(agentDir: string, signal: AbortSignal, options: { remo socket.on("data", (data) => { if (handled) return; buffer += data; - if (Buffer.byteLength(buffer) > 65536) { socket.destroy(); return; } - if (!buffer.includes("\n")) return; + const end = buffer.indexOf("\n"); + // The ceiling is on the frame: bytes after its newline are ignored, not counted. + if (Buffer.byteLength(end < 0 ? buffer : buffer.slice(0, end)) > 65536) { socket.destroy(); return; } + if (end < 0) return; handled = true; socket.setTimeout(610_000, () => socket.destroy()); - void (async () => { + // A reply is not delivered until it has flushed or its client has gone. + const reply = (body: unknown) => new Promise((resolve) => { + if (socket.destroyed) { resolve(); return; } + socket.once("close", () => resolve()); + socket.end(JSON.stringify(body) + "\n", () => resolve()); + }); + lifetime.track((async () => { try { - if (closing) throw new Error("The Aiden daemon is shutting down."); - const request = JSON.parse(buffer); + if (!lifetime.acceptsCommands) throw new Error("The Aiden daemon is shutting down."); + const request = JSON.parse(buffer.slice(0, end)); if (!["schedule", "remote", "bots", "workspace", "serve"].includes(request.command) || !Array.isArray(request.args) || request.args.some((arg: unknown) => typeof arg !== "string")) throw new Error("Invalid daemon command."); if (request.command === "remote" && !remote) throw new Error("Remote is off for this server. Restart it with `aiden serve` (without --no-remote) to use Remote controls."); const result = request.command === "serve" ? await serveStatus(remote, request.args) : request.command === "workspace" ? await workspaceCommand(agentDir, request.args, (remote?.workspaces ?? workspaceRuntime).application) : request.command === "bots" ? await bots.command(request.args) : request.command === "remote" ? await remote!.command(request.args) : await runtime.command(request.args); - socket.end(JSON.stringify({ result }) + "\n"); - } catch (error) { socket.end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) }) + "\n"); } - })(); + await reply({ result }); + } catch (error) { await reply({ error: error instanceof Error ? error.message : String(error) }); } + })()); }); }); try { + if (signal.aborted) return; if (options.remote) { try { remote = await createCliRemote(agentDir, chats, runtime, { bots }); await remote.start(); } catch (error) { throw new Error(`Remote could not start: ${(error instanceof Error ? error.message : String(error)).replace(/\.*$/u, ".")} Run \`aiden serve --no-remote\` to serve without Remote.`, { cause: error }); } } + if (signal.aborted) return; ensurePrivateDirectory(agentDir, "reject"); rmSync(path, { force: true }); await new Promise((resolve, reject) => { server.once("error", reject); server.listen(path, () => { server.removeListener("error", reject); resolve(); }); }); chmodSync(path, 0o600); + if (signal.aborted) return; await runtime.service.start(); + if (signal.aborted) return; await telegram.start(); + if (signal.aborted) return; process.stderr.write(`Aiden scheduler listening at ${path}\n`); if (remote) { const status = await remote.service.status().catch(() => undefined); process.stderr.write(`Aiden Remote listening${status ? ` on port ${status.lanPort}${status.lanEndpoint ? ` (${status.lanEndpoint})` : ""}` : ""}. Pair a device with \`aiden remote pair lan|tailscale\`.\n`); } else process.stderr.write("Aiden Remote is off.\n"); + if (signal.aborted) return; + lifetime.markServing(); options.onReady?.(); if (!signal.aborted) await new Promise((resolve) => signal.addEventListener("abort", () => resolve(), { once: true })); } finally { // Refuse new control requests and stop accepting connections before draining. - closing = true; + lifetime.beginDrain(); const closed = server.listening ? new Promise((resolve) => server.close(() => resolve())) : Promise.resolve(); // chats.stop() runs first and synchronously closes turn admission, so no ingress stopped // alongside it can begin a turn that exit would cut short. const settled = await Promise.allSettled([chats.stop(), bots.stop(), telegram.stopAndSettle(), remote?.stop(), runtime.service.stopAndSettle()]); + // An accepted command may still be changing state, and its client is owed the outcome. + await lifetime.settleCommands(); for (const client of clients) client.destroy(); await closed; rmSync(path, { force: true }); diff --git a/packages/cli/tests/daemon-turns.test.mjs b/packages/cli/tests/daemon-turns.test.mjs new file mode 100644 index 0000000000..1070e7c43d --- /dev/null +++ b/packages/cli/tests/daemon-turns.test.mjs @@ -0,0 +1,736 @@ +// Behavioral oracles for the daemon turn owners (cli-native C09, C10, C11): +// 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, 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 { dirname, join } from "node:path"; +import test from "node:test"; +import * as api from "../dist/parity-test-api.js"; + +const tick = () => new Promise((resolve) => setImmediate(resolve)); + +async function until(condition, label, timeoutMs = 10_000) { + const deadline = Date.now() + timeoutMs; + while (!condition()) { + if (Date.now() > deadline) throw new Error(`Timed out waiting for ${label}.`); + await new Promise((resolve) => setTimeout(resolve, 5)); + } +} + +const chunk = (delta, finish = null) => `data: ${JSON.stringify({ id: "test", object: "chat.completion.chunk", choices: [{ index: 0, delta, finish_reason: finish }] })}\n\n`; +const usage = `data: ${JSON.stringify({ id: "test", object: "chat.completion.chunk", choices: [], usage: { prompt_tokens: 10, completion_tokens: 4, total_tokens: 14 } })}\n\n`; + +/** One scripted step per provider request; an unscripted request answers "Done". */ +const reply = (text) => (response) => { + response.write(chunk({ role: "assistant", content: text })); + response.write(chunk({}, "stop")); response.write(usage); + response.end("data: [DONE]\n\n"); +}; +const callTool = (name, args) => (response) => { + response.write(chunk({ role: "assistant", tool_calls: [{ index: 0, id: "call_1", type: "function", function: { name, arguments: JSON.stringify(args) } }] })); + response.write(chunk({}, "tool_calls")); response.write(usage); + response.end("data: [DONE]\n\n"); +}; +/** Streams a first delta and then stays open, as a slow provider does. */ +const hangAfter = (text) => (response) => { response.write(chunk({ role: "assistant", content: text })); }; + +/** A refusal the session does not retry. */ +const reject = (response) => { response.writeHead(400, { "content-type": "application/json" }); response.end(JSON.stringify({ error: { message: "Rejected" } })); }; + +async function fixture(t, { access = "full" } = {}) { + const dir = mkdtempSync(join(tmpdir(), "aiden-daemon-turns-")); + const steps = [], requests = []; + const server = createServer(async (request, response) => { + let body = ""; for await (const part of request) body += part; + requests.push(JSON.parse(body)); + const step = steps.shift() ?? reply("Done"); + if (step !== reject) response.writeHead(200, { "content-type": "text/event-stream" }); + step(response); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + api.atomicJson(join(dir, "models.json"), { providers: { "cli-test": { api: "openai-completions", baseUrl: `http://127.0.0.1:${server.address().port}/v1`, apiKey: "test-only", + models: [{ id: "test", name: "Test", reasoning: false, input: ["text"], contextWindow: 32000, maxTokens: 4096, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } }] } } }); + const workspace = await api.workspaceCommand(dir, ["add", dir]); + await api.workspaceCommand(dir, ["access", workspace.id, access]); + const daemon = api.createDaemonChats(dir); + t.after(async () => { + await daemon.stop(); + server.closeAllConnections(); server.close(); + rmSync(dir, { recursive: true, force: true }); + }); + return { dir, daemon, workspace, steps, requests }; +} + +function ownerFor(documentId = "owner") { + const events = [], listeners = new Set(); + let destroyed = false; + return { events, id: 0, kind: "remote", documentId, isDestroyed: () => destroyed, + onInvalidated(listener) { listeners.add(listener); return () => listeners.delete(listener); }, + send(channel, value) { events.push({ channel, value }); }, + invalidate() { destroyed = true; for (const listener of listeners) listener(); }, + of(channel) { return events.filter((event) => event.channel === channel).map((event) => event.value); } }; +} + +/** The ordinary ingress order: reserve, durably append the user message, settle, hand off. */ +async function beginTurn({ daemon, workspace }, chatId, { streamId = `stream-${chatId}`, owner = ownerFor(), usageSource = "chat", text = "Hello", create = true } = {}) { + if (create) await daemon.chatStore.create({ id: chatId, title: chatId, workspaceId: workspace.id }); + const lease = daemon.llmClient.beginChatTurn(chatId, streamId, owner.documentId); assert.ok(lease, "the turn was admitted"); + await daemon.chatStore.appendMessage(chatId, { role: "user", content: text }); + lease.settleAsyncWork(); + const started = await daemon.llmClient.start(streamId, { chatId, workspaceId: workspace.id, providerId: "cli-test", model: "test", messages: [{ role: "user", content: text }] }, owner, { usageSource }); + return { lease, owner, streamId, started }; +} + +const assistantMessages = async (daemon, chatId) => (await daemon.chatStore.get(chatId)).messages.filter((message) => message.role === "assistant"); + +/** Only a settled generation lets another owner take the chat's session lease. */ +function assertSessionReleased(daemon, chatId) { api.acquireLease(daemon.sessionPath(chatId))(); } + +test("a completed turn saves one answer, tells the client, and frees the chat", async (t) => { + const f = await fixture(t); + f.steps.push(reply("Answer")); + const { owner, started } = await beginTurn(f, "complete"); + assert.equal(started, true); + await f.daemon.llmClient.waitForChatIdle("complete"); + const [done] = owner.of("chat:done"); + assert.equal(done.content, "Answer"); + assert.equal(done.timeline.status, "completed"); + assert.deepEqual((await assistantMessages(f.daemon, "complete")).map((message) => message.content), ["Answer"]); + assert.equal(owner.of("chat:error").length, 0); + assert.equal(f.daemon.llmClient.isChatBusy("complete"), false); + assert.deepEqual(f.daemon.activity.snapshot().activeChatIds, []); + assertSessionReleased(f.daemon, "complete"); +}); + +test("a failing activity listener cannot leave the session lease held after idle", async (t) => { + const f = await fixture(t); + f.steps.push(reply("Answer")); + let armed = false; + const remove = f.daemon.onActivityChange(() => { if (armed) throw new Error("listener failed"); }); + t.after(remove); + const { started } = await beginTurn(f, "listener"); + assert.equal(started, true); + armed = true; + await f.daemon.llmClient.waitForChatIdle("listener"); + armed = false; + assertSessionReleased(f.daemon, "listener"); + assert.equal(f.daemon.runs.summary("stream-listener")?.state, "done"); +}); + +test("a run that cannot register gives the chat back and does not hold shutdown", async (t) => { + const f = await fixture(t); + let armed = true; + const remove = f.daemon.onActivityChange(() => { if (armed) throw new Error("listener failed"); }); + t.after(remove); + await assert.rejects(beginTurn(f, "unregistered"), /listener failed/u); + armed = false; + assert.equal(f.daemon.llmClient.isChatBusy("unregistered"), false); + assertSessionReleased(f.daemon, "unregistered"); + f.steps.push(reply("Second try")); + const { started } = await beginTurn(f, "unregistered", { streamId: "again", create: false }); + assert.equal(started, true); + await f.daemon.llmClient.waitForChatIdle("unregistered"); + await f.daemon.stop(); +}); + +test("a chat holds one turn at a time and the daemon holds three chats", async (t) => { + const { daemon } = await fixture(t); + const leases = ["one", "two", "three"].map((id) => daemon.llmClient.beginChatTurn(id, `s-${id}`, "owner")); + assert.ok(leases.every(Boolean)); + assert.equal(daemon.llmClient.beginChatTurn("one", "s-again", "other"), null, "a second turn cannot share a chat"); + assert.equal(daemon.llmClient.beginChatTurn("four", "s-four", "owner"), null, "a fourth chat waits for a slot"); + leases[0].settleAsyncWork(); leases[0].release(); + await tick(); + const later = daemon.llmClient.beginChatTurn("four", "s-four", "owner"); + assert.ok(later, "a released reservation frees its slot"); + for (const lease of [later, leases[1], leases[2]]) { lease.settleAsyncWork(); lease.release(); } +}); + +test("a turn cannot begin on a chat that is being deleted", async (t) => { + const { daemon } = await fixture(t); + const release = daemon.deletion.begin("deleting"); + assert.equal(daemon.llmClient.beginChatTurn("deleting", "stream", "owner"), null); + release(); + const lease = daemon.llmClient.beginChatTurn("deleting", "stream", "owner"); assert.ok(lease); + lease.settleAsyncWork(); lease.release(); +}); + +test("only the reservation's own settled turn may start a generation", async (t) => { + const f = await fixture(t), { daemon, workspace } = f; + await daemon.chatStore.create({ id: "owned", title: "Owned", workspaceId: workspace.id }); + const owner = ownerFor(), params = { chatId: "owned", workspaceId: workspace.id, providerId: "cli-test", model: "test", messages: [{ role: "user", content: "Hello" }] }; + const lease = daemon.llmClient.beginChatTurn("owned", "stream", owner.documentId); + assert.equal(await daemon.llmClient.start("stream", params, owner, { usageSource: "chat" }), false, "preparation is still pending"); + lease.settleAsyncWork(); + assert.equal(await daemon.llmClient.start("other-stream", params, owner, { usageSource: "chat" }), false, "another turn id"); + assert.equal(await daemon.llmClient.start("stream", params, ownerFor("stranger"), { usageSource: "chat" }), false, "another owner"); + assert.equal(f.requests.length, 0); + assertSessionReleased(daemon, "owned"); + lease.release(); + assert.equal(await daemon.llmClient.start("stream", params, owner, { usageSource: "chat" }), false, "the reservation is gone"); + assert.equal(owner.events.length, 0); +}); + +test("a stop before the provider is reached ends the turn with no answer and no request", async (t) => { + const f = await fixture(t); + const { owner } = await beginTurn(f, "early-stop"); + await f.daemon.llmClient.cancelChat("early-stop", "user_stop"); + await f.daemon.llmClient.waitForChatIdle("early-stop"); + assert.equal(f.requests.length, 0); + const [error] = owner.of("chat:error"); + assert.equal(error.cancelled, true); + assert.equal(error.timeline.status, "cancelled"); + assert.equal(error.timeline.cancellationOrigin, "user_stop"); + assert.equal(owner.of("chat:done").length, 0); + assert.deepEqual(await assistantMessages(f.daemon, "early-stop"), []); + assertSessionReleased(f.daemon, "early-stop"); +}); + +test("a stop after the first delta keeps the partial answer exactly once", async (t) => { + const f = await fixture(t); + f.steps.push(hangAfter("Partial")); + const { owner } = await beginTurn(f, "mid-stop"); + await until(() => owner.of("chat:delta").length > 0, "the first delta"); + await f.daemon.llmClient.cancelChat("mid-stop", "user_stop"); + // A later stop never rewrites what the first stop recorded. + await f.daemon.llmClient.cancelChat("mid-stop", "chat_deletion"); + await f.daemon.llmClient.waitForChatIdle("mid-stop"); + const [error] = owner.of("chat:error"); + assert.equal(error.cancelled, true); + assert.equal(error.timeline.cancellationOrigin, "user_stop"); + assert.deepEqual((await assistantMessages(f.daemon, "mid-stop")).map((message) => message.content), ["Partial"]); + assert.equal(owner.of("chat:error").length, 1, "one terminal event"); +}); + +test("stops are bound to the owner and stream they name", async (t) => { + const f = await fixture(t); + f.steps.push(hangAfter("Working")); + const { owner, streamId } = await beginTurn(f, "scoped-stop"); + await until(() => owner.of("chat:delta").length > 0, "the first delta"); + assert.equal(f.daemon.llmClient.cancel(streamId, "stranger"), false); + assert.equal(f.daemon.llmClient.cancel("other-stream", owner.documentId), false); + assert.equal(f.daemon.llmClient.cancelRun("other-stream"), false); + await tick(); + assert.equal(owner.of("chat:error").length, 0, "a mismatched stop leaves the run alone"); + assert.equal(f.daemon.llmClient.cancelRun(streamId), true); + await f.daemon.llmClient.waitForChatIdle("scoped-stop"); + assert.equal(owner.of("chat:error")[0].timeline.cancellationOrigin, "user_stop"); + assert.equal(f.daemon.llmClient.cancelRun(streamId), false, "a settled run cannot be stopped again"); +}); + +test("an owner that goes away ends its run and the journal keeps the terminal", async (t) => { + const f = await fixture(t); + f.steps.push(hangAfter("Partial")); + const { owner, streamId } = await beginTurn(f, "owner-gone"); + await until(() => owner.of("chat:delta").length > 0, "the first delta"); + const before = owner.events.length; + owner.invalidate(); + await f.daemon.llmClient.waitForChatIdle("owner-gone"); + assert.equal(owner.events.length, before, "a destroyed owner is not written to"); + assert.deepEqual((await assistantMessages(f.daemon, "owner-gone")).map((message) => message.content), ["Partial"]); + const journal = f.daemon.runs.read(streamId, 0).events; + assert.deepEqual([journal.at(-1).type, journal.at(-1).terminal], ["cancelled", true]); + assertSessionReleased(f.daemon, "owner-gone"); +}); + +test("a provider failure is an uncancelled error and a replacement turn is unaffected", async (t) => { + const f = await fixture(t); + f.steps.push(reject); + const first = await beginTurn(f, "replaced", { streamId: "first" }); + await f.daemon.llmClient.waitForChatIdle("replaced"); + const [error] = first.owner.of("chat:error"); + assert.equal(error.cancelled, false); + assert.equal(error.timeline.status, "failed"); + f.steps.push(reply("Recovered")); + const second = await beginTurn(f, "replaced", { streamId: "second", create: false }); + await f.daemon.llmClient.waitForChatIdle("replaced"); + assert.equal(f.daemon.llmClient.cancel("first", first.owner.documentId), false, "the old stream no longer names a run"); + assert.equal(second.owner.of("chat:done")[0].content, "Recovered"); + assert.equal(first.owner.of("chat:done").length, 0); +}); + +test("a failed final save reports the error and is retried once as the partial answer", async (t) => { + const f = await fixture(t); + f.steps.push(reply("Answer")); + const append = f.daemon.chatStore.appendMessage, assistantWrites = []; + f.daemon.chatStore.appendMessage = async (...args) => { + if (args[1].role !== "assistant") return append(...args); + assistantWrites.push(args[1]); + if (assistantWrites.length === 1) throw new Error("disk full"); + return append(...args); + }; + const { owner } = await beginTurn(f, "save-fault"); + await f.daemon.llmClient.waitForChatIdle("save-fault"); + assert.equal(owner.of("chat:done").length, 0, "done means the answer is durable"); + const [error] = owner.of("chat:error"); + assert.equal(error.message, "disk full"); + assert.equal(error.cancelled, false); + assert.equal(assistantWrites.length, 2); + assert.equal(error.timeline.status, "failed"); + const stored = await assistantMessages(f.daemon, "save-fault"); + assert.deepEqual(stored.map((message) => message.content), ["Answer"]); + assert.equal(stored[0].timeline.status, "failed", "the record agrees with what the client was told"); + assertSessionReleased(f.daemon, "save-fault"); +}); + +test("a partial answer that cannot be saved still ends the run and frees the chat", async (t) => { + const f = await fixture(t); + f.steps.push(hangAfter("Partial")); + const append = f.daemon.chatStore.appendMessage; + f.daemon.chatStore.appendMessage = async (...args) => { + if (args[1].role === "assistant") throw new Error("disk full"); + return append(...args); + }; + const { owner } = await beginTurn(f, "lost-partial"); + await until(() => owner.of("chat:delta").length > 0, "the first delta"); + await f.daemon.llmClient.cancelChat("lost-partial", "user_stop"); + await f.daemon.llmClient.waitForChatIdle("lost-partial"); + assert.equal(owner.of("chat:error").length, 1); + assert.equal(f.daemon.llmClient.isChatBusy("lost-partial"), false); + assertSessionReleased(f.daemon, "lost-partial"); +}); + +test("shutdown stops running work, keeps its partial answer, and admits nothing more", async (t) => { + const f = await fixture(t); + f.steps.push(hangAfter("Partial")); + const { owner } = await beginTurn(f, "draining-run"); + await until(() => owner.of("chat:delta").length > 0, "the first delta"); + const stopping = f.daemon.stop(); + assert.equal(f.daemon.llmClient.beginChatTurn("late", "stream", "owner"), null, "admission closes before the first await"); + await stopping; + assert.equal(owner.of("chat:error")[0].timeline.cancellationOrigin, "application_shutdown"); + assert.deepEqual((await assistantMessages(f.daemon, "draining-run")).map((message) => message.content), ["Partial"]); + assert.deepEqual(f.daemon.activity.snapshot().activeChatIds, []); + assertSessionReleased(f.daemon, "draining-run"); +}); + +test("a reservation that shutdown revoked cannot start afterwards", async (t) => { + const f = await fixture(t), { daemon, workspace } = f; + await daemon.chatStore.create({ id: "revoked", title: "Revoked", workspaceId: workspace.id }); + const owner = ownerFor(), lease = daemon.llmClient.beginChatTurn("revoked", "stream", owner.documentId); + lease.settleAsyncWork(); + await daemon.stop(); + assert.equal(await daemon.llmClient.start("stream", { chatId: "revoked", workspaceId: workspace.id, providerId: "cli-test", model: "test", messages: [{ role: "user", content: "Hello" }] }, owner, { usageSource: "chat" }), false); + assert.equal(f.requests.length, 0); + assert.equal(owner.events.length, 0); +}); + +test("idle waiters see work through a reservation handing off to its generation", async (t) => { + const f = await fixture(t); + await f.daemon.chatStore.create({ id: "handoff", title: "Handoff", workspaceId: f.workspace.id }); + f.steps.push(hangAfter("Working")); + const owner = ownerFor(), lease = f.daemon.llmClient.beginChatTurn("handoff", "stream", owner.documentId); + let idle = false; + const waiting = f.daemon.llmClient.waitForChatIdle("handoff").then(() => { idle = true; }); + await f.daemon.chatStore.appendMessage("handoff", { role: "user", content: "Hello" }); + lease.settleAsyncWork(); + assert.equal(await f.daemon.llmClient.start("stream", { chatId: "handoff", workspaceId: f.workspace.id, providerId: "cli-test", model: "test", messages: [{ role: "user", content: "Hello" }] }, owner, { usageSource: "chat" }), true); + await until(() => owner.of("chat:delta").length > 0, "the first delta"); + await tick(); + assert.equal(idle, false, "the handoff is not idle"); + assert.equal(f.daemon.llmClient.isChatBusy("handoff"), true); + await f.daemon.llmClient.cancelChat("handoff", "user_stop"); + await waiting; + assert.equal(f.daemon.llmClient.isChatBusy("handoff"), false); +}); + +// C11: a tool call in an `ask` workspace waits on the person's answer. + +/** Runs one turn up to its approval prompt. */ +async function awaitingApproval(f, chatId, { tool = "ls", args = { path: "." }, owner = ownerFor() } = {}) { + f.steps.push(callTool(tool, args), reply("Finished")); + const turn = await beginTurn(f, chatId, { owner }); + await until(() => owner.of("chat:approval").length > 0, "the approval prompt"); + return { ...turn, approval: owner.of("chat:approval")[0] }; +} +test("every raised approval reports one decision, and it matches the outcome", async () => { + const run = async ({ raised = () => {}, publish }) => { + const decisions = []; + const approvals = api.createDaemonApprovals({ raised, resolved: (id, decision) => decisions.push(decision) }); + const outcome = await approvals.request({ streamId: "stream", toolCallId: "call", toolName: "ls", summary: "List" }, new AbortController().signal, "owner", (prompt) => publish(approvals, prompt)); + return { outcome, decisions }; + }; + const allow = (approvals, prompt) => assert.equal(approvals.approve(prompt.approvalId, "allow", "owner"), true); + assert.deepEqual(await run({ publish: allow }), { outcome: "allowed", decisions: ["allow"] }, "answered during delivery"); + assert.deepEqual(await run({ publish: (approvals, prompt) => { allow(approvals, prompt); throw new Error("send failed"); } }), + { outcome: "allowed", decisions: ["allow"] }, "answered, then delivery failed"); + assert.deepEqual(await run({ publish: () => { throw new Error("send failed"); } }), { outcome: "unavailable", decisions: ["cancelled"] }); + assert.deepEqual(await run({ raised: () => { throw new Error("attention failed"); }, publish: () => assert.fail("never delivered") }), + { outcome: "unavailable", decisions: ["cancelled"] }, "attention may have changed before it threw"); + assert.deepEqual(await run({ publish: (approvals, prompt) => { setImmediate(() => approvals.approve(prompt.approvalId, "deny", "owner")); } }), + { outcome: "denied", decisions: ["deny"] }, "the ordinary path reports once too"); +}); + +const toolResult = (owner) => owner.of("chat:tool").find((event) => event.phase !== "call")?.phase; +const toolResultSeen = (request) => JSON.stringify(request.messages.filter((message) => message.role === "tool")); + +test("an allowed tool call runs once, and only the owner or a host may answer", async (t) => { + const f = await fixture(t, { access: "ask" }); + writeFileSync(join(f.dir, "visible.txt"), "x"); + const { owner, approval } = await awaitingApproval(f, "allow"); + assert.equal(approval.toolName, "ls"); + assert.equal(approval.summary, "List folder: ."); + assert.deepEqual(f.daemon.activity.snapshot().approvalChatIds, ["allow"]); + assert.equal(f.daemon.llmClient.approve(approval.approvalId, "allow", "stranger"), false, "another owner cannot answer"); + assert.equal(f.daemon.llmClient.approve("approval_unknown", "allow", owner.documentId), false); + assert.equal(f.daemon.llmClient.approve(approval.approvalId, "allow", owner.documentId), true); + assert.equal(f.daemon.llmClient.approve(approval.approvalId, "deny", owner.documentId), false, "the first answer stands"); + assert.equal(f.daemon.llmClient.approveAsHost(approval.approvalId, "deny"), false, "the first answer stands for a host too"); + await f.daemon.llmClient.waitForChatIdle("allow"); + assert.equal(toolResult(owner), "result"); + assert.match(toolResultSeen(f.requests[1]), /visible\.txt/u); + assert.equal(owner.of("chat:done")[0].content, "Finished"); +}); + +test("a denied tool call never runs and the model hears the refusal", async (t) => { + const f = await fixture(t, { access: "ask" }); + writeFileSync(join(f.dir, "visible.txt"), "x"); + const { approval, streamId } = await awaitingApproval(f, "deny"); + assert.equal(f.daemon.llmClient.approveAsHost(approval.approvalId, "deny"), true, "a paired desktop can answer any run"); + await f.daemon.llmClient.waitForChatIdle("deny"); + const seen = toolResultSeen(f.requests[1]); + assert.doesNotMatch(seen, /visible\.txt/u); + assert.match(seen, /denied, changed or expired/u); + assert.deepEqual(f.daemon.runs.resolution(approval.approvalId)?.decision, "deny"); + assert.ok(f.daemon.runs.summary(streamId)); +}); + +test("a stop during an approval wait cancels the prompt and the tool never runs", async (t) => { + const f = await fixture(t, { access: "ask" }); + writeFileSync(join(f.dir, "visible.txt"), "x"); + const { owner, approval } = await awaitingApproval(f, "stop-approval"); + await f.daemon.llmClient.cancelChat("stop-approval", "user_stop"); + await f.daemon.llmClient.waitForChatIdle("stop-approval"); + assert.equal(f.daemon.llmClient.approve(approval.approvalId, "allow", owner.documentId), false, "a lapsed prompt cannot be answered"); + assert.equal(f.daemon.runs.resolution(approval.approvalId)?.decision, "cancelled"); + assert.equal(f.requests.length, 1, "no tool result went back to the provider"); + assert.equal(owner.of("chat:tool").filter((event) => event.phase === "result").length, 0); + assert.equal(owner.of("chat:error")[0].cancelled, true); +}); + +test("access revoked during an approval wait wins over a later allow", async (t) => { + const f = await fixture(t, { access: "ask" }); + writeFileSync(join(f.dir, "visible.txt"), "x"); + const { owner, approval } = await awaitingApproval(f, "revoke-approval"); + await api.workspaceCommand(f.dir, ["access", f.workspace.id, "none"]); + assert.equal(f.daemon.llmClient.approve(approval.approvalId, "allow", owner.documentId), true); + await f.daemon.llmClient.waitForChatIdle("revoke-approval"); + assert.doesNotMatch(toolResultSeen(f.requests[1]), /visible\.txt/u); +}); + +test("a tool request too large for the phone is refused without a prompt", async (t) => { + const f = await fixture(t, { access: "ask" }); + f.steps.push(callTool("ls", { path: "x".repeat(2_000) }), reply("Finished")); + const { owner } = await beginTurn(f, "oversized"); + await f.daemon.llmClient.waitForChatIdle("oversized"); + assert.equal(owner.of("chat:approval").length, 0); + assert.match(toolResultSeen(f.requests[1]), /approval display budget/u); +}); + +test("a tool in a full-access workspace needs no prompt and one in a disabled workspace never runs", async (t) => { + const f = await fixture(t, { access: "full" }); + writeFileSync(join(f.dir, "visible.txt"), "x"); + f.steps.push(callTool("ls", { path: "." }), reply("Finished")); + const open = await beginTurn(f, "full-access"); + await f.daemon.llmClient.waitForChatIdle("full-access"); + assert.equal(open.owner.of("chat:approval").length, 0); + assert.match(toolResultSeen(f.requests[1]), /visible\.txt/u); + await api.workspaceCommand(f.dir, ["access", f.workspace.id, "none"]); + f.steps.push(callTool("ls", { path: "." }), reply("Finished")); + const closed = await beginTurn(f, "no-access"); + await f.daemon.llmClient.waitForChatIdle("no-access"); + assert.equal(closed.owner.of("chat:approval").length, 0); + const last = f.requests.at(-1); + assert.doesNotMatch(toolResultSeen(last), /visible\.txt/u); +}); + +// Shutdown waits for whoever really holds the chat, not only for a live lease. + +test("shutdown waits for a cancelled reservation whose append is still in flight", async (t) => { + const { daemon } = await fixture(t); + const lease = daemon.llmClient.beginChatTurn("cancelled-append", "stream", "owner"); + lease.reserveAppendPayload(100); + await daemon.llmClient.cancelChat("cancelled-append"); + assert.equal(daemon.llmClient.isChatBusy("cancelled-append"), true, "the write still holds the chat"); + let stopped = false; + const stopping = daemon.stop().then(() => { stopped = true; }); + await tick(); await tick(); + assert.equal(stopped, false, "the process may not exit under an in-flight write"); + lease.settleAsyncWork(); + await stopping; + assert.equal(daemon.llmClient.isChatBusy("cancelled-append"), false); +}); + +/** A Bot chat whose authority check calls back into the test. */ +function fakeBots(onCheck, tools = []) { + const authority = { botId: "bot", provider: { sourceProviderId: "cli-test", sourceModelId: "test" }, managedHome: { workspaceId: "bot-workspace" } }; + return { assertLegacyChatAllowed() {}, async assertNotPaused() {}, tools: async () => tools, instructions: async () => "Be brief.", + authority: { admit: async () => ({ authority, signal: new AbortController().signal, release() {}, revalidateBeforeEffect: onCheck }) } }; +} + +async function beginBotTurn(f, chatId, owner) { + await f.daemon.chatStore.create({ id: chatId, title: "Bot", workspaceId: f.workspace.id, botId: "bot" }); + const lease = f.daemon.llmClient.beginChatTurn(chatId, `stream-${chatId}`, owner.documentId); + await f.daemon.chatStore.appendMessage(chatId, { role: "user", content: "Hello" }); + lease.settleAsyncWork(); + assert.equal(await f.daemon.llmClient.start(`stream-${chatId}`, { chatId, workspaceId: f.workspace.id, providerId: "cli-test", model: "test", messages: [{ role: "user", content: "Hello" }] }, owner, { usageSource: "chat", botAudienceId: "audience" }), true); +} + +test("a stop during any Bot authority check before the prompt keeps the provider request from going out", async (t) => { + for (const stopAt of [1, 2, 3]) { + const f = await fixture(t), owner = ownerFor(), chatId = `bot-${stopAt}`; + let checks = 0; + f.daemon.setBots(fakeBots(async () => { checks += 1; if (checks === stopAt) await f.daemon.llmClient.cancelChat(chatId, "user_stop"); })); + await beginBotTurn(f, chatId, owner); + await f.daemon.llmClient.waitForChatIdle(chatId); + assert.equal(f.requests.length, 0, `no provider request after a stop during check ${stopAt}`); + assert.equal(owner.of("chat:error")[0].cancelled, true); + assert.equal(owner.of("chat:error")[0].timeline.cancellationOrigin, "user_stop"); + } +}); + +test("a stop during a Bot tool's authority check keeps the tool from running", async (t) => { + const f = await fixture(t), owner = ownerFor(); + let stopping = false, ran = 0; + const probe = { name: "probe", description: "Probe", parameters: { type: "object", properties: {} }, execute: async () => { ran += 1; return { content: [{ type: "text", text: "ran" }], details: {} }; } }; + // The session's abort waits for this very check, so the stop lands without being awaited here. + f.daemon.setBots(fakeBots(async () => { if (stopping) void f.daemon.llmClient.cancelChat("bot-tool", "user_stop"); }, [probe])); + f.steps.push((response) => { stopping = true; callTool("probe", {})(response); }, reply("Finished")); + await beginBotTurn(f, "bot-tool", owner); + await f.daemon.llmClient.waitForChatIdle("bot-tool"); + assert.equal(ran, 0); + assert.equal(owner.of("chat:error")[0].cancelled, true); +}); + +test("a run whose session lease cannot be removed still reports idle", { skip: process.platform === "win32" || process.getuid?.() === 0 }, async (t) => { + const f = await fixture(t); + f.steps.push(hangAfter("Partial")); + const { owner } = await beginTurn(f, "stuck-release"); + await until(() => owner.of("chat:delta").length > 0, "the first delta"); + const journals = join(f.dir, "daemon-chats", "journals"); + chmodSync(journals, 0o500); + try { + const waiting = f.daemon.llmClient.waitForChatIdle("stuck-release"); + await f.daemon.llmClient.cancelChat("stuck-release", "user_stop"); + await Promise.race([waiting, new Promise((_, reject) => setTimeout(() => reject(new Error("the idle waiter never woke")), 5_000))]); + assert.equal(f.daemon.llmClient.isChatBusy("stuck-release"), false); + } 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 }); + const prompt = { streamId: "stream", toolCallId: "call", toolName: "ls", summary: "List" }; + return { approvals, prompt, raised, resolved }; +} + +test("an unanswered approval expires, is journaled as expired, and cannot be answered late", async () => { + const { approvals, prompt, resolved } = approvalsFixture({ expiryMs: 10 }); + let published; + const outcome = await approvals.request(prompt, new AbortController().signal, "owner", (value) => { published = value; }); + assert.notEqual(outcome, "allowed"); + assert.deepEqual(resolved, [[published.approvalId, "expired"]]); + assert.equal(approvals.approve(published.approvalId, "allow", "owner"), false); +}); + +test("an approval is never published to a run that is already stopping, and a failed publish fails closed", async () => { + const stopped = approvalsFixture(), controller = new AbortController(); + controller.abort(); + assert.notEqual(await stopped.approvals.request(stopped.prompt, controller.signal, "owner", () => assert.fail("published")), "allowed"); + assert.deepEqual([stopped.raised, stopped.resolved], [[], []], "nobody saw it, so nothing is withdrawn"); + const broken = approvalsFixture(); + assert.notEqual(await broken.approvals.request(broken.prompt, new AbortController().signal, "owner", () => { throw new Error("owner gone"); }), "allowed"); + assert.deepEqual(broken.resolved.map(([id]) => id), broken.raised, "an undelivered prompt leaves no attention behind"); +}); + +test("the journal records how a published approval really ended", async () => { + const { approvals, prompt, resolved } = approvalsFixture(), controller = new AbortController(); + const answered = []; + const allowed = approvals.request(prompt, controller.signal, "owner", (value) => answered.push(value.approvalId)); + const denied = approvals.request(prompt, controller.signal, "owner", (value) => answered.push(value.approvalId)); + const stopped = approvals.request(prompt, controller.signal, "owner", (value) => answered.push(value.approvalId)); + assert.equal(approvals.approve(answered[0], "allow", "owner"), true); + assert.equal(approvals.approveAsHost(answered[1], "deny"), true); + controller.abort(); + assert.deepEqual(await Promise.all([allowed, denied]), ["allowed", "denied"]); + assert.notEqual(await stopped, "allowed"); + assert.deepEqual(resolved, [[answered[0], "allow"], [answered[1], "deny"], [answered[2], "cancelled"]]); +}); + +// The custody owner on its own: legal and refused events, stale leases, and +// generated event orders against independently stated invariants. + +test("custody follows the reservation to its one holder and ignores events that do not apply", () => { + const step = (state, type) => api.transitionDaemonChat(state, { type }); + const reserved = step(undefined, "reserved"), settled = step(reserved, "preparation_settled"); + assert.deepEqual(reserved, { holder: "lease", preparation: "pending" }); + assert.equal(step(settled, "lease_revoked"), undefined, "nothing left to wait for"); + assert.deepEqual(step(reserved, "lease_revoked"), { holder: "settling" }, "revoked work keeps the chat"); + assert.equal(step(step(reserved, "lease_revoked"), "preparation_settled"), undefined); + assert.equal(step(reserved, "generation_registered"), reserved, "unsettled work cannot hand off"); + const running = step(settled, "generation_registered"); + assert.deepEqual(running, { holder: "generation" }); + for (const type of ["reserved", "preparation_settled", "lease_revoked", "generation_registered"]) assert.equal(step(running, type), running); + assert.equal(step(running, "generation_released"), undefined); + for (const type of ["preparation_settled", "lease_revoked", "generation_registered", "generation_released"]) assert.equal(step(undefined, type), undefined); +}); + +function ownerFixture(t) { + const dir = mkdtempSync(join(tmpdir(), "aiden-daemon-owner-")); + const { admission } = api.createDaemonChats(dir); + t.after(() => rmSync(dir, { recursive: true, force: true })); + return { admission, owner: new api.DaemonTurnOwner({ admission, isDeleting: () => false }) }; +} + +const fakeRun = (streamId) => { let settle; const settled = new Promise((resolve) => { settle = resolve; }); return { streamId, ownerId: "owner", settled, settle }; }; + +test("a lease that lost its chat cannot move the turn that replaced it", (t) => { + const { owner } = ownerFixture(t); + const first = owner.begin("chat", "first", "owner"); + first.settleAsyncWork(); first.release(); + const second = owner.begin("chat", "second", "owner"); assert.ok(second); + first.release(); first.settleAsyncWork(); + assert.equal(owner.isBusy("chat"), true); + second.settleAsyncWork(); + const run = fakeRun("second"); + assert.equal(owner.handoff("chat", "second", "owner", run, () => {}), true); + first.release(); + assert.equal(owner.run("chat"), run); + assert.equal(owner.release("chat", fakeRun("stale")), false, "a stale run releases nothing"); + assert.equal(owner.run("chat"), run); + assert.equal(owner.release("chat", run), true); + assert.equal(owner.isBusy("chat"), false); +}); + +test("a handoff that fails leaves the turn to its reservation", (t) => { + const { owner } = ownerFixture(t); + const lease = owner.begin("chat", "turn", "owner"); + assert.equal(owner.handoff("chat", "turn", "owner", fakeRun("turn"), () => assert.fail("not settled")), false); + lease.settleAsyncWork(); + assert.equal(owner.handoff("chat", "other", "owner", fakeRun("other"), () => assert.fail("another turn")), false); + assert.equal(owner.run("chat"), undefined); + assert.equal(owner.isBusy("chat"), true); + lease.release(); + assert.equal(owner.isBusy("chat"), false); +}); + +/** Small seeded generator, so a failing order can be replayed from its seed. */ +function random(seed) { + let state = seed >>> 0; + return (limit) => { + state = (state + 0x6d2b79f5) >>> 0; + let value = Math.imul(state ^ (state >>> 15), 1 | state); + value = (value + Math.imul(value ^ (value >>> 7), 61 | value)) ^ value; + return ((value ^ (value >>> 14)) >>> 0) % limit; + }; +} + +test("generated event orders keep one holder per chat, capacity, and honest idle answers", async (t) => { + for (let seed = 1; seed <= 40; seed += 1) { + const { owner } = ownerFixture(t), next = random(seed), chats = ["a", "b", "c", "d", "e"]; + const leases = new Map(), runs = new Map(), idle = new Map(); + const trace = []; + for (let step = 0; step < 300; step += 1) { + const chat = chats[next(chats.length)], action = next(6), lease = leases.get(chat), run = runs.get(chat); + trace.push(`${action}:${chat}`); + if (action === 0) { + const liveChats = new Set([...runs.keys(), ...[...leases].filter(([, held]) => held.live).map(([id]) => id)]).size; + const blocked = leases.has(chat) || runs.has(chat) || liveChats >= 3; + const begun = owner.begin(chat, `turn-${step}`, "owner"); + assert.equal(begun === null, blocked, `seed ${seed}: ${trace.join(" ")}`); + if (begun) leases.set(chat, { value: begun, turn: `turn-${step}`, live: true, settled: false }); + } else if (action === 1 && lease) { + lease.value.settleAsyncWork(); lease.settled = true; + if (!lease.live) leases.delete(chat); + } else if (action === 2 && lease?.live) { + lease.value.release(); lease.live = false; + if (lease.settled) leases.delete(chat); + } else if (action === 3 && lease?.live && lease.settled) { + const started = fakeRun(lease.turn); + assert.equal(owner.handoff(chat, lease.turn, "owner", started, () => {}), true); + leases.delete(chat); runs.set(chat, started); + } else if (action === 4 && run) { + assert.equal(owner.release(chat, run), true); + run.settle(); runs.delete(chat); + } else if (action === 5 && !idle.has(chat) && (lease || run)) { + const entry = { resolved: false }; + idle.set(chat, entry); + void owner.waitForIdle(chat).then(() => { entry.resolved = true; }); + } + for (const id of chats) assert.equal(owner.isBusy(id), leases.has(id) || runs.has(id), `seed ${seed}, ${id}: ${trace.join(" ")}`); + await tick(); + for (const [id, entry] of idle) { + if (entry.resolved) { assert.equal(owner.isBusy(id), false, `seed ${seed}: an idle waiter woke while ${id} was held`); idle.delete(id); } + } + } + const remaining = owner.closeIntake(); + assert.deepEqual(new Set(remaining), new Set([...leases.keys(), ...runs.keys()]), "shutdown knows every holder"); + assert.equal(owner.begin("z", "late", "owner"), null); + for (const [chat, lease] of leases) { lease.value.settleAsyncWork(); lease.value.release(); assert.equal(owner.isBusy(chat), false); } + for (const [chat, run] of runs) { owner.release(chat, run); run.settle(); } + } +}); 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); +}); + diff --git a/packages/cli/tests/serve-lifetime.test.mjs b/packages/cli/tests/serve-lifetime.test.mjs new file mode 100644 index 0000000000..d5eb78cb18 --- /dev/null +++ b/packages/cli/tests/serve-lifetime.test.mjs @@ -0,0 +1,382 @@ +// Behavioral oracles for the `aiden serve` process (cli-native C03, C04): real +// daemon processes, their control socket and the artifacts they leave behind. +import assert from "node:assert/strict"; +import { spawn, spawnSync } from "node:child_process"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import fsPromises from "node:fs/promises"; +import { syncBuiltinESMExports } from "node:module"; +import { createConnection, createServer, Server } from "node:net"; +import { tmpdir } from "node:os"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import test from "node:test"; +import * as api from "../dist/parity-test-api.js"; + +const cli = join(resolve(dirname(fileURLToPath(import.meta.url)), ".."), "dist", "app", "cli.js"); +const posix = { skip: process.platform === "win32" }; + +function sandbox(t) { + const root = mkdtempSync(join(tmpdir(), "aiden-serve-life-")); + const home = join(root, "home"), agentDir = join(root, "agent"); + mkdirSync(home); mkdirSync(agentDir, { mode: 0o700 }); + const box = { agentDir, socket: api.daemonSocket(agentDir), lock: join(agentDir, "serve.lock"), env: { ...process.env, HOME: home, AIDEN_CODING_AGENT_DIR: agentDir, PI_OFFLINE: "1" } }; + // Hooks run in order, so the daemon has to stop here, while its directory still exists. + t.after(() => { + if (box.stopServer) run(["serve", "stop"], box.env); + rmSync(root, { recursive: true, force: true }); + }); + return box; +} + +const run = (args, env) => spawnSync(process.execPath, [cli, ...args], { encoding: "utf8", timeout: 60_000, env }); + +/** A foreground server with Remote off, resolved once its control socket answers. */ +async function foreground(t, box) { + const child = spawn(process.execPath, [cli, "serve", "--no-remote"], { env: box.env, stdio: ["ignore", "ignore", "pipe"] }); + let stderr = ""; + child.stderr.setEncoding("utf8").on("data", (part) => { stderr += part; }); + const exited = new Promise((resolveExit) => child.once("exit", (code, signal) => resolveExit({ code, signal }))); + t.after(async () => { if (child.exitCode === null && child.signalCode === null) { child.kill("SIGKILL"); await exited; } }); + const deadline = Date.now() + 30_000; + while (!stderr.includes("listening at")) { + if (child.exitCode !== null) throw new Error(`serve exited early:\n${stderr}`); + if (Date.now() > deadline) throw new Error(`serve did not become ready:\n${stderr}`); + await new Promise((resolveWait) => setTimeout(resolveWait, 25)); + } + return { child, exited, stderr: () => stderr }; +} + +/** Sends raw bytes and returns everything the daemon answered before it closed. */ +function exchange(socketPath, ...writes) { + return new Promise((resolveReply, rejectReply) => { + const socket = createConnection(socketPath); + let reply = ""; + socket.setEncoding("utf8"); + socket.on("connect", () => { for (const write of writes) socket.write(write); }); + socket.on("data", (part) => { reply += part; }); + socket.on("close", () => resolveReply(reply)); + socket.on("error", rejectReply); + }); +} + +test("a stop that arrives during startup ends it there", posix, async (t) => { + const box = sandbox(t); + const previous = { agentDir: process.env.AIDEN_CODING_AGENT_DIR, home: process.env.HOME }; + process.env.AIDEN_CODING_AGENT_DIR = box.agentDir; process.env.HOME = box.env.HOME; + const controller = new AbortController(), { listen } = Server.prototype; + // The socket is being bound, so scheduler and Telegram startup are still ahead. + Server.prototype.listen = function (...args) { controller.abort(); return listen.apply(this, args); }; + t.after(() => { + Server.prototype.listen = listen; + process.env.AIDEN_CODING_AGENT_DIR = previous.agentDir; process.env.HOME = previous.home; + }); + let ready = false; + await api.serve(box.agentDir, controller.signal, { remote: false, onReady: () => { ready = true; } }); + assert.equal(ready, false, "a cancelled startup never reports ready"); + assert.equal(existsSync(box.socket), false); + assert.equal(existsSync(box.lock), false); +}); + +test("a stop in the last step of startup still never reports ready", posix, async (t) => { + const box = sandbox(t); + const previous = { agentDir: process.env.AIDEN_CODING_AGENT_DIR, home: process.env.HOME }; + process.env.AIDEN_CODING_AGENT_DIR = box.agentDir; process.env.HOME = box.env.HOME; + const controller = new AbortController(), { write } = process.stderr; + // These lines are written once every service has started, just before ready. + process.stderr.write = function (chunk, ...rest) { + if (String(chunk).includes("listening at")) controller.abort(); + return write.call(this, chunk, ...rest); + }; + t.after(() => { + process.stderr.write = write; + process.env.AIDEN_CODING_AGENT_DIR = previous.agentDir; process.env.HOME = previous.home; + }); + let ready = false; + await api.serve(box.agentDir, controller.signal, { remote: false, onReady: () => { ready = true; } }); + assert.equal(ready, false); + assert.equal(existsSync(box.lock), false); +}); + +test("a stopped server leaves nothing behind and a new one takes over at once", posix, async (t) => { + const box = sandbox(t); + box.stopServer = true; + assert.equal(run(["serve", "--daemon", "--no-remote"], box.env).status, 0); + const first = JSON.parse(readFileSync(join(box.lock, "owner.json"), "utf8")); + const stopped = run(["serve", "stop"], box.env); + assert.equal(stopped.status, 0, stopped.stderr); + assert.equal(existsSync(box.lock), false); + assert.equal(existsSync(box.socket), false); + const again = run(["serve", "--daemon", "--no-remote"], box.env); + assert.equal(again.status, 0, again.stderr); + const second = JSON.parse(readFileSync(join(box.lock, "owner.json"), "utf8")); + assert.notEqual(second.pid, first.pid); + assert.notEqual(second.token, first.token); +}); + +test("a second server is refused while the first holds the lease, and the first is unharmed", posix, async (t) => { + const box = sandbox(t); + const server = await foreground(t, box); + const second = run(["serve", "--no-remote"], box.env); + assert.notEqual(second.status, 0); + assert.match(second.stderr, /Another Aiden process owns/u); + assert.equal(JSON.parse(await exchange(box.socket, `${JSON.stringify({ command: "serve", args: ["status"] })}\n`)).result.remote.on, false); + server.child.kill("SIGTERM"); + assert.deepEqual(await server.exited, { code: 0, signal: null }, server.stderr()); +}); + +test("a failed startup releases its lease and the next start succeeds", posix, async (t) => { + const box = sandbox(t); + // A directory at the socket path cannot be cleared, so startup fails after the lease is taken. + mkdirSync(join(box.socket, "occupied"), { recursive: true }); + const failed = run(["serve", "--no-remote"], box.env); + assert.notEqual(failed.status, 0); + assert.equal(existsSync(box.lock), false, "the lease went with the failed start"); + rmSync(box.socket, { recursive: true, force: true }); + const server = await foreground(t, box); + server.child.kill("SIGTERM"); + assert.deepEqual(await server.exited, { code: 0, signal: null }, server.stderr()); +}); + +test("an idle or half-sent control client does not hold up shutdown", posix, async (t) => { + const box = sandbox(t); + const server = await foreground(t, box); + const idle = createConnection(box.socket), partial = createConnection(box.socket); + idle.on("error", () => {}); partial.on("error", () => {}); + await new Promise((resolveWait) => partial.once("connect", resolveWait)); + partial.write('{"command":"serve"'); + await new Promise((resolveWait) => setTimeout(resolveWait, 50)); + server.child.kill("SIGTERM"); + assert.deepEqual(await server.exited, { code: 0, signal: null }, server.stderr()); + assert.equal(existsSync(box.socket), false); + assert.equal(existsSync(box.lock), false); + idle.destroy(); partial.destroy(); +}); + +test("the control socket answers one framed request per connection and refuses malformed ones", posix, async (t) => { + const box = sandbox(t); + await foreground(t, box); + const status = `${JSON.stringify({ command: "serve", args: ["status"] })}\n`; + // A request may arrive in pieces; only its newline frames it. + assert.deepEqual(JSON.parse(await exchange(box.socket, status.slice(0, 5), status.slice(5))), { result: { remote: { on: false } } }); + // Anything after the first frame is ignored, however the bytes were split. + assert.deepEqual(JSON.parse(await exchange(box.socket, status + status)), { result: { remote: { on: false } } }); + assert.match(await exchange(box.socket, "not json\n"), /"error"/u); + assert.match(await exchange(box.socket, `${JSON.stringify({ command: "shell", args: [] })}\n`), /Invalid daemon command/u); + assert.match(await exchange(box.socket, `${JSON.stringify({ command: "serve", args: [1] })}\n`), /Invalid daemon command/u); + assert.match(await exchange(box.socket, `${JSON.stringify({ command: "remote", args: ["status"] })}\n`), /Remote is off/u); + // The ceiling is on the frame, so bytes after a request that fits cannot push it over. + const full = `${JSON.stringify({ command: "serve", args: ["status"], padding: "x".repeat(65_000) })}\n`; + const fits = await new Promise((resolveReply, rejectReply) => { + const socket = createConnection(box.socket); + let reply = ""; + socket.setEncoding("utf8").on("data", (part) => { reply += part; }).on("close", () => resolveReply(reply)).on("error", rejectReply); + socket.on("connect", () => { + socket.write(full.slice(0, 60_000)); + setTimeout(() => socket.write(`${full.slice(60_000)}${"y".repeat(10_000)}`), 100); + }); + }); + assert.deepEqual(JSON.parse(fits), { result: { remote: { on: false } } }); + // A request with no newline inside the byte ceiling is cut off, with no reply. + assert.equal(await exchange(box.socket, "x".repeat(70_000)), ""); + assert.deepEqual(JSON.parse(await exchange(box.socket, status)), { result: { remote: { on: false } } }, "the server is still healthy"); +}); + +test("shutdown keeps the lease until a running control command has answered", posix, async (t) => { + const box = sandbox(t), controller = new AbortController(), ready = Promise.withResolvers(); + const serving = api.serve(box.agentDir, controller.signal, { onReady: ready.resolve }); + void serving.catch(ready.reject); + await ready.promise; + const workspace = await api.remoteDaemonCommand(box.agentDir, "workspace", ["add", box.agentDir]); + // Workspace changes look at the chat index first, which gives the test a place to hold one. + const { stat } = fsPromises, reached = Promise.withResolvers(), held = Promise.withResolvers(); + fsPromises.stat = async (...args) => { + if (String(args[0]).endsWith("index.json")) { reached.resolve(); await held.promise; } + return stat(...args); + }; + syncBuiltinESMExports(); + t.after(() => { fsPromises.stat = stat; syncBuiltinESMExports(); }); + const answer = api.remoteDaemonCommand(box.agentDir, "workspace", ["access", workspace.id, "none"]); + await reached.promise; + controller.abort(); + let released = false; + void serving.then(() => { released = true; }); + await new Promise((resolveWait) => setTimeout(resolveWait, 300)); + assert.equal(released, false, "the command is still changing state"); + assert.equal(existsSync(box.lock), true); + held.resolve(); + assert.equal((await answer).access, "none", "the client hears how its command ended"); + await serving; + assert.equal(existsSync(box.lock), false); + assert.equal(existsSync(box.socket), false); +}); + +test("shutdown delivers the whole reply to a client that reads it slowly", posix, async (t) => { + const box = sandbox(t), controller = new AbortController(), ready = Promise.withResolvers(); + const serving = api.serve(box.agentDir, controller.signal, { onReady: ready.resolve }); + void serving.catch(ready.reject); + t.after(() => { controller.abort(); return serving.catch(() => {}); }); + await ready.promise; + const workspace = await api.remoteDaemonCommand(box.agentDir, "workspace", ["add", box.agentDir]); + const input = join(box.agentDir, "input.json"); + writeFileSync(input, JSON.stringify({ name: "Large", mode: "llm", cron: "0 9 * * *", timezone: "UTC", prompt: "Review", permission: "read-only", enabled: false, workspaceId: workspace.id })); + await api.remoteDaemonCommand(box.agentDir, "schedule", ["save", input]); + // Far more than a socket buffers, so the reply cannot finish until the client reads. + const file = join(box.agentDir, "schedules.json"), [task] = JSON.parse(readFileSync(file, "utf8")); + api.atomicJson(file, [{ ...task, prompt: "x".repeat(4 * 1024 * 1024) }]); + const client = createConnection(box.socket); + client.pause(); + client.write(`${JSON.stringify({ command: "schedule", args: ["list"] })}\n`); + await new Promise((resolveWait) => setTimeout(resolveWait, 300)); + controller.abort(); + await new Promise((resolveWait) => setTimeout(resolveWait, 300)); + const chunks = [], closed = new Promise((resolveClose) => client.once("close", resolveClose)); + client.on("data", (part) => chunks.push(part)).on("error", () => {}); + client.resume(); + await closed; + const { result } = JSON.parse(Buffer.concat(chunks).toString("utf8")); + assert.equal(result[0].prompt.length, 4 * 1024 * 1024); + await serving; + assert.equal(existsSync(box.lock), false); +}); + +test("serve phases only move forward and draining waits for every accepted command", async () => { + const lifetime = new api.ServeLifetime(); + assert.equal(lifetime.acceptsCommands, true, "commands are answered while services start"); + lifetime.markServing(); + assert.equal(lifetime.phase, "serving"); + const first = Promise.withResolvers(), second = Promise.withResolvers(); + lifetime.track(first.promise); lifetime.track(second.promise); + lifetime.beginDrain(); + assert.equal(lifetime.acceptsCommands, false); + lifetime.markServing(); + assert.equal(lifetime.phase, "draining", "a late ready report cannot reopen the socket"); + let settled = false; + const settling = lifetime.settleCommands().then(() => { settled = true; }); + first.reject(new Error("answered already")); + await new Promise((resolveWait) => setImmediate(resolveWait)); + assert.equal(settled, false); + second.resolve(); + await settling; + assert.equal(settled, true); +}); + +test("a daemon PID that stops being ours before the stop deadline is never killed or blamed", posix, async (t) => { + const box = sandbox(t), script = join(box.agentDir, "becomes-foreign.sh"); + // Ignores TERM like a stuck daemon, then its PID stops being a daemon at all. + writeFileSync(script, "trap '' TERM\nsleep 0.5\nexec sleep 30\n"); + const child = spawn("/bin/sh", [script, "serve"], { stdio: "ignore" }); + t.after(() => { child.kill("SIGKILL"); }); + mkdirSync(box.lock, { mode: 0o700 }); + writeFileSync(join(box.lock, "owner.json"), JSON.stringify({ pid: child.pid, argv: ["/bin/sh", script, "serve"], startedAt: 1, token: "legacy" })); + await new Promise((resolveWait) => setTimeout(resolveWait, 150)); + assert.deepEqual(await api.stopDaemon(box.agentDir, 1_000), { stopped: true, pid: child.pid }); + assert.equal(child.exitCode, null); + assert.equal(child.signalCode, null, "the unrelated process was left alone"); + assert.equal(existsSync(box.lock), false, "its stale lease is gone"); +}); + +test("a stop that cannot confirm its owner at the deadline signals nothing and advises no kill", posix, async (t) => { + const box = sandbox(t), script = join(box.agentDir, "becomes-command.sh"), entry = join(box.agentDir, "entry.js"); + writeFileSync(entry, "setInterval(() => {}, 1000);\n"); + // Ignores TERM like a stuck daemon, then its PID shows another Aiden command. + writeFileSync(script, `trap '' TERM\nsleep 0.5\nexec "${process.execPath}" "${entry}" schedule\n`); + const previous = process.env.AIDEN_CLI_ENTRY; + process.env.AIDEN_CLI_ENTRY = entry; + const child = spawn("/bin/sh", [script, "serve"], { stdio: "ignore" }); + t.after(() => { + child.kill("SIGKILL"); + if (previous === undefined) delete process.env.AIDEN_CLI_ENTRY; else process.env.AIDEN_CLI_ENTRY = previous; + }); + mkdirSync(box.lock, { mode: 0o700 }); + writeFileSync(join(box.lock, "owner.json"), JSON.stringify({ pid: child.pid, argv: ["/bin/sh", script, "serve"], startedAt: 1, token: "legacy" })); + await new Promise((resolveWait) => setTimeout(resolveWait, 150)); + await assert.rejects(api.stopDaemon(box.agentDir, 1_000), (error) => { + assert.match(error.message, /could not confirm/iu); + assert.doesNotMatch(error.message, /kill/u); + return true; + }); + assert.equal(child.exitCode, null); + assert.equal(child.signalCode, null, "the process was left alone"); + assert.equal(existsSync(box.lock), true, "its lease is not ours to clear"); +}); + +test("stop signals only a verified daemon, at the start and at the deadline", () => { + assert.equal(api.decideServeStopStart("daemon"), "signal"); + for (const owner of ["gone", "foreign"]) assert.equal(api.decideServeStopStart(owner), "clear_stale"); + assert.equal(api.decideServeStopStart("aiden"), "refuse_aiden"); + assert.equal(api.decideServeStopStart("unknown"), "refuse_unverified"); + assert.equal(api.decideServeStopDeadline("daemon", true), "force"); + assert.equal(api.decideServeStopDeadline("daemon", false), "stopped", "a replacement daemon is not the one asked to stop"); + for (const owner of ["gone", "foreign"]) assert.equal(api.decideServeStopDeadline(owner, true), "clear_stale"); + for (const owner of ["aiden", "unknown"]) assert.equal(api.decideServeStopDeadline(owner, true), "unconfirmed"); +}); + +test("two daemon starts cannot both spawn", posix, async (t) => { + const box = sandbox(t); + box.stopServer = true; + const release = api.acquireLease(join(box.agentDir, "serve-start")); + const refused = run(["serve", "--daemon", "--no-remote"], box.env); + assert.notEqual(refused.status, 0); + assert.match(refused.stderr, /Another daemon start is already in progress/u); + release(); + assert.equal(existsSync(box.lock), false, "the refused start spawned nothing"); + assert.equal(run(["serve", "--daemon", "--no-remote"], box.env).status, 0); + const again = run(["serve", "--daemon", "--no-remote"], box.env); + assert.notEqual(again.status, 0); + assert.match(again.stderr, /already running/u); +}); + +/** A fake daemon that answers every connection with the given bytes. */ +async function fakeDaemon(t, answer) { + const box = sandbox(t); + const server = createServer((socket) => { socket.on("data", () => answer(socket)); socket.on("error", () => {}); }); + await new Promise((resolveListen) => server.listen(box.socket, resolveListen)); + t.after(() => new Promise((resolveClose) => { server.close(resolveClose); })); + return box.agentDir; +} + +test("the command client settles once for every way a daemon can answer", posix, async (t) => { + assert.deepEqual(await api.remoteDaemonCommand(await fakeDaemon(t, (socket) => socket.end('{"result":{"ok":true}}\n')), "serve", ["status"]), { ok: true }); + await assert.rejects(api.remoteDaemonCommand(await fakeDaemon(t, (socket) => socket.end('{"error":"Refused."}\n')), "serve", ["status"]), /Refused\./u); + await assert.rejects(api.remoteDaemonCommand(await fakeDaemon(t, (socket) => socket.end()), "serve", ["status"]), /closed without a response/u); + await assert.rejects(api.remoteDaemonCommand(await fakeDaemon(t, (socket) => socket.end('{"partial"')), "serve", ["status"]), /closed without a response/u); + await assert.rejects(api.remoteDaemonCommand(await fakeDaemon(t, (socket) => socket.end("not json\n")), "serve", ["status"]), SyntaxError); + await assert.rejects(api.remoteDaemonCommand(await fakeDaemon(t, (socket) => { socket.write("x".repeat(9 * 1024 * 1024)); }), "serve", ["status"]), /too large/u); + // The ceiling holds even when the chunk that crosses it also completes the frame. + const oversized = JSON.stringify({ result: "x".repeat(8 * 1024 * 1024 - 8) }); + const crossing = await fakeDaemon(t, (socket) => { + socket.write(oversized.slice(0, -16)); + setTimeout(() => socket.end(`${oversized.slice(-16)}\n`), 100); + }); + await assert.rejects(api.remoteDaemonCommand(crossing, "serve", ["status"]), /too large/u); + // The ceiling is on the frame, so bytes after a reply that fits cannot push it over. + const fits = "x".repeat(8 * 1024 * 1024 - 64), framed = JSON.stringify({ result: fits }); + const padded = await fakeDaemon(t, (socket) => { + socket.write(framed.slice(0, -16)); + setTimeout(() => socket.end(`${framed.slice(-16)}\n${"y".repeat(1024)}`), 100); + }); + assert.equal((await api.remoteDaemonCommand(padded, "serve", ["status"])).length, fits.length); + // Once the first frame settles the command, a peer that keeps writing is cut off. + const peer = sandbox(t), peerClosed = Promise.withResolvers(); + let accepted; + const talkative = createServer({ allowHalfOpen: true }, (socket) => { + accepted = socket; + socket.on("error", () => {}); + socket.once("data", () => { + socket.write('{"result":"ok"}\n'); + const flood = setInterval(() => socket.write("y".repeat(1024)), 5); + socket.once("close", () => { clearInterval(flood); peerClosed.resolve("closed"); }); + }); + }); + await new Promise((resolveListen) => talkative.listen(peer.socket, resolveListen)); + // A failed assertion must not leave cleanup waiting on a peer that is still writing. + t.after(() => new Promise((resolveClose) => { accepted?.destroy(); talkative.close(resolveClose); })); + assert.equal(await api.remoteDaemonCommand(peer.agentDir, "serve", ["status"]), "ok"); + const timedOut = new Promise((resolveWait) => setTimeout(resolveWait, 1_000, "still connected").unref()); + assert.equal(await Promise.race([peerClosed.promise, timedOut]), "closed"); + // The reply is its first frame: bytes after the newline do not turn it into an error. + const trailing = await fakeDaemon(t, (socket) => { socket.end(`${JSON.stringify({ result: "ok" })}\nleftover`); }); + assert.equal(await api.remoteDaemonCommand(trailing, "serve", ["status"]), "ok"); + const missing = sandbox(t); + await assert.rejects(api.remoteDaemonCommand(missing.agentDir, "serve", ["status"]), (error) => error.code === "ENOENT" && /not running/u.test(error.message)); +});