@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,415 @@
1
+ // #1830 S2c: the board-workflow control messages moved out of onMessage. Each function is one case group of the switch, unchanged apart from reading the daemon's names through `scope`.
2
+ import { conductorPeer } from "../conductor.ts";
3
+ import { readControl } from "../control-client.ts";
4
+ import { dogfoodLines } from "../dogfood-read.ts";
5
+ import { HUB, USER } from "../envelope.ts";
6
+ import { EXECUTION_REFERENCE_LIMITS, executionText } from "../execution-reference.ts";
7
+ import { GuidanceProbeError, probeSessionGeneration } from "../guidance-probes.ts";
8
+ import type { ProbePublicReceipt, ProbePublicStatus, ProbeReceiptExport } from "../guidance-probes.ts";
9
+ import { HandoffRefusal } from "../handoff.ts";
10
+ import { IMPLEMENTER_HUB_TOOL_NAMES } from "../hub-tools.ts";
11
+ import { CONDUCTOR_DAEMON_OPERATIONS, CONDUCTOR_TASK_OPS, OperationalAuthorityError, conductorLocalOperation } from "../operational-authority.ts";
12
+ import { inspectSelectedOrphans, orphanProcessPorts, stopSelectedOrphan } from "../orphan-process.ts";
13
+ import type { PeerAdapter } from "../peers.ts";
14
+ import { PreEffectToolRefusal } from "../tool-refusal.ts";
15
+ import { toolWriteOperation, toolWriteUnknownReply } from "../tool-request.ts";
16
+ import type { ActionMeta } from "@staix/agent-console/contract";
17
+ import { join } from "node:path";
18
+ import { fileURLToPath } from "node:url";
19
+ import type { ControlMessage, DaemonScope, GuidanceProbeRequestContext } from "./scope.ts";
20
+
21
+ function publicReleaseShow(scope: DaemonScope, input: Record<string, any>) {
22
+ const release = input.id !== undefined ? Number.isSafeInteger(input.id) && input.id > 0 ? scope.board.release(input.id) : undefined
23
+ : scope.board.releases().find(row => row.name === input.name);
24
+ if (!release) throw new PreEffectToolRefusal("no such release");
25
+ const shown = scope.tasks.publicRelease(release);
26
+ return { id: shown.id, name: scope.publicReadValue(shown.name), goal: scope.publicReadValue(shown.goal), order: shown.order, state: shown.state,
27
+ plannedStart: shown.plannedStart, cut: shown.cut, ship: shown.ship, activatedAt: shown.activatedAt, frozenAt: shown.frozenAt,
28
+ shippedAt: shown.shippedAt, created: shown.created, updated: shown.updated, revision: shown.revision,
29
+ public: true, complete: false, withheld: ["train", "tasks", "afterCut", "afterCutUnknown", "planner"] };
30
+ }
31
+ // conductor_operational
32
+ export function conductorOperational(scope: DaemonScope, m: ControlMessage): void {
33
+ const { sock, msg, reply } = m;
34
+ {
35
+ try {
36
+ if(!["authorize","admit","logs","export","orphans"].includes(msg.op))return void reply({ok:false,error:"unknown operational request"});
37
+ const command=msg.op==="authorize"||msg.op==="admit"?msg.command:msg.op==="orphans"?"doctor orphans kill":msg.op;
38
+ // #933: `admit` is the one audited admission of a form whose effect runs in the CLI process; `authorize` only checks the role for a form whose own request admits.
39
+ if(msg.op==="admit"?!conductorLocalOperation(command):!(CONDUCTOR_DAEMON_OPERATIONS as readonly string[]).includes(command))return void reply({ok:false,error:"unknown operational command"});
40
+ const current=msg.op==="authorize"?scope.operationalCurrent(sock):scope.admitOperational(sock,command);current();
41
+ if(msg.op==="authorize"||msg.op==="admit")return void reply({ok:true,instanceId: scope.instanceId});
42
+ if(msg.op==="logs" || msg.op==="export") {
43
+ const lines=dogfoodLines(join(scope.opts.stateDir,msg.op==="logs"?"hub.log":"events.jsonl"),128*1024);
44
+ if(!lines.available)return void reply({ok:false,error:"operational history unavailable"});
45
+ const view=scope.publicOperationalView();current();
46
+ if(msg.op==="logs") {
47
+ if(msg.follow!==undefined && typeof msg.follow!=="boolean")return void reply({ok:false,error:"invalid log subscription"});
48
+ if(msg.follow)scope.operationalLogSubscribers.set(sock,current);
49
+ return void reply({ok:true,lines:lines.data.slice(-100).map(view.line),complete:lines.complete&&view.complete,...(!view.complete?{incompleteReason:view.incompleteReason}:!lines.complete?{incompleteReason:"history read limit"}:{}),truncated:!lines.complete || lines.data.length>100});
50
+ }
51
+ if(msg.since!==undefined && (typeof msg.since!=="number" || !Number.isFinite(msg.since) || msg.since<0))return void reply({ok:false,error:"invalid export window"});
52
+ const records=lines.data.flatMap(line=>{try{const row=JSON.parse(line);return typeof row?.at==="string" && Date.parse(row.at)>=(msg.since??0)?[view.event(row)]:[];}catch{return [{type:"withheld"}];}});
53
+ return void reply({ok:true,events:records.slice(-1000),complete:lines.complete&&view.complete,...(!view.complete?{incompleteReason:view.incompleteReason}:!lines.complete?{incompleteReason:"history read limit"}:{}),truncated:!lines.complete || records.length>1000});
54
+ }
55
+ if(msg.op!=="orphans")return void reply({ok:false,error:"unknown operational request"});
56
+ const selection={root:scope.opts.cwd,projectId: scope.projectId,instanceId: scope.instanceId,pid:process.pid,executable:process.execPath,programs:[scope.CLI_ENTRY,fileURLToPath(new URL("../../cli/main.js",import.meta.url))]},ports={...orphanProcessPorts,current};
57
+ const inspected=inspectSelectedOrphans(selection,undefined,readControl(scope.opts.stateDir),ports);
58
+ void (async()=>{
59
+ const stopped:number[]=[];let self=false,unknown=inspected.state==="unknown";
60
+ for(const candidate of inspected.candidates){const result=await stopSelectedOrphan(candidate,selection,ports);current();if(result==="stopped")stopped.push(candidate.pid);else if(result==="self")self=true;else unknown=true;}
61
+ current();reply({ok:true,stopped,unknown,self});
62
+ if(self)setTimeout(()=>{try{
63
+ const accepted=scope.operationalCurrent(sock,true);accepted();
64
+ const fresh=inspectSelectedOrphans(selection,undefined,readControl(scope.opts.stateDir),{...ports,current:accepted});
65
+ if(fresh.candidates.some(candidate=>candidate.pid===process.pid))void scope.stop().catch(()=>{});
66
+ }catch{/* Changed authority, instance or ownership never stops the hub. */}},0);
67
+ })().catch(error=>reply(scope.operationalFailure(error,"operational orphan cleanup unconfirmed")));
68
+ } catch(error) {reply(scope.operationalFailure(error));}
69
+ return;
70
+ }
71
+ }
72
+
73
+ // review_comment_put, review_comment_delete, review_comment_send
74
+ export function reviewCommentWrite(scope: DaemonScope, m: ControlMessage): void {
75
+ const { c, msg, reply } = m;
76
+ {
77
+ if (c.role !== "console") return void reply({ ok: false, error: "review comments are person-only; open the task in acon" });
78
+ if (scope.recoveryActive() || scope.stopping) return void reply({ ok: false, error: "recovery or shutdown is holding review comments; refresh after it finishes" });
79
+ if (msg.instanceId !== undefined && msg.instanceId !== scope.instanceId) return void reply({ ok: false, error: "hub restarted; refresh before acting" });
80
+ const { t: _op, rid: _rid, instanceId: _instance, personMeta, ...input } = msg;
81
+ let verified: ActionMeta | undefined;
82
+ if (personMeta !== undefined) {
83
+ if (!personMeta || typeof personMeta !== "object" || Array.isArray(personMeta)
84
+ || Object.keys(personMeta).some(key => !["identity", "node", "via"].includes(key))
85
+ || personMeta.via !== "console" || typeof personMeta.identity !== "string" || !personMeta.identity.trim()
86
+ || Buffer.byteLength(personMeta.identity) > 256 || typeof personMeta.node !== "string" || !personMeta.node.trim() || Buffer.byteLength(personMeta.node) > 256) {
87
+ return void reply({ ok: false, error: "verified console identity is invalid; reopen acon and retry" });
88
+ }
89
+ verified = { identity: personMeta.identity, node: personMeta.node, via: "console" };
90
+ }
91
+ void (async () => {
92
+ if (msg.t === "review_comment_put") return await scope.tasks.reviewCommentPut(USER, input, verified);
93
+ if (msg.t === "review_comment_delete") return await scope.tasks.reviewCommentDelete(USER, input, verified);
94
+ return await scope.tasks.reviewCommentSend(USER, input, verified);
95
+ })().then(result => reply({ ok: true, ...result }), error => reply({ ok: false, error: (error as Error).message }));
96
+ return;
97
+ }
98
+ }
99
+
100
+ // review_comments
101
+ export function reviewCommentsRead(scope: DaemonScope, m: ControlMessage): void {
102
+ const { c, msg, reply } = m;
103
+ if (c.role !== "console") return void reply({ ok: false, error: "review comment details are a console read" });
104
+ if (msg.instanceId !== undefined && msg.instanceId !== scope.instanceId) return void reply({ ok: false, error: "hub restarted; refresh before reading" });
105
+ void scope.tasks.reviewCommentList(USER, { task: msg.task }).then(result => reply({ ok: true, ...result }), () => reply({ ok: false, error: "review comments unavailable; refresh the task" }));
106
+ return;
107
+ }
108
+
109
+ // review_blob
110
+ export function reviewBlob(scope: DaemonScope, m: ControlMessage): void {
111
+ const { c, msg, reply } = m;
112
+ {
113
+ if (c.role !== "console") return void reply({ ok: false, error: "review material is a console read" });
114
+ if (msg.instanceId !== undefined && msg.instanceId !== scope.instanceId) return void reply({ ok: false, error: "hub restarted; refresh before reading" });
115
+ const task = Number.isSafeInteger(msg.task) ? scope.board.get(msg.task) : undefined;
116
+ if (!task || (scope.tasks.isPii(task) || task.signals.includes("pii") || task.signals.includes("pii_path")) || typeof msg.path !== "string" || Buffer.byteLength(msg.path) > 4096 || msg.side !== undefined && !["base", "head"].includes(msg.side)) return void reply({ ok: false, error: "review material unavailable for this task scope; refresh and select a declared public task file" });
117
+ void scope.reviewMaterials(task, [{ path: msg.path, side: msg.side ?? "head" }]).then(batch => {
118
+ const material = batch.materials[0];
119
+ if (!material || material.state !== "available") return reply({ ok: false, error: "review material unavailable for this task scope; refresh and select a declared public task file" });
120
+ return reply({ ok: true, task: task.id, head: batch.head, doc: { kind: "text", path: material.path, text: material.text, contentHash: material.contentHash, ...(material.projection ? { projection: material.projection } : {}) } });
121
+ }, () => reply({ ok: false, error: "review material unavailable; refresh the task" }));
122
+ return;
123
+ }
124
+ }
125
+
126
+ // task_catalog_role
127
+ export function taskCatalogRole(scope: DaemonScope, m: ControlMessage): void {
128
+ const { c, msg, reply } = m;
129
+ if (c.role !== "console" && (c.role !== "tools" || !c.peer || c.toolsOwner || c.externalOwner || scope.readOnlyPeer(c.peer) || scope.contextPii(c.peer))) return void reply({ ok: false, error: "task roles are a person command" });
130
+ if (scope.recoveryActive() || scope.stopping) return void reply({ ok: false, error: "recovery or shutdown is holding task role changes" });
131
+ try { const task = scope.tasks.setRole(c.role === "console" ? USER : c.peer!, msg.id, msg.role); return void reply({ ok: true, text: `task #${task.id}: catalog role ${task.role ?? "none"}` }); }
132
+ catch (error) { return void reply({ ok: false, error: (error as Error).message }); }
133
+ }
134
+
135
+ // guidance_list, guidance_show, guidance_create, guidance_withdraw
136
+ export function guidanceMessage(scope: DaemonScope, m: ControlMessage): void {
137
+ const { sock, c, msg, reply } = m;
138
+ {
139
+ const role = c.role, actor = role === "console" ? USER : role === "tools" && typeof c.peer === "string" && scope.peerIdPattern.test(c.peer) ? c.peer : undefined;
140
+ if (!actor) return void reply({ ok: false, error: "guidance is unavailable for this caller; use an authorized current project session" });
141
+ const { t: _t, rid: _rid, ...input } = msg;
142
+ const ownedCurrent = c.toolsOwner ? scope.captureImplementerTools(c) : undefined;
143
+ const current = () => {
144
+ if (sock.data !== c || c.closed || sock.readyState !== WebSocket.OPEN || c.role !== role || role === "tools" && c.peer !== actor || scope.stopping)
145
+ throw new PreEffectToolRefusal("guidance caller changed; reconnect in the current project session");
146
+ if (c.externalOwner && !scope.currentExternalTools(c, true) || ownedCurrent && !ownedCurrent()) throw new PreEffectToolRefusal("guidance runtime owner changed; reconnect before retrying");
147
+ };
148
+ try { current(); } catch (error) { return void reply({ ok: false, error: (error as Error).message }); }
149
+ if (msg.t === "guidance_list" || msg.t === "guidance_show") return void reply(scope.guidanceRead(actor, msg.t === "guidance_list" ? "list" : "show", input));
150
+ const op = msg.t === "guidance_create" ? "hub_guidance_create" : "hub_guidance_withdraw";
151
+ void scope.childToolAuthority.run({ by: actor, current: () => { try { current(); return true; } catch { return false; } } }, () => scope.taskOp(actor, op, input)).then(
152
+ text => { try { current(); reply(JSON.parse(text)); } catch { reply({ ok: false, error: "guidance write is unconfirmed; inspect the task guidance before explicitly retrying" }); } },
153
+ error => reply({ ok: false, error: error instanceof Error ? error.message : "guidance write is unconfirmed; inspect the task guidance before explicitly retrying" }));
154
+ return;
155
+ }
156
+ }
157
+
158
+ // guidance_probe_register, guidance_probe_start, guidance_probe_show, guidance_probe_receipts, guidance_probe_cancel
159
+ export function guidanceProbeMessage(scope: DaemonScope, m: ControlMessage): void {
160
+ const { sock, c, msg, reply } = m;
161
+ {
162
+ const role = c.role, actor = role === "console" ? USER : role === "tools" && typeof c.peer === "string" && scope.peerIdPattern.test(c.peer) ? c.peer : undefined;
163
+ if ((role !== "console" && role !== "tools") || !actor) return void reply({ ok: false, error: "guidance probes require a person or the current configured conductor" });
164
+ if (scope.stopping || scope.recoveryActive() || scope.bus.isRecoveryHeld) return void reply({ ok: false, error: "recovery or shutdown is holding guidance probe operations; inspect retained state after release" });
165
+ const operation = msg.t === "guidance_probe_register" ? "guidance probe register" : msg.t === "guidance_probe_start" ? "guidance probe start"
166
+ : msg.t === "guidance_probe_show" ? "guidance probe show" : msg.t === "guidance_probe_receipts" ? "guidance probe receipts" : "guidance probe cancel";
167
+ let authorityCurrent: () => void;
168
+ if (role === "tools") {
169
+ try { authorityCurrent = scope.admitOperational(sock, operation); }
170
+ catch (error) { return void reply(scope.operationalFailure(error)); }
171
+ } else authorityCurrent = () => {
172
+ if (sock.data !== c || c.closed || sock.readyState !== WebSocket.OPEN || c.role !== "console" || scope.stopping)
173
+ throw new PreEffectToolRefusal("guidance probe console session changed; reconnect and inspect retained state");
174
+ };
175
+ const requestConnectionId = c.guidanceProbeConnectionId;
176
+ if (!executionText(requestConnectionId, EXECUTION_REFERENCE_LIMITS.id))
177
+ return void reply({ ok: false, error: "guidance probe request identity is unavailable; reconnect through the authenticated project connection" });
178
+ let generation: string | number, nativeSession: string | null, owner: PeerAdapter | undefined;
179
+ const claudeChannel = role === "tools" && scope.definitionOf(actor)?.transport === "claude-channel";
180
+ const attestedClaude = () => {
181
+ const peer = scope.claudeLaunchProof.owner(actor);
182
+ return peer === owner && peer
183
+ ? scope.claudeLaunchProof.attestedSession(actor, peer.managedLaunchId, c.claudeSessionId) : undefined;
184
+ };
185
+ if (role === "console") {
186
+ generation = requestConnectionId;
187
+ nativeSession = null;
188
+ } else {
189
+ owner = scope.bus.peers.get(actor);
190
+ const peerGeneration = owner?.sessionGeneration, peerNativeSession = owner?.nativeSession;
191
+ if (!owner || !("sessionGeneration" in owner) || !probeSessionGeneration(peerGeneration)
192
+ || !("nativeSession" in owner) || typeof peerNativeSession !== "string"
193
+ || !executionText(peerNativeSession, EXECUTION_REFERENCE_LIMITS.id))
194
+ return void reply({ ok: false, error: claudeChannel
195
+ ? "guidance probe conductor session identity is unavailable; start a new session with ahub claude"
196
+ : "guidance probe conductor session identity is unavailable; reconnect the current native peer session" });
197
+ if (claudeChannel && attestedClaude() !== peerNativeSession)
198
+ return void reply({ ok: false, error: "guidance probe conductor session is not attested; start a new session with ahub claude" });
199
+ generation = peerGeneration;
200
+ nativeSession = peerNativeSession;
201
+ }
202
+ const current = (): void => {
203
+ if (sock.data !== c || c.closed || sock.readyState !== WebSocket.OPEN || c.role !== role || c.guidanceProbeConnectionId !== requestConnectionId
204
+ || role === "tools" && (c.peer !== actor || scope.bus.peers.get(actor) !== owner || owner!.sessionGeneration !== generation || owner!.nativeSession !== nativeSession
205
+ || claudeChannel && attestedClaude() !== nativeSession))
206
+ throw new PreEffectToolRefusal("guidance probe request connection or native peer session changed; inspect retained state and reconnect");
207
+ authorityCurrent();
208
+ };
209
+ const requestContext: GuidanceProbeRequestContext = { actor, requestConnectionId, generation, nativeSession, current };
210
+ const input = msg.registration;
211
+ scope.taskOpsInFlight++;
212
+ const run = () => {
213
+ current();
214
+ if (scope.recoveryActive() || scope.bus.isRecoveryHeld || scope.stopping) throw new PreEffectToolRefusal("recovery or shutdown is holding guidance probe operations; inspect retained state after release");
215
+ const action = (): Promise<ProbePublicReceipt | ProbePublicStatus | ProbeReceiptExport> => msg.t === "guidance_probe_register" ? scope.tasks.guidanceProbeRegister(actor, input)
216
+ : msg.t === "guidance_probe_start" ? scope.tasks.guidanceProbeStart(actor, msg.id, msg.revision, msg.variantId)
217
+ : msg.t === "guidance_probe_show" ? scope.tasks.guidanceProbeShow(actor, msg.id)
218
+ : msg.t === "guidance_probe_receipts" ? scope.tasks.guidanceProbeReceipts(actor, msg.id)
219
+ : scope.tasks.guidanceProbeCancel(actor, msg.id, msg.revision);
220
+ const withRequest = () => scope.guidanceProbeRequestContext.run(requestContext, action);
221
+ return role === "tools" ? scope.operationalContext.run({ actor, current }, withRequest) : withRequest();
222
+ };
223
+ void Promise.resolve().then(run).then(value => reply(msg.t === "guidance_probe_show" ? { ok: true, status: value } : msg.t === "guidance_probe_receipts" ? { ok: true, receipts: value } : { ok: true, receipt: value }), error => {
224
+ if (error instanceof PreEffectToolRefusal || error instanceof GuidanceProbeError) return reply({ ok: false, error: error.message });
225
+ if (error instanceof OperationalAuthorityError) return reply(scope.operationalFailure(error));
226
+ return reply({ ok: false, error: "guidance probe operation is unconfirmed; inspect retained state before retrying" });
227
+ })
228
+ .finally(() => { scope.taskOpsInFlight--; }).catch(() => {});
229
+ return;
230
+ }
231
+ }
232
+
233
+ // lineage_show, lineage_link
234
+ export function lineageMessage(scope: DaemonScope, m: ControlMessage): void {
235
+ const { sock, c, msg, reply } = m;
236
+ {
237
+ const role = c.role, actor = role === "console" ? USER : role === "tools" && typeof c.peer === "string" && scope.peerIdPattern.test(c.peer) ? c.peer : undefined;
238
+ if (!actor) return void reply({ ok: false, error: "execution lineage is unavailable for this caller; use an authorized project session" });
239
+ const { t: _t, rid: _rid, ...input } = msg;
240
+ const ownedCurrent = c.toolsOwner ? scope.captureImplementerTools(c) : undefined;
241
+ const current = () => {
242
+ if (sock.data !== c || c.closed || sock.readyState !== WebSocket.OPEN || c.role !== role || (role === "tools" && c.peer !== actor) || scope.stopping) throw new PreEffectToolRefusal("execution lineage caller changed; reconnect and retry");
243
+ if (c.externalOwner && !scope.currentExternalTools(c, true) || ownedCurrent && !ownedCurrent()) throw new PreEffectToolRefusal("execution lineage owner changed; reconnect in the current project session");
244
+ };
245
+ const op = msg.t === "lineage_show" ? "hub_lineage_show" : "hub_lineage_link";
246
+ try { current(); } catch (error) { return void reply({ ok: false, error: (error as Error).message }); }
247
+ // A pure read is checked and serialized in this stack, without a new policy-change await.
248
+ if (op === "hub_lineage_show") return void reply(scope.executionLineageRead(actor, input));
249
+ void scope.childToolAuthority.run({ by: actor, current: () => { try { current(); return true; } catch { return false; } } }, () => scope.taskOp(actor, op, input)).then(
250
+ text => { try { current(); reply(JSON.parse(text)); } catch { reply({ ok: false, error: "execution lineage caller changed; reconnect and retry" }); } },
251
+ error => reply({ ok: false, error: error instanceof Error ? error.message : "execution lineage unavailable; inspect the project task and retry" }));
252
+ return;
253
+ }
254
+ }
255
+
256
+ // task
257
+ export function taskMessage(ds: DaemonScope, m: ControlMessage): void {
258
+ const { sock, c, msg, reply } = m;
259
+ const runTaskRequest = (run: () => Promise<string>, extraCurrent: () => void = () => {}, formatError: (error: unknown) => Record<string, unknown> = error => ({ t: "task", ok: false, error: error instanceof Error ? error.message : "task write refused" })): void => {
260
+ const operation = toolWriteOperation(msg);
261
+ const payload = { t: "task", op: msg.op, args: msg.args ?? {} };
262
+ const actor = c.peer ?? USER, args = payload.args && typeof payload.args === "object" && !Array.isArray(payload.args) ? payload.args as Record<string, unknown> : {};
263
+ const knownPreEffectRefusal = operation !== undefined && (
264
+ ds.readOnlyPeer(actor) && !ds.readOnlyHubTools.has(operation)
265
+ || operation === "hub_task_propose" && (!ds.may(actor, "propose") || (() => {
266
+ const owner = typeof args.owner === "string" ? args.owner.trim().toLowerCase() : "";
267
+ return !!owner && ds.peerIdPattern.test(owner) && ![actor, USER, HUB, "digest"].includes(owner) && !ds.may(actor, "assign");
268
+ })())
269
+ || operation === "hub_review" && actor !== USER && (() => {
270
+ const id = ds.taskWriteId(args.id);
271
+ if (id === undefined || id < 1) return false;
272
+ const task = ds.board.get(id);
273
+ return !!task && task.reviewer !== actor;
274
+ })()
275
+ );
276
+ if (!operation || msg.requestId === undefined || knownPreEffectRefusal) {
277
+ void run().then(text => reply({ t: "task", ok: true, text }), error => reply(formatError(error)));
278
+ return;
279
+ }
280
+ const scope = ds.toolWriteScope(c, operation);
281
+ void ds.toolWriteRegistry.run({ id: msg.requestId, scope, bucket: actor, payload,
282
+ current: result => ds.toolWriteCurrent(c, sock, operation, payload, scope, result) && (() => { try { extraCurrent(); return true; } catch { return false; } })(),
283
+ }, async () => {
284
+ try { return { t: "task", ok: true, text: await run() }; }
285
+ catch (error) {
286
+ if (error instanceof PreEffectToolRefusal || error instanceof OperationalAuthorityError) return formatError(error);
287
+ throw error;
288
+ }
289
+ }).then(result => reply(result), () => reply(toolWriteUnknownReply(payload, typeof msg.requestId === "string" ? msg.requestId : undefined)));
290
+ };
291
+ if (c.role === "tools" && msg.op === "task_unassign") {
292
+ if (conductorPeer(ds.config.roles) !== c.peer) return void reply({ t: "task", ok: false, error: "task_unassign is a console command" });
293
+ try {
294
+ const current = ds.admitOperational(sock, "task unassign");
295
+ void ds.childToolAuthority.run({ by: c.peer!, current: () => { current(); return true; } },
296
+ () => ds.taskOp(c.peer!, "task_unassign", msg.args ?? {})).then(
297
+ text => reply({ t: "task", ok: true, text }),
298
+ error => reply({ t: "task", ok: false, error: error instanceof Error ? error.message : "unassign refused" }));
299
+ } catch (error) { reply({ t: "task", ok: false, error: error instanceof Error ? error.message : "unassign refused" }); }
300
+ return;
301
+ }
302
+ if (c.role === "tools" && msg.op === "release_show") {
303
+ try { const current = ds.publicReadCurrent(sock); current(); const release = publicReleaseShow(ds, msg.args ?? {}); current(); return void reply({ t: "task", ok: true, text: JSON.stringify(release) }); }
304
+ catch { return void reply({ t: "task", ok: false, error: "public release read unavailable" }); }
305
+ }
306
+ // #601: ahub study is the person's. A tools connection (any agent) may use the hub_study_* tools, never these op names, whatever Tasks would answer.
307
+ if ((msg.op === "study_evidence" || msg.op === "study_check") && c.role !== "console") return void reply({ t: "task", ok: false, error: "task inventory and synthesis checks are console commands; ask the person to run ahub study evidence --task or ahub study check; a single link is readable through hub_evidence_read" });
308
+ if (String(msg.op).startsWith("study_") && c.role !== "console") return void reply({ t: "task", ok: false, error: "ahub study draft, revise, approve and close are console commands; agents use the hub_study_* tools" });
309
+ if (msg.op === "hub_ask_answer" && c.role !== "tools") return void reply({ t: "task", ok: false, error: "instructed answers require the conductor tools connection; the person can use ahub console" });
310
+ if (msg.op === "hub_ask_answer" && (c.toolsOwner || c.externalOwner)) return void reply({ t: "task", ok: false, error: "delegated runs cannot record person answers; use ahub console" });
311
+ if (c.toolsOwner && !IMPLEMENTER_HUB_TOOL_NAMES.includes(String(msg.op))) return void reply({ t: "task", ok: false, error: "tool is not available to this Claude implementer child" });
312
+ if (ds.recoveryActive() && ds.recoveryPhase !== "preparing" && String(msg.op) !== "hub_checkpoint") return void reply({ t: "task", ok: false, error: msg.op === "hub_visual" || msg.op === "hub_visual_show" ? ds.visualOperational("recovery").message : "recovery is holding mutations" });
313
+ if (c.role === "tools" && c.peer && Object.hasOwn(CONDUCTOR_TASK_OPS, String(msg.op))) {
314
+ // #933: a console task op the conductor may run: admitted (role recheck and one audit row) before Tasks sees it; Tasks asks `operational` again.
315
+ let current: () => void;
316
+ try { current = ds.admitOperational(sock, CONDUCTOR_TASK_OPS[String(msg.op)]!); } catch (error) { return void reply({ t: "task", ...ds.operationalFailure(error) }); }
317
+ runTaskRequest(() => ds.operationalContext.run({ actor: c.peer!, current }, () => ds.taskOp(c.peer!, String(msg.op), msg.args ?? {})), current,
318
+ error => ({ t: "task", ...ds.operationalFailure(error) }));
319
+ return;
320
+ }
321
+ let invocation: AbortController | undefined;
322
+ if (msg.op === "hub_invoke" || msg.op === "hub_ask") {
323
+ if (!Number.isSafeInteger(msg.rid) || msg.rid < 1) return void reply({ t: "task", ok: false, error: msg.op === "hub_ask" ? "a question requires a request id; call hub_ask through the hub's tool, not a raw message" : "invocation requires a request id" });
324
+ c.invocationRequests ??= new Map();
325
+ const previous = c.invocationRequests.get(msg.rid);
326
+ if (previous) { previous.abort(); return void reply({ t: "task", ok: false, error: "duplicate invocation request id" }); }
327
+ if (c.closed || sock.readyState !== WebSocket.OPEN || c.invocationRequests.size >= 64) return void reply({ t: "task", ok: false, error: "invocation request connection unavailable" });
328
+ invocation = new AbortController(); c.invocationRequests.set(msg.rid, invocation);
329
+ }
330
+ const dispatch = () => ds.taskOp(c.peer ?? USER, String(msg.op), msg.args ?? {}, false, false, sock);
331
+ const run = async () => c.externalOwner ? ds.childToolAuthority.run({ by: c.peer!, current: () => ds.currentExternalTools(c, true) }, dispatch) : c.toolsOwner ? ds.childToolAuthority.run({ by: c.peer!, current: ds.captureImplementerTools(c) }, dispatch) : dispatch();
332
+ const execute = () => (invocation ? ds.invocationRequestSignal.run({ signal: invocation.signal, current: () => {
333
+ const live = !c.closed && sock.readyState === WebSocket.OPEN && c.invocationRequests?.get(msg.rid) === invocation;
334
+ if (!live) invocation?.abort();
335
+ return live;
336
+ } }, run) : run());
337
+ if (invocation) void execute().then(text => reply({ t: "task", ok: true, text }), (error: Error) => reply({ t: "task", ok: false, error: error.message }))
338
+ .finally(() => { if (c.invocationRequests?.get(msg.rid) === invocation) c.invocationRequests.delete(msg.rid); });
339
+ else runTaskRequest(execute);
340
+ return;
341
+ }
342
+
343
+ // goal_link
344
+ export function goalLink(scope: DaemonScope, m: ControlMessage): void {
345
+ const { sock, c, msg, reply } = m;
346
+ if (c.role !== "console" && c.role !== "tools") return void reply({ t: msg.t, ok: false, error: "goal_link is a console command" });
347
+ try {
348
+ if (c.role === "tools") scope.admitOperational(sock, "goal link");
349
+ const text = scope.tasks.linkGoal(c.role === "console" ? USER : c.peer!, msg.task, msg.goal);
350
+ const linked = scope.board.get(Number(msg.task));
351
+ if (linked?.state === "in_progress" && !scope.tasks.isPii(linked)) scope.renewLeases(linked); // already being worked on: hold it now
352
+ return void reply({ t: msg.t, ok: true, text });
353
+ }
354
+ catch (e) { return void reply({ t: msg.t, ...scope.operationalFailure(e) }); }
355
+ }
356
+
357
+ // board_revision
358
+ export function boardRevision(scope: DaemonScope, m: ControlMessage): void {
359
+ const { c, reply } = m;
360
+ {
361
+ if (c.role !== "console") return void reply({ t: "board_revision", ok: false, error: "the board revision is read by the console" });
362
+ return void reply({ t: "board_revision", ok: true, boardRevision: scope.board.statusRevision() });
363
+ }
364
+ }
365
+
366
+ // task_handoff
367
+ export function taskHandoff(scope: DaemonScope, m: ControlMessage): void {
368
+ const { c, msg, reply } = m;
369
+ {
370
+ if (c.role !== "console") return void reply({ t: "task_handoff", ok: false, error: "a handoff comes from another project's hub, not from an agent connection" });
371
+ if (scope.recoveryActive()) return void reply({ t: "task_handoff", ok: false, error: "recovery is holding mutations; hand the task off again after it ends" });
372
+ // Counted like a task op: a recovery commit waits for it (`recoveryReady` reads `taskOpsInFlight`), and the fence is asked again right before the board write, after the PII screen.
373
+ scope.taskOpsInFlight++;
374
+ const recoveryFence = (): string | undefined => scope.recoveryActive() || scope.stopping ? "recovery or shutdown is holding mutations; hand the task off again after it ends" : undefined;
375
+ void Promise.resolve(scope.startupSpecPending() ? scope.firstSpecProbe : undefined).then(() => scope.tasks.handoffIn(msg.origin ?? {}, msg.request, recoveryFence)).then(
376
+ result => reply({ t: "task_handoff", ok: true, ...result }),
377
+ error => reply({ t: "task_handoff", ok: false, error: error instanceof HandoffRefusal ? error.message : "the handoff was refused" })).finally(() => { scope.taskOpsInFlight--; });
378
+ return;
379
+ }
380
+ }
381
+
382
+ // task_handoff_event
383
+ export function taskHandoffEvent(scope: DaemonScope, m: ControlMessage): void {
384
+ const { c, msg, reply } = m;
385
+ {
386
+ if (c.role !== "console") return void reply({ t: "task_handoff_event", ok: false, error: "a handoff event comes from another project's hub, not from an agent connection" });
387
+ try { reply({ t: "task_handoff_event", ok: true, ...scope.tasks.handoffEvent(msg.event) }); }
388
+ catch (error) { reply({ t: "task_handoff_event", ok: false, error: error instanceof HandoffRefusal ? error.message : "the handoff event was refused" }); }
389
+ return;
390
+ }
391
+ }
392
+
393
+ // task_handoff_by_key
394
+ export function taskHandoffByKey(scope: DaemonScope, m: ControlMessage): void {
395
+ const { c, msg, reply } = m;
396
+ {
397
+ // #731: the origin whose request got no answer asks where the task its key made stands. Console role only, only for the asking project's own key, and nothing is written.
398
+ if (c.role !== "console") return void reply({ t: "task_handoff_by_key", ok: false, error: "a handoff key lookup comes from another project's hub, not from an agent connection" });
399
+ try { const found = scope.tasks.handoffStateByKey(msg.projectId, msg.key); reply({ t: "task_handoff_by_key", ok: true, found: found !== undefined, ...(found ?? {}) }); }
400
+ catch (error) { reply({ t: "task_handoff_by_key", ok: false, error: error instanceof HandoffRefusal ? error.message : "the handoff key lookup was refused" }); }
401
+ return;
402
+ }
403
+ }
404
+
405
+ // task_handoff_states
406
+ export function taskHandoffStates(scope: DaemonScope, m: ControlMessage): void {
407
+ const { c, msg, reply } = m;
408
+ {
409
+ // #604: the origin asks, after a restart, where the tasks it handed us stand now. Console role only, and only for tasks whose recorded origin is the asking project.
410
+ if (c.role !== "console") return void reply({ t: "task_handoff_states", ok: false, error: "a handoff state request comes from another project's hub, not from an agent connection" });
411
+ try { reply({ t: "task_handoff_states", ok: true, states: scope.tasks.handoffStatesFor(msg.projectId, msg.tasks) }); }
412
+ catch (error) { reply({ t: "task_handoff_states", ok: false, error: error instanceof HandoffRefusal ? error.message : "the handoff state request was refused" }); }
413
+ return;
414
+ }
415
+ }