@staix/agent-hub 0.41.0 → 0.43.0

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 (52) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +2 -1
  3. package/docs/adding-an-ai-tool.md +2 -0
  4. package/docs/addons/claude-mem.md +1 -1
  5. package/docs/agent-notes/tasks.md +1 -1
  6. package/docs/agent-notes/tests.md +1 -1
  7. package/docs/design/adapters.md +3 -0
  8. package/docs/design/bus.md +2 -0
  9. package/docs/design/task-board.md +6 -0
  10. package/docs/dogfood.md +6 -2
  11. package/docs/memory.md +8 -6
  12. package/docs/operations.md +65 -5
  13. package/docs/quickstart.md +18 -2
  14. package/docs/sdlc.md +1 -1
  15. package/docs/security.md +3 -3
  16. package/docs/verification/2026-11-16-0.42.0.md +48 -0
  17. package/docs/verification/2026-11-18-0.43.0.md +56 -0
  18. package/docs/verified.json +23 -23
  19. package/package.json +2 -2
  20. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  21. package/plugins/agent-hub/kimi-hook.js +316 -107
  22. package/plugins/agent-hub/server.js +316 -107
  23. package/src/adapters/claude-implementer.ts +11 -1
  24. package/src/adapters/claude-print-child.ts +4 -1
  25. package/src/adapters/conformance/fakes/acp-server.ts +2 -1
  26. package/src/adapters/conformance/fakes/app-server.ts +1 -1
  27. package/src/adapters/local-worker.ts +7 -3
  28. package/src/adapters/reviewer-print.ts +3 -1
  29. package/src/cli/agent-attribution.ts +6 -0
  30. package/src/cli/help.ts +8 -8
  31. package/src/cli/identity.ts +10 -2
  32. package/src/cli/main.ts +58 -5
  33. package/src/cli/memory.ts +21 -6
  34. package/src/cli/upgrade-output.ts +43 -2
  35. package/src/cli/upgrade-stopped.ts +162 -0
  36. package/src/cli/upgrade-wait.ts +37 -0
  37. package/src/hub/board.ts +4 -2
  38. package/src/hub/config-apply.ts +1 -0
  39. package/src/hub/daemon.ts +75 -13
  40. package/src/hub/envelope.ts +1 -0
  41. package/src/hub/handoff.ts +14 -0
  42. package/src/hub/questions.ts +7 -0
  43. package/src/hub/recovery-store.ts +39 -0
  44. package/src/hub/research-record.ts +2 -1
  45. package/src/hub/runtime-capture-prune.ts +114 -3
  46. package/src/hub/runtime-prune-health.ts +6 -2
  47. package/src/hub/sdlc-metrics.ts +2 -2
  48. package/src/hub/settings.ts +2 -0
  49. package/src/hub/task-sweep.ts +6 -2
  50. package/src/hub/tasks.ts +8 -3
  51. package/src/hub/turn-attribution.ts +46 -0
  52. package/templates/AGENTS.block.md +1 -1
@@ -0,0 +1,162 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { readControl } from "../hub/control-client.ts";
5
+ import { RecoveryDeferredHubError } from "../hub/deferred-hub.ts";
6
+ import { inspectProject, type ProjectInspection } from "../hub/lifecycle.ts";
7
+ import { canonicalPath, hubHome } from "../hub/project.ts";
8
+ import { recordProjectRuntime } from "../hub/project-runtime.ts";
9
+ import { createProjectRuntimeAccess, projectRuntimeFile, type ProjectRuntimeIdentity, type ProjectRuntimeSelection } from "../hub/project-runtime-state.ts";
10
+ import { recoveryLock } from "../hub/recovery-store.ts";
11
+ import { Registry, type Project } from "../hub/registry.ts";
12
+ import { readRestartSnapshot, restartPath } from "../hub/restart.ts";
13
+ import { processLiveness } from "../pi/process-signature.ts";
14
+ import { exactVersion, newerVersion, registryRelease, runCommand, stageCurrentRuntime, stageRelease, verifyRecoveryTarget, type RunCommand } from "./recovery-package.ts";
15
+ import { registeredProjects } from "./upgrade.ts";
16
+
17
+ /**
18
+ * #1540: `ahub upgrade` for a project whose hub is stopped. It rewrites that project's `runtime.json` to the target and nothing else: no daemon, no terminal, no peer and no recovery
19
+ * operation. The write is `recordProjectRuntime`, the verified-write path every startup uses, under the registry's runtime-capture lock.
20
+ */
21
+ export type StoppedOutcome = "retarget" | "current" | "running" | "refused";
22
+ export interface StoppedRow {
23
+ project: Project;
24
+ outcome: StoppedOutcome;
25
+ /** What inspection read: only `stopped` and `missing` are this module's to plan alone; any other reading belongs to the ordinary recovery plan. */
26
+ inspected: string;
27
+ /** The recorded version, for `retarget` and `current`; absent when the project records no runtime yet. */
28
+ from?: string;
29
+ /** Identity of the recorded selection the plan read, so the apply refuses a record that changed meanwhile. */
30
+ before?: string;
31
+ cause?: string;
32
+ next?: string;
33
+ command?: string;
34
+ }
35
+ export interface StoppedPlan {
36
+ schema: 1;
37
+ kind: "upgrade";
38
+ mode: "runtime-selection";
39
+ scope: "project" | "all-stopped";
40
+ version: string;
41
+ integrity?: string;
42
+ rows: StoppedRow[];
43
+ blockers: string[];
44
+ fingerprint: string;
45
+ }
46
+ export interface StoppedResult { id: string; root: string; outcome: "retargeted" | "failed"; from?: string; to: string; cause?: string }
47
+ export interface StoppedDeps {
48
+ home?: string;
49
+ inspect?: (project: Project) => Promise<ProjectInspection>;
50
+ /** Stage and verify the target once; the default is the same staging a scoped recovery uses. */
51
+ stage?: (version: string, integrity: string, run: RunCommand) => Promise<{ root: string; digest: string }>;
52
+ }
53
+
54
+ const message = (error: unknown): string => (error instanceof Error ? error.message : String(error)).split("\n")[0]!.slice(0, 300);
55
+ const selectionKey = (runtime: ProjectRuntimeIdentity | undefined): string => runtime
56
+ ? JSON.stringify([runtime.version, runtime.root, runtime.digest, runtime.kind, runtime.instanceId]) : "none";
57
+ const fingerprintOf = (plan: Omit<StoppedPlan, "fingerprint">): string => createHash("sha256").update(JSON.stringify({
58
+ scope: plan.scope, version: plan.version, integrity: plan.integrity, blockers: plan.blockers,
59
+ rows: plan.rows.map(row => [row.project.id, row.project.root, row.outcome, row.inspected, row.from, row.before, row.cause]),
60
+ })).digest("hex");
61
+
62
+ async function classify(project: Project, version: string, inspect: NonNullable<StoppedDeps["inspect"]>, home: string): Promise<StoppedRow> {
63
+ let inspected = "unknown";
64
+ const refuse = (cause: string, next: string): StoppedRow => ({ project, outcome: "refused", inspected, cause, next });
65
+ let state: ProjectInspection;
66
+ try { state = await inspect(project); }
67
+ catch (error) { return refuse(`inspection failed: ${message(error)}`, `check \`ahub doctor\`, then run this again`); }
68
+ inspected = state.state;
69
+ if (state.state === "running") return { project, outcome: "running", inspected, command: `ahub --project ${project.id} upgrade --to ${version}` };
70
+ if (state.state === "missing") return refuse("project directory is missing", `restore ${project.root}, or forget the registration with \`ahub projects remove ${project.id}\``);
71
+ // Only a positive reading of "stopped" qualifies: unknown, unavailable, starting, stopping and incompatible are never read as stopped.
72
+ if (state.state !== "stopped") return refuse(`its hub is not verifiably stopped (${state.state}${state.error ? `: ${message(state.error)}` : ""})`, `wait for it to settle or run \`ahub --project ${project.id} status\`, then run this again`);
73
+ if (!existsSync(join(project.root, ".agenthub", "config.json"))) return refuse("project is not initialized", `run \`ahub init\` in ${project.root} first, or forget it with \`ahub projects remove ${project.id}\``);
74
+ // restart.json exists only while a restart snapshot is unreleased (a released one is renamed away); a corrupt one counts too.
75
+ if (existsSync(restartPath(project.stateDir))) {
76
+ let held = "";
77
+ try { held = readRestartSnapshot(project.stateDir, { projectRoot: project.root, projectId: project.id })?.operationId ?? ""; }
78
+ catch (error) { if (!(error instanceof RecoveryDeferredHubError)) throw error; }
79
+ return refuse(held ? `it holds the unreleased restart snapshot of recovery operation ${held}` : "it holds a restart snapshot that cannot be read",
80
+ `start it with \`ahub --project ${project.id} up\` and finish or abort that operation with \`ahub recovery status\`, then run this again`);
81
+ }
82
+ try {
83
+ const owner = recoveryLock(home, project.root);
84
+ if (owner) return refuse(`recovery operation ${owner} holds this project`, `finish it with \`ahub recovery status ${owner}\`, then run this again`);
85
+ } catch (error) { return refuse(`the recovery lock cannot be read: ${message(error)}`, "check `ahub doctor`, then run this again"); }
86
+ let retained: ProjectRuntimeIdentity | undefined;
87
+ try { retained = createProjectRuntimeAccess(project).read(); }
88
+ catch (error) { return refuse(message(error), `inspect ${projectRuntimeFile(project)} (keep it out of git, or remove it), then run this again`); }
89
+ const before = selectionKey(retained);
90
+ if (retained && (retained.version === version || newerVersion(retained.version, version))) return { project, outcome: "current", inspected, from: retained.version, before };
91
+ return { project, outcome: "retarget", inspected, ...(retained ? { from: retained.version } : {}), before };
92
+ }
93
+
94
+ /**
95
+ * Plan the runtime-selection-only retarget of one project (`selection.root`) or of every registered project (`"all"`). Each project is read independently, so one refusal never blocks another.
96
+ * A single project that is not stopped is the caller's business (the ordinary recovery plan); here it reads as `running` or `refused`.
97
+ */
98
+ export async function planStoppedRetargets(version: string, selection: { root: string } | "all", run: RunCommand = runCommand, deps: StoppedDeps = {}): Promise<StoppedPlan> {
99
+ exactVersion(version);
100
+ const home = deps.home ?? hubHome(), inspect = deps.inspect ?? ((project: Project) => inspectProject(project));
101
+ const all = selection === "all";
102
+ const wanted = all ? undefined : canonicalPath(selection.root);
103
+ const projects = registeredProjects(home).filter(project => wanted === undefined || project.root === wanted);
104
+ const rows: StoppedRow[] = [];
105
+ for (const project of projects) rows.push(await classify(project, version, inspect, home));
106
+ const blockers: string[] = [];
107
+ if (!all) {
108
+ if (!rows.length) blockers.push(`project is not registered: ${wanted}`);
109
+ for (const row of rows) if (row.outcome === "refused") blockers.push(`${row.project.id}: ${row.cause}; ${row.next}`);
110
+ }
111
+ const release = rows.some(row => row.outcome === "retarget") ? await registryRelease(version, run) : undefined;
112
+ const body: Omit<StoppedPlan, "fingerprint"> = { schema: 1, kind: "upgrade", mode: "runtime-selection", scope: all ? "all-stopped" : "project", version,
113
+ ...(release ? { integrity: release.integrity } : {}), rows, blockers };
114
+ return { ...body, fingerprint: fingerprintOf(body) };
115
+ }
116
+
117
+ async function defaultStage(version: string, integrity: string, run: RunCommand): Promise<{ root: string; digest: string }> {
118
+ const staged = await stageRelease(version, integrity, run, hubHome(), true);
119
+ return stageCurrentRuntime(staged.root, version);
120
+ }
121
+
122
+ /** The write itself, atomic with its own checks under the registry's runtime-capture lock: a hub that started after planning, a new snapshot, a hold or a changed record refuses. */
123
+ function retargetOne(row: StoppedRow, selection: ProjectRuntimeSelection, home: string): void {
124
+ const access = createProjectRuntimeAccess(row.project); // Git-trust check; callers create it before taking the registry lock
125
+ const registry = new Registry(join(home, "registry.db"));
126
+ try {
127
+ registry.runtimeCaptureLocked(() => {
128
+ const current = registry.get(row.project.id);
129
+ if (!current || current.root !== row.project.root || current.stateDir !== row.project.stateDir) throw new Error("project registration changed; plan again");
130
+ const started = "a hub started for this project after planning; nothing was written";
131
+ if (current.instanceId && processLiveness(current.pid, current.pidSignature) !== "gone") throw new Error(started);
132
+ const control = readControl(current.stateDir);
133
+ if (control && processLiveness(control.pid, control.pidSignature) !== "gone") throw new Error(started);
134
+ if (existsSync(restartPath(current.stateDir))) throw new Error("a restart snapshot appeared after planning; nothing was written");
135
+ const owner = recoveryLock(home, current.root);
136
+ if (owner) throw new Error(`recovery operation ${owner} holds this project; nothing was written`);
137
+ if (selectionKey(access.read()) !== row.before) throw new Error("the recorded runtime changed after planning; plan again");
138
+ // ponytail: a starter that published its pending selection (instance null) but whose daemon has not claimed the registry yet is seen only as an unchanged record; a start marker under the lock would close that window.
139
+ recordProjectRuntime(current, selection, null, registry, access);
140
+ });
141
+ } finally { registry.close(); }
142
+ }
143
+
144
+ /** Apply the `retarget` rows of a plan: stage and verify the target once, then write each project independently. A failed project never stops the others. */
145
+ export async function applyStoppedRetargets(plan: StoppedPlan, run: RunCommand = runCommand, deps: StoppedDeps = {}): Promise<StoppedResult[]> {
146
+ const home = deps.home ?? hubHome();
147
+ const rows = plan.rows.filter(row => row.outcome === "retarget");
148
+ if (!rows.length) return [];
149
+ const failed = (row: StoppedRow, cause: string): StoppedResult => ({ id: row.project.id, root: row.project.root, outcome: "failed", ...(row.from ? { from: row.from } : {}), to: plan.version, cause });
150
+ let selection: ProjectRuntimeSelection;
151
+ try {
152
+ if (!plan.integrity) throw new Error("the plan carries no release identity");
153
+ const target = await (deps.stage ?? defaultStage)(plan.version, plan.integrity, run);
154
+ if (verifyRecoveryTarget("upgrade", target.root, plan.version) !== target.digest) throw new Error("the staged package changed after verification");
155
+ selection = { version: plan.version, root: target.root, digest: target.digest, kind: "upgrade" };
156
+ } catch (error) { return rows.map(row => failed(row, `staging the target failed: ${message(error)}; no runtime was changed`)); }
157
+ return rows.map(row => {
158
+ try { retargetOne(row, selection, home); }
159
+ catch (error) { return failed(row, message(error)); }
160
+ return { id: row.project.id, root: row.project.root, outcome: "retargeted" as const, ...(row.from ? { from: row.from } : {}), to: plan.version };
161
+ });
162
+ }
@@ -0,0 +1,37 @@
1
+ import type { RecoveryOperation } from "./upgrade.ts";
2
+
3
+ export interface OperationWaitPorts {
4
+ read(id: string): RecoveryOperation;
5
+ /** The claimed runner: a pid, "unknown" when it cannot be told, undefined when none holds the claim. */
6
+ runner(id: string): number | "unknown" | undefined;
7
+ now(): number;
8
+ sleep(ms: number): Promise<void>;
9
+ }
10
+
11
+ /** A runner claims and writes within a moment of being spawned; this long without either reads as gone. */
12
+ export const RUNNER_APPEARS_MS = 10_000;
13
+ /**
14
+ * The longest `upgrade --yes` waits for an operation that is still running. A restart waits up to 10 minutes for a quiet hub and each peer restore can wait as long (docs/operations.md), so this is
15
+ * several of those; past it the command fails and names the status command, leaving the operation to its runner.
16
+ * ponytail: a fixed cap; read it from a recovery setting if a longer upgrade needs it.
17
+ */
18
+ export const OPERATION_WAIT_MS = 2 * 60 * 60 * 1000;
19
+
20
+ /**
21
+ * #1540 AC10: wait until a scheduled recovery operation is terminal (completed, cancelled or blocked), so `ahub upgrade --yes; ahub down` no longer races "recovery operation <id> is active".
22
+ * A runner that never shows, or is gone with the receipt still open, returns that open receipt: the caller reads it as a failure, never as success. The receipt is read once more after the runner
23
+ * lets go of its claim, because a runner writes its end state first.
24
+ */
25
+ export async function awaitOperationEnd(operation: Pick<RecoveryOperation, "id" | "updatedAt">, ports: OperationWaitPorts): Promise<RecoveryOperation> {
26
+ const started = ports.now();
27
+ let seen = false;
28
+ for (;;) {
29
+ const op = ports.read(operation.id);
30
+ if (op.phase === "completed" || op.phase === "cancelled" || op.phase === "blocked") return op;
31
+ const runner = ports.runner(operation.id);
32
+ if (runner !== undefined || op.updatedAt !== operation.updatedAt) seen = true;
33
+ if (runner === undefined && (seen || ports.now() - started > RUNNER_APPEARS_MS)) return ports.read(operation.id);
34
+ if (ports.now() - started > OPERATION_WAIT_MS) return op;
35
+ await ports.sleep(250);
36
+ }
37
+ }
package/src/hub/board.ts CHANGED
@@ -296,6 +296,8 @@ export interface HistoryEntry {
296
296
  noWrites?: true;
297
297
  /** Host-recorded expected cost and exact review head, never narrative. */
298
298
  reviewCost?: ReviewCost;
299
+ /** Full commit submitted for review; independent of cost planning. */
300
+ requestHead?: string;
299
301
  /** #901: on the hub's own `check passed` / `check failed`: the check key (task class or profile class alias) whose command ran. Set by the hub from its own selection, never from output or an owner's words. */
300
302
  checkKey?: string;
301
303
  /** #901: on such an entry, the number of unresolved citation keys the example citation check printed (`citations: N declared keys, M missing`); absent when the check printed no such line. */
@@ -2685,7 +2687,7 @@ export class Board {
2685
2687
 
2686
2688
  /** The only way a task changes. Validates the move, records who did what, returns the new row. */
2687
2689
  /** A `plan` in the patch replaces the old one whole: a new plan is the owner's current intent, not an addition. */
2688
- update(id: number, by: PeerId, event: string, patch: Partial<Pick<Task, "state" | "owner" | "planner" | "reviewer" | "reserved" | "refs" | "plan" | "rejections" | "signals" | "sdlc" | "role" | "cancelled" | "codeSymbols">>, note?: string, extra: Pick<HistoryEntry, "invocation" | "plannerReason" | "planAuthor" | "selfReview" | "profile" | "sweep" | "wait" | "reason" | "from" | "capacity" | "conductorManual" | "withheld" | "noWrites" | "reviewCost" | "reviewContext" | "reviewScope" | "evidenceOnly" | "reviewedHead" | "reviewFindings" | "unmetCriteria" | "deliverables" | "checkKey" | "missingKeys" | "claim" | "planObservation" | "planDeparture" | "planDepartureInvalidated" | "specReport" | "specRefBinding" | "resolvedReviewComments" | "securityPass" | keyof ReviewerHistory> = {}, expectedFlowRevision?: number, codeSymbolsAuthority?: typeof HOST_CODE_SYMBOLS, adoptionAuthority?: typeof HOST_MERGE_ADOPTION): Task {
2690
+ update(id: number, by: PeerId, event: string, patch: Partial<Pick<Task, "state" | "owner" | "planner" | "reviewer" | "reserved" | "refs" | "plan" | "rejections" | "signals" | "sdlc" | "role" | "cancelled" | "codeSymbols">>, note?: string, extra: Pick<HistoryEntry, "invocation" | "plannerReason" | "planAuthor" | "selfReview" | "profile" | "sweep" | "wait" | "reason" | "from" | "capacity" | "conductorManual" | "withheld" | "noWrites" | "reviewCost" | "requestHead" | "reviewContext" | "reviewScope" | "evidenceOnly" | "reviewedHead" | "reviewFindings" | "unmetCriteria" | "deliverables" | "checkKey" | "missingKeys" | "claim" | "planObservation" | "planDeparture" | "planDepartureInvalidated" | "specReport" | "specRefBinding" | "resolvedReviewComments" | "securityPass" | keyof ReviewerHistory> = {}, expectedFlowRevision?: number, codeSymbolsAuthority?: typeof HOST_CODE_SYMBOLS, adoptionAuthority?: typeof HOST_MERGE_ADOPTION): Task {
2689
2691
  if (extra.resolvedReviewComments?.length && !this.db.inTransaction) return this.atomic(() => this.update(id, by, event, patch, note, extra, expectedFlowRevision, codeSymbolsAuthority, adoptionAuthority));
2690
2692
  const task = this.get(id);
2691
2693
  if (!task) throw new Error(`no task #${id}`);
@@ -2783,7 +2785,7 @@ export class Board {
2783
2785
  && priorHead !== undefined && /^[a-f0-9]{40}$/.test(priorHead);
2784
2786
  const previousHistory = backfill ? task.history.map((entry, index) => index === priorApproval && !entry.reviewedHead
2785
2787
  ? { ...entry, reviewedHead: entry.reviewFindings?.head ?? priorHead } : entry) : task.history;
2786
- const history = [...previousHistory, { at: Date.now(), by, event, ...(resolvedReviewComments?.length ? { resolvedReviewComments } : {}), ...(returnPlanning ? { planning: returnPlanning } : {}), ...(extra.invocation ? { invocation: extra.invocation } : {}), ...plannerHistory, ...authorHistory, ...(extra.selfReview === true ? { selfReview: true as const } : {}), ...(planRevision ? { planRevision } : {}), ...(extra.planObservation ? { planObservation: extra.planObservation } : {}), ...(extra.planDeparture ? { planDeparture: extra.planDeparture } : {}), ...(departureInvalidated ? { planDepartureInvalidated: true as const } : {}), ...reviewMetadata, ...specMetadata, ...(note ? { note } : {}), ...(patch.cancelled?.supersededBy ? { supersededBy: patch.cancelled.supersededBy } : {}), ...("owner" in patch ? { owner: next.owner } : {}), ...(extra.profile ? { profile: extra.profile } : {}), ...(extra.sweep ? { sweep: extra.sweep } : {}), ...(event === "wait recorded" && extra.wait && Number.isSafeInteger(extra.wait.until) && extra.wait.until > 0 ? { wait: { until: extra.wait.until, owner: extra.wait.owner } } : {}), ...(extra.reason && TASK_MOVE_REASONS.includes(extra.reason) ? { reason: extra.reason } : {}), ...(extra.from ? { from: extra.from } : {}), ...(extra.capacity === true ? { capacity: true as const } : {}), ...(extra.conductorManual === true ? { conductorManual: true as const } : {}), ...(extra.withheld && (note || reviewFindings) ? { withheld: true as const } : {}), ...(reviewFindings ? { reviewFindings } : {}), ...(extra.reviewedHead ? { reviewedHead: extra.reviewedHead } : {}), ...(unmetCriteria?.length ? { unmetCriteria } : {}), ...(securityPass ? { securityPass } : {}), ...(deliverables ? { deliverables } : {}), ...(extra.reviewContext === "fresh" || extra.reviewContext === "continuing" ? { reviewContext: extra.reviewContext } : {}), ...(extra.reviewScope === "code" ? { reviewScope: "code" as const } : {}), ...(extra.evidenceOnly === true && event === "changes_requested" ? { evidenceOnly: true as const } : {}), ...(extra.reviewCost ? { reviewCost: extra.reviewCost } : {}), ...(event === "done" && extra.noWrites === true ? { noWrites: true as const } : {}), ...(["check passed", "check failed"].includes(event) && typeof extra.checkKey === "string" && /^[a-z][a-z0-9_]{0,47}$/.test(extra.checkKey) ? { checkKey: extra.checkKey } : {}), ...(["check passed", "check failed"].includes(event) && Number.isSafeInteger(extra.missingKeys) && extra.missingKeys! >= 0 && extra.missingKeys! <= 100_000 ? { missingKeys: extra.missingKeys } : {}), ...(event === "claim verdict" && extra.claim ? { claim: extra.claim } : {}) }];
2788
+ const history = [...previousHistory, { at: Date.now(), by, event, ...(resolvedReviewComments?.length ? { resolvedReviewComments } : {}), ...(returnPlanning ? { planning: returnPlanning } : {}), ...(extra.invocation ? { invocation: extra.invocation } : {}), ...plannerHistory, ...authorHistory, ...(extra.selfReview === true ? { selfReview: true as const } : {}), ...(planRevision ? { planRevision } : {}), ...(extra.planObservation ? { planObservation: extra.planObservation } : {}), ...(extra.planDeparture ? { planDeparture: extra.planDeparture } : {}), ...(departureInvalidated ? { planDepartureInvalidated: true as const } : {}), ...reviewMetadata, ...specMetadata, ...(note ? { note } : {}), ...(patch.cancelled?.supersededBy ? { supersededBy: patch.cancelled.supersededBy } : {}), ...("owner" in patch ? { owner: next.owner } : {}), ...(extra.profile ? { profile: extra.profile } : {}), ...(extra.sweep ? { sweep: extra.sweep } : {}), ...(event === "wait recorded" && extra.wait && Number.isSafeInteger(extra.wait.until) && extra.wait.until > 0 ? { wait: { until: extra.wait.until, owner: extra.wait.owner } } : {}), ...(extra.reason && TASK_MOVE_REASONS.includes(extra.reason) ? { reason: extra.reason } : {}), ...(extra.from ? { from: extra.from } : {}), ...(extra.capacity === true ? { capacity: true as const } : {}), ...(extra.conductorManual === true ? { conductorManual: true as const } : {}), ...(extra.withheld && (note || reviewFindings) ? { withheld: true as const } : {}), ...(reviewFindings ? { reviewFindings } : {}), ...(extra.reviewedHead ? { reviewedHead: extra.reviewedHead } : {}), ...(unmetCriteria?.length ? { unmetCriteria } : {}), ...(securityPass ? { securityPass } : {}), ...(deliverables ? { deliverables } : {}), ...(extra.reviewContext === "fresh" || extra.reviewContext === "continuing" ? { reviewContext: extra.reviewContext } : {}), ...(extra.reviewScope === "code" ? { reviewScope: "code" as const } : {}), ...(extra.evidenceOnly === true && event === "changes_requested" ? { evidenceOnly: true as const } : {}), ...(extra.reviewCost ? { reviewCost: extra.reviewCost } : {}), ...(event === "done" && extra.requestHead && /^[a-f0-9]{40}$/.test(extra.requestHead) ? { requestHead: extra.requestHead } : {}), ...(event === "done" && extra.noWrites === true ? { noWrites: true as const } : {}), ...(["check passed", "check failed"].includes(event) && typeof extra.checkKey === "string" && /^[a-z][a-z0-9_]{0,47}$/.test(extra.checkKey) ? { checkKey: extra.checkKey } : {}), ...(["check passed", "check failed"].includes(event) && Number.isSafeInteger(extra.missingKeys) && extra.missingKeys! >= 0 && extra.missingKeys! <= 100_000 ? { missingKeys: extra.missingKeys } : {}), ...(event === "claim verdict" && extra.claim ? { claim: extra.claim } : {}) }];
2787
2789
  this.taskWrite(() => {
2788
2790
  if (resolvedReviewComments?.length) for (const record of this.reviewComments(task.id, task.created)) {
2789
2791
  if (!resolvedReviewComments.includes(record.thread.id) || record.lifecycle !== "sent") continue;
@@ -308,6 +308,7 @@ export function configApply(key: string, scopes: readonly ConfigIdentityScope[]
308
308
  }
309
309
  const operational = operationalNumber(key);
310
310
  if (operational) return { applies: operational.applies, ...(operational.restartReason ? { reason: operational.restartReason } : {}) };
311
+ if (key === "memory.sync_interval_min") return { applies: "live" };
311
312
  if (nextMemory.has(key)) return { applies: "next use" };
312
313
  for (const [path, reason] of Object.entries(restart)) if (key === path || key.startsWith(`${path}.`)) return { applies: "restart", reason };
313
314
  if ([...live].some(path => key === path || key.startsWith(`${path}.`))) return { applies: "live" };
package/src/hub/daemon.ts CHANGED
@@ -112,7 +112,7 @@ import { CONSOLE_POLL_SETTING, CONSOLE_NOTICE_SETTING, CONSOLE_HISTORY_SETTING,
112
112
  import { MODEL_COOLDOWN_FAILURES_SETTING, MODEL_COOLDOWN_SETTING, MODEL_COOLDOWN_CAP_SETTING, MODEL_TERMINAL_HISTORY_SETTING, modelOperationalReaders, type ModelOperationalConfig } from "./operational-settings.ts";
113
113
  import { ACP_TOOL_CEILING_SETTING, ACP_ACTIVITY_BATCH_SETTING, JCODE_STEER_TIMEOUT_SETTING, adapterOperationalReaders, type AdapterTimingConfig } from "./operational-settings.ts";
114
114
  import { BUS_ACCEPTED_SETTLE_MS_SETTING, BUS_DIGEST_MAX_SETTING, BUS_MAX_ATTEMPTS_SETTING, BUS_NOTES_KEPT_SETTING, BUS_PULL_BUDGET_BYTES_SETTING, BUS_TERMINAL_HISTORY_LIMIT_SETTING, busOperationalReaders, RECOVERY_CONTROL_TIMEOUT_SETTING, RECOVERY_RECONNECT_WAIT_SETTING, RECOVERY_SHUTDOWN_WAIT_SETTING, RECOVERY_TERMINAL_IDLE_WAIT_SETTING, RECOVERY_UNMANAGED_RECONNECT_WAIT_SETTING } from "./operational-settings.ts";
115
- import { foldersConfig, scheduleViews, schedulesConfig, ScheduleStore, type FolderEntry, type ScheduleEntry } from "./schedules.ts";
115
+ import { foldersConfig, scheduleKeyOf, scheduleViews, schedulesConfig, ScheduleStore, type FolderEntry, type ScheduleEntry } from "./schedules.ts";
116
116
  import { FolderStore, registerScanned, scanFolder, type FolderPolicy } from "./folder-trigger.ts";
117
117
  import { QuestionStore, QUESTION_SURFACES, questionView } from "./questions.ts";
118
118
  import { RunTracker, outcomeOf, settleVerdict, type Run } from "./completions.ts";
@@ -157,6 +157,7 @@ import { CHECKPOINT_FIELDS, CHECKPOINT_FIELDS_SENTENCE, checkpointFieldCount, pa
157
157
  import { ModelOverrides, ModelOverrideLatches, type RuntimeModelStatus, type ModelSource } from "./model-overrides.ts";
158
158
  import { isNativeModelToken } from "../adapters/model-token.ts";
159
159
  import { processSignature, processLiveness } from "../pi/process-signature.ts";
160
+ import { processSignatureAsync } from "@staix/agent-mem/platform";
160
161
  import { PiSessionBookmarkMismatch, PiSessionUnresumable, recordPiReplacement, validatePiSession } from "../pi/session.ts";
161
162
  import { profile, proxyEnv, sandboxAvailable, type SandboxNetwork } from "../local/sandbox.ts";
162
163
  import { DEFAULT_NETWORK_ALLOW, startEgressProxy, type EgressProxy } from "../local/proxy.ts";
@@ -185,12 +186,13 @@ import { Board, isClosedTaskState, taskProposalAt, taskHasStarted, CLASSES, type
185
186
  import { UsageRollup, USAGE_GROUPS, LIMITS_MAX, type UsageGroup } from "./usage-rollup.ts";
186
187
  import { Budget, readNativeQuota, DEFAULT_BUDGET, type BudgetConfig } from "./budget.ts";
187
188
  import { remoteEnvelope, HUB } from "./envelope.ts";
189
+ import { applyTurnAttribution, turnAttribution } from "./turn-attribution.ts";
188
190
  import { recallMemoryLines, trimToTokens, aggregateUse, orderByUse } from "../memory/recall.ts";
189
191
  import { closeSync, constants as fsConstants, openSync, lstatSync, readSync, statSync } from "node:fs";
190
192
  import { basename, isAbsolute } from "node:path";
191
193
  import { fileURLToPath } from "node:url";
192
194
  import { canonicalPath, realPath, hubHome } from "./project.ts";
193
- import { HandoffRefusal, checkTarget, handoffAge, handoffCatchUpRow, handoffChunks, handoffConnectFailure, handoffLogGate, handoffOutcomeUnknown, handoffReach, parseHandoff, resolveTarget, handoffEventFor, type HandoffEvent } from "./handoff.ts";
195
+ import { HandoffRefusal, checkTarget, handoffAge, handoffCatchUpRow, handoffChunks, handoffConnectFailure, handoffLogGate, handoffOutcomeUnknown, handoffReach, handoffStateGate, handoffTargetStopped, parseHandoff, resolveTarget, handoffEventFor, type HandoffEvent } from "./handoff.ts";
194
196
  import { mainCheckoutBranch, mainCheckoutWarning } from "./main-checkout.ts";
195
197
  import type { BusEvent, PublishResult } from "./bus.ts";
196
198
  import { QUESTION_TOOLS, CONDUCTOR_TOOLS, CONDUCTOR_TOOL_NAMES, DEFAULT_ROLES, IMPLEMENTER_HUB_TOOL_NAMES, roleContract, TASK_TOOL_NAMES, TASK_TOOLS, BOUNDED_TASK_TOOLS, LINEAGE_TOOL_NAMES, GUIDANCE_TOOL_NAMES, CAPABILITY_TOOLS, profileTaskTools, sessionTitleTools } from "./hub-tools.ts";
@@ -3007,8 +3009,10 @@ export async function startDaemon(opts: DaemonOptions) {
3007
3009
  const projectSpecs = specInspectorAt(opts.cwd);
3008
3010
  let specsMissingBlockHintShown = false;
3009
3011
  let releaseReportPolicy: ((head: string, repo: string) => ReleaseReportPolicy | undefined) | undefined;
3012
+ let questionStore!: QuestionStore;
3010
3013
  startupTimings.mark("task_ports");
3011
3014
  const tasks: Tasks = new Tasks({
3015
+ ownerQuestionWait: (task, peer) => questionStore?.ownerWait(task, peer),
3012
3016
  guidanceProbes: { store: guidanceProbeStore, session: by => {
3013
3017
  const request = guidanceProbeRequestContext.getStore();
3014
3018
  return request?.actor === by ? { generation: request.generation, nativeSession: request.nativeSession,
@@ -4488,6 +4492,14 @@ export async function startDaemon(opts: DaemonOptions) {
4488
4492
  const owned = board.list("in_progress").filter(task => task.owner === peer && !tasks.isPii(task));
4489
4493
  return owned.length === 1 ? owned[0]!.id : undefined;
4490
4494
  }
4495
+ /** Attribution only: the same board provenance check used by the schedule inventory. */
4496
+ function scheduledTask(taskId: number): boolean | undefined {
4497
+ try {
4498
+ const task = board.get(taskId);
4499
+ if (!task?.history[0]) return undefined;
4500
+ return task.history[0].by === HUB && scheduleKeyOf(task.detail) !== undefined;
4501
+ } catch { return undefined; }
4502
+ }
4491
4503
  type ImplementerFailureEntry = { launchId: string; generation: string; signal: AbortSignal; trace: ClaudeFailureTrace; probeCount: number; permissionAttempt: number };
4492
4504
  const implementerFailures = new WeakMap<PeerAdapter, ImplementerFailureEntry>();
4493
4505
  function currentImplementerTools(c: Client, verifyRoot = true): ReturnType<NonNullable<PeerAdapter["ownedTools"]>> {
@@ -4923,6 +4935,26 @@ export async function startDaemon(opts: DaemonOptions) {
4923
4935
  };
4924
4936
  rescheduleSweep();
4925
4937
  startupCleanup.push(() => clearInterval(sweepTimer));
4938
+ let memorySyncFirst: ReturnType<typeof setTimeout> | undefined;
4939
+ let memorySyncTimer: ReturnType<typeof setInterval> | undefined;
4940
+ const clearMemorySyncTimers = () => {
4941
+ clearTimeout(memorySyncFirst);
4942
+ clearInterval(memorySyncTimer);
4943
+ memorySyncFirst = undefined;
4944
+ memorySyncTimer = undefined;
4945
+ };
4946
+ const rescheduleMemorySync = (firstPass: boolean) => {
4947
+ clearMemorySyncTimers();
4948
+ const every = config.memory.sync_interval_min ?? 10;
4949
+ if (!memoryStore || opts.memorySyncTrigger || every <= 0) return;
4950
+ if (firstPass) {
4951
+ memorySyncFirst = setTimeout(() => void syncNow(), 5_000);
4952
+ memorySyncFirst.unref?.();
4953
+ }
4954
+ memorySyncTimer = setInterval(() => void syncNow(), every * 60_000);
4955
+ memorySyncTimer.unref?.();
4956
+ };
4957
+ startupCleanup.push(clearMemorySyncTimers);
4926
4958
  // #512a: the schedules timer is its own interval, started whenever `schedules` is configured, whatever `task_sweep.enabled` says, and re-armed on reload.
4927
4959
  // It runs no task sweep. Held while stopping or recovering (inside `proposeFromSchedules`), where a due schedule counts the skip and coalesces.
4928
4960
  const schedulesStore = new ScheduleStore(join(opts.stateDir, "hub.db"));
@@ -5080,6 +5112,7 @@ export async function startDaemon(opts: DaemonOptions) {
5080
5112
  * target is unreachable without asking it again.
5081
5113
  */
5082
5114
  const handoffLogSeen = new Map<string, number>(), handoffFailures = new Map<string, { cause: string; at: number }>();
5115
+ const handoffCatchUpState = new Map<string, string>();
5083
5116
  const handoffLog = (target: string, cause: string, line: string): void => {
5084
5117
  handoffFailures.set(target, { cause, at: Date.now() });
5085
5118
  if (handoffLogGate(handoffLogSeen, `${target}|${cause}`, Date.now(), opts.handoffLogWindowMs ?? 15 * 60_000)) log(line);
@@ -5234,9 +5267,26 @@ export async function startDaemon(opts: DaemonOptions) {
5234
5267
  if (stopping) return;
5235
5268
  try {
5236
5269
  const project = registeredProjects(hubHome()).find(candidate => candidate.id === remote);
5237
- const descriptor = project && readControl(project.stateDir);
5238
- if (!project) { handoffLog(remote, "project not registered (moved?)", `handoff catch-up of ${remote} skipped: project not registered (moved?)`); continue; }
5239
- if (!descriptor) { handoffLog(remote, "not running", `handoff catch-up of ${remote} skipped: its hub is not running`); continue; }
5270
+ if (!project) { handoffStateGate(handoffCatchUpState, remote, "moved"); handoffLog(remote, "project not registered (moved?)", `handoff catch-up of ${remote} skipped: project not registered (moved?)`); continue; }
5271
+ const before = readControl(project.stateDir);
5272
+ const signature = before?.pidSignature && Number.isSafeInteger(before.pid) && before.pid! > 0
5273
+ ? await processSignatureAsync(before.pid!).catch(() => undefined) : undefined;
5274
+ if (stopping) return;
5275
+ const currentProject = registeredProjects(hubHome()).find(candidate => candidate.id === remote);
5276
+ if (!currentProject || currentProject.root !== project.root || currentProject.stateDir !== project.stateDir) {
5277
+ handoffStateGate(handoffCatchUpState, remote, "moved");
5278
+ handoffLog(remote, "project not registered (moved?)", `handoff catch-up of ${remote} skipped: project not registered (moved?)`);
5279
+ continue;
5280
+ }
5281
+ const descriptor = readControl(project.stateDir);
5282
+ const sameIdentity = before?.pid === descriptor?.pid && before?.pidSignature === descriptor?.pidSignature;
5283
+ if (handoffTargetStopped(descriptor, (pid, expected) => processLiveness(pid, expected, () => sameIdentity ? signature : undefined))) {
5284
+ handoffFailures.set(remote, { cause: "not running", at: Date.now() });
5285
+ if (handoffStateGate(handoffCatchUpState, remote, "stopped")) log(`handoff catch-up of ${remote} skipped: its hub is not running`);
5286
+ continue;
5287
+ }
5288
+ handoffStateGate(handoffCatchUpState, remote, "available");
5289
+ if (!descriptor) continue; // handoffTargetStopped handles absence above
5240
5290
  if (!descriptor.features?.includes("task_handoff")) { handoffLog(remote, "too old for handoffs", `handoff catch-up of ${remote} skipped: its hub is too old for handoffs`); continue; }
5241
5291
  const client = await ControlClient.connect(project.stateDir, { role: "console", projectRoot: descriptor.cwd ?? project.root }, 3000);
5242
5292
  let answered = true;
@@ -5258,10 +5308,13 @@ export async function startDaemon(opts: DaemonOptions) {
5258
5308
  const handoffDescriptors = new Map<string, string>();
5259
5309
  const handoffWatch = (): void => {
5260
5310
  const changed = new Set<string>();
5261
- for (const remote of new Set(board.handoffOutboundOpen().filter(row => handoffCatchUpRow(row, Date.now())).map(row => row.remoteProject))) {
5311
+ const targets = new Set(board.handoffOutboundOpen().filter(row => handoffCatchUpRow(row, Date.now())).map(row => row.remoteProject));
5312
+ for (const target of handoffCatchUpState.keys()) if (!targets.has(target)) handoffCatchUpState.delete(target);
5313
+ for (const target of handoffDescriptors.keys()) if (!targets.has(target)) handoffDescriptors.delete(target);
5314
+ for (const remote of targets) {
5262
5315
  const project = registeredProjects(hubHome()).find(candidate => candidate.id === remote);
5263
5316
  const descriptor = project && readControl(project.stateDir);
5264
- const seen = descriptor ? `${descriptor.instanceId ?? ""}|${descriptor.url}` : "";
5317
+ const seen = descriptor ? `${descriptor.instanceId ?? ""}|${descriptor.url}|${descriptor.pid ?? ""}|${descriptor.pidSignature ?? ""}` : "";
5265
5318
  const before = handoffDescriptors.get(remote);
5266
5319
  handoffDescriptors.set(remote, seen);
5267
5320
  if (before !== undefined && before !== seen && seen) changed.add(remote);
@@ -6567,7 +6620,7 @@ export async function startDaemon(opts: DaemonOptions) {
6567
6620
  const nativeUnattended = (peer: string): boolean => startingUnattended.get(peer) ?? unattendedPeers.has(peer);
6568
6621
  // #1053: questions a peer asks the person. The store is the one record; the desk owns the waiting calls, supersede, cancel, expiry and the late-answer envelope.
6569
6622
  // Question text lives in hub.db and the envelope to the asking peer only: never a log line, an event, a notice or memory capture.
6570
- const questionStore = new QuestionStore(join(opts.stateDir, "hub.db"));
6623
+ questionStore = new QuestionStore(join(opts.stateDir, "hub.db"));
6571
6624
  startupCleanup.push(() => questionStore.close());
6572
6625
  const questionAttributions = new Map<string, TaskAttribution>();
6573
6626
  /**
@@ -8920,11 +8973,15 @@ export async function startDaemon(opts: DaemonOptions) {
8920
8973
  if (signal?.aborted) return "error: turn cancelled before tool effects";
8921
8974
  if (stopping || (recoveryActive() && recoveryPhase !== "preparing")) return "error: recovery is holding tool effects";
8922
8975
  const humanBash = context?.userBash === true && name === "bash";
8976
+ const attributionEnvs = humanBash ? [] : pi.budgetEnvelopes;
8977
+ let attributionTask: string | undefined;
8978
+ try { if (!humanBash) attributionTask = tasks.turnPolicy(attributionEnvs)?.task; } catch { /* Hints never block a tool. */ }
8923
8979
  let exitCode: number | null = null;
8924
8980
  const result = await piReceipts!.execute(sessionId ?? "", callId, name, humanBash ? { origin: "verified-user-bash", args: raw } : raw, async () => {
8925
8981
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return "error: invalid tool arguments";
8926
8982
  const nativeTurn = pi.observationTurn;
8927
8983
  const output = TASK_TOOL_NAMES.has(name) || CONDUCTOR_TOOL_NAMES.has(name) ? await (name === "hub_ask" && signal ? invocationRequestSignal.run({ signal, current: () => !signal.aborted }, () => taskOp(peer, name, raw as Record<string, unknown>, true)) : taskOp(peer, name, raw as Record<string, unknown>, true)) : await runTool(name, JSON.stringify(raw), { ...ctx, signal,
8984
+ sandboxEnv: applyTurnAttribution(ctx.sandboxEnv ?? {}, humanBash ? { trigger: "manual" } : turnAttribution(attributionEnvs, { task: attributionTask === undefined ? undefined : Number(attributionTask), scheduled: scheduledTask })) as Record<string, string>,
8928
8985
  ...(humanBash ? { onProcessExit: (code: number | null) => { exitCode = code; } } : {}),
8929
8986
  shellExecutionCheck: input => signal?.aborted || context?.isCurrent?.() === false || bus.peers.get(peer) !== pi ? "aborted" : humanBash ? "valid" : shellProofs.check(input),
8930
8987
  permit: async (title, tool, toolSignal, path, _observe, originalPath, input, policy) => {
@@ -9166,6 +9223,7 @@ export async function startDaemon(opts: DaemonOptions) {
9166
9223
  beforeInput: (context, envs) => beforeOwnedObserverInput(peer, local, context, envs),
9167
9224
  inputReleased: (context, envs) => ownedObserverInputReleased(peer, local, context, envs),
9168
9225
  titlePreface: () => titlePreface(peer),
9226
+ scheduledTask,
9169
9227
  turnPolicy: (envs) => {
9170
9228
  const policy = tasks.turnPolicy(envs);
9171
9229
  if (!policy) return undefined;
@@ -9215,6 +9273,11 @@ export async function startDaemon(opts: DaemonOptions) {
9215
9273
  } catch { return false; }
9216
9274
  },
9217
9275
  chatTask: () => implementerChatTask(peer),
9276
+ scheduledTask,
9277
+ taskHintAllowed: taskId => {
9278
+ try { const task = board.get(taskId); return !!task && task.owner === peer && !tasks.isPii(task) && currentRoot(); }
9279
+ catch { return false; }
9280
+ },
9218
9281
  failureTrace: (launch, nativeVersion) => {
9219
9282
  const trace = createClaudeFailureTrace({ instanceId, nativeVersion, current: () => {
9220
9283
  const active = implementer.ownedTools?.(launch.launchId);
@@ -10162,6 +10225,8 @@ export async function startDaemon(opts: DaemonOptions) {
10162
10225
  refreshAutonomyConsent(prepared.fileConfig);
10163
10226
  for (const peer of changedPermissionDefaults) applyPendingPermissionDefault(peer);
10164
10227
  if (changes.some(change => change.key === "task_sweep" || change.key.startsWith("task_sweep."))) rescheduleSweep();
10228
+ const syncChange = changes.find(change => change.key === "memory.sync_interval_min");
10229
+ if (syncChange) rescheduleMemorySync((Number(syncChange.before ?? 10) <= 0) && Number(syncChange.after ?? 10) > 0);
10165
10230
  if (changes.some(change => change.key === "schedules" || change.key.startsWith("schedules.") || change.key === "folder_triggers" || change.key.startsWith("folder_triggers."))) rescheduleSchedules();
10166
10231
  if (changes.some(change => ["batch_max", "batch_ms", "queue_cap"].includes(change.key))) bus.configureScheduling({ batchMax: config.batch_max, batchMs: config.batch_ms, queueCap: config.queue_cap });
10167
10232
  if (changes.some(change => change.key === "watchdog_ms")) for (const peer of bus.peers.values()) if (peer instanceof BasePeer) peer.configureWatchdog(config.watchdog_ms);
@@ -13283,6 +13348,7 @@ export async function startDaemon(opts: DaemonOptions) {
13283
13348
  dashboard?.stop();
13284
13349
  stopConfigWatch();
13285
13350
  clearInterval(sweepTimer);
13351
+ clearMemorySyncTimers();
13286
13352
  clearInterval(schedulesTimer);
13287
13353
  tasks.stopCiWatchers(); // #785 P1b: no per-head CI watcher outlives the hub
13288
13354
  for (const i of intervals) clearInterval(i);
@@ -13404,11 +13470,7 @@ export async function startDaemon(opts: DaemonOptions) {
13404
13470
  catch (e) { log(`hub memory goals unreadable: ${(e as Error).message}`); }
13405
13471
  renewAllLeases();
13406
13472
  const leases = setInterval(renewAllLeases, 10 * 60_000); leases.unref?.(); intervals.push(leases);
13407
- const every = config.memory.sync_interval_min ?? 10;
13408
- if (every > 0 && !opts.memorySyncTrigger) {
13409
- const first = setTimeout(() => void syncNow(), 5_000); first.unref?.(); intervals.push(first);
13410
- const timer = setInterval(() => void syncNow(), every * 60_000); timer.unref?.(); intervals.push(timer);
13411
- }
13473
+ rescheduleMemorySync(true);
13412
13474
  }
13413
13475
  opts.memorySyncTrigger?.(syncNow);
13414
13476
  if (crashed) {
@@ -86,6 +86,7 @@ export const STANDING_INSTRUCTION =
86
86
  // burned a full turn writing "ack" because nothing told them a reply costs everyone else a turn. Same
87
87
  // wording as the channel's: an ack asked for "in one short line" is still the ack the issue is about.
88
88
  "Do not acknowledge a message that needs no answer; every reply costs the other agents a turn. " +
89
+ "When nothing in a delivery needs an answer from you, end your turn with exactly [FYI]; it sends nothing. Start progress notes with [FYI]. " +
89
90
  // Measured: told only not to acknowledge, Kimi still answers "Noted." The marker is the lever that actually
90
91
  // costs nobody a turn, and it was explained only in the Claude channel's instructions.
91
92
  "Start your own message with [FYI] when it needs nobody's turn (it goes to the console and the log only), " +
@@ -171,6 +171,20 @@ export function handoffLogGate(seen: Map<string, number>, key: string, now: numb
171
171
  return true;
172
172
  }
173
173
 
174
+ /** Missing descriptors or proven-gone processes are stopped; uncertain identity keeps the existing probe path. */
175
+ export function handoffTargetStopped(descriptor: { pid?: number; pidSignature?: string } | undefined, liveness: (pid: number, signature?: string) => "live" | "gone" | "unknown"): boolean {
176
+ if (!descriptor) return true;
177
+ if (!Number.isSafeInteger(descriptor.pid) || descriptor.pid! <= 0) return false;
178
+ try { return liveness(descriptor.pid!, descriptor.pidSignature) === "gone"; } catch { return false; }
179
+ }
180
+
181
+ /** Report only a change; the host prunes entries for targets no longer in its open handoffs. */
182
+ export function handoffStateGate(seen: Map<string, string>, target: string, state: string): boolean {
183
+ if (seen.get(target) === state) return false;
184
+ seen.set(target, state);
185
+ return true;
186
+ }
187
+
174
188
  /** What the target's own status descriptor says. A daemon that is not running, or does not know the handoff, is refused with the person's action. */
175
189
  export function checkTarget(project: RegisteredProject, descriptor: TargetDescriptor | undefined): void {
176
190
  if (!descriptor) throw new HandoffRefusal("not_running", `the hub of ${project.id} is not running; run \`ahub up\` in ${project.root}, then hand the task off again (handoffs are not queued)`);
@@ -204,6 +204,13 @@ export class QuestionStore {
204
204
  }
205
205
  close(): void { try { this.db.close(); } catch { /* already closed */ } }
206
206
 
207
+ /** Timing only: never hydrate question text for the idle-owner sweep.
208
+ * ponytail: QuestionDesk's KEEP_SETTLED_MS (7 days) is the anchor ceiling; after pruning the ladder falls back to its own state. A durable board marker is the upgrade path. */
209
+ ownerWait(task: number, peer: string): { open: boolean; settled?: number } {
210
+ const row = this.db.query("SELECT MAX(CASE WHEN state = 'open' THEN 1 ELSE 0 END) AS open, MAX(settled) AS settled FROM questions WHERE task = ? AND peer = ?").get(task, peer) as { open: number | null; settled: number | null };
211
+ return { open: row.open === 1, ...(row.settled === null ? {} : { settled: row.settled }) };
212
+ }
213
+
207
214
  get(set: string): QuestionRow | undefined {
208
215
  if (typeof set !== "string" || !QUESTION_SET.test(set)) return undefined;
209
216
  const raw = this.db.query("SELECT * FROM questions WHERE set_id = ?").get(set) as RawRow | null;
@@ -282,3 +282,42 @@ export function claimRunner(id: string, home = hubHome()): () => void {
282
282
  db.close();
283
283
  };
284
284
  }
285
+
286
+ /** True when any machine or project recovery hold exists, or the coordination state cannot be read: unknown is held. */
287
+ export function anyRecoveryHold(home = hubHome()): boolean {
288
+ try {
289
+ if (legacyRecoveryLock(home)) return true;
290
+ const db = projectLocks(home);
291
+ if (!db) return false;
292
+ try { return !!db.query("SELECT 1 FROM project_locks LIMIT 1").get(); } finally { db.close(); }
293
+ } catch { return true; }
294
+ }
295
+
296
+ /**
297
+ * #1541: remove one terminal receipt and its runner db. The exclusive runner claim is the only mutual exclusion: a live or
298
+ * unidentifiable runner keeps the receipt, a dead one is replaced by `claimRunner` in its own transaction, so two retirers
299
+ * on the same stale claim cannot both proceed. Under the claim `confirm` sees the receipt as it is now; the receipt leaves
300
+ * first, then the claim row is released, then the runner db. An interruption between them leaves only a runner db without
301
+ * a receipt, which the next call settles through the ENOENT branch (a later claimant re-reads the receipt, finds none and
302
+ * fails). A runner db whose receipt is gone is settled the same way (`settled`, `confirm` never called); only the call that
303
+ * removed the receipt answers `retired`.
304
+ */
305
+ export function retireOperation(id: string, home: string, confirm: (record: unknown) => boolean, hooks: { betweenPair?: () => void } = {}): "retired" | "settled" | "kept" {
306
+ const file = operationPath(id, home);
307
+ let release: () => void;
308
+ try { release = claimRunner(id, home); } catch { return "kept"; }
309
+ let result: "retired" | "settled" = "settled";
310
+ try {
311
+ let record: unknown, removed = false;
312
+ try { record = readOperation(id, home); }
313
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") return "kept"; }
314
+ if (record !== undefined) {
315
+ if (!confirm(record)) return "kept";
316
+ rmSync(file); removed = true;
317
+ hooks.betweenPair?.();
318
+ }
319
+ result = removed ? "retired" : "settled";
320
+ } finally { release(); }
321
+ rmSync(`${file}.runner.db`, { force: true });
322
+ return result;
323
+ }
@@ -115,7 +115,8 @@ export function evidenceEntry(raw: unknown): EvidenceEntry | undefined {
115
115
  const family = closedId(e.reviewerFamily);
116
116
  if (family) out.reviewerFamily = family;
117
117
  const cost = text(e.reviewCost), findings = text(e.reviewFindings);
118
- if (typeof cost?.head === "string" && /^[0-9a-f]{40}$/.test(cost.head)) out.requestHead = cost.head;
118
+ const requestedHead = e.event === "done" ? e.requestHead ?? cost?.head ?? text(e.specReport)?.head : undefined;
119
+ if (typeof requestedHead === "string" && /^[0-9a-f]{40}$/.test(requestedHead)) out.requestHead = requestedHead;
119
120
  const planned = member(PLANNED_SCOPES, text(cost?.review)?.scope);
120
121
  if (planned) out.plannedScope = planned;
121
122
  if (typeof findings?.head === "string" && /^[0-9a-f]{40}$/.test(findings.head)) out.verdictHead = findings.head;