@staix/agent-hub 0.12.19 → 0.12.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +3 -3
  3. package/docs/agent-notes/adapters.md +1 -0
  4. package/docs/agent-notes/bus.md +1 -0
  5. package/docs/agent-notes/daemon.md +2 -1
  6. package/docs/agent-notes/models.md +3 -0
  7. package/docs/agent-notes/tasks.md +3 -2
  8. package/docs/events.md +4 -1
  9. package/docs/operations.md +413 -17
  10. package/docs/quickstart.md +1 -1
  11. package/docs/security.md +17 -10
  12. package/docs/smoke.md +58 -0
  13. package/docs/specs/2026-09-19-agent-hub-design.md +399 -3
  14. package/docs/specs/2026-09-20-pi-local-models-design.md +2 -0
  15. package/docs/specs/2026-09-20-upgrade-recovery-design.md +287 -0
  16. package/docs/specs/2026-10-04-switchyard-source-port-design.md +10 -0
  17. package/docs/verified.json +13 -13
  18. package/package.json +1 -1
  19. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  20. package/plugins/agent-hub/server.js +63 -25
  21. package/src/adapters/claude-channel.ts +61 -20
  22. package/src/adapters/codex-appserver.ts +3 -0
  23. package/src/adapters/local-worker.ts +4 -0
  24. package/src/cli/console-state.ts +325 -102
  25. package/src/cli/console.ts +44 -23
  26. package/src/cli/help.ts +120 -0
  27. package/src/cli/identity.ts +3 -3
  28. package/src/cli/launch.ts +2 -0
  29. package/src/cli/main.ts +171 -75
  30. package/src/cli/preview.ts +1 -0
  31. package/src/cli/reset.ts +194 -0
  32. package/src/cli/status-lines.ts +9 -5
  33. package/src/cli/terminal-recovery.ts +140 -36
  34. package/src/cli/upgrade-runtime.ts +274 -56
  35. package/src/cli/upgrade.ts +366 -41
  36. package/src/hub/ask.ts +1 -1
  37. package/src/hub/board.ts +15 -7
  38. package/src/hub/bus.ts +60 -4
  39. package/src/hub/child-process.ts +1 -0
  40. package/src/hub/conductor.ts +38 -6
  41. package/src/hub/control-client.ts +5 -3
  42. package/src/hub/daemon.ts +56 -9
  43. package/src/hub/events.ts +7 -1
  44. package/src/hub/execution-budget.ts +15 -6
  45. package/src/hub/hub-tools.ts +4 -4
  46. package/src/hub/inference.ts +136 -1
  47. package/src/hub/lifecycle.ts +7 -1
  48. package/src/hub/peers.ts +2 -0
  49. package/src/hub/recovery-store.ts +51 -3
  50. package/src/hub/report.ts +43 -1
  51. package/src/hub/restart.ts +25 -0
  52. package/src/hub/routing.ts +48 -16
  53. package/src/hub/snapshots.ts +3 -2
  54. package/src/hub/tasks.ts +236 -83
  55. package/src/local/deny.ts +2 -1
  56. package/src/models/mlx.ts +11 -8
  57. package/src/models/ollama.ts +2 -2
  58. package/src/models/relay.ts +190 -42
  59. package/src/models/route/relay-selector.ts +43 -31
  60. package/src/models/route/runtime.ts +17 -7
  61. package/src/models/route/signals.ts +12 -1
  62. package/src/models/route/stage.ts +57 -3
  63. package/src/omniroute/client.ts +1 -1
  64. package/src/ui/index.html +1 -0
  65. package/templates/AGENTS.block.md +1 -1
  66. package/templates/routing.toml +8 -0
@@ -4,7 +4,7 @@ import { existsSync, readFileSync } from "node:fs";
4
4
  import { join } from "node:path";
5
5
  import type { Project } from "../hub/registry.ts";
6
6
  import { hubHome } from "../hub/project.ts";
7
- import { acquireRecoveryLock, claimRunner, readOperation, recoveryLock, releaseRecoveryLock, writeOperation } from "../hub/recovery-store.ts";
7
+ import { acquireRecoveryLock, claimRunner, coordinatorCurrent, readOperation, recoveryCommand, recoveryLock, releaseRecoveryLock, writeOperation } from "../hub/recovery-store.ts";
8
8
 
9
9
  export interface RecoveryPeer {
10
10
  id: string;
@@ -22,12 +22,18 @@ export interface Inspection {
22
22
  peers: RecoveryPeer[];
23
23
  recovery?: { operationId?: string; phase?: string; ready?: boolean };
24
24
  blockers: string[];
25
+ /** #215: for a stopped runtime, the operation whose committed restart snapshot its state dir holds (unreleased). */
26
+ snapshot?: string;
25
27
  }
26
28
  export interface PlannedProject {
27
29
  project: Project;
28
30
  source: Inspection;
29
31
  terminals: unknown[];
30
32
  blockers: string[];
33
+ /** Unmanaged sessions (#206): their plugin reattaches to the new daemon; no terminal is closed or relaunched and no session id is compared. */
34
+ reconnectOnly?: string[];
35
+ /** #215: Codex threads with no rollout and no turn the hub recorded; they restart as a new session, nothing to lose. */
36
+ freshStart?: string[];
31
37
  }
32
38
  export interface UpgradePlan {
33
39
  schema: 1;
@@ -46,6 +52,10 @@ export interface ProjectProgress {
46
52
  instanceId?: string;
47
53
  terminals: Record<string, unknown>;
48
54
  releaseRequested?: boolean;
55
+ /** #215: peers the operator moved to a fresh session, with the session or thread id whose continuity is lost. */
56
+ fresh?: Record<string, { lost: string; reason: string; at: number }>;
57
+ /** #215: set before the commit request is sent; from then on the source may have committed (abort is not offered). */
58
+ commitSent?: boolean;
49
59
  }
50
60
  export interface RecoveryOperation {
51
61
  schema: 1;
@@ -62,6 +72,157 @@ export interface RecoveryOperation {
62
72
  pluginInstalled?: boolean;
63
73
  globalInstalled?: boolean;
64
74
  error?: string;
75
+ /** #215: every human disposition, in order. Operator reasons only; never task or message text. */
76
+ audit?: { at: number; action: "fresh-session" | "stop-and-archive"; reason: string; peer?: string; projects: string[] }[];
77
+ disposition?: { choice: "stop-and-archive"; at: number; projects: Record<string, string> };
78
+ /** #215: a refusal no resume can get past was recorded (FinalRefusal); `next` no longer offers resume. */
79
+ final?: boolean;
80
+ }
81
+
82
+ /** #215: a refusal that holds for every resume of the operation (its staged target or preserved source is fixed). */
83
+ export class FinalRefusal extends Error {}
84
+
85
+ export { recoveryCommand };
86
+ const STOP = "--stop-and-archive --reason <text>";
87
+ /**
88
+ * Whether the staged target reads recovery waivers: a fresh session cannot be released without them. The one waiver
89
+ * check (status, dispose, staging and restore all use it).
90
+ * ponytail: a text sniff of the target's restart.ts; a rename or re-export reads as "no waivers" (the safe side). Upgrade
91
+ * path: a capability list in package.json read here and by coordinatorCurrent.
92
+ */
93
+ export function targetReadsWaivers(op: { targetRoot?: string }): boolean {
94
+ try { return !!op.targetRoot && readFileSync(join(op.targetRoot, "src/hub/restart.ts"), "utf8").includes("export function readRecoveryWaivers"); } catch { return false; }
95
+ }
96
+
97
+ /** Effects anywhere in the operation: a project past `prepared` or any terminal receipt. Abort needs none. */
98
+ export const hasEffects = (op: RecoveryOperation) => op.projects.some((p) => !["pending", "prepared"].includes(p.phase) || Object.keys(p.terminals).length > 0);
99
+ /**
100
+ * #215: why abort would refuse, or undefined when it can cancel. Abort and `next` both ask this, so `next` never
101
+ * offers an abort that refuses. `live` holds inspections of the operation's projects. A #215 coordinator writes
102
+ * `commitSent` before every commit request, so its receipt alone rules a commit in or out; an older one does not,
103
+ * and a prepared source of its operation that is not running (or was not inspected) may have committed.
104
+ */
105
+ export function abortRefusal(op: RecoveryOperation, live: Record<string, Inspection | undefined> = {}): string | undefined {
106
+ if (op.disposition) return "a stop-and-archive of this operation is partway";
107
+ if (hasEffects(op)) return "operation has stopped runtimes or uncertain terminal effects";
108
+ const recorded = !op.sourceRoot || coordinatorCurrent(op.sourceRoot);
109
+ for (let i = 0; i < op.projects.length; i++) {
110
+ const progress = op.projects[i]!, planned = op.plan.projects[i]!, state = live[progress.id];
111
+ if (progress.commitSent) return `${progress.id}: its commit request may have been sent`;
112
+ if (state?.recovery?.operationId === op.id && state.recovery.phase !== "released" &&
113
+ (state.instanceId !== planned.source.instanceId || !["preparing", "prepared"].includes(state.recovery.phase ?? ""))) return `${progress.id}: recovery has progressed`;
114
+ // A #215 coordinator's prepared source that stopped was never asked to commit; one that cannot be read (unavailable,
115
+ // stopping, not inspected) may still hold this operation's hold. An older coordinator records no sent commit.
116
+ if (progress.phase === "prepared" && state?.state !== "running" && (!recorded || state?.state !== "stopped")) {
117
+ return recorded ? `${progress.id}: the source reads as ${state?.state ?? "not inspected"}, so whether this operation's hold still stands is uncertain`
118
+ : `${progress.id}: the source is ${state?.state ?? "not inspected"} and may have committed (this operation's coordinator does not record a sent commit)`;
119
+ }
120
+ }
121
+ return undefined;
122
+ }
123
+
124
+ /**
125
+ * #215: why resume can never get past what is live, or undefined. The runner's checks, mirrored (the invariant test in
126
+ * test/upgrade.test.ts holds the two together); `next` offers resume and --fresh-session only when this is undefined,
127
+ * and dispose accepts --fresh-session only then. Unavailable, starting or stopping is waited for.
128
+ */
129
+ export function resumeBlocked(op: RecoveryOperation, live: Record<string, Inspection | undefined> = {}): string | undefined {
130
+ if (op.final) return "staging refused this operation's fixed target or preserved source";
131
+ const old = !!op.sourceRoot && !coordinatorCurrent(op.sourceRoot);
132
+ for (let i = 0; i < op.projects.length; i++) {
133
+ const p = op.projects[i]!, planned = op.plan.projects[i], state = live[p.id];
134
+ if (!state || !planned || p.phase === "verified") continue;
135
+ if (state.state === "missing") return `${p.id}: the project directory is missing`;
136
+ if (state.state === "incompatible") return `${p.id}: its hub speaks another control protocol`;
137
+ const source = p.phase === "pending" || p.phase === "prepared";
138
+ if (state.state === "running") {
139
+ const expected = source ? state.instanceId === planned.source.instanceId
140
+ : state.recovery?.operationId === op.id && (!p.instanceId || state.instanceId === p.instanceId) && state.version === op.plan.version;
141
+ if (!expected) return `${p.id}: its hub is not the one this operation expects`;
142
+ continue;
143
+ }
144
+ if (state.state !== "stopped") continue;
145
+ if (p.phase === "pending") return `${p.id}: the source stopped before it was prepared`;
146
+ if (p.phase === "prepared" && !p.commitSent && !old) return `${p.id}: the source stopped while prepared, with no commit request`;
147
+ // ponytail: a target that dies after it started is not restarted; that needs its peers relaunched against the new
148
+ // instance (CodexPeer is created only by start, launcher records are keyed by instance). Follow-up issue.
149
+ if (p.phase === "started" || p.phase === "peers-restored") return `${p.id}: the target stopped after it started; restarting it is not supported in this release`;
150
+ if (state.snapshot !== op.id) return `${p.id}: its hub stopped without this operation's restart snapshot`;
151
+ }
152
+ return undefined;
153
+ }
154
+
155
+ /**
156
+ * #215: why stop-and-archive would refuse, or undefined when it can act. Dispose and `next` both ask this, so `next`
157
+ * never offers a stop-and-archive that refuses. Every unverified project must read as running, stopped or missing:
158
+ * any other state (unavailable, starting, stopping, incompatible, not inspected) hides whether this operation owns it.
159
+ */
160
+ export function disposeRefusal(op: RecoveryOperation, live: Record<string, Inspection | undefined> = {}): { project: string; reads: string } | undefined {
161
+ const unsettled = op.projects.find((p) => p.phase !== "verified" && !["running", "stopped", "missing"].includes(live[p.id]?.state ?? ""));
162
+ return unsettled ? { project: unsettled.id, reads: live[unsettled.id]?.state ?? "not inspected" } : undefined;
163
+ }
164
+
165
+ /**
166
+ * #215: what the person can do now, in the receipt table's order: resume (it also launches a failed peer again),
167
+ * abort where it can succeed, a fresh session for a failed Codex or Claude restoration, and stop-and-archive last.
168
+ * `status` and every error that names choices use this one list.
169
+ */
170
+ export function nextActions(receipt: RecoveryOperation, runner?: number | "unknown", live: Record<string, Inspection | undefined> = {}): string[] {
171
+ // A receipt read without its project lists (never written so by a coordinator) still gets the general choices.
172
+ const op: RecoveryOperation = receipt.projects ? receipt : { ...receipt, projects: [], plan: { ...receipt.plan, projects: receipt.plan?.projects ?? [] } };
173
+ if (op.phase === "completed" || op.phase === "cancelled") return [];
174
+ // claimRunner refuses an owner it cannot read, so resume, abort and dispose are all refused until the record reads.
175
+ if (runner === "unknown") return [`${recoveryCommand(op, "status")} again: whether a runner holds the operation could not be read (resume, abort and dispose are refused until it can)`];
176
+ if (runner) return [`wait: runner ${runner} is working; ${recoveryCommand(op, "status")}`];
177
+ const unsettled = disposeRefusal(op, live);
178
+ const stop = unsettled ? `wait until ${unsettled.project}'s hub settles, then ${recoveryCommand(op, "status")}` : recoveryCommand(op, "dispose", STOP);
179
+ if (op.disposition) return [unsettled ? stop : `rerun ${stop}`];
180
+ const failed = [...new Set(op.projects.flatMap((p) => failedPeers(op, p, live)))];
181
+ const old = !!op.sourceRoot && !coordinatorCurrent(op.sourceRoot);
182
+ const abortable = !abortRefusal(op, live);
183
+ const stuck = resumeBlocked(op, live);
184
+ return [
185
+ ...(stuck ? [] : [`${recoveryCommand(op, "resume")}${op.error ? " (after the next action in error)" : ""}${old ? ` (runs the coordinator that started this operation, which cannot re-prepare an expired hold: if it reports "source is no longer prepared", use ${abortable ? "abort or " : ""}stop-and-archive)` : ""}`]),
186
+ ...(abortable ? [recoveryCommand(op, "abort")] : []),
187
+ ...(targetReadsWaivers(op) && !stuck ? failed.map((peer) => recoveryCommand(op, "dispose", `--fresh-session ${peer} --reason <text>`)) : []),
188
+ stop,
189
+ ];
190
+ }
191
+
192
+ /**
193
+ * "next actions: ..." from nextActions, with the inspections the caller holds. Every error that lists choices ends with
194
+ * it, after only its own peer-specific step ("end that codex session", "close Orca terminal <h>"), so no error offers
195
+ * an abort that abort refuses or leaves out one that would succeed.
196
+ */
197
+ export const nextActionsText = (op: RecoveryOperation, live: Record<string, Inspection | undefined> = {}): string => `next actions: ${nextActions(op, undefined, live).join(" | ")}`;
198
+
199
+ /**
200
+ * #215: what `next` reads, the same for status, abort and the runner's errors: every project not yet verified, its
201
+ * source or its target. An inspection that throws reads as not inspected, never as stopped.
202
+ */
203
+ export async function liveProjects(op: RecoveryOperation, inspect: (project: Project) => Promise<Inspection>): Promise<Record<string, Inspection | undefined>> {
204
+ if (op.phase === "completed" || op.phase === "cancelled") return {};
205
+ const open = op.plan.projects.filter((_, i) => op.projects[i] && op.projects[i].phase !== "verified");
206
+ return Object.fromEntries(await Promise.all(open.map(async (p) => [p.project.id, await inspect(p.project).catch(() => undefined)] as const)));
207
+ }
208
+
209
+ /**
210
+ * Peers of a project whose restoration failed and for which a fresh session is a real choice: not Pi (a restored hub
211
+ * resumes its recorded session), not one already chosen, and not a planned fresh start (nothing to lose; resume
212
+ * launches it new again).
213
+ */
214
+ function failedPeers(op: RecoveryOperation, progress: ProjectProgress, live: Record<string, Inspection | undefined> = {}): string[] {
215
+ const planned = op.plan.projects.find((p) => p.project.id === progress.id);
216
+ return Object.entries(progress.terminals).filter(([key, value]) => key.startsWith("restored:") && value === "failed").map(([key]) => key.slice("restored:".length))
217
+ .filter((peer) => peer !== "pi" && !progress.fresh?.[peer] && !planned?.freshStart?.includes(peer) && !plannedAttached(op, progress, peer, live));
218
+ }
219
+
220
+ /** #215: the inspection shows the planned session attached for `peer`, so resume records it as restored: nothing is lost. */
221
+ function plannedAttached(op: RecoveryOperation, progress: ProjectProgress, peer: string, live: Record<string, Inspection | undefined>): boolean {
222
+ const state = live[progress.id];
223
+ const binding = (op.plan.projects.find((p) => p.project.id === progress.id)?.terminals as { peer: string; sessionId: string }[] | undefined)?.find((t) => t.peer === peer);
224
+ const current = state?.state === "running" ? state.peers.find((p) => p.id === peer && p.state !== "offline") : undefined;
225
+ return !!binding && (peer === "codex" ? current?.threadId : current?.sessionId) === binding.sessionId;
65
226
  }
66
227
 
67
228
  /** Registry reads for planning must not create a registry or run migrations. */
@@ -116,6 +277,8 @@ export interface RecoveryDriver {
116
277
  refreshManager?(op: RecoveryOperation): Promise<void>;
117
278
  release(project: Project, operation: string, instance: string): Promise<void>;
118
279
  verify(planned: PlannedProject, progress: ProjectProgress, op: RecoveryOperation): Promise<void>;
280
+ /** #215 stop-and-archive: stop this operation's unreleased target (when given) and archive its committed snapshot. */
281
+ stopAndArchive(project: Project, op: RecoveryOperation, targetInstance?: string): Promise<void>;
119
282
  sleep(ms: number): Promise<void>;
120
283
  now(): number;
121
284
  }
@@ -140,24 +303,67 @@ export async function runRecovery(id: string, driver: RecoveryDriver, home = hub
140
303
  const save = () => { op.updatedAt = driver.now(); writeOperation(id, op, home); };
141
304
  const step = (value: string) => { op.step = value; save(); };
142
305
  const identity = (observed: Inspection, planned: PlannedProject, progress: ProjectProgress) => {
143
- if (observed.state !== "running") throw new Error(`${planned.project.id}: runtime is ${observed.state}`);
144
- if (progress.instanceId && observed.instanceId !== progress.instanceId) throw new Error("daemon instance changed; refusing to act on its replacement");
145
- if (observed.recovery?.operationId !== id) throw new Error("daemon is not owned by this recovery operation");
146
- if (observed.version !== op.plan.version) throw new Error("target daemon version mismatch");
306
+ if (observed.state === "stopped") throw new Error(progress.phase !== "stopped" ? `${planned.project.id}: the target stopped after it started (a crash or a reboot); restarting it is not supported in this release`
307
+ : `${planned.project.id}: the target is stopped${observed.snapshot === id ? "" : " and this operation's restart snapshot is gone, so nothing can start it"}`);
308
+ if (observed.state === "missing") throw new Error(`${planned.project.id}: the project directory is missing`);
309
+ if (observed.state !== "running") throw new Error(`${planned.project.id}: the target reads as ${observed.state}; wait until it answers`);
310
+ if (progress.instanceId && observed.instanceId !== progress.instanceId) throw new Error(`${planned.project.id}: daemon instance changed; refusing to act on its replacement`);
311
+ if (observed.recovery?.operationId !== id) throw new Error(`${planned.project.id}: daemon is not owned by this recovery operation`);
312
+ if (observed.version !== op.plan.version) throw new Error(`${planned.project.id}: target daemon version mismatch`);
147
313
  };
148
- const sourceRoster = (live: Inspection, planned: PlannedProject) => {
314
+ const sourceRoster = (live: Inspection, planned: PlannedProject, progress: ProjectProgress, again = false) => {
315
+ // #215: a peer whose terminal this operation already closed must stay detached after a re-preparation, and a
316
+ // planned peer that detached since may pass it, as the daemon's readiness lets it (#21): closeTerminals then
317
+ // records its close only once Orca no longer lists the terminal.
318
+ const closed = (peer: string) => progress.terminals[`closed:${peer}`] === true;
149
319
  const expected = planned.source.peers.filter((p) => p.state !== "offline");
150
320
  const active = live.peers.filter((p) => p.state !== "offline");
151
- if (active.length !== expected.length || expected.some((peer) => {
321
+ const extra = active.find((p) => !expected.some((peer) => peer.id === p.id));
322
+ const changed = extra ?? expected.find((peer) => {
152
323
  const current = active.find((p) => p.id === peer.id);
153
- return !current || current.threadId !== peer.threadId || current.sessionId !== peer.sessionId;
154
- })) throw new Error("source conversation or active peer membership changed; make a new plan");
324
+ if (closed(peer.id)) return !!current;
325
+ if (!current) return !again;
326
+ return !planned.reconnectOnly?.includes(peer.id) && (current.threadId !== peer.threadId || current.sessionId !== peer.sessionId);
327
+ });
328
+ if (!changed) return;
329
+ // A session that is not in the plan, or whose terminal this operation closed, has no original to restore.
330
+ const fix = extra || closed(changed.id) ? `end that ${changed.id} session` : `restore ${changed.id}'s original session`;
331
+ if (hasEffects(op)) throw new Error(`${planned.project.id}: ${changed.id} changed while this operation has recorded effects, so a new plan cannot replace it; ${fix} before resuming`);
332
+ // The lock this operation holds refuses a new upgrade until the operation is cancelled or ended.
333
+ throw new Error(`${planned.project.id}: source conversation or active peer membership changed (${changed.id}); ${fix} before resuming, or end this operation: a new plan can be made once it is cancelled or ended`);
334
+ };
335
+ // Prepare, or after an expired lease re-prepare, the planned source and wait until it is quiet.
336
+ const prepareSource = async (planned: PlannedProject, progress: ProjectProgress, again = false) => {
337
+ const project = planned.project, instance = planned.source.instanceId!;
338
+ await driver.prepare(project, id, instance);
339
+ const deadline = driver.now() + idleTimeoutMs;
340
+ for (;;) {
341
+ const live = await driver.inspect(project);
342
+ if (live.instanceId !== instance) throw new Error(`${project.id}: source daemon changed during preparation`);
343
+ if (live.recovery?.operationId !== id) {
344
+ const other = live.recovery?.phase !== "released" ? live.recovery?.operationId : undefined;
345
+ throw new Error(other ? `${project.id}: the source is held by another recovery operation ${other}; wait until that operation ends or its hold lapses`
346
+ : `${project.id}: the preparation expired before the source was quiet (resume prepares it again)`);
347
+ }
348
+ if (live.recovery.ready) return sourceRoster(live, planned, progress, again);
349
+ if (driver.now() >= deadline) {
350
+ await driver.abort(project, id, instance);
351
+ throw new Error(`${project.id}: active turns, approvals or completion checks did not finish; source runtime left running`);
352
+ }
353
+ await driver.sleep(250);
354
+ }
155
355
  };
156
356
  try {
357
+ if (op.disposition) {
358
+ // The stop-and-archive in progress keeps its own cause; resume never runs an operation being abandoned.
359
+ op.error ??= `a stop-and-archive of this operation is partway; ${nextActionsText(op, await liveProjects(op, driver.inspect))}`;
360
+ op.phase = "blocked"; save();
361
+ return op;
362
+ }
157
363
  op.phase = "running"; delete op.error; save();
158
364
  step("stage");
159
365
  const target = await driver.stage(op);
160
- if (op.targetDigest && (target.root !== op.targetRoot || target.digest !== op.targetDigest)) throw new Error("staged target changed since operation started");
366
+ if (op.targetDigest && (target.root !== op.targetRoot || target.digest !== op.targetDigest)) throw new FinalRefusal("staged target changed since operation started");
161
367
  op.targetRoot = target.root; op.targetDigest = target.digest; save();
162
368
 
163
369
  // Check every untouched source before stopping even the first project.
@@ -165,47 +371,58 @@ export async function runRecovery(id: string, driver: RecoveryDriver, home = hub
165
371
  const progress = op.projects[i]!, planned = op.plan.projects[i]!;
166
372
  if (progress.phase !== "pending") continue;
167
373
  const live = await driver.inspect(planned.project);
374
+ if (!["running", "stopped", "missing"].includes(live.state)) throw new Error(`${planned.project.id}: the source reads as ${live.state}; wait until it answers`);
168
375
  if (live.state !== "running" || live.instanceId !== planned.source.instanceId || live.version !== planned.source.version) {
169
- throw new Error(`${planned.project.id}: source runtime changed; make a new plan`);
376
+ throw new Error(`${planned.project.id}: source runtime changed`);
170
377
  }
171
- sourceRoster(live, planned);
378
+ const other = live.recovery?.phase !== "released" ? live.recovery?.operationId : undefined;
379
+ if (other && other !== id) throw new Error(`${planned.project.id}: the source is held by another recovery operation ${other}; wait until that operation ends or its hold lapses`);
380
+ sourceRoster(live, planned, progress);
172
381
  }
173
382
  for (let i = 0; i < op.projects.length; i++) {
174
383
  const progress = op.projects[i]!, planned = op.plan.projects[i]!, project = planned.project;
175
384
  if (progress.phase === "verified" || progress.phase === "peers-restored") continue;
176
385
  if (progress.phase === "pending") {
177
386
  step(`prepare:${project.id}`);
178
- await driver.prepare(project, id, planned.source.instanceId!);
179
- const deadline = driver.now() + idleTimeoutMs;
180
- for (;;) {
181
- const live = await driver.inspect(project);
182
- if (live.instanceId !== planned.source.instanceId) throw new Error("source daemon changed during preparation");
183
- if (live.recovery?.operationId !== id) throw new Error("preparation expired or belongs to another operation");
184
- if (live.recovery.ready) { sourceRoster(live, planned); break; }
185
- if (driver.now() >= deadline) {
186
- await driver.abort(project, id, planned.source.instanceId!);
187
- throw new Error(`${project.id}: active turns, approvals or completion checks did not finish; source runtime left running`);
188
- }
189
- await driver.sleep(250);
190
- }
387
+ await prepareSource(planned, progress);
191
388
  progress.phase = "prepared"; save();
192
389
  }
193
390
  if (progress.phase === "prepared") {
194
391
  step(`commit:${project.id}`);
195
392
  let live = await driver.inspect(project);
196
393
  if (live.state === "running" && live.instanceId === planned.source.instanceId) {
197
- if (live.recovery?.operationId !== id || !live.recovery.ready) throw new Error("source is no longer prepared");
394
+ if (live.recovery?.operationId !== id || !live.recovery.ready) {
395
+ const other = live.recovery?.operationId;
396
+ if (other && other !== id && live.recovery?.phase !== "released") throw new Error(`${project.id}: the source is held by another recovery operation ${other}; nothing was prepared, closed or stopped, and ending this one leaves that hold alone; wait until that operation ends or its hold lapses`);
397
+ // #215: the hold lapsed (an expired lease) after this operation may have recorded terminal effects.
398
+ // Re-prepare the same verified source; the receipts stay, so no terminal is closed twice.
399
+ step(`reprepare:${project.id}`);
400
+ await prepareSource(planned, progress, true);
401
+ step(`commit:${project.id}`);
402
+ } else {
403
+ // #215: a hold of ours can predate a roster change, as after a resume whose roster check failed: check again.
404
+ sourceRoster(live, planned, progress, true);
405
+ }
198
406
  await driver.closeTerminals(planned, progress, op, save);
407
+ // Durable, unlike `step`: from here the source may have committed, which status and abort must not forget.
408
+ progress.commitSent = true; save();
199
409
  await driver.commit(project, id, planned.source.instanceId!);
200
410
  const deadline = driver.now() + 30_000;
201
411
  do {
202
412
  live = await driver.inspect(project);
203
413
  if (live.state === "stopped") break;
204
- if (live.instanceId && live.instanceId !== planned.source.instanceId) throw new Error("another daemon started during shutdown");
414
+ if (live.instanceId && live.instanceId !== planned.source.instanceId) throw new Error(`${project.id}: another daemon started during shutdown`);
205
415
  await driver.sleep(100);
206
416
  } while (driver.now() < deadline);
417
+ } else if (live.state === "running") {
418
+ throw new Error(`${project.id}: the source daemon was replaced by instance ${live.instanceId ?? "unknown"}; refusing to prepare, close or stop it (ending this operation leaves that daemon running)`);
419
+ } else if (live.state === "stopped" && !progress.commitSent && (!op.sourceRoot || coordinatorCurrent(op.sourceRoot))) {
420
+ // #215: this coordinator records a commit request before sending it, so a stopped source with none crashed while
421
+ // prepared: no snapshot was committed and there is nothing to start from. The phase stays `prepared`.
422
+ throw new Error(`${project.id}: the source stopped while prepared and no commit was requested, so there is nothing to restore`);
207
423
  }
208
- if (live.state !== "stopped") throw new Error("old shutdown is not verified; not starting a second daemon");
424
+ if (live.state === "missing") throw new Error(`${project.id}: the project directory is missing`);
425
+ if (live.state !== "stopped") throw new Error(`${project.id}: old shutdown is not verified (the source reads as ${live.state}); not starting a second daemon; check ${recoveryCommand(op, "status")} once it answers`);
209
426
  progress.phase = "stopped"; save();
210
427
  }
211
428
  if (progress.phase === "stopped") {
@@ -253,14 +470,26 @@ export async function runRecovery(id: string, driver: RecoveryDriver, home = hub
253
470
  }
254
471
  releaseRecoveryLock(id, home); op.phase = "completed"; step("completed");
255
472
  } catch (error) {
256
- op.phase = "blocked"; op.error = error instanceof Error ? error.message : "recovery failed"; save();
473
+ // #215: every runner error ends with the choices status shows, read from every open source, never only this one.
474
+ if (error instanceof FinalRefusal) op.final = true;
475
+ const next = nextActionsText(op, await liveProjects(op, driver.inspect));
476
+ op.phase = "blocked"; op.error = `${error instanceof Error ? error.message : "recovery failed"}; ${next}`; save();
257
477
  } finally { releaseRunner(); }
258
478
  return op;
259
479
  }
260
480
 
261
- export function publicOperation(op: RecoveryOperation) {
481
+ /** Receipts and runner state only (#215): ids, phases and effects, never task or message text. */
482
+ export function publicOperation(op: RecoveryOperation, runnerPid?: number | "unknown", live: Record<string, Inspection | undefined> = {}) {
483
+ const effect = (value: unknown) => value === "pending" || value === "failed" ? value : "done";
484
+ const next = nextActions(op, runnerPid, live);
262
485
  return { id: op.id, phase: op.phase, step: op.step, version: op.plan.version, updatedAt: op.updatedAt,
263
- projects: op.projects.map((p) => ({ id: p.id, phase: p.phase })), ...(op.error ? { error: op.error } : {}) };
486
+ runner: runnerPid === "unknown" ? { state: "unknown" } : runnerPid ? { state: "running", pid: runnerPid } : { state: "none" },
487
+ ...(op.phase === "running" && !runnerPid ? { stale: "the receipt says running but no runner holds the operation: its last runner stopped mid-step" } : {}),
488
+ projects: op.projects.map((p) => ({ id: p.id, phase: p.phase, ...(Object.keys(p.terminals).length ? { effects: Object.fromEntries(Object.entries(p.terminals).map(([key, value]) => [key, effect(value)])) } : {}),
489
+ ...(p.fresh ? { lostContinuity: Object.fromEntries(Object.entries(p.fresh).map(([peer, f]) => [peer, f.lost])) } : {}) })),
490
+ pluginInstalled: !!op.pluginInstalled, globalInstalled: !!op.globalInstalled,
491
+ ...(!targetReadsWaivers(op) && op.projects.some((p) => failedPeers(op, p).length) ? { freshSession: `not offered: target ${op.plan.version} cannot read recovery waivers, so it could not release a new session` } : {}),
492
+ ...(op.error ? { error: op.error } : {}), ...(op.disposition ? { disposition: op.disposition } : {}), ...(op.audit ? { audit: op.audit } : {}), next };
264
493
  }
265
494
 
266
495
  /** Escape a blocked preflight without abandoning a stopped runtime or an uncertain terminal mutation. */
@@ -278,21 +507,117 @@ export async function abortRecovery(id: string, driver: RecoveryDriver, home = h
278
507
  if (recoveryLock(home) === id) releaseRecoveryLock(id, home);
279
508
  return;
280
509
  }
281
- if (op.projects.some((p) => !["pending", "prepared"].includes(p.phase) || Object.keys(p.terminals).length)) {
282
- throw new Error("operation has stopped runtimes or uncertain terminal effects; resume it instead");
283
- }
284
510
  const { fingerprint, ...body } = op.plan;
285
511
  if (fingerprint !== planFingerprint(body)) throw new Error("operation plan changed");
512
+ const live = await liveProjects(op, driver.inspect);
513
+ const refusal = abortRefusal(op, live);
514
+ if (refusal) throw new Error(`abort refused: ${refusal}; ${nextActionsText(op, live)}`);
515
+ // Only this operation's own uncommitted holds are aborted; a lapsed hold, a replacement daemon or another
516
+ // operation's hold is left alone, and a source that is not running had no commit sent (abortRefusal).
286
517
  for (const planned of op.plan.projects) {
287
- const live = await driver.inspect(planned.project);
288
- if (live.recovery?.operationId === id) {
289
- if (live.instanceId !== planned.source.instanceId || !["preparing", "prepared"].includes(live.recovery.phase ?? "")) throw new Error("recovery has progressed; resume it instead");
290
- await driver.abort(planned.project, id, planned.source.instanceId!);
291
- } else if (op.projects.find((p) => p.id === planned.project.id)?.phase === "prepared") {
292
- throw new Error("prepared source outcome is uncertain; resume it instead");
293
- }
518
+ const state = live[planned.project.id];
519
+ if (state?.recovery?.operationId === id && state.recovery.phase !== "released") await driver.abort(planned.project, id, planned.source.instanceId!);
294
520
  }
295
521
  op.phase = "cancelled"; op.step = "cancelled"; op.updatedAt = driver.now();
296
522
  writeOperation(id, op, home); releaseRecoveryLock(id, home);
297
523
  } finally { releaseRunner(); }
298
524
  }
525
+
526
+ /**
527
+ * #215: the human-only ways out of an operation that cannot restore a native session. `fresh` records the lost
528
+ * conversation and leaves the operation to resume; `stop-and-archive` abandons it, and releases the lock only after
529
+ * every runtime this operation held or started is verified released or stopped.
530
+ */
531
+ export async function disposeRecovery(id: string, choice: { fresh: string } | { stop: true }, reason: string, driver: RecoveryDriver, home = hubHome()): Promise<RecoveryOperation> {
532
+ let op = readOperation<RecoveryOperation>(id, home);
533
+ validateReceipt(id, op);
534
+ // A finished operation owns no lock: never take one only to refuse.
535
+ if (op.phase === "completed" || op.phase === "cancelled") throw new Error(`operation is already ${op.phase}`);
536
+ acquireRecoveryLock(id, home);
537
+ const releaseRunner = claimRunner(id, home);
538
+ try {
539
+ op = readOperation<RecoveryOperation>(id, home);
540
+ validateReceipt(id, op);
541
+ if (op.phase === "completed" || op.phase === "cancelled") {
542
+ // Another runner finished it while this one waited: leave no lock behind, as resume and abort do.
543
+ if (recoveryLock(home) === id) releaseRecoveryLock(id, home);
544
+ throw new Error(`operation is already ${op.phase}`);
545
+ }
546
+ const at = driver.now();
547
+ // Read once, as status and the runner do: every choice and refusal below is decided on it.
548
+ const live = await liveProjects(op, driver.inspect);
549
+ const next = nextActionsText(op, live);
550
+ if ("fresh" in choice) {
551
+ // `ahub pi` sends no fresh flag, and a restored hub refills a Pi start from its recorded resume (daemon startPeer).
552
+ if (choice.fresh === "pi") throw new Error(`pi: --fresh-session is not supported: a restored hub resumes Pi's recorded session, so a fresh one cannot be guaranteed; ${next}`);
553
+ if (op.disposition) throw new Error(`a stop-and-archive of this operation is partway; ${next}`);
554
+ if (!targetReadsWaivers(op)) throw new Error(`--fresh-session is not available: target ${op.plan.version} cannot read recovery waivers, so it could not release a new session; ${next}`);
555
+ // The new session is launched by resume, so it helps only where resume can get past what is live.
556
+ const stuck = resumeBlocked(op, live);
557
+ if (stuck) throw new Error(`--fresh-session cannot help: ${stuck}, so resume could never launch the new session; ${next}`);
558
+ const peer = choice.fresh;
559
+ // Per project: a planned fresh start has nothing to lose, so only the other failed projects take the choice.
560
+ const failed = op.projects.filter((p) => failedPeers(op, p, live).includes(peer));
561
+ if (!failed.length && op.projects.some((p) => p.terminals[`restored:${peer}`] === "failed" && op.plan.projects.find((planned) => planned.project.id === p.id)?.freshStart?.includes(peer))) {
562
+ throw new Error(`${peer}: its plan already restarts it as a new session (no rollout and no turn, nothing to lose), so there is no conversation to record as lost; ${next}`);
563
+ }
564
+ if (!failed.length && op.projects.some((p) => p.terminals[`restored:${peer}`] === "failed" && plannedAttached(op, p, peer, live))) {
565
+ throw new Error(`${peer}: its planned session is attached again, so nothing was lost; resume records it as restored; ${next}`);
566
+ }
567
+ if (!failed.length) throw new Error(`${peer}: no failed restoration of it is open to a fresh session (none failed, or one is already chosen); --fresh-session applies only then (${recoveryCommand(op, "status")})`);
568
+ for (const progress of failed) {
569
+ const binding = (op.plan.projects.find((p) => p.project.id === progress.id)!.terminals as { peer: string; sessionId: string }[]).find((t) => t.peer === peer)!;
570
+ (progress.fresh ??= {})[peer] = { lost: binding.sessionId, reason, at };
571
+ }
572
+ (op.audit ??= []).push({ at, action: "fresh-session", reason, peer, projects: failed.map((p) => p.id) });
573
+ op.updatedAt = at; writeOperation(id, op, home);
574
+ return op;
575
+ }
576
+ // Every project is inspected before acting on any, as the runner does before its first stop.
577
+ const unsettled = disposeRefusal(op, live);
578
+ if (unsettled) throw new Error(`${unsettled.project}: its hub reads as ${unsettled.reads}, so whether this operation owns it cannot be verified; nothing was stopped or released; ${next}`);
579
+ const acts: { planned: PlannedProject; live?: Inspection; act: string }[] = [];
580
+ for (let i = 0; i < op.projects.length; i++) {
581
+ const progress = op.projects[i]!, planned = op.plan.projects[i]!;
582
+ const state = progress.phase === "verified" ? undefined : live[planned.project.id]!;
583
+ const ours = state?.state === "running" && state.recovery?.operationId === id && state.recovery.phase !== "released";
584
+ // A target is known by its operation fence, not only by the receipt: `up` may have failed, or the first
585
+ // identity read thrown, after the target started and before its instance was recorded.
586
+ const target = ours && state.instanceId !== planned.source.instanceId && state.recovery?.phase === "restored";
587
+ const act = !state ? "released earlier; left running"
588
+ : state.state === "stopped" ? "stopped"
589
+ : state.state === "missing" ? "project directory is missing; nothing was stopped or archived (ahub doctor --orphans lists a hub left running there)"
590
+ : ours && state.instanceId === planned.source.instanceId && ["pending", "prepared"].includes(progress.phase) ? "source hold released; source left running"
591
+ : target ? "target stopped"
592
+ : state.instanceId === planned.source.instanceId && ["pending", "prepared"].includes(progress.phase)
593
+ ? `source left running (${state.recovery?.operationId && state.recovery.phase !== "released" ? `held by another operation, ${state.recovery.operationId}` : progress.phase === "prepared" ? "its hold had lapsed" : "never prepared"})`
594
+ : `left running: instance ${state.instanceId ?? "unknown"} is not held by this operation`;
595
+ acts.push({ planned, ...(state ? { live: state } : {}), act });
596
+ }
597
+ // Each outcome is recorded as it happens, so a disposition that stops partway stays true and resume refuses it.
598
+ const disposition = (op.disposition ??= { choice: "stop-and-archive", at, projects: {} });
599
+ (op.audit ??= []).push({ at, action: "stop-and-archive", reason, projects: acts.map((a) => a.planned.project.id) });
600
+ // Recorded before the first act: a crash inside a stop leaves a disposition that resume refuses to override.
601
+ op.updatedAt = driver.now(); writeOperation(id, op, home);
602
+ try {
603
+ for (const { planned, live, act } of acts) {
604
+ if (act.startsWith("source hold")) await driver.abort(planned.project, id, planned.source.instanceId!);
605
+ else if (act === "stopped" || act === "target stopped") {
606
+ await driver.stopAndArchive(planned.project, op, act === "target stopped" ? live!.instanceId : undefined);
607
+ if ((await driver.inspect(planned.project)).state !== "stopped") throw new Error(`${planned.project.id}: shutdown of instance ${live!.instanceId ?? "unknown"} is not verified`);
608
+ }
609
+ disposition.projects[planned.project.id] ??= act;
610
+ op.updatedAt = driver.now(); writeOperation(id, op, home);
611
+ }
612
+ } catch (error) {
613
+ op.phase = "blocked"; op.updatedAt = driver.now();
614
+ op.error = `stop-and-archive stopped partway and keeps the lock: ${error instanceof Error ? error.message : "disposition failed"} (a committed source stops by itself); ${nextActionsText(op, await liveProjects(op, driver.inspect))}`;
615
+ writeOperation(id, op, home);
616
+ throw error;
617
+ }
618
+ delete op.error;
619
+ op.phase = "cancelled"; op.step = "disposed: stop-and-archive (abandoned, not completed)"; op.updatedAt = driver.now();
620
+ writeOperation(id, op, home); releaseRecoveryLock(id, home);
621
+ return op;
622
+ } finally { releaseRunner(); }
623
+ }
package/src/hub/ask.ts CHANGED
@@ -87,7 +87,7 @@ export async function gather(question: string, d: AskDeps): Promise<{ evidence:
87
87
  const tasks = d.board.list().sort((a, b) => hit(b.title) - hit(a.title) || b.updated - a.updated).slice(0, MAX_TASKS);
88
88
  // An ordinary task's last note is model-written (a summary, a review note): one that matches a PII pattern is shown
89
89
  // only on campus, like a PII task (#69).
90
- const notePii = (t: (typeof tasks)[number]) => !d.isPii(t) && !!t.history.at(-1)?.note && (d.isPiiText?.(t.history.at(-1)!.note!) ?? false);
90
+ const notePii = (t: (typeof tasks)[number]) => !d.isPii(t) && !!t.history.at(-1)?.note && (!!t.history.at(-1)!.withheld || (d.isPiiText?.(t.history.at(-1)!.note!) ?? false));
91
91
  const anyPii = tasks.some((t) => d.isPii(t) || notePii(t));
92
92
  const showPii = anyPii ? await onCampus() : false;
93
93
  let piiShown = false;
package/src/hub/board.ts CHANGED
@@ -27,12 +27,16 @@ export interface HistoryEntry {
27
27
  note?: string;
28
28
  /** The owner an event that set it left the task with (#67); absent in rows written before 0.11. */
29
29
  owner?: PeerId | null;
30
+ /** On a decline or an escalation: the owner it was declined for or taken from (#207); later reroutes leave it out. */
31
+ from?: PeerId;
30
32
  /** On a hand-over: the new owner's split profile then (#109); absent when it was unknown. */
31
33
  profile?: string;
32
34
  /** Structured cause recorded at the operation source, never inferred from note text. */
33
35
  reason?: TaskMoveReason;
34
36
  /** Persisted task-idle ladder; never counted as fresh task activity (#186). */
35
37
  sweep?: SweepRecord;
38
+ /** The PII screen did not clear this entry's note (#198): only the console reads it. */
39
+ withheld?: true;
36
40
  }
37
41
  export interface Task {
38
42
  id: number;
@@ -47,6 +51,8 @@ export interface Task {
47
51
  plan?: TaskPlan;
48
52
  /** Tasks that must be approved before this one is offered (issue #34); fixed when it is proposed. */
49
53
  deps?: number[];
54
+ /** Who routing offers the task first once nothing is left to wait for (issue #207); null when nobody was named. */
55
+ reserved?: PeerId | null;
50
56
  signals: string[];
51
57
  /** consecutive changes_requested verdicts */
52
58
  rejections: number;
@@ -95,14 +101,16 @@ export class Board {
95
101
  for (const [col, empty] of [["plan", "{}"], ["deps", "[]"]] as const) {
96
102
  if (!have.has(col)) this.db.run(`ALTER TABLE tasks ADD COLUMN ${col} TEXT NOT NULL DEFAULT '${empty}'`);
97
103
  }
104
+ // And from before issue #207: existing rows reserve nobody.
105
+ if (!have.has("reserved")) this.db.run("ALTER TABLE tasks ADD COLUMN reserved TEXT");
98
106
  }
99
107
 
100
- propose(by: PeerId, t: { title: string; detail?: string; class: TaskClass; refs?: TaskRefs; plan?: TaskPlan; deps?: number[]; signals?: string[] }): Task {
108
+ propose(by: PeerId, t: { title: string; detail?: string; class: TaskClass; refs?: TaskRefs; plan?: TaskPlan; deps?: number[]; reserved?: PeerId; signals?: string[] }): Task {
101
109
  const now = Date.now();
102
110
  const history: HistoryEntry[] = [{ at: now, by, event: "proposed" }];
103
111
  const { lastInsertRowid } = this.db
104
- .query("INSERT INTO tasks (title, detail, class, state, refs, plan, deps, signals, history, created, updated) VALUES (?, ?, ?, 'proposed', ?, ?, ?, ?, ?, ?, ?)")
105
- .run(t.title, t.detail ?? "", t.class, JSON.stringify(t.refs ?? {}), JSON.stringify(t.plan ?? {}), JSON.stringify(t.deps ?? []), JSON.stringify(t.signals ?? []), JSON.stringify(history), now, now);
112
+ .query("INSERT INTO tasks (title, detail, class, state, refs, plan, deps, reserved, signals, history, created, updated) VALUES (?, ?, ?, 'proposed', ?, ?, ?, ?, ?, ?, ?, ?)")
113
+ .run(t.title, t.detail ?? "", t.class, JSON.stringify(t.refs ?? {}), JSON.stringify(t.plan ?? {}), JSON.stringify(t.deps ?? []), t.reserved ?? null, JSON.stringify(t.signals ?? []), JSON.stringify(history), now, now);
106
114
  const task = this.get(Number(lastInsertRowid))!;
107
115
  this.changed(task, history[0]!);
108
116
  return task;
@@ -126,17 +134,17 @@ export class Board {
126
134
 
127
135
  /** The only way a task changes. Validates the move, records who did what, returns the new row. */
128
136
  /** A `plan` in the patch replaces the old one whole: a new plan is the owner's current intent, not an addition. */
129
- update(id: number, by: PeerId, event: string, patch: Partial<Pick<Task, "state" | "owner" | "reviewer" | "refs" | "plan" | "rejections">>, note?: string, extra: Pick<HistoryEntry, "profile" | "sweep" | "reason"> = {}): Task {
137
+ update(id: number, by: PeerId, event: string, patch: Partial<Pick<Task, "state" | "owner" | "reviewer" | "reserved" | "refs" | "plan" | "rejections" | "signals">>, note?: string, extra: Pick<HistoryEntry, "profile" | "sweep" | "reason" | "from" | "withheld"> = {}): Task {
130
138
  const task = this.get(id);
131
139
  if (!task) throw new Error(`no task #${id}`);
132
140
  if (patch.state && patch.state !== task.state && !MOVES[task.state].includes(patch.state)) {
133
141
  throw new Error(`task #${id} is ${task.state}: cannot move to ${patch.state}`);
134
142
  }
135
143
  const next = { ...task, ...patch, refs: { ...task.refs, ...patch.refs } };
136
- const history = [...task.history, { at: Date.now(), by, event, ...(note ? { note } : {}), ...("owner" in patch ? { owner: next.owner } : {}), ...(extra.profile ? { profile: extra.profile } : {}), ...(extra.sweep ? { sweep: extra.sweep } : {}), ...(extra.reason && TASK_MOVE_REASONS.includes(extra.reason) ? { reason: extra.reason } : {}) }];
144
+ const history = [...task.history, { at: Date.now(), by, event, ...(note ? { note } : {}), ...("owner" in patch ? { owner: next.owner } : {}), ...(extra.profile ? { profile: extra.profile } : {}), ...(extra.sweep ? { sweep: extra.sweep } : {}), ...(extra.reason && TASK_MOVE_REASONS.includes(extra.reason) ? { reason: extra.reason } : {}), ...(extra.from ? { from: extra.from } : {}), ...(extra.withheld && note ? { withheld: true as const } : {}) }];
137
145
  this.db
138
- .query("UPDATE tasks SET state = ?, owner = ?, reviewer = ?, refs = ?, plan = ?, rejections = ?, history = ?, updated = ? WHERE id = ?")
139
- .run(next.state, next.owner, next.reviewer, JSON.stringify(next.refs), JSON.stringify(next.plan ?? {}), next.rejections, JSON.stringify(history), Date.now(), id);
146
+ .query("UPDATE tasks SET state = ?, owner = ?, reviewer = ?, reserved = ?, refs = ?, plan = ?, rejections = ?, signals = ?, history = ?, updated = ? WHERE id = ?")
147
+ .run(next.state, next.owner, next.reviewer, next.reserved ?? null, JSON.stringify(next.refs), JSON.stringify(next.plan ?? {}), next.rejections, JSON.stringify(next.signals), JSON.stringify(history), Date.now(), id);
140
148
  const updated = this.get(id)!;
141
149
  this.changed(updated, history.at(-1)!);
142
150
  return updated;