Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
f65f266
Finish interrupted chat deletions on every server
sambitcreate Nov 5, 2026
7c5a7de
Give schedule consent one phase and behavioral coverage
sambitcreate Nov 5, 2026
24e47ee
Record C15 and triage the remaining cli-native entries
sambitcreate Nov 5, 2026
8678c5a
Bind schedule consent to the reviewed input, once
sambitcreate Nov 5, 2026
3bb8964
Remove a schedule receipt when its command ends
sambitcreate Nov 5, 2026
67eaa64
Document that every server finishes interrupted deletions
sambitcreate Nov 5, 2026
0dadb47
Record Lane D review lessons
sambitcreate Nov 5, 2026
799a7a4
Merge branch 'feature/sm-serve-framing' into feature/sm-serve-chat-re…
sambitcreate Nov 5, 2026
50a02d2
Refuse to start when the deletion record is unreadable
sambitcreate Nov 5, 2026
37c7311
Merge branch 'feature/sm-serve-chat-recovery' into feature/sm-serve-s…
sambitcreate Nov 5, 2026
b981b16
Merge branch 'feature/sm-serve-framing' into feature/sm-serve-chat-re…
sambitcreate Nov 5, 2026
3f35155
Merge branch 'feature/sm-serve-chat-recovery' into feature/sm-serve-s…
sambitcreate Nov 5, 2026
da59192
Merge branch 'feature/sm-serve-framing' into feature/sm-serve-chat-re…
sambitcreate Nov 5, 2026
c1cafd2
Merge branch 'feature/sm-serve-chat-recovery' into feature/sm-serve-s…
sambitcreate Nov 5, 2026
37fd8a8
Update the Lane D approval note
sambitcreate Nov 5, 2026
0138204
Consume schedule consent at its first write
sambitcreate Nov 5, 2026
89590a8
Treat a deletion record of non-ids as unreadable
sambitcreate Nov 5, 2026
e99cd4b
Merge branch 'feature/sm-serve-chat-recovery' into feature/sm-serve-s…
sambitcreate Nov 5, 2026
f210556
Merge branch 'feature/sm-serve-chat-recovery' into feature/sm-serve-s…
sambitcreate Nov 5, 2026
1b4fb7c
Merge branch 'feature/sm-serve-framing' into feature/sm-serve-chat-re…
sambitcreate Nov 5, 2026
09f48d7
Let a revocation win the race for the receipt
sambitcreate Nov 5, 2026
741a95d
Merge pull request #765 from sambitcreate/feature/sm-serve-schedule-c…
sambitcreate Nov 6, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .memory/explicit-state-machines-lane-d.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,10 @@ Started 2026-11-04. Scope: `cli-native` C09, C10, C03, C01, C02, C11, C04, then
- `DaemonTurnOwner` (`packages/cli/src/daemon-turn-lifecycle.ts`) is the only writer of chat custody. Lane A's #735 keeps the lease API, so this does not stack on it; its doc home is `docs/state-machines/`.
- Never await `cancelChat` from inside a tool_call or before_agent_start hook: `session.abort()` waits for the very hook that called it.
- `.memory/` is gitignored but tracked: new files need `git add -f`.
- C15 converted to one `phase`. Triage of the other `C*` entries is at the end of `docs/state-machines/serve-daemon.md`.
- C18 and C19 are blocked on the subagent upgrade branch, which rewrites those files. C05 waits on #733. C12, C16, C28 and C32 are P6.
- No file outside `packages/cli`, `docs/state-machines` and `.memory` changed, so no mobile contract moved.
- Cleanup hooks in `node:test` (`t.after`) run in registration order here, so stop a daemon before removing its directory. `box.stopServer` in `tests/serve-lifetime.test.mjs` does that; an earlier `t.after(serve stop)` orphaned real daemons.
- The local shell is zsh: an unquoted `$files` is one argument, so a looped `node --test $files` silently runs nothing. Check that a pass count came back.
- Control-socket chunks stop near 64 KiB, so a ceiling test needs a frame near the limit plus a later write, not one big write.
- `createDaemonApprovals` reports each raised prompt once from the settled outcome, so it does not rely on the coordinator's published flag, on `main` or after Lane B's #738.
60 changes: 60 additions & 0 deletions docs/state-machines/serve-daemon.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,3 +131,63 @@ Owners: `remoteDaemonCommand` (`daemon-control.ts`) and the socket handler in `s
**Defect fixed:** both ends parsed their whole buffer, so a frame followed by more bytes in the same chunk failed as bad JSON, while the same bytes in two chunks succeeded. Each end now reads only its first frame, and its ceiling applies to that frame alone. The client closes on that frame, so a peer that keeps writing can neither grow its buffer nor keep it alive.

**Defect fixed:** when the chunk that crossed the 8 MiB ceiling also completed the frame, the client destroyed the socket and then parsed and returned the reply anyway, so the ceiling did not hold on the last chunk.

## C14: interrupted chat deletion

Owner: `recoverChatDeletions` in `daemon-chats.ts`, over the `daemon-chat-deletions.json` tombstones and `ChatDeletionGate`. The file format is unchanged.

| Event | Prior | Next | Effect |
|---|---|---|---|
| daemon constructed | tombstone on disk | chat closed | `ChatDeletionGate` held, so `beginChatTurn` refuses |
| recovery | closed | closed | bot history, journal, then chat record removed, each repeatable |
| tombstone removed | closed | gone | gate released |
| any step fails | closed | closed | tombstone kept, retried on the next start |
| record unreadable | unknown | every chat closed | no server starts, Remote or not |

Recovery runs in `serve` for every server. A failure there is logged and closes only those chats. `createCliRemoteChats` runs it again and still fails startup, because Remote must not list a chat whose deletion is stuck.

**Defect fixed:** recovery lived only in `createCliRemoteChats`, so `aiden serve --no-remote` neither finished a committed deletion nor closed the chat to new turns.

## C15: schedule consent publication

Owner: `approvedMutation` in `createCliScheduler` (`schedules.ts`) over `assertScheduleApproval` (`schedule-tool-approval.ts`). Two booleans became one `phase`.

| Event | Prior | Next | Effect |
|---|---|---|---|
| command with consent | none | `first_write` | snapshot, expiry and receipt verified at entry |
| durable write verified | `first_write` | `follow_on` | receipt consumed just before the write publishes, task checked once; later writes check only expiry and the environment |
| verification fails | `first_write` or `follow_on` | `closed` | abort, so the shared lifecycle rolls back |
| command ends | any | `closed` | this context is finished, and its receipt is spent |

A receipt is spent in memory as the command starts, removed at the first write, and removed when the command ends if no write happened. It works once even if the command fails, and neither another scheduler nor a restart after a crash can replay it. A crash between that removal and the write loses the consent, so the person reviews again. Revocation holds up to the first write. A `save` must also read back the input that was reviewed, because the file is read after consent.

**Defects fixed:** a `save` trusted whatever the file held by then, and a new-task consent could be replayed until it expired, since only the retired producer ever removed the receipt.

No producer of consent remains in `src` since the model-facing tool was retired; only this guard is live. It had no tests, so `tests/schedule-consent.test.mjs` covers valid, reused, expired, cancelled, mismatched, and environment or task changed after review, and revocation between the entry check and the write.

## Triage of the remaining `cli-native` entries

"Retained" means already explicit or fenced, with the listed coverage, and no conversion here would add a guarantee. None of these was reproduced as a defect.

| Entry | On the serve path | Disposition |
|---|---|---|
| C05 service install | No, admin command | Deferred: #733 and the subagent upgrade branch both change `service.ts`. Covered by `tests/service.test.mjs`. |
| C06 pairing presentation | Startup only | Retained: presentation, and #733 changes `serve-command.ts`. |
| C07 Tailscale health wait | Startup only | Retained: single settlement and a byte bound, covered by `tests/reachability.test.mjs`. |
| C08 Linux Bonjour | Yes, Linux | Retained: generation and child identity already fence late callbacks. Not exercised against real avahi here. |
| C12 Bot pause | Yes | Deferred to P6: the shared pause store and durable runtime own it. It reuses `stopChatWork`, which now waits on C09 settlement. |
| C13 durable Bot migration | Admin command | Retained: `preparing` and `enabled` are already an explicit durable marker. |
| C16 scheduled execution | Yes | Deferred to P6: the shared scheduler owns timing and revisions; drain already awaits `stopAndSettle`. |
| C17 inference metering | Yes | Retained: an algorithmic streaming counter, deferred after P6 by the plan. |
| C18, C19 child inference and worker RPC | Yes, through Bot subagents | Blocked: the subagent upgrade branch rewrites `subagent-process.ts` and `subagent-worker.ts`. Revisit after it lands. |
| C20 MCP connection incarnation | Yes | Retained: entry identity fences every await, covered by the MCP pool cases in `tests/parity.test.mjs`. |
| C21 terminal provider auth | No | Skipped: interactive terminal only. |
| C22 speech worker | Yes, through Remote | Retained: worker and client identity already fence late exits, and Remote stop awaits `speech.stop()`. |
| C23 avatar decoder | Yes, through Remote Bots | Retained: bounded slots with `finally` cleanup, deferred after P6 by the plan. |
| C24 lease and JSON publication | Yes | Retained: idempotent release and a failed publication that releases its guard. C03, C14 and C15 rely on it unchanged. |
| C25, C30, C31 credentials | Reads only | Retained: per-file queue plus lease; migrations are explicit transactions outside the daemon's turn path. |
| C26 todo restore | Yes, inside sessions | Retained: `restoreEpoch` fences late restores, covered by the todo cases in `tests/parity.test.mjs`. |
| C27 advisor availability | Yes, inside sessions | Retained: the shared advisor runtime owns attempts, deferred after P6 by the plan. |
| C28 Bot inventory invalidation | Yes | Deferred to P6 with the shared Bot authority owners. |
| C29 MCP config migration | Store construction | Retained: an explicit publish-then-retire transaction. |
| C32 usage accounting | Yes | Deferred to P6: receipt and aggregate already publish together. |
2 changes: 1 addition & 1 deletion packages/cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
2 changes: 1 addition & 1 deletion packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
],
"scripts": {
"build": "node scripts/patch-branding.mjs && node scripts/build.mjs",
"test": "node --test tests/bundle.test.mjs tests/runtime.test.mjs tests/extensions.test.mjs tests/parity.test.mjs tests/serve-startup.test.mjs tests/service.test.mjs tests/reachability.test.mjs tests/inbox-host.test.mjs tests/daemon-turns.test.mjs tests/serve-lifetime.test.mjs",
"test": "node --test tests/bundle.test.mjs tests/runtime.test.mjs tests/extensions.test.mjs tests/parity.test.mjs tests/serve-startup.test.mjs tests/service.test.mjs tests/reachability.test.mjs tests/inbox-host.test.mjs tests/daemon-turns.test.mjs tests/serve-lifetime.test.mjs tests/schedule-consent.test.mjs",
"type-check": "tsc --noEmit"
},
"dependencies": {
Expand Down
32 changes: 30 additions & 2 deletions packages/cli/src/daemon-chats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import type { CliBotGenerationRuntime } from "./bots.ts";
import type { BotRuntimeAuthorityAdmission } from "../../../main/services/bot-runtime-authority.js";
import { assertBotRuntimeProviderSelection } from "../../../main/services/bot-runtime-authority.js";
import { mkdirSync } from "node:fs";
import { rm } from "node:fs/promises";
import { createHash } from "node:crypto";
import { join } from "node:path";
import { createAgentSession, DefaultResourceLoader, SessionManager, type AgentSession } from "@earendil-works/pi-coding-agent";
Expand All @@ -26,7 +27,8 @@ import { ChatTurnAdmission } from "../../../main/services/chat-turn-admission.js
import { ChatDeletionGate } from "../../../main/services/chat-deletion-gate.js";
import { parseAttachments, withReadableImages } from "../../../main/services/attachment-contract.js";
import { createCliModelRuntime } from "./providers.ts";
import { acquireLease } from "./state.ts";
import { acquireLease, JsonStore, readJson } from "./state.ts";
import { deleteCliBotSubagentHistory } from "./bot-subagents.ts";
import { DaemonGenerationRun, DaemonTurnOwner } from "./daemon-turn-lifecycle.ts";
import { createDaemonApprovals } from "./daemon-approvals.ts";
import { workspaceStore, accessFor } from "./workspaces.ts";
Expand Down Expand Up @@ -68,7 +70,20 @@ export function createDaemonChats(agentDir: string) {
const recorders = createHostRunRecorders((_scope, message) => process.stderr.write(`aiden: ${message}\n`));
const admission = new ChatTurnAdmission();
const deletion = new ChatDeletionGate();
const turns = new DaemonTurnOwner<DaemonGenerationRun<AgentSession>>({ admission, isDeleting: (id) => deletion.isDeleting(id) });
// A journal deletion is a durable roll-forward checkpoint, including after a crash:
// its chat stays closed from here until recoverChatDeletions finishes the job.
const tombstones = new JsonStore<string[]>(join(agentDir, "daemon-chat-deletions.json"), []);
const interrupted = new Map<string, () => 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<string[]>(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<DaemonGenerationRun<AgentSession>>({ 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); },
Expand Down Expand Up @@ -310,6 +325,19 @@ export function createDaemonChats(agentDir: string) {
}
return { chatStore, llmClient, activity, runs, admission, deletion, sessionPath,
/** Every activity change (a run began or ended, an approval was raised or settled). */
/** Finishes deletions a crash interrupted. Repeatable: a failure leaves its tombstone and its chat closed. */
/** Unlike a deletion that fails to finish, a lost record cannot be scoped to its chats. */
assertChatDeletionsReadable() { if (deletionRecordFailure) throw deletionRecordFailure; },
async recoverChatDeletions() {
if (deletionRecordFailure) throw deletionRecordFailure;
for (const [id, reopen] of [...interrupted]) {
await deleteCliBotSubagentHistory(agentDir, id);
await rm(sessionPath(id), { force: true });
if (await chatStore.get(id)) await chatStore.remove(id);
await tombstones.update((values) => { for (let index = values.indexOf(id); index >= 0; index = values.indexOf(id)) values.splice(index, 1); });
interrupted.delete(id); reopen();
}
},
onActivityChange(listener: (snapshot: ChatActivitySnapshot) => void) { activityListeners.add(listener); return () => { activityListeners.delete(listener); }; },
setBots(runtime: CliBotGenerationRuntime) { bots = runtime; },
/** Closes intake before its first await, so no ingress stopping alongside it can begin a turn. */
Expand Down
1 change: 1 addition & 0 deletions packages/cli/src/parity-test-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export * from "./sessions.ts";
export * from "./providers.ts";
export * from "./credentials.ts";
export * from "./schedules.ts";
export * from "./schedule-tool-approval.ts";
export * from "./serve.ts";
export * from "./serve-lifecycle.ts";
export * from "./serve-lifetime.ts";
Expand Down
9 changes: 2 additions & 7 deletions packages/cli/src/remote-chats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,8 @@ import { liveRunAttention } from "../../../main/services/chat-pending-attention.
export async function createCliRemoteChats(agentDir: string, daemon: ReturnType<typeof createDaemonChats>, workspace: ReturnType<typeof createCliWorkspaceApplication>, state: AidenRemoteStateRegistry,
idempotency: AidenIdempotencyLedger, persistIdempotency: (value: AidenIdempotencySnapshot) => Promise<void>, bots: Awaited<ReturnType<typeof createCliBots>>) {
const deleting = new JsonStore<string[]>(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); }); },
Expand Down
9 changes: 8 additions & 1 deletion packages/cli/src/schedule-tool-approval.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown> {
const { action: _action, ...input } = approval.input as Record<string, unknown>;
return input;
}

export const isScheduleMutation = (action: unknown): boolean =>
action === "save" || action === "pause" || action === "resume" || action === "remove";

Expand Down Expand Up @@ -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<string, unknown>;
Expand Down
Loading
Loading