@staix/agent-hub 0.52.0 → 0.54.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 (196) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +4 -3
  3. package/docs/addons/open-code-review.md +3 -6
  4. package/docs/agent-notes/README.md +1 -1
  5. package/docs/agent-notes/adapters.md +5 -4
  6. package/docs/agent-notes/budget.md +2 -2
  7. package/docs/agent-notes/bus.md +1 -0
  8. package/docs/agent-notes/daemon.md +6 -5
  9. package/docs/agent-notes/models.md +1 -1
  10. package/docs/agent-notes/tasks.md +3 -3
  11. package/docs/agent-notes/tests.md +4 -4
  12. package/docs/contracts/companion-cli-v2.json +90 -0
  13. package/docs/contracts/companion-cli-v3.json +348 -0
  14. package/docs/design/adapters.md +1 -1
  15. package/docs/design/agent-hub-architecture.md +8 -5
  16. package/docs/design/bus.md +1 -1
  17. package/docs/design/cli-output-inventory.md +4 -2
  18. package/docs/design/execution-reference.md +1 -1
  19. package/docs/design/guidance-experiments.md +1 -0
  20. package/docs/design/guidance-probes.md +1 -0
  21. package/docs/design/model-routes.md +20 -5
  22. package/docs/design/roadmap.md +6 -4
  23. package/docs/design/task-board.md +21 -2
  24. package/docs/dogfood.md +13 -6
  25. package/docs/events.md +1 -1
  26. package/docs/memory.md +2 -2
  27. package/docs/operations.md +158 -50
  28. package/docs/quickstart.md +14 -2
  29. package/docs/security.md +17 -9
  30. package/docs/specs/2026-09-19-agent-hub-design.md +5 -3
  31. package/docs/specs/2026-09-19-multi-project-design.md +1 -1
  32. package/docs/specs/2026-09-20-upgrade-recovery-design.md +24 -0
  33. package/docs/specs/2026-12-04-arev-adoption-design.md +84 -0
  34. package/docs/specs/mcp-endpoint.md +15 -4
  35. package/docs/specs/relay-contract.md +38 -0
  36. package/docs/verification/2026-12-04-host-shared-receipts.md +43 -0
  37. package/docs/verification/2026-12-05-0.53.0.md +101 -0
  38. package/docs/verification/2026-12-05-agy-1.5.24.md +55 -0
  39. package/docs/verification/2026-12-05-claude-implementer-2.1.337.md +43 -0
  40. package/docs/verification/2026-12-06-0.54.0.md +76 -0
  41. package/docs/verification/2026-12-06-codex-0174-reviewer-isolation.md +43 -0
  42. package/docs/verification/2026-12-06-codex-0174-reviewer-tool-call.md +34 -0
  43. package/docs/verification/2026-12-06-compat-codex-capabilities-0.174.0.md +25 -0
  44. package/docs/verification/2026-12-06-compat-pi-1.8.0.md +23 -0
  45. package/docs/verified.json +38 -29
  46. package/package.json +9 -3
  47. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  48. package/plugins/agent-hub/.mcp.json +1 -1
  49. package/plugins/agent-hub/compat.json +9 -5
  50. package/plugins/agent-hub/kimi-hook.js +892 -874
  51. package/plugins/agent-hub/relay-launcher.js +24 -0
  52. package/plugins/agent-hub/server.js +27271 -25146
  53. package/src/adapters/acp-session-model.ts +1 -1
  54. package/src/adapters/acp.ts +5 -4
  55. package/src/adapters/agy/definition.ts +1 -1
  56. package/src/adapters/agy/hooks.ts +1 -1
  57. package/src/adapters/channel-peer.ts +3 -1
  58. package/src/adapters/claude-channel-evidence.ts +26 -1
  59. package/src/adapters/claude-channel.ts +27 -30
  60. package/src/adapters/claude-connection-policy.ts +62 -0
  61. package/src/adapters/claude-relay.ts +255 -0
  62. package/src/adapters/codex-review-isolation.ts +1 -2
  63. package/src/adapters/compat.ts +28 -18
  64. package/src/adapters/definitions/native-cli-preview-pi.ts +2 -1
  65. package/src/adapters/definitions/native-config-defaults.ts +1 -1
  66. package/src/adapters/definitions/native-context.ts +1 -2
  67. package/src/adapters/definitions/native-factories.ts +4 -1
  68. package/src/adapters/definitions/native-quota.ts +1 -1
  69. package/src/adapters/definitions/native-recovery.ts +3 -1
  70. package/src/adapters/external-modules.ts +2 -2
  71. package/src/adapters/kimi-review.ts +1 -1
  72. package/src/adapters/kimi-tui-facts.ts +1 -1
  73. package/src/adapters/local-worker.ts +3 -3
  74. package/src/adapters/native-capabilities.ts +1 -1
  75. package/src/adapters/pi.ts +26 -7
  76. package/src/adapters/registry-types.ts +2 -0
  77. package/src/adapters/relay-launcher.ts +27 -0
  78. package/src/adapters/reviewer-mcp.ts +1 -1
  79. package/src/cli/agents.ts +20 -8
  80. package/src/cli/agy-mcp.ts +1 -1
  81. package/src/cli/claude-profile-hook.ts +1 -1
  82. package/src/cli/command-table.ts +1 -0
  83. package/src/cli/commands/agents.ts +18 -1
  84. package/src/cli/commands/doctor.ts +18 -4
  85. package/src/cli/commands/launch-line.ts +32 -0
  86. package/src/cli/commands/status.ts +14 -3
  87. package/src/cli/help.ts +7 -4
  88. package/src/cli/identity.ts +1 -1
  89. package/src/cli/init-roles.ts +1 -1
  90. package/src/cli/init-settings.ts +1 -1
  91. package/src/cli/launch-line-plan.ts +82 -0
  92. package/src/cli/launch-line-project.ts +13 -0
  93. package/src/cli/main.ts +10 -9
  94. package/src/cli/pi-steps-warning.ts +14 -0
  95. package/src/cli/recovery-package.ts +60 -6
  96. package/src/cli/reset.ts +1 -1
  97. package/src/cli/shell-quote.ts +1 -3
  98. package/src/cli/upgrade-interactive.ts +7 -2
  99. package/src/cli/upgrade-keep-plan.ts +47 -0
  100. package/src/cli/upgrade-restore-state.ts +1 -1
  101. package/src/cli/upgrade-runtime.ts +119 -18
  102. package/src/cli/upgrade.ts +17 -2
  103. package/src/hub/accounts.ts +8 -4
  104. package/src/hub/action-class.ts +1 -3
  105. package/src/hub/adec-triage.ts +105 -0
  106. package/src/hub/autonomy.ts +1 -1
  107. package/src/hub/board.ts +3 -27
  108. package/src/hub/bus.ts +39 -6
  109. package/src/hub/capabilities.ts +1 -1
  110. package/src/hub/channel-project-base.ts +46 -0
  111. package/src/hub/channel-project.ts +21 -46
  112. package/src/hub/config-apply.ts +1 -1
  113. package/src/hub/config-edit.ts +1 -1
  114. package/src/hub/config-tier.ts +1 -1
  115. package/src/hub/config.ts +2 -2
  116. package/src/hub/confirmation-matrix.ts +1 -1
  117. package/src/hub/control/board-messages.ts +415 -0
  118. package/src/hub/control/dashboard-messages.ts +221 -0
  119. package/src/hub/control/delivery-messages.ts +356 -0
  120. package/src/hub/control/dispatch.ts +114 -0
  121. package/src/hub/control/hub-tool-helpers.ts +243 -0
  122. package/src/hub/control/hub-tools.ts +147 -0
  123. package/src/hub/control/native-messages.ts +665 -0
  124. package/src/hub/control/operations-messages.ts +269 -0
  125. package/src/hub/control/peer-messages.ts +126 -0
  126. package/src/hub/control/recovery-messages.ts +391 -0
  127. package/src/hub/control/recovery-operation.ts +480 -0
  128. package/src/hub/control/scope.ts +460 -0
  129. package/src/hub/control/sdlc-messages.ts +373 -0
  130. package/src/hub/control/task-ops-more.ts +245 -0
  131. package/src/hub/control/task-ops.ts +553 -0
  132. package/src/hub/control/ui-actions.ts +241 -0
  133. package/src/hub/control-write-trace.ts +1 -4
  134. package/src/hub/daemon.ts +485 -4324
  135. package/src/hub/delivery-hints.ts +2 -0
  136. package/src/hub/delivery-journal.ts +17 -6
  137. package/src/hub/events.ts +2 -1
  138. package/src/hub/execution-reference.ts +1 -1
  139. package/src/hub/host.ts +41 -9
  140. package/src/hub/hub-tools.ts +3 -4
  141. package/src/hub/invocations.ts +1 -1
  142. package/src/hub/lifecycle.ts +4 -3
  143. package/src/hub/mcp-endpoint-serve.ts +4 -3
  144. package/src/hub/mcp-endpoint.ts +15 -6
  145. package/src/hub/memory-profile-check.ts +1 -1
  146. package/src/hub/no-writes.ts +1 -1
  147. package/src/hub/peers.ts +2 -0
  148. package/src/hub/pi-exit-policy.ts +27 -0
  149. package/src/hub/progress.ts +1 -1
  150. package/src/hub/project-runtime-state.ts +17 -4
  151. package/src/hub/project-runtime.ts +3 -1
  152. package/src/hub/protocol-window.ts +1 -1
  153. package/src/hub/recovery-continuity.ts +3 -3
  154. package/src/hub/recovery-kept-roster.ts +50 -0
  155. package/src/hub/review-anchor.ts +13 -181
  156. package/src/hub/review-brief.ts +78 -28
  157. package/src/hub/review-findings.ts +15 -193
  158. package/src/hub/review-ledger.ts +162 -0
  159. package/src/hub/review-material.ts +3 -3
  160. package/src/hub/reviewer-pool.ts +4 -2
  161. package/src/hub/roadmap-issue-states.ts +65 -14
  162. package/src/hub/roadmap-sync.ts +39 -14
  163. package/src/hub/routing.ts +9 -0
  164. package/src/hub/runtime-capture-prune.ts +8 -2
  165. package/src/hub/runtime-package-assets.ts +3 -0
  166. package/src/hub/sdlc-release-policy.ts +1 -2
  167. package/src/hub/settings.ts +1 -1
  168. package/src/hub/spec-ack-tool.ts +4 -0
  169. package/src/hub/spec-report-history.ts +36 -0
  170. package/src/hub/specs.ts +1 -4
  171. package/src/hub/supervision.ts +33 -6
  172. package/src/hub/tasks-audit.ts +390 -0
  173. package/src/hub/tasks-backlog.ts +522 -0
  174. package/src/hub/tasks-handoff.ts +208 -0
  175. package/src/hub/tasks-release.ts +257 -0
  176. package/src/hub/tasks-roadmap.ts +17 -3
  177. package/src/hub/tasks-specs.ts +672 -0
  178. package/src/hub/tasks-types.ts +334 -0
  179. package/src/hub/tasks.ts +286 -1961
  180. package/src/hub/upgrade-session-contract.ts +11 -0
  181. package/src/local/probe-sandbox.ts +1 -2
  182. package/src/local/probe-workspace.ts +1 -1
  183. package/src/models/route/config.ts +4 -4
  184. package/src/models/route/decision.ts +18 -10
  185. package/src/models/route/observation-signals.ts +1 -2
  186. package/src/models/route/runtime.ts +8 -5
  187. package/src/npm-artifact.ts +76 -0
  188. package/src/omniroute/client.ts +6 -0
  189. package/src/pi/extension.ts +5 -2
  190. package/src/pi/install.ts +77 -0
  191. package/src/pi/pin.ts +49 -0
  192. package/src/primitives.ts +14 -0
  193. package/src/version.ts +2 -0
  194. package/templates/adec/README.md +10 -6
  195. package/templates/config.json +1 -1
  196. package/templates/specs.block.md +1 -0
@@ -0,0 +1,665 @@
1
+ // #1830 S2d: moved onMessage bodies and their private helpers. The daemon owns all state.
2
+ import { isWsPeer } from "../../adapters/channel-peer.ts";
3
+ import { isLocalPeer } from "../../adapters/local-worker.ts";
4
+ import { isFixedBuiltinDefinition } from "../../adapters/registry.ts";
5
+ import { projectFileTool, scopedWriteBlocked } from "../../cli/facts-hook.ts";
6
+ import { classifyPeerCommand, cliCommandLabel } from "../../cli/identity.ts";
7
+ import { shellQuote } from "../../cli/terminal-recovery.ts";
8
+ import { ensureMlx } from "../../models/mlx.ts";
9
+ import { processLiveness } from "../../pi/process-signature.ts";
10
+ import { claudeActionClasses } from "../action-enforce.ts";
11
+ import { isClosedTaskState } from "../board.ts";
12
+ import { personEnv } from "../child-process.ts";
13
+ import { readClaudeLaunchProof } from "../claude-launch-proof.ts";
14
+ import { claudeStateFile } from "../claude-state.ts";
15
+ import { USER } from "../envelope.ts";
16
+ import { SCREEN_MAX_BYTES, SCREEN_TIMEOUT_MS, screenPii } from "../inference.ts";
17
+ import { isPlannerOnly } from "../instances.ts";
18
+ import { INSTRUCTION_CHILD_TIMEOUT_MS, exactForm, parseExactInstruction } from "../instructed-exact.ts";
19
+ import { intentForm, intentRefusal, literalInstructionIds } from "../instructed-intent.ts";
20
+ import { instructedRuntimeAllowed } from "../instructed-runtime.ts";
21
+ import { MAX_PROMPT_BYTES } from "../instruction-receipt.ts";
22
+ import { reviewCaptureExcluded } from "../memory-policy.ts";
23
+ import { ClaudeTodoSource, readAiTitle } from "../peer-doing.ts";
24
+ import { normalizeClaudeObservation } from "../progress.ts";
25
+ import { projectChildEnv, realPath } from "../project.ts";
26
+ import { Registry } from "../registry.ts";
27
+ import { readClaudeTranscriptCompletion, waitForClaudeCompletion } from "../usage.ts";
28
+ import { createHash } from "node:crypto";
29
+ import { chmodSync, closeSync, openSync, readSync, renameSync, statSync, writeFileSync } from "node:fs";
30
+ import { homedir } from "node:os";
31
+ import { basename, isAbsolute, join, resolve } from "node:path";
32
+ import type { TaskAttribution } from "../attribution.ts";
33
+ import type { Sock } from "../daemon.ts";
34
+ import type { PeerId } from "../envelope.ts";
35
+ import type { ExactForm, InstructedExecution } from "../instructed-exact.ts";
36
+ import type { ControlMessage, DaemonScope } from "./scope.ts";
37
+
38
+ const tallyHook = (scope: DaemonScope, peer: PeerId, callStarted: number, startedMs: unknown) => {
39
+ const st = scope.hookStats.get(peer) ?? { n: 0, startupMs: 0, hubMs: 0, maxStartupMs: 0 };
40
+ const startup = typeof startedMs === "number" && Number.isFinite(startedMs) ? Math.max(0, startedMs) : 0;
41
+ scope.hookStats.set(peer, { n: st.n + 1, startupMs: st.startupMs + startup, hubMs: st.hubMs + (performance.now() - callStarted), maxStartupMs: Math.max(st.maxStartupMs, startup) });
42
+ };
43
+
44
+ const emitHookStats = (scope: DaemonScope, peer: PeerId) => {
45
+ const st = scope.hookStats.get(peer);
46
+ if (!st) return;
47
+ scope.event({ type: "hook_stats", peer, n: st.n, startupMs: Math.round(st.startupMs), hubMs: Math.round(st.hubMs), maxStartupMs: Math.round(st.maxStartupMs) });
48
+ scope.hookStats.delete(peer);
49
+ };
50
+
51
+ const effectiveInstructionMode = (scope: DaemonScope) => scope.instructionReceipts.mode();
52
+
53
+ async function launchInstructed(scope: DaemonScope, argv: string[], binding: InstructedExecution): Promise<Record<string, unknown>> {
54
+ binding.current();
55
+ if (!scope.instructedRuntime || !instructedRuntimeReady(scope)) return { ok: false, error: "instructed execution requires an installed hub outside project and peer write roots; install the hub package and restart this session with ahub claude" };
56
+ const client: Sock["data"] = { authed: false, instructed: binding };
57
+ let open = true;
58
+ let child: ReturnType<typeof Bun.spawn>;
59
+ const inherited = { data: client, get readyState() { return open ? WebSocket.OPEN : WebSocket.CLOSED; }, send: (text: string) => child.send(JSON.parse(text)), close: () => { open = false; child.disconnect(); }, getBufferedAmount: () => 0 } as unknown as Sock;
60
+ child = Bun.spawn({ cmd: [scope.instructedRuntime.bun, join(scope.instructedRuntime.root, "src/cli/main.js"), ...argv],
61
+ cwd: scope.opts.cwd, env: { ...personEnv(scope.ctx.env), AGENTHUB_INSTRUCTED_IPC: "1", ...projectChildEnv(scope.ctx) },
62
+ stdin: "ignore", stdout: "pipe", stderr: "pipe", serialization: "json",
63
+ ipc(message) {
64
+ try {
65
+ if (!open || !message || typeof message !== "object" || Buffer.byteLength(JSON.stringify(message)) > 1024 * 1024) throw new Error("invalid instruction control message");
66
+ scope.onControlMessage(inherited, message);
67
+ } catch { open = false; child.disconnect(); }
68
+ },
69
+ });
70
+ let output = Buffer.alloc(0), overflow = false, timedOut = false;
71
+ const readers = [(child.stdout as ReadableStream<Uint8Array>).getReader(), (child.stderr as ReadableStream<Uint8Array>).getReader()];
72
+ const cancel = () => { for (const reader of readers) void reader.cancel().catch(() => {}); };
73
+ const drain = async (reader: (typeof readers)[number]) => {
74
+ try {
75
+ for (;;) {
76
+ const part = await reader.read(); if (part.done) break;
77
+ const bytes = Buffer.from(part.value);
78
+ if (output.length + bytes.length > 64 * 1024) { overflow = true; child.kill(); cancel(); break; }
79
+ output = Buffer.concat([output, bytes]);
80
+ }
81
+ } finally { reader.releaseLock(); }
82
+ };
83
+ const timer = setTimeout(() => { timedOut = true; child.kill("SIGKILL"); cancel(); }, INSTRUCTION_CHILD_TIMEOUT_MS);
84
+ let code: number;
85
+ try { [code] = await Promise.all([child.exited, ...readers.map(drain)]); }
86
+ finally { clearTimeout(timer); open = false; client.closed = true; child.disconnect(); }
87
+ if (timedOut) return { ok: false, error: "instruction timed out; inspect the target before retrying because the effect may have occurred" };
88
+ return overflow ? { ok: false, error: "instruction output exceeded its limit; inspect the target before retrying because the effect may have occurred" } : { ok: code === 0, exitCode: code, output: output.toString("utf8") };
89
+ }
90
+
91
+ /** Claude's transcript for this session: the one the status line reported, or the hook's own, inside Claude's projects. */
92
+ const claudeTranscript = (scope: DaemonScope, sessionId: string | undefined, fromHook: unknown, peer: string): string | undefined => {
93
+ if (scope.definitionOf(peer)?.transport !== "claude-channel") return undefined; // #624: no Claude transcript for another kind
94
+ const reported = scope.claudeSession(peer);
95
+ if (reported.transcriptPath && (!sessionId || reported.sessionId === sessionId)) return reported.transcriptPath;
96
+ if (!sessionId || typeof fromHook !== "string" || !isAbsolute(fromHook) || basename(fromHook) !== `${sessionId}.jsonl`) return undefined;
97
+ try {
98
+ const projects = realPath(join(process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), ".claude"), "projects"));
99
+ const real = realPath(fromHook);
100
+ return real.startsWith(`${projects}/`) && statSync(real).isFile() ? real : undefined;
101
+ } catch { return undefined; }
102
+ };
103
+
104
+ const observeClaudeDoing = (scope: DaemonScope, peer: PeerId, session: string, transcript: string | undefined, tool: string, input: Record<string, unknown>) => {
105
+ let source = scope.claudeDoing.get(peer);
106
+ if (source?.session !== session) {
107
+ scope.observeDoing(peer, "reset");
108
+ scope.claudeDoing.set(peer, source = { session, cursor: { path: "", offset: 0, skip: false }, todos: new ClaudeTodoSource() });
109
+ }
110
+ if (transcript) {
111
+ // ponytail: one bounded read per hook call, so a long transcript first seen mid-session catches up over several calls.
112
+ if (source.cursor.path !== transcript) source.cursor = { path: transcript, offset: 0, skip: false };
113
+ const title = readAiTitle(source.cursor);
114
+ if (title !== undefined) scope.observeDoing(peer, "title", title);
115
+ }
116
+ const item = tool ? source.todos.item(tool, input, subject => scope.contextPii(peer) || !scope.tasks.publicMetadataText(subject)) : undefined;
117
+ if (item !== undefined) scope.observeDoing(peer, "todo", item?.text, item?.private === true);
118
+ };
119
+
120
+ const readbacks = (scope: DaemonScope, peer: PeerId, transcript: string | undefined) => {
121
+ const pending = scope.factsFor(peer).pending(peer).filter((o) => o.toolUseId);
122
+ if (!pending.length || !transcript) return;
123
+ readTranscript(scope, transcript);
124
+ for (const o of pending) if (scope.injected.get(o.toolUseId!)?.includes(`[${o.id}]`)) scope.acked(peer, o.id, "hook");
125
+ };
126
+
127
+ function instructedRuntimeReady(scope: DaemonScope): boolean {
128
+ if (!scope.instructedRuntime) return false;
129
+ let registry: Registry | undefined;
130
+ try {
131
+ registry = new Registry();
132
+ const roots = [scope.opts.cwd, ...registry.list().map(project => project.root), ...scope.executionRoots.values(), ...Object.values(scope.declarations).flatMap(instance => instance.worktree ? [resolve(scope.opts.cwd, instance.worktree)] : [])];
133
+ return instructedRuntimeAllowed(scope.instructedRuntime.root, roots);
134
+ } catch { return false; }
135
+ finally { registry?.close(); }
136
+ }
137
+
138
+ const readTranscript = (scope: DaemonScope, path: string) => {
139
+ try {
140
+ if (scope.transcriptRead.path !== path) scope.transcriptRead = { path, offset: 0 };
141
+ const st = statSync(path);
142
+ if (st.size < scope.transcriptRead.offset) scope.transcriptRead.offset = 0;
143
+ if (st.size === scope.transcriptRead.offset) return;
144
+ const fd = openSync(path, "r");
145
+ try {
146
+ const start = Math.max(scope.transcriptRead.offset, st.size - 4 * 1024 * 1024);
147
+ const buf = Buffer.alloc(st.size - start);
148
+ readSync(fd, buf, 0, buf.length, start);
149
+ // Lines end at a newline byte: decoding first would misplace the offset after a split multi-byte character.
150
+ const end = buf.lastIndexOf(10);
151
+ if (end === -1) return;
152
+ const lines = buf.subarray(0, end).toString("utf8").split("\n");
153
+ if (start > scope.transcriptRead.offset) lines.shift(); // the window began inside a line
154
+ scope.transcriptRead.offset = start + end + 1;
155
+ for (const line of lines) {
156
+ if (!line.includes("hook_additional_context")) continue;
157
+ try {
158
+ const a = JSON.parse(line)?.attachment;
159
+ if (a?.type !== "hook_additional_context" || typeof a.toolUseID !== "string") continue;
160
+ scope.injected.set(a.toolUseID, Array.isArray(a.content) ? a.content.join("\n") : String(a.content ?? ""));
161
+ if (scope.injected.size > 512) scope.injected.delete(scope.injected.keys().next().value as string);
162
+ } catch { /* a partial or foreign line */ }
163
+ }
164
+ } finally { closeSync(fd); }
165
+ } catch { /* no transcript yet: no readback */ }
166
+ };
167
+
168
+ export function nativeHookLaunchMessage(scope: DaemonScope, m: ControlMessage): void {
169
+ const { sock, c, msg, reply } = m;
170
+ if (c.role !== "console" || typeof msg.peer !== "string" || !scope.definitionOf(msg.peer)?.hooks?.factsHook) return void reply({ ok: false, error: "managed native launch requires the person and a supported hook adapter" });
171
+ if (msg.op === "end") {
172
+ const launch = scope.nativeHookLaunches.get(msg.peer, msg.launchId);
173
+ if (!launch) return void reply({ ok: false });
174
+ const run = scope.runs.get(msg.peer);
175
+ if (run) {
176
+ if (scope.budget.record(msg.peer)) scope.completionStore.dropRun(run.runTurn);
177
+ else scope.completionDone(msg.peer, run, "interrupted");
178
+ scope.runs.close(msg.peer);
179
+ }
180
+ return void reply({ ok: scope.nativeHookLaunches.end(msg.peer, msg.launchId) });
181
+ }
182
+ if (scope.recoveryActive() || scope.stopping) return void reply({ ok: false, error: "recovery or shutdown is holding native launches" });
183
+ if (!scope.membershipAllowed(msg.peer)) return void reply({ ok: false, error: "peer is off roster" });
184
+ if (msg.op !== "begin") return void reply({ ok: false, error: "unknown native launch operation" });
185
+ if (msg.nativeHome !== undefined && (typeof msg.nativeHome !== "string" || !isAbsolute(msg.nativeHome) || msg.nativeHome.length > 4096 || /[\u0000-\u001f\u007f]/.test(msg.nativeHome))) return void reply({ ok: false, error: "native home must be an absolute control-free path" });
186
+ const owner = scope.bus.peers.get(msg.peer);
187
+ if (owner && owner.state !== "offline") return void reply({ ok: false, error: "native peer is already attached; end it in its terminal first" });
188
+ try { return void reply({ ok: true, launchId: scope.nativeHookLaunches.begin(msg.peer, sock, typeof msg.nativeHome === "string" ? msg.nativeHome : undefined).id, instanceId: scope.instanceId }); }
189
+ catch (error) { return void reply({ ok: false, error: (error as Error).message }); }
190
+ }
191
+
192
+ export function nativeFactsMessage(scope: DaemonScope, m: ControlMessage): void {
193
+ const { c, msg, reply } = m;
194
+ const peer = c.peer, port = peer ? scope.definitionOf(peer)?.hooks?.factsHook : undefined;
195
+ if (!peer || c.role !== "tools" || !port || msg.nativeInstanceId !== scope.instanceId) return void reply({ ok: false });
196
+ const launch = scope.nativeHookLaunches.get(peer, msg.nativeLaunchId);
197
+ const native = typeof msg.event === "string" ? port.decode(msg.event, msg.payload) : undefined;
198
+ if (!launch || !native || !native.workspacePaths.every(root => { try { return realPath(root) === realPath(scope.opts.cwd); } catch { return false; } })) return void reply({ ok: false });
199
+ if (launch.home && native.transcriptPath !== join(launch.home, "session_index.jsonl")) return void reply({ ok: false });
200
+ if (launch.session && launch.session !== native.sessionId) return void reply({ ok: false });
201
+ launch.session = native.sessionId;
202
+ const owner = scope.bus.peers.get(peer);
203
+ if (!isWsPeer(owner) || owner.state === "offline" && !owner.claiming) return void reply({ ok: false });
204
+ if (launch.generation && launch.generation !== owner.sessionGeneration) return void reply({ ok: false });
205
+ launch.generation = owner.sessionGeneration;
206
+ launch.transcript = native.transcriptPath;
207
+ if (native.model) scope.hookModels.set(peer, native.model);
208
+ const callStarted = performance.now();
209
+ const tally = () => tallyHook(scope, peer, callStarted, msg.startedMs);
210
+ const current = () => !scope.stopping && scope.nativeHookLaunches.get(peer, msg.nativeLaunchId) === launch && scope.bus.peers.get(peer) === owner && owner.sessionGeneration === launch.generation && owner.state !== "offline";
211
+ // Preserve the start baseline at observation, even if native output is flushed before recall allows attach.
212
+ // Skip transcript I/O on PostToolUse, PostInvocation, Stop, and active-turn PreToolUse with no pending fact offers (#1280).
213
+ const needsBaseline = (native.event === "PreInvocation" || native.event === "PreToolUse") && (!launch.active || native.event === "PreInvocation" && native.invocation === 0)
214
+ || native.event === "TurnStarted" || native.event === "Stop" || native.event === "StopFailure" || native.event === "Interrupt";
215
+ const needsAck = scope.factsOn() && (native.event === "SessionStart" || native.event === "PreInvocation" || native.event === "PreToolUse" && scope.factsFor(peer).pending(peer).length > 0);
216
+ const since = launch.transcriptPath === native.transcriptPath && launch.transcriptOffset !== undefined ? { sinceOffset: launch.transcriptOffset } : {};
217
+ const readback: ReturnType<typeof port.read> = needsBaseline
218
+ ? port.read(native.sessionId, native.transcriptPath, since)
219
+ : needsAck
220
+ ? port.read(native.sessionId, native.transcriptPath, { completion: false, ...since })
221
+ : { factIds: [] };
222
+ // ponytail: an unacknowledged fact row followed by >4 MiB of output before the next readback hits the 4 MiB lookback cap in readAgyTranscript.
223
+ const acknowledge = (read: ReturnType<typeof port.read>, turnCtx?: { hubTurnId?: string; baseline: number; attribution: TaskAttribution }) => {
224
+ for (const u of read.usage ?? []) {
225
+ if (scope.agyNativeUsageSeen.has(u.id)) continue;
226
+ scope.agyNativeUsageSeen.add(u.id);
227
+ const producedByTurn = !!turnCtx && u.index > turnCtx.baseline;
228
+ const attr: TaskAttribution = producedByTurn ? turnCtx.attribution : { attribution: "unattributed" };
229
+ if (u.totalTokens > 0) {
230
+ if (scope.noQuotaPeer(peer)) scope.hubTokenWindow(peer).add(Date.now(), Math.round(u.totalTokens));
231
+ const supervisionTurn = scope.supervisionTurns.get(peer);
232
+ if (producedByTurn && supervisionTurn && turnCtx.hubTurnId && supervisionTurn.id === turnCtx.hubTurnId) {
233
+ supervisionTurn.tokens = (supervisionTurn.tokens ?? 0) + u.totalTokens;
234
+ }
235
+ scope.event({ type: "tokens", peer, n: u.totalTokens, ...attr });
236
+ const openTurn = scope.turns.get(peer);
237
+ if (producedByTurn && openTurn && turnCtx.hubTurnId && openTurn.id === turnCtx.hubTurnId) {
238
+ openTurn.tokens += u.totalTokens;
239
+ }
240
+ }
241
+ scope.event({ type: "usage", peer, source: "agy_transcript", id: u.id, inputTokens: u.inputTokens, outputTokens: u.outputTokens, cacheReadTokens: u.cacheReadTokens, totalTokens: u.totalTokens, ...attr, ...(u.at ? { measuredAt: u.at } : {}) });
242
+ }
243
+ if (scope.factsOn()) {
244
+ scope.factSession(peer, native.sessionId);
245
+ for (const id of read.factIds) scope.acked(peer, id, "native-hook");
246
+ }
247
+ if (read.size !== undefined && read.scannedFrom !== undefined) {
248
+ const prev = launch.transcriptPath === native.transcriptPath ? (launch.transcriptOffset ?? 0) : 0;
249
+ if (read.scannedFrom <= prev) {
250
+ launch.transcriptPath = native.transcriptPath;
251
+ launch.transcriptOffset = read.size;
252
+ }
253
+ }
254
+ };
255
+ const apply = () => {
256
+ if (!current()) return void reply({ ok: false });
257
+ if (native.event === "TurnStarted") {
258
+ const started = readback.started;
259
+ if (!started) return void reply({ ok: false });
260
+ if (launch.active && launch.turn === started.id) return void reply({ ok: true });
261
+ if (readback.completion && readback.completion.index >= started.index) return void reply({ ok: true });
262
+ launch.active = true; launch.turn = started.id; launch.baseline = started.index - 1;
263
+ scope.pendingNativePerson.delete(peer);
264
+ if (started.origin === "user") scope.pendingNativePerson.add(peer);
265
+ scope.activeAt.set(peer, Date.now()); owner.nativeStarted(native.sessionId);
266
+ }
267
+ owner.bindNativeSession(native.sessionId);
268
+ const startsTurn = (native.event === "PreInvocation" || native.event === "PreToolUse") && (!launch.active || native.event === "PreInvocation" && native.invocation === 0);
269
+ if (native.event === "PreInvocation" || native.event === "PreToolUse") {
270
+ if (startsTurn) {
271
+ // Credit any leftover rows read at turn start to the preceding turn that produced them, never the new turn.
272
+ acknowledge(readback, scope.agyTurnContext.get(launch));
273
+ launch.active = true; launch.turn = crypto.randomUUID(); launch.baseline = readback.completion?.index ?? -1;
274
+ scope.activeAt.set(peer, Date.now()); owner.nativeStarted(native.sessionId);
275
+ scope.agyTurnContext.set(launch, { hubTurnId: scope.turns.get(peer)?.id, baseline: launch.baseline, attribution: scope.taskAttribution(peer) });
276
+ } else {
277
+ scope.activeAt.set(peer, Date.now()); owner.nativeStarted(native.sessionId);
278
+ const activeCtx = { hubTurnId: scope.turns.get(peer)?.id ?? scope.agyTurnContext.get(launch)?.hubTurnId, baseline: launch.baseline ?? -1, attribution: scope.taskAttribution(peer) };
279
+ scope.agyTurnContext.set(launch, activeCtx);
280
+ acknowledge(readback, activeCtx);
281
+ }
282
+ } else if (native.event !== "Stop") {
283
+ const activeCtx = launch.active ? { hubTurnId: scope.turns.get(peer)?.id ?? scope.agyTurnContext.get(launch)?.hubTurnId, baseline: launch.baseline ?? -1, attribution: scope.taskAttribution(peer) } : scope.agyTurnContext.get(launch);
284
+ if (launch.active && activeCtx) scope.agyTurnContext.set(launch, activeCtx);
285
+ acknowledge(readback, activeCtx);
286
+ }
287
+ const stopCtx = { hubTurnId: scope.turns.get(peer)?.id ?? scope.agyTurnContext.get(launch)?.hubTurnId, baseline: launch.baseline ?? -1, attribution: scope.taskAttribution(peer) };
288
+ scope.agyTurnContext.set(launch, stopCtx);
289
+ if (native.event === "Stop" && native.terminationReason !== undefined) {
290
+ if (!launch.active || native.fullyIdle !== true) return void reply({ ok: false });
291
+ const terminalReason = ({ USER_CANCELED: "user_canceled", ERROR: "error", MAX_INVOCATIONS: "max_invocations", MAX_FORCED_INVOCATIONS: "max_forced_invocations", MAX_TOKEN_BUDGET_EXCEEDED: "max_token_budget_exceeded", TERMINAL_STEP_TYPE: "terminal_step_type", TERMINAL_CUSTOM_HOOK: "terminal_custom_hook" } as const)[native.terminationReason];
292
+ if (terminalReason) {
293
+ acknowledge(port.read(native.sessionId, native.transcriptPath, { completion: false, ...since }), stopCtx);
294
+ launch.active = false; scope.turnEnded.set(peer, Date.now()); scope.tasks.cohorts.turnEnded(peer);
295
+ tally(); emitHookStats(scope, peer);
296
+ scope.event({ type: "native_turn_end", peer, reason: terminalReason }); owner.nativeStopped(native.sessionId);
297
+ // #1054: pull-only agy opens no run (`settles(peer)` is false); if a future native-hook peer does, settle an open run by its closed reason.
298
+ try {
299
+ const run = scope.runs.get(peer);
300
+ if (run) {
301
+ if (terminalReason === "user_canceled") { scope.completionDone(peer, run, "interrupted"); scope.runs.close(peer); }
302
+ else { scope.runs.note(peer, terminalReason === "error" || terminalReason === "terminal_step_type" || terminalReason === "terminal_custom_hook" ? { failed: true } : { limit: true }); scope.runs.signalled(peer); scope.settleCheck(peer); }
303
+ }
304
+ } catch { scope.log(`completion settle for ${peer} failed`); }
305
+ return void reply({ ok: true });
306
+ }
307
+ if (native.terminationReason !== "NO_TOOL_CALL") return void reply({ ok: false });
308
+ tally();
309
+ }
310
+ if (native.event === "Stop" || native.event === "StopFailure" || native.event === "Interrupt") {
311
+ if (!launch.active || native.event === "Stop" && native.terminationReason !== undefined && native.fullyIdle !== true) return void reply({ ok: false });
312
+ // A hook is only the candidate. The final native turn and prompt rows, correlated by id and reason, are the completion evidence.
313
+ const turn = launch.turn, baseline = launch.baseline ?? -1, expected = native.event === "StopFailure" ? "failed" : native.event === "Interrupt" ? "cancelled" : "completed";
314
+ reply({ ok: true, pending: true });
315
+ void (async () => {
316
+ const deadline = Date.now() + 2000;
317
+ let delay = 5;
318
+ let lastStat: { size: number; mtimeMs: number } | undefined;
319
+ while (current() && launch.active && launch.turn === turn) {
320
+ const pollSince = launch.transcriptPath === native.transcriptPath && launch.transcriptOffset !== undefined ? { sinceOffset: launch.transcriptOffset } : {};
321
+ const polled = port.read(native.sessionId, native.transcriptPath, { ...(lastStat ? { unchanged: lastStat } : {}), ...pollSince });
322
+ if (polled.size !== undefined && polled.mtimeMs !== undefined) lastStat = { size: polled.size, mtimeMs: polled.mtimeMs };
323
+ acknowledge(polled, stopCtx);
324
+ const completion = polled.completion;
325
+ if (completion && completion.index > baseline && completion.id !== launch.completed && (completion.reason ?? "completed") === expected) {
326
+ scope.completeNativeTurn(peer, launch, completion);
327
+ emitHookStats(scope, peer);
328
+ return;
329
+ }
330
+ if (Date.now() >= deadline) { scope.settleCheck(peer); emitHookStats(scope, peer); scope.notify(`${peer}: native completion could not be verified; it stays busy until a verified turn end or detach`); return; }
331
+ await Bun.sleep(delay); delay = Math.min(50, delay * 2);
332
+ }
333
+ })().catch(() => scope.log("managed native completion unavailable"));
334
+ return;
335
+ }
336
+ if (native.event === "TaskStarted") scope.activeAt.set(peer, Date.now());
337
+ if (native.event === "TaskStarted" || native.event === "Notification") { scope.nativeBackgroundBackoff.delete(peer); scope.settleCheck(peer); }
338
+ queueMicrotask(tally);
339
+ const offeredFacts = scope.factsOn() && (native.event === "PreInvocation" || native.event === "SessionStart") ? scope.offerFor(peer, native.toolUseId ?? `${native.sessionId}:invocation`) : undefined;
340
+ // #1280 P2: agy is pull-only, so a model boundary is the one place the hub can tell it mail waits. Counts only, never a body or sender.
341
+ const modelBoundary = native.event === "PreInvocation" || native.event === "SessionStart";
342
+ const waiting = scope.bus.queued(peer), important = scope.bus.queuedImportant(peer);
343
+ const inboxHint = modelBoundary && waiting ? `[agent-hub: ${waiting} message(s) waiting${important ? ` (${important} important)` : ""}; call hub_inbox]` : undefined;
344
+ const offered = offeredFacts || inboxHint ? { ...(offeredFacts ?? {}), text: [offeredFacts?.text, inboxHint].filter(Boolean).join("\n") } : undefined;
345
+ // The decoded native read (agy view_file or read_file, as `Read`) is a peer fact: its target is observed before it runs and the
346
+ // view moves after it. Nothing is offered here: agy's hook encodes an offer only on SessionStart/PreInvocation.
347
+ if (scope.factsOn() && native.event === "PreToolUse") scope.factsFor(peer).preTool(peer, native.toolUseId, native.tool, native.input);
348
+ if (scope.factsOn() && native.event === "PostToolUse") scope.factsFor(peer).postTool(peer, native.toolUseId, native.tool, native.input);
349
+ return void reply({ ok: true, ...(offered ? { text: offered.text } : {}) });
350
+ };
351
+ if (owner.claiming) {
352
+ void owner.waitForAttach(launch.generation).then(attached => {
353
+ if (attached) apply(); else reply({ ok: false });
354
+ }).catch(() => { scope.log("managed native observation unavailable"); reply({ ok: false }); });
355
+ return;
356
+ }
357
+ return apply();
358
+ }
359
+
360
+ export function instructionExecuteMessage(scope: DaemonScope, m: ControlMessage): void {
361
+ const { sock, c, msg, reply } = m;
362
+ if (c.role !== "tools" || !c.peer || c.toolsOwner || c.externalOwner || Object.keys(msg).some(key => !["t", "rid", "session", "argv"].includes(key)) || typeof msg.session !== "string" || msg.argv !== undefined && (!Array.isArray(msg.argv) || msg.argv.some((word: unknown) => typeof word !== "string") || Buffer.byteLength(JSON.stringify(msg.argv)) > MAX_PROMPT_BYTES)) return void reply({ ok: false, error: "instruction unavailable" });
363
+ const peer = c.peer, session = msg.session, socket = sock;
364
+ let initialMode: ReturnType<typeof effectiveInstructionMode>;
365
+ try { initialMode = effectiveInstructionMode(scope); }
366
+ catch { return void reply({ ok: false, error: "instructed.mode is unavailable; inspect hub status and run the command in a terminal" }); }
367
+ const initialSession = scope.claudeSession(peer), owner = scope.claudeLaunchProof.owner(peer), generation = owner?.sessionGeneration;
368
+ const launch = readClaudeLaunchProof(scope.opts.stateDir, peer, scope.instanceId);
369
+ class InstructionRefusal extends Error {}
370
+ const sessionRefusal = `this Claude session changed or was not started by ahub claude. The person starts a managed session in this project:\n\n\`\`\`sh\ncd ${shellQuote(scope.opts.cwd)} && ahub claude\n\`\`\`\n\nSuccess: a new managed Claude session starts; type the instruction again there.`;
371
+ const requestedMode = msg.argv === undefined ? "exact" : "intent";
372
+ const modeRefusal = `instructed.mode is off. The person turns it on in a terminal:\n\n\`\`\`sh\ncd ${shellQuote(scope.opts.cwd)} && ahub settings set instructed.mode ${requestedMode}\n\`\`\`\n\nSuccess: the command reports witness ${requestedMode}; type the instruction again.`;
373
+ const receiptRefusal = "no usable instruction receipt; type the /agent-hub:ahub command again. A receipt is used once and expires after 10 minutes.";
374
+ const runtimeRefusal = "the installed hub runtime is unavailable or inside a project or peer write root; install the hub package and start a new managed session with ahub claude";
375
+ const current = () => {
376
+ const observed = scope.claudeSession(peer), latest = readClaudeLaunchProof(scope.opts.stateDir, peer, scope.instanceId);
377
+ const checks = { socket: socket.readyState === WebSocket.OPEN && socket.data === c && !c.closed && c.role === "tools" && c.peer === peer, lifecycle: !scope.stopping && !scope.recoveryActive() && !scope.bus.isRecoveryHeld, policy: scope.membershipAllowed(peer) && !scope.readOnlyPeer(peer) && !scope.turns.get(peer)?.private && !scope.contextPii(peer) && !scope.board.peerTaskSignals(peer).some(task => !isClosedTaskState(task.state) && (task.signals.includes("pii") || task.signals.includes("pii_path"))), owner: !!owner && owner.attached && owner.state !== "offline" && !owner.claiming && scope.bus.peers.get(peer) === owner && !!generation && owner.sessionGeneration === generation, session: observed.sessionId === session && observed.sessionId === initialSession.sessionId && observed.transcriptPath === initialSession.transcriptPath && observed.launchId === initialSession.launchId, launch: !!launch?.privateRecord && !!launch.launcherPid && !!launch.launcherSignature && launch.launchId === observed.launchId && !!latest?.privateRecord && latest.launchId === launch.launchId && latest.launcherPid === launch.launcherPid && latest.launcherSignature === launch.launcherSignature && processLiveness(launch.launcherPid, launch.launcherSignature) === "live", mode: initialMode !== "off" && effectiveInstructionMode(scope) === initialMode };
378
+ if (!checks.mode) throw new InstructionRefusal(effectiveInstructionMode(scope) === "off" ? modeRefusal : "instructed.mode changed; type the instruction again in the current mode");
379
+ if (!checks.lifecycle) throw new InstructionRefusal("the hub is stopping or recovering; retry after ahub status shows it running");
380
+ if (!checks.policy) throw new InstructionRefusal("a private turn or private task is active for this peer, or its access is restricted; run the command in a terminal");
381
+ if (!checks.socket || !checks.owner || !checks.session || !checks.launch) throw new InstructionRefusal(sessionRefusal);
382
+ };
383
+ void (async () => {
384
+ try {
385
+ if (!launch?.privateRecord || !launch.launcherPid || !launch.launcherSignature || processLiveness(launch.launcherPid, launch.launcherSignature) !== "live") return { ok: false, error: `this Claude session was not started by ahub claude. The person starts a managed session in this project:\n\n\`\`\`sh\ncd ${shellQuote(scope.opts.cwd)} && ahub claude\n\`\`\`\n\nSuccess: a new Claude session starts under the hub; type the instruction again there.` };
386
+ if (!initialSession.sessionId || !initialSession.transcriptPath) return { ok: false, error: "no session evidence for this Claude session yet; send one ordinary prompt in this session, then type the /agent-hub:ahub command again" };
387
+ current();
388
+ if (!instructedRuntimeReady(scope)) return { ok: false, error: `the loaded hub runtime is inside a project or peer write root, or its location is unknown. The person installs the hub package before restarting the session:\n\n\`\`\`sh\ncd ${shellQuote(scope.opts.cwd)} && bun add -g @staix/agent-hub\n\`\`\`\n\nSuccess: the package is installed globally. The person then starts the managed session:\n\n\`\`\`sh\ncd ${shellQuote(scope.opts.cwd)} && ahub claude\n\`\`\`\n\nSuccess: the installed hub starts Claude; type the instruction again.` };
389
+ if (initialMode === "exact" && msg.argv !== undefined) return { ok: false, error: "exact mode takes no agent-selected command; type the exact /agent-hub:ahub run command again" };
390
+ const receipt = await (initialMode === "intent" ? scope.instructionReceipts.forPeer(peer).confirmIntent(session, Date.now()) : scope.instructionReceipts.forPeer(peer).confirmReceipt(session, Date.now()));
391
+ current();
392
+ if (!receipt) return { ok: false, error: receiptRefusal };
393
+ const typedExact = /^run(?:\s|$)/u.test(receipt.args);
394
+ if (typedExact && msg.argv !== undefined) return { ok: false, error: "the person typed an exact command; run it without an agent-selected command" };
395
+ const argv: string[] | undefined = typedExact || initialMode === "exact" ? parseExactInstruction(receipt.args) : msg.argv;
396
+ const form = argv && (typedExact || initialMode === "exact" ? exactForm(argv) : intentForm(argv));
397
+ if (!argv) {
398
+ const raw = receipt.args.startsWith("run ") ? receipt.args.slice("run ".length).trim() : "";
399
+ if (!raw || /[\p{Cc}\p{Cf}]/u.test(raw) || raw.includes("~~~")) return { ok: false, error: "instruction syntax is not supported for exact mode; the original command cannot be rendered safely" };
400
+ return { ok: false, error: `this syntax is not proven for instructed exact mode. The person runs the original command in a terminal:\n\n~~~sh\ncd ${shellQuote(scope.opts.cwd)} && ahub ${raw}\n~~~\n\nSuccess: the command reports its result in that terminal.` };
401
+ }
402
+ if (!form || (typedExact || initialMode === "exact") && !["console", "conductor"].includes(classifyPeerCommand(argv[0]!, argv.slice(1), scope.adapterCatalog))) return { ok: false, error: `${typedExact || initialMode === "exact" ? "this form is not proven for instructed exact mode" : intentRefusal(argv)}. The person runs the same command in a terminal:\n\n\`\`\`sh\ncd ${shellQuote(scope.opts.cwd)} && ahub ${argv.map(shellQuote).join(" ")}\n\`\`\`\n\nSuccess: the command reports its result in that terminal.` };
403
+ if ("verdictIds" in form && Array.isArray(form.verdictIds) && !literalInstructionIds(receipt.args, form.verdictIds)) return { ok: false, error: "the verdict's item id or slot is not written in the person's instruction; type it in a new instruction" };
404
+ if (initialMode === "intent" && !typedExact && !scope.tasks.publicMetadataText(JSON.stringify(argv))) return { ok: false, error: "the selected command may contain private information; run the command in a terminal" };
405
+ const screened = "screen" in form && form.screen === true;
406
+ const screenRefusal = `instruction privacy screening did not clear the command. The person runs it in a terminal:\n\n\`\`\`sh\ncd ${shellQuote(scope.opts.cwd)} && ahub ${argv.map(shellQuote).join(" ")}\n\`\`\`\n\nSuccess: the command reports its result in that terminal.`;
407
+ const titleOwner = (form as ExactForm).titleTarget && form.targetPeer ? scope.bus.peers.get(form.targetPeer) : undefined;
408
+ const previousTitle = titleOwner?.sessionTitle;
409
+ const titleSession = titleOwner?.titleSession;
410
+ if ((form as ExactForm).titleTarget && (!isLocalPeer(titleOwner) || !previousTitle || scope.titlePrivate(form.targetPeer!, previousTitle))) throw new InstructionRefusal("this title cannot be safely restored or fenced; run the command in a terminal");
411
+ const study = (form as ExactForm).study;
412
+ const campaign = study ? scope.board.researchCampaign(study.id, study.revision) : undefined;
413
+ if (study && (!campaign || campaign.project !== scope.chain.at(-1) || campaign.private)) throw new InstructionRefusal("the study is unavailable or private; run the command in a terminal");
414
+ const taskId = form.taskId ?? campaign?.parentTaskId;
415
+ const studySources = campaign ? [...new Set([...campaign.contract.sourceIds, ...campaign.contract.units.flatMap(unit => unit.sourceIds)])] : [];
416
+ const studyBindings = () => campaign ? JSON.stringify(campaign.contract.units.map(unit => scope.board.researchLatestUnitBinding(campaign.id, unit.id))) : "";
417
+ const initialStudyBindings = studyBindings();
418
+ const studyTasks = campaign ? [...new Set([campaign.parentTaskId, ...campaign.contract.units.flatMap(unit => { const previous = scope.board.researchLatestUnitBinding(campaign.id, unit.id); return [...(unit.adoptTaskId === undefined ? [] : [unit.adoptTaskId]), ...(previous ? [previous.taskId] : [])]; }), ...scope.board.researchCampaignBindings(campaign.id, campaign.revision).map(unit => unit.taskId)])] : [];
419
+ const studyHash = campaign?.hash;
420
+ const screenedInputs = screened ? [receipt.args, JSON.stringify(argv), ...(campaign ? [JSON.stringify(campaign.contract)] : previousTitle ? [previousTitle] : [])] : [];
421
+ let studyEffectStarted = false;
422
+ const guarded = () => {
423
+ current();
424
+ if (!instructedRuntimeReady(scope)) throw new InstructionRefusal(runtimeRefusal);
425
+ if (screenedInputs.some(input => Buffer.byteLength(input) > SCREEN_MAX_BYTES || !scope.tasks.publicMetadataText(input))) throw new InstructionRefusal(screenRefusal);
426
+ if (taskId !== undefined) { const task = scope.board.get(taskId); if (!task || task.signals.includes("pii") || task.signals.includes("pii_path") || scope.tasks.isPii(task)) throw new InstructionRefusal("the command targets unavailable or private work; run the command in a terminal"); }
427
+ if (study && (!campaign || (() => { const latest = scope.board.researchCampaign(study.id, study.revision); return !latest || latest.private || latest.hash !== studyHash; })() || !studyEffectStarted && studyBindings() !== initialStudyBindings || studyTasks.some(id => { const task = scope.board.get(id); return !task || task.signals.includes("pii") || task.signals.includes("pii_path") || scope.tasks.isPii(task) || !scope.tasks.publicMetadataText(JSON.stringify(task.refs)); }) || studySources.some(id => { const source = scope.sourceRegistry.get(id); return !source || source.private; }))) throw new InstructionRefusal("the study changed or refers to private work; run the command in a terminal");
428
+ if ((form as ExactForm).titleTarget && (!form.targetPeer || !isLocalPeer(titleOwner) || scope.bus.peers.get(form.targetPeer) !== titleOwner || titleOwner.titleSession !== titleSession || titleOwner.sessionTitle !== previousTitle || scope.titlePrivate(form.targetPeer, previousTitle))) throw new InstructionRefusal("the session or previous title changed; run the command in a terminal");
429
+ if ("review" in form && form.review && (taskId === undefined || scope.board.get(taskId)?.reviewer !== USER)) throw new InstructionRefusal("only a task assigned to the person as reviewer can receive this verdict; run the command in a terminal");
430
+ if (form.targetPeer && scope.board.list().some(task => (task.signals.includes("pii") || task.signals.includes("pii_path") || scope.tasks.isPii(task)) && (task.owner === form.targetPeer || task.reviewer === form.targetPeer || task.reserved === form.targetPeer))) throw new InstructionRefusal("the command targets private work; run the command in a terminal");
431
+ };
432
+ guarded();
433
+ if (screened) {
434
+ const screen = scope.opts.piiScreen ?? ((text: string) => screenPii(text, { ...(scope.config.mlx.enabled === false ? {} : { device: () => ensureMlx(scope.config.mlx) }), onCampus: scope.onCampus, omni: scope.omni, fixedModel: () => scope.activeRouting().local.fixed_model }));
435
+ for (const input of screenedInputs) {
436
+ let timer: ReturnType<typeof setTimeout> | undefined;
437
+ const verdict = await Promise.race([screen(input).catch(() => undefined), new Promise<undefined>(resolve => { timer = setTimeout(() => resolve(undefined), SCREEN_TIMEOUT_MS); })]).finally(() => clearTimeout(timer));
438
+ guarded();
439
+ if (verdict?.label !== "clear") throw new InstructionRefusal(screenRefusal);
440
+ const fresh = await scope.instructionReceipts.forPeer(peer).confirmIntent(session, Date.now());
441
+ guarded();
442
+ if (!fresh || fresh.id !== receipt.id || fresh.args !== receipt.args) throw new InstructionRefusal(receiptRefusal);
443
+ }
444
+ }
445
+ if (!(initialMode === "intent" && !typedExact ? scope.instructionReceipts.consumeIntent(receipt.id, Date.now()) : scope.instructionReceipts.consumeExact(receipt.id, Date.now()))) return { ok: false, error: receiptRefusal };
446
+ if (!scope.event({ type: "agent_cli", peer, command: cliCommandLabel(argv[0]!, argv.slice(1), scope.adapterCatalog), refused: false, instructed: true, instructionReceipt: receipt.id })) { scope.instructionReceipts.finishExact(receipt.id); return { ok: false, error: "instruction audit is unavailable; check hub status and run the command in a terminal" }; }
447
+ let revoked = false;
448
+ const binding: InstructedExecution = { peer, receipt: receipt.id, active: true, ...(taskId === undefined ? {} : { taskId }), ...(study ? { beginStudy: () => { guarded(); studyEffectStarted = true; } } : {}), current: () => {
449
+ if (revoked) throw new Error("instruction authority revoked");
450
+ try { guarded(); if (!scope.instructionReceipts.exactCurrent(receipt.id, Date.now())) throw new InstructionRefusal(receiptRefusal); }
451
+ catch (error) { revoked = true; throw error; }
452
+ } };
453
+ try { return await launchInstructed(scope, argv, binding); }
454
+ catch (error) {
455
+ if (error instanceof InstructionRefusal) throw error;
456
+ throw new InstructionRefusal("the hub could not complete instructed execution; inspect the target before running the command in a terminal because an effect may have occurred");
457
+ }
458
+ finally { binding.active = false; scope.instructionReceipts.finishExact(receipt.id); }
459
+ } catch (error) { return { ok: false, error: error instanceof InstructionRefusal ? error.message : "instruction execution failed unexpectedly; inspect hub status and run the command in a terminal" }; }
460
+ })().then(reply, () => reply({ ok: false, error: "instruction unavailable" }));
461
+ return;
462
+ }
463
+
464
+ export function instructionHookMessage(scope: DaemonScope, m: ControlMessage): void {
465
+ const { c, msg, reply } = m;
466
+ const peer = c.peer;
467
+ const adapter = peer ? scope.definitionOf(peer) : undefined;
468
+ const fields = msg.op === "stop" ? ["t", "rid", "op", "session"] : ["t", "rid", "op", "session", "promptId", "transcript", "home", "cwd", "hash"];
469
+ if (Object.keys(msg).some(key => !fields.includes(key))) return void reply({ ok: false });
470
+ if (c.role !== "tools" || !peer || !isFixedBuiltinDefinition(adapter) || adapter?.transport !== "claude-channel" || scope.stopping || scope.recoveryActive()) return void reply({ ok: false });
471
+ if (msg.op === "stop") {
472
+ if (typeof msg.session !== "string" || scope.claudeSession(peer).sessionId !== msg.session || scope.bus.stateOf(peer) === "offline") return void reply({ ok: false });
473
+ scope.instructionReceipts.stop(msg.session, peer);
474
+ return void reply({ ok: true });
475
+ }
476
+ if (msg.op !== "pending" || typeof msg.session !== "string" || typeof msg.promptId !== "string" || typeof msg.transcript !== "string"
477
+ || typeof msg.home !== "string" || typeof msg.cwd !== "string" || typeof msg.hash !== "string") return void reply({ ok: false });
478
+ const current = scope.claudeSession(peer);
479
+ const attached = current.sessionId === msg.session && current.transcriptPath === msg.transcript && scope.bus.stateOf(peer) !== "offline";
480
+ try {
481
+ const ok = scope.instructionReceipts.pending({ session: msg.session, promptId: msg.promptId, transcript: msg.transcript, home: msg.home, cwd: msg.cwd, project: scope.opts.cwd,
482
+ hash: msg.hash, ...(attached ? { peer } : {}) }, Date.now());
483
+ return void reply({ ok });
484
+ } catch { return void reply({ ok: false }); }
485
+ }
486
+
487
+ export function factsMessage(scope: DaemonScope, m: ControlMessage): void {
488
+ const { c, msg, reply } = m;
489
+ // Turn-free facts (issue #108) for Claude's hooks: `pre` before a tool runs (the fact rides back as additional
490
+ // context), `post` after it (its effect, and the readback of what went in before), `stop` when its turn ends.
491
+ // The hook never shows an error: on any failure the answer is just empty.
492
+ if (!c.peer || c.role === "console") return void reply({ t: "facts", ok: false, error: "facts are for a peer" });
493
+ if (scope.definitionOf(c.peer)?.hooks?.factsHook) return void reply({ t: "facts", ok: false, error: "managed native hooks require native_facts" });
494
+ const phase: "session" | "start" | "pre" | "post" | "stop" = ["session", "start", "post", "stop"].includes(msg.phase) ? msg.phase : "pre";
495
+ const tool = typeof msg.tool === "string" ? msg.tool.slice(0, 64) : "";
496
+ const input = msg.input && typeof msg.input === "object" && !Array.isArray(msg.input) ? msg.input : {};
497
+ const toolUseId = typeof msg.toolUseId === "string" && msg.toolUseId ? msg.toolUseId.slice(0, 128) : undefined;
498
+ const sessionId = typeof msg.sessionId === "string" && msg.sessionId ? msg.sessionId.slice(0, 128) : undefined;
499
+ const callStarted = performance.now();
500
+ const tally = (peer: PeerId) => tallyHook(scope, peer, callStarted, msg.startedMs);
501
+ try {
502
+ const peer = c.peer;
503
+ if (scope.definitionOf(peer)?.start.daemonPort === "claude-implementer") {
504
+ const launch = scope.currentImplementerTools(c), root = scope.ownerWriteRoot(peer);
505
+ if (!launch || !root || root === scope.opts.cwd || sessionId !== launch.sessionId || msg.nativeLaunchId !== launch.launchId || msg.nativeInstanceId !== scope.instanceId) return void reply({ t: "facts", ok: false });
506
+ if (typeof msg.transcriptPath === "string" && isAbsolute(msg.transcriptPath) && basename(msg.transcriptPath) === `${launch.sessionId}.jsonl`) {
507
+ try {
508
+ const projects = realPath(join(process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), ".claude"), "projects")), transcript = realPath(msg.transcriptPath);
509
+ if (transcript.startsWith(`${projects}/`) && statSync(transcript).isFile() && launch.task !== undefined) scope.implementerTranscripts.set(`${peer}:${launch.task}:${launch.sessionId}`, transcript);
510
+ } catch { /* Exact path is not yet present or is unreadable: unknown preserves session identity. */ }
511
+ }
512
+ const mode = scope.permissionMode(peer);
513
+ if (mode !== "ask" && mode !== "ask-when-needed") return void reply({ t: "facts", ok: false });
514
+ const blocked = scopedWriteBlocked(phase, mode, msg.tool, () => projectFileTool(msg.tool, msg.input, root, scope.config.protect_instruction_files, scope.config.data?.readonly));
515
+ const actionClasses = phase === "pre" && typeof msg.tool === "string" ? claudeActionClasses(scope.actionBudgets, msg.tool, msg.input, root, scope.floorFacts(peer)) : [];
516
+ return void reply({ t: "facts", ok: true, ...(phase === "pre" ? { permission: mode === "ask-when-needed" && blocked ? "ask" : mode, projectRoot: root, protectInstructionFiles: scope.config.protect_instruction_files, ...(actionClasses.length ? { actionClasses } : {}) } : {}) });
517
+ }
518
+ let nativeClaude = false, nativeTranscript: string | undefined;
519
+ if (scope.definitionOf(peer)?.transport === "claude-channel" && sessionId && msg.nativeInstanceId === scope.instanceId) {
520
+ const expectedLaunch = scope.claudeLaunchProof.expectedLaunch(peer);
521
+ const current = scope.claudeSession(peer);
522
+ if ((phase === "stop" || phase === "post") && current.sessionId && current.sessionId !== sessionId) return void reply({ t: "facts", ok: false });
523
+ if (!expectedLaunch || msg.nativeLaunchId === expectedLaunch) {
524
+ const transcript = nativeTranscript = claudeTranscript(scope, sessionId, msg.transcriptPath, peer);
525
+ const launchId = typeof msg.nativeLaunchId === "string" ? msg.nativeLaunchId : undefined;
526
+ const file = join(scope.opts.stateDir, claudeStateFile("claude-session", peer));
527
+ writeFileSync(`${file}.hook.tmp`, JSON.stringify({ at: Date.now(), instanceId: scope.instanceId, sessionId, ...(launchId ? { launchId } : {}), ...(transcript ? { transcriptPath: transcript } : {}) }), { mode: 0o600 });
528
+ chmodSync(`${file}.hook.tmp`, 0o600); renameSync(`${file}.hook.tmp`, file);
529
+ nativeClaude = true;
530
+ }
531
+ if (!nativeClaude) return void reply({ t: "facts", ok: false });
532
+ }
533
+ if (scope.definitionOf(peer)?.transport === "claude-channel" && msg.nativeInstanceId !== undefined && msg.nativeInstanceId !== scope.instanceId) return void reply({ t: "facts", ok: false });
534
+ if (nativeClaude && (phase === "pre" || phase === "stop")) {
535
+ try { observeClaudeDoing(scope, peer, sessionId!, nativeTranscript, phase === "pre" ? tool : "", input); } catch { /* #878: a display value never costs the hook its answer */ }
536
+ }
537
+ const nativePeer = nativeClaude ? scope.claudeLaunchProof.owner(peer) : undefined;
538
+ const permissionLaunch = scope.definitionOf(peer)?.transport === "claude-channel" ? scope.claudeLaunchProof.permissionLaunch(peer) : undefined;
539
+ const writeRoot = scope.declarations[peer]?.worktree ? scope.ownerWriteRoot(peer) : scope.executionRoot(peer);
540
+ if (scope.declarations[peer]?.worktree && writeRoot === undefined) return void reply({ t: "facts", ok: false });
541
+ const permission = nativeClaude && permissionLaunch && !permissionLaunch.unattended && msg.nativeLaunchId === permissionLaunch.launchId && writeRoot !== undefined ? scope.permissionMode(peer) : undefined;
542
+ if (permission !== undefined && nativePeer) scope.claudeLaunchProof.bindGeneration(peer, nativePeer.sessionGeneration);
543
+ const protectedWrite = scopedWriteBlocked(phase, permission, msg.tool, () => projectFileTool(msg.tool, msg.input, writeRoot ?? scope.opts.cwd, scope.config.protect_instruction_files, scope.config.data?.readonly));
544
+ // Always-ask (#636): a classed call is asked about in every permission mode. The hub names only the classes, under the same verified root as the file policy above; the hook turns them into `ask`.
545
+ const actionClasses = phase === "pre" && permission !== undefined && typeof msg.tool === "string" ? claudeActionClasses(scope.actionBudgets, msg.tool, msg.input, writeRoot ?? scope.opts.cwd, scope.floorFacts(peer)) : [];
546
+ const plannerOnly = !!scope.declarations[peer] && scope.definitionOf(peer)?.transport === "claude-channel" && isPlannerOnly(scope.config.roles[peer] ?? []);
547
+ // Older hooks do not know mutationGrants; the existing permission field must also withhold their mutation grant.
548
+ const plannerMutation = plannerOnly && !["Read", "LS", "Glob", "Grep"].includes(tool);
549
+ const permissionReply = phase === "pre" && permission !== undefined ? { permission: plannerMutation || permission === "ask-when-needed" && protectedWrite ? "ask" : permission, projectRoot: writeRoot ?? scope.opts.cwd, protectInstructionFiles: scope.config.protect_instruction_files, ...(plannerOnly ? { mutationGrants: false } : {}), ...(actionClasses.length ? { actionClasses } : {}) } : {};
550
+ // Permission-only hooks carry no native-turn evidence and must never drive busy state.
551
+ const purpose = permissionLaunch?.hookPurpose ?? msg.hookPurpose;
552
+ const observesNative = purpose === "facts" || purpose === "idle" || purpose === "facts-and-idle" || (purpose === undefined && (scope.config.coordination === "turn-free" || scope.config.task_sweep.enabled || scope.config.roles[peer]?.includes("conductor")));
553
+ if (nativeClaude && !observesNative) return void reply({ t: "facts", ok: true, ...permissionReply });
554
+ if (phase === "session") { scope.recordSessions(); return void reply({ t: "facts", ok: true }); }
555
+ if ((phase === "start" || phase === "pre") && nativePeer) {
556
+ const previous = scope.nativeTurnStart.get(peer);
557
+ const current = scope.claudeSession(peer);
558
+ if (phase === "start" || nativePeer.state !== "busy" || previous?.generation !== nativePeer.sessionGeneration || previous?.session !== sessionId || previous?.launch !== (current.launchId ?? "")) {
559
+ const session = scope.claudeSession(peer);
560
+ const baseline = session.sessionId && session.transcriptPath ? readClaudeTranscriptCompletion(session.sessionId, session.transcriptPath)?.id : undefined;
561
+ scope.nativeTurnStart.set(peer, { at: Date.now(), ...(baseline ? { baseline } : {}), generation: nativePeer.sessionGeneration, session: sessionId!, launch: session.launchId ?? "" });
562
+ }
563
+ nativePeer.nativeStarted(sessionId!);
564
+ }
565
+ if (phase === "start") { scope.activeAt.set(peer, Date.now()); return void reply({ t: "facts", ok: true }); }
566
+ // Quiescence evidence is kept in every regime: a PII window must not make an active peer look stopped. Only
567
+ // a tool call starting is new activity: a PostToolUse of an earlier call can arrive after the Stop.
568
+ if (phase === "stop") {
569
+ const finishStop = (id?: string) => {
570
+ if (id) {
571
+ scope.collectClaudeUsage(); scope.finishSupervisionTurn(peer); scope.nativeCompletedAt.set(peer, Date.now());
572
+ scope.event({ type: "native_turn_end", peer, id });
573
+ try { if (scope.runs.get(peer)) { scope.runs.signalled(peer); scope.settleCheck(peer); } } catch { scope.log(`completion settle for ${peer} failed`); } // #1054: the verified native Stop
574
+ }
575
+ scope.turnEnded.set(peer, Date.now()); scope.tasks.cohorts.turnEnded(peer); tally(peer); emitHookStats(scope, peer);
576
+ if (id && nativePeer) nativePeer.nativeStopped(sessionId!);
577
+ if (scope.factsOn()) { scope.factSession(peer, sessionId); readbacks(scope, peer, claudeTranscript(scope, sessionId, msg.transcriptPath, peer)); }
578
+ };
579
+ if (!nativeClaude) { finishStop(); reply({ t: "facts", ok: true }); return; } // legacy bookkeeping cannot certify native completion
580
+ const session = scope.claudeSession(peer);
581
+ let transcript = session.transcriptPath ?? claudeTranscript(scope, sessionId, msg.transcriptPath, peer);
582
+ const readCompletion = () => { transcript ??= claudeTranscript(scope, sessionId, msg.transcriptPath, peer); return session.sessionId && transcript ? readClaudeTranscriptCompletion(session.sessionId, transcript) : undefined; };
583
+ const completionId = (id: string) => createHash("sha256").update(`${sessionId}:${session.launchId ?? "legacy"}:${id}`).digest("hex");
584
+ const started = scope.nativeTurnStart.get(peer);
585
+ const activeStart = !!started && started.session === sessionId && started.launch === (session.launchId ?? "") && !!nativePeer && started.generation === nativePeer.sessionGeneration;
586
+ // A seen previous completion is a duplicate only outside an active start. During B it is B's baseline.
587
+ if (!activeStart) {
588
+ const latest = readCompletion();
589
+ if (latest?.at && scope.nativeStopsSeen.has(completionId(latest.id))) return void reply({ t: "facts", ok: true });
590
+ }
591
+ if (!started || !activeStart || !nativePeer) { scope.log("native Stop refused for claude: current native turn start unavailable"); return void reply({ t: "facts", ok: false }); }
592
+ const scopeCurrent = () => {
593
+ const now = scope.claudeSession(peer);
594
+ return !scope.stopping && scope.bus.peers.get(peer) === nativePeer && nativePeer.sessionGeneration === started.generation && now.sessionId === started.session && (now.launchId ?? "") === started.launch;
595
+ };
596
+ const current = () => scopeCurrent() && scope.nativeTurnStart.get(peer) === started;
597
+ let pending = scope.nativeStopWaits.get(peer);
598
+ // Claude flushes final transcript rows after its command hook returns. ACK is observation, not completion.
599
+ reply({ t: "facts", ok: true, pending: true });
600
+ if (pending?.start === started) return;
601
+ pending = { start: started, wait: (async () => { await Bun.sleep(0); return waitForClaudeCompletion(readCompletion, current, started); })() };
602
+ scope.nativeStopWaits.set(peer, pending);
603
+ const ownWait = pending;
604
+ void ownWait.wait.then(result => {
605
+ if (scope.nativeStopWaits.get(peer) === ownWait) scope.nativeStopWaits.delete(peer);
606
+ if (!result.record) {
607
+ const reason = ({ unavailable: "completed transcript message unavailable", baseline: "completion still matches start baseline", "before-start": "completion timestamp precedes native start", superseded: "native start superseded during completion wait", verified: "completed transcript message unavailable" } as const)[result.reason];
608
+ scope.log(`native Stop refused for claude: ${reason}`);
609
+ // #517: a peer left busy receives no pushed messages; say so where the person looks, once per turn.
610
+ if (result.reason === "unavailable" && !scope.stopUnconfirmedNoticed.has(started)) {
611
+ scope.stopUnconfirmedNoticed.add(started);
612
+ scope.notify(`${peer}: its turn end could not be confirmed from its transcript, so it stays busy and messages to it wait in its queue (hub_inbox reads them)`);
613
+ }
614
+ return;
615
+ }
616
+ const id = completionId(result.record.id);
617
+ if (scopeCurrent() && scope.nativeStopsSeen.has(id)) return;
618
+ if (!current()) { scope.log("native Stop refused for claude: native start superseded during completion wait"); return; }
619
+ scope.nativeStopsSeen.add(id); scope.nativeTurnStart.delete(peer); // consume before idle admits another native turn
620
+ if (transcript && !session.transcriptPath) {
621
+ const file = join(scope.opts.stateDir, claudeStateFile("claude-session", peer));
622
+ writeFileSync(`${file}.hook.tmp`, JSON.stringify({ at: Date.now(), instanceId: scope.instanceId, sessionId, launchId: session.launchId, transcriptPath: transcript }), { mode: 0o600 });
623
+ chmodSync(`${file}.hook.tmp`, 0o600); renameSync(`${file}.hook.tmp`, file);
624
+ }
625
+ finishStop(id);
626
+ }).catch(() => { if (scope.nativeStopWaits.get(peer) === ownWait) scope.nativeStopWaits.delete(peer); scope.log("native Stop refused for claude: completion wait unavailable"); });
627
+ return;
628
+ } else {
629
+ if (phase === "pre") scope.activeAt.set(peer, Date.now());
630
+ queueMicrotask(() => tally(peer)); // after this call's own work below
631
+ }
632
+ if (!scope.factsOn()) {
633
+ if (nativeClaude && scope.editObservationOn(peer) && !reviewCaptureExcluded(tool, JSON.stringify(input ?? {}))) {
634
+ scope.factSession(peer, sessionId);
635
+ if (phase === "pre") scope.factsFor(peer).preTool(peer, toolUseId, tool, input);
636
+ if (phase === "post") scope.factsFor(peer).postTool(peer, toolUseId, tool, input);
637
+ }
638
+ return void reply({ t: "facts", ok: true, ...permissionReply });
639
+ }
640
+ if (scope.definitionOf(peer)?.transport === "claude-channel" && phase === "pre" && !reviewCaptureExcluded(tool, JSON.stringify(input ?? {}))) scope.observeProgress(peer, normalizeClaudeObservation(tool, input));
641
+ scope.factSession(peer, sessionId);
642
+ const transcript = claudeTranscript(scope, sessionId, msg.transcriptPath, peer);
643
+ if (phase === "post") {
644
+ scope.factsFor(peer).postTool(peer, toolUseId, tool, input);
645
+ readbacks(scope, peer, transcript);
646
+ return void reply({ t: "facts", ok: true });
647
+ }
648
+ readbacks(scope, peer, transcript);
649
+ scope.checkCapability(peer);
650
+ const started = performance.now();
651
+ scope.factsFor(peer).preTool(peer, toolUseId, tool, input);
652
+ // Without a transcript nothing offered could ever be read back: a verified path is lost, and nothing is offered
653
+ // (the same diff would otherwise go in at every tool call).
654
+ if (!transcript) {
655
+ if (scope.capable.delete(peer)) scope.loseCapability(peer, "its transcript cannot be found");
656
+ return void reply({ t: "facts", ok: true, ...permissionReply });
657
+ }
658
+ const offered = scope.offerFor(peer, toolUseId);
659
+ if (offered) scope.event({ type: "fact", peer, id: offered.id, files: offered.files, plans: offered.plans, unknown: offered.unknown, named: offered.named, bytes: offered.bytes, via: "hook", ms: Math.round(performance.now() - started), ...(typeof msg.startedMs === "number" && Number.isFinite(msg.startedMs) ? { hookMs: Math.round(msg.startedMs) } : {}), ...(offered.probe ? { probe: true } : {}), ...(offered.coverage ? { coverage: true } : {}) });
660
+ return void reply({ t: "facts", ok: true, ...permissionReply, ...(offered ? { text: offered.text, id: offered.id } : {}) });
661
+ } catch (error) {
662
+ scope.log(`facts for ${c.peer}: ${(error as Error).message}`);
663
+ return void reply({ t: "facts", ok: true });
664
+ }
665
+ }