Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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.
44 changes: 44 additions & 0 deletions docs/state-machines/serve-daemon.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,3 +147,47 @@ Owner: `recoverChatDeletions` in `daemon-chats.ts`, over the `daemon-chat-deleti
Recovery runs in `serve` for every server. A failure there is logged and closes only those chats. `createCliRemoteChats` runs it again and still fails startup, because Remote must not list a chat whose deletion is stuck.

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

## C15: schedule consent publication

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

| Event | Prior | Next | Effect |
|---|---|---|---|
| command with consent | none | `first_write` | snapshot, expiry and receipt verified at entry |
| durable write verified | `first_write` | `follow_on` | 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/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
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: 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
43 changes: 32 additions & 11 deletions packages/cli/src/schedules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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<string> {
if (!providerId || !modelId) throw new Error("Select an explicit provider and model for unattended inference.");
Expand All @@ -25,25 +26,38 @@ 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<string>();
const approvedMutation = new AsyncLocalStorage<{ approval: ScheduleToolApproval; phase: "first_write" | "follow_on" | "closed"; cancellation: AbortController }>();
const persistence = new JsonStore<unknown[]>(join(agentDir, "schedules.json"), []);
const tasks = {
load: () => persistence.load(),
update<R>(mutation: (draft: unknown[]) => R | Promise<R>, isCurrent?: () => boolean): Promise<R> {
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;
});
Expand Down Expand Up @@ -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);
Comment thread
sambitcreate marked this conversation as resolved.
Resolved
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) {
Expand Down Expand Up @@ -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 };
Expand Down
Loading
Loading