@staix/agent-hub 0.50.0 → 0.52.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 (350) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/README.md +1 -1
  3. package/docs/adding-an-ai-tool.md +26 -4
  4. package/docs/agent-notes/README.md +1 -0
  5. package/docs/agent-notes/adapters.md +4 -3
  6. package/docs/agent-notes/budget.md +8 -2
  7. package/docs/agent-notes/daemon.md +13 -8
  8. package/docs/agent-notes/local-worker.md +3 -3
  9. package/docs/agent-notes/security-review.md +6 -5
  10. package/docs/agent-notes/tasks.md +10 -3
  11. package/docs/agent-notes/tests.md +4 -3
  12. package/docs/cooperbench.md +1 -1
  13. package/docs/design/adapters.md +21 -0
  14. package/docs/design/cli-output-inventory.md +165 -150
  15. package/docs/design/cli-output.md +4 -3
  16. package/docs/design/guidance-probes.md +1 -0
  17. package/docs/design/roadmap.md +3 -1
  18. package/docs/design/task-board.md +35 -0
  19. package/docs/dogfood.md +21 -3
  20. package/docs/events.md +4 -2
  21. package/docs/memory.md +5 -3
  22. package/docs/operations.md +259 -19
  23. package/docs/quickstart.md +29 -2
  24. package/docs/roadmap.json +20 -20
  25. package/docs/roadmap.md +2 -2
  26. package/docs/roles.md +1 -1
  27. package/docs/sdlc.md +29 -5
  28. package/docs/security.md +11 -5
  29. package/docs/specs/2026-09-19-agent-hub-design.md +44 -0
  30. package/docs/specs/2026-09-19-multi-project-design.md +4 -0
  31. package/docs/specs/2026-09-20-upgrade-recovery-design.md +17 -0
  32. package/docs/specs/mcp-endpoint.md +63 -0
  33. package/docs/verification/2026-11-29-agy-1.5.20.md +33 -0
  34. package/docs/verification/2026-11-29-claude-profile-hook.md +12 -0
  35. package/docs/verification/2026-11-29-idle-daemon-footprint.md +75 -0
  36. package/docs/verification/2026-11-29-kimi-281-reviewer-compat.md +38 -0
  37. package/docs/verification/2026-11-29-kimi-tui-281.md +12 -0
  38. package/docs/verification/2026-11-30-0.51.0.md +91 -0
  39. package/docs/verification/2026-11-30-account-switch-1806.md +445 -0
  40. package/docs/verification/2026-11-30-capability-listing-shape-1808.md +45 -0
  41. package/docs/verification/2026-11-30-upgrade-keep-1807.md +174 -0
  42. package/docs/verification/2026-12-01-1811-confirmation-receipt.md +19 -0
  43. package/docs/verification/2026-12-01-1811-orca-agent-list.md +20 -0
  44. package/docs/verification/2026-12-01-1811-orca-pane-key.md +21 -0
  45. package/docs/verification/2026-12-02-1819-claude-process-after-renewal.md +54 -0
  46. package/docs/verification/2026-12-02-agy-1.5.21.md +74 -0
  47. package/docs/verification/2026-12-02-claude-implementer-2.1.334.md +44 -0
  48. package/docs/verification/2026-12-02-cli-import-graph.md +33 -0
  49. package/docs/verification/2026-12-03-0.52.0.md +150 -0
  50. package/docs/verification/2026-12-03-codex-0173-reviewer-isolation.md +53 -0
  51. package/docs/verification/2026-12-03-codex-0173-reviewer-tool-call.md +34 -0
  52. package/docs/verification/2026-12-03-jcode-1.3.0.md +25 -0
  53. package/docs/verification/agy/README.md +17 -0
  54. package/docs/verification/agy/cli-surface.ts +68 -0
  55. package/docs/verification/agy/interactive-bridge.ts +92 -0
  56. package/docs/verification/agy/interactive-session.ts +131 -0
  57. package/docs/verification/agy/launcher-nonce.ts +215 -0
  58. package/docs/verification/agy/native-hooks.ts +210 -0
  59. package/docs/verification/agy/originals/agent-hub-681/cli-surface.ts +87 -0
  60. package/docs/verification/agy/originals/agent-hub-681/native-hooks-adapted.ts +91 -0
  61. package/docs/verification/agy/originals/agent-hub-681/tui-actual.ts +200 -0
  62. package/docs/verification/agy/originals/agent-hub-684/probe.ts +107 -0
  63. package/docs/verification/agy/originals.json +25 -0
  64. package/docs/verification/agy/permission-new-functions.ts +128 -0
  65. package/docs/verification/agy/run-probe.py +108 -0
  66. package/docs/verification/agy/runtime.ts +171 -0
  67. package/docs/verification/agy/tmux-helper-control.ts +6 -0
  68. package/docs/verification/agy/tmux-session.ts +235 -0
  69. package/docs/verified.json +87 -42
  70. package/package.json +3 -3
  71. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  72. package/plugins/agent-hub/compat.json +157 -0
  73. package/plugins/agent-hub/kimi-hook.js +1416 -24985
  74. package/plugins/agent-hub/server.js +17415 -32755
  75. package/scripts/check-docs.mjs +1 -1
  76. package/src/adapters/acp.ts +13 -13
  77. package/src/adapters/agy/definition.ts +9 -26
  78. package/src/adapters/agy/entry.ts +2 -0
  79. package/src/adapters/channel-peer.ts +3 -1
  80. package/src/adapters/claude-channel-evidence.ts +7 -3
  81. package/src/adapters/claude-channel.ts +38 -257
  82. package/src/adapters/claude-implementer.ts +3 -1
  83. package/src/adapters/codex-appserver.ts +77 -15
  84. package/src/adapters/compat.ts +78 -14
  85. package/src/adapters/configured-acp.ts +23 -163
  86. package/src/adapters/configured-adapter-policy.ts +160 -0
  87. package/src/adapters/configured-pull-entry.ts +53 -0
  88. package/src/adapters/configured-pull.ts +38 -0
  89. package/src/adapters/conformance/fakes/app-server.ts +9 -2
  90. package/src/adapters/declaration-catalog.ts +25 -0
  91. package/src/adapters/declaration-data.ts +342 -0
  92. package/src/adapters/declaration-resolution.ts +53 -0
  93. package/src/adapters/definitions/builtin-metadata.ts +62 -84
  94. package/src/adapters/definitions/jcode-launch.ts +13 -0
  95. package/src/adapters/definitions/native-adapter-policy.ts +390 -0
  96. package/src/adapters/definitions/native-cli-claude-launch.ts +6 -3
  97. package/src/adapters/definitions/native-cli-codex-launch.ts +2 -1
  98. package/src/adapters/definitions/native-cli-entry-claude.ts +17 -2
  99. package/src/adapters/definitions/native-cli-entry-codex.ts +2 -0
  100. package/src/adapters/definitions/native-cli-entry-jcode.ts +6 -2
  101. package/src/adapters/definitions/native-cli-entry-kimi.ts +2 -0
  102. package/src/adapters/definitions/native-cli-entry-pi.ts +2 -0
  103. package/src/adapters/definitions/native-cli-entry-qwen.ts +2 -0
  104. package/src/adapters/definitions/native-cli-entry-types.ts +12 -3
  105. package/src/adapters/definitions/native-cli-jcode-home-init.ts +1 -1
  106. package/src/adapters/definitions/native-cli-launch-common.ts +2 -2
  107. package/src/adapters/definitions/native-cli-preview-common.ts +1 -1
  108. package/src/adapters/definitions/native-cli-retained.ts +1 -1
  109. package/src/adapters/definitions/native-config-defaults.ts +1 -1
  110. package/src/adapters/definitions/native-configuration.ts +18 -0
  111. package/src/adapters/definitions/native-help.ts +24 -0
  112. package/src/adapters/definitions/native-launch-declarations.ts +34 -0
  113. package/src/adapters/definitions/native-launch-policy.ts +4 -0
  114. package/src/adapters/definitions/native-launch-settings.ts +72 -0
  115. package/src/adapters/definitions/native-light-cli.ts +18 -0
  116. package/src/adapters/definitions/native-light-preview.ts +10 -0
  117. package/src/adapters/definitions/native-wrapper-launch.ts +10 -0
  118. package/src/adapters/definitions/qwen.ts +6 -29
  119. package/src/adapters/definitions/reviewer-variants.ts +7 -8
  120. package/src/adapters/external-declarations.ts +31 -0
  121. package/src/adapters/external-modules.ts +4 -29
  122. package/src/adapters/jcode.ts +19 -12
  123. package/src/adapters/native-capabilities.ts +18 -8
  124. package/src/adapters/native-facts-hooks.ts +12 -0
  125. package/src/adapters/native-proof-ports.ts +1 -1
  126. package/src/adapters/presets.ts +136 -0
  127. package/src/adapters/qwen-dual.ts +2 -2
  128. package/src/adapters/registry-types.ts +3 -0
  129. package/src/adapters/registry.ts +20 -81
  130. package/src/adapters/reviewer-print.ts +26 -9
  131. package/src/adapters/role-eligibility.ts +2 -1
  132. package/src/cli/accounts-import.ts +72 -0
  133. package/src/cli/agents-latest-table.ts +88 -0
  134. package/src/cli/agents-latest.ts +22 -0
  135. package/src/cli/agents-output.ts +10 -0
  136. package/src/cli/agents-presets.ts +100 -0
  137. package/src/cli/agents.ts +1 -1
  138. package/src/cli/attention.ts +3 -2
  139. package/src/cli/autonomy-homes.ts +7 -2
  140. package/src/cli/autonomy-offline.ts +1 -1
  141. package/src/cli/bench.ts +1 -1
  142. package/src/cli/budget-renew-guidance.ts +129 -0
  143. package/src/cli/claude-homes.ts +9 -5
  144. package/src/cli/claude-profile-hook.ts +31 -11
  145. package/src/cli/command-context.ts +3 -0
  146. package/src/cli/command-table.ts +123 -0
  147. package/src/cli/commands/accounts.ts +8 -0
  148. package/src/cli/commands/agents.ts +18 -0
  149. package/src/cli/commands/answer.ts +28 -0
  150. package/src/cli/commands/ask.ts +17 -0
  151. package/src/cli/commands/autonomy.ts +83 -0
  152. package/src/cli/commands/backlog.ts +46 -0
  153. package/src/cli/commands/bench.ts +60 -0
  154. package/src/cli/commands/board.ts +48 -0
  155. package/src/cli/commands/broker.ts +9 -0
  156. package/src/cli/commands/budget.ts +96 -0
  157. package/src/cli/commands/capabilities.ts +12 -0
  158. package/src/cli/commands/check-path.ts +55 -0
  159. package/src/cli/commands/completion.ts +8 -0
  160. package/src/cli/commands/console.ts +12 -0
  161. package/src/cli/commands/daemon.ts +8 -0
  162. package/src/cli/commands/deliverables.ts +25 -0
  163. package/src/cli/commands/doctor.ts +249 -0
  164. package/src/cli/commands/down.ts +3 -0
  165. package/src/cli/commands/export.ts +15 -0
  166. package/src/cli/commands/facts.ts +15 -0
  167. package/src/cli/commands/goal.ts +22 -0
  168. package/src/cli/commands/guidance.ts +102 -0
  169. package/src/cli/commands/help.ts +17 -0
  170. package/src/cli/commands/host.ts +45 -0
  171. package/src/cli/commands/init.ts +121 -0
  172. package/src/cli/commands/instructed.ts +19 -0
  173. package/src/cli/commands/instruction-hook.ts +15 -0
  174. package/src/cli/commands/intake.ts +24 -0
  175. package/src/cli/commands/kill.ts +15 -0
  176. package/src/cli/commands/learn.ts +23 -0
  177. package/src/cli/commands/lineage.ts +30 -0
  178. package/src/cli/commands/logs.ts +21 -0
  179. package/src/cli/commands/manager.ts +15 -0
  180. package/src/cli/commands/memory.ts +21 -0
  181. package/src/cli/commands/model.ts +25 -0
  182. package/src/cli/commands/models.ts +40 -0
  183. package/src/cli/commands/native.ts +39 -0
  184. package/src/cli/commands/pause.ts +5 -0
  185. package/src/cli/commands/peer.ts +32 -0
  186. package/src/cli/commands/permission.ts +26 -0
  187. package/src/cli/commands/permit.ts +12 -0
  188. package/src/cli/commands/pet.ts +24 -0
  189. package/src/cli/commands/projects.ts +49 -0
  190. package/src/cli/commands/queue.ts +70 -0
  191. package/src/cli/commands/recovery-run.ts +13 -0
  192. package/src/cli/commands/recovery.ts +130 -0
  193. package/src/cli/commands/release.ts +23 -0
  194. package/src/cli/commands/releases.ts +91 -0
  195. package/src/cli/commands/remember.ts +6 -0
  196. package/src/cli/commands/report.ts +27 -0
  197. package/src/cli/commands/research.ts +53 -0
  198. package/src/cli/commands/reset.ts +89 -0
  199. package/src/cli/commands/restart.ts +5 -0
  200. package/src/cli/commands/results.ts +31 -0
  201. package/src/cli/commands/resume.ts +5 -0
  202. package/src/cli/commands/review.ts +24 -0
  203. package/src/cli/commands/roadmap.ts +21 -0
  204. package/src/cli/commands/role.ts +34 -0
  205. package/src/cli/commands/roles.ts +30 -0
  206. package/src/cli/commands/room.ts +14 -0
  207. package/src/cli/commands/roster.ts +48 -0
  208. package/src/cli/commands/route.ts +9 -0
  209. package/src/cli/commands/say.ts +21 -0
  210. package/src/cli/commands/schedule.ts +17 -0
  211. package/src/cli/commands/sdlc.ts +321 -0
  212. package/src/cli/commands/settings.ts +148 -0
  213. package/src/cli/commands/setup.ts +89 -0
  214. package/src/cli/commands/shared-refusals.ts +25 -0
  215. package/src/cli/commands/smoke.ts +44 -0
  216. package/src/cli/commands/source.ts +64 -0
  217. package/src/cli/commands/specs.ts +13 -0
  218. package/src/cli/commands/status.ts +28 -0
  219. package/src/cli/commands/stop.ts +17 -0
  220. package/src/cli/commands/structure.ts +60 -0
  221. package/src/cli/commands/study.ts +39 -0
  222. package/src/cli/commands/tail.ts +19 -0
  223. package/src/cli/commands/task.ts +114 -0
  224. package/src/cli/commands/title.ts +17 -0
  225. package/src/cli/commands/turns.ts +10 -0
  226. package/src/cli/commands/ui.ts +47 -0
  227. package/src/cli/commands/undo.ts +77 -0
  228. package/src/cli/commands/up.ts +39 -0
  229. package/src/cli/commands/upgrade.ts +5 -0
  230. package/src/cli/commands/usage.ts +33 -0
  231. package/src/cli/commands/version.ts +5 -0
  232. package/src/cli/commands/watch.ts +30 -0
  233. package/src/cli/commands/worktrees.ts +31 -0
  234. package/src/cli/conductor-recovery.ts +1 -1
  235. package/src/cli/console-state.ts +5 -138
  236. package/src/cli/console-versions.ts +1 -1
  237. package/src/cli/facts-hook.ts +11 -4
  238. package/src/cli/help.ts +44 -20
  239. package/src/cli/identity.ts +27 -4
  240. package/src/cli/init-prompt.ts +1 -1
  241. package/src/cli/init-settings.ts +4 -35
  242. package/src/cli/init.ts +1 -1
  243. package/src/cli/json-text-spans.ts +57 -0
  244. package/src/cli/launch-check.ts +156 -0
  245. package/src/cli/launch.ts +19 -70
  246. package/src/cli/light-dispatch.ts +29 -0
  247. package/src/cli/main.js +8 -1
  248. package/src/cli/main.ts +257 -2799
  249. package/src/cli/memory.ts +1 -1
  250. package/src/cli/orca-probe.ts +119 -0
  251. package/src/cli/output.ts +45 -3
  252. package/src/cli/preview.ts +11 -6
  253. package/src/cli/recovery-launch.ts +1 -1
  254. package/src/cli/recovery-version-preflight.ts +28 -9
  255. package/src/cli/replace-process.ts +22 -0
  256. package/src/cli/report-layout.ts +142 -0
  257. package/src/cli/roadmap-usage.ts +16 -0
  258. package/src/cli/roadmap.ts +3 -16
  259. package/src/cli/sdlc-doctor.ts +27 -0
  260. package/src/cli/sdlc-output.ts +55 -1
  261. package/src/cli/setup-homes.ts +2 -2
  262. package/src/cli/start-agents-run.ts +85 -7
  263. package/src/cli/start-check.ts +28 -0
  264. package/src/cli/statusline-tee.ts +25 -4
  265. package/src/cli/terminal-recovery.ts +53 -10
  266. package/src/cli/upgrade-interactive.ts +1 -0
  267. package/src/cli/upgrade-runtime.ts +12 -1
  268. package/src/cli/upgrade.ts +4 -15
  269. package/src/cli/warn-line.ts +1 -1
  270. package/src/hub/accounts.ts +148 -0
  271. package/src/hub/addons.ts +20 -0
  272. package/src/hub/agent-drift.ts +2 -1
  273. package/src/hub/budget-projection.ts +39 -7
  274. package/src/hub/budget.ts +231 -16
  275. package/src/hub/channel-project.ts +3 -3
  276. package/src/hub/ci-watch.ts +311 -79
  277. package/src/hub/conductor-peer.ts +24 -0
  278. package/src/hub/conductor.ts +2 -21
  279. package/src/hub/config-apply.ts +25 -14
  280. package/src/hub/config-edit.ts +1 -1
  281. package/src/hub/config-tier.ts +2 -0
  282. package/src/hub/config.ts +535 -0
  283. package/src/hub/control-client.ts +49 -1
  284. package/src/hub/daemon.ts +492 -569
  285. package/src/hub/delivery-public.ts +11 -0
  286. package/src/hub/events.ts +3 -0
  287. package/src/hub/home-tag.ts +12 -0
  288. package/src/hub/host.ts +217 -0
  289. package/src/hub/hub-check.ts +125 -0
  290. package/src/hub/hub-tools.ts +2 -1
  291. package/src/hub/instance-budget.ts +2 -2
  292. package/src/hub/instance-config.ts +15 -126
  293. package/src/hub/instances.ts +22 -6
  294. package/src/hub/instruction-receipt.ts +2 -2
  295. package/src/hub/kimi-usage.ts +38 -11
  296. package/src/hub/lifecycle.ts +86 -4
  297. package/src/hub/mcp-bridge-core.ts +98 -0
  298. package/src/hub/mcp-channel-push.ts +20 -0
  299. package/src/hub/mcp-endpoint-serve.ts +178 -0
  300. package/src/hub/mcp-endpoint.ts +226 -0
  301. package/src/hub/mcp-tool-call.ts +181 -0
  302. package/src/hub/operational-settings.ts +2 -0
  303. package/src/hub/orca-env.ts +6 -0
  304. package/src/hub/orca-state.ts +84 -0
  305. package/src/hub/path-policy.ts +1 -1
  306. package/src/hub/peers.ts +5 -1
  307. package/src/hub/permission-mode.ts +5 -41
  308. package/src/hub/permission-paths.ts +41 -0
  309. package/src/hub/project.ts +20 -0
  310. package/src/hub/protocol-window.ts +58 -0
  311. package/src/hub/quota-origin.ts +20 -0
  312. package/src/hub/recovery-policy.ts +1 -1
  313. package/src/hub/registry.ts +36 -2
  314. package/src/hub/releases-inventory.ts +198 -0
  315. package/src/hub/report.ts +1 -1
  316. package/src/hub/research.ts +1 -1
  317. package/src/hub/review-brief.ts +47 -2
  318. package/src/hub/roster.ts +6 -3
  319. package/src/hub/routing.ts +9 -2
  320. package/src/hub/runtime-capture-prune.ts +25 -3
  321. package/src/hub/runtime-prune-health.ts +8 -1
  322. package/src/hub/sdlc-check.ts +205 -0
  323. package/src/hub/sdlc-release-authorization.ts +42 -21
  324. package/src/hub/sdlc-release-diagnostics.ts +5 -0
  325. package/src/hub/sdlc-release-policy.ts +21 -7
  326. package/src/hub/sdlc-release.ts +80 -20
  327. package/src/hub/sdlc-sync.ts +146 -0
  328. package/src/hub/sdlc.ts +38 -5
  329. package/src/hub/settings.ts +7 -4
  330. package/src/hub/start-agents.ts +1 -1
  331. package/src/hub/start-mode.ts +11 -4
  332. package/src/hub/structure-budget.ts +131 -0
  333. package/src/hub/structure-scan.ts +149 -0
  334. package/src/hub/tasks-experiment.ts +455 -0
  335. package/src/hub/tasks-guidance.ts +606 -0
  336. package/src/hub/tasks-roadmap-plan.ts +419 -0
  337. package/src/hub/tasks-roadmap.ts +491 -0
  338. package/src/hub/tasks-study.ts +661 -0
  339. package/src/hub/tasks-survey.ts +192 -0
  340. package/src/hub/tasks.ts +457 -2584
  341. package/src/hub/terminal-open.ts +5 -3
  342. package/src/hub/tooling.ts +3 -19
  343. package/src/hub/usage-rollup.ts +9 -3
  344. package/src/local/tools.ts +5 -0
  345. package/src/ui/index.html +1 -1
  346. package/src/ui/needs.ts +17 -5
  347. package/src/ui/peer-palette.ts +2 -4
  348. package/src/ui/plugin.ts +1 -1
  349. package/templates/presets/agents.json +60 -0
  350. package/templates/presets/confirmation-matrix.json +8 -8
@@ -0,0 +1,455 @@
1
+ // #1830 S4c: the experiment, execution lineage and execution link methods of `Tasks`, moved whole. `Tasks` builds one `ExperimentDomain` with its deps and an explicit host (the callbacks the moved bodies reach), keeps a one-line
2
+ // delegating method for each member it or a caller still uses, and stays the only board writer. No module-level state.
3
+ import { executionOwnerSnapshot, parseOwnerLineageQuery, type ExecutionLineageOwnerPorts } from "./execution-lineage-owner.ts";
4
+ import { readExecutionLineage, type LineageResult } from "./execution-lineage.ts";
5
+ import { parseExecutionLinkInput, taskExecutionReference, executionLinkActor, type ExecutionLinkInput } from "./execution-links.ts";
6
+ import { executionReferenceKey, type ExecutionReferenceV1 } from "./execution-reference.ts";
7
+ import { parseAttemptReceipt, parseResearchRunners, verifyAttemptReceipt } from "./research-runner.ts";
8
+ import { createHash, randomBytes } from "node:crypto";
9
+ import { canonicalJson } from "./packs.ts";
10
+ import { parseExperimentProtocol, parseExperimentAttempt, parseExperimentEvent, protocolHash, checkRunObservation, deliverableObservation, projectExperimentWithObservations, projectRunnerReceipt, type ExperimentProtocolContract, type ExperimentProtocolRecord, type ExperimentAttemptRecord, type ExperimentWriteFence, type ExperimentHostEvidence, type ExperimentStatus } from "./research-experiments.ts";
11
+ import { parseComparisonPlan, comparisonPlanHash, comparisonProjection, evaluatorIdentityHash, protocolApprovalBindingMatches, type ComparisonPlanV1 } from "./research-experiments.ts";
12
+ import { campaignHash } from "./research-campaign.ts";
13
+ import type { ResearchCampaignRecord } from "./board.ts";
14
+ import { matchesPolicyLexically } from "./path-policy.ts";
15
+ import { latestDeliverables } from "./deliverables.ts";
16
+ import { hashDeliverables, type DeliverablePorts } from "./deliverable-files.ts";
17
+ import { resolve } from "node:path";
18
+ import { looksSecret } from "@staix/agent-mem";
19
+ import { type Board, type Task } from "./board.ts";
20
+ import { HUB, USER, type PeerId } from "./envelope.ts";
21
+ import type { PiiVerdict, ScreenItem } from "./inference.ts";
22
+ import { ownerRoleOfClass } from "./routing.ts";
23
+ import { TaskRepositories } from "./task-repository.ts";
24
+ import { PreEffectToolRefusal } from "./tool-refusal.ts";
25
+ import type { TasksDeps } from "./tasks.ts";
26
+
27
+ export interface ExperimentReceipt { kind: "protocol" | "attempt" | "event" | "receipt"; protocolHash: string; attemptId?: string; seq?: number; receiptId?: string }
28
+ export interface ComparisonPlanReceipt { kind: "plan"; planHash: string }
29
+ export interface ProtocolApprovalReceipt { protocolHash: string; evaluatorHash: string; approvedBy: string; approvedAt: number }
30
+ export interface ExperimentAttemptView {
31
+ id: string; protocolHash: string; taskId: number; phase: "development" | "final"; status: ExperimentStatus; private: boolean;
32
+ protocol: unknown; events: unknown[]; evidence: Record<string, unknown>; eventsComplete: boolean; nextEventCursor?: number;
33
+ campaignRevision: number; approval: "approved" | "unapproved"; postHoc: "unknown" | "predeclared" | "post-hoc";
34
+ retryOf?: string; reproducesAttemptId?: string; independentlyReproduced: false;
35
+ }
36
+ export interface ExperimentView { attempts: ExperimentAttemptView[]; counts: { all: number; statuses: Record<ExperimentStatus, number> }; nextCursor?: number;
37
+ comparison?: { planHash: string; baselineAttemptId: string; variantAttemptId: string; approved: boolean; private: boolean; projection: ReturnType<typeof comparisonProjection> | "[pii]" } }
38
+ interface ExperimentContext { task: Task; campaign: ResearchCampaignRecord; private: boolean; key: string; fence: ExperimentWriteFence }
39
+
40
+ export interface ExperimentHost {
41
+ taskShowAllowed(actor: string, task: Pick<Task, "state" | "owner" | "reviewer">, roles: unknown, planner: boolean): boolean;
42
+ deliverablePorts: (task: Task, policy?: { failClosedOnDiscoveryLimit?: boolean; }) => DeliverablePorts;
43
+ experimentOutputPrivate: (task: Task, path: string) => boolean;
44
+ isConfiguredPlanner: (peer: PeerId) => boolean;
45
+ readonly isPii: (task: Pick<Task, "signals">) => boolean;
46
+ readonly nameable: (t: string) => boolean;
47
+ readonly publicMetadataText: (text: string) => boolean;
48
+ readonly repositories: TaskRepositories;
49
+ requireLocalTaskPeer(peer: unknown): void;
50
+ requestCheck: (by: PeerId, fence?: () => string | undefined) => () => void;
51
+ reviewTaskPrivate: (task: Task) => boolean;
52
+ screenCall: (text: string) => Promise<PiiVerdict>;
53
+ readonly screenOn: () => boolean;
54
+ studyFields: (input: unknown, allowed: readonly string[]) => Record<string, unknown>;
55
+ studyHold: () => string | undefined;
56
+ studyId: (value: unknown) => string;
57
+ studyNumber: (value: unknown, field: string) => number;
58
+ studyParent: (id: number) => Task;
59
+ studyRecord: (id: string, revision?: number) => ResearchCampaignRecord;
60
+ studyReplayPrivacy: (record: ResearchCampaignRecord, parent: Task) => boolean;
61
+ studySource: (id: string) => { id: string; sha256: string; private: boolean; } | undefined;
62
+ studyTime: () => number;
63
+ studyWrite: <T>(write: () => Promise<T>) => Promise<T>;
64
+ withholds: (item: ScreenItem, text: unknown, task?: Task) => Promise<boolean>;
65
+ }
66
+
67
+ export class ExperimentDomain {
68
+ constructor(private readonly d: TasksDeps, private readonly host: ExperimentHost) {}
69
+
70
+ experimentHash(input: unknown): string { return createHash("sha256").update(canonicalJson(input)).digest("hex"); }
71
+ experimentId(input: unknown): string {
72
+ if (typeof input !== "string" || !/^ra-[a-f0-9]{12}$/.test(input)) throw new PreEffectToolRefusal("experiment identity is invalid");
73
+ return input;
74
+ }
75
+ experimentProtocol(hash: string): ExperimentProtocolRecord {
76
+ try {
77
+ const record = this.d.board.experimentProtocol(hash);
78
+ if (record?.project === this.d.project) return record;
79
+ } catch { /* damaged records are never returned as evidence */ }
80
+ throw new PreEffectToolRefusal("experiment protocol is unavailable in this project");
81
+ }
82
+ experimentAttempt(id: string): ExperimentAttemptRecord {
83
+ try {
84
+ const record = this.d.board.experimentAttempt(id);
85
+ if (record?.project === this.d.project) return record;
86
+ } catch { /* fail closed without including any stored body */ }
87
+ throw new PreEffectToolRefusal("experiment attempt is unavailable in this project");
88
+ }
89
+ experimentContext(by: PeerId, taskId: number, protocol: ExperimentProtocolContract, recordedForTaskId = taskId): ExperimentContext {
90
+ const task = this.host.studyParent(taskId), bound = this.d.board.researchDispatchBinding(taskId);
91
+ if (task.owner !== by || task.state !== "in_progress") throw new PreEffectToolRefusal("experiment records require the current in-progress task owner");
92
+ if (this.d.privateTurn?.(by) && !this.host.isPii(task)) throw new PreEffectToolRefusal("a private turn cannot write experiment records on a public task");
93
+ const campaign = bound?.campaign;
94
+ // ponytail: new attempts against an older revision's protocol are refused; upgrade: explicit membership+source fence.
95
+ if (!bound?.binding || !campaign || campaign.project !== this.d.project || campaign.id !== protocol.campaignId || campaign.revision !== protocol.campaignRevision || campaign.status !== "approved")
96
+ throw new PreEffectToolRefusal("experiment task must be a unit of the protocol's current approved campaign revision");
97
+ const recording = this.d.board.researchDispatchBinding(recordedForTaskId), origin = this.host.studyParent(recordedForTaskId);
98
+ if (!recording?.binding || recording.campaign.id !== campaign.id || recording.campaign.revision !== campaign.revision || recording.campaign.status !== "approved")
99
+ throw new PreEffectToolRefusal("experiment recording task is no longer a unit of this campaign");
100
+ const sources = protocol.inputs.map(input => {
101
+ const source = this.host.studySource(input.sourceId);
102
+ if (!campaign.contract.sourceIds.includes(input.sourceId) || !source || source.sha256 !== input.sha256) throw new PreEffectToolRefusal("experiment input source identity or hash is unavailable in this campaign");
103
+ return source;
104
+ });
105
+ let artifactPrivate = false;
106
+ if ("deliverable" in protocol.code) {
107
+ const reference = protocol.code.deliverable, artifact = latestDeliverables(origin.history)?.find(value => value.id === reference.id && value.sha256 === reference.sha256);
108
+ if (!artifact) throw new PreEffectToolRefusal("experiment code deliverable identity is not recorded for its task");
109
+ artifactPrivate = artifact.private === true;
110
+ }
111
+ const privateRecord = this.host.studyReplayPrivacy(campaign, this.host.studyParent(campaign.parentTaskId)) || this.host.isPii(task) || this.host.isPii(origin) || artifactPrivate || sources.some(source => source.private);
112
+ const fence: ExperimentWriteFence = { project: this.d.project, taskId, taskFlowRevision: task.history.length, owner: by,
113
+ campaignId: campaign.id, campaignRevision: campaign.revision, campaignHash: campaign.hash };
114
+ return { task, campaign, private: privateRecord, fence, key: JSON.stringify([fence, sources, privateRecord, origin.history.length, recording.binding]) };
115
+ }
116
+ experimentFresh(before: ExperimentContext, by: PeerId, protocol: ExperimentProtocolContract, recordedForTaskId?: number): ExperimentContext {
117
+ const current = this.experimentContext(by, before.task.id, protocol, recordedForTaskId);
118
+ if (current.key !== before.key) throw new PreEffectToolRefusal("experiment authority, source or campaign changed during admission");
119
+ return current;
120
+ }
121
+ async experimentScreen(text: string, task: Task): Promise<void> {
122
+ if (!this.host.isPii(task) && (!this.host.nameable(text) || looksSecret(text) || await this.host.withholds("note", text, task)))
123
+ throw new PreEffectToolRefusal("experiment text was not cleared; nothing was recorded");
124
+ }
125
+ experimentPlanContext(by: PeerId, taskId: number, plan: ComparisonPlanV1): ExperimentContext {
126
+ const task = this.host.studyParent(taskId), bound = this.d.board.researchDispatchBinding(taskId), campaign = bound?.campaign;
127
+ if (task.owner !== by || task.state !== "in_progress" || !bound?.binding || !campaign || campaign.project !== this.d.project
128
+ || campaign.id !== plan.campaignId || campaign.status !== "approved")
129
+ throw new PreEffectToolRefusal("comparison plans require the current in-progress campaign unit owner");
130
+ if (this.d.privateTurn?.(by) && !this.host.isPii(task)) throw new PreEffectToolRefusal("a private turn cannot write comparison plans on a public task");
131
+ const sources = plan.fixed.inputs.map(input => {
132
+ const source = this.host.studySource(input.sourceId);
133
+ if (!campaign.contract.sourceIds.includes(input.sourceId) || !source || source.sha256 !== input.sha256)
134
+ throw new PreEffectToolRefusal("comparison input source identity or hash is unavailable in this campaign");
135
+ return source;
136
+ });
137
+ const privateRecord = this.host.studyReplayPrivacy(campaign, this.host.studyParent(campaign.parentTaskId)) || this.host.isPii(task) || sources.some(source => source.private);
138
+ const fence: ExperimentWriteFence = { project: this.d.project, taskId, taskFlowRevision: task.history.length, owner: by,
139
+ campaignId: campaign.id, campaignRevision: campaign.revision, campaignHash: campaign.hash };
140
+ return { task, campaign, private: privateRecord, fence, key: canonicalJson([fence, privateRecord, sources, bound.binding]) };
141
+ }
142
+ experimentApproved(record: ExperimentProtocolRecord): boolean {
143
+ const approval = this.d.board.experimentProtocolApproval(record.hash);
144
+ return protocolApprovalBindingMatches(record.protocol, approval && { protocolHash: approval.protocolHash, evaluatorHash: approval.evaluatorHash });
145
+ }
146
+ /** Approval is an explicit person's decision about immutable bytes, including historical protocols. */
147
+ async experimentApproveProtocol(by: PeerId, input: unknown): Promise<ProtocolApprovalReceipt> {
148
+ const requestCheck = this.host.requestCheck(by, () => this.host.studyHold());
149
+ if (by !== USER) throw new PreEffectToolRefusal("protocol approval is person only");
150
+ const fields = this.host.studyFields(input, ["hash"]);
151
+ if (typeof fields.hash !== "string" || fields.hash.length !== 64 || !/^[a-f0-9]{64}$/.test(fields.hash)) throw new PreEffectToolRefusal("protocol approval needs an exact protocol hash");
152
+ const hash = fields.hash;
153
+ return this.host.studyWrite(async () => {
154
+ requestCheck();
155
+ const record = this.experimentProtocol(hash), evaluatorHash = evaluatorIdentityHash(record.protocol);
156
+ requestCheck();
157
+ let saved;
158
+ try { saved = this.d.board.approveExperimentProtocol(this.d.project, hash, evaluatorHash, by, this.host.studyTime()); }
159
+ catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "protocol approval was not saved"); }
160
+ return { protocolHash: saved.protocolHash, evaluatorHash: saved.evaluatorHash, approvedBy: saved.approvedBy, approvedAt: saved.at };
161
+ });
162
+ }
163
+ /** Record evidence only: this path never runs a check, a shell command or a runner. */
164
+ async experimentRecord(by: PeerId, input: { kind: "plan"; [key: string]: unknown }): Promise<ComparisonPlanReceipt>;
165
+ async experimentRecord(by: PeerId, input: { kind: "protocol" | "attempt" | "event" | "receipt"; [key: string]: unknown }): Promise<ExperimentReceipt>;
166
+ async experimentRecord(by: PeerId, input: unknown): Promise<ExperimentReceipt | ComparisonPlanReceipt>;
167
+ async experimentRecord(by: PeerId, input: unknown): Promise<ExperimentReceipt | ComparisonPlanReceipt> {
168
+ const requestCheck = this.host.requestCheck(by, () => this.host.studyHold());
169
+ const envelope = this.host.studyFields(input, ["kind", "taskId", "protocol", "attempt", "attemptId", "idempotencyKey", "event", "plan", "receipt", "signature"]);
170
+ return this.host.studyWrite(async () => {
171
+ try {
172
+ if (envelope.kind === "receipt") {
173
+ const fields = this.host.studyFields(input, ["kind", "receipt", "signature"]), receipt = parseAttemptReceipt(fields.receipt);
174
+ const attempt = this.experimentAttempt(receipt.attemptId), record = this.experimentProtocol(attempt.attempt.protocolHash);
175
+ const relayOwner = by === USER ? this.host.studyParent(attempt.attempt.taskId).owner : by;
176
+ if (!relayOwner) throw new PreEffectToolRefusal("receipt relay requires a current task owner");
177
+ const before = this.experimentContext(relayOwner, attempt.attempt.taskId, record.protocol, record.recordedForTaskId);
178
+ requestCheck();
179
+ const proof = (stored: NonNullable<ReturnType<Board["runnerReceipt"]>>): ExperimentReceipt => ({ kind: "receipt", protocolHash: record.hash,
180
+ attemptId: attempt.attemptId, seq: stored.seq, receiptId: receipt.receiptId });
181
+ const known = this.d.board.runnerReceipt(receipt.receiptId);
182
+ if (known) {
183
+ if (canonicalJson(known.receipt) !== canonicalJson(receipt) || known.signature !== fields.signature)
184
+ throw new PreEffectToolRefusal("receiptId already records different signed bytes");
185
+ this.experimentFresh(before, relayOwner, record.protocol, record.recordedForTaskId); requestCheck();
186
+ return proof(known); // immutable stored proof: do not re-verify against a revoked/replaced registration or write on replay
187
+ }
188
+ const registrations = parseResearchRunners(this.d.researchRunners?.() ?? {}), registrationKey = canonicalJson(registrations);
189
+ const context = { projectId: this.d.project, attempt: { id: attempt.attemptId, projectId: attempt.project, protocolHash: attempt.attempt.protocolHash,
190
+ ...("commit" in record.protocol.code ? { codeCommit: record.protocol.code.commit } : {}) } };
191
+ verifyAttemptReceipt(receipt, fields.signature, { ...context, runners: registrations });
192
+ const lastSeq = this.d.board.experimentLastSeq(attempt.attemptId);
193
+ await this.experimentScreen(canonicalJson(receipt), before.task); requestCheck();
194
+ const current = this.experimentFresh(before, relayOwner, record.protocol, record.recordedForTaskId);
195
+ const latest = parseResearchRunners(this.d.researchRunners?.() ?? {});
196
+ if (canonicalJson(latest) !== registrationKey) throw new PreEffectToolRefusal("runner registration changed during receipt admission");
197
+ verifyAttemptReceipt(receipt, fields.signature, { ...context, runners: latest }); requestCheck();
198
+ const saved = this.d.board.appendRunnerReceipt({ receipt, signature: fields.signature as string, publicKey: latest[receipt.runner]!.publicKey,
199
+ by, at: this.host.studyTime(), private: current.private || record.private || attempt.private }, lastSeq, current.fence);
200
+ return proof(saved);
201
+ }
202
+ if (envelope.kind === "plan") {
203
+ const fields = this.host.studyFields(input, ["kind", "taskId", "plan"]), taskId = this.host.studyNumber(fields.taskId, "taskId"), plan = parseComparisonPlan(fields.plan);
204
+ const before = this.experimentPlanContext(by, taskId, plan);
205
+ await this.experimentScreen(canonicalJson(plan), before.task); requestCheck();
206
+ const current = this.experimentPlanContext(by, taskId, plan);
207
+ if (current.key !== before.key) throw new PreEffectToolRefusal("comparison authority, source or campaign changed during admission");
208
+ requestCheck();
209
+ const saved = this.d.board.saveExperimentComparisonPlan({ hash: comparisonPlanHash(plan), project: this.d.project, recordedForTaskId: taskId,
210
+ plan, by, at: this.host.studyTime(), private: current.private }, current.fence);
211
+ return { kind: "plan", planHash: saved.hash };
212
+ }
213
+ if (envelope.kind === "protocol") {
214
+ const fields = this.host.studyFields(input, ["kind", "taskId", "protocol"]), taskId = this.host.studyNumber(fields.taskId, "taskId"), protocol = parseExperimentProtocol(fields.protocol);
215
+ const before = this.experimentContext(by, taskId, protocol);
216
+ for (const reference of [protocol.variantOf, protocol.supersedes]) if (reference) {
217
+ const previous = this.experimentProtocol(reference);
218
+ if (previous.protocol.campaignId !== protocol.campaignId || reference === protocol.supersedes && previous.protocol.lineage !== protocol.lineage)
219
+ throw new PreEffectToolRefusal("experiment protocol reference belongs to another campaign or lineage");
220
+ }
221
+ await this.experimentScreen(canonicalJson(protocol), before.task); requestCheck();
222
+ const current = this.experimentFresh(before, by, protocol); requestCheck();
223
+ const saved = this.d.board.saveExperimentProtocol({ hash: protocolHash(protocol), project: this.d.project, recordedForTaskId: taskId, protocol, by, at: this.host.studyTime(), private: current.private }, current.fence);
224
+ return { kind: "protocol", protocolHash: saved.hash };
225
+ }
226
+ if (envelope.kind === "attempt") {
227
+ const fields = this.host.studyFields(input, ["kind", "attempt"]), attempt = parseExperimentAttempt(fields.attempt), record = this.experimentProtocol(attempt.protocolHash);
228
+ const before = this.experimentContext(by, attempt.taskId, record.protocol, record.recordedForTaskId);
229
+ for (const reference of [attempt.retryOf, attempt.reproducesAttemptId]) if (reference) {
230
+ const previous = this.experimentAttempt(reference), protocol = this.experimentProtocol(previous.attempt.protocolHash);
231
+ if (protocol.protocol.campaignId !== record.protocol.campaignId) throw new PreEffectToolRefusal("attempt reference belongs to another campaign");
232
+ }
233
+ await this.experimentScreen(canonicalJson(attempt), before.task); requestCheck();
234
+ const current = this.experimentFresh(before, by, record.protocol, record.recordedForTaskId); requestCheck();
235
+ const saved = this.d.board.createExperimentAttempt({ attemptId: `ra-${randomBytes(6).toString("hex")}`, project: this.d.project, attempt, bodyHash: this.experimentHash(attempt), by, at: this.host.studyTime(), private: current.private || record.private }, current.fence);
236
+ return { kind: "attempt", protocolHash: saved.attempt.protocolHash, attemptId: saved.attemptId };
237
+ }
238
+ if (envelope.kind === "event") {
239
+ const fields = this.host.studyFields(input, ["kind", "attemptId", "idempotencyKey", "event"]), id = this.experimentId(fields.attemptId), key = fields.idempotencyKey;
240
+ if (typeof key !== "string" || !key.trim() || key.length > 64 || Buffer.byteLength(key, "utf8") > 64 || Buffer.from(key, "utf8").toString("utf8") !== key) throw new PreEffectToolRefusal("event idempotencyKey needs at most 64 UTF-8 bytes");
241
+ const attempt = this.experimentAttempt(id), record = this.experimentProtocol(attempt.attempt.protocolHash), event = parseExperimentEvent(fields.event, record.protocol);
242
+ const before = this.experimentContext(by, attempt.attempt.taskId, record.protocol, record.recordedForTaskId), lastSeq = this.d.board.experimentLastSeq(id);
243
+ await this.experimentScreen(canonicalJson([key, event]), before.task); requestCheck();
244
+ this.experimentFresh(before, by, record.protocol, record.recordedForTaskId);
245
+ const observations: ExperimentHostEvidence[] = [];
246
+ let outputPrivate = event.kind === "output" && "path" in event.body ? this.host.experimentOutputPrivate(before.task, event.body.path) : false;
247
+ if (event.kind === "end" && event.body.run && this.d.experimentCheck) {
248
+ let receipt: unknown;
249
+ try { receipt = await this.d.experimentCheck(event.body.run); } catch { /* unavailable is unknown */ }
250
+ requestCheck(); this.experimentFresh(before, by, record.protocol, record.recordedForTaskId);
251
+ const observation = checkRunObservation(receipt, event.body.run, before.task.id, record.protocol);
252
+ if (observation) observations.push(observation);
253
+ } else if (event.kind === "output" && "path" in event.body) {
254
+ try {
255
+ const measured = await hashDeliverables([event.body], this.host.deliverablePorts(before.task));
256
+ const output = measured[0];
257
+ if (output) { observations.push(deliverableObservation(output)); outputPrivate ||= output.private === true; }
258
+ } catch { /* #509 refusal, missing or unreadable means unknown; never use a declared fallback hash */ }
259
+ requestCheck(); this.experimentFresh(before, by, record.protocol, record.recordedForTaskId);
260
+ }
261
+ const current = this.experimentFresh(before, by, record.protocol, record.recordedForTaskId); requestCheck();
262
+ if (event.kind === "output" && "path" in event.body) outputPrivate ||= this.host.experimentOutputPrivate(current.task, event.body.path);
263
+ const saved = this.d.board.appendExperimentEvent(id, key, event, observations, by, this.host.studyTime(), current.private || record.private || attempt.private || outputPrivate, lastSeq, current.fence);
264
+ return { kind: "event", protocolHash: record.hash, attemptId: id, seq: saved.event.seq };
265
+ }
266
+ throw new PreEffectToolRefusal("unsupported experiment record kind");
267
+ } catch (error) {
268
+ if (error instanceof PreEffectToolRefusal) throw error;
269
+ throw new PreEffectToolRefusal(error instanceof Error ? error.message : "experiment record was not saved");
270
+ }
271
+ });
272
+ }
273
+ runnerKeyStatus(stored: NonNullable<ReturnType<Board["runnerReceipt"]>>): "active" | "revoked" | "replaced" | "unavailable" {
274
+ try {
275
+ const runners = parseResearchRunners(this.d.researchRunners?.() ?? {});
276
+ if (!Object.hasOwn(runners, stored.receipt.runner)) return "unavailable";
277
+ const current = runners[stored.receipt.runner]!;
278
+ if (current.publicKey !== stored.publicKey) return "replaced";
279
+ if (current.revoked) return "revoked";
280
+ return current.projects.includes(stored.receipt.projectId) ? "active" : "unavailable";
281
+ } catch { return "unavailable"; }
282
+ }
283
+ experimentPrivate(record: ExperimentProtocolRecord, attempt: ExperimentAttemptRecord): boolean {
284
+ try {
285
+ const campaign = this.d.board.researchCampaign(record.protocol.campaignId, record.protocol.campaignRevision), task = this.d.board.get(attempt.attempt.taskId);
286
+ return record.private || attempt.private || !campaign || this.host.studyReplayPrivacy(campaign, this.host.studyParent(campaign.parentTaskId)) || !task || this.host.isPii(task)
287
+ || record.protocol.inputs.some(input => { const source = this.host.studySource(input.sourceId); return !source || source.private; });
288
+ } catch { return true; }
289
+ }
290
+ async experimentShow(by: PeerId, input: unknown): Promise<ExperimentView> {
291
+ return this.experimentRead(by, input);
292
+ }
293
+ experimentRead(by: PeerId, input: unknown): ExperimentView {
294
+ this.host.requireLocalTaskPeer(by);
295
+ const fields = this.host.studyFields(input, ["attemptId", "campaignId", "after", "eventAfter", "limit", "planHash", "baselineAttemptId", "variantAttemptId"]);
296
+ const cursor = (value: unknown, name: string) => value === undefined ? 0 : typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : (() => { throw new PreEffectToolRefusal(`${name} must be a nonnegative integer`); })();
297
+ const after = cursor(fields.after, "after"), eventAfter = cursor(fields.eventAfter, "eventAfter"), limit = fields.limit === undefined ? 50 : this.host.studyNumber(fields.limit, "limit");
298
+ if (limit > 50) throw new PreEffectToolRefusal("experiment readback is limited to 50 rows");
299
+ if (fields.planHash !== undefined || fields.baselineAttemptId !== undefined || fields.variantAttemptId !== undefined) {
300
+ if (fields.attemptId !== undefined || fields.campaignId !== undefined || fields.after !== undefined
301
+ || typeof fields.planHash !== "string" || fields.planHash.length !== 64 || !/^[a-f0-9]{64}$/.test(fields.planHash))
302
+ throw new PreEffectToolRefusal("comparison readback needs one plan hash and two attempt ids");
303
+ const plan = this.d.board.experimentComparisonPlan(fields.planHash);
304
+ if (!plan || plan.project !== this.d.project) throw new PreEffectToolRefusal("comparison plan is unavailable in this project");
305
+ const baseline = this.experimentAttempt(this.experimentId(fields.baselineAttemptId)), variant = this.experimentAttempt(this.experimentId(fields.variantAttemptId));
306
+ const first = this.experimentProtocol(baseline.attempt.protocolHash), second = this.experimentProtocol(variant.attempt.protocolHash);
307
+ if (first.protocol.campaignId !== plan.plan.campaignId || second.protocol.campaignId !== plan.plan.campaignId)
308
+ throw new PreEffectToolRefusal("comparison attempts must belong to the plan's campaign");
309
+ const left = this.experimentRead(by, { attemptId: baseline.attemptId, eventAfter, limit });
310
+ const right = this.experimentRead(by, { attemptId: variant.attemptId, eventAfter, limit });
311
+ let planPrivate = true;
312
+ try {
313
+ const campaign = this.host.studyRecord(plan.plan.campaignId);
314
+ planPrivate = plan.private || this.host.studyReplayPrivacy(campaign, this.host.studyParent(campaign.parentTaskId))
315
+ || plan.plan.fixed.inputs.some(input => { const source = this.host.studySource(input.sourceId); return !source || source.private; });
316
+ } catch { /* an unavailable privacy classification withholds the comparison */ }
317
+ const privateRecord = planPrivate || left.attempts.some(row => row.private) || right.attempts.some(row => row.private);
318
+ return { attempts: [...left.attempts, ...right.attempts], counts: left.counts,
319
+ comparison: { planHash: plan.hash, baselineAttemptId: baseline.attemptId, variantAttemptId: variant.attemptId,
320
+ approved: this.experimentApproved(first) && this.experimentApproved(second), private: privateRecord,
321
+ projection: privateRecord ? "[pii]" : comparisonProjection(plan.plan, first.protocol, second.protocol) } };
322
+ }
323
+ let campaignId: string, attempts: ExperimentAttemptRecord[], nextCursor: number | undefined;
324
+ if (fields.attemptId !== undefined) {
325
+ if (fields.campaignId !== undefined || fields.after !== undefined) throw new PreEffectToolRefusal("choose one attempt or campaign page");
326
+ const attempt = this.experimentAttempt(this.experimentId(fields.attemptId));
327
+ campaignId = this.experimentProtocol(attempt.attempt.protocolHash).protocol.campaignId; attempts = [attempt];
328
+ } else {
329
+ campaignId = this.host.studyId(fields.campaignId); this.host.studyRecord(campaignId);
330
+ const page = this.d.board.experimentAttempts(this.d.project, campaignId, after, limit); attempts = page.rows;
331
+ if (!page.done) nextCursor = page.afterRow;
332
+ }
333
+ const summary = this.d.board.experimentSummary(this.d.project, campaignId), views: ExperimentAttemptView[] = [];
334
+ for (const attempt of attempts) {
335
+ const record = this.experimentProtocol(attempt.attempt.protocolHash), page = this.d.board.experimentEvents(attempt.attemptId, eventAfter, limit);
336
+ const runnerReceipts = this.d.board.runnerReceipts(attempt.attemptId);
337
+ const privateRecord = this.experimentPrivate(record, attempt) || page.rows.some(row => row.private)
338
+ || runnerReceipts.some(row => row.private || !this.host.nameable(canonicalJson(row.receipt)) || looksSecret(canonicalJson(row.receipt)));
339
+ const status = this.d.board.experimentAttemptStatus(attempt.attemptId);
340
+ const observations = page.rows.flatMap(row => row.observations), events = page.rows.map(row => row.event);
341
+ const evidence = { ...projectExperimentWithObservations(record.protocol, events, observations),
342
+ ...(runnerReceipts.length ? { runnerAttested: runnerReceipts.map(row => ({ ...projectRunnerReceipt(record.protocol, row.receipt), key: { hash: row.keyHash, status: this.runnerKeyStatus(row) } })) } : {}) };
343
+ views.push({ id: attempt.attemptId, protocolHash: record.hash, taskId: attempt.attempt.taskId, phase: attempt.attempt.phase, status, private: privateRecord,
344
+ campaignRevision: record.protocol.campaignRevision, approval: this.experimentApproved(record) ? "approved" : "unapproved",
345
+ postHoc: this.d.board.experimentProtocolContext(record.hash).state,
346
+ ...(attempt.attempt.retryOf ? { retryOf: attempt.attempt.retryOf } : {}), ...(attempt.attempt.reproducesAttemptId ? { reproducesAttemptId: attempt.attempt.reproducesAttemptId } : {}), independentlyReproduced: false,
347
+ protocol: { value: privateRecord ? "[pii]" : record.protocol, provenance: "declared" },
348
+ events: page.rows.map(row => privateRecord ? { seq: row.event.seq, kind: row.event.kind, at: row.event.at, provenance: row.event.provenance, body: "[pii]" } : row.event),
349
+ evidence: privateRecord ? { declared: "[pii]", measured: evidence.measured.map(row => ({ eventSeq: row.eventSeq, source: row.source, provenance: "host-observed", values: "[pii]" })), ...(runnerReceipts.length ? { runnerAttested: runnerReceipts.map(() => ({ provenance: "runner-attested", values: "[pii]" })) } : {}) } : evidence,
350
+ eventsComplete: page.done, ...(!page.done ? { nextEventCursor: page.afterSeq } : {}) });
351
+ }
352
+ return { attempts: views, counts: { all: summary.total, statuses: summary.statuses }, ...(nextCursor === undefined ? {} : { nextCursor }) };
353
+ }
354
+ /** Pure read screen: never resolve an address or a path to decide whether to publish it. */
355
+ lineageMetadata(text: string): boolean {
356
+ try {
357
+ if (!this.host.nameable(text) || looksSecret(text)) return false;
358
+ const policy = [...this.d.piiPaths ?? [], ...this.d.deny ?? []];
359
+ if (!policy.length) return true;
360
+ let parsed: unknown;
361
+ try { parsed = JSON.parse(text); } catch { return false; } // direct stored paths have no alias proof
362
+ const strings = (value: unknown): string[] => typeof value === "string" ? [value] : Array.isArray(value) ? value.flatMap(strings) : value && typeof value === "object" ? Object.values(value).flatMap(strings) : [];
363
+ // ponytail: a path-shaped opaque field has no cached alias proof. Withhold it until owner-maintained
364
+ // public metadata can prove it without filesystem discovery on this read path.
365
+ return strings(parsed).every(value => !/[\\/]|\.[a-zA-Z]/.test(value) && !matchesPolicyLexically(this.d.cwd, value, policy));
366
+ } catch { return false; }
367
+ }
368
+ lineageVisible(by: PeerId, task: Task): boolean {
369
+ try {
370
+ if (this.d.privateTurn?.(by) || this.d.reviewObserverInput?.(by) || this.host.reviewTaskPrivate(task)) return false;
371
+ if (this.d.piiPaths?.length && ((task.refs.paths?.length ?? 0) || (task.plan?.paths?.length ?? 0) || (task.plan?.sections?.length ?? 0))) return false;
372
+ if (this.host.repositories.cachedScope(task.refs)?.key !== this.host.repositories.project.key) return false;
373
+ return by === USER || this.d.bus.isRostered(by) && this.host.taskShowAllowed(by, task, this.d.roles, this.host.isConfiguredPlanner(by));
374
+ } catch { return false; }
375
+ }
376
+ lineagePorts(by: PeerId): ExecutionLineageOwnerPorts | undefined {
377
+ const binding = this.d.executionLineage;
378
+ if (!binding) return undefined;
379
+ // Agent-wide roles do not grant diagnostic authority over a hidden or staged source.
380
+ const diagnostics = by === USER;
381
+ // ponytail: raw50 event pages cannot prove current field privacy after policy narrowing.
382
+ // Refuse by policy alone until a privacy-aware page source supplies a complete public projection.
383
+ let eventProjectionSupported = false;
384
+ try { eventProjectionSupported = !this.d.piiPaths?.length && !this.d.deny?.length && !this.d.routing().signals.pii_patterns.length; } catch { /* unknown current policy cannot admit event projection */ }
385
+ return { project: this.d.project, projectKey: binding.projectKey, cursorKey: binding.cursorKey,
386
+ scope: createHash("sha256").update(by).digest("hex"), diagnostics, eventProjectionSupported,
387
+ task: id => this.d.board.get(id), visible: task => this.lineageVisible(by, task), metadata: text => this.lineageMetadata(text),
388
+ links: task => this.d.board.executionReferences(binding.projectKey, task.id, task.created),
389
+ delivery: binding.readDelivery,
390
+ attempt: id => this.d.board.experimentAttempt(id), events: (id, after, limit) => this.d.board.experimentEvents(id, after, limit),
391
+ receipts: id => this.d.board.runnerReceipts(id), attemptStatus: id => this.d.board.experimentAttemptStatus(id) };
392
+ }
393
+ /** Read one explicit owner neighborhood; unauthorized, private and missing roots are indistinguishable. */
394
+ executionLineage(by: PeerId, input: unknown): LineageResult {
395
+ if (!executionLinkActor(by) || by === HUB || by === "admin") return { state: "unavailable" };
396
+ try {
397
+ const check = this.host.requestCheck(by);
398
+ if (this.d.privateTurn?.(by) || this.d.reviewObserverInput?.(by)) return { state: "unavailable" };
399
+ const ports = this.lineagePorts(by);
400
+ if (!ports) return { state: "unavailable" };
401
+ let query;
402
+ try { query = parseOwnerLineageQuery(input); }
403
+ catch { return ports.diagnostics ? { state: "unavailable", reason: "invalid" } : { state: "unavailable" }; }
404
+ const snapshot = executionOwnerSnapshot(ports, query);
405
+ check();
406
+ if (this.d.privateTurn?.(by) || this.d.reviewObserverInput?.(by)) return { state: "unavailable" };
407
+ if (snapshot.task) {
408
+ const current = this.d.board.get(snapshot.task.id);
409
+ if (!current || current.created !== snapshot.task.created || current.history.length !== snapshot.task.history.length || !this.lineageVisible(by, current)) return { state: "unavailable" };
410
+ }
411
+ return readExecutionLineage(snapshot.source, snapshot.query);
412
+ } catch { return { state: "unavailable" }; }
413
+ }
414
+ /** A declaration carries no resolver, runner attestation, review approval or model-execution authority. */
415
+ async linkExecutionReference(by: PeerId, input: unknown): Promise<{ id: string; taskId: number; reference: ExecutionReferenceV1; strength: "declared"; already: boolean }> {
416
+ if (!executionLinkActor(by) || by === HUB || by === "admin") throw new PreEffectToolRefusal("execution links require a current local task actor; ask the person or the task owner to record the declaration");
417
+ const check = this.host.requestCheck(by, () => this.host.studyHold() ? "execution links are held; inspect ahub status and retry after recovery or shutdown" : undefined);
418
+ let proposed: ExecutionLinkInput;
419
+ try { proposed = parseExecutionLinkInput(input); } catch { throw new PreEffectToolRefusal("execution link fields are invalid; refresh the task identity and use a bounded execution reference"); }
420
+ return this.host.studyWrite(async () => {
421
+ const context = () => {
422
+ check();
423
+ const ports = this.lineagePorts(by);
424
+ if (!ports) throw new PreEffectToolRefusal("execution reference storage is unavailable; inspect ahub status before retrying");
425
+ let task: Task;
426
+ try { task = this.host.studyParent(proposed.taskId); } catch { throw new PreEffectToolRefusal("execution link task is unavailable in this project; refresh ahub task show before retrying"); }
427
+ const role = by === task.owner ? ownerRoleOfClass(task.class) : by === task.reviewer ? "reviewer" : undefined;
428
+ if (by !== USER && (!role || !this.d.roles?.[by]?.includes(role) || !this.d.bus.isRostered(by))) throw new PreEffectToolRefusal("execution links require the task's current owner or reviewer role; ask that peer or the person to record the declaration");
429
+ if (!this.lineageVisible(by, task)) throw new PreEffectToolRefusal("execution links require a public task outside private or review input; refresh the current task policy before retrying");
430
+ if (task.created !== proposed.taskCreated || task.history.length !== proposed.flowRevision) throw new PreEffectToolRefusal("execution link task identity or revision changed; refresh ahub task show before retrying");
431
+ const from = proposed.from ?? taskExecutionReference(ports.projectKey, task.id, task.created);
432
+ const scope = { id: task.id, created: task.created };
433
+ const origin = executionOwnerSnapshot(ports, { root: from, task: scope });
434
+ if (origin.source.health !== "ready" || !origin.source.nodes.some(node => executionReferenceKey(node.ref) === executionReferenceKey(from))) throw new PreEffectToolRefusal("execution link origin is not recorded in this task; select an existing public task-scoped reference");
435
+ if (proposed.reference.tool === "ahub") {
436
+ const target = executionOwnerSnapshot(ports, { root: proposed.reference, task: scope });
437
+ if (target.source.health !== "ready" || !target.source.nodes.some(node => executionReferenceKey(node.ref) === executionReferenceKey(proposed.reference))) throw new PreEffectToolRefusal("local execution target is not recorded in this task; select a verified task-scoped reference");
438
+ }
439
+ const metadata = JSON.stringify([from, proposed.reference]);
440
+ if (!this.host.publicMetadataText(metadata)) throw new PreEffectToolRefusal("execution reference metadata is private or sensitive; use public metadata before retrying");
441
+ return { ports, task, from, metadata, key: JSON.stringify([task.created, task.history.length, task.owner, task.reviewer, task.state, origin.source.revision]) };
442
+ };
443
+ const before = context();
444
+ if (this.host.screenOn()) {
445
+ const result = await this.host.screenCall(before.metadata);
446
+ if (result.label !== "clear") throw new PreEffectToolRefusal("execution reference privacy screening did not clear the metadata; retry with public metadata when screening is available");
447
+ }
448
+ check();
449
+ const current = context();
450
+ if (current.key !== before.key) throw new PreEffectToolRefusal("execution link authority or source changed during admission; refresh the task and source references before retrying");
451
+ const saved = this.d.board.recordExecutionReference(current.ports.projectKey, { ...proposed, from: current.from }, { by, at: this.d.now?.() ?? Date.now() });
452
+ return { id: saved.record.id, taskId: saved.record.taskId, reference: saved.record.reference, strength: "declared", already: saved.already };
453
+ });
454
+ }
455
+ }