@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
package/src/hub/tasks.ts CHANGED
@@ -1,33 +1,19 @@
1
- import { requireConductor } from "./conductor.ts";
2
- import { instructedExecution, instructedHistory } from "./instructed-exact.ts";
1
+ import { ESCALATE_AFTER } from "./operational-settings.ts";
2
+ import { conductorPeer, requireConductor } from "./conductor.ts";
3
3
  import { managedTaskPullRequest } from "./task-pr.ts";
4
- import { parseMilestoneInput, parseMilestonePatch, milestoneId, milestoneRevision, milestoneLinkRef, githubRepo, MILESTONE_STATES, type Milestone, type MilestoneLinkKind, type MilestonePatch, type MilestoneState, type MilestoneSuggestion, type SuggestionItemKind, type DecomposePart, type DecomposeIntake, type MilestoneDecomposition, type DecompositionAccept } from "./roadmap.ts";
5
- import { milestoneViews, type MilestoneView, type RoadmapSnapshot } from "./roadmap-view.ts";
6
- import { readMirrorSnapshot, planRoadmapMirror, recoverMirrorBinding } from "./roadmap-sync.ts";
4
+ import { type Milestone, type MilestoneLinkKind, type MilestonePatch, type MilestoneState, type MilestoneSuggestion, type DecomposePart, type DecomposeIntake, type MilestoneDecomposition } from "./roadmap.ts";
5
+ import { type MilestoneView, type RoadmapSnapshot } from "./roadmap-view.ts";
7
6
  import { roadmapExport } from "./roadmap-export.ts";
8
- import { roadmapIssueStates } from "./roadmap-issue-states.ts";
9
- import { checkRoadmap, type DriftMilestone, type RoadmapDrift } from "./roadmap-check.ts";
7
+ import { checkRoadmap, type RoadmapDrift } from "./roadmap-check.ts";
10
8
  import type { RoadmapConfig } from "./roadmap.ts";
11
- import { computeUnplaced, withTree, type ReadyToClose, type TreeRollup, type UnplacedResult } from "./roadmap-unplaced.ts";
12
- import { buildTriagePrompt, parseTriage, TRIAGE_BATCH, type TriageItem } from "./roadmap-triage.ts";
13
- import { buildDecomposePrompt, parseDecomposition, planPartPublish, DECOMPOSE_ITEMS, DECOMPOSE_PATHS, type DecomposeItem, type PublishDraft, type PublishPlanPart } from "./roadmap-decompose.ts";
14
- import { pathCandidates } from "@staix/agent-mem";
15
- import { renderGuidanceVariantV1 } from "./guidance-variants.ts";
16
- import { GuidanceProbeFixtureHost, type GuidanceProbeStore } from "./guidance-probe-store.ts";
17
- import { GuidanceProbeError, GUIDANCE_PROBE_STOP_TIMEOUT_MS, GUIDANCE_PROBE_FENCE_INTERVAL_MS, GUIDANCE_PROBE_LIVE_LIMITS, isLiveGuidanceProbeManifest, guidanceProbeCanonical, guidanceProbeManifestKey,
18
- parseGuidanceProbeRegistration, parseGuidanceProbeReceiptExport, probeHash, probeSha256, probeInteger, probeSessionGeneration,
19
- type ProbeChildBinding, type ProbeStoredState, type ProbePublicReceipt, type ProbePublicStatus, type ProbeHostBinding,
20
- type ProbeReceiptExport, type ProbeExportSlot, type ProbeReceiptV1, type ProbeRetentionState,
21
- type ProbeAdmissionRecheck, type ProbeReservation, type ProbeSlot, type GuidanceProbeFakePorts, type GuidanceProbeManifestV1, type ProbeWorkerFramePreparer } from "./guidance-probes.ts";
22
- import { GuidanceVariantError, GUIDANCE_PAGE_MAX_RECORDS, GUIDANCE_REPLY_MAX_BYTES, guidanceVariantSectionDiff, guidanceProtectedSectionNames, parseGuidancePageResult, parseGuidanceDiffResult, parseGuidanceListQuery, parseGuidanceIdQuery, guidancePageCursor, guidancePageAfter, guidanceVariantMetadata, parseGuidanceVariantV1, validateGuidanceVariantV1, parseGuidanceSelector, type GuidanceVariantV1, type GuidanceStoredRecord, type GuidanceSelector, type GuidanceIdSelector, type GuidanceWriteFence, type GuidanceWriteReceipt, type GuidanceCurrent, type GuidancePublicRecord, type GuidancePageResult, type GuidanceDiffResult, type GuidanceReadResult } from "./guidance-variants.ts";
9
+ import { type ReadyToClose, type TreeRollup, type UnplacedResult } from "./roadmap-unplaced.ts";
10
+ import { type PublishPlanPart } from "./roadmap-decompose.ts";
11
+ import { type GuidanceProbeStore } from "./guidance-probe-store.ts";
12
+ import { type ProbeStoredState, type ProbeSlot, type GuidanceProbeFakePorts, type ProbeWorkerFramePreparer } from "./guidance-probes.ts";
23
13
  import { buildEntryDiagnostic } from "./build-entry.ts";
24
14
  import { taskShowAllowed } from "./conductor.ts";
25
- import { executionOwnerSnapshot, parseOwnerLineageQuery, type ExecutionLineageOwnerPorts } from "./execution-lineage-owner.ts";
26
- import { readExecutionLineage, type LineageResult } from "./execution-lineage.ts";
27
- import { parseExecutionLinkInput, taskExecutionReference, executionLinkActor, executionReferenceDigest, type ExecutionLinkInput } from "./execution-links.ts";
28
- import { executionReferenceKey, executionText, EXECUTION_REFERENCE_LIMITS, type ExecutionReferenceV1 } from "./execution-reference.ts";
29
15
  import type { JournalDelivery } from "./delivery-journal.ts";
30
- import { checkSynthesis, inventoryBinding, parseSynthesisManifest, synthesisManifestHash, type SynthesisManifestV1, type SynthesisCurrent, type SynthesisCurrentClaim, type SynthesisArtifactSnapshot, type SynthesisReadiness } from "./synthesis-readiness.ts";
16
+ import { inventoryBinding, parseSynthesisManifest, synthesisManifestHash, type SynthesisManifestV1, type SynthesisCurrent, type SynthesisReadiness } from "./synthesis-readiness.ts";
31
17
  import { parseEvidenceRecord, parseEvidenceLink, evidenceLinkId, evidenceLinkCanonical, type EvidenceRecordInput, type EvidenceReceipt, type EvidenceLinkV1 } from "./research-evidence.ts";
32
18
  import type { ActionMeta, ReviewAnchor } from "@staix/agent-console/contract";
33
19
  import { parseReviewAnchor, reviewAnchorErrorMessage, anchorStatus, type ReviewAnchorStatus } from "./review-anchor.ts";
@@ -38,21 +24,16 @@ import { reviewCommentFields, reviewCommentNumber, reviewCommentId, reviewCommen
38
24
  type ReviewCommentRecord, type ReviewCommentFence, type ReviewCommentMutation, type ReviewCommentCounts, type ReviewCommentView } from "./review-comments.ts";
39
25
  import { evidenceOriginKeys, type EvidenceSourceRead } from "./source-read.ts";
40
26
  import type { SourceMeta } from "./sources.ts";
41
- import { parseAttemptReceipt, parseResearchRunners, verifyAttemptReceipt } from "./research-runner.ts";
42
27
  import { approvalBinding, approvalText } from "./task-approval.ts";
43
28
  import type { InvocationRow } from "./invocations.ts";
44
29
  import type { ContextAdmission } from "./context-window.ts";
45
30
  import { queueBackpressure, queueBackpressurePolicy, type QueueBackpressureCode, type QueueBackpressurePolicy, type QueueBackpressureStatus, type QueuePressure } from "./queue-backpressure.ts";
46
31
  import { generatedRecordAnchors, type GeneratedNoteProof } from "../memory/record-provenance.ts";
47
32
  import { canonicalMemorySymbolNode, normalizeMemorySymbolInput, MEMORY_SYMBOL_LIMIT, type MemorySymbolNodes } from "./memory-symbols.ts";
48
- import { createHash, randomBytes } from "node:crypto";
33
+ import { createHash } from "node:crypto";
49
34
  import { types } from "node:util";
50
- import { canonicalJson } from "./packs.ts";
51
- import { parseExperimentProtocol, parseExperimentAttempt, parseExperimentEvent, protocolHash, checkRunObservation, deliverableObservation, projectExperimentWithObservations, projectRunnerReceipt,
52
- type ExperimentProtocolContract, type ExperimentProtocolRecord, type ExperimentAttemptRecord, type ExperimentWriteFence, type ExperimentHostEvidence, type ExperimentStatus } from "./research-experiments.ts";
53
- import { parseComparisonPlan, comparisonPlanHash, comparisonProjection, evaluatorIdentityHash, protocolApprovalBindingMatches, type ComparisonPlanV1 } from "./research-experiments.ts";
54
- import { parseResearchHandoff, studyProjection, campaignHash, parseResearchCampaign, type ResearchCampaignContract, type ResearchCampaignStatus } from "./research-campaign.ts";
55
- import type { ResearchCampaignRecord, ResearchUnitBinding, PreparedResearchUnit, HandoffOutboundRow } from "./board.ts";
35
+ import { studyProjection, type ResearchCampaignStatus } from "./research-campaign.ts";
36
+ import type { ResearchCampaignRecord, ResearchUnitBinding, HandoffOutboundRow } from "./board.ts";
56
37
  import { HANDOFF_EVENTS, HANDOFF_KEY, HandoffRefusal, handoffRequestDigest, duplicateIssueTasks, duplicateRefusalText, followBackLine, handoffEventFor, parseHandoff, type HandoffEvent } from "./handoff.ts";
57
38
  import { taskShellBindingValid, type TaskShellBinding } from "./task-shell-command.ts";
58
39
  import type { ReviewBudgetSnapshot, ReviewGate, ReviewUnknownQuota } from "./review-budget.ts";
@@ -62,12 +43,10 @@ import { publicTestIntegrity, readTestIntegrity, testIntegrityBlockers, type Tes
62
43
  import { evalAdvice, evalGapBlockers, evalRequiredChecks, readEvalFor } from "./eval-gate.ts";
63
44
  import { parseSecurityPass, securityPassBlockers, securityPassView, securityRequestLine, SECURITY_CHECKLIST, type SecurityPassRecord, type SecurityPassView } from "./security-pass.ts";
64
45
  import { deriveRiskTier, riskLine, riskPlanFloor, riskView, withoutRisk, type RiskCard, type RiskRecord, type RiskView } from "./risk-tier.ts";
65
- import { AUDIT_PROFILES, applyUnitReports, auditBrief, auditFindingView, auditIsPartial, auditSummary, needsVerification, parseUnitReports, seedLedger, settlementRefusal, SETTLEMENTS, unitId, verificationRefusal, type AuditFinding, type AuditProfile, type AuditSummary, type CarryLookup, type PublicAuditFinding } from "./security-audit.ts";
46
+ import { AUDIT_PROFILES, applyUnitReports, auditBrief, auditFindingView, auditIsPartial, auditSummary, needsVerification, parseUnitReports, seedLedger, settlementRefusal, SETTLEMENTS, unitId, verificationRefusal, type AuditProfile, type AuditSummary, type CarryLookup, type PublicAuditFinding } from "./security-audit.ts";
66
47
  import type { AuditSource } from "./audit-source.ts";
67
- import { SURVEY_FOCUS, SURVEY_LIMITS, parseSurveyFindings, parseSurveyVetDecisions, publicSurveyFinding, surveyBrief, surveyFindingKey, surveyObject, surveyPath, surveyInputAt, surveyInputProblem,
68
- type SurveyFinding, type SurveyFocus, type SurveyPass } from "./advisor-survey.ts";
48
+ import { surveyPath, surveyInputProblem, type SurveyFinding, type SurveyFocus, type SurveyPass } from "./advisor-survey.ts";
69
49
  import { consideredFindingMatch, parseConsideredEntry, type ConsideredEntry } from "./considered-findings.ts";
70
- import type { StoredSurvey, SurveyPreparedCard } from "./board.ts";
71
50
  import { matchConfigPath } from "./eval-gate.ts";
72
51
  import { completePlanInventory, planDrift, planConformance, planConformanceBlockers, planFingerprint, type PlanConformance } from "./plan-conformance.ts";
73
52
  import { RELEASE_TRAIN_HISTORY_LIMIT, releaseTrainData, releaseTrainReadiness, releaseMetrics } from "./sdlc-release.ts";
@@ -83,7 +62,7 @@ import type { InstancesConfig } from "./instances.ts";
83
62
  import { composeRememberText } from "./memory-fail.ts";
84
63
  import { VERSION } from "../version.ts";
85
64
  import { NoWriteTurns } from "./no-writes.ts";
86
- import { readGitHubImport, readGitHubIssuePages, readGitHubMilestonePages, type GitHubSource, type GitHubImportSelection } from "./github-import.ts";
65
+ import { readGitHubImport, type GitHubSource, type GitHubImportSelection } from "./github-import.ts";
87
66
  import { BACKLOG_SPLIT_SCREEN_TIMEOUT_MS, actualTaskDates, planningPatch, type PlanningFields, type Release, type ReleaseState } from "./planning.ts";
88
67
  import { readMergeQueue, type DeliveryTask, type MergeQueue } from "./sdlc-queue.ts";
89
68
  import { INLINE_MERGE_READBACK_DEADLINE_MS, MERGE_READBACK_DEADLINE_MS, adoptMergeGates, guardedMerge, mergeModeFor, mergeView, readAdoptMergeEvidence, requiredChecksFor, type MergeView } from "./sdlc-merge.ts";
@@ -91,8 +70,8 @@ import { mirrorVerdict as mirrorToGitHub, type MirrorVerdict } from "./sdlc-mirr
91
70
  import { CODE_SCOPE_LINE, evidenceOnlyNotice, type ReviewScope } from "./review-scope.ts";
92
71
  import { DEFAULT_MAX_NITS, parseReviewFindings, findingsForHead, findingHead as resolveFindingHead, findingTally, findingFollowUps, positionalFindingId, type ReviewFinding, type ReviewFindingSet } from "./review-findings.ts";
93
72
  import { readReleaseReadiness, type ReleaseReportPolicy } from "./sdlc-release.ts";
94
- import { loadRoleCatalog, roleIdentity, taskRole, taskRoleText, type RoleCatalog } from "./roles.ts";
95
- import { matchesPolicy, matchesPolicyLexically, policyRealPath, insideRoot } from "./path-policy.ts";
73
+ import { loadRoleCatalog, taskRole, taskRoleText, type RoleCatalog } from "./roles.ts";
74
+ import { matchesPolicy, policyRealPath, insideRoot } from "./path-policy.ts";
96
75
  import { isDenied } from "../local/deny.ts";
97
76
  import { foldSegment, isHubWritePath } from "./permission-mode.ts";
98
77
  import { correctionInput, resolveVisibleMemory } from "./memory-candidates.ts";
@@ -102,7 +81,7 @@ import { withoutPii, mentionsPrivatePath } from "./memory-policy.ts";
102
81
  import { createMemorySyncPolicy } from "./memory-sync-policy.ts";
103
82
  import { profileClass, profileData, profileTaskLabel, projectProfile, type ProfileName, type ProfileSelection, type ProjectProfile } from "./profiles.ts";
104
83
  import { criteriaView, unmetCriteriaIds, workflowHash } from "./workflow.ts";
105
- import { candidateCard, CHECKLIST_MAX_LINES, checklistLineMarker, criterionKey, groupUnmetCriteria, LEARNING_DEFAULTS, overridesDiff, parseCandidateCard, parseRemovalCard, removalCard, removalKey, selectGroups, withoutChecklistLine, type CriterionGroup } from "./learning.ts";
84
+ import { candidateCard, CHECKLIST_MAX_LINES, checklistLineMarker, criterionKey, groupUnmetCriteria, LEARNING_DEFAULTS, overridesDiff, parseCandidateCard, parseRemovalCard, removalCard, removalKey, selectGroups, type CriterionGroup } from "./learning.ts";
106
85
  import { acceptanceSuffix, FOLLOWUP_DEFAULTS, outcomeOf, rateIn, readAcceptance, removalDue, weakest, type AcceptanceRecord, type OutcomeView, type Rate } from "./learn-followup.ts";
107
86
  /** #514b: how a closed candidate card says what the person decided; `learnCandidates` reads them back. */
108
87
  const LEARN_ACCEPTED = "candidate accepted", LEARN_REJECTED = "candidate rejected";
@@ -114,12 +93,12 @@ const learnVerdict = (card: Pick<Task, "state" | "history">): "accepted" | "reje
114
93
  return closed.note?.startsWith(LEARN_ACCEPTED) ? "accepted" : closed.note?.startsWith(LEARN_REJECTED) ? "rejected" : undefined;
115
94
  };
116
95
  import { approvedDeliverables, latestDeliverables, parseDeliverableClaims, publicDeliverables, type DeliverableRecord, type DeliverableStatus } from "./deliverables.ts";
117
- import { checkDeliverables, DeliverableRefusal, hashDeliverables, vetDeliverables, readGuardedDeliverable, guardedDeliverableCurrent, type GuardedDeliverableRead, type DeliverablePorts } from "./deliverable-files.ts";
96
+ import { checkDeliverables, DeliverableRefusal, hashDeliverables, vetDeliverables, type DeliverablePorts } from "./deliverable-files.ts";
118
97
  import { isAbsolute, relative, resolve } from "node:path";
119
98
  import type { Briefs, NativeItem } from "../memory/brief.ts";
120
99
  import type { MemoryClient } from "../memory/client.ts";
121
- import { candidateTargetRevision, type CandidateInput, type CandidateStore, extractNodes, looksSecret, PROMOTED_KINDS, taskKey, type GoalView, type Kind, type MemoryStore, type NoteInput, type Scope, type Tier } from "@staix/agent-mem";
122
- import { HOST_SPEC_ACCEPTANCE_CARRY, HOST_MERGE_ADOPTION, HOST_ROADMAP_DRAFT, parseClaimVerdict, taskClaimIdentity, CLASSES, OUTCOMES_KEPT_MS, ALL_PLAN_KEYS, TASK_MOVE_REASONS, TASK_REASONS, type TaskReason, taskCanPlan, taskHasWorkEvidence, taskHasStarted, planningUndoEntry, isClosedTaskState, type TaskStall, type HistoryEntry, type ReviewerHistory, type Board, type Task, type TaskClass, type TaskMoveReason, type TaskPlan, type TaskRefs, type SpecAcceptanceCandidate, type SpecAcceptanceCommit, type PlannerBinding, type SpecAck, type SpecTaskReport } from "./board.ts";
100
+ import { captureSessionKey, candidateTargetRevision, type CandidateInput, type CandidateStore, extractNodes, looksSecret, PROMOTED_KINDS, taskKey, type GoalView, type Kind, type MemoryStore, type NoteInput, type Scope, type Tier } from "@staix/agent-mem";
101
+ import { HOST_SPEC_ACCEPTANCE_CARRY, HOST_MERGE_ADOPTION, HOST_ROADMAP_DRAFT, parseClaimVerdict, taskClaimIdentity, CLASSES, OUTCOMES_KEPT_MS, ALL_PLAN_KEYS, TASK_MOVE_REASONS, type TaskReason, taskCanPlan, taskHasWorkEvidence, taskHasStarted, planningUndoEntry, isClosedTaskState, type TaskStall, type HistoryEntry, type ReviewerHistory, type Board, type Task, type TaskClass, type TaskMoveReason, type TaskPlan, type TaskRefs, type SpecAcceptanceCandidate, type SpecAcceptanceCommit, type PlannerBinding, type SpecAck, type SpecTaskReport } from "./board.ts";
123
102
  import type { Bus } from "./bus.ts";
124
103
  import { HUB, newEnvelope, NOTE_KINDS, noteLine, sanitize, USER, type Envelope, type PeerId, type PeerState } from "./envelope.ts";
125
104
  import type { PiiVerdict, ScreenItem, ScreenRecord } from "./inference.ts";
@@ -138,9 +117,15 @@ import type { SpecsCheckReport, SpecsCoverReport } from "./specs.ts";
138
117
  import { definitionOf as builtinDefinitionOf } from "../adapters/registry.ts";
139
118
  import { ADAPTERS, DEFAULT_REVIEW_POOL, definitionOf, familyOf, type ProjectAdapterCatalog } from "../adapters/registry.ts";
140
119
  import { plannerGrooming, nextSweep, plannedStartPending, taskSweepConfig, taskWait, TASK_WAIT_MAX_MS, TASK_WAIT_REASON_MAX, type TaskSweepConfig, type SweepRecord } from "./task-sweep.ts";
141
- import { CiWatchers, pollCi, type CiOutcome, type CiWatch } from "./ci-watch.ts";
120
+ import { CiWatchers, pollCi, type CiOutcome, type CiRetryDecision, type CiShardRetry, type CiSnapshot, type CiWatch } from "./ci-watch.ts";
142
121
  import { acceptedSpecEdit, planningIssueReceipt, linkedReceipt, openPrFor, readPrCostHistory, readReviewReadiness, reviewReadinessFromEvidence, type PrEvidence, type ReviewReadiness, readPlanIssueMetadata, canonicalStage, checklistOf, readSdlcPr, readSdlcPrHead, readSpecEdit, sdlcConfig, sdlcReceipt, sdlcStatus, specState, SPEC_STATE_TEXT, stageDefinition, lifecycleStage, type SdlcConfig, type MergeRecord, type ReadbackMergeRecord, type PlanIssueMetadata, sdlcGh, type SdlcGh, type SdlcStatus, type SpecEdit, type SpecState, localSupersedingTask, storedSpecAcceptance, carriedSpecAcceptance } from "./sdlc.ts";
143
122
  import { missingReadbackRefs, parseSpecReadbackReport, type ReadbackView, type SpecReadbackReport } from "./spec-readback.ts";
123
+ import { StudyDomain, type StudyHost } from "./tasks-study.ts";
124
+ import { RoadmapDomain, type RoadmapHost } from "./tasks-roadmap.ts";
125
+ import { RoadmapPlanDomain, type RoadmapPlanHost } from "./tasks-roadmap-plan.ts";
126
+ import { GuidanceDomain, type GuidanceHost } from "./tasks-guidance.ts";
127
+ import { ExperimentDomain, type ExperimentHost, type ComparisonPlanReceipt, type ExperimentReceipt } from "./tasks-experiment.ts";
128
+ import { SurveyDomain, type SurveyHost } from "./tasks-survey.ts";
144
129
 
145
130
  /** #1176: refusals for an agent that reaches a person-run card by a path other than the pull gate. */
146
131
  const PERSON_RUN_SPLIT = "a person-run card is the person's to split: its children would be unmarked cards an agent could take (the person's own split marks every child person-run)";
@@ -180,9 +165,6 @@ export interface AuditView extends AuditSummary {
180
165
  /** Findings in this report that were already verified or rejected, so the hub left them as decided. */
181
166
  notUpdated?: string[];
182
167
  }
183
- /** #1738: how long one working-tree spec check serves the roadmap snapshot. */
184
- const ROADMAP_SPECS_REUSE_MS = 60_000;
185
-
186
168
  export interface TasksDeps {
187
169
  /** #1647 AC4: the hub's own token increments per task (a task id to its count, null when unknown), for the metrics grouped by reason. Read-only; absent means no reading. */
188
170
  taskTokens?: () => Readonly<Record<number, number | null>>;
@@ -273,7 +255,7 @@ export interface TasksDeps {
273
255
  */
274
256
  reviewerCheckout?: (peer: PeerId) => AuditSource | undefined;
275
257
  /** #785 P1b: the per-head CI watcher's bounds; tests shorten them, the defaults are `CI_WATCH_*` in `ci-watch.ts`. */
276
- ciWatch?: { deadlineMs?: number; pollMs?: number };
258
+ ciWatch?: { deadlineMs?: number; missingRunMs?: number; pollMs?: number };
277
259
  /** #785 P1c: `tasks.auto_pull`, read for every automatic pull trigger; absent or false pulls nothing. */
278
260
  autoPull?: () => boolean;
279
261
  briefs?: Briefs;
@@ -422,7 +404,7 @@ export interface TasksDeps {
422
404
  }
423
405
 
424
406
  /** The `tasks.escalate_after` default (#488): the third consecutive changes_requested escalates. */
425
- export const ESCALATE_AFTER = 3;
407
+ export { ESCALATE_AFTER } from "./operational-settings.ts";
426
408
  // Demotion (issue #36): a failure counts half after a day. A peer is demoted for a class once its decayed failures
427
409
  // reach 1.5 (two within about half a day, three within two days) and outweigh its decayed successes there.
428
410
  // #489 H2: `tasks.demotion_half_life_h` and `tasks.demote_at` set these; unset they are exactly the constants below (pinned in test/operational-settings.test.ts).
@@ -482,9 +464,6 @@ export class AssignmentSupersededError extends Error {
482
464
  export const normPath = (p: string) => p.replace(/^(\.\/)+/, "").replace(/\/{2,}/g, "/").replace(/\/+$/, "") || ".";
483
465
 
484
466
  /** Same path, or one is a directory of the other; the project root (`.`) holds everything. */
485
- /** #1647: how many overlapping paths a parallel-sibling refusal names, so the text stays one line. */
486
- const PARALLEL_PATHS_NAMED = 5;
487
-
488
467
  export const samePlace = (a: string, b: string) => {
489
468
  const [x, y] = [normPath(a), normPath(b)];
490
469
  return x === "." || y === "." || x === y || x.startsWith(`${y}/`) || y.startsWith(`${x}/`);
@@ -589,19 +568,7 @@ export const GROOM_FYI_WINDOW_MS = 10 * 60_000;
589
568
  */
590
569
  /** #694: a PR staged at done with the commit or branch it was read for. */
591
570
  export interface ResearchCampaignReceipt { id: string; parentTaskId: number; revision: number; status: ResearchCampaignStatus; unitCount: number; units: ResearchUnitBinding[] }
592
- interface StudyReferences { parent: Task; adopted: Map<string, Task>; reused: Map<string, Task>; private: boolean; key: string }
593
- export interface ExperimentReceipt { kind: "protocol" | "attempt" | "event" | "receipt"; protocolHash: string; attemptId?: string; seq?: number; receiptId?: string }
594
- export interface ComparisonPlanReceipt { kind: "plan"; planHash: string }
595
- export interface ProtocolApprovalReceipt { protocolHash: string; evaluatorHash: string; approvedBy: string; approvedAt: number }
596
- export interface ExperimentAttemptView {
597
- id: string; protocolHash: string; taskId: number; phase: "development" | "final"; status: ExperimentStatus; private: boolean;
598
- protocol: unknown; events: unknown[]; evidence: Record<string, unknown>; eventsComplete: boolean; nextEventCursor?: number;
599
- campaignRevision: number; approval: "approved" | "unapproved"; postHoc: "unknown" | "predeclared" | "post-hoc";
600
- retryOf?: string; reproducesAttemptId?: string; independentlyReproduced: false;
601
- }
602
- export interface ExperimentView { attempts: ExperimentAttemptView[]; counts: { all: number; statuses: Record<ExperimentStatus, number> }; nextCursor?: number;
603
- comparison?: { planHash: string; baselineAttemptId: string; variantAttemptId: string; approved: boolean; private: boolean; projection: ReturnType<typeof comparisonProjection> | "[pii]" } }
604
- interface ExperimentContext { task: Task; campaign: ResearchCampaignRecord; private: boolean; key: string; fence: ExperimentWriteFence }
571
+ export type { ExperimentReceipt, ComparisonPlanReceipt, ProtocolApprovalReceipt, ExperimentAttemptView, ExperimentView } from "./tasks-experiment.ts";
605
572
  interface CompletionRefresh { revision: number; commit: string; state: "in_review" | "approved" }
606
573
  interface RefileHeadGuard { recorded?: string }
607
574
  interface IdentityLink { repo: string; pr: number; basis: { commit?: string; branch?: string }; managedRevision?: number }
@@ -644,18 +611,7 @@ function hasReviewAnchorInput(raw: unknown): boolean {
644
611
  } catch { return true; }
645
612
  }
646
613
 
647
- interface GuidanceProbeRuntime {
648
- id: string; by: PeerId; controller: AbortController; current: () => ProbeAdmissionRecheck;
649
- requestedRevision: number; variantId?: string;
650
- ports: GuidanceProbeFakePorts;
651
- reservation?: ProbeReservation; promise?: Promise<ProbePublicReceipt>; stopPromise?: Promise<void>;
652
- launched: boolean; launchSettled: boolean; stopSettled: boolean; stopKnown: boolean; stopRequested: boolean;
653
- watch?: { handle: unknown }; failure?: Error;
654
- }
655
614
  export class Tasks {
656
- private guidanceProbeStopping = false;
657
- private guidanceProbeAdmissions = 0;
658
- private readonly guidanceProbeActive = new Map<string, GuidanceProbeRuntime>();
659
615
  private readonly findingPlacements = new WeakMap<ReviewReadiness, { binding: string; placements: Map<string, ReviewAnchorStatus>; placementOnly: boolean }>();
660
616
  private findingPlacementBinding(task: Task): string {
661
617
  return JSON.stringify([task.id, task.created, this.reviewHead(task), task.refs.paths, task.plan, this.reviewFindingSets(task)]);
@@ -909,9 +865,7 @@ export class Tasks {
909
865
  private readonly repositories: TaskRepositories;
910
866
  private readonly incomingBacklog = new Set<number>();
911
867
  /** One accept attempt per (answer, part), so two concurrent accepts of one part make one draft (#1480 R2 part 2). */
912
- private readonly decompositionAccepts = new Map<string, Promise<unknown>>();
913
868
  /** One apply per milestone while it creates issues, so a retried call cannot POST every planned issue twice (#1480 R2 part 3). */
914
- private readonly roadmapPublishes = new Set<number>();
915
869
  private readonly plannerBacklog = new Map<PeerId, Set<number>>();
916
870
  private readonly plannerBlockedQueue = new Map<PeerId, string>();
917
871
  private readonly knownPlanners = new Set<PeerId>();
@@ -933,12 +887,151 @@ export class Tasks {
933
887
  private readonly heldReviews = new Map<number, { head: string; reviewer: PeerId; revision: number }>();
934
888
  private readonly autoPullAttached = new Set<PeerId>();
935
889
 
890
+ private readonly study: StudyDomain;
891
+ private readonly survey: SurveyDomain;
892
+ private readonly roadmap: RoadmapDomain;
893
+ private readonly roadmapPlan: RoadmapPlanDomain;
894
+ private readonly guidance: GuidanceDomain;
895
+ private readonly experiment: ExperimentDomain;
896
+
936
897
  constructor(private readonly d: TasksDeps) {
898
+ // #1830 S4a: a host property is read through a getter so it is the value at the call, never one captured here.
899
+ const host = this;
900
+ this.study = new StudyDomain(d, {
901
+ cleanRefs: input => cleanRefs(input),
902
+ taskShowAllowed: (actor, task, roles, planner) => taskShowAllowed(actor, task, roles, planner),
903
+ get coordinationModes() { return host.coordinationModes; },
904
+ deliverablePorts: (...args: Parameters<StudyHost["deliverablePorts"]>) => host.deliverablePorts(...args),
905
+ experimentOutputPrivate: (...args: Parameters<StudyHost["experimentOutputPrivate"]>) => host.experimentOutputPrivate(...args),
906
+ get incomingBacklog() { return host.incomingBacklog; },
907
+ isConfiguredPlanner: (...args: Parameters<StudyHost["isConfiguredPlanner"]>) => host.isConfiguredPlanner(...args),
908
+ get isPii() { return host.isPii; },
909
+ get nameable() { return host.nameable; },
910
+ need: (...args: Parameters<StudyHost["need"]>) => host.need(...args),
911
+ places: (...args: Parameters<StudyHost["places"]>) => host.places(...args),
912
+ plannerWriteAuthority: (...args: Parameters<StudyHost["plannerWriteAuthority"]>) => host.plannerWriteAuthority(...args),
913
+ proposalPlanner: (...args: Parameters<StudyHost["proposalPlanner"]>) => host.proposalPlanner(...args),
914
+ get publicMetadataText() { return host.publicMetadataText; },
915
+ get publicTitle() { return host.publicTitle; },
916
+ releaseNotice: (...args: Parameters<StudyHost["releaseNotice"]>) => host.releaseNotice(...args),
917
+ get repositories() { return host.repositories; },
918
+ requestCheck: (...args: Parameters<StudyHost["requestCheck"]>) => host.requestCheck(...args),
919
+ requireLocalTaskPeer: peer => requireLocalTaskPeer(peer),
920
+ sendTask: (...args: Parameters<StudyHost["sendTask"]>) => host.sendTask(...args),
921
+ signalsFor: (...args: Parameters<StudyHost["signalsFor"]>) => host.signalsFor(...args),
922
+ states: (...args: Parameters<StudyHost["states"]>) => host.states(...args),
923
+ warmRepository: (...args: Parameters<StudyHost["warmRepository"]>) => host.warmRepository(...args),
924
+ withholds: (...args: Parameters<StudyHost["withholds"]>) => host.withholds(...args),
925
+ });
926
+ this.survey = new SurveyDomain(d, {
927
+ configuredManualConductor: (...args: Parameters<SurveyHost["configuredManualConductor"]>) => host.configuredManualConductor(...args),
928
+ consideredBefore: (...args: Parameters<SurveyHost["consideredBefore"]>) => host.consideredBefore(...args),
929
+ consideredBrief: (...args: Parameters<SurveyHost["consideredBrief"]>) => host.consideredBrief(...args),
930
+ consideredChanges: (...args: Parameters<SurveyHost["consideredChanges"]>) => host.consideredChanges(...args),
931
+ consideredDetails: (...args: Parameters<SurveyHost["consideredDetails"]>) => host.consideredDetails(...args),
932
+ get incomingBacklog() { return host.incomingBacklog; },
933
+ isConfiguredPlanner: (...args: Parameters<SurveyHost["isConfiguredPlanner"]>) => host.isConfiguredPlanner(...args),
934
+ get isPii() { return host.isPii; },
935
+ need: (...args: Parameters<SurveyHost["need"]>) => host.need(...args),
936
+ observerExcluded: (...args: Parameters<SurveyHost["observerExcluded"]>) => host.observerExcluded(...args),
937
+ propose: (...args: Parameters<SurveyHost["propose"]>) => host.propose(...args),
938
+ get publicMetadataText() { return host.publicMetadataText; },
939
+ releaseNotice: (...args: Parameters<SurveyHost["releaseNotice"]>) => host.releaseNotice(...args),
940
+ get repositories() { return host.repositories; },
941
+ requestCheck: (...args: Parameters<SurveyHost["requestCheck"]>) => host.requestCheck(...args),
942
+ reviewObserverTurn: (...args: Parameters<SurveyHost["reviewObserverTurn"]>) => host.reviewObserverTurn(...args),
943
+ screenCall: (...args: Parameters<SurveyHost["screenCall"]>) => host.screenCall(...args),
944
+ get screenOn() { return host.screenOn; },
945
+ signalsFor: (...args: Parameters<SurveyHost["signalsFor"]>) => host.signalsFor(...args),
946
+ studyHold: (...args: Parameters<SurveyHost["studyHold"]>) => host.studyHold(...args),
947
+ studyNumber: (...args: Parameters<SurveyHost["studyNumber"]>) => host.studyNumber(...args),
948
+ studyWrite: <T>(write: () => Promise<T>) => host.studyWrite(write),
949
+ });
950
+ this.roadmap = new RoadmapDomain(d, {
951
+ configuredManualConductor: (...args: Parameters<RoadmapHost["configuredManualConductor"]>) => host.configuredManualConductor(...args),
952
+ currentSpecReport: (...args: Parameters<RoadmapHost["currentSpecReport"]>) => host.currentSpecReport(...args),
953
+ isConfiguredPlanner: (...args: Parameters<RoadmapHost["isConfiguredPlanner"]>) => host.isConfiguredPlanner(...args),
954
+ get isPii() { return host.isPii; },
955
+ observerExcluded: (...args: Parameters<RoadmapHost["observerExcluded"]>) => host.observerExcluded(...args),
956
+ planIssueIdentity: (...args: Parameters<RoadmapHost["planIssueIdentity"]>) => host.planIssueIdentity(...args),
957
+ get publicMetadataText() { return host.publicMetadataText; },
958
+ get repositories() { return host.repositories; },
959
+ requestCheck: (...args: Parameters<RoadmapHost["requestCheck"]>) => host.requestCheck(...args),
960
+ requireLocalTaskPeer: peer => requireLocalTaskPeer(peer),
961
+ reviewObserverTurn: (...args: Parameters<RoadmapHost["reviewObserverTurn"]>) => host.reviewObserverTurn(...args),
962
+ samePlace: (a, b) => samePlace(a, b),
963
+ screenCall: (...args: Parameters<RoadmapHost["screenCall"]>) => host.screenCall(...args),
964
+ get screenOn() { return host.screenOn; },
965
+ });
966
+ this.roadmapPlan = new RoadmapPlanDomain(d, {
967
+ get incomingBacklog() { return host.incomingBacklog; },
968
+ get isPii() { return host.isPii; },
969
+ milestoneShow: (...args: Parameters<RoadmapPlanHost["milestoneShow"]>) => host.milestoneShow(...args),
970
+ propose: (...args: Parameters<RoadmapPlanHost["propose"]>) => host.propose(...args),
971
+ get publicMetadataText() { return host.publicMetadataText; },
972
+ publicView: (...args: Parameters<RoadmapPlanHost["publicView"]>) => host.publicView(...args),
973
+ releaseNotice: (...args: Parameters<RoadmapPlanHost["releaseNotice"]>) => host.releaseNotice(...args),
974
+ roadmapApplyAuthority: (...args: Parameters<RoadmapPlanHost["roadmapApplyAuthority"]>) => host.roadmapApplyAuthority(...args),
975
+ roadmapCurrent: (...args: Parameters<RoadmapPlanHost["roadmapCurrent"]>) => host.roadmapCurrent(...args),
976
+ roadmapGh: (...args: Parameters<RoadmapPlanHost["roadmapGh"]>) => host.roadmapGh(...args),
977
+ roadmapParsed: <T>(read: () => T): T => host.roadmapParsed(read),
978
+ roadmapReadAuthority: (...args: Parameters<RoadmapPlanHost["roadmapReadAuthority"]>) => host.roadmapReadAuthority(...args),
979
+ roadmapRepo: (...args: Parameters<RoadmapPlanHost["roadmapRepo"]>) => host.roadmapRepo(...args),
980
+ roadmapRepository: (...args: Parameters<RoadmapPlanHost["roadmapRepository"]>) => host.roadmapRepository(...args),
981
+ roadmapResult: (...args: Parameters<RoadmapPlanHost["roadmapResult"]>) => host.roadmapResult(...args),
982
+ roadmapScreen: (...args: Parameters<RoadmapPlanHost["roadmapScreen"]>) => host.roadmapScreen(...args),
983
+ roadmapSnapshot: (...args: Parameters<RoadmapPlanHost["roadmapSnapshot"]>) => host.roadmapSnapshot(...args),
984
+ roadmapWriteAuthority: (...args: Parameters<RoadmapPlanHost["roadmapWriteAuthority"]>) => host.roadmapWriteAuthority(...args),
985
+ screenCall: (...args: Parameters<RoadmapPlanHost["screenCall"]>) => host.screenCall(...args),
986
+ get screenOn() { return host.screenOn; },
987
+ });
988
+ this.guidance = new GuidanceDomain(d, {
989
+ requireConductor: (peer, roles) => requireConductor(peer, roles),
990
+ lineageMetadata: (...args: Parameters<GuidanceHost["lineageMetadata"]>) => host.lineageMetadata(...args),
991
+ lineagePorts: (...args: Parameters<GuidanceHost["lineagePorts"]>) => host.lineagePorts(...args),
992
+ lineageVisible: (...args: Parameters<GuidanceHost["lineageVisible"]>) => host.lineageVisible(...args),
993
+ get nameable() { return host.nameable; },
994
+ personOrConductor: (...args: Parameters<GuidanceHost["personOrConductor"]>) => host.personOrConductor(...args),
995
+ get publicMetadataText() { return host.publicMetadataText; },
996
+ requestCheck: (...args: Parameters<GuidanceHost["requestCheck"]>) => host.requestCheck(...args),
997
+ reviewObserverTurn: (...args: Parameters<GuidanceHost["reviewObserverTurn"]>) => host.reviewObserverTurn(...args),
998
+ screenCall: (...args: Parameters<GuidanceHost["screenCall"]>) => host.screenCall(...args),
999
+ get screenOn() { return host.screenOn; },
1000
+ studyHold: (...args: Parameters<GuidanceHost["studyHold"]>) => host.studyHold(...args),
1001
+ studyWrite: <T>(write: () => Promise<T>) => host.studyWrite(write),
1002
+ });
1003
+ this.experiment = new ExperimentDomain(d, {
1004
+ taskShowAllowed: (actor, task, roles, planner) => taskShowAllowed(actor, task, roles, planner),
1005
+ deliverablePorts: (...args: Parameters<ExperimentHost["deliverablePorts"]>) => host.deliverablePorts(...args),
1006
+ experimentOutputPrivate: (...args: Parameters<ExperimentHost["experimentOutputPrivate"]>) => host.experimentOutputPrivate(...args),
1007
+ isConfiguredPlanner: (...args: Parameters<ExperimentHost["isConfiguredPlanner"]>) => host.isConfiguredPlanner(...args),
1008
+ get isPii() { return host.isPii; },
1009
+ get nameable() { return host.nameable; },
1010
+ get publicMetadataText() { return host.publicMetadataText; },
1011
+ get repositories() { return host.repositories; },
1012
+ requireLocalTaskPeer: peer => requireLocalTaskPeer(peer),
1013
+ requestCheck: (...args: Parameters<ExperimentHost["requestCheck"]>) => host.requestCheck(...args),
1014
+ reviewTaskPrivate: (...args: Parameters<ExperimentHost["reviewTaskPrivate"]>) => host.reviewTaskPrivate(...args),
1015
+ screenCall: (...args: Parameters<ExperimentHost["screenCall"]>) => host.screenCall(...args),
1016
+ get screenOn() { return host.screenOn; },
1017
+ studyFields: (...args: Parameters<ExperimentHost["studyFields"]>) => host.studyFields(...args),
1018
+ studyHold: (...args: Parameters<ExperimentHost["studyHold"]>) => host.studyHold(...args),
1019
+ studyId: (...args: Parameters<ExperimentHost["studyId"]>) => host.studyId(...args),
1020
+ studyNumber: (...args: Parameters<ExperimentHost["studyNumber"]>) => host.studyNumber(...args),
1021
+ studyParent: (...args: Parameters<ExperimentHost["studyParent"]>) => host.studyParent(...args),
1022
+ studyRecord: (...args: Parameters<ExperimentHost["studyRecord"]>) => host.studyRecord(...args),
1023
+ studyReplayPrivacy: (...args: Parameters<ExperimentHost["studyReplayPrivacy"]>) => host.studyReplayPrivacy(...args),
1024
+ studySource: (...args: Parameters<ExperimentHost["studySource"]>) => host.studySource(...args),
1025
+ studyTime: (...args: Parameters<ExperimentHost["studyTime"]>) => host.studyTime(...args),
1026
+ studyWrite: <T>(write: () => Promise<T>) => host.studyWrite(write),
1027
+ withholds: (...args: Parameters<ExperimentHost["withholds"]>) => host.withholds(...args),
1028
+ });
937
1029
  this.ciWatchers = new CiWatchers({
938
1030
  ...d.ciWatch,
939
- poll: watch => pollCi(watch, watch.head, d.sdlc ? requiredChecksFor(d.sdlc.config(), watch.repo) : [], d.sdlc?.gh ?? sdlcGh),
1031
+ poll: watch => pollCi(watch, watch.head, d.sdlc ? requiredChecksFor(d.sdlc.config(), watch.repo) : [], d.sdlc?.gh ?? sdlcGh, true),
940
1032
  current: watch => this.ciWatchCurrent(watch),
941
- finish: (watch, outcome) => this.ciCompleted(watch, outcome),
1033
+ retry: (watch, retry, completed, mergeable) => this.retryCiShard(watch, retry, completed, mergeable),
1034
+ finish: (watch, outcome, snapshot) => this.ciCompleted(watch, outcome, snapshot),
942
1035
  });
943
1036
  d.board.trackPlanRevisions = () => (d.sdlc?.config().mode ?? "off") !== "off";
944
1037
  this.repositories = new TaskRepositories(d.cwd, d.repository);
@@ -1157,6 +1250,7 @@ export class Tasks {
1157
1250
  const task = validate();
1158
1251
  if (task.history.length !== revision) refuse(`task #${task.id}: it changed while the reason was screened; read it with hub_task_show and record the wait again`);
1159
1252
  const next = this.d.board.update(task.id, by, "wait recorded", {}, reason, { wait: { until, owner: task.owner! }, ...(pii || withheld ? { withheld: true as const } : {}) }, revision);
1253
+ this.watchCi(next);
1160
1254
  this.d.notify(`task ${this.publicTitle(next)}: wait recorded by ${by} until ${new Date(until).toISOString()}`);
1161
1255
  return next;
1162
1256
  }
@@ -2281,271 +2375,62 @@ export class Tasks {
2281
2375
  this.planningAuthority(by, task);
2282
2376
  }
2283
2377
 
2284
- private studiesRunning = 0;
2285
- private studyStopped = false;
2286
- private readonly studyDrainWaiters = new Set<() => void>();
2287
- studiesPending = (): number => this.studiesRunning;
2378
+ async stopStudies(): Promise<void> { await this.study.stopStudies(); }
2379
+ studiesPending = (): number => this.study.studiesPending();
2380
+ private studyHold(): string | undefined { return this.study.studyHold(); }
2381
+ private async studyWrite<T>(write: () => Promise<T>): Promise<T> { return this.study.studyWrite(write); }
2382
+ private studyFields(input: unknown, allowed: readonly string[]): Record<string, unknown> { return this.study.studyFields(input, allowed); }
2383
+ private studyId(value: unknown): string { return this.study.studyId(value); }
2384
+ private studyNumber(value: unknown, field: string): number { return this.study.studyNumber(value, field); }
2385
+ private studyTime(): number { return this.study.studyTime(); }
2386
+ private studyRecord(id: string, revision?: number): ResearchCampaignRecord { return this.study.studyRecord(id, revision); }
2387
+ private studyParent(id: number): Task { return this.study.studyParent(id); }
2388
+ private studySource(id: string): { id: string; sha256: string; private: boolean } | undefined { return this.study.studySource(id); }
2389
+ private studyDispatchReason(task: Task, owner?: PeerId): string | undefined { return this.study.studyDispatchReason(task, owner); }
2390
+ private studyDispatchCheck(task: Task, owner?: PeerId): void { return this.study.studyDispatchCheck(task, owner); }
2391
+ private studyExcludedOwners(task: Task): PeerId[] { return this.study.studyExcludedOwners(task); }
2392
+ async studyHandoff(by: PeerId, input: unknown): Promise<{ campaignId: string; unitId: string; seq: number }> { return this.study.studyHandoff(by, input); }
2393
+ studyList(by: PeerId, input: unknown): { campaigns: ResearchCampaignReceipt[]; next?: string } { return this.study.studyList(by, input); }
2394
+ studyShow(by: PeerId, input: unknown): ReturnType<typeof studyProjection> { return this.study.studyShow(by, input); }
2395
+ private studyReplayPrivacy(record: ResearchCampaignRecord, parent: Task): boolean { return this.study.studyReplayPrivacy(record, parent); }
2396
+ async studyDraft(by: PeerId, input: unknown): Promise<ResearchCampaignReceipt> { return this.study.studyDraft(by, input); }
2397
+ async studyRevise(by: PeerId, input: unknown): Promise<ResearchCampaignReceipt> { return this.study.studyRevise(by, input); }
2398
+ async studyApprove(by: PeerId, input: unknown): Promise<ResearchCampaignReceipt> { return this.study.studyApprove(by, input); }
2399
+ async studyClose(by: PeerId, input: unknown): Promise<ResearchCampaignReceipt> { return this.study.studyClose(by, input); }
2400
+ async synthesisEvidence(by: PeerId, input: unknown) { return this.study.synthesisEvidence(by, input); }
2401
+ async synthesisCheck(by: PeerId, input: unknown): Promise<SynthesisReadiness | { taskId: number; status: "unavailable" | "stale"; cause: string }> { return this.study.synthesisCheck(by, input); }
2402
+ private synthesisInspect(by: PeerId, input: unknown): Promise<SynthesisReadiness | { taskId: number; status: "unavailable" | "stale"; cause: string }>;
2403
+ private synthesisInspect(by: PeerId, input: unknown, onSnapshot: (manifest: SynthesisManifestV1, current: SynthesisCurrent, report: SynthesisReadiness, valid: () => boolean) => Task): Promise<Task | SynthesisReadiness | { taskId: number; status: "unavailable" | "stale"; cause: string }>;
2404
+ private async synthesisInspect(by: PeerId, input: unknown, onSnapshot?: (manifest: SynthesisManifestV1, current: SynthesisCurrent, report: SynthesisReadiness, valid: () => boolean) => Task): Promise<Task | SynthesisReadiness | { taskId: number; status: "unavailable" | "stale"; cause: string }> { return onSnapshot ? this.study.synthesisInspect(by, input, onSnapshot) : this.study.synthesisInspect(by, input); }
2405
+ private surveyPrivate(task: Task, by?: PeerId): boolean { return this.survey.surveyPrivate(task, by); }
2406
+ async surveyStart(by: PeerId, input: unknown = {}, fence?: () => string | undefined): Promise<{ task: number; survey: number; ref: string; focus?: SurveyFocus }> { return this.survey.surveyStart(by, input, fence); }
2407
+ surveyShow(by: PeerId, id: unknown) { return this.survey.surveyShow(by, id); }
2408
+ async surveyReport(by: PeerId, input: unknown, fence?: () => string | undefined) { return this.survey.surveyReport(by, input, fence); }
2409
+
2410
+
2411
+
2288
2412
 
2289
- async stopStudies(): Promise<void> {
2290
- this.studyStopped = true;
2291
- if (this.studiesRunning) await new Promise<void>(resolve => this.studyDrainWaiters.add(resolve));
2292
- }
2293
2413
 
2294
- private studyHold(): string | undefined {
2295
- try {
2296
- if (this.studyStopped || this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError)
2297
- return "study writes are held by recovery, shutdown or storage failure";
2298
- } catch { return "study write admission is unavailable"; }
2299
- return undefined;
2300
- }
2301
2414
 
2302
- private async studyWrite<T>(write: () => Promise<T>): Promise<T> {
2303
- this.studiesRunning++;
2304
- try { return await write(); } finally {
2305
- if (--this.studiesRunning === 0) { for (const resolve of this.studyDrainWaiters) resolve(); this.studyDrainWaiters.clear(); }
2306
- }
2307
- }
2308
2415
 
2309
- private studyFields(input: unknown, allowed: readonly string[]): Record<string, unknown> {
2310
- if (!input || typeof input !== "object" || Array.isArray(input) || types.isProxy(input)
2311
- || ![Object.prototype, null].includes(Object.getPrototypeOf(input)) || Object.getOwnPropertySymbols(input).length)
2312
- throw new PreEffectToolRefusal("study request must be a plain data object");
2313
- const fields = Object.getOwnPropertyDescriptors(input);
2314
- if (Object.entries(fields).some(([key, descriptor]) => !allowed.includes(key) || !Object.hasOwn(descriptor, "value")))
2315
- throw new PreEffectToolRefusal("study request has unknown fields or accessors");
2316
- return Object.fromEntries(Object.entries(fields).map(([key, descriptor]) => [key, descriptor.value]));
2317
- }
2318
2416
 
2319
- private studyId(value: unknown): string {
2320
- if (typeof value !== "string" || !/^rc-[a-f0-9]{12}$/.test(value)) throw new PreEffectToolRefusal("study id is invalid");
2321
- return value;
2322
- }
2323
2417
 
2324
- private studyNumber(value: unknown, field: string): number {
2325
- if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1) throw new PreEffectToolRefusal(`${field} must be a positive integer`);
2326
- return value;
2327
- }
2328
2418
 
2329
- private studyContract(value: unknown): ResearchCampaignContract {
2330
- try { return parseResearchCampaign(value); }
2331
- catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "invalid study contract"); }
2332
- }
2333
2419
 
2334
- private studyTime(): number {
2335
- const now = this.d.studyNow?.() ?? Date.now();
2336
- if (!Number.isFinite(now)) throw new PreEffectToolRefusal("study clock is unavailable");
2337
- return now;
2338
- }
2339
2420
 
2340
- private studyRecord(id: string, revision?: number): ResearchCampaignRecord {
2341
- let record: ResearchCampaignRecord | undefined;
2342
- try { record = this.d.board.researchCampaign(id, revision); }
2343
- catch { throw new PreEffectToolRefusal("study record is unavailable or invalid"); }
2344
- if (!record || record.project !== this.d.project) throw new PreEffectToolRefusal("study is unavailable in this project");
2345
- return record;
2346
- }
2347
2421
 
2348
- private studyParent(id: number): Task {
2349
- const parent = this.need(id, false, true, true);
2350
- if (this.places(parent).repositoryKey !== this.repositories.scope({}).key) throw new PreEffectToolRefusal("study parent is outside this project");
2351
- return parent;
2352
- }
2353
2422
 
2354
- /** Write receipts expose no contract text; only person-only approval returns the unit mapping. */
2355
- private studyReceipt(record: ResearchCampaignRecord, includeMapping = false): ResearchCampaignReceipt {
2356
- const units = this.d.board.researchCampaignBindings(record.id, record.revision);
2357
- return { id: record.id, parentTaskId: record.parentTaskId, revision: record.revision, status: record.status,
2358
- unitCount: units.length, units: includeMapping ? units : [] };
2359
- }
2360
2423
 
2361
- private studySource(id: string): { id: string; sha256: string; private: boolean } | undefined {
2362
- try {
2363
- const source = this.d.studySource?.(id);
2364
- return source && source.id === id && /^[a-f0-9]{64}$/.test(source.sha256) && typeof source.private === "boolean"
2365
- ? { id: source.id, sha256: source.sha256, private: source.private } : undefined;
2366
- } catch { return undefined; }
2367
- }
2368
2424
 
2369
- private studyLatest(id: string, revision: number): ResearchCampaignRecord {
2370
- const record = this.studyRecord(id);
2371
- if (record.revision !== revision || record.status === "closed") throw new PreEffectToolRefusal("study revision is stale or closed");
2372
- return record;
2373
- }
2374
2425
 
2375
- private studyFamily(parent: Task): Set<number> {
2376
- if (!parent.history.some(entry => entry.event === "draft approved")) throw new PreEffectToolRefusal("adoption requires an approved intake family");
2377
- const family = new Set<number>(), pending = [...(parent.deps ?? [])];
2378
- // ponytail: 512 dependency nodes bound intake provenance walks; a larger family needs indexed family identities.
2379
- while (pending.length) {
2380
- const id = pending.pop()!;
2381
- if (family.has(id)) continue;
2382
- if (family.size >= 512) throw new PreEffectToolRefusal("study intake family exceeds its bounded scope");
2383
- const task = this.d.board.get(id);
2384
- if (!task) throw new PreEffectToolRefusal("study intake family is incomplete");
2385
- family.add(id); pending.push(...(task.deps ?? []));
2386
- }
2387
- family.delete(parent.id);
2388
- return family;
2389
- }
2390
2426
 
2391
- private studyReferences(parentId: number, contract: ResearchCampaignContract, campaignId?: string): StudyReferences {
2392
- const parent = this.studyParent(parentId);
2393
- const profile = parent.profile ?? "dev", storedProfile = profile === (this.d.profile ?? "dev") ? this.d.profileData ?? profile : profile;
2394
- try {
2395
- if (profileClass(parent.profileClass ?? parent.class, storedProfile) !== parent.class) throw new Error("changed class");
2396
- } catch { throw new PreEffectToolRefusal("study parent profile class is unavailable or changed"); }
2397
- const sources = contract.sourceIds.map(id => {
2398
- const source = this.studySource(id);
2399
- if (!source)
2400
- throw new PreEffectToolRefusal("study source is unavailable in this project");
2401
- return source;
2402
- });
2403
- if (contract.budget) {
2404
- const budget = this.d.executionBudget?.status(contract.budget.id);
2405
- if (!budget || Array.isArray(budget)) throw new PreEffectToolRefusal("study budget is unavailable");
2406
- }
2407
- const adopted = new Map<string, Task>();
2408
- const family = contract.units.some(unit => unit.adoptTaskId !== undefined) ? this.studyFamily(parent) : new Set<number>();
2409
- for (const unit of contract.units) if (unit.adoptTaskId !== undefined) {
2410
- const task = this.studyParent(unit.adoptTaskId);
2411
- if (!family.has(task.id) || task.draft || !task.history.some(entry => entry.event === "draft approved"))
2412
- throw new PreEffectToolRefusal("study unit must adopt an approved intake child");
2413
- const binding = this.d.board.researchTaskBinding(task.id);
2414
- if (binding && (binding.campaignId !== campaignId || binding.unitId !== unit.id)) throw new PreEffectToolRefusal("intake child is already bound to another study unit");
2415
- adopted.set(unit.id, task);
2416
- }
2417
- const reused = new Map<string, Task>();
2418
- if (campaignId) for (const unit of contract.units) {
2419
- const previous = this.d.board.researchLatestUnitBinding(campaignId, unit.id);
2420
- if (previous) reused.set(unit.id, this.studyParent(previous.taskId));
2421
- }
2422
- const priv = this.isPii(parent) || sources.some(source => source.private) || [...adopted.values(), ...reused.values()].some(task => this.isPii(task))
2423
- || !this.nameable(JSON.stringify(contract));
2424
- const flows = (rows: Map<string, Task>) => [...rows].map(([unit, task]) => [unit, task.id, task.history.length]);
2425
- return { parent, adopted, reused, private: priv, key: JSON.stringify([parent.history.length, sources, flows(adopted), flows(reused), priv]) };
2426
- }
2427
-
2428
- /** Always re-read persisted approval and limits at the dispatch write, including after a metadata await. */
2429
- private studyDispatchReason(task: Task, owner?: PeerId): string | undefined {
2430
- try {
2431
- const bound = this.d.board.researchDispatchBinding(task.id);
2432
- if (!bound) return undefined;
2433
- const { campaign, binding } = bound;
2434
- if (campaign.project !== this.d.project || campaign.status !== "approved" || !binding) return "study revision is not approved or its unit was removed";
2435
- const stop = campaign.contract.stopPolicy;
2436
- if (Date.parse(stop.deadline) <= this.studyTime()) return "study deadline has expired";
2437
- const units = this.d.board.researchCampaignBindings(campaign.id, campaign.revision);
2438
- if (units.length > stop.maxUnits || binding.round > stop.maxFollowUpRounds) return "study stop limit exceeded";
2439
- const budget = campaign.contract.budget;
2440
- if (budget?.hardCap.length) {
2441
- const ledger = this.d.executionBudget, current = ledger?.status(budget.id);
2442
- if (!ledger || !current || Array.isArray(current) || !campaign.eligibleOwners?.length ||
2443
- budget.hardCap.some(resource => resource === "tokens" || current.limits[resource] === undefined || resource === "model_calls" && current.limits.tokens !== undefined)) return "study hard-cap budget is unavailable";
2444
- if (budget.hardCap.some(resource => !current.units[resource] || current.units[resource]!.remaining <= 0 || current.units[resource]!.reason === "unknown_usage")) return "study hard-cap budget is exhausted or usage is unknown";
2445
- if (owner && (!campaign.eligibleOwners.includes(owner) || !ledger.covers(budget.id, task.id, owner, budget.hardCap)))
2446
- return "study owner is not covered by its named hard-cap budget";
2447
- }
2448
- return undefined;
2449
- } catch { return "study dispatch evidence is unavailable"; }
2450
- }
2451
2427
 
2452
- private studyDispatchCheck(task: Task, owner?: PeerId): void {
2453
- const reason = this.studyDispatchReason(task, owner);
2454
- if (reason) throw new PreEffectToolRefusal(reason);
2455
- }
2456
2428
 
2457
- private studyExcludedOwners(task: Task): PeerId[] {
2458
- return Object.keys(this.states()).filter(peer => this.studyDispatchReason(task, peer) !== undefined);
2459
- }
2460
2429
 
2461
- private studyEligibleOwners(contract: ResearchCampaignContract): string[] | undefined {
2462
- if (!contract.budget?.hardCap.length) return undefined;
2463
- const ledger = this.d.executionBudget, budget = ledger?.status(contract.budget.id);
2464
- if (!ledger || !budget || Array.isArray(budget) || contract.budget.hardCap.some(resource => resource === "tokens" || budget.limits[resource] === undefined || resource === "model_calls" && budget.limits.tokens !== undefined))
2465
- throw new PreEffectToolRefusal("study hard-cap requires an enabled budget with supported resource limits");
2466
- const eligible = budget.peers.filter(peer => ledger.instrumented(peer)).sort();
2467
- if (!eligible.length) throw new PreEffectToolRefusal("study hard-cap has no instrumented eligible owner");
2468
- return eligible;
2469
- }
2470
2430
 
2471
- private studyRoundCheck(original: ResearchCampaignRecord, contract: ResearchCampaignContract): void {
2472
- const added = contract.units.filter(unit => unit.round > 0 && !original.contract.units.some(previous => previous.id === unit.id && previous.round === unit.round));
2473
- if (!added.length) return;
2474
- const stored = this.d.board.researchCampaignBindings(original.id, original.revision), handoffs = this.d.board.researchHandoffs(original.id, original.revision);
2475
- for (const unit of added) {
2476
- // The revised contract decides which discovery units precede this round: a discovery added in the same revision has no stored binding, so it has no handoff and refuses.
2477
- const previous = contract.units.filter(value => value.round === unit.round - 1 && value.purpose === "discovery");
2478
- if (!previous.length || previous.some(value => {
2479
- const binding = stored.find(bound => bound.unitId === value.id && bound.round === value.round && bound.purpose === "discovery");
2480
- const handoff = binding && handoffs.find(handoff => handoff.handoff.unitId === value.id);
2481
- return !handoff || !handoff.handoff.insufficientEvidence && value.sourceIds.some(source => !handoff.handoff.evidence.some(item => item.sourceId === source));
2482
- })) throw new PreEffectToolRefusal("follow-up rounds require complete stored discovery handoffs or insufficientEvidence");
2483
- }
2484
- }
2485
2431
 
2486
- async studyHandoff(by: PeerId, input: unknown): Promise<{ campaignId: string; unitId: string; seq: number }> {
2487
- const requestCheck = this.requestCheck(by, () => this.studyHold());
2488
- let handoff: ReturnType<typeof parseResearchHandoff>;
2489
- try { handoff = parseResearchHandoff(input); } catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "invalid study handoff"); }
2490
- return this.studyWrite(async () => {
2491
- const campaign = this.studyRecord(handoff.campaignId, handoff.revision), task = this.studyParent(handoff.taskId);
2492
- if (by !== task.owner || task.state !== "in_progress" || this.d.privateTurn?.(by) && !this.isPii(task)) throw new PreEffectToolRefusal("handoff requires the current in-progress unit owner");
2493
- const sources = campaign.contract.sourceIds.map(id => this.studySource(id));
2494
- if (sources.some(source => !source)) throw new PreEffectToolRefusal("study handoff source is unavailable");
2495
- const sourceKey = JSON.stringify(sources);
2496
- const text = JSON.stringify(handoff);
2497
- const withheld = !this.nameable(text) || looksSecret(text) || await this.withholds("note", text, task);
2498
- requestCheck();
2499
- const current = this.studyParent(task.id);
2500
- if (current.history.length !== task.history.length || current.owner !== by || current.state !== "in_progress") throw new PreEffectToolRefusal("study handoff task changed during screening");
2501
- if (JSON.stringify(campaign.contract.sourceIds.map(id => this.studySource(id))) !== sourceKey) throw new PreEffectToolRefusal("study handoff sources changed during screening");
2502
- if ((withheld || this.studyReplayPrivacy(campaign, this.studyParent(campaign.parentTaskId))) && !this.isPii(current)) throw new PreEffectToolRefusal("study handoff privacy requires private task authority");
2503
- requestCheck();
2504
- try {
2505
- const saved = this.d.board.recordResearchHandoff(handoff, this.d.project, by, this.studyTime(), current.history.length);
2506
- return { campaignId: saved.handoff.campaignId, unitId: saved.handoff.unitId, seq: saved.seq };
2507
- } catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "study handoff was not saved"); }
2508
- });
2509
- }
2510
2432
 
2511
- /**
2512
- * #601: one page of receipts, one per campaign of this project, newest revision, never its question, scope, sources or unit text. At most 50 rows per call (the spec's readback bound), in id
2513
- * order, strictly after the optional cursor `after`; `next` names the last id of a page that has more behind it. The bound is in the Board query, not in a slice after loading everything.
2514
- */
2515
- studyList(by: PeerId, input: unknown): { campaigns: ResearchCampaignReceipt[]; next?: string } {
2516
- requireLocalTaskPeer(by);
2517
- const fields = this.studyFields(input, ["after"]);
2518
- const after = fields.after === undefined ? undefined : this.studyId(fields.after);
2519
- const page = this.d.board.researchCampaignPage(this.d.project, after, 50);
2520
- return { campaigns: page.ids.map(id => this.studyReceipt(this.studyRecord(id))), ...(page.next ? { next: page.next } : {}) };
2521
- }
2522
2433
 
2523
- studyShow(by: PeerId, input: unknown): ReturnType<typeof studyProjection> {
2524
- requireLocalTaskPeer(by);
2525
- const fields = this.studyFields(input, ["id"]), campaign = this.studyRecord(this.studyId(fields.id));
2526
- const bindings = this.d.board.researchCampaignBindings(campaign.id, campaign.revision);
2527
- const tasks = bindings.map(unit => this.d.board.get(unit.taskId)).filter((task): task is Task => !!task);
2528
- const ledger = this.d.executionBudget, configured = campaign.contract.budget, budget = configured && ledger?.status(configured.id);
2529
- const instrumentedPeers = tasks.flatMap(task => task.owner && ledger?.instrumented(task.owner) ? [task.owner] : []);
2530
- const projection = studyProjection({ campaign, bindings, tasks, handoffs: this.d.board.researchHandoffs(campaign.id), now: this.studyTime(), instrumentedPeers,
2531
- ...(budget && !Array.isArray(budget) ? { budget: { ...budget, coveredTaskIds: tasks.filter(task => task.owner && ledger?.covers(budget.id, task.id, task.owner, [])).map(task => task.id) } } : {}) });
2532
- projection.reasons = [...new Set([...projection.reasons, ...tasks.flatMap(task => { const reason = this.studyDispatchReason(task, task.owner ?? undefined); return reason ? [reason] : []; })])];
2533
- projection.held = projection.reasons.length > 0;
2534
- if (this.studyReplayPrivacy(campaign, this.studyParent(campaign.parentTaskId))) {
2535
- // IDs, counts, states and resource names only. Source references are private view data too.
2536
- for (const unit of projection.units) { unit.sourceIds = []; unit.duplicateSourceIds = []; unit.handoff.coveredSourceIds = []; }
2537
- }
2538
- return projection;
2539
- }
2540
-
2541
- private studyReplayPrivacy(record: ResearchCampaignRecord, parent: Task): boolean {
2542
- return record.private || this.isPii(parent) || record.contract.sourceIds.some(id => {
2543
- const source = this.studySource(id);
2544
- return !source || source.private;
2545
- }) || this.d.board.researchCampaignBindings(record.id, record.revision).some(unit => {
2546
- const task = this.d.board.get(unit.taskId); return !task || this.isPii(task);
2547
- });
2548
- }
2549
2434
 
2550
2435
  /**
2551
2436
  * #604 (agent-hub#1030), ORIGIN side. Who may hand work to another project: the person, or a configured planner, or the conductor. The host (the daemon) has already resolved and
@@ -2717,462 +2602,15 @@ export class Tasks {
2717
2602
 
2718
2603
  /** ORIGIN side, readback: what this project handed over, with the last state each target reported. */
2719
2604
  handoffList(): HandoffOutboundRow[] { return this.d.board.handoffOutbound(); }
2605
+ experimentApproveProtocol(...args: Parameters<ExperimentDomain["experimentApproveProtocol"]>): ReturnType<ExperimentDomain["experimentApproveProtocol"]> { return this.experiment.experimentApproveProtocol(...args); }
2720
2606
 
2721
- async studyDraft(by: PeerId, input: unknown): Promise<ResearchCampaignReceipt> {
2722
- const requestCheck = this.requestCheck(by, () => this.studyHold()); this.plannerWriteAuthority(by);
2723
- const fields = this.studyFields(input, ["parentTaskId", "contract"]), parentId = this.studyNumber(fields.parentTaskId, "parentTaskId");
2724
- const contract = this.studyContract(fields.contract);
2725
- if (contract.units.some(unit => unit.round !== 0)) throw new PreEffectToolRefusal("an initial study contains only round zero");
2726
- return this.studyWrite(async () => {
2727
- this.plannerWriteAuthority(by, this.studyParent(parentId));
2728
- const before = this.studyReferences(parentId, contract);
2729
- const withheld = await this.withholds("note", JSON.stringify(contract), before.parent);
2730
- requestCheck();
2731
- const current = this.studyReferences(parentId, contract); this.plannerWriteAuthority(by, current.parent);
2732
- if (current.key !== before.key) throw new PreEffectToolRefusal("study references changed during draft screening");
2733
- const record: ResearchCampaignRecord = { id: `rc-${randomBytes(6).toString("hex")}`, project: this.d.project, parentTaskId: parentId,
2734
- revision: 1, status: "draft", contract, hash: campaignHash(contract), private: current.private || withheld, createdBy: by, createdAt: this.studyTime() };
2735
- let saved: ResearchCampaignRecord;
2736
- requestCheck(); this.plannerWriteAuthority(by, current.parent);
2737
- try { saved = this.d.board.saveResearchCampaignDraft(record, undefined, current.parent.history.length); }
2738
- catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "study draft was not saved"); }
2739
- this.releaseNotice(`study ${saved.id} revision ${saved.revision} drafted`);
2740
- return this.studyReceipt(saved);
2741
- });
2742
- }
2743
-
2744
- async studyRevise(by: PeerId, input: unknown): Promise<ResearchCampaignReceipt> {
2745
- const requestCheck = this.requestCheck(by, () => this.studyHold()); this.plannerWriteAuthority(by);
2746
- const fields = this.studyFields(input, ["id", "revision", "contract"]), id = this.studyId(fields.id), revision = this.studyNumber(fields.revision, "revision");
2747
- const contract = this.studyContract(fields.contract);
2748
- return this.studyWrite(async () => {
2749
- const original = this.studyLatest(id, revision);
2750
- this.plannerWriteAuthority(by, this.studyParent(original.parentTaskId));
2751
- const before = this.studyReferences(original.parentTaskId, contract, id);
2752
- this.studyRoundCheck(original, contract);
2753
- const withheld = await this.withholds("note", JSON.stringify(contract), before.parent);
2754
- requestCheck();
2755
- const latest = this.studyLatest(id, revision), current = this.studyReferences(latest.parentTaskId, contract, id);
2756
- this.plannerWriteAuthority(by, current.parent);
2757
- if (latest.hash !== original.hash || current.key !== before.key) throw new PreEffectToolRefusal("study changed during revision screening");
2758
- this.studyRoundCheck(latest, contract);
2759
- const next: ResearchCampaignRecord = { id, project: this.d.project, parentTaskId: latest.parentTaskId, revision: revision + 1, status: "draft",
2760
- contract, hash: campaignHash(contract), private: latest.private || current.private || withheld, createdBy: by, createdAt: this.studyTime() };
2761
- let saved: ResearchCampaignRecord;
2762
- requestCheck(); this.plannerWriteAuthority(by, current.parent);
2763
- try { saved = this.d.board.saveResearchCampaignDraft(next, revision, current.parent.history.length); }
2764
- catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "study revision was not saved"); }
2765
- this.releaseNotice(`study ${id} revision ${saved.revision} drafted`);
2766
- return this.studyReceipt(saved);
2767
- });
2768
- }
2769
-
2770
- async studyApprove(by: PeerId, input: unknown): Promise<ResearchCampaignReceipt> {
2771
- const requestCheck = this.requestCheck(by, () => this.studyHold());
2772
- if (by !== USER) throw new PreEffectToolRefusal("study approval requires the person");
2773
- const fields = this.studyFields(input, ["id", "revision"]), id = this.studyId(fields.id), revision = this.studyNumber(fields.revision, "revision");
2774
- return this.studyWrite(async () => {
2775
- const original = this.studyRecord(id, revision), parent = this.studyParent(original.parentTaskId);
2776
- if (original.status === "approved") {
2777
- const privacy = this.studyReplayPrivacy(original, parent); requestCheck();
2778
- const replay = this.d.board.activateCampaign(id, revision, this.d.project, by, this.studyTime(), [], parent.history.length, privacy);
2779
- return this.studyReceipt(replay.campaign, true);
2780
- }
2781
- this.studyLatest(id, revision);
2782
- if (original.status !== "draft" || parent.draft) throw new PreEffectToolRefusal("study approval requires a draft and an approved parent input");
2783
- this.studyEligibleOwners(original.contract);
2784
- const before = this.studyReferences(parent.id, original.contract, id);
2785
- let priv = original.private || before.private || await this.withholds("note", JSON.stringify(original.contract), parent);
2786
- const prepared: PreparedResearchUnit[] = [];
2787
- for (const unit of original.contract.units) {
2788
- requestCheck();
2789
- const reused = before.reused.get(unit.id);
2790
- if (reused) { prepared.push({ unitId: unit.id, reuse: { taskId: reused.id, flowRevision: reused.history.length } }); continue; }
2791
- const adopted = before.adopted.get(unit.id);
2792
- if (adopted) { prepared.push({ unitId: unit.id, adopt: { taskId: adopted.id, flowRevision: adopted.history.length } }); continue; }
2793
- const title = `Study unit ${unit.id}`, detail = `Study: ${id} unit ${unit.id}\nQuestion: ${unit.question}\nPerspective: ${unit.perspective}\nRequired output: ${unit.requiredOutput}\nSources: ${unit.sourceIds.join(", ")}`;
2794
- priv ||= await this.withholds("task", detail, parent);
2795
- const refs = cleanRefs(parent.refs), signals = [...new Set([...this.signalsFor({ title, detail, refs }), ...parent.signals.filter(signal => ["pii", "pii_path", "urgent"].includes(signal))])];
2796
- prepared.push({ unitId: unit.id, create: { title, detail, class: parent.class, refs, signals,
2797
- ...(parent.profile ? { profile: parent.profile } : {}), ...(parent.profileClass ? { profileClass: parent.profileClass } : {}),
2798
- } });
2799
- }
2800
- requestCheck();
2801
- const latest = this.studyLatest(id, revision), current = this.studyReferences(parent.id, original.contract, id);
2802
- if (latest.hash !== original.hash || current.key !== before.key) throw new PreEffectToolRefusal("study changed during approval screening");
2803
- const now = this.studyTime(), deadline = Date.parse(original.contract.stopPolicy.deadline);
2804
- if (deadline <= now || deadline - now > 90 * 86_400_000) throw new PreEffectToolRefusal("study deadline must be in the next ninety days at approval");
2805
- priv ||= latest.private || current.private;
2806
- const instruction = instructedExecution.getStore();
2807
- if (instruction?.active) {
2808
- instruction.current();
2809
- if (priv || prepared.some(unit => unit.create?.signals?.some(signal => signal === "pii" || signal === "pii_path"))) throw new PreEffectToolRefusal("an instructed study approval cannot create private work; run it in a terminal");
2810
- }
2811
- if (priv && [...current.adopted.values(), ...current.reused.values()].some(task => !this.isPii(task)))
2812
- throw new PreEffectToolRefusal("a private study cannot retain a public task without changing its authority");
2813
- for (const unit of prepared) if (unit.create) {
2814
- if (priv && !unit.create.signals?.includes("pii")) unit.create.signals = [...(unit.create.signals ?? []), "pii"];
2815
- const planner = this.proposalPlanner({ ...parent, ...unit.create, signals: unit.create.signals ?? [], refs: unit.create.refs ?? {}, draft: undefined, state: "backlog", owner: null, reviewer: null });
2816
- unit.create.planner = planner.planner; unit.create.plannerReason = planner.plannerReason;
2817
- this.warmRepository({ refs: unit.create.refs ?? {}, plan: unit.create.plan });
2818
- }
2819
- const mode = this.d.coordination?.();
2820
- let result: ReturnType<Board["activateCampaign"]>;
2821
- requestCheck();
2822
- instruction?.beginStudy?.(); // The synchronous board transaction now owns the screened binding.
2823
- try { result = this.d.board.activateCampaign(id, revision, this.d.project, by, now, prepared, current.parent.history.length, priv, { eligibleOwners: this.studyEligibleOwners(original.contract) }); }
2824
- catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "study approval was not saved"); }
2825
- for (const child of result.children) {
2826
- this.incomingBacklog.add(child.id);
2827
- if (mode !== undefined) this.coordinationModes.set(child.id, mode);
2828
- }
2829
- this.releaseNotice(`study ${id} revision ${revision} approved; ${result.bindings.length} units`);
2830
- await this.studyReoffer(result.bindings.map(unit => unit.taskId));
2831
- return this.studyReceipt(result.campaign, true);
2832
- });
2833
- }
2834
-
2835
- /**
2836
- * A unit held only because a newer draft existed lost its queued offer at delivery. Once a revision is approved, each retained unit task whose offer was dropped, that still has
2837
- * the same owner and has not been accepted, gets a fresh offer through the one offer path (`sendTask`), which re-runs `studyDispatchCheck`. The approval is already saved: a
2838
- * refusal here is a notice, never a failure of the approval.
2839
- */
2840
- private async studyReoffer(taskIds: readonly number[]): Promise<void> {
2841
- for (const taskId of taskIds) {
2842
- let owner: PeerId | undefined;
2843
- try { owner = this.d.board.researchDroppedOffer(taskId); } catch (e) { this.releaseNotice(`task #${taskId}: study dropped-offer record is unreadable: ${e instanceof Error ? e.message : String(e)}`); continue; }
2844
- if (owner === undefined) continue;
2845
- const task = this.d.board.get(taskId);
2846
- // The record names an owner that no longer holds the unproposed task: it is stale, not a pending offer.
2847
- if (!task || task.owner !== owner || task.state !== "proposed") { this.d.board.clearResearchDroppedOffer(taskId); continue; }
2848
- try {
2849
- await this.sendTask(task, { owner, ...(task.reviewer ? { reviewer: task.reviewer } : {}), trace: [] });
2850
- this.d.board.clearResearchDroppedOffer(taskId); // after the offer is published: a refusal keeps the record for the next approval
2851
- } catch (e) { this.releaseNotice(`task ${this.publicTitle(task)}: could not re-offer after the study was approved: ${e instanceof Error ? e.message : String(e)}`); }
2852
- }
2853
- }
2854
-
2855
- async studyClose(by: PeerId, input: unknown): Promise<ResearchCampaignReceipt> {
2856
- const requestCheck = this.requestCheck(by, () => this.studyHold()); this.plannerWriteAuthority(by);
2857
- const fields = this.studyFields(input, ["id", "revision", "reason"]), id = this.studyId(fields.id), revision = this.studyNumber(fields.revision, "revision");
2858
- if (typeof fields.reason !== "string" || !fields.reason.trim() || Buffer.byteLength(fields.reason, "utf8") > 512) throw new PreEffectToolRefusal("study close needs a bounded reason");
2859
- const reason = fields.reason;
2860
- return this.studyWrite(async () => {
2861
- const original = this.studyLatest(id, revision), parent = this.studyParent(original.parentTaskId);
2862
- this.plannerWriteAuthority(by, parent);
2863
- const withheld = await this.withholds("note", reason, parent);
2864
- requestCheck();
2865
- const latest = this.studyLatest(id, revision), currentParent = this.studyParent(latest.parentTaskId);
2866
- this.plannerWriteAuthority(by, currentParent);
2867
- if (latest.hash !== original.hash || currentParent.history.length !== parent.history.length) throw new PreEffectToolRefusal("study changed during close screening");
2868
- const priv = this.studyReplayPrivacy(latest, currentParent) || withheld || !this.nameable(reason);
2869
- let closed: ResearchCampaignRecord;
2870
- requestCheck(); this.plannerWriteAuthority(by, currentParent);
2871
- try { closed = this.d.board.closeCampaign(id, revision, this.d.project, by, this.studyTime(), reason, currentParent.history.length, priv); }
2872
- catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "study close was not saved"); }
2873
- this.releaseNotice(`study ${id} revision ${revision} closed`);
2874
- return this.studyReceipt(closed);
2875
- });
2876
- }
2877
-
2878
- private experimentHash(input: unknown): string { return createHash("sha256").update(canonicalJson(input)).digest("hex"); }
2879
-
2880
- private experimentId(input: unknown): string {
2881
- if (typeof input !== "string" || !/^ra-[a-f0-9]{12}$/.test(input)) throw new PreEffectToolRefusal("experiment identity is invalid");
2882
- return input;
2883
- }
2884
-
2885
- private experimentProtocol(hash: string): ExperimentProtocolRecord {
2886
- try {
2887
- const record = this.d.board.experimentProtocol(hash);
2888
- if (record?.project === this.d.project) return record;
2889
- } catch { /* damaged records are never returned as evidence */ }
2890
- throw new PreEffectToolRefusal("experiment protocol is unavailable in this project");
2891
- }
2892
-
2893
- private experimentAttempt(id: string): ExperimentAttemptRecord {
2894
- try {
2895
- const record = this.d.board.experimentAttempt(id);
2896
- if (record?.project === this.d.project) return record;
2897
- } catch { /* fail closed without including any stored body */ }
2898
- throw new PreEffectToolRefusal("experiment attempt is unavailable in this project");
2899
- }
2900
-
2901
- private experimentContext(by: PeerId, taskId: number, protocol: ExperimentProtocolContract, recordedForTaskId = taskId): ExperimentContext {
2902
- const task = this.studyParent(taskId), bound = this.d.board.researchDispatchBinding(taskId);
2903
- if (task.owner !== by || task.state !== "in_progress") throw new PreEffectToolRefusal("experiment records require the current in-progress task owner");
2904
- if (this.d.privateTurn?.(by) && !this.isPii(task)) throw new PreEffectToolRefusal("a private turn cannot write experiment records on a public task");
2905
- const campaign = bound?.campaign;
2906
- // ponytail: new attempts against an older revision's protocol are refused; upgrade: explicit membership+source fence.
2907
- if (!bound?.binding || !campaign || campaign.project !== this.d.project || campaign.id !== protocol.campaignId || campaign.revision !== protocol.campaignRevision || campaign.status !== "approved")
2908
- throw new PreEffectToolRefusal("experiment task must be a unit of the protocol's current approved campaign revision");
2909
- const recording = this.d.board.researchDispatchBinding(recordedForTaskId), origin = this.studyParent(recordedForTaskId);
2910
- if (!recording?.binding || recording.campaign.id !== campaign.id || recording.campaign.revision !== campaign.revision || recording.campaign.status !== "approved")
2911
- throw new PreEffectToolRefusal("experiment recording task is no longer a unit of this campaign");
2912
- const sources = protocol.inputs.map(input => {
2913
- const source = this.studySource(input.sourceId);
2914
- 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");
2915
- return source;
2916
- });
2917
- let artifactPrivate = false;
2918
- if ("deliverable" in protocol.code) {
2919
- const reference = protocol.code.deliverable, artifact = latestDeliverables(origin.history)?.find(value => value.id === reference.id && value.sha256 === reference.sha256);
2920
- if (!artifact) throw new PreEffectToolRefusal("experiment code deliverable identity is not recorded for its task");
2921
- artifactPrivate = artifact.private === true;
2922
- }
2923
- const privateRecord = this.studyReplayPrivacy(campaign, this.studyParent(campaign.parentTaskId)) || this.isPii(task) || this.isPii(origin) || artifactPrivate || sources.some(source => source.private);
2924
- const fence: ExperimentWriteFence = { project: this.d.project, taskId, taskFlowRevision: task.history.length, owner: by,
2925
- campaignId: campaign.id, campaignRevision: campaign.revision, campaignHash: campaign.hash };
2926
- return { task, campaign, private: privateRecord, fence, key: JSON.stringify([fence, sources, privateRecord, origin.history.length, recording.binding]) };
2927
- }
2928
-
2929
- private experimentFresh(before: ExperimentContext, by: PeerId, protocol: ExperimentProtocolContract, recordedForTaskId?: number): ExperimentContext {
2930
- const current = this.experimentContext(by, before.task.id, protocol, recordedForTaskId);
2931
- if (current.key !== before.key) throw new PreEffectToolRefusal("experiment authority, source or campaign changed during admission");
2932
- return current;
2933
- }
2934
-
2935
- private async experimentScreen(text: string, task: Task): Promise<void> {
2936
- if (!this.isPii(task) && (!this.nameable(text) || looksSecret(text) || await this.withholds("note", text, task)))
2937
- throw new PreEffectToolRefusal("experiment text was not cleared; nothing was recorded");
2938
- }
2939
-
2940
- private experimentPlanContext(by: PeerId, taskId: number, plan: ComparisonPlanV1): ExperimentContext {
2941
- const task = this.studyParent(taskId), bound = this.d.board.researchDispatchBinding(taskId), campaign = bound?.campaign;
2942
- if (task.owner !== by || task.state !== "in_progress" || !bound?.binding || !campaign || campaign.project !== this.d.project
2943
- || campaign.id !== plan.campaignId || campaign.status !== "approved")
2944
- throw new PreEffectToolRefusal("comparison plans require the current in-progress campaign unit owner");
2945
- if (this.d.privateTurn?.(by) && !this.isPii(task)) throw new PreEffectToolRefusal("a private turn cannot write comparison plans on a public task");
2946
- const sources = plan.fixed.inputs.map(input => {
2947
- const source = this.studySource(input.sourceId);
2948
- if (!campaign.contract.sourceIds.includes(input.sourceId) || !source || source.sha256 !== input.sha256)
2949
- throw new PreEffectToolRefusal("comparison input source identity or hash is unavailable in this campaign");
2950
- return source;
2951
- });
2952
- const privateRecord = this.studyReplayPrivacy(campaign, this.studyParent(campaign.parentTaskId)) || this.isPii(task) || sources.some(source => source.private);
2953
- const fence: ExperimentWriteFence = { project: this.d.project, taskId, taskFlowRevision: task.history.length, owner: by,
2954
- campaignId: campaign.id, campaignRevision: campaign.revision, campaignHash: campaign.hash };
2955
- return { task, campaign, private: privateRecord, fence, key: canonicalJson([fence, privateRecord, sources, bound.binding]) };
2956
- }
2957
-
2958
- private experimentApproved(record: ExperimentProtocolRecord): boolean {
2959
- const approval = this.d.board.experimentProtocolApproval(record.hash);
2960
- return protocolApprovalBindingMatches(record.protocol, approval && { protocolHash: approval.protocolHash, evaluatorHash: approval.evaluatorHash });
2961
- }
2962
-
2963
- /** Approval is an explicit person's decision about immutable bytes, including historical protocols. */
2964
- async experimentApproveProtocol(by: PeerId, input: unknown): Promise<ProtocolApprovalReceipt> {
2965
- const requestCheck = this.requestCheck(by, () => this.studyHold());
2966
- if (by !== USER) throw new PreEffectToolRefusal("protocol approval is person only");
2967
- const fields = this.studyFields(input, ["hash"]);
2968
- 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");
2969
- const hash = fields.hash;
2970
- return this.studyWrite(async () => {
2971
- requestCheck();
2972
- const record = this.experimentProtocol(hash), evaluatorHash = evaluatorIdentityHash(record.protocol);
2973
- requestCheck();
2974
- let saved;
2975
- try { saved = this.d.board.approveExperimentProtocol(this.d.project, hash, evaluatorHash, by, this.studyTime()); }
2976
- catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "protocol approval was not saved"); }
2977
- return { protocolHash: saved.protocolHash, evaluatorHash: saved.evaluatorHash, approvedBy: saved.approvedBy, approvedAt: saved.at };
2978
- });
2979
- }
2980
-
2981
- /** Record evidence only: this path never runs a check, a shell command or a runner. */
2982
2607
  async experimentRecord(by: PeerId, input: { kind: "plan"; [key: string]: unknown }): Promise<ComparisonPlanReceipt>;
2983
2608
  async experimentRecord(by: PeerId, input: { kind: "protocol" | "attempt" | "event" | "receipt"; [key: string]: unknown }): Promise<ExperimentReceipt>;
2984
2609
  async experimentRecord(by: PeerId, input: unknown): Promise<ExperimentReceipt | ComparisonPlanReceipt>;
2985
- async experimentRecord(by: PeerId, input: unknown): Promise<ExperimentReceipt | ComparisonPlanReceipt> {
2986
- const requestCheck = this.requestCheck(by, () => this.studyHold());
2987
- const envelope = this.studyFields(input, ["kind", "taskId", "protocol", "attempt", "attemptId", "idempotencyKey", "event", "plan", "receipt", "signature"]);
2988
- return this.studyWrite(async () => {
2989
- try {
2990
- if (envelope.kind === "receipt") {
2991
- const fields = this.studyFields(input, ["kind", "receipt", "signature"]), receipt = parseAttemptReceipt(fields.receipt);
2992
- const attempt = this.experimentAttempt(receipt.attemptId), record = this.experimentProtocol(attempt.attempt.protocolHash);
2993
- const relayOwner = by === USER ? this.studyParent(attempt.attempt.taskId).owner : by;
2994
- if (!relayOwner) throw new PreEffectToolRefusal("receipt relay requires a current task owner");
2995
- const before = this.experimentContext(relayOwner, attempt.attempt.taskId, record.protocol, record.recordedForTaskId);
2996
- requestCheck();
2997
- const proof = (stored: NonNullable<ReturnType<Board["runnerReceipt"]>>): ExperimentReceipt => ({ kind: "receipt", protocolHash: record.hash,
2998
- attemptId: attempt.attemptId, seq: stored.seq, receiptId: receipt.receiptId });
2999
- const known = this.d.board.runnerReceipt(receipt.receiptId);
3000
- if (known) {
3001
- if (canonicalJson(known.receipt) !== canonicalJson(receipt) || known.signature !== fields.signature)
3002
- throw new PreEffectToolRefusal("receiptId already records different signed bytes");
3003
- this.experimentFresh(before, relayOwner, record.protocol, record.recordedForTaskId); requestCheck();
3004
- return proof(known); // immutable stored proof: do not re-verify against a revoked/replaced registration or write on replay
3005
- }
3006
- const registrations = parseResearchRunners(this.d.researchRunners?.() ?? {}), registrationKey = canonicalJson(registrations);
3007
- const context = { projectId: this.d.project, attempt: { id: attempt.attemptId, projectId: attempt.project, protocolHash: attempt.attempt.protocolHash,
3008
- ...("commit" in record.protocol.code ? { codeCommit: record.protocol.code.commit } : {}) } };
3009
- verifyAttemptReceipt(receipt, fields.signature, { ...context, runners: registrations });
3010
- const lastSeq = this.d.board.experimentLastSeq(attempt.attemptId);
3011
- await this.experimentScreen(canonicalJson(receipt), before.task); requestCheck();
3012
- const current = this.experimentFresh(before, relayOwner, record.protocol, record.recordedForTaskId);
3013
- const latest = parseResearchRunners(this.d.researchRunners?.() ?? {});
3014
- if (canonicalJson(latest) !== registrationKey) throw new PreEffectToolRefusal("runner registration changed during receipt admission");
3015
- verifyAttemptReceipt(receipt, fields.signature, { ...context, runners: latest }); requestCheck();
3016
- const saved = this.d.board.appendRunnerReceipt({ receipt, signature: fields.signature as string, publicKey: latest[receipt.runner]!.publicKey,
3017
- by, at: this.studyTime(), private: current.private || record.private || attempt.private }, lastSeq, current.fence);
3018
- return proof(saved);
3019
- }
3020
- if (envelope.kind === "plan") {
3021
- const fields = this.studyFields(input, ["kind", "taskId", "plan"]), taskId = this.studyNumber(fields.taskId, "taskId"), plan = parseComparisonPlan(fields.plan);
3022
- const before = this.experimentPlanContext(by, taskId, plan);
3023
- await this.experimentScreen(canonicalJson(plan), before.task); requestCheck();
3024
- const current = this.experimentPlanContext(by, taskId, plan);
3025
- if (current.key !== before.key) throw new PreEffectToolRefusal("comparison authority, source or campaign changed during admission");
3026
- requestCheck();
3027
- const saved = this.d.board.saveExperimentComparisonPlan({ hash: comparisonPlanHash(plan), project: this.d.project, recordedForTaskId: taskId,
3028
- plan, by, at: this.studyTime(), private: current.private }, current.fence);
3029
- return { kind: "plan", planHash: saved.hash };
3030
- }
3031
- if (envelope.kind === "protocol") {
3032
- const fields = this.studyFields(input, ["kind", "taskId", "protocol"]), taskId = this.studyNumber(fields.taskId, "taskId"), protocol = parseExperimentProtocol(fields.protocol);
3033
- const before = this.experimentContext(by, taskId, protocol);
3034
- for (const reference of [protocol.variantOf, protocol.supersedes]) if (reference) {
3035
- const previous = this.experimentProtocol(reference);
3036
- if (previous.protocol.campaignId !== protocol.campaignId || reference === protocol.supersedes && previous.protocol.lineage !== protocol.lineage)
3037
- throw new PreEffectToolRefusal("experiment protocol reference belongs to another campaign or lineage");
3038
- }
3039
- await this.experimentScreen(canonicalJson(protocol), before.task); requestCheck();
3040
- const current = this.experimentFresh(before, by, protocol); requestCheck();
3041
- const saved = this.d.board.saveExperimentProtocol({ hash: protocolHash(protocol), project: this.d.project, recordedForTaskId: taskId, protocol, by, at: this.studyTime(), private: current.private }, current.fence);
3042
- return { kind: "protocol", protocolHash: saved.hash };
3043
- }
3044
- if (envelope.kind === "attempt") {
3045
- const fields = this.studyFields(input, ["kind", "attempt"]), attempt = parseExperimentAttempt(fields.attempt), record = this.experimentProtocol(attempt.protocolHash);
3046
- const before = this.experimentContext(by, attempt.taskId, record.protocol, record.recordedForTaskId);
3047
- for (const reference of [attempt.retryOf, attempt.reproducesAttemptId]) if (reference) {
3048
- const previous = this.experimentAttempt(reference), protocol = this.experimentProtocol(previous.attempt.protocolHash);
3049
- if (protocol.protocol.campaignId !== record.protocol.campaignId) throw new PreEffectToolRefusal("attempt reference belongs to another campaign");
3050
- }
3051
- await this.experimentScreen(canonicalJson(attempt), before.task); requestCheck();
3052
- const current = this.experimentFresh(before, by, record.protocol, record.recordedForTaskId); requestCheck();
3053
- const saved = this.d.board.createExperimentAttempt({ attemptId: `ra-${randomBytes(6).toString("hex")}`, project: this.d.project, attempt, bodyHash: this.experimentHash(attempt), by, at: this.studyTime(), private: current.private || record.private }, current.fence);
3054
- return { kind: "attempt", protocolHash: saved.attempt.protocolHash, attemptId: saved.attemptId };
3055
- }
3056
- if (envelope.kind === "event") {
3057
- const fields = this.studyFields(input, ["kind", "attemptId", "idempotencyKey", "event"]), id = this.experimentId(fields.attemptId), key = fields.idempotencyKey;
3058
- 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");
3059
- const attempt = this.experimentAttempt(id), record = this.experimentProtocol(attempt.attempt.protocolHash), event = parseExperimentEvent(fields.event, record.protocol);
3060
- const before = this.experimentContext(by, attempt.attempt.taskId, record.protocol, record.recordedForTaskId), lastSeq = this.d.board.experimentLastSeq(id);
3061
- await this.experimentScreen(canonicalJson([key, event]), before.task); requestCheck();
3062
- this.experimentFresh(before, by, record.protocol, record.recordedForTaskId);
3063
- const observations: ExperimentHostEvidence[] = [];
3064
- let outputPrivate = event.kind === "output" && "path" in event.body ? this.experimentOutputPrivate(before.task, event.body.path) : false;
3065
- if (event.kind === "end" && event.body.run && this.d.experimentCheck) {
3066
- let receipt: unknown;
3067
- try { receipt = await this.d.experimentCheck(event.body.run); } catch { /* unavailable is unknown */ }
3068
- requestCheck(); this.experimentFresh(before, by, record.protocol, record.recordedForTaskId);
3069
- const observation = checkRunObservation(receipt, event.body.run, before.task.id, record.protocol);
3070
- if (observation) observations.push(observation);
3071
- } else if (event.kind === "output" && "path" in event.body) {
3072
- try {
3073
- const measured = await hashDeliverables([event.body], this.deliverablePorts(before.task));
3074
- const output = measured[0];
3075
- if (output) { observations.push(deliverableObservation(output)); outputPrivate ||= output.private === true; }
3076
- } catch { /* #509 refusal, missing or unreadable means unknown; never use a declared fallback hash */ }
3077
- requestCheck(); this.experimentFresh(before, by, record.protocol, record.recordedForTaskId);
3078
- }
3079
- const current = this.experimentFresh(before, by, record.protocol, record.recordedForTaskId); requestCheck();
3080
- if (event.kind === "output" && "path" in event.body) outputPrivate ||= this.experimentOutputPrivate(current.task, event.body.path);
3081
- const saved = this.d.board.appendExperimentEvent(id, key, event, observations, by, this.studyTime(), current.private || record.private || attempt.private || outputPrivate, lastSeq, current.fence);
3082
- return { kind: "event", protocolHash: record.hash, attemptId: id, seq: saved.event.seq };
3083
- }
3084
- throw new PreEffectToolRefusal("unsupported experiment record kind");
3085
- } catch (error) {
3086
- if (error instanceof PreEffectToolRefusal) throw error;
3087
- throw new PreEffectToolRefusal(error instanceof Error ? error.message : "experiment record was not saved");
3088
- }
3089
- });
3090
- }
3091
-
3092
- private runnerKeyStatus(stored: NonNullable<ReturnType<Board["runnerReceipt"]>>): "active" | "revoked" | "replaced" | "unavailable" {
3093
- try {
3094
- const runners = parseResearchRunners(this.d.researchRunners?.() ?? {});
3095
- if (!Object.hasOwn(runners, stored.receipt.runner)) return "unavailable";
3096
- const current = runners[stored.receipt.runner]!;
3097
- if (current.publicKey !== stored.publicKey) return "replaced";
3098
- if (current.revoked) return "revoked";
3099
- return current.projects.includes(stored.receipt.projectId) ? "active" : "unavailable";
3100
- } catch { return "unavailable"; }
3101
- }
2610
+ async experimentRecord(by: PeerId, input: unknown): Promise<ExperimentReceipt | ComparisonPlanReceipt> { return this.experiment.experimentRecord(by, input); }
3102
2611
 
3103
- private experimentPrivate(record: ExperimentProtocolRecord, attempt: ExperimentAttemptRecord): boolean {
3104
- try {
3105
- const campaign = this.d.board.researchCampaign(record.protocol.campaignId, record.protocol.campaignRevision), task = this.d.board.get(attempt.attempt.taskId);
3106
- return record.private || attempt.private || !campaign || this.studyReplayPrivacy(campaign, this.studyParent(campaign.parentTaskId)) || !task || this.isPii(task)
3107
- || record.protocol.inputs.some(input => { const source = this.studySource(input.sourceId); return !source || source.private; });
3108
- } catch { return true; }
3109
- }
2612
+ experimentShow(...args: Parameters<ExperimentDomain["experimentShow"]>): ReturnType<ExperimentDomain["experimentShow"]> { return this.experiment.experimentShow(...args); }
3110
2613
 
3111
- async experimentShow(by: PeerId, input: unknown): Promise<ExperimentView> {
3112
- return this.experimentRead(by, input);
3113
- }
3114
-
3115
- private experimentRead(by: PeerId, input: unknown): ExperimentView {
3116
- requireLocalTaskPeer(by);
3117
- const fields = this.studyFields(input, ["attemptId", "campaignId", "after", "eventAfter", "limit", "planHash", "baselineAttemptId", "variantAttemptId"]);
3118
- 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`); })();
3119
- const after = cursor(fields.after, "after"), eventAfter = cursor(fields.eventAfter, "eventAfter"), limit = fields.limit === undefined ? 50 : this.studyNumber(fields.limit, "limit");
3120
- if (limit > 50) throw new PreEffectToolRefusal("experiment readback is limited to 50 rows");
3121
- if (fields.planHash !== undefined || fields.baselineAttemptId !== undefined || fields.variantAttemptId !== undefined) {
3122
- if (fields.attemptId !== undefined || fields.campaignId !== undefined || fields.after !== undefined
3123
- || typeof fields.planHash !== "string" || fields.planHash.length !== 64 || !/^[a-f0-9]{64}$/.test(fields.planHash))
3124
- throw new PreEffectToolRefusal("comparison readback needs one plan hash and two attempt ids");
3125
- const plan = this.d.board.experimentComparisonPlan(fields.planHash);
3126
- if (!plan || plan.project !== this.d.project) throw new PreEffectToolRefusal("comparison plan is unavailable in this project");
3127
- const baseline = this.experimentAttempt(this.experimentId(fields.baselineAttemptId)), variant = this.experimentAttempt(this.experimentId(fields.variantAttemptId));
3128
- const first = this.experimentProtocol(baseline.attempt.protocolHash), second = this.experimentProtocol(variant.attempt.protocolHash);
3129
- if (first.protocol.campaignId !== plan.plan.campaignId || second.protocol.campaignId !== plan.plan.campaignId)
3130
- throw new PreEffectToolRefusal("comparison attempts must belong to the plan's campaign");
3131
- const left = this.experimentRead(by, { attemptId: baseline.attemptId, eventAfter, limit });
3132
- const right = this.experimentRead(by, { attemptId: variant.attemptId, eventAfter, limit });
3133
- let planPrivate = true;
3134
- try {
3135
- const campaign = this.studyRecord(plan.plan.campaignId);
3136
- planPrivate = plan.private || this.studyReplayPrivacy(campaign, this.studyParent(campaign.parentTaskId))
3137
- || plan.plan.fixed.inputs.some(input => { const source = this.studySource(input.sourceId); return !source || source.private; });
3138
- } catch { /* an unavailable privacy classification withholds the comparison */ }
3139
- const privateRecord = planPrivate || left.attempts.some(row => row.private) || right.attempts.some(row => row.private);
3140
- return { attempts: [...left.attempts, ...right.attempts], counts: left.counts,
3141
- comparison: { planHash: plan.hash, baselineAttemptId: baseline.attemptId, variantAttemptId: variant.attemptId,
3142
- approved: this.experimentApproved(first) && this.experimentApproved(second), private: privateRecord,
3143
- projection: privateRecord ? "[pii]" : comparisonProjection(plan.plan, first.protocol, second.protocol) } };
3144
- }
3145
- let campaignId: string, attempts: ExperimentAttemptRecord[], nextCursor: number | undefined;
3146
- if (fields.attemptId !== undefined) {
3147
- if (fields.campaignId !== undefined || fields.after !== undefined) throw new PreEffectToolRefusal("choose one attempt or campaign page");
3148
- const attempt = this.experimentAttempt(this.experimentId(fields.attemptId));
3149
- campaignId = this.experimentProtocol(attempt.attempt.protocolHash).protocol.campaignId; attempts = [attempt];
3150
- } else {
3151
- campaignId = this.studyId(fields.campaignId); this.studyRecord(campaignId);
3152
- const page = this.d.board.experimentAttempts(this.d.project, campaignId, after, limit); attempts = page.rows;
3153
- if (!page.done) nextCursor = page.afterRow;
3154
- }
3155
- const summary = this.d.board.experimentSummary(this.d.project, campaignId), views: ExperimentAttemptView[] = [];
3156
- for (const attempt of attempts) {
3157
- const record = this.experimentProtocol(attempt.attempt.protocolHash), page = this.d.board.experimentEvents(attempt.attemptId, eventAfter, limit);
3158
- const runnerReceipts = this.d.board.runnerReceipts(attempt.attemptId);
3159
- const privateRecord = this.experimentPrivate(record, attempt) || page.rows.some(row => row.private)
3160
- || runnerReceipts.some(row => row.private || !this.nameable(canonicalJson(row.receipt)) || looksSecret(canonicalJson(row.receipt)));
3161
- const status = this.d.board.experimentAttemptStatus(attempt.attemptId);
3162
- const observations = page.rows.flatMap(row => row.observations), events = page.rows.map(row => row.event);
3163
- const evidence = { ...projectExperimentWithObservations(record.protocol, events, observations),
3164
- ...(runnerReceipts.length ? { runnerAttested: runnerReceipts.map(row => ({ ...projectRunnerReceipt(record.protocol, row.receipt), key: { hash: row.keyHash, status: this.runnerKeyStatus(row) } })) } : {}) };
3165
- views.push({ id: attempt.attemptId, protocolHash: record.hash, taskId: attempt.attempt.taskId, phase: attempt.attempt.phase, status, private: privateRecord,
3166
- campaignRevision: record.protocol.campaignRevision, approval: this.experimentApproved(record) ? "approved" : "unapproved",
3167
- postHoc: this.d.board.experimentProtocolContext(record.hash).state,
3168
- ...(attempt.attempt.retryOf ? { retryOf: attempt.attempt.retryOf } : {}), ...(attempt.attempt.reproducesAttemptId ? { reproducesAttemptId: attempt.attempt.reproducesAttemptId } : {}), independentlyReproduced: false,
3169
- protocol: { value: privateRecord ? "[pii]" : record.protocol, provenance: "declared" },
3170
- 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),
3171
- 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,
3172
- eventsComplete: page.done, ...(!page.done ? { nextEventCursor: page.afterSeq } : {}) });
3173
- }
3174
- return { attempts: views, counts: { all: summary.total, statuses: summary.statuses }, ...(nextCursor === undefined ? {} : { nextCursor }) };
3175
- }
3176
2614
 
3177
2615
  /** Every new host proposal, including split children, consumes the same pure walk before its first notification. */
3178
2616
  private proposalPlanner(task: Task): PlannerBinding {
@@ -3273,12 +2711,13 @@ export class Tasks {
3273
2711
  private writePlannerNotices(task: Task, before: ReadonlyMap<PeerId, number>, approved = false): void {
3274
2712
  this.releaseNotice(`task #${task.id}: could not notify planner about ready work`, () => {
3275
2713
  const now = this.d.now?.() ?? Date.now();
3276
- const changes = new Map<PeerId, { capacity: Set<PeerId>; ready: Set<number> }>();
3277
- const add = (planner: PeerId, peer?: PeerId, id?: number) => {
2714
+ const changes = new Map<PeerId, { capacity: Set<PeerId>; ready: Set<number>; owned: Set<number> }>();
2715
+ const add = (planner: PeerId, peer?: PeerId, id?: number, owned?: number) => {
3278
2716
  if (!this.d.bus.isRostered(planner)) return;
3279
- const change = changes.get(planner) ?? { capacity: new Set<PeerId>(), ready: new Set<number>() };
2717
+ const change = changes.get(planner) ?? { capacity: new Set<PeerId>(), ready: new Set<number>(), owned: new Set<number>() };
3280
2718
  if (peer) change.capacity.add(peer);
3281
2719
  if (id !== undefined) change.ready.add(id);
2720
+ if (owned !== undefined) change.owned.add(owned);
3282
2721
  changes.set(planner, change);
3283
2722
  };
3284
2723
  const released = new Set<PeerId>();
@@ -3290,6 +2729,8 @@ export class Tasks {
3290
2729
  if (card.reserved) readied.add(card.reserved);
3291
2730
  }
3292
2731
  }
2732
+ // #1801: a dependent that already has an owner is ready too; the planner sees it beside the reserved ready ones.
2733
+ if (approved) for (const card of this.ownedReadyDependents(task)) for (const planner of this.taskPlanner(card)) add(planner, undefined, undefined, card.id);
3293
2734
  for (const [planner, change] of changes) this.releaseNotice(`could not notify planner ${planner} about ready work`, () => {
3294
2735
  const pending = this.d.bus.pendingEnvelopes(planner).filter(env => env.from === HUB && env.kind === "task" && env.body.startsWith("Planner work ready:"));
3295
2736
  // The bus retains these hub-written lines across restart; an in-memory cache would lose unsettled events.
@@ -3298,6 +2739,8 @@ export class Tasks {
3298
2739
  if (capacity) change.capacity.add(capacity[1]!);
3299
2740
  const ready = /^backlog_ready: #(\d+)$/.exec(line);
3300
2741
  if (ready && Number.isSafeInteger(Number(ready[1]))) change.ready.add(Number(ready[1]));
2742
+ const owned = /^owned_ready: #(\d+) \(\S+\)$/.exec(line);
2743
+ if (owned && Number.isSafeInteger(Number(owned[1]))) change.owned.add(Number(owned[1]));
3301
2744
  }
3302
2745
  const lines: string[] = [];
3303
2746
  for (const peer of change.capacity) {
@@ -3309,6 +2752,11 @@ export class Tasks {
3309
2752
  if (card?.state === "backlog" && this.taskPlanner(card).includes(planner) && !this.waitsFor(card).length && !plannedStartPending(card, now)) lines.push(`backlog_ready: #${id}`);
3310
2753
  else change.ready.delete(id);
3311
2754
  }
2755
+ for (const id of change.owned) {
2756
+ const card = this.d.board.get(id);
2757
+ if (card?.owner && this.ownedReadyNow(card) && this.taskPlanner(card).includes(planner)) lines.push(`owned_ready: #${id} (${card.owner})`);
2758
+ else change.owned.delete(id);
2759
+ }
3312
2760
  for (const env of pending) this.d.bus.withdraw(env.id);
3313
2761
  const env = newEnvelope(HUB, sanitize(`Planner work ready:\n${lines.join("\n")}\nRead the current board before planning or pulling work.`), { to: [planner], kind: "task" });
3314
2762
  if (!this.d.bus.publish(env).includes(planner)) throw new Error("the notice was not queued");
@@ -3319,6 +2767,16 @@ export class Tasks {
3319
2767
  });
3320
2768
  }
3321
2769
 
2770
+ /** #1801: an owned dependent that has not started and has nothing left to wait for. */
2771
+ private ownedReadyNow(card: Task): boolean {
2772
+ return !!card.owner && (card.state === "proposed" || card.state === "in_progress") && !taskHasStarted(card) && !this.waitsFor(card).length
2773
+ && !plannedStartPending(card, this.d.now?.() ?? Date.now());
2774
+ }
2775
+
2776
+ private ownedReadyDependents(approved: Task): Task[] {
2777
+ return this.d.board.list().filter(card => card.deps?.includes(approved.id) && this.ownedReadyNow(card));
2778
+ }
2779
+
3322
2780
  /** The top card explicitly reserved for `peer` that this planner may pull now; the notice and the opt-in pull read the same rule. `pullable` keeps the staged backlog cards only. */
3323
2781
  private topReservedReady(peer: PeerId, planner?: PeerId, pullable = false): Task | undefined {
3324
2782
  const now = this.d.now?.() ?? Date.now();
@@ -3675,812 +3133,40 @@ export class Tasks {
3675
3133
  }
3676
3134
  return notified.size;
3677
3135
  }
3678
- private roadmapReadAuthority(by: PeerId): void {
3679
- requireLocalTaskPeer(by);
3680
- if (this.d.privateTurn?.(by) || this.observerExcluded(by) || this.reviewObserverTurn(by)) throw new PreEffectToolRefusal("roadmap is unavailable during private or review-observer input; use ahub roadmap list after that turn");
3681
- }
3682
-
3683
- private roadmapWriteAuthority(by: PeerId): () => void {
3684
- const check = this.requestCheck(by, () => this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError ? "roadmap writes are held by recovery, shutdown or storage; retry ahub roadmap list after recovery" : undefined);
3685
- const current = () => {
3686
- check(); this.roadmapReadAuthority(by);
3687
- if (by !== USER && (!this.d.bus.isRostered(by) || !this.isConfiguredPlanner(by) && !this.configuredManualConductor(by)))
3688
- throw new PreEffectToolRefusal("roadmap writes require a configured planner or the unique conductor; ask the person to run ahub roadmap");
3689
- };
3690
- current(); return current;
3691
- }
3692
-
3693
- private roadmapParsed<T>(read: () => T): T {
3694
- try { return read(); }
3695
- catch (error) { throw new PreEffectToolRefusal(`${error instanceof Error ? error.message : "invalid roadmap input"}; check ahub roadmap show and correct the fields`); }
3696
- }
3697
-
3698
- private roadmapCurrent(id: unknown, state?: MilestoneState): Milestone {
3699
- const row = this.d.board.milestone(this.roadmapParsed(() => milestoneId(id)));
3700
- if (!row) throw new PreEffectToolRefusal("roadmap milestone does not exist; use ahub roadmap list");
3701
- if (["done", "dropped"].includes(row.state) && state !== row.state) throw new PreEffectToolRefusal("a settled milestone is final; create new work with ahub roadmap new");
3702
- return row;
3703
- }
3704
-
3705
- private roadmapStateAuthority(by: PeerId, state: MilestoneState | undefined): void {
3706
- if (state !== undefined && !(MILESTONE_STATES as readonly string[]).includes(state)) throw new PreEffectToolRefusal("invalid milestone state; use proposed, planned, active, done or dropped with ahub roadmap state");
3707
- if (by !== USER && (state === "done" || state === "dropped")) throw new PreEffectToolRefusal("done and dropped require the person; ask them to run ahub roadmap state");
3708
- }
3709
-
3710
- private roadmapTextCurrent(fields: MilestonePatch): string {
3711
- const text = [fields.title, fields.outcome].filter((value): value is string => value !== undefined).join("\n");
3712
- if (text && !this.publicMetadataText(text))
3713
- throw new PreEffectToolRefusal("milestone text was not cleared for public planning; remove private content before ahub roadmap new or edit");
3714
- return text;
3715
- }
3716
-
3717
- private async roadmapScreen(fields: MilestonePatch): Promise<void> {
3718
- const text = this.roadmapTextCurrent(fields);
3719
- if (text && this.screenOn() && (await this.screenCall(text)).label !== "clear")
3720
- throw new PreEffectToolRefusal("milestone text was not cleared for public planning; remove private content before ahub roadmap new or edit");
3721
- this.roadmapTextCurrent(fields);
3722
- }
3723
-
3724
- private roadmapResult(by: PeerId, id: number): MilestoneView {
3725
- try { return this.milestoneShow(by, id); }
3726
- catch { throw new Error("roadmap operation finished but public readback is unavailable; inspect ahub roadmap show before retrying"); }
3727
- }
3728
-
3729
- async milestoneNew(by: PeerId, raw: unknown): Promise<MilestoneView> {
3730
- const current = this.roadmapWriteAuthority(by), fields = this.roadmapParsed(() => parseMilestoneInput(raw));
3731
- this.roadmapStateAuthority(by, fields.state);
3732
- await this.roadmapScreen(fields); current(); this.roadmapStateAuthority(by, fields.state); this.roadmapTextCurrent(fields);
3733
- const row = this.d.board.newMilestone(fields, by, this.d.now?.() ?? Date.now());
3734
- return this.roadmapResult(by, row.id);
3735
- }
3736
-
3737
- async milestoneEdit(by: PeerId, id: number, revision: number, raw: unknown): Promise<MilestoneView> {
3738
- const current = this.roadmapWriteAuthority(by), fields = this.roadmapParsed(() => parseMilestonePatch(raw));
3739
- this.roadmapParsed(() => milestoneRevision(revision)); this.roadmapStateAuthority(by, fields.state);
3740
- const validate = () => {
3741
- current(); this.roadmapStateAuthority(by, fields.state);
3742
- const row = this.roadmapCurrent(id);
3743
- if (row.revision !== revision) throw new PreEffectToolRefusal("roadmap revision changed; reload ahub roadmap show before editing");
3744
- return row;
3745
- };
3746
- validate(); await this.roadmapScreen(fields); const row = validate(); this.roadmapTextCurrent(fields);
3747
- if (Object.entries(fields).every(([key, value]) => row[key as keyof Milestone] === value)) return this.milestoneShow(by, id);
3748
- this.d.board.updateMilestone(id, fields, revision, { by, at: this.d.now?.() ?? Date.now(), event: "edited", fields: Object.keys(fields) });
3749
- return this.roadmapResult(by, id);
3750
- }
3751
-
3752
- milestoneLink(by: PeerId, id: number, kind: MilestoneLinkKind, raw: string): MilestoneView {
3753
- this.roadmapWriteAuthority(by);
3754
- const row = this.roadmapCurrent(id), ref = this.roadmapParsed(() => milestoneLinkRef(kind, raw));
3755
- if (!this.publicMetadataText(ref)) throw new PreEffectToolRefusal("roadmap reference is private; use a public reference with ahub roadmap link");
3756
- if (kind === "task" && !this.d.board.get(Number(ref)) || kind === "release" && !this.d.board.release(Number(ref)))
3757
- throw new PreEffectToolRefusal("roadmap target does not exist; inspect ahub board or ahub release list before linking");
3758
- this.d.board.linkMilestone(id, kind, ref, by, row.revision, this.d.now?.() ?? Date.now());
3759
- return this.roadmapResult(by, id);
3760
- }
3761
-
3762
- milestoneUnlink(by: PeerId, id: number, kind: MilestoneLinkKind, raw: string): MilestoneView {
3763
- this.roadmapWriteAuthority(by);
3764
- const row = this.roadmapCurrent(id), ref = this.roadmapParsed(() => milestoneLinkRef(kind, raw));
3765
- this.d.board.unlinkMilestone(id, kind, ref, by, row.revision, this.d.now?.() ?? Date.now());
3766
- return this.roadmapResult(by, id);
3767
- }
3768
-
3769
- milestoneOrder(by: PeerId, id: number, order: number): MilestoneView {
3770
- this.roadmapWriteAuthority(by);
3771
- const row = this.roadmapCurrent(id), fields = this.roadmapParsed(() => parseMilestonePatch({ order }));
3772
- if (row.order !== order) this.d.board.updateMilestone(id, fields, row.revision, { by, at: this.d.now?.() ?? Date.now(), event: "ordered", fields: ["order"] });
3773
- return this.roadmapResult(by, id);
3774
- }
3775
-
3776
- milestoneState(by: PeerId, id: number, state: MilestoneState): MilestoneView {
3777
- this.roadmapWriteAuthority(by); this.roadmapStateAuthority(by, state);
3778
- this.roadmapParsed(() => parseMilestonePatch({ state }));
3779
- const row = this.roadmapCurrent(id, state);
3780
- // #1622 family 4: an instructed person verdict records the same three provenance keys task history does, for done and dropped only.
3781
- const instruction = by === USER && (state === "done" || state === "dropped") ? instructedHistory(by) : {};
3782
- if (row.state !== state) this.d.board.updateMilestone(id, { state }, row.revision, { by, at: this.d.now?.() ?? Date.now(), event: "state", fields: ["state"], ...instruction });
3783
- return this.roadmapResult(by, id);
3784
- }
3785
-
3786
- /** #1738: the hub's own roadmap pass (the five-minute sweep and each task change's notice) runs milestoneList several times (the sweep, roadmapNotify, roadmapCheck and each
3787
- * finding's recheck), and a working-tree spec check runs one synchronous git per spec path, so hub reads reuse one check for ROADMAP_SPECS_REUSE_MS. A thrown check is not
3788
- * kept. Reads by the person and peers, and explicit `specs check`, stay uncached.
3789
- * ponytail: a time window, not a repository key; key it on HEAD and index state, or run the check off the event loop, if a minute of stale freshness ever matters. */
3790
- private roadmapSpecs: { at: number; report: SpecsCheckReport | SpecsCoverReport | undefined } | undefined;
3791
- private roadmapSpecsCheck(): SpecsCheckReport | SpecsCoverReport | undefined {
3792
- const now = this.d.now?.() ?? Date.now(), kept = this.roadmapSpecs;
3793
- if (kept && now >= kept.at && now - kept.at < ROADMAP_SPECS_REUSE_MS) return kept.report;
3794
- const report = this.d.specsRead?.("check", []);
3795
- this.roadmapSpecs = { at: now, report };
3796
- return report;
3797
- }
3798
-
3799
- private roadmapSpecsFor(by: PeerId): SpecsCheckReport | SpecsCoverReport | undefined {
3800
- return by === HUB ? this.roadmapSpecsCheck() : this.d.specsRead?.("check", []);
3801
- }
3802
-
3803
- private roadmapSnapshot(by: PeerId, specs = () => this.roadmapSpecsFor(by)): RoadmapSnapshot {
3804
- let freshness: SpecsCheckReport["freshness"] | undefined;
3805
- try { const report = specs(); if (report && "freshness" in report && !report.truncated && report.errors === 0)
3806
- freshness = report.freshness.filter(row => this.publicMetadataText(row.path) && (row.id === undefined || this.publicMetadataText(row.id))); } catch { /* unavailable evidence stays unknown */ }
3807
- return { milestones: this.d.board.milestones(), links: this.d.board.milestoneLinks(), tasks: this.d.board.list(), releases: this.d.board.releases(), freshness,
3808
- issueOf: task => { try { const source = this.planIssueIdentity(task); return source ? `${source.repo.toLowerCase()}#${source.issue}` : undefined; } catch { return undefined; } },
3809
- privateTask: task => this.isPii(task) || task.signals.includes("pii") || task.state === "backlog" && by !== USER && !this.isConfiguredPlanner(by),
3810
- publicText: text => this.publicMetadataText(text),
3811
- };
3812
- }
3813
-
3814
- milestoneList(by: PeerId, specs?: () => SpecsCheckReport | SpecsCoverReport | undefined): (MilestoneView & { tree: TreeRollup; readyToClose: ReadyToClose })[] {
3815
- this.roadmapReadAuthority(by);
3816
- const views = withTree(milestoneViews(this.roadmapSnapshot(by, specs)));
3817
- this.roadmapReadAuthority(by); return views;
3818
- }
3819
-
3820
- milestoneShow(by: PeerId, id: number): MilestoneView {
3821
- this.roadmapParsed(() => milestoneId(id));
3822
- const row = this.milestoneList(by).find(row => row.id === id);
3823
- if (!row) throw new PreEffectToolRefusal("roadmap milestone does not exist; use ahub roadmap list");
3824
- return row;
3825
- }
3826
-
3827
- /** Host-sampled GitHub authority is never supplied by a tool argument. */
3828
- private roadmapRepository(): string {
3829
- const repo = this.roadmapParsed(() => githubRepo(this.d.repository));
3830
- let origin: string | undefined;
3831
- try { origin = this.d.roadmapOrigin ? this.d.roadmapOrigin() : githubOriginRepository(this.d.cwd); } catch { /* unknown is not a trusted origin */ }
3832
- if (!origin || origin.toLowerCase() !== repo) throw new PreEffectToolRefusal("roadmap GitHub origin is unavailable or does not match this project; inspect the local origin before retrying");
3833
- return repo;
3834
- }
3835
- private roadmapApplyAuthority(by: PeerId): void {
3836
- this.roadmapReadAuthority(by);
3837
- if (this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError) throw new PreEffectToolRefusal("roadmap writes are held; retry after recovery");
3838
- if (by !== USER && (!(this.d.roadmapConfig?.().github_write === "conductor") || !this.configuredManualConductor(by) || !this.d.bus.isRostered(by)))
3839
- throw new PreEffectToolRefusal("GitHub roadmap writes require the person or the configured conductor with roadmap.github_write enabled");
3840
- }
3841
-
3842
- private roadmapIssueRefs(views: ReturnType<Tasks["milestoneList"]>): Set<string> {
3843
- const refs = new Set<string>();
3844
- for (const view of views) {
3845
- for (const issue of view.issues) refs.add(issue.ref);
3846
- for (const member of view.tasks) {
3847
- const task = this.d.board.get(member.id); if (!task) continue;
3848
- try { const source = this.planIssueIdentity(task); if (source && this.publicMetadataText(source.repo)) refs.add(`${source.repo.toLowerCase()}#${source.issue}`); } catch { /* ambiguous identity is unknown */ }
3849
- }
3850
- }
3851
- return refs;
3852
- }
3853
-
3854
- /** Render only screened views. Issue writes require an exact preview and fresh authority. */
3855
- async roadmapExport(by: PeerId, input: { issue?: number; apply?: boolean; confirm?: string } = {}): Promise<{ json: string; markdown: string; fingerprint: string; call?: string[]; applied: boolean }> {
3856
- const check = this.requestCheck(by, () => this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError ? "roadmap is held by recovery or storage" : undefined);
3857
- check(); this.roadmapReadAuthority(by);
3858
- if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some(key => !["issue", "apply", "confirm"].includes(key)) || input.apply !== undefined && typeof input.apply !== "boolean" || input.confirm !== undefined && (typeof input.confirm !== "string" || !/^[a-f0-9]{64}$/.test(input.confirm))) throw new PreEffectToolRefusal("invalid roadmap export options; preview before applying");
3859
- if (input.issue !== undefined) this.roadmapParsed(() => milestoneId(input.issue));
3860
- if (input.apply && input.issue === undefined) throw new PreEffectToolRefusal("roadmap export --apply needs an issue; preview with --issue first");
3861
- if (input.apply) this.roadmapApplyAuthority(by);
3862
- let pinned: { report: SpecsCheckReport | SpecsCoverReport | undefined } | undefined;
3863
- const specs = () => { if (!pinned) { pinned = { report: undefined }; pinned.report = this.roadmapSpecsFor(by); } return pinned.report; };
3864
- let checkedKey = this.roadmapBoardKey(by);
3865
- const views = this.milestoneList(by, specs), refs = this.roadmapIssueRefs(views);
3866
- const evidence = JSON.stringify([views, [...refs]]);
3867
- const privacy = JSON.stringify([this.d.routing(), this.d.piiPaths, this.d.deny]);
3868
- const current = () => {
3869
- check(); this.roadmapReadAuthority(by);
3870
- const key = this.roadmapBoardKey(by);
3871
- const sameViews = () => {
3872
- if (key === checkedKey) return true;
3873
- const latest = this.milestoneList(by, specs);
3874
- return JSON.stringify([latest, [...this.roadmapIssueRefs(latest)]]) === evidence;
3875
- };
3876
- if (JSON.stringify([this.d.routing(), this.d.piiPaths, this.d.deny]) !== privacy || !sameViews())
3877
- throw new PreEffectToolRefusal("roadmap or privacy policy changed while exporting; retry ahub roadmap export");
3878
- checkedKey = key;
3879
- };
3880
- const issueStates = await roadmapIssueStates(refs, this.roadmapGh(), current);
3881
- current();
3882
- const rendered = roadmapExport(views, issueStates);
3883
- const repo = input.issue === undefined ? undefined : this.roadmapRepository();
3884
- const call = repo === undefined ? undefined : ["api", `repos/${repo}/issues/${input.issue}`, "--hostname", "github.com", "--method", "PATCH", "-f", `body=${rendered.markdown}`];
3885
- const fingerprint = createHash("sha256").update(JSON.stringify({ repo: repo ?? null, issue: input.issue ?? null, markdown: rendered.markdown })).digest("hex");
3886
- if (!input.apply) return { ...rendered, fingerprint, ...(call ? { call } : {}), applied: false };
3887
- if (input.confirm !== fingerprint) throw new PreEffectToolRefusal(`roadmap export preview changed; run ahub roadmap export --issue ${input.issue} and retry with --confirm ${fingerprint}`);
3888
- check(); this.roadmapApplyAuthority(by); if (this.roadmapRepository() !== repo) throw new PreEffectToolRefusal("roadmap GitHub origin changed; preview again");
3889
- let result: Awaited<ReturnType<SdlcGh>>;
3890
- try { result = await this.roadmapGh()(call!, 10_000, undefined, 64 * 1024); }
3891
- catch { throw new Error("roadmap issue update outcome is unknown; inspect the issue before retrying"); }
3892
- if (result.code !== 0) throw new Error("roadmap issue update was not confirmed; inspect the issue before retrying");
3893
- try { current(); this.roadmapApplyAuthority(by); if (this.roadmapRepository() !== repo) throw new Error("changed"); }
3894
- catch { throw new Error("roadmap or authority changed after issue update; inspect the issue and preview again"); }
3895
- return { ...rendered, fingerprint, call, applied: true };
3896
- }
3897
-
3898
- /** Build drift only from the same screened views and host-owned evidence as roadmap reads. */
3899
- async roadmapCheck(by: PeerId, include?: (finding: RoadmapDrift) => boolean): Promise<ReturnType<typeof checkRoadmap>> {
3900
- const check = this.requestCheck(by); check(); this.roadmapReadAuthority(by);
3901
- // #1741: one spec check per roadmap check. current() rebuilds the views before and after every issue read, and an uncached working-tree check is a
3902
- // synchronous git per spec path (about a second on this repository), so it ran up to 200 times per call. A thrown check is kept as unavailable.
3903
- let pinned: { report: SpecsCheckReport | SpecsCoverReport | undefined } | undefined;
3904
- const specs = () => { if (!pinned) { pinned = { report: undefined }; pinned.report = this.roadmapSpecsFor(by); } return pinned.report; };
3905
- const boardKey = () => this.roadmapBoardKey(by);
3906
- let checkedKey = boardKey(); // taken before the views, so a write between the two is compared, not skipped
3907
- const views = this.milestoneList(by, specs), config = this.d.roadmapConfig?.() ?? { github_mirror: false, github_write: "off" as const }, privacy = JSON.stringify([this.d.routing(), this.d.piiPaths, this.d.deny]);
3908
- const snapshot = (rows: typeof views) => JSON.stringify([rows, rows.flatMap(view => view.tasks.map(member => this.d.board.get(member.id)))]);
3909
- const evidence = snapshot(views);
3910
- // #1741: building the views runs issueOf over every board task (a regex scan of its text), about 140 ms on a 1156-task board, and current() runs before
3911
- // and after each issue read. Rebuild only when a task write (statusRevision), a milestone, link or release row, or the caller's planner role (it screens backlog tasks) says the views can differ; config and privacy are compared on every call below.
3912
- const sameViews = () => { const key = boardKey(); if (key === checkedKey) return true; if (snapshot(this.milestoneList(by, specs)) !== evidence) return false; checkedKey = key; return true; };
3913
- const current = () => { check(); this.roadmapReadAuthority(by); if (!sameViews() || JSON.stringify(this.d.roadmapConfig?.() ?? { github_mirror: false, github_write: "off" }) !== JSON.stringify(config) || JSON.stringify([this.d.routing(), this.d.piiPaths, this.d.deny]) !== privacy) throw new PreEffectToolRefusal("roadmap or privacy policy changed while checking; retry ahub roadmap check"); };
3914
- const issueStates = await roadmapIssueStates(this.roadmapIssueRefs(views), this.roadmapGh(), current);
3915
- const rendered = roadmapExport(views, issueStates), exportStates: (boolean | undefined)[] = [];
3916
- for (const [path, expected] of [["docs/roadmap.json", rendered.json], ["docs/roadmap.md", rendered.markdown]] as const) {
3917
- try {
3918
- const file = await readGuardedDeliverable(path, { cwd: this.d.cwd, deny: this.d.deny ?? [], private: name => matchesPolicy(this.d.cwd, name, this.d.piiPaths ?? [], true) });
3919
- current(); exportStates.push(Buffer.from(file.data).toString("utf8") === expected);
3920
- } catch (error) { if (error instanceof PreEffectToolRefusal) throw error; exportStates.push(error instanceof DeliverableRefusal && error.message.includes("does not exist") ? false : undefined); }
3921
- }
3922
- const exportMatches = exportStates.includes(false) ? false : exportStates.every(value => value === true) ? true : undefined;
3923
- current();
3924
- let mirror: Awaited<ReturnType<typeof readMirrorSnapshot>> | undefined, repo: string | undefined;
3925
- if (config.github_mirror) {
3926
- try { repo = this.roadmapRepository(); mirror = await readMirrorSnapshot(repo, this.roadmapGh()); }
3927
- catch { /* partial or unavailable evidence stays unknown */ }
3928
- current();
3929
- }
3930
- const milestones: DriftMilestone[] = views.map(view => {
3931
- const tasks = view.tasks.map(member => {
3932
- const task = this.d.board.get(member.id)!;
3933
- let issue: string | null | undefined;
3934
- try { const source = this.planIssueIdentity(task); issue = source ? `${source.repo.toLowerCase()}#${source.issue}` : null; } catch { issue = undefined; }
3935
- const issueState: "open" | "closed" | "unknown" = issue ? issueStates.get(issue) ?? "unknown" : "unknown";
3936
- const merge = task.sdlc?.merge?.state === "merged" ? task.sdlc.merge : task.sdlc?.mergeReadback;
3937
- const mergedAt = merge?.state === "merged" ? merge.cost?.mergedAt ?? undefined : task.sdlc?.pr && task.state === "approved" ? undefined : null;
3938
- const report = merge?.state === "merged" ? this.currentSpecReport(task) : undefined;
3939
- const unchangedSpecs = mergedAt === null ? [] : report?.complete && report.errors === 0 && !report.truncated && report.head === merge?.head
3940
- ? report.unchanged.filter(row => !row.reason?.trim()).map(row => row.id) : undefined;
3941
- return { id: task.id, state: task.state, issue, issueState, feature: /^feat(?:\([^)]*\))?:/i.test(task.title), specIssue: !!task.sdlc?.issue, mergedAt, unchangedSpecs };
3942
- });
3943
- const children = view.children.map(id => views.find(row => row.id === id));
3944
- const open = view.tasks.some(row => !["approved", "cancelled"].includes(row.state)) || view.issues.some(row => issueStates.get(row.ref) === "open") || view.releases.some(row => !["shipped", "dropped", "unknown"].includes(row.state)) || children.some(row => row && !["done", "dropped"].includes(row.state));
3945
- const uncertain = !!view.withheld || view.issues.some(row => !issueStates.has(row.ref)) || view.releases.some(row => row.state === "unknown") || children.some(row => !row);
3946
- const merged = view.tasks.some(row => { const task = this.d.board.get(row.id); return task?.sdlc?.merge?.state === "merged" || task?.sdlc?.mergeReadback?.state === "merged"; });
3947
- let mirrorDiff: boolean | undefined;
3948
- if (mirror && repo && !view.withheld && view.title !== "[withheld]") {
3949
- try {
3950
- const marker = `<!-- ahub-roadmap:${this.d.project}:${view.id} -->`, bound = this.d.board.mirrorMilestone(repo, view.id);
3951
- const recovered = bound === undefined ? recoverMirrorBinding(marker, view.title, mirror.milestones) : undefined;
3952
- if (recovered?.kind === "ambiguous" || recovered?.titleConflicts.length) mirrorDiff = true;
3953
- else {
3954
- const number = bound ?? (recovered?.kind === "bind" ? recovered.number : undefined), remote = number === undefined ? null : mirror.milestones.find(row => row.number === number);
3955
- if (number === undefined || remote) mirrorDiff = bound === undefined || planRoadmapMirror(repo, { title: view.title, state: view.state === "done" || view.state === "dropped" ? "closed" : "open", marker, issues: view.issues.filter(row => row.ref.startsWith(`${repo}#`)).map(row => Number(row.ref.slice(repo!.length + 1))) }, remote ?? null, mirror.issues).calls.length > 0;
3956
- }
3957
- } catch { /* unknown mirror evidence */ }
3958
- }
3959
- return { id: view.id, state: view.state, tasks, openItems: open ? true : uncertain ? undefined : false, mergedCode: merged ? true : tasks.some(row => row.mergedAt === undefined) ? undefined : false, specs: view.specs, mirrorDiff };
3960
- });
3961
- current(); return checkRoadmap({ milestones, now: this.d.now?.() ?? Date.now(), closeLagMs: 24 * 60 * 60_000, mirrorEnabled: config.github_mirror, exportMatches }, include);
3962
- }
3963
-
3964
- /** #1741: what the milestone views are built from, apart from config, privacy and the spec report: equal keys build equal views. */
3965
- private roadmapBoardKey(by: PeerId): string {
3966
- return JSON.stringify([this.d.board.statusRevision(), this.d.board.milestones(), this.d.board.milestoneLinks(), this.d.board.releases(), this.isConfiguredPlanner(by)]);
3967
- }
3968
-
3969
- /** Serialize at the host caller. Persist only admitted ids-only notices, so unavailable feeds can retry. */
3970
- async roadmapNotify(taskIds: readonly number[], send: (task: number, milestone: number | null, rule: number, marker: string) => boolean): Promise<number> {
3971
- if (!taskIds.length) return 0;
3972
- const views = this.milestoneList(HUB);
3973
- if (!views.some(view => view.tasks.some(task => taskIds.includes(task.id)))) return 0;
3974
- const select = (finding: RoadmapDrift) => {
3975
- const referenced = finding.items.filter(item => /^task:[1-9][0-9]*$/.test(item)).map(item => Number(item.slice(5)));
3976
- const eligible = views.filter(view => finding.milestone === null || view.id === finding.milestone).flatMap(view => view.tasks.map(task => task.id));
3977
- const marker = createHash("sha256").update(JSON.stringify([finding.rule, finding.milestone, finding.items, finding.cause])).digest("hex");
3978
- return !this.d.board.hasRoadmapNotice(marker) && taskIds.some(id => eligible.includes(id) && (!referenced.length || referenced.includes(id)));
3979
- };
3980
- const checked = await this.roadmapCheck(HUB, select);
3981
- // #1741: each finding rechecks membership against the current views; rebuild them only when the board key moved (a build is ~140 ms on a 1156-task board, once per finding before).
3982
- let latestViews: ReturnType<Tasks["milestoneList"]> | undefined, latestKey: string | undefined;
3983
- const currentViews = () => { const key = this.roadmapBoardKey(HUB); if (key !== latestKey || !latestViews) { latestKey = key; latestViews = this.milestoneList(HUB); } return latestViews; };
3984
- let sent = 0;
3985
- for (const finding of checked.findings) {
3986
- const referenced = finding.items.filter(item => /^task:[1-9][0-9]*$/.test(item)).map(item => Number(item.slice(5)));
3987
- const eligible = views.filter(view => finding.milestone === null || view.id === finding.milestone).flatMap(view => view.tasks.map(task => task.id));
3988
- const task = taskIds.find(id => eligible.includes(id) && (!referenced.length || referenced.includes(id)));
3989
- if (task === undefined) continue;
3990
- const marker = createHash("sha256").update(JSON.stringify([finding.rule, finding.milestone, finding.items, finding.cause])).digest("hex");
3991
- if (this.d.board.hasRoadmapNotice(marker)) continue;
3992
- const latest = this.d.board.get(task);
3993
- if (!latest || this.isPii(latest) || !currentViews().some(view => (finding.milestone === null || view.id === finding.milestone) && view.tasks.some(row => row.id === task))) continue;
3994
- if (send(task, finding.milestone, finding.rule, marker) && this.d.board.recordRoadmapNotice(marker)) sent++;
3995
- }
3996
- return sent;
3997
- }
3998
-
3999
- /** #1647: the optional reason a task was split off. Absent stays legal; anything outside the closed set is refused before any effect, naming the allowed values. */
4000
- private proposalReason(value: unknown): TaskReason | undefined {
4001
- if (value === undefined || value === null || value === "") return undefined;
4002
- if (typeof value !== "string" || !(TASK_REASONS as readonly string[]).includes(value)) throw new PreEffectToolRefusal(`reason must be one of ${TASK_REASONS.join(", ")}; omit it when no reason applies, then call hub_task_propose again`);
4003
- return value as TaskReason;
4004
- }
4005
-
4006
- /**
4007
- * #1647 AC2: siblings proposed for one plan, by one planner with the same dependencies and `reason: "parallel"`, must touch disjoint `refs.paths` (prefix overlap, `samePlace`).
4008
- * Refused before the new task exists, naming both tasks and the paths.
4009
- * ponytail: the board has no plan-revision id on a task, so "one plan" is the same proposer, the same `after` set, the same repository and an open state; ceiling: two unrelated
4010
- * parallel batches by one planner with equal dependencies read as siblings; upgrade: record the planning revision on the task and compare within it.
4011
- */
4012
- private parallelSiblingsDisjoint(by: PeerId, title: string, refs: TaskRefs, deps: number[]): void {
4013
- const mine = refs.paths ?? [];
4014
- if (!mine.length) return;
4015
- const scope = this.repositories.scope(refs), key = [...deps].sort((a, b) => a - b).join(",");
4016
- for (const other of this.d.board.list()) {
4017
- if (other.reason !== "parallel" || isClosedTaskState(other.state) || other.history[0]?.by !== by || this.isPii(other)) continue;
4018
- if ([...(other.deps ?? [])].sort((a, b) => a - b).join(",") !== key || this.repositories.scope(other.refs).key !== scope.key) continue;
4019
- const shared = mine.filter(path => (other.refs.paths ?? []).some(theirs => samePlace(path, theirs)));
4020
- if (shared.length) throw new PreEffectToolRefusal(`parallel siblings must touch disjoint paths: "${title}" and task #${other.id} both touch ${shared.slice(0, PARALLEL_PATHS_NAMED).join(", ")}; call hub_task_propose again with disjoint refs.paths, or without reason parallel, or keep the work as one task you own`);
4021
- }
4022
- }
4023
-
4024
- /** Preview every fixed GitHub call from a complete inventory; confirmation binds both calls and local bindings. */
4025
- async roadmapSync(by: PeerId, input: { apply?: boolean; confirm?: string } = {}): Promise<{ repo: string; calls: string[][]; bindings: { milestone: number; number: number }[]; fingerprint: string; applied: boolean }> {
4026
- this.roadmapReadAuthority(by);
4027
- if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some(key => key !== "apply" && key !== "confirm") || typeof input.apply !== "undefined" && typeof input.apply !== "boolean" || input.confirm !== undefined && (typeof input.confirm !== "string" || !/^[a-f0-9]{64}$/.test(input.confirm))) throw new PreEffectToolRefusal("invalid roadmap sync options; preview before applying");
4028
- if (input.apply) this.roadmapApplyAuthority(by);
4029
- const config = this.d.roadmapConfig?.() ?? { github_mirror: false, github_write: "off" as const };
4030
- if (!config.github_mirror) throw new PreEffectToolRefusal("roadmap GitHub mirror is off; enable roadmap.github_mirror in trusted configuration before syncing");
4031
- const repo = this.roadmapRepository(), views = this.milestoneList(by);
4032
- if (views.length > 100) throw new PreEffectToolRefusal("roadmap mirror exceeds 100 milestones; narrow the roadmap before syncing");
4033
- const deadline = performance.now() + 50_000;
4034
- const stamp = () => createHash("sha256").update(JSON.stringify([this.d.board.milestones(), this.d.board.milestoneLinks(), this.d.board.list(), views.map(view => [view.id, this.d.board.mirrorMilestone(repo, view.id)]), this.d.roadmapConfig?.(), this.d.routing(), this.d.piiPaths, this.d.deny])).digest("hex");
4035
- let before = stamp(); const check = this.requestCheck(by, () => this.d.sweepHeld?.() || this.d.bus.isRecoveryHeld || this.d.bus.storageError ? "roadmap is held by recovery or storage" : undefined);
4036
- const current = () => { check(); this.roadmapReadAuthority(by); if (input.apply) this.roadmapApplyAuthority(by); if (this.roadmapRepository() !== repo || stamp() !== before) throw new PreEffectToolRefusal("roadmap, origin or authority changed; preview sync again"); };
4037
- const run = this.roadmapGh();
4038
- const snapshot = await readMirrorSnapshot(repo, async (...args) => { current(); const result = await run(...args); current(); return result; });
4039
- current();
4040
- const bindings: { milestone: number; number: number }[] = [], calls: string[][] = [], createIds: (number | undefined)[] = [], issueOwners = new Set<number>();
4041
- for (const view of views) for (const issue of view.issues) if (issue.ref.startsWith(`${repo}#`)) {
4042
- const id = milestoneId(Number(issue.ref.slice(repo.length + 1)));
4043
- if (issueOwners.has(id)) throw new PreEffectToolRefusal("an issue is linked to multiple roadmap milestones; settle its placement before syncing");
4044
- issueOwners.add(id);
4045
- }
4046
- for (const view of views) {
4047
- if (view.withheld || view.title === "[withheld]" || view.outcome === "[withheld]") throw new PreEffectToolRefusal("roadmap mirror contains withheld membership or metadata; inspect privacy before syncing");
4048
- const marker = `<!-- ahub-roadmap:${this.d.project}:${view.id} -->`, bound = this.d.board.mirrorMilestone(repo, view.id);
4049
- const matching = bound === undefined ? recoverMirrorBinding(marker, view.title, snapshot.milestones) : undefined;
4050
- if (matching?.kind === "ambiguous" || matching?.titleConflicts.length) throw new PreEffectToolRefusal("roadmap GitHub milestone identity is ambiguous; inspect matching milestones before syncing");
4051
- const remoteId = bound ?? (matching?.kind === "bind" ? matching.number : undefined);
4052
- if (bound === undefined && remoteId !== undefined) bindings.push({ milestone: view.id, number: remoteId });
4053
- const remote = remoteId === undefined ? null : snapshot.milestones.find(row => row.number === remoteId);
4054
- if (remoteId !== undefined && !remote) throw new PreEffectToolRefusal("recorded GitHub milestone is missing from the complete inventory; inspect the binding");
4055
- const issues = view.issues.filter(row => row.ref.startsWith(`${repo}#`)).map(row => Number(row.ref.slice(repo.length + 1)));
4056
- const planned = planRoadmapMirror(repo, { title: view.title, state: view.state === "done" || view.state === "dropped" ? "closed" : "open", issues, marker }, remote ?? null, snapshot.issues);
4057
- for (const call of planned.calls) {
4058
- const detached = /^repos\/[^/]+\/[^/]+\/issues\/([1-9][0-9]*)$/.exec(call[1] ?? "");
4059
- if (detached && call.includes("milestone=null") && issueOwners.has(Number(detached[1]))) continue;
4060
- calls.push(call); createIds.push(remoteId === undefined ? view.id : undefined);
4061
- if (calls.length > 200) throw new PreEffectToolRefusal("roadmap mirror exceeds 200 writes; narrow the roadmap before syncing");
4062
- }
4063
- }
4064
- const hiddenIssues = new Set<number>();
4065
- for (const task of this.d.board.list()) if (this.isPii(task) || task.signals.includes("pii") || task.signals.includes("pii_path")) {
4066
- try { const issue = this.planIssueIdentity(task); if (issue?.repo.toLowerCase() === repo) hiddenIssues.add(issue.issue); }
4067
- catch { throw new PreEffectToolRefusal("private issue placement is unknown; inspect privacy before syncing"); }
4068
- }
4069
- if (calls.some(call => { const match = /^repos\/[^/]+\/[^/]+\/issues\/([1-9][0-9]*)$/.exec(call[1] ?? ""); return !!match && hiddenIssues.has(Number(match[1])); })) throw new PreEffectToolRefusal("roadmap mirror would change private issue membership; inspect privacy before syncing");
4070
- const fingerprint = createHash("sha256").update(JSON.stringify({ repo, bindings, calls })).digest("hex");
4071
- if (!input.apply) return { repo, calls, bindings, fingerprint, applied: false };
4072
- if (input.confirm !== fingerprint) throw new PreEffectToolRefusal(`roadmap sync preview changed; run ahub roadmap sync and retry with --confirm ${fingerprint}`);
4073
- let effects = false;
4074
- const effectCurrent = () => { try { current(); } catch (error) { if (effects) throw new Error("roadmap sync authority changed after effects; inspect the mirror and preview again before retrying"); throw error; } };
4075
- effectCurrent();
4076
- for (const binding of bindings) {
4077
- effectCurrent();
4078
- try { this.d.board.bindMirrorMilestone(repo, binding.milestone, binding.number); effects = true; before = stamp(); }
4079
- catch (error) { if (effects) throw new Error("roadmap binding changed after effects; inspect the mirror and preview again"); throw error; }
4080
- }
4081
- for (let index = 0; index < calls.length; index++) {
4082
- effectCurrent();
4083
- let result: Awaited<ReturnType<SdlcGh>>;
4084
- const remaining = deadline - performance.now();
4085
- if (remaining <= 0) { if (effects) throw new Error("roadmap sync reached its deadline after effects; inspect the mirror and preview again"); throw new PreEffectToolRefusal("roadmap sync deadline expired before writes; preview again"); }
4086
- effects = true;
4087
- try { result = await run(calls[index]!, Math.min(10_000, remaining), undefined, 64 * 1024); }
4088
- catch { throw new Error("roadmap GitHub write outcome is unknown; inspect the mirror and preview again before retrying"); }
4089
- if (result.code !== 0 || Buffer.byteLength(result.stdout) > 64 * 1024) throw new Error("roadmap GitHub write was not confirmed; inspect the mirror and preview again before retrying");
4090
- const local = createIds[index];
4091
- if (local !== undefined) {
4092
- let number: number;
4093
- try {
4094
- const created = JSON.parse(result.stdout) as Record<string, unknown>, call = calls[index]!;
4095
- number = milestoneId(created.number);
4096
- if (created.title !== call.find(value => value.startsWith("title="))?.slice(6) || created.description !== call.find(value => value.startsWith("description="))?.slice(12) || created.state !== call.find(value => value.startsWith("state="))?.slice(6) || typeof created.html_url !== "string" || created.html_url.toLowerCase() !== `https://github.com/${repo}/milestone/${number}`) throw new Error("mismatch");
4097
- } catch { throw new Error("roadmap milestone creation was not confirmed; preview again to recover its marker"); }
4098
- effectCurrent();
4099
- try { this.d.board.bindMirrorMilestone(repo, local, number); before = stamp(); }
4100
- catch { throw new Error("roadmap milestone was created but its binding is uncertain; preview again to recover its marker"); }
4101
- }
4102
- effectCurrent();
4103
- }
4104
- return { repo, calls, bindings, fingerprint, applied: true };
4105
- }
4106
-
4107
- // ---- R3 (#1481): bottom-up placement. Reads are the roadmap read authority; every write below is the R1 writer, never a new one. ----
4108
-
4109
- /** The one repository the roadmap reads from GitHub: the caller's choice, else the project's. Never derived from model text. */
4110
- private roadmapRepo(raw: unknown): string | undefined {
4111
- if (raw === undefined) return undefined;
4112
- return this.roadmapParsed(() => githubRepo(raw));
4113
- }
4114
-
4115
- private roadmapGh(run?: SdlcGh): SdlcGh {
4116
- return run ?? this.d.roadmapGh ?? this.d.sdlc?.gh ?? ((args, timeout, _cwd, bound) => sdlcGh(args, timeout, this.d.cwd, bound));
4117
- }
4118
-
4119
- /** Issues, tasks and specs that no live milestone places, each with its reason. Private tasks are counted and never named. */
4120
- async roadmapUnplaced(by: PeerId, input: { repo?: unknown } = {}, run?: SdlcGh): Promise<UnplacedResult & { repo: string | null }> {
4121
- this.roadmapReadAuthority(by);
4122
- const repo = this.roadmapRepo(input.repo);
4123
- let issues: Awaited<ReturnType<typeof readGitHubIssuePages>> | undefined;
4124
- try { issues = await readGitHubIssuePages({ ...(repo === undefined ? {} : { repo }) }, this.roadmapGh(run)); } catch { issues = undefined; }
4125
- this.roadmapReadAuthority(by);
4126
- let specs: { id: string; title: string; status: string | null }[] | undefined;
4127
- try { const list = this.d.specsList?.(); if (list && !list.truncated && list.errors === 0) specs = list.specs; } catch { specs = undefined; }
4128
- const snapshot = this.roadmapSnapshot(by);
4129
- const result = computeUnplaced({ milestones: snapshot.milestones, links: snapshot.links, tasks: snapshot.tasks, issues, specs, issueOf: snapshot.issueOf, privateTask: snapshot.privateTask, publicText: snapshot.publicText });
4130
- return { ...result, repo: issues?.repo ?? repo ?? null };
4131
- }
4132
-
4133
- /** Pending and settled suggestions as a caller may read them: public text only. */
4134
- milestoneSuggestions(by: PeerId, state?: MilestoneSuggestion["state"]): MilestoneSuggestion[] {
4135
- this.roadmapReadAuthority(by);
4136
- return this.d.board.suggestions(state).filter(row => this.suggestionPublic(row));
4137
- }
4138
-
4139
- private suggestionPublic(row: MilestoneSuggestion): boolean {
4140
- const text = [row.ref, row.citeItem, row.citeMilestone ?? "", row.proposal?.title ?? "", row.proposal?.outcome ?? ""].join("\n");
4141
- if (!this.publicMetadataText(text)) return false;
4142
- if (row.kind !== "task") return true;
4143
- const task = this.d.board.get(Number(row.ref));
4144
- return task !== undefined && !this.isPii(task) && !task.signals.includes("pii");
4145
- }
4146
-
4147
- /**
4148
- * Ask the hub's model where unplaced items belong. The model sees only public text, answers are checked against what it was shown
4149
- * (ids offered, cited words present), saved as pending suggestions, and nothing is linked: that is `roadmapAccept`.
4150
- */
4151
- async roadmapTriage(by: PeerId, input: { repo?: unknown } = {}, run?: SdlcGh): Promise<{ suggestions: MilestoneSuggestion[]; asked: number; dropped: number; partial: boolean; unavailable: string | null }> {
4152
- const current = this.roadmapWriteAuthority(by);
4153
- const unplaced = await this.roadmapUnplaced(by, input, run);
4154
- current();
4155
- const snapshot = this.roadmapSnapshot(by), views = milestoneViews(snapshot);
4156
- const pending = new Set(this.d.board.suggestions("pending").map(row => `${row.kind}:${row.ref}`));
4157
- const items: TriageItem[] = [
4158
- ...unplaced.tasks.map(row => ({ kind: "task" as const, ref: String(row.id), text: row.title })),
4159
- ...unplaced.issues.map(row => ({ kind: "issue" as const, ref: row.ref, text: row.title })),
4160
- ...unplaced.specs.map(row => ({ kind: "spec" as const, ref: row.id, text: row.title })),
4161
- ].filter(item => !pending.has(`${item.kind}:${item.ref}`));
4162
- const live = views.filter(view => view.state !== "done" && view.state !== "dropped" && view.title !== "[withheld]");
4163
- const batch = items.slice(0, TRIAGE_BATCH);
4164
- const done = (suggestions: MilestoneSuggestion[], dropped: number, unavailable: string | null) => ({ suggestions, asked: batch.length, dropped, partial: unplaced.partial || items.length > batch.length, unavailable });
4165
- if (!batch.length) return done([], 0, null);
4166
- if (!this.d.roadmapModel) return done([], 0, "no hub model is configured for roadmap triage");
4167
- const prompt = buildTriagePrompt(batch, live.map(view => ({ id: view.id, title: view.title, outcome: view.outcome })));
4168
- const answer = await this.d.roadmapModel(prompt.system, prompt.user, () => { try { current(); return true; } catch { return false; } });
4169
- current();
4170
- if (!answer) return done([], 0, "the hub model gave no answer; retry ahub roadmap triage later");
4171
- const parsed = parseTriage(answer, prompt), saved: MilestoneSuggestion[] = [], at = this.d.now?.() ?? Date.now();
4172
- for (const row of parsed.suggestions) {
4173
- // Re-screen at the write: what is stored is public planning text only, and a milestone that has since settled is not a target.
4174
- if (row.milestone !== null) { const target = this.d.board.milestone(row.milestone); if (!target || ["done", "dropped"].includes(target.state)) continue; }
4175
- const text = [row.ref, row.citeItem, row.citeMilestone ?? "", row.proposal?.title ?? "", row.proposal?.outcome ?? ""].join("\n");
4176
- if (!this.publicMetadataText(text)) continue;
4177
- if (this.screenOn() && (await this.screenCall(text)).label !== "clear") continue;
4178
- current();
4179
- // A model's answer, attributed to the hub (never to the asker), is advisory data: no ask or memory path reads this table.
4180
- const made = this.d.board.addSuggestion(row, "hub", at);
4181
- if (made) saved.push(made);
4182
- }
4183
- return done(saved, parsed.dropped + parsed.suggestions.length - saved.length, null);
4184
- }
4185
-
4186
- /**
4187
- * R2 (#1480) part 1: ask the hub's model how one milestone decomposes. The model sees only the milestone's public text, the
4188
- * specs it links and the issues it links; each part must cite an id it was shown, and the answer is saved as a hub-attributed
4189
- * model answer. Nothing is intaken, linked, published or accepted here.
4190
- */
4191
- async roadmapDecompose(by: PeerId, rawId: unknown, run?: SdlcGh): Promise<{ milestone: number; parts: DecomposePart[]; dropped: number; saved: MilestoneDecomposition | null; unavailable: string | null }> {
4192
- const current = this.roadmapWriteAuthority(by);
4193
- const id = this.roadmapParsed(() => milestoneId(rawId)), view = this.milestoneShow(by, id);
4194
- current();
4195
- if (view.title === "[withheld]" || view.outcome === "[withheld]") throw new PreEffectToolRefusal("milestone text is not cleared for public planning; remove private content before ahub roadmap decompose");
4196
- const done = (parts: DecomposePart[], dropped: number, saved: MilestoneDecomposition | null, unavailable: string | null) => ({ milestone: id, parts, dropped, saved, unavailable });
4197
- const publicText = (value: string): boolean => { try { return this.publicMetadataText(value); } catch { return false; } };
4198
- let rows: { id: string; title: string; status: string | null; type?: string; paths?: string[] }[] | undefined;
4199
- try { const list = this.d.specsList?.(); if (list && !list.truncated && list.errors === 0) rows = list.specs; } catch { rows = undefined; }
4200
- const linked = new Set(view.specs.map(row => row.id));
4201
- // Every field that enters the prompt passes the same public screen R3's unplaced list uses; a spec that fails it is not
4202
- // offered at all, exactly as an unplaced spec is dropped from triage.
4203
- const summaries = (rows ?? []).filter(row => linked.has(row.id)
4204
- && [row.id, row.title, ...(row.type ? [row.type] : []), ...(row.status ? [row.status] : []), ...(row.paths ?? []).slice(0, DECOMPOSE_PATHS)].every(publicText));
4205
- // The milestone's own context is the goal and architecture specs it links; when it links only other types, those are its context.
4206
- const top = summaries.filter(row => row.type === "goal" || row.type === "architecture");
4207
- const specs: DecomposeItem[] = (top.length ? top : summaries).map(row => ({ ref: row.id, label: `spec ${row.id}`,
4208
- text: `${row.title} (${row.type || "spec"}${row.status ? `, ${row.status}` : ""})${row.paths?.length ? ` covers: ${row.paths.slice(0, DECOMPOSE_PATHS).join(", ")}` : ""}` }));
4209
- // Titles for linked issues come from the same bounded page read R3 uses. A ref outside that repository, an unreadable
4210
- // page, or a title the public screen refuses still offers its id with no text, so a part can cite it; the milestone's own
4211
- // links are the only source of refs.
4212
- const refs = view.issues.map(row => row.ref), first = refs.length ? /^([^#]+)#[1-9][0-9]*$/.exec(refs[0]!)![1]! : undefined;
4213
- const titles = new Map<string, string>();
4214
- if (first !== undefined) {
4215
- try { const page = await readGitHubIssuePages({ repo: first }, this.roadmapGh(run)); current(); for (const row of page.rows) if (publicText(row.title)) titles.set(`${page.repo}#${row.number}`, row.title); }
4216
- catch { /* unavailable titles are not an empty list: the ref is still offered */ }
4217
- }
4218
- const issues: DecomposeItem[] = refs.map(ref => ({ ref, label: `issue ${ref}`, text: titles.get(ref) ?? "" }));
4219
- if (!specs.length && !issues.length) return done([], 0, null, "the milestone links no spec or issue to decompose from");
4220
- if (!this.d.roadmapModel) return done([], 0, null, "no hub model is configured for roadmap decompose");
4221
- const prompt = buildDecomposePrompt({ milestone: { id, title: view.title, outcome: view.outcome }, specs: specs.slice(0, DECOMPOSE_ITEMS), issues: issues.slice(0, DECOMPOSE_ITEMS) });
4222
- const answer = await this.d.roadmapModel(prompt.system, prompt.user, () => { try { current(); return true; } catch { return false; } });
4223
- current();
4224
- if (!answer) return done([], 0, null, "the hub model gave no answer; retry ahub roadmap decompose later");
4225
- const parsed = parseDecomposition(answer, prompt), kept: DecomposePart[] = [];
4226
- for (const part of parsed.parts) {
4227
- // Re-screen at the write, exactly as triage does: what is stored is public planning text only.
4228
- const text = [part.title, part.detail, ...part.cites].join("\n");
4229
- if (!this.publicMetadataText(text)) continue;
4230
- if (this.screenOn() && (await this.screenCall(text)).label !== "clear") continue;
4231
- current(); kept.push(part);
4232
- }
4233
- const dropped = parsed.dropped + parsed.parts.length - kept.length;
4234
- if (!kept.length) return done([], dropped, null, null);
4235
- const saved = this.d.board.addDecomposition({ milestone: id, parts: kept }, HUB, this.d.now?.() ?? Date.now());
4236
- return done(kept, dropped, saved, null);
4237
- }
4238
-
4239
- /**
4240
- * R2 (#1480) part 2: accept one proposed part as a held intake draft. The draft is the existing intake hold (`draft` and
4241
- * `backlog`): nothing offers, pulls or routes it until the person approves it with `ahub intake approve`, and this path grants
4242
- * no new release authority. It carries the milestone link and the part's `spec`/`task` kind, each part is accepted on its own,
4243
- * and a second accept of the same part returns the draft the first one made. The reply is a public view, so a private draft
4244
- * reads `[withheld]` and no notice repeats the part's words. One accept per part runs at a time: a concurrent caller waits for
4245
- * the attempt in flight and then reads the accept row, so two accepts of one part cannot make two drafts.
4246
- */
4247
- async roadmapDecomposePart(by: PeerId, rawId: unknown, rawPart: unknown): Promise<{ milestone: number; part: number; intake: DecomposeIntake; task: Record<string, unknown>; created: boolean }> {
4248
- const current = this.roadmapWriteAuthority(by);
4249
- const id = this.roadmapParsed(() => milestoneId(rawId)), part = this.roadmapParsed(() => milestoneId(rawPart));
4250
- const view = this.milestoneShow(by, id);
4251
- current();
4252
- if (view.title === "[withheld]" || view.outcome === "[withheld]") throw new PreEffectToolRefusal("milestone text is not cleared for public planning; remove private content before accepting a part");
4253
- const pending = this.d.board.pendingDecomposition(id);
4254
- if (!pending) throw new PreEffectToolRefusal(`milestone ${id} has no pending decomposition; run ahub roadmap decompose ${id} first`);
4255
- if (part > pending.parts.length) throw new PreEffectToolRefusal(`milestone ${id} holds ${pending.parts.length} proposed part${pending.parts.length === 1 ? "" : "s"}; run ahub roadmap decompose ${id} to read them again`);
4256
- const chosen = pending.parts[part - 1]!;
4257
- // A retry reads the draft the first accept made, and records the link again if an interrupted tail lost it.
4258
- const earlier = this.roadmapAcceptedPart(by, id, pending.id, part);
4259
- if (earlier) return earlier;
4260
- const taskClass = CLASSES.includes(chosen.class as TaskClass) ? chosen.class as TaskClass : undefined;
4261
- if (!taskClass) throw new PreEffectToolRefusal(`part ${part} names no hub task class; run ahub roadmap decompose ${id} to replace the answer`);
4262
- // A milestone settled while its answer was pending refuses here, before any write. The same check runs again where the link
4263
- // is written, and there it is best-effort: the draft is durable by then.
4264
- this.roadmapCurrent(id);
4265
- current();
4266
- // One accept per part: a concurrent caller of the same part waits for the attempt in flight and then reads the accept row.
4267
- const key = `${pending.id}:${part}`, running = this.decompositionAccepts.get(key);
4268
- if (running) {
4269
- await running.catch(() => undefined);
4270
- const after = this.roadmapAcceptedPart(by, id, pending.id, part);
4271
- if (after) return after;
4272
- if (this.d.board.pendingDecomposition(id)?.id !== pending.id) throw new PreEffectToolRefusal(`milestone ${id} has a newer decomposition answer; run ahub roadmap decompose ${id} to read it again`);
4273
- }
4274
- const attempt = this.acceptDecompositionPartOnce(by, id, part, pending, chosen, taskClass);
4275
- this.decompositionAccepts.set(key, attempt);
4276
- try { return await attempt; } finally { if (this.decompositionAccepts.get(key) === attempt) this.decompositionAccepts.delete(key); }
4277
- }
4278
-
4279
- /** The accept row's own draft, while that task exists: the retry's answer, with the milestone link recorded again. */
4280
- private roadmapAcceptedPart(by: PeerId, id: number, decomposition: number, part: number): { milestone: number; part: number; intake: DecomposeIntake; task: Record<string, unknown>; created: boolean } | undefined {
4281
- const accepted = this.d.board.decompositionAccept(decomposition, part), earlier = accepted ? this.d.board.get(accepted.task) : undefined;
4282
- if (!accepted || !earlier) return undefined;
4283
- // Idempotent, so a missing link heals here; a milestone settled since refuses that as a notice, never as the caller's refusal.
4284
- this.releaseNotice(`task #${earlier.id}: milestone ${id} part ${part} accepted without its milestone link`, () => {
4285
- const milestone = this.roadmapCurrent(id);
4286
- this.d.board.linkMilestone(id, "task", String(earlier.id), by, milestone.revision, this.d.now?.() ?? Date.now());
4287
- });
4288
- return { milestone: id, part, intake: accepted.intake, task: this.publicView(earlier), created: false };
4289
- }
4290
-
4291
- /** One accept attempt: the durable draft, then a tail that records the hold and never refuses the caller. */
4292
- private async acceptDecompositionPartOnce(by: PeerId, id: number, part: number, pending: MilestoneDecomposition, chosen: DecomposePart, taskClass: TaskClass): Promise<{ milestone: number; part: number; intake: DecomposeIntake; task: Record<string, unknown>; created: boolean }> {
4293
- const draft = await this.propose(by, { [HOST_ROADMAP_DRAFT]: true, title: chosen.title, detail: this.decompositionDraftDetail(chosen, id, part, pending.parts.length), class: taskClass, backlog: true, draft: true });
4294
- // The task and its hold are saved, so nothing below may fail the caller: a planner is not told about a held draft, and the
4295
- // accept row, the milestone link and the notice are best-effort in that order.
4296
- this.incomingBacklog.delete(draft.id);
4297
- this.releaseNotice(`task #${draft.id}: milestone ${id} part ${part} accepted without its accept record`, () => {
4298
- this.d.board.acceptDecompositionPart({ decomposition: pending.id, milestone: id, part, task: draft.id, intake: chosen.intake }, by, this.d.now?.() ?? Date.now());
4299
- });
4300
- this.releaseNotice(`task #${draft.id}: milestone ${id} part ${part} accepted without its milestone link`, () => {
4301
- const milestone = this.roadmapCurrent(id);
4302
- this.d.board.linkMilestone(id, "task", String(draft.id), by, milestone.revision, this.d.now?.() ?? Date.now());
4303
- });
4304
- this.releaseNotice(`task #${draft.id}: milestone ${id} part ${part} accepted as a held intake draft`);
4305
- return { milestone: id, part, intake: chosen.intake, task: this.publicView(this.d.board.get(draft.id) ?? draft), created: true };
4306
- }
4307
-
4308
- /** The held draft's detail: the part's own words, then the one line a person reads before releasing it. */
4309
- private decompositionDraftDetail(part: DecomposePart, milestone: number, index: number, total: number): string {
4310
- const kind = part.intake === "spec" ? "needs its own spec issue before implementation" : "a mechanical chore that goes straight to a task";
4311
- return [part.detail, `Milestone ${milestone} part ${index} of ${total}: ${kind}. Cites: ${part.cites.join(", ")}.`, `Held until released: ahub intake approve`].join("\n\n");
4312
- }
4313
-
4314
- /**
4315
- * R2 (#1480) part 3: publish the milestone's held drafts to GitHub. `--publish` plans one issue per held `spec` part from a
4316
- * complete reading of the holds and writes nothing; apply creates each issue through one gh call and links it to the
4317
- * milestone: R1's own `issue` link, and the R4 membership field the create carries when the mirror has a binding, so this
4318
- * path adds no second link. A `task` part is its own held draft, a released draft is no longer the hold's work, a private part
4319
- * is only counted, and a refused or unconfirmed call leaves the draft held and names the failure.
4320
- */
4321
- async roadmapDecomposePublish(by: PeerId, rawId: unknown, input: { apply?: boolean; confirm?: string } = {}): Promise<{
4322
- milestone: number; repo: string; githubMilestone: number | null; parts: PublishPlanPart[]; calls: string[][];
4323
- skippedPrivate: number; skippedUnknown: number; fingerprint: string; applied: boolean; created: { part: number; task: number; issue: number }[];
4324
- }> {
4325
- const current = this.roadmapWriteAuthority(by);
4326
- if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some(key => key !== "apply" && key !== "confirm")
4327
- || input.apply !== undefined && typeof input.apply !== "boolean"
4328
- || input.confirm !== undefined && (typeof input.confirm !== "string" || !/^[a-f0-9]{64}$/.test(input.confirm)))
4329
- throw new PreEffectToolRefusal("invalid roadmap publish options; preview with ahub roadmap decompose <id> --publish before applying");
4330
- if (input.apply && input.confirm === undefined) throw new PreEffectToolRefusal("roadmap decompose --apply needs its preview fingerprint; preview with ahub roadmap decompose <id> --publish first");
4331
- if (input.apply) this.roadmapApplyAuthority(by);
4332
- const id = this.roadmapParsed(() => milestoneId(rawId)), view = this.milestoneShow(by, id);
4333
- if (view.title === "[withheld]" || view.outcome === "[withheld]") throw new PreEffectToolRefusal("milestone text is not cleared for public planning; remove private content before publishing a part");
4334
- // A milestone settled while its drafts are held refuses here, before any read of GitHub or any write.
4335
- this.roadmapCurrent(id);
4336
- current();
4337
- const repo = this.roadmapRepository(), config = this.d.roadmapConfig?.() ?? { github_mirror: false, github_write: "off" as const };
4338
- // The GitHub milestone comes from the mirror binding, never from an argument; with the mirror off nothing is attached.
4339
- const githubMilestone = config.github_mirror ? this.d.board.mirrorMilestone(repo, id) ?? null : null;
4340
- const drafts: PublishDraft[] = [], held = new Map<number, DecompositionAccept>();
4341
- let skippedPrivate = 0, skippedUnknown = 0;
4342
- for (const accept of this.d.board.decompositionAcceptsFor(id)) {
4343
- const task = this.d.board.get(accept.task);
4344
- if (!task) continue;
4345
- const part = this.d.board.decomposition(accept.decomposition)?.parts[accept.part - 1];
4346
- // Without the answer a part's own words are gone; the draft stays held and the preview says to propose the parts again.
4347
- const text = part ? [part.title, part.detail, ...part.cites].join("\n") : "";
4348
- let privatePart = true;
4349
- try { privatePart = this.isPii(task) || !part || !this.publicMetadataText(text); } catch { privatePart = true; }
4350
- if (part && !privatePart && this.screenOn()) { const label = (await this.screenCall(text)).label; current(); privatePart = label !== "clear"; }
4351
- if (!part) { skippedUnknown++; continue; }
4352
- if (privatePart) { skippedPrivate++; continue; }
4353
- held.set(task.id, accept);
4354
- drafts.push({ part: accept.part, task: task.id, intake: accept.intake, title: part.title, detail: part.detail, cites: part.cites,
4355
- published: this.d.board.decompositionPublish(accept.decomposition, accept.part) ?? null,
4356
- hold: task.draft === true && task.state === "backlog" ? "held" : "released" });
4357
- }
4358
- const planned = planPartPublish({ project: this.d.project, repo, milestone: id, githubMilestone, parts: drafts });
4359
- const fingerprint = createHash("sha256").update(JSON.stringify({ repo, milestone: id, githubMilestone, calls: planned.calls })).digest("hex");
4360
- const reply = { milestone: id, repo, githubMilestone, ...planned, skippedPrivate, skippedUnknown, fingerprint, applied: false as boolean, created: [] as { part: number; task: number; issue: number }[] };
4361
- if (!input.apply) return reply;
4362
- if (input.confirm !== fingerprint) throw new PreEffectToolRefusal(`roadmap publish preview changed; run ahub roadmap decompose ${id} --publish and retry with --confirm ${fingerprint}`);
4363
- current(); this.roadmapApplyAuthority(by); if (this.roadmapRepository() !== repo) throw new PreEffectToolRefusal("roadmap GitHub origin changed; preview the publish again");
4364
- // A retried call whose first attempt is still creating must not POST every planned issue again: `INSERT OR IGNORE` would keep
4365
- // the first publish row and GitHub would keep both issues. One apply per milestone, refused with the next step it can take.
4366
- if (this.roadmapPublishes.has(id))
4367
- throw new PreEffectToolRefusal(`a publish for milestone ${id} is already running; wait for it to finish and run ahub roadmap decompose ${id} --publish again`);
4368
- this.roadmapPublishes.add(id);
4369
- try {
4370
- const creating = planned.parts.filter(row => row.action === "create"), created = reply.created;
4371
- for (const [index, call] of planned.calls.entries()) {
4372
- const row = creating[index]!, accept = held.get(row.task)!;
4373
- // A part an earlier attempt already recorded has its issue: never POST it a second time.
4374
- if (this.d.board.decompositionPublish(accept.decomposition, row.part) !== undefined) continue;
4375
- const refused = `roadmap publish was refused for milestone ${id} part ${row.part}; the draft stays held and no issue was linked. Inspect ${repo} before retrying`;
4376
- let result: Awaited<ReturnType<SdlcGh>>;
4377
- try { result = await this.roadmapGh()(call, 10_000, undefined, 64 * 1024); }
4378
- catch { throw new Error(`roadmap publish was not confirmed for milestone ${id} part ${row.part}; the draft stays held and no issue was linked. Inspect ${repo} before retrying`); }
4379
- if (result.code !== 0 || Buffer.byteLength(result.stdout) > 64 * 1024) throw new Error(refused);
4380
- let issue: number;
4381
- try {
4382
- const made = JSON.parse(result.stdout) as Record<string, unknown>;
4383
- issue = milestoneId(made.number);
4384
- if (made.title !== call.find(value => value.startsWith("title="))?.slice(6)
4385
- || typeof made.html_url !== "string" || made.html_url.toLowerCase() !== `https://github.com/${repo}/issues/${issue}`) throw new Error("mismatch");
4386
- } catch { throw new Error(`roadmap publish created an issue for milestone ${id} part ${row.part} but its answer was not confirmed; inspect ${repo} before retrying`); }
4387
- // The issue exists, so nothing below may refuse the caller: the publish record and the milestone link are best effort.
4388
- this.releaseNotice(`milestone ${id} part ${row.part}: issue ${repo}#${issue} created without its publish record`, () => {
4389
- this.d.board.recordDecompositionPublish({ decomposition: accept.decomposition, milestone: id, part: row.part, issue }, by, this.d.now?.() ?? Date.now());
4390
- });
4391
- this.releaseNotice(`milestone ${id} part ${row.part}: issue ${repo}#${issue} created without its milestone link`, () => {
4392
- const milestone = this.roadmapCurrent(id);
4393
- this.d.board.linkMilestone(id, "issue", `${repo}#${issue}`, by, milestone.revision, this.d.now?.() ?? Date.now());
4394
- });
4395
- created.push({ part: row.part, task: row.task, issue });
4396
- }
4397
- reply.applied = true;
4398
- return reply;
4399
- } finally { this.roadmapPublishes.delete(id); }
4400
- }
4401
-
4402
- /** Apply one suggestion through R1's own writers. A "new milestone" suggestion creates it first; a retry never creates a second. */
4403
- async roadmapAccept(by: PeerId, rawId: unknown): Promise<{ suggestion: MilestoneSuggestion; milestone: MilestoneView }> {
4404
- const current = this.roadmapWriteAuthority(by);
4405
- const id = this.roadmapParsed(() => milestoneId(rawId)), row = this.d.board.suggestion(id);
4406
- if (!row) throw new PreEffectToolRefusal("roadmap suggestion does not exist; use ahub roadmap triage");
4407
- if (row.state !== "pending") throw new PreEffectToolRefusal(`roadmap suggestion was already ${row.state}; run ahub roadmap triage for current suggestions`);
4408
- if (!this.suggestionPublic(row)) throw new PreEffectToolRefusal("roadmap suggestion text is no longer public; reject it with ahub roadmap reject");
4409
- let target = row.milestone ?? this.d.board.suggestionCreated(id);
4410
- if (target === undefined) {
4411
- const proposal = row.proposal;
4412
- if (!proposal) throw new PreEffectToolRefusal("roadmap suggestion has no target; reject it with ahub roadmap reject");
4413
- const fields = this.roadmapParsed(() => parseMilestoneInput({ title: proposal.title, outcome: proposal.outcome }));
4414
- await this.roadmapScreen(fields); current();
4415
- const made = this.d.board.newMilestone(fields, by, this.d.now?.() ?? Date.now());
4416
- this.d.board.setSuggestionCreated(id, made.id); target = made.id;
4417
- }
4418
- const milestone = this.roadmapCurrent(target);
4419
- const ref = this.roadmapParsed(() => milestoneLinkRef(row.kind, row.ref));
4420
- if (row.kind === "task" && !this.d.board.get(Number(ref))) throw new PreEffectToolRefusal("roadmap target does not exist; reject the suggestion with ahub roadmap reject");
4421
- current();
4422
- this.d.board.linkMilestone(target, row.kind, ref, by, milestone.revision, this.d.now?.() ?? Date.now());
4423
- const settled = this.d.board.settleSuggestion(id, "accepted", by, this.d.now?.() ?? Date.now());
4424
- return { suggestion: settled, milestone: this.roadmapResult(by, target) };
4425
- }
4426
-
4427
- roadmapReject(by: PeerId, rawId: unknown): MilestoneSuggestion {
4428
- this.roadmapWriteAuthority(by);
4429
- const id = this.roadmapParsed(() => milestoneId(rawId));
4430
- return this.d.board.settleSuggestion(id, "rejected", by, this.d.now?.() ?? Date.now());
4431
- }
4432
-
4433
- /**
4434
- * One-time import of open GitHub milestones as `proposed` milestones, linking their open issues. A dry run unless `apply`.
4435
- * A repeat finds each milestone's import mark and each link, so a second `apply` changes nothing. Nothing is ever written to GitHub.
4436
- */
4437
- async roadmapImportGitHub(by: PeerId, input: { repo?: unknown; apply?: unknown } = {}, run?: SdlcGh): Promise<{
4438
- repo: string; apply: boolean; partial: boolean; milestones: { number: number; title: string; milestone: number | null; action: "create" | "exists"; issues: string[]; newLinks: number }[]; created: number; linked: number; withheld: number;
4439
- }> {
4440
- const current = this.roadmapWriteAuthority(by);
4441
- if (by !== USER) throw new PreEffectToolRefusal("GitHub milestone import is a console command; ask the person to run ahub roadmap import-github");
4442
- if (input.apply !== undefined && typeof input.apply !== "boolean") throw new PreEffectToolRefusal("roadmap import apply must be true or false; omit it for a dry run");
4443
- const apply = input.apply === true, gh = this.roadmapGh(run), repoInput = this.roadmapRepo(input.repo);
4444
- const milestonePages = await readGitHubMilestonePages({ ...(repoInput === undefined ? {} : { repo: repoInput }) }, gh);
4445
- const issuePages = await readGitHubIssuePages({ repo: milestonePages.repo }, gh);
4446
- current();
4447
- const issuesOf = new Map<number, string[]>();
4448
- for (const row of issuePages.rows) if (row.milestone !== null) issuesOf.set(row.milestone, [...(issuesOf.get(row.milestone) ?? []), `${issuePages.repo}#${row.number}`]);
4449
- const out: { number: number; title: string; milestone: number | null; action: "create" | "exists"; issues: string[]; newLinks: number }[] = [];
4450
- let created = 0, linked = 0, withheld = 0;
4451
- for (const source of milestonePages.rows) {
4452
- const description = source.description || `Imported from GitHub milestone ${milestonePages.repo}#milestone/${source.number}`;
4453
- let fields: ReturnType<typeof parseMilestoneInput>;
4454
- try { fields = parseMilestoneInput({ title: source.title, outcome: description.slice(0, 4000), ...(source.due ? { target: source.due } : {}) }); }
4455
- catch { withheld++; continue; }
4456
- const prior = this.d.board.importedMilestone(milestonePages.repo, source.number), existing = prior === undefined ? undefined : this.d.board.milestone(prior);
4457
- const refs = (issuesOf.get(source.number) ?? []).filter(ref => this.publicMetadataText(ref));
4458
- const have = new Set(existing ? this.d.board.milestoneLinks(existing.id).filter(link => link.kind === "issue").map(link => link.ref) : []);
4459
- const newRefs = refs.filter(ref => !have.has(ref));
4460
- const text = `${fields.title}\n${fields.outcome}`;
4461
- if (!this.publicMetadataText(text)) { withheld++; continue; }
4462
- const row = { number: source.number, title: sanitize(fields.title), milestone: existing?.id ?? null, action: existing ? "exists" as const : "create" as const, issues: refs, newLinks: newRefs.length };
4463
- if (apply) {
4464
- // The model screen runs on apply only, for a milestone about to be created; a dry run lists what passes the pattern screen.
4465
- if (!existing && this.screenOn() && (await this.screenCall(text)).label !== "clear") { withheld++; continue; }
4466
- current();
4467
- const made = this.d.board.importMilestone(milestonePages.repo, source.number, fields, by, this.d.now?.() ?? Date.now());
4468
- if (made.created) created++;
4469
- row.milestone = made.milestone.id;
4470
- for (const ref of newRefs) {
4471
- const live = this.d.board.milestone(made.milestone.id)!;
4472
- // A settled milestone is final: an import never reopens or relinks it.
4473
- if (["done", "dropped"].includes(live.state)) break;
4474
- const before = this.d.board.milestoneLinks(made.milestone.id).length;
4475
- this.d.board.linkMilestone(made.milestone.id, "issue", ref, by, live.revision, this.d.now?.() ?? Date.now());
4476
- if (this.d.board.milestoneLinks(made.milestone.id).length > before) linked++;
4477
- }
4478
- }
4479
- out.push(row);
4480
- }
4481
- return { repo: milestonePages.repo, apply, partial: milestonePages.partial || issuePages.partial, milestones: out, created, linked, withheld };
4482
- }
4483
-
3136
+ private roadmapReadAuthority(by: PeerId): void { return this.roadmap.roadmapReadAuthority(by); }
3137
+ private roadmapWriteAuthority(by: PeerId): () => void { return this.roadmap.roadmapWriteAuthority(by); }
3138
+ private roadmapParsed<T>(read: () => T): T { return this.roadmap.roadmapParsed(read); }
3139
+ private roadmapCurrent(id: unknown, state?: MilestoneState): Milestone { return this.roadmap.roadmapCurrent(id, state); }
3140
+ private async roadmapScreen(fields: MilestonePatch): Promise<void> { return this.roadmap.roadmapScreen(fields); }
3141
+ private roadmapResult(by: PeerId, id: number): MilestoneView { return this.roadmap.roadmapResult(by, id); }
3142
+ async milestoneNew(by: PeerId, raw: unknown): Promise<MilestoneView> { return this.roadmap.milestoneNew(by, raw); }
3143
+ async milestoneEdit(by: PeerId, id: number, revision: number, raw: unknown): Promise<MilestoneView> { return this.roadmap.milestoneEdit(by, id, revision, raw); }
3144
+ milestoneLink(by: PeerId, id: number, kind: MilestoneLinkKind, raw: string): MilestoneView { return this.roadmap.milestoneLink(by, id, kind, raw); }
3145
+ milestoneUnlink(by: PeerId, id: number, kind: MilestoneLinkKind, raw: string): MilestoneView { return this.roadmap.milestoneUnlink(by, id, kind, raw); }
3146
+ milestoneOrder(by: PeerId, id: number, order: number): MilestoneView { return this.roadmap.milestoneOrder(by, id, order); }
3147
+ milestoneState(by: PeerId, id: number, state: MilestoneState): MilestoneView { return this.roadmap.milestoneState(by, id, state); }
3148
+ private roadmapSnapshot(by: PeerId, specs?: () => SpecsCheckReport | SpecsCoverReport | undefined): RoadmapSnapshot { return this.roadmap.roadmapSnapshot(by, specs); }
3149
+ milestoneList(by: PeerId, specs?: () => SpecsCheckReport | SpecsCoverReport | undefined): (MilestoneView & { tree: TreeRollup; readyToClose: ReadyToClose })[] { return this.roadmap.milestoneList(by, specs); }
3150
+ milestoneShow(by: PeerId, id: number): MilestoneView { return this.roadmap.milestoneShow(by, id); }
3151
+ private roadmapRepository(): string { return this.roadmap.roadmapRepository(); }
3152
+ private roadmapApplyAuthority(by: PeerId): void { return this.roadmap.roadmapApplyAuthority(by); }
3153
+ async roadmapExport(by: PeerId, input: { issue?: number; apply?: boolean; confirm?: string } = {}): Promise<{ json: string; markdown: string; fingerprint: string; call?: string[]; applied: boolean }> { return this.roadmap.roadmapExport(by, input); }
3154
+ async roadmapCheck(by: PeerId, include?: (finding: RoadmapDrift) => boolean): Promise<ReturnType<typeof checkRoadmap>> { return this.roadmap.roadmapCheck(by, include); }
3155
+ async roadmapNotify(taskIds: readonly number[], send: (task: number, milestone: number | null, rule: number, marker: string) => boolean): Promise<number> { return this.roadmap.roadmapNotify(taskIds, send); }
3156
+ private proposalReason(value: unknown): TaskReason | undefined { return this.roadmap.proposalReason(value); }
3157
+ private parallelSiblingsDisjoint(by: PeerId, title: string, refs: TaskRefs, deps: number[]): void { return this.roadmap.parallelSiblingsDisjoint(by, title, refs, deps); }
3158
+ async roadmapSync(by: PeerId, input: { apply?: boolean; confirm?: string } = {}): Promise<{ repo: string; calls: string[][]; bindings: { milestone: number; number: number }[]; fingerprint: string; applied: boolean }> { return this.roadmap.roadmapSync(by, input); }
3159
+ private roadmapRepo(raw: unknown): string | undefined { return this.roadmap.roadmapRepo(raw); }
3160
+ private roadmapGh(run?: SdlcGh): SdlcGh { return this.roadmap.roadmapGh(run); }
3161
+ async roadmapUnplaced(by: PeerId, input: { repo?: unknown } = {}, run?: SdlcGh): Promise<UnplacedResult & { repo: string | null }> { return this.roadmapPlan.roadmapUnplaced(by, input, run); }
3162
+ milestoneSuggestions(by: PeerId, state?: MilestoneSuggestion["state"]): MilestoneSuggestion[] { return this.roadmapPlan.milestoneSuggestions(by, state); }
3163
+ async roadmapTriage(by: PeerId, input: { repo?: unknown } = {}, run?: SdlcGh): Promise<{ suggestions: MilestoneSuggestion[]; asked: number; dropped: number; partial: boolean; unavailable: string | null }> { return this.roadmapPlan.roadmapTriage(by, input, run); }
3164
+ async roadmapDecompose(by: PeerId, rawId: unknown, run?: SdlcGh): Promise<{ milestone: number; parts: DecomposePart[]; dropped: number; saved: MilestoneDecomposition | null; unavailable: string | null }> { return this.roadmapPlan.roadmapDecompose(by, rawId, run); }
3165
+ async roadmapDecomposePart(by: PeerId, rawId: unknown, rawPart: unknown): Promise<{ milestone: number; part: number; intake: DecomposeIntake; task: Record<string, unknown>; created: boolean }> { return this.roadmapPlan.roadmapDecomposePart(by, rawId, rawPart); }
3166
+ async roadmapDecomposePublish(by: PeerId, rawId: unknown, input: { apply?: boolean; confirm?: string } = {}): Promise<{ milestone: number; repo: string; githubMilestone: number | null; parts: PublishPlanPart[]; calls: string[][]; skippedPrivate: number; skippedUnknown: number; fingerprint: string; applied: boolean; created: { part: number; task: number; issue: number }[]; }> { return this.roadmapPlan.roadmapDecomposePublish(by, rawId, input); }
3167
+ async roadmapAccept(by: PeerId, rawId: unknown): Promise<{ suggestion: MilestoneSuggestion; milestone: MilestoneView }> { return this.roadmapPlan.roadmapAccept(by, rawId); }
3168
+ roadmapReject(by: PeerId, rawId: unknown): MilestoneSuggestion { return this.roadmapPlan.roadmapReject(by, rawId); }
3169
+ async roadmapImportGitHub(by: PeerId, input: { repo?: unknown; apply?: unknown } = {}, run?: SdlcGh): Promise<{ repo: string; apply: boolean; partial: boolean; milestones: { number: number; title: string; milestone: number | null; action: "create" | "exists"; issues: string[]; newLinks: number }[]; created: number; linked: number; withheld: number; }> { return this.roadmapPlan.roadmapImportGitHub(by, input, run); }
4484
3170
  releaseList(by: PeerId): Record<string, unknown>[] {
4485
3171
  this.planningAuthority(by);
4486
3172
  const scopes = new Map<number, { id: number; state: Task["state"]; deps: number[] }[]>();
@@ -5927,9 +4613,16 @@ export class Tasks {
5927
4613
  private async releaseDependents(approved: Task): Promise<void> {
5928
4614
  try {
5929
4615
  // Its dependents and, as its owner's slot just freed (#655), that owner's held ready tasks: one list in priority order.
4616
+ const alreadyOwned = this.ownedReadyDependents(approved); // before the offers below give unowned dependents an owner
5930
4617
  const ready = this.d.board.list("proposed").filter(t => !t.owner && !this.waitsFor(t).length
5931
4618
  && (t.deps?.includes(approved.id) || !!approved.owner && t.reserved === approved.owner && this.isHeld(t))).sort(this.readyOrder);
5932
4619
  for (const t of ready) await this.offerReady(t, t.deps?.includes(approved.id) ? `#${approved.id} approved` : "owner slot freed");
4620
+ // #1801: an owned dependent is never offered again; its owner hears once per approval that nothing is left to wait for.
4621
+ for (const t of alreadyOwned) {
4622
+ if (!t.owner || t.owner === HUB || t.owner === USER) continue;
4623
+ this.releaseNotice(`task #${t.id}: could not tell ${t.owner} it is ready`, () => this.d.bus.publish(newEnvelope(HUB,
4624
+ `ready: hub task ${approved.id} approved; nothing left to wait for\nRead hub_task_show for the task before acting.`, { to: [t.owner!], kind: "task", priority: "status", refs: { task: String(t.id) } })));
4625
+ }
5933
4626
  } catch (e) {
5934
4627
  this.releaseNotice(`task #${approved.id}: could not release dependents: ${e instanceof Error ? e.message : String(e)}`);
5935
4628
  }
@@ -6201,180 +4894,14 @@ export class Tasks {
6201
4894
  // Advice joins the planner's next delivery; it must not manufacture a turn beside a withheld backlog batch.
6202
4895
  for (const peer of this.taskPlanner(task).filter(peer => this.d.bus.isRostered(peer))) this.releaseNotice(`task #${task.id}: stall notice unavailable`, () => this.d.tell?.(peer, noteLine(HUB, "finding", text)));
6203
4896
  }
6204
- private synthesisTask(by: PeerId, id: unknown): Task {
6205
- requireLocalTaskPeer(by);
6206
- if (this.d.profile !== "research") throw new PreEffectToolRefusal("synthesis evidence is research-only; use a research profile and a visible task");
6207
- const task = this.studyParent(this.studyNumber(id, "taskId"));
6208
- if (task.profile !== "research" || by !== USER && !taskShowAllowed(by, task, this.d.roles, this.isConfiguredPlanner(by)))
6209
- throw new PreEffectToolRefusal("synthesis task unavailable; use a research task visible through hub_task_show");
6210
- return task;
6211
- }
6212
4897
 
6213
- private synthesisPrivate(task: Task, by: PeerId): boolean {
6214
- try { return !!this.d.privateTurn?.(by) || this.isPii(task) || !this.publicMetadataText(JSON.stringify(task.plan?.claims ?? [])); }
6215
- catch { return true; }
6216
- }
6217
4898
 
6218
- private synthesisPolicy(task: Task): string {
6219
- let root: string | undefined;
6220
- try { root = this.deliverablePorts(task).cwd; } catch { /* unknown is part of the fence */ }
6221
- return JSON.stringify([this.d.profile, this.d.routing().signals, this.d.piiPaths, this.d.deny, root]);
6222
- }
6223
4899
 
6224
- private synthesisRows(links: readonly EvidenceLinkV1[]) {
6225
- return links.map(link => ({ link, status: link.status === "withdrawn" ? "withdrawn" as const : "active" as const }));
6226
- }
6227
4900
 
6228
- private synthesisInventories(task: Task) {
6229
- const claims = task.plan?.claims;
6230
- if (!Array.isArray(claims) || claims.length > 50) throw new PreEffectToolRefusal("synthesis claims unavailable; refresh the task's bounded declared claim list");
6231
- return claims.map((_claim, index) => {
6232
- const identity = taskClaimIdentity(task, index + 1);
6233
- try {
6234
- const inventory = this.d.board.latestEvidenceLinks(this.d.project, task.id, identity.claimId, identity.claimRevision, 128);
6235
- let contradictionHistory: ReturnType<Board["evidenceContradictionHistory"]> = { ids: [], sources: [], members: [], complete: false };
6236
- if (inventory.complete) try { contradictionHistory = this.d.board.evidenceContradictionHistory(this.d.project, task.id, identity.claimId, identity.claimRevision, inventory.links); } catch { /* Unknown immutable history cannot erase a contradiction. */ }
6237
- if (contradictionHistory.complete && contradictionHistory.sources.some(id => { try { return !this.d.evidenceSourceMeta?.(id); } catch { return true; } })) contradictionHistory.complete = false;
6238
- return { ...identity, inventory, contradictionHistory };
6239
- }
6240
- catch { return { ...identity, inventory: { links: [] as EvidenceLinkV1[], complete: false }, contradictionHistory: { ids: [] as string[], sources: [] as string[], members: [] as string[], complete: false } }; }
6241
- });
6242
- }
6243
4901
 
6244
- private synthesisSources(links: readonly Pick<EvidenceLinkV1, "sourceId">[]): { private: boolean; key: string; bytes: number } {
6245
- const meta: unknown[] = [], seen = new Set<string>(); let bytes = 0;
6246
- for (const link of links) {
6247
- if (seen.has(link.sourceId)) continue; seen.add(link.sourceId);
6248
- const source = (() => { try { return this.d.evidenceSourceMeta?.(link.sourceId) ?? this.studySource(link.sourceId); } catch { return undefined; } })();
6249
- if (source?.private || source && !this.publicMetadataText(JSON.stringify(source))) return { private: true, key: "", bytes: 0 };
6250
- meta.push([link.sourceId, source]);
6251
- if (source && "bytes" in source && typeof source.bytes === "number") bytes += source.bytes;
6252
- }
6253
- return { private: false, key: createHash("sha256").update(JSON.stringify(meta)).digest("hex"), bytes };
6254
- }
6255
4902
 
6256
- /** Explicit authoring metadata only: no claim text, source identity, passage, origin or path. */
6257
- async synthesisEvidence(by: PeerId, input: unknown) {
6258
- const fields = this.studyFields(input, ["taskId"]), check = this.requestCheck(by, () => this.studyHold());
6259
- return this.studyWrite(async () => {
6260
- check(); const revision = this.d.board.statusRevision(), task = this.synthesisTask(by, fields.taskId);
6261
- if (this.synthesisPrivate(task, by)) return { taskId: task.id, status: "private" as const };
6262
- const claims = this.synthesisInventories(task), links = claims.flatMap(claim => [...claim.inventory.links, ...claim.contradictionHistory.sources.map(sourceId => ({ sourceId }))]);
6263
- if (this.synthesisSources(links).private) return { taskId: task.id, status: "private" as const };
6264
- const delivered = latestDeliverables(task.history) ?? [];
6265
- const artifacts = delivered.filter(record => !record.private && record.path && !this.experimentOutputPrivate(task, record.path))
6266
- .map(({ id, sha256, format }) => ({ id, sha256, format }));
6267
- check();
6268
- if (this.d.board.statusRevision() !== revision) return { taskId: task.id, status: "unavailable" as const, cause: "inventory_changed" };
6269
- return { taskId: task.id, taskCreated: task.created, status: "available" as const, scope: "declared_inventory" as const,
6270
- deliverables: artifacts, claims: claims.map(claim => {
6271
- const binding = inventoryBinding(this.synthesisRows(claim.inventory.links), claim.inventory.complete, claim.contradictionHistory);
6272
- return { claimId: claim.claimId, claimRevision: claim.claimRevision, complete: claim.inventory.complete && claim.contradictionHistory.complete,
6273
- ...(binding ? { inventory: binding } : {}), evidence: this.synthesisRows(claim.inventory.links).map(({ link, status }) => ({ id: link.id, revision: link.revision, status })) };
6274
- }) };
6275
- });
6276
- }
6277
4903
 
6278
- /** Deterministic, explicit and offline: no caller-supplied current state and no semantic/model judge. */
6279
- async synthesisCheck(by: PeerId, input: unknown): Promise<SynthesisReadiness | { taskId: number; status: "unavailable" | "stale"; cause: string }> {
6280
- return this.synthesisInspect(by, input);
6281
- }
6282
4904
 
6283
- private synthesisInspect(by: PeerId, input: unknown): Promise<SynthesisReadiness | { taskId: number; status: "unavailable" | "stale"; cause: string }>;
6284
- private synthesisInspect(by: PeerId, input: unknown, onSnapshot: (manifest: SynthesisManifestV1, current: SynthesisCurrent, report: SynthesisReadiness, valid: () => boolean) => Task): Promise<Task | SynthesisReadiness | { taskId: number; status: "unavailable" | "stale"; cause: string }>;
6285
- private async synthesisInspect(by: PeerId, input: unknown, onSnapshot?: (manifest: SynthesisManifestV1, current: SynthesisCurrent, report: SynthesisReadiness, valid: () => boolean) => Task): Promise<Task | SynthesisReadiness | { taskId: number; status: "unavailable" | "stale"; cause: string }> {
6286
- const fields = this.studyFields(input, ["taskId", "manifest"]), manifest = parseSynthesisManifest(fields.manifest);
6287
- if (fields.taskId !== manifest.taskId) throw new PreEffectToolRefusal("synthesis manifest names another task; refresh its task binding and retry");
6288
- const check = this.requestCheck(by, () => this.studyHold());
6289
- return this.studyWrite(async () => {
6290
- check(); const boardRevision = this.d.board.statusRevision(), task = this.synthesisTask(by, fields.taskId), taskId = task.id;
6291
- if (this.synthesisPrivate(task, by)) return { taskId, status: "private" };
6292
- const before = this.synthesisInventories(task), allLinks = before.flatMap(claim => claim.inventory.links);
6293
- const privacyLinks = [...allLinks, ...before.flatMap(claim => claim.contradictionHistory.sources.map(sourceId => ({ sourceId })))];
6294
- const sources = this.synthesisSources(privacyLinks);
6295
- if (sources.private) return { taskId, status: "private" };
6296
- const activeLinks = allLinks.filter(link => link.status !== "withdrawn");
6297
- if (this.synthesisSources(activeLinks).bytes > 64 * 1024 * 1024) return { taskId, status: "unavailable", cause: "source_input_limit" };
6298
- const delivered = latestDeliverables(task.history) ?? [], policy = this.synthesisPolicy(task);
6299
- // ponytail: any concurrent board write stales this explicit batch. A task-scoped evidence generation narrows the fence later.
6300
- const base = JSON.stringify([task.created, task.owner, task.reviewer, task.history.length, task.plan?.claims, delivered]);
6301
- const current = () => {
6302
- try { check(); const now = this.synthesisTask(by, taskId); return !this.synthesisPrivate(now, by)
6303
- && this.d.board.statusRevision() === boardRevision && this.synthesisPolicy(now) === policy
6304
- && JSON.stringify([now.created, now.owner, now.reviewer, now.history.length, now.plan?.claims, latestDeliverables(now.history) ?? []]) === base; }
6305
- catch { return false; }
6306
- };
6307
- const changed = () => {
6308
- check(); const now = this.synthesisTask(by, taskId);
6309
- if (this.synthesisPrivate(now, by) || this.synthesisSources(privacyLinks).private) return { taskId, status: "private" as const };
6310
- return { taskId, status: "stale" as const, cause: "context_changed" };
6311
- };
6312
- try { if (by !== USER) this.d.onReviewObserverInput?.(by); } catch { return { taskId, status: "unavailable", cause: "observer_unavailable" }; }
6313
- const sourceKeys = new Map<string, string | undefined>();
6314
- for (const link of activeLinks) if (!sourceKeys.has(link.sourceId)) {
6315
- let key: string | undefined;
6316
- try { const meta = this.d.evidenceSourceMeta?.(link.sourceId); key = meta && Number.isSafeInteger(meta.bytes) && meta.bytes >= 0 ? this.d.evidenceSourceSnapshotKey?.(link) : undefined; } catch { /* unavailable source cannot verify provenance */ }
6317
- sourceKeys.set(link.sourceId, key);
6318
- }
6319
- if (!current()) return changed();
6320
- const reads: { path: string; read: GuardedDeliverableRead }[] = [];
6321
- const artifact = async (reference: { id: string; sha256: string }, limit: number): Promise<SynthesisArtifactSnapshot | "private"> => {
6322
- const record = delivered.find(record => record.id === reference.id);
6323
- if (!record) return { id: reference.id, state: "missing" };
6324
- if (record.private || !record.path || this.experimentOutputPrivate(task, record.path)) return "private";
6325
- try {
6326
- const read = await readGuardedDeliverable(record.path, this.deliverablePorts(task, { failClosedOnDiscoveryLimit: true }), limit);
6327
- const text = new TextDecoder("utf-8", { fatal: true }).decode(read.data);
6328
- if (!this.publicMetadataText(text)) return "private";
6329
- reads.push({ path: record.path, read });
6330
- return { id: record.id, sha256: read.sha256, state: read.sha256 === reference.sha256 && record.sha256 === reference.sha256 ? "unchanged" : "changed", text };
6331
- } catch { return { id: record.id, state: "unknown" }; }
6332
- };
6333
- const doc = await artifact(manifest.deliverable, 256 * 1024); if (doc === "private") return { taskId, status: "private" };
6334
- if (!current()) return changed();
6335
- const bib = await artifact(manifest.bibliography, 4 * 1024 * 1024); if (bib === "private") return { taskId, status: "private" };
6336
- if (!current()) return changed();
6337
- const observed: SynthesisCurrentClaim[] = [];
6338
- for (const claim of before) {
6339
- const resolutions: NonNullable<NonNullable<SynthesisCurrent["claims"]>[number]["resolutions"]>[number][] = [];
6340
- for (const link of claim.inventory.links) {
6341
- if (!current()) return changed();
6342
- const withdrawn = link.status === "withdrawn";
6343
- if (withdrawn) { resolutions.push({ id: link.id, revision: link.revision, status: "withdrawn" }); continue; }
6344
- if (!this.d.evidenceSourceRead || !sourceKeys.get(link.sourceId)) { resolutions.push({ id: link.id, revision: link.revision, status: "unavailable" }); continue; }
6345
- let resolution: EvidenceSourceRead["resolution"];
6346
- try { resolution = (await this.d.evidenceSourceRead(by, link, current, { privacyReadOnly: true })).resolution; }
6347
- catch { resolution = { status: "unavailable", cause: "source_unavailable" }; }
6348
- if (resolution.status === "unavailable" && resolution.cause === "private") return { taskId, status: "private" };
6349
- if (!current()) return changed();
6350
- resolutions.push({ id: link.id, revision: link.revision, status: resolution.status === "resolved" ? "resolved" : resolution.status === "stale" ? "stale" : "unavailable" });
6351
- }
6352
- const entry = task.history.findLast(entry => entry.by === USER && entry.event === "claim verdict" && entry.claim?.slot === claim.slot && entry.claim.list === claim.claimRevision)?.claim;
6353
- const verdict = entry && ["supported", "unsupported", "unclear"].includes(entry.verdict) ? entry.verdict : undefined;
6354
- const synthesis = entry?.synthesis;
6355
- observed.push({ claimId: claim.claimId, claimRevision: claim.claimRevision,
6356
- inventory: { ...claim.inventory, links: this.synthesisRows(claim.inventory.links) },
6357
- contradictionHistory: claim.contradictionHistory,
6358
- resolutions, judgment: { present: !!verdict, ...(verdict ? { verdict } : {}), ...(verdict && synthesis ? synthesis : {}) } });
6359
- }
6360
- const finalCurrent = () => {
6361
- try {
6362
- if (!current() || this.synthesisSources(privacyLinks).key !== sources.key) return false;
6363
- const fencedSources = new Set<string>();
6364
- for (const link of activeLinks) if (!fencedSources.has(link.sourceId)) {
6365
- fencedSources.add(link.sourceId);
6366
- if (sourceKeys.get(link.sourceId) && this.d.evidenceSourceSnapshotKey?.(link) !== sourceKeys.get(link.sourceId)) return false;
6367
- }
6368
- if (reads.some(value => !guardedDeliverableCurrent(value.path, this.deliverablePorts(task, { failClosedOnDiscoveryLimit: true }), value.read))) return false;
6369
- return this.synthesisSources(privacyLinks).key === sources.key && current();
6370
- } catch { return false; }
6371
- };
6372
- if (!finalCurrent()) return changed();
6373
- const snapshot: SynthesisCurrent = { taskId, taskCreated: task.created, deliverable: doc, bibliography: bib, claims: observed };
6374
- const report = checkSynthesis(manifest, snapshot);
6375
- return onSnapshot ? onSnapshot(manifest, snapshot, report, finalCurrent) : report;
6376
- });
6377
- }
6378
4905
 
6379
4906
  /** Resolve declared provenance afresh, without manufacturing a #901 judgment or synthesis readiness. */
6380
4907
  async evidenceRead(by: PeerId, input: unknown): Promise<EvidenceReadResult> {
@@ -6463,668 +4990,42 @@ export class Tasks {
6463
4990
  return { state: "known", group: `origin:${createHash("sha256").update(JSON.stringify([...group].sort())).digest("hex").slice(0, 32)}`, groups: groups.length };
6464
4991
  } catch { return unknown; }
6465
4992
  }
4993
+ private lineageMetadata(...args: Parameters<ExperimentDomain["lineageMetadata"]>): ReturnType<ExperimentDomain["lineageMetadata"]> { return this.experiment.lineageMetadata(...args); }
6466
4994
 
6467
- /** Pure read screen: never resolve an address or a path to decide whether to publish it. */
6468
- private lineageMetadata(text: string): boolean {
6469
- try {
6470
- if (!this.nameable(text) || looksSecret(text)) return false;
6471
- const policy = [...this.d.piiPaths ?? [], ...this.d.deny ?? []];
6472
- if (!policy.length) return true;
6473
- let parsed: unknown;
6474
- try { parsed = JSON.parse(text); } catch { return false; } // direct stored paths have no alias proof
6475
- const strings = (value: unknown): string[] => typeof value === "string" ? [value] : Array.isArray(value) ? value.flatMap(strings) : value && typeof value === "object" ? Object.values(value).flatMap(strings) : [];
6476
- // ponytail: a path-shaped opaque field has no cached alias proof. Withhold it until owner-maintained
6477
- // public metadata can prove it without filesystem discovery on this read path.
6478
- return strings(parsed).every(value => !/[\\/]|\.[a-zA-Z]/.test(value) && !matchesPolicyLexically(this.d.cwd, value, policy));
6479
- } catch { return false; }
6480
- }
4995
+ private lineageVisible(...args: Parameters<ExperimentDomain["lineageVisible"]>): ReturnType<ExperimentDomain["lineageVisible"]> { return this.experiment.lineageVisible(...args); }
6481
4996
 
6482
- private lineageVisible(by: PeerId, task: Task): boolean {
6483
- try {
6484
- if (this.d.privateTurn?.(by) || this.d.reviewObserverInput?.(by) || this.reviewTaskPrivate(task)) return false;
6485
- if (this.d.piiPaths?.length && ((task.refs.paths?.length ?? 0) || (task.plan?.paths?.length ?? 0) || (task.plan?.sections?.length ?? 0))) return false;
6486
- if (this.repositories.cachedScope(task.refs)?.key !== this.repositories.project.key) return false;
6487
- return by === USER || this.d.bus.isRostered(by) && taskShowAllowed(by, task, this.d.roles, this.isConfiguredPlanner(by));
6488
- } catch { return false; }
6489
- }
4997
+ private lineagePorts(...args: Parameters<ExperimentDomain["lineagePorts"]>): ReturnType<ExperimentDomain["lineagePorts"]> { return this.experiment.lineagePorts(...args); }
6490
4998
 
6491
- private lineagePorts(by: PeerId): ExecutionLineageOwnerPorts | undefined {
6492
- const binding = this.d.executionLineage;
6493
- if (!binding) return undefined;
6494
- // Agent-wide roles do not grant diagnostic authority over a hidden or staged source.
6495
- const diagnostics = by === USER;
6496
- // ponytail: raw50 event pages cannot prove current field privacy after policy narrowing.
6497
- // Refuse by policy alone until a privacy-aware page source supplies a complete public projection.
6498
- let eventProjectionSupported = false;
6499
- 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 */ }
6500
- return { project: this.d.project, projectKey: binding.projectKey, cursorKey: binding.cursorKey,
6501
- scope: createHash("sha256").update(by).digest("hex"), diagnostics, eventProjectionSupported,
6502
- task: id => this.d.board.get(id), visible: task => this.lineageVisible(by, task), metadata: text => this.lineageMetadata(text),
6503
- links: task => this.d.board.executionReferences(binding.projectKey, task.id, task.created),
6504
- delivery: binding.readDelivery,
6505
- attempt: id => this.d.board.experimentAttempt(id), events: (id, after, limit) => this.d.board.experimentEvents(id, after, limit),
6506
- receipts: id => this.d.board.runnerReceipts(id), attemptStatus: id => this.d.board.experimentAttemptStatus(id) };
6507
- }
6508
-
6509
- /** Read one explicit owner neighborhood; unauthorized, private and missing roots are indistinguishable. */
6510
- executionLineage(by: PeerId, input: unknown): LineageResult {
6511
- if (!executionLinkActor(by) || by === HUB || by === "admin") return { state: "unavailable" };
6512
- try {
6513
- const check = this.requestCheck(by);
6514
- if (this.d.privateTurn?.(by) || this.d.reviewObserverInput?.(by)) return { state: "unavailable" };
6515
- const ports = this.lineagePorts(by);
6516
- if (!ports) return { state: "unavailable" };
6517
- let query;
6518
- try { query = parseOwnerLineageQuery(input); }
6519
- catch { return ports.diagnostics ? { state: "unavailable", reason: "invalid" } : { state: "unavailable" }; }
6520
- const snapshot = executionOwnerSnapshot(ports, query);
6521
- check();
6522
- if (this.d.privateTurn?.(by) || this.d.reviewObserverInput?.(by)) return { state: "unavailable" };
6523
- if (snapshot.task) {
6524
- const current = this.d.board.get(snapshot.task.id);
6525
- if (!current || current.created !== snapshot.task.created || current.history.length !== snapshot.task.history.length || !this.lineageVisible(by, current)) return { state: "unavailable" };
6526
- }
6527
- return readExecutionLineage(snapshot.source, snapshot.query);
6528
- } catch { return { state: "unavailable" }; }
6529
- }
4999
+ executionLineage(...args: Parameters<ExperimentDomain["executionLineage"]>): ReturnType<ExperimentDomain["executionLineage"]> { return this.experiment.executionLineage(...args); }
6530
5000
 
6531
- private guidanceProbeTimer(): NonNullable<NonNullable<TasksDeps["guidanceProbes"]>["timer"]> {
6532
- return this.d.guidanceProbes?.timer ?? {
6533
- set: (callback, ms) => { const timer = setTimeout(callback, ms); timer.unref?.(); return timer; },
6534
- clear: handle => clearTimeout(handle as ReturnType<typeof setTimeout>),
6535
- };
6536
- }
6537
- /** Owned in-process work only, not persisted held lanes or a quiescence assertion. */
6538
- guidanceProbesPending = (): number => this.guidanceProbeAdmissions + this.guidanceProbeActive.size;
6539
- async stopGuidanceProbes(): Promise<void> {
6540
- this.guidanceProbeStopping = true;
6541
- const active = [...this.guidanceProbeActive.values()];
6542
- for (const entry of active) this.guidanceProbeAbort(entry, "observation", true);
6543
- if (this.guidanceProbesPending() === 0) return;
6544
- await this.guidanceProbeDrain(active);
6545
- if (this.guidanceProbesPending() !== 0) throw new Error("guidance probe admission drain is unconfirmed; retain project storage and explicitly retry after owned callbacks settle");
6546
- }
6547
- private async guidanceProbeDrain(active: GuidanceProbeRuntime[]): Promise<void> {
6548
- const settled = Promise.allSettled(active.flatMap(entry => [entry.promise, entry.stopPromise].filter((value): value is Promise<ProbePublicReceipt> | Promise<void> => value !== undefined)));
6549
- let timeout: { handle: unknown } | undefined;
6550
- try {
6551
- await Promise.race([settled, new Promise<never>((_resolve, reject) => {
6552
- timeout = { handle: this.guidanceProbeTimer().set(() => reject(new Error("guidance probe stop is unconfirmed after the owned drain bound; retain the held lane and explicitly drain after its fixture callbacks settle")), GUIDANCE_PROBE_STOP_TIMEOUT_MS) };
6553
- })]);
6554
- if (active.some(entry => this.guidanceProbeActive.get(entry.id) === entry)) throw new Error("guidance probe stop evidence is unknown; retain owned handles and explicitly retry the drain after matching fixture stop evidence");
6555
- } finally { if (timeout !== undefined) this.guidanceProbeTimer().clear(timeout.handle); }
6556
- }
6557
- private guidanceProbeClearWatch(entry: GuidanceProbeRuntime): void {
6558
- if (entry.watch !== undefined) { this.guidanceProbeTimer().clear(entry.watch.handle); entry.watch = undefined; }
6559
- }
6560
- private guidanceProbeRetire(entry: GuidanceProbeRuntime): void {
6561
- if (this.guidanceProbeActive.get(entry.id) !== entry || !entry.launchSettled || entry.stopRequested && (!entry.stopSettled || !entry.stopKnown)) return;
6562
- this.guidanceProbeClearWatch(entry); this.guidanceProbeActive.delete(entry.id);
6563
- }
6564
- private guidanceProbeAbort(entry: GuidanceProbeRuntime, reason: "elapsed" | "observation", explicitStop = false): void {
6565
- if (this.guidanceProbeActive.get(entry.id) !== entry) return;
6566
- this.guidanceProbeClearWatch(entry);
6567
- if (entry.reservation) {
6568
- try { this.d.guidanceProbes!.store.latchHold(entry.reservation, reason); }
6569
- catch { entry.failure = new Error("guidance probe hold bookkeeping is unconfirmed; inspect retained state before any further work"); }
6570
- }
6571
- entry.controller.abort();
6572
- if (!entry.launched || !entry.reservation) { this.guidanceProbeRetire(entry); return; }
6573
- if (entry.stopRequested && (!entry.stopSettled || entry.stopKnown || !explicitStop)) return;
6574
- const reservation = entry.reservation, ports = entry.ports;
6575
- entry.stopRequested = true; entry.stopSettled = false; entry.stopKnown = false;
6576
- entry.stopPromise = (async () => {
6577
- try {
6578
- const result = await ports.stop({ reservation }, new AbortController().signal);
6579
- entry.stopKnown = result?.stopped === "known_fixture" && guidanceProbeCanonical(result.reservation) === guidanceProbeCanonical(reservation);
6580
- if (!entry.stopKnown) entry.failure = new Error("guidance probe stop evidence is unknown; inspect the owned reservation and explicitly drain without replaying it");
6581
- } catch { entry.failure = new Error("guidance probe stop failed; retain owned handles and explicitly drain before closing project storage"); }
6582
- finally { entry.stopSettled = true; this.guidanceProbeRetire(entry); }
6583
- })();
6584
- }
6585
- private guidanceProbeWatch(entry: GuidanceProbeRuntime): void {
6586
- if (this.guidanceProbeActive.get(entry.id) !== entry || entry.controller.signal.aborted) return;
6587
- try {
6588
- entry.current();
6589
- const state = this.d.guidanceProbes!.store.read({ projectKey: this.guidanceProject(), id: entry.id });
6590
- if (!state || !entry.reservation || state.firstReservedAt === null) throw new Error("owned probe clock is unavailable");
6591
- const now = this.d.now?.() ?? Date.now(), elapsed = now - state.firstReservedAt;
6592
- if (!probeInteger(elapsed) || elapsed < state.counters.elapsedHighWaterMs || state.admissionHold !== "none") { this.guidanceProbeAbort(entry, "elapsed"); return; }
6593
- const live = state.sessions.find(session => session.slotId === entry.reservation!.slotId)?.live;
6594
- const remaining = Math.min(state.registration.manifest.limits.elapsedMs - elapsed,
6595
- live === undefined ? Infinity : GUIDANCE_PROBE_LIVE_LIMITS.elapsedMs - (now - live.reservedAt));
6596
- if (remaining <= 0) { this.guidanceProbeAbort(entry, "elapsed"); return; }
6597
- entry.watch = { handle: this.guidanceProbeTimer().set(() => {
6598
- if (this.guidanceProbeActive.get(entry.id) !== entry || entry.controller.signal.aborted) return;
6599
- entry.watch = undefined; this.guidanceProbeWatch(entry);
6600
- }, Math.min(GUIDANCE_PROBE_FENCE_INTERVAL_MS, remaining)) };
6601
- } catch { this.guidanceProbeAbort(entry, "observation"); }
6602
- }
6603
- private guidanceProbeProjection(state: ProbeStoredState, already = false): ProbePublicStatus {
6604
- const holds = state.admissionHold !== "none" || state.counters.usageUnknown;
6605
- const authoring: ProbePublicStatus["authoring"] = state.sessions.some(item => item.child?.authoring === "uncontrolled") ? "uncontrolled"
6606
- : state.sessions.some(item => item.child?.authoring === "admitted_fixture") ? "admitted_fixture" : "unknown";
6607
- const launchedSessions = state.sessions.filter(item => item.coverage.launchExposed);
6608
- const verifiedCoverage = launchedSessions.length > 0 && launchedSessions.every(item => item.coverage.coverageVerified)
6609
- && state.sessions.filter(item => item.state === "closed_fixture").every(item => item.coverage.coverageVerified)
6610
- && state.sessions.every(item => item.state !== "failed_known" || item.coverage.preLaunchFailure || item.coverage.coverageVerified);
6611
- const evidence: ProbePublicReceipt["evidence"] = state.counters.workerAttempts + state.counters.editorAttempts === 0 ? "declaration"
6612
- : holds || !verifiedCoverage || state.sessions.some(item => ["reserved", "running", "unknown_held"].includes(item.state)) ? "unknown" : launchedSessions.every(item => item.live !== undefined) ? "live" : "fixture";
6613
- return { ...state.receipt, already, taskId: state.registration.manifest.task.id,
6614
- experimentId: this.guidancePublicField(state.registration.manifest.experimentId), evidence,
6615
- counters: { ...state.counters }, cancelRequested: state.cancelRequested, notNeeded: state.notNeeded, authoring,
6616
- comparable: state.receipt.state === "closed_fixture" && !holds && verifiedCoverage && authoring === "admitted_fixture" };
6617
- }
6618
- private guidanceProbeReceipt(state: ProbeStoredState, already = false): ProbePublicReceipt {
6619
- const { counters: _counters, cancelRequested: _cancelRequested, notNeeded: _notNeeded, comparable: _comparable, authoring: _authoring, ...result } = this.guidanceProbeProjection(state, already);
6620
- return result;
6621
- }
6622
- private guidanceProbeState(by: PeerId, id: string, check: () => void): ProbeStoredState {
6623
- check();
6624
- if (!probeSha256(id)) throw new PreEffectToolRefusal("guidance probe id is invalid; use the exact registered content id");
6625
- if (!this.d.guidanceProbes) throw new PreEffectToolRefusal("guidance probe storage is unavailable; restart a supporting hub before retrying");
6626
- const state = this.d.guidanceProbes.store.read({ projectKey: this.guidanceProject(), id });
6627
- if (!state) throw new PreEffectToolRefusal("guidance probe is unavailable; inspect a registered declaration in this project");
6628
- this.guidanceProbeTask(by, state.registration.manifest.task, false); check(); return state;
6629
- }
6630
- private guidanceProbeHost(by: PeerId, manifest: GuidanceProbeManifestV1, request: ReturnType<Tasks["guidanceProbeRequest"]>, history?: ProbeHostBinding): ProbeHostBinding {
6631
- request.check();
6632
- const projectKey = this.guidanceProject();
6633
- if (projectKey !== manifest.projectKey) throw new PreEffectToolRefusal("guidance probe project changed; register within the current project namespace");
6634
- const task = this.guidanceProbeTask(by, manifest.task, history === undefined);
6635
- const binding = { projectKey, actor: by, task: { id: task.id, created: task.created, flowRevision: task.history.length },
6636
- sessionGeneration: request.generation, nativeSession: request.nativeSession, requestConnectionId: request.requestConnectionId };
6637
- // A narrowing cancellation carries its original baseline as history, never a new applicability grant.
6638
- if (history) return { ...binding, role: history.role, baselineGuidance: history.baselineGuidance };
6639
- const role = this.guidanceRole(task);
6640
- return { ...binding, role: { id: role.id, layer: role.layer, baselineSha256: role.hash }, baselineGuidance: taskRoleText(role) };
6641
- }
6642
- private guidanceProbeSnapshotClear(state: ProbeStoredState["registration"]): boolean {
6643
- return Object.entries(state.snapshots).every(([field, value]) => {
6644
- const text = field === "dataPolicy" ? guidanceProbeCanonical(value) : value as string;
6645
- return this.nameable(text) && !looksSecret(text);
6646
- });
6647
- }
6648
- private guidanceProbeRenderedClear(text: string): boolean {
6649
- if (!this.nameable(text) || looksSecret(text)) return false;
6650
- const policy = [...this.d.deny ?? [], ...this.d.piiPaths ?? []];
6651
- if ([...pathCandidates(text)].some(candidate => matchesPolicyLexically(this.d.cwd, candidate, policy))) return false;
6652
- return !policy.some(entry => {
6653
- const literal = entry.replace(/^\.\//, "").split(/[*?[\]{}]/)[0]!.replace(/\/+$/, "");
6654
- return /[/\s]/.test(literal) && text.includes(literal);
6655
- });
6656
- }
6657
- async guidanceProbeRegister(by: PeerId, value: unknown): Promise<ProbePublicReceipt> {
6658
- const request = this.guidanceProbeRequest(by), registration = parseGuidanceProbeRegistration(value);
6659
- if (!registration) throw new PreEffectToolRefusal("guidance probe declaration is invalid or oversized; use the closed V1 envelope without trimming its snapshots");
6660
- const binding = this.guidanceProbeHost(by, registration.manifest, request);
6661
- if (!this.guidanceProbeSnapshotClear(registration)) throw new PreEffectToolRefusal("guidance probe inputs are private; register public task-local inputs in a current public session");
6662
- this.guidanceProbeAdmissions++;
6663
- let wrote = false;
6664
- try {
6665
- const saved = this.d.guidanceProbes!.store.register(registration, binding, () => {
6666
- if (!this.guidanceProbeSnapshotClear(registration)) throw new PreEffectToolRefusal("guidance probe input policy changed; inspect its current public scope before retrying");
6667
- return this.guidanceProbeHost(by, registration.manifest, request);
6668
- });
6669
- wrote = !saved.already;
6670
- const state = this.guidanceProbeState(by, saved.id, request.check);
6671
- return this.guidanceProbeReceipt(state, saved.already);
6672
- } catch (error) {
6673
- if (!wrote && (error instanceof PreEffectToolRefusal || error instanceof GuidanceProbeError && error.reason !== "storage")) throw error;
6674
- throw new Error("guidance probe registration is unconfirmed; inspect retained state before explicitly retrying");
6675
- }
6676
- finally { this.guidanceProbeAdmissions--; }
6677
- }
6678
- async guidanceProbeShow(by: PeerId, id: string): Promise<ProbePublicStatus> {
6679
- const request = this.guidanceProbeRequest(by), state = this.guidanceProbeState(by, id, request.check);
6680
- request.check();
6681
- const status = this.guidanceProbeProjection(state);
6682
- // T3 (#1226): the sealed receipts can only make the verdict stricter, never grant one the older expression refused. The reasons and the denominator stay in
6683
- // the store's private status; public show keeps just this flag. A store that cannot be read is not comparable.
6684
- if (!status.comparable) return status;
6685
- let sealedComparable = false;
6686
- try { sealedComparable = this.d.guidanceProbes!.store.outcome({ projectKey: this.guidanceProject(), id: state.receipt.id })?.comparability.comparable === true; } catch { /* fail closed */ }
6687
- return sealedComparable ? status : { ...status, comparable: false };
6688
- }
6689
- /**
6690
- * T4 (#1226): the producer receipt reader and export. The same person/conductor, session and task fences as `guidanceProbeShow`, and read-only: it launches,
6691
- * reserves, writes and prunes nothing. It carries the status, the outcome denominator and the sealed receipts, each re-verified against its own digest by the
6692
- * Store, so a tampered row refuses the whole read instead of being skipped. Output names are model-written, so each receipt passes the same screen as any
6693
- * other public field; one that fails is replaced by its digest alone and the slot says `withheld`. A retained directory is a state, never a path.
6694
- */
6695
- async guidanceProbeReceipts(by: PeerId, id: string): Promise<ProbeReceiptExport> {
6696
- const request = this.guidanceProbeRequest(by), state = this.guidanceProbeState(by, id, request.check);
6697
- request.check();
6698
- const store = this.d.guidanceProbes!.store, key = { projectKey: this.guidanceProject(), id: state.receipt.id };
6699
- const status = await this.guidanceProbeShow(by, id);
6700
- let receipts: ProbeReceiptV1[], outcome: ReturnType<GuidanceProbeStore["outcome"]>, retention: Map<string, ProbeRetentionState>;
6701
- try { receipts = store.receipts(key); outcome = store.outcome(key); retention = store.retentionStates(key); }
6702
- catch (error) { if (error instanceof GuidanceProbeError) throw error; throw new GuidanceProbeError("storage"); }
6703
- if (!outcome) throw new GuidanceProbeError("storage");
6704
- request.check();
6705
- const bySlot = new Map(receipts.map(item => [item.slotId, item]));
6706
- const slots: ProbeExportSlot[] = state.registration.manifest.slots.map((slot, index) => {
6707
- const session = state.sessions[index]!, receipt = bySlot.get(slot.id);
6708
- const shown = receipt !== undefined && this.guidanceProbeReceiptClear(receipt);
6709
- return { slotId: slot.id, stage: slot.stage, role: slot.role, arm: slot.arm, state: session.state, receipt: shown ? receipt : null,
6710
- receiptDigest: receipt?.digest ?? null, withheld: receipt !== undefined && !shown, retention: retention.get(slot.id) ?? "none" };
6711
- });
6712
- // The sealed verdict can only make the public one stricter, exactly as in `show`: a status that already refused stays refused.
6713
- const comparable = status.comparable && outcome.comparability.comparable;
6714
- const result: ProbeReceiptExport = { v: 1, status: { ...status, comparable }, comparable, reasons: outcome.comparability.reasons, counts: outcome.counts, slots };
6715
- // What leaves this process is what the consumer's parser will accept: a result that does not round-trip is a storage fault, never a partial answer.
6716
- const checked = parseGuidanceProbeReceiptExport(JSON.parse(JSON.stringify(result)));
6717
- if (!checked) throw new GuidanceProbeError("storage");
6718
- return checked;
6719
- }
6720
- /** Every free-text name a receipt carries (output paths, exclusions, the served model) must pass the public-field screen; the digest alone is kept otherwise. */
6721
- private guidanceProbeReceiptClear(receipt: ProbeReceiptV1): boolean {
6722
- const names = [receipt.experimentId, receipt.slotId, receipt.servedModel ?? "", ...receipt.output.entries.map(item => item.relative), ...receipt.output.excluded.map(item => item.relative)];
6723
- return names.every(text => text === "" || this.guidanceFieldAllowed(text));
6724
- }
6725
- async guidanceProbeStart(by: PeerId, id: string, revision: number, variantId?: string): Promise<ProbePublicReceipt> {
6726
- const request = this.guidanceProbeRequest(by), state = this.guidanceProbeState(by, id, request.check);
6727
- const host = this.guidanceProbeHost(by, state.registration.manifest, request);
6728
- if (!probeInteger(revision) || variantId !== undefined && !probeSha256(variantId))
6729
- throw new PreEffectToolRefusal("guidance probe start selector is invalid; use its current CAS revision and exact G1 id");
6730
- const dependency = this.d.guidanceProbes!;
6731
- // Match a host-configured content ID, never a mode requested by the caller or carried by imported evidence.
6732
- const live = dependency.live?.id === id ? dependency.live.adapter : undefined;
6733
- if (live && (by === USER || request.nativeSession === null))
6734
- // refusal:by-design human-authority: live starts require an authenticated conductor session
6735
- throw new PreEffectToolRefusal("live guidance probes require the current authenticated conductor native session");
6736
- if (live && !isLiveGuidanceProbeManifest(state.registration.manifest))
6737
- // refusal:by-design operator-knowledge: the operator must supply the preregistered bounded declaration
6738
- throw new PreEffectToolRefusal("live guidance probe requires a bounded baseline and candidate declaration");
6739
- const selectedPorts = live?.ports ?? dependency.fakePorts;
6740
- // refusal:by-design human-authority: only the host operator can select a live registration
6741
- if (!selectedPorts) throw new PreEffectToolRefusal("guidance probe runner is unavailable in production T1 for this registration");
6742
- const key = { projectKey: host.projectKey, id }, original = dependency.store.startSelector(key, revision);
6743
- if (original && (original.actor !== by || original.sessionGeneration !== host.sessionGeneration || original.nativeSession !== host.nativeSession
6744
- || original.requestConnectionId !== host.requestConnectionId)) throw new PreEffectToolRefusal("guidance probe original start belongs to another request session; inspect its retained id without replaying it");
6745
- const slot = original ? state.registration.manifest.slots.find(item => item.id === original.slotId)
6746
- : state.registration.manifest.slots.find(item => state.sessions.find(session => session.slotId === item.id)?.state === "planned");
6747
- if (!slot) throw new PreEffectToolRefusal("guidance probe has no eligible slot; inspect its retained terminal or held state");
6748
- if (original && original.variantId !== (variantId ?? null)) throw new PreEffectToolRefusal("guidance probe original selector differs; inspect its original G1 id without rebinding the start");
6749
- const needsVariant = slot.role === "worker" && slot.arm !== "baseline";
6750
- if (needsVariant !== (variantId !== undefined)) throw new PreEffectToolRefusal("guidance probe next worker needs its existing G1 id only; use --variant for the next non-baseline worker");
6751
- const current = (): ProbeAdmissionRecheck => {
6752
- const fresh = this.guidanceProbeHost(by, state.registration.manifest, request);
6753
- if (!this.guidanceProbeSnapshotClear(state.registration)) throw new PreEffectToolRefusal("guidance probe input privacy changed; retain its declaration and use current public inputs");
6754
- return { host: fresh, ...(variantId === undefined ? {} : { child: this.guidanceProbeVariantBinding(by, this.guidanceProbeTask(by, state.registration.manifest.task, true), variantId) }) };
6755
- };
6756
- const prepared = current();
6757
- const active = this.guidanceProbeActive.get(id);
6758
- if (active) {
6759
- if (active.requestedRevision !== revision || active.variantId !== variantId)
6760
- throw new PreEffectToolRefusal("another owned probe attempt is still settling; inspect its state before explicitly starting the next stage");
6761
- const captured = active.current().host;
6762
- if (captured.actor !== host.actor || captured.sessionGeneration !== host.sessionGeneration || captured.nativeSession !== host.nativeSession
6763
- || captured.requestConnectionId !== host.requestConnectionId)
6764
- throw new PreEffectToolRefusal("guidance probe active start belongs to another request session; inspect its retained id without replaying it");
6765
- // Frame preparation has not granted a reservation. A duplicate is only a read of truthful current metadata.
6766
- if (!active.reservation) return this.guidanceProbeReceipt(this.guidanceProbeState(by, id, request.check), true);
6767
- const replay = dependency.store.reserveSession({ key, expectedRevision: revision, ...prepared, ...(live ? { mode: "live" as const } : {}), now: this.d.now?.() ?? Date.now() }, current);
6768
- if (replay.kind !== "existing") throw new Error("guidance probe start is unconfirmed; inspect retained state before any further work");
6769
- return this.guidanceProbeReceipt(this.guidanceProbeState(by, id, request.check), true);
6770
- }
6771
- const entry: GuidanceProbeRuntime = { id, by, requestedRevision: revision, ...(variantId === undefined ? {} : { variantId }), controller: new AbortController(), current, ports: selectedPorts, launched: false, launchSettled: false,
6772
- stopRequested: false, stopSettled: false, stopKnown: false };
6773
- this.guidanceProbeActive.set(id, entry);
6774
- const ports: GuidanceProbeFakePorts = {
6775
- launch: async (input, effects, signal) => {
6776
- entry.reservation = input.reservation;
6777
- this.guidanceProbeWatch(entry);
6778
- if (signal.aborted) throw new Error("owned probe was aborted before launch");
6779
- entry.launched = true;
6780
- return selectedPorts.launch(input, effects, signal);
6781
- },
6782
- stop: (input, signal) => selectedPorts.stop(input, signal),
6783
- ...(selectedPorts.discardRetained ? { discardRetained: record => selectedPorts.discardRetained!(record) } : {}),
6784
- };
6785
- let reserved = false, returned = false;
6786
- const runner = new GuidanceProbeFixtureHost(dependency.store, { ports, ...(live ? { mode: "live" as const } : {}), revalidate: current, now: () => this.d.now?.() ?? Date.now(),
6787
- prepareWorkerFrame: live?.prepareWorkerFrame ?? dependency.prepareWorkerFrame, prepareEditorFrame: dependency.prepareEditorFrame, onReserved: () => { reserved = true; } });
6788
- entry.promise = (async () => {
6789
- try {
6790
- const saved = await runner.start({ key, expectedRevision: revision, ...prepared, ...(live ? { mode: "live" as const } : {}), now: this.d.now?.() ?? Date.now() }, entry.controller.signal);
6791
- returned = true;
6792
- if (saved.state === "unknown_held" && entry.launched) {
6793
- this.guidanceProbeAbort(entry, "observation", true);
6794
- if (!entry.stopPromise) throw new Error("owned probe stop was not recorded; retain the held lane and explicitly inspect its outcome");
6795
- await entry.stopPromise;
6796
- }
6797
- request.check();
6798
- if (entry.failure) throw entry.failure;
6799
- return this.guidanceProbeReceipt(this.guidanceProbeState(by, id, request.check), saved.already);
6800
- } catch (error) {
6801
- this.guidanceProbeAbort(entry, "observation");
6802
- if (!reserved && !returned && (error instanceof PreEffectToolRefusal || error instanceof GuidanceProbeError && error.reason !== "storage")) throw error;
6803
- throw new Error("guidance probe attempt outcome is unconfirmed; inspect its retained id without replaying work");
6804
- } finally { entry.launchSettled = true; this.guidanceProbeClearWatch(entry); this.guidanceProbeRetire(entry); }
6805
- })();
6806
- return entry.promise;
6807
- }
6808
- async guidanceProbeCancel(by: PeerId, id: string, revision: number): Promise<ProbePublicReceipt> {
6809
- const request = this.guidanceProbeRequest(by), state = this.guidanceProbeState(by, id, request.check);
6810
- if (!probeInteger(revision)) throw new PreEffectToolRefusal("guidance probe cancellation revision is invalid; inspect its current CAS revision");
6811
- const current = () => this.guidanceProbeHost(by, state.registration.manifest, request, state.binding), host = current();
6812
- try {
6813
- const saved = this.d.guidanceProbes!.store.cancelIntent({ key: { projectKey: host.projectKey, id }, expectedRevision: revision, host }, current);
6814
- const entry = this.guidanceProbeActive.get(id);
6815
- if (entry) { this.guidanceProbeAbort(entry, "observation", true); await this.guidanceProbeDrain([entry]); }
6816
- request.check();
6817
- return this.guidanceProbeReceipt(this.guidanceProbeState(by, id, request.check), saved.already);
6818
- } catch { throw new Error("guidance probe cancellation is unconfirmed; inspect its retained intent and owned drain before retrying"); }
6819
- }
6820
- private guidanceProbeRequest(by: PeerId): { check: () => void; generation: number | string; nativeSession: string | null; requestConnectionId: string } {
6821
- const request = this.guidanceRequest(by, "probe");
6822
- if (!this.personOrConductor(by)) throw new PreEffectToolRefusal("guidance probes require the person or current configured conductor; use an admitted operational session");
6823
- const session = this.d.guidanceProbes?.session?.(by);
6824
- if (!session || !probeSessionGeneration(session.generation) || !executionText(session.requestConnectionId, EXECUTION_REFERENCE_LIMITS.id)
6825
- || session.nativeSession !== null && !executionText(session.nativeSession, EXECUTION_REFERENCE_LIMITS.id))
6826
- throw new PreEffectToolRefusal("guidance probe request session is unavailable; reconnect through a current authenticated project connection");
6827
- const sessionCurrent = session.current;
6828
- const current = () => {
6829
- sessionCurrent(); request();
6830
- if (this.guidanceProbeStopping) throw new PreEffectToolRefusal("guidance probe admission is stopping; inspect retained work after the owned drain");
6831
- if (this.d.reviewOnly?.(by)) throw new PreEffectToolRefusal("guidance probes are unavailable in a review-only context; use a current public operational session");
6832
- if (by !== USER) {
6833
- try { requireConductor(by, this.d.roles); }
6834
- catch { throw new PreEffectToolRefusal("guidance probe conductor authority changed; refresh the configured role before retrying"); }
6835
- if (!this.d.bus.isRostered(by)) throw new PreEffectToolRefusal("guidance probe conductor is not currently rostered; restore current membership before retrying");
6836
- }
6837
- };
6838
- current(); return { check: current, generation: session.generation, nativeSession: session.nativeSession, requestConnectionId: session.requestConnectionId };
6839
- }
6840
- private guidanceProbeTask(by: PeerId, selected: { id: number; created: number; flowRevision: number }, admission: boolean): Task {
6841
- const task = this.guidanceTask(by, { taskId: selected.id, taskCreated: selected.created }, false);
6842
- if (admission && (task.history.length !== selected.flowRevision || !["in_progress", "changes_requested"].includes(task.state)))
6843
- throw new PreEffectToolRefusal(`guidance probe admission is stale or task state is ${task.state}; accept current work in in_progress or changes_requested and reload its revision`);
6844
- return task;
6845
- }
6846
- /** Actual probe actor only; the source owner validates/hydrates G1, never an impersonated read or separate SQL parser. */
6847
- private guidanceProbeVariantBinding(by: PeerId, task: Task, variantId: string): ProbeChildBinding {
6848
- if (by !== USER) {
6849
- try { requireConductor(by, this.d.roles); }
6850
- catch { throw new PreEffectToolRefusal("guidance probe conductor authority changed; reconnect in a current operational session"); }
6851
- if (!this.d.bus.isRostered(by)) throw new PreEffectToolRefusal("guidance probe conductor membership changed; restore current roster membership before retrying");
6852
- }
6853
- const current = this.guidanceProbeTask(by, { id: task.id, created: task.created, flowRevision: task.history.length }, true);
6854
- if (!probeSha256(variantId)) throw new PreEffectToolRefusal("guidance probe variant selector is invalid; choose an existing current G1 content id");
6855
- const project = this.guidanceProject(), role = this.guidanceRole(current);
6856
- const experiment = this.guidanceStorage("read", () => this.d.board.guidanceVariantLocation(project, current.id, current.created, variantId));
6857
- const record = experiment === undefined ? undefined : this.guidanceStorage("read", () => this.d.board.guidanceVariants(project, current.id, current.created, experiment)).find(item => item.variant.id === variantId);
6858
- if (!record || record.withdrawn || record.variant.flowRevision !== current.history.length || record.variant.baseline.roleId !== role.id
6859
- || record.variant.baseline.layer !== role.layer || record.variant.baseline.sha256 !== role.hash)
6860
- throw new PreEffectToolRefusal("guidance probe G1 is unavailable, withdrawn or stale; separately admit a current owner/person variant before retrying");
6861
- const guidance = renderGuidanceVariantV1(record.variant);
6862
- if (!this.guidanceProbeRenderedClear(guidance))
6863
- throw new PreEffectToolRefusal("guidance probe handoff text is private; use a current public G1 before retrying");
6864
- return { variantId, candidateSha256: record.variant.candidate.sha256, guidanceSha256: probeHash(guidance), guidance,
6865
- task: { id: current.id, created: current.created, flowRevision: current.history.length },
6866
- role: { id: role.id, layer: role.layer, baselineSha256: role.hash }, authoring: "uncontrolled", sourceSessionId: null };
6867
- }
6868
-
6869
- private guidanceRequest(by: PeerId, mode: "guidance" | "probe" = "guidance"): () => void {
6870
- if (!executionText(by, EXECUTION_REFERENCE_LIMITS.id) || !executionLinkActor(by) || by === HUB || by === "admin")
6871
- throw new PreEffectToolRefusal("guidance requires a current local task actor; ask the task owner or the person");
6872
- const request = this.requestCheck(by, () => this.studyHold());
6873
- const peer = by === USER ? undefined : this.d.bus.peers.get(by), generation = peer?.sessionGeneration, session = peer?.nativeSession;
6874
- const delivery = () => this.d.bus.lastDeliveredTo(by).map(item => item.id).join("\n"), delivered = mode === "guidance" ? delivery() : undefined;
6875
- const check = () => {
6876
- request();
6877
- if (this.d.privateTurn?.(by) || this.reviewObserverTurn(by))
6878
- throw new PreEffectToolRefusal("guidance is unavailable during private or review input; retry in a public owner context");
6879
- if (by !== USER && (!peer || this.d.bus.peers.get(by) !== peer || "sessionGeneration" in peer && generation === undefined
6880
- || peer.sessionGeneration !== generation || peer.nativeSession !== session || mode === "guidance" && delivery() !== delivered))
6881
- throw new PreEffectToolRefusal("guidance request session changed or is unavailable; reload the task in the current session before retrying");
6882
- };
6883
- check(); return check;
6884
- }
6885
- private guidanceTask(by: PeerId, selector: Pick<GuidanceSelector, "taskId" | "taskCreated">, write: boolean): Task {
6886
- const task = this.guidanceStorage("read", () => this.d.board.get(selector.taskId));
6887
- if (!task) throw new PreEffectToolRefusal("guidance task is unavailable; read a current task in this project before retrying");
6888
- if (task.created !== selector.taskCreated || !this.lineageVisible(by, task) || this.reviewObserverTurn(by, task.id))
6889
- throw new PreEffectToolRefusal("guidance task is unavailable; refresh the current public task and privacy context before retrying");
6890
- if (write && (isClosedTaskState(task.state) || by !== USER && (task.owner !== by || task.state === "in_review"
6891
- || !this.d.roles?.[by]?.includes(ownerRoleOfClass(task.class)) || !this.d.bus.isRostered(by))))
6892
- throw new PreEffectToolRefusal("guidance changes require the current task owner outside review, or the person, on an open task; refresh the task before retrying");
6893
- return task;
6894
- }
6895
- private guidanceProject(): string {
6896
- const key = this.d.executionLineage?.projectKey;
6897
- if (!key) throw new PreEffectToolRefusal("guidance project storage is unavailable; inspect hub status before retrying");
6898
- return key;
6899
- }
6900
- private guidanceRole(task: Task) {
6901
- let role;
6902
- try { role = taskRole(task.role, task.class, this.d.catalog ?? loadRoleCatalog(this.d.cwd)); }
6903
- catch { throw new Error("guidance catalog validation is unavailable; inspect the current task role and catalog before retrying"); }
6904
- if (!role) throw new PreEffectToolRefusal("guidance requires a current catalog task role; select a task role before proposing a variant");
6905
- return role;
6906
- }
6907
- private guidancePublic(record: GuidanceStoredRecord | { variant: GuidanceVariantV1 }): boolean {
6908
- const { evidenceRefs, ...text } = record.variant;
6909
- // Opaque evidence addresses never become filesystem/producer lookup instructions.
6910
- return this.publicMetadataText(JSON.stringify(text)) && evidenceRefs.every(reference => this.lineageMetadata(JSON.stringify(reference)));
6911
- }
6912
- /** Unknown storage/readback failures never certify a pre-effect refusal, even when SQLite rolled back. */
6913
- private guidanceStorage<T>(operation: "read" | "write", action: () => T): T {
6914
- try { return action(); }
6915
- catch { throw new Error(`guidance storage ${operation} failed; inspect the retained task experiment and its outcome before retrying`); }
6916
- }
6917
- private guidanceFence(by: PeerId, task: Task): GuidanceWriteFence {
6918
- return { by, at: this.d.now?.() ?? Date.now(), taskId: task.id, taskCreated: task.created, flowRevision: task.history.length,
6919
- owner: task.owner, state: task.state, roleId: task.role };
6920
- }
6921
- private guidanceFieldAllowed(text: string): boolean {
6922
- try { return this.nameable(text) && !looksSecret(text) && this.lineageMetadata(JSON.stringify(text)); }
6923
- catch { return false; }
6924
- }
6925
- private guidancePublicField(text: string): string { return this.guidanceFieldAllowed(text) ? text : "withheld"; }
6926
- private guidanceExperimentFor(projectKey: string, task: Task, selector: Pick<GuidanceSelector, "taskId" | "taskCreated" | "id"> & { experimentId?: string }): string | undefined {
6927
- return selector.experimentId ?? (selector.id ? this.guidanceStorage("read", () => this.d.board.guidanceVariantLocation(projectKey, task.id, task.created, selector.id!)) : undefined);
6928
- }
6929
- private guidanceCurrent(task: Task): GuidanceCurrent { return { taskId: task.id, taskCreated: task.created, flowRevision: task.history.length }; }
6930
- private guidanceReadFence(by: PeerId, selector: Pick<GuidanceSelector, "taskId" | "taskCreated">, task: Task, check: () => void): Task {
6931
- check(); const current = this.guidanceTask(by, selector, false);
6932
- if (JSON.stringify([current.created, current.history.length, current.owner, current.reviewer, current.state, current.role])
6933
- !== JSON.stringify([task.created, task.history.length, task.owner, task.reviewer, task.state, task.role])) throw new Error("guidance read binding changed");
6934
- return current;
6935
- }
6936
- private guidanceEvidence(by: PeerId, task: Task, records: readonly GuidanceStoredRecord[]): GuidancePublicRecord["evidence"][] {
6937
- const ports = this.lineagePorts(by), projectKey = this.guidanceProject();
6938
- return records.map(record => record.variant.evidenceRefs.map(reference => {
6939
- let known = false;
6940
- if (ports && reference.tool === "ahub" && reference.projectKey === projectKey) {
6941
- const snapshot = executionOwnerSnapshot(ports, { root: reference, task: { id: task.id, created: task.created } });
6942
- known = snapshot.source.health === "ready" && snapshot.source.nodes.some(node => executionReferenceKey(node.ref) === executionReferenceKey(reference));
6943
- }
6944
- return { key: executionReferenceDigest(reference), status: known ? "declared" as const : "unavailable" as const };
6945
- }));
6946
- }
6947
- private guidanceProjection(by: PeerId, task: Task, record: GuidanceStoredRecord, evidence: GuidancePublicRecord["evidence"]): GuidancePublicRecord {
6948
- return { ...guidanceVariantMetadata(record.variant), experimentId: this.guidancePublicField(record.variant.experimentId),
6949
- status: record.withdrawn ? "withdrawn" : "declared", applicable: this.guidanceApplicable(by, task, record),
6950
- rationale: { problemHypothesis: this.guidancePublicField(record.variant.rationale.problemHypothesis), expectedObservableDifference: this.guidancePublicField(record.variant.rationale.expectedObservableDifference) }, evidence };
6951
- }
6952
- private guidanceReceipt(saved: { record: GuidanceStoredRecord; already: boolean }): GuidanceWriteReceipt {
6953
- const value = saved.record.variant;
6954
- return { id: value.id, taskId: value.taskId, experimentId: this.guidancePublicField(value.experimentId), status: saved.record.withdrawn ? "withdrawn" : "declared", already: saved.already };
6955
- }
6956
- /** Immutable declarations only. Neither creation nor readback changes effective role guidance. */
6957
- async guidanceVariantCreate(by: PeerId, input: unknown): Promise<GuidanceWriteReceipt> {
6958
- const check = this.guidanceRequest(by);
6959
- let variant: Readonly<GuidanceVariantV1>;
6960
- try { variant = parseGuidanceVariantV1(input); } catch { throw new PreEffectToolRefusal("invalid guidance variant; use the closed V1 record and current task identity before retrying"); }
6961
- return this.studyWrite(async () => {
6962
- const context = () => {
6963
- check();
6964
- const task = this.guidanceTask(by, variant, true), projectKey = this.guidanceProject(), role = this.guidanceRole(task);
6965
- if (!this.guidancePublic({ variant })) throw new PreEffectToolRefusal("guidance text or evidence metadata is private; use public task-local metadata before retrying");
6966
- const experiment = this.guidanceStorage("read", () => this.d.board.guidanceExperiment(projectKey, task.id, task.created, variant.experimentId));
6967
- const records = this.guidanceStorage("read", () => this.d.board.guidanceVariants(projectKey, task.id, task.created, variant.experimentId));
6968
- try {
6969
- validateGuidanceVariantV1(variant, { projectKey, taskId: task.id, taskCreated: task.created, flowRevision: task.history.length,
6970
- experimentId: variant.experimentId, actor: by, baseline: experiment?.baseline ?? variant.baseline,
6971
- currentBaseline: roleIdentity(role), variantIds: records.map(item => item.variant.id) });
6972
- } catch (error) {
6973
- if (error instanceof GuidanceVariantError) throw new PreEffectToolRefusal("guidance variant or frozen baseline is invalid or changed; reload the task and use a new experiment for a changed baseline");
6974
- throw new Error("guidance validation is unavailable; inspect the task experiment before retrying");
6975
- }
6976
- return { task, key: JSON.stringify([task.created, task.history.length, task.owner, task.state, task.role, roleIdentity(role), experiment?.baseline ?? variant.baseline]) };
6977
- };
6978
- const before = context();
6979
- if (this.screenOn() && (await this.screenCall(JSON.stringify(variant))).label !== "clear")
6980
- throw new PreEffectToolRefusal("guidance privacy screening did not clear the proposal; retry with public metadata when local screening is available");
6981
- const current = context();
6982
- if (before.key !== current.key) throw new PreEffectToolRefusal("guidance context changed during admission; reload the task and experiment before retrying");
6983
- check();
6984
- const saved = this.guidanceStorage("write", () => this.d.board.recordGuidanceVariant(variant, this.guidanceFence(by, current.task)));
6985
- return this.guidanceReceipt(saved);
6986
- });
6987
- }
6988
- async guidanceVariantWithdraw(by: PeerId, input: unknown): Promise<GuidanceWriteReceipt> {
6989
- const check = this.guidanceRequest(by);
6990
- let selector: GuidanceSelector | GuidanceIdSelector;
6991
- try { try { selector = parseGuidanceSelector(input, true); } catch { selector = parseGuidanceIdQuery(input, true); } }
6992
- catch { throw new PreEffectToolRefusal("invalid guidance withdrawal; name a current task epoch, flow revision and existing variant selector"); }
6993
- return this.studyWrite(async () => {
6994
- check(); const task = this.guidanceTask(by, selector, true), projectKey = this.guidanceProject();
6995
- if (task.history.length !== selector.flowRevision) throw new PreEffectToolRefusal("guidance task revision changed; reload the task before withdrawing");
6996
- const experimentId = this.guidanceExperimentFor(projectKey, task, selector);
6997
- const record = experimentId === undefined ? undefined : this.guidanceStorage("read", () => this.d.board.guidanceVariants(projectKey, task.id, task.created, experimentId)).find(item => item.variant.id === selector.id);
6998
- if (!record) throw new PreEffectToolRefusal("guidance variant is unavailable; refresh the task experiment before withdrawing");
6999
- check();
7000
- const saved = this.guidanceStorage("write", () => this.d.board.withdrawGuidanceVariant(projectKey, experimentId!, selector.id!, this.guidanceFence(by, task)));
7001
- return this.guidanceReceipt(saved);
7002
- });
7003
- }
7004
- private guidanceApplicable(by: PeerId, task: Task, record: GuidanceStoredRecord): boolean {
7005
- try {
7006
- if (record.withdrawn || isClosedTaskState(task.state) || by !== USER && task.owner !== by || by !== USER && task.state === "in_review") return false;
7007
- const value = record.variant, role = this.guidanceRole(task);
7008
- return value.flowRevision === task.history.length && value.baseline.roleId === role.id && value.baseline.layer === role.layer
7009
- && value.baseline.sha256 === role.hash && (by === USER || this.d.roles?.[by]?.includes(ownerRoleOfClass(task.class)) === true);
7010
- } catch { return false; }
7011
- }
7012
- /** Historical data can be visible without being applicable. No model, external resolver or delivery runs here. */
7013
- guidanceVariantRead(by: PeerId, input: unknown): GuidanceReadResult {
7014
- try {
7015
- const check = this.guidanceRequest(by), selector = parseGuidanceSelector(input);
7016
- check(); const task = this.guidanceTask(by, selector, false), projectKey = this.guidanceProject();
7017
- const experimentId = this.guidanceExperimentFor(projectKey, task, selector);
7018
- if (experimentId === undefined) return { state: "unavailable" };
7019
- const records = this.d.board.guidanceVariants(projectKey, task.id, task.created, experimentId);
7020
- const selected = selector.id ? records.filter(item => item.variant.id === selector.id) : records;
7021
- if (!selected.length) return { state: "unavailable" };
7022
- const evidence = this.guidanceEvidence(by, task, selected), current = this.guidanceReadFence(by, selector, task, check);
7023
- if (this.guidanceExperimentFor(projectKey, current, selector) !== experimentId) return { state: "unavailable" };
7024
- const fresh = this.d.board.guidanceVariants(projectKey, current.id, current.created, experimentId);
7025
- const currentSelected = selector.id ? fresh.filter(item => item.variant.id === selector.id) : fresh;
7026
- if (JSON.stringify(selected) !== JSON.stringify(currentSelected)) return { state: "unavailable" };
7027
- const result: GuidanceReadResult = { state: "available", records: currentSelected.map((record, index) => this.guidanceProjection(by, current, record, evidence[index]!)) };
7028
- check();
7029
- return result;
7030
- } catch { return { state: "unavailable" }; }
7031
- }
7032
- /** Public T3 detail: private selection, screened editable fields, no raw snapshot readback. */
7033
- guidanceVariantDiff(by: PeerId, input: unknown): GuidanceDiffResult {
7034
- try {
7035
- const check = this.guidanceRequest(by), selector = parseGuidanceIdQuery(input);
7036
- const task = this.guidanceTask(by, selector, false), projectKey = this.guidanceProject(), experimentId = this.guidanceExperimentFor(projectKey, task, selector);
7037
- if (experimentId === undefined) return { state: "unavailable" };
7038
- const record = this.d.board.guidanceVariants(projectKey, task.id, task.created, experimentId).find(item => item.variant.id === selector.id);
7039
- if (!record) return { state: "unavailable" };
7040
- const evidence = this.guidanceEvidence(by, task, [record]), current = this.guidanceReadFence(by, selector, task, check);
7041
- if (this.guidanceExperimentFor(projectKey, current, selector) !== experimentId) return { state: "unavailable" };
7042
- const fresh = this.d.board.guidanceVariants(projectKey, current.id, current.created, experimentId).find(item => item.variant.id === selector.id);
7043
- if (!fresh || JSON.stringify(fresh) !== JSON.stringify(record)) return { state: "unavailable" };
7044
- const result = parseGuidanceDiffResult({ state: "available", current: this.guidanceCurrent(current), record: this.guidanceProjection(by, current, fresh, evidence[0]!),
7045
- sections: guidanceVariantSectionDiff(fresh.variant, text => this.guidanceFieldAllowed(text)), protectedSections: guidanceProtectedSectionNames() });
7046
- check(); return result;
7047
- } catch { return { state: "unavailable" }; }
7048
- }
7049
- /** Fixed indexed keyset pages; cursor contains only an existing public variant id and authenticated context. */
7050
- guidanceVariantList(by: PeerId, input: unknown): GuidancePageResult {
7051
- try {
7052
- const check = this.guidanceRequest(by), query = parseGuidanceListQuery(input), task = this.guidanceTask(by, query, false), projectKey = this.guidanceProject();
7053
- const key = this.d.executionLineage?.cursorKey; if (!key) return { state: "unavailable" };
7054
- const context = { ...this.guidanceCurrent(task), projectKey, actor: by };
7055
- const after = query.cursor ? guidancePageAfter(key, context, query.cursor) : "";
7056
- if (after && !this.d.board.guidanceVariantLocation(projectKey, task.id, task.created, after)) return { state: "unavailable" };
7057
- const page = this.d.board.guidanceVariantPage(projectKey, task.id, task.created, after), selected = page.slice(0, GUIDANCE_PAGE_MAX_RECORDS);
7058
- const evidence = this.guidanceEvidence(by, task, selected), current = this.guidanceReadFence(by, query, task, check);
7059
- const fresh = this.d.board.guidanceVariantPage(projectKey, current.id, current.created, after);
7060
- if (JSON.stringify(page) !== JSON.stringify(fresh)) return { state: "unavailable" };
7061
- const records: GuidancePublicRecord[] = [];
7062
- for (const [index, record] of selected.entries()) {
7063
- const candidate = this.guidanceProjection(by, current, record, evidence[index]!);
7064
- const sized = { state: "available", current: this.guidanceCurrent(current), records: [...records, candidate], truncated: true, cursor: guidancePageCursor(key, context, candidate.id) };
7065
- if (Buffer.byteLength(JSON.stringify(sized)) > GUIDANCE_REPLY_MAX_BYTES) break;
7066
- records.push(candidate);
7067
- }
7068
- const truncated = records.length < page.length;
7069
- if (truncated && !records.length) return { state: "unavailable" };
7070
- const result = parseGuidancePageResult({ state: "available", current: this.guidanceCurrent(current), records, truncated,
7071
- ...(truncated ? { cursor: guidancePageCursor(key, context, records.at(-1)!.id) } : {}) });
7072
- check(); return result;
7073
- } catch { return { state: "unavailable" }; }
7074
- }
5001
+ guidanceProbesPending = (): number => this.guidance.guidanceProbesPending();
5002
+
5003
+ stopGuidanceProbes(...args: Parameters<GuidanceDomain["stopGuidanceProbes"]>): ReturnType<GuidanceDomain["stopGuidanceProbes"]> { return this.guidance.stopGuidanceProbes(...args); }
5004
+
5005
+ guidanceProbeRegister(...args: Parameters<GuidanceDomain["guidanceProbeRegister"]>): ReturnType<GuidanceDomain["guidanceProbeRegister"]> { return this.guidance.guidanceProbeRegister(...args); }
5006
+
5007
+ guidanceProbeShow(...args: Parameters<GuidanceDomain["guidanceProbeShow"]>): ReturnType<GuidanceDomain["guidanceProbeShow"]> { return this.guidance.guidanceProbeShow(...args); }
5008
+
5009
+ guidanceProbeReceipts(...args: Parameters<GuidanceDomain["guidanceProbeReceipts"]>): ReturnType<GuidanceDomain["guidanceProbeReceipts"]> { return this.guidance.guidanceProbeReceipts(...args); }
5010
+
5011
+ guidanceProbeStart(...args: Parameters<GuidanceDomain["guidanceProbeStart"]>): ReturnType<GuidanceDomain["guidanceProbeStart"]> { return this.guidance.guidanceProbeStart(...args); }
5012
+
5013
+ guidanceProbeCancel(...args: Parameters<GuidanceDomain["guidanceProbeCancel"]>): ReturnType<GuidanceDomain["guidanceProbeCancel"]> { return this.guidance.guidanceProbeCancel(...args); }
5014
+
5015
+ guidanceVariantCreate(...args: Parameters<GuidanceDomain["guidanceVariantCreate"]>): ReturnType<GuidanceDomain["guidanceVariantCreate"]> { return this.guidance.guidanceVariantCreate(...args); }
5016
+
5017
+ guidanceVariantWithdraw(...args: Parameters<GuidanceDomain["guidanceVariantWithdraw"]>): ReturnType<GuidanceDomain["guidanceVariantWithdraw"]> { return this.guidance.guidanceVariantWithdraw(...args); }
5018
+
5019
+ guidanceVariantRead(...args: Parameters<GuidanceDomain["guidanceVariantRead"]>): ReturnType<GuidanceDomain["guidanceVariantRead"]> { return this.guidance.guidanceVariantRead(...args); }
5020
+
5021
+ guidanceVariantDiff(...args: Parameters<GuidanceDomain["guidanceVariantDiff"]>): ReturnType<GuidanceDomain["guidanceVariantDiff"]> { return this.guidance.guidanceVariantDiff(...args); }
5022
+
5023
+ guidanceVariantList(...args: Parameters<GuidanceDomain["guidanceVariantList"]>): ReturnType<GuidanceDomain["guidanceVariantList"]> { return this.guidance.guidanceVariantList(...args); }
5024
+
5025
+ guidanceVariantApplicable(...args: Parameters<GuidanceDomain["guidanceVariantApplicable"]>): ReturnType<GuidanceDomain["guidanceVariantApplicable"]> { return this.guidance.guidanceVariantApplicable(...args); }
5026
+
5027
+ linkExecutionReference(...args: Parameters<ExperimentDomain["linkExecutionReference"]>): ReturnType<ExperimentDomain["linkExecutionReference"]> { return this.experiment.linkExecutionReference(...args); }
7075
5028
 
7076
- /** Future probe admission must capture its own current runtime/turn fence; this boolean is no handoff receipt. */
7077
- guidanceVariantApplicable(by: PeerId, input: unknown): boolean {
7078
- try {
7079
- const selected = parseGuidanceIdQuery(input), read = this.guidanceVariantDiff(by, selected);
7080
- return read.state === "available" && read.record.applicable;
7081
- } catch { /* Existing explicit experiment selectors keep the T2 metadata-only path. */ }
7082
- try { if (parseGuidanceSelector(input).id === undefined) return false; } catch { return false; }
7083
- const read = this.guidanceVariantRead(by, input);
7084
- return read.state === "available" && read.records.length === 1 && read.records[0]!.applicable;
7085
- }
7086
-
7087
- /** A declaration carries no resolver, runner attestation, review approval or model-execution authority. */
7088
- async linkExecutionReference(by: PeerId, input: unknown): Promise<{ id: string; taskId: number; reference: ExecutionReferenceV1; strength: "declared"; already: boolean }> {
7089
- 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");
7090
- const check = this.requestCheck(by, () => this.studyHold() ? "execution links are held; inspect ahub status and retry after recovery or shutdown" : undefined);
7091
- let proposed: ExecutionLinkInput;
7092
- try { proposed = parseExecutionLinkInput(input); } catch { throw new PreEffectToolRefusal("execution link fields are invalid; refresh the task identity and use a bounded execution reference"); }
7093
- return this.studyWrite(async () => {
7094
- const context = () => {
7095
- check();
7096
- const ports = this.lineagePorts(by);
7097
- if (!ports) throw new PreEffectToolRefusal("execution reference storage is unavailable; inspect ahub status before retrying");
7098
- let task: Task;
7099
- try { task = this.studyParent(proposed.taskId); } catch { throw new PreEffectToolRefusal("execution link task is unavailable in this project; refresh ahub task show before retrying"); }
7100
- const role = by === task.owner ? ownerRoleOfClass(task.class) : by === task.reviewer ? "reviewer" : undefined;
7101
- 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");
7102
- 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");
7103
- 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");
7104
- const from = proposed.from ?? taskExecutionReference(ports.projectKey, task.id, task.created);
7105
- const scope = { id: task.id, created: task.created };
7106
- const origin = executionOwnerSnapshot(ports, { root: from, task: scope });
7107
- 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");
7108
- if (proposed.reference.tool === "ahub") {
7109
- const target = executionOwnerSnapshot(ports, { root: proposed.reference, task: scope });
7110
- 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");
7111
- }
7112
- const metadata = JSON.stringify([from, proposed.reference]);
7113
- if (!this.publicMetadataText(metadata)) throw new PreEffectToolRefusal("execution reference metadata is private or sensitive; use public metadata before retrying");
7114
- return { ports, task, from, metadata, key: JSON.stringify([task.created, task.history.length, task.owner, task.reviewer, task.state, origin.source.revision]) };
7115
- };
7116
- const before = context();
7117
- if (this.screenOn()) {
7118
- const result = await this.screenCall(before.metadata);
7119
- if (result.label !== "clear") throw new PreEffectToolRefusal("execution reference privacy screening did not clear the metadata; retry with public metadata when screening is available");
7120
- }
7121
- check();
7122
- const current = context();
7123
- if (current.key !== before.key) throw new PreEffectToolRefusal("execution link authority or source changed during admission; refresh the task and source references before retrying");
7124
- const saved = this.d.board.recordExecutionReference(current.ports.projectKey, { ...proposed, from: current.from }, { by, at: this.d.now?.() ?? Date.now() });
7125
- return { id: saved.record.id, taskId: saved.record.taskId, reference: saved.record.reference, strength: "declared", already: saved.already };
7126
- });
7127
- }
7128
5029
 
7129
5030
  /** T1 records declared provenance only; no locator resolution or #901 judgment is manufactured. */
7130
5031
  async evidenceRecord(by: PeerId, input: unknown): Promise<EvidenceReceipt> {
@@ -8054,7 +5955,7 @@ export class Tasks {
8054
5955
  return this.recordLifecycle(by, id, receipt, records, spec?.carry);
8055
5956
  }
8056
5957
 
8057
- recordLifecycle(by: PeerId, id: unknown, input: unknown, deliverables?: DeliverableRecord[], specCarry?: object): Task {
5958
+ recordLifecycle(by: PeerId, id: unknown, input: unknown, deliverables?: DeliverableRecord[], specCarry?: object, syncRepair = false): Task {
8058
5959
  requireLocalTaskPeer(by);
8059
5960
  const task = this.stagedSpec(by, this.need(id, false, true), specCarry);
8060
5961
  const config = this.d.sdlc?.config() ?? sdlcConfig(undefined);
@@ -8063,7 +5964,7 @@ export class Tasks {
8063
5964
  const plannerStage = !!input && typeof input === "object" && !Array.isArray(input) && Object.hasOwn(input, "stage")
8064
5965
  && Object.keys(input).every(key => ["stage", "repo", "issue"].includes(key))
8065
5966
  && (definition?.actor === "planner" || definition?.actor === "owner/planner") && this.taskPlanner(task).includes(by);
8066
- if (by !== USER && by !== task.owner && by !== task.reviewer && !plannerStage) throw new PreEffectToolRefusal("only the task owner, reviewer or console user may record lifecycle evidence; a stage planner may record stage identity");
5967
+ if (by !== USER && by !== task.owner && by !== task.reviewer && !plannerStage && !syncRepair) throw new PreEffectToolRefusal("only the task owner, reviewer or console user may record lifecycle evidence; a stage planner may record stage identity");
8067
5968
  // The spec identity is person-owned in enforce. No observation cache or restart can reopen a relink bypass.
8068
5969
  const specRelink = (task.sdlc?.repo !== undefined && next.repo !== task.sdlc.repo) || (task.sdlc?.issue !== undefined && next.issue !== task.sdlc.issue);
8069
5970
  if (config.mode === "enforce" && by !== USER && specRelink) throw new PreEffectToolRefusal("only the person may relink an established repository or issue in enforce");
@@ -8088,7 +5989,9 @@ export class Tasks {
8088
5989
  if (next.reviewedHead !== undefined && (next.reviewedHead !== task.sdlc?.reviewedHead || (suppliedHead && artifactChanged))) this.mine(task, by, "reviewer", true);
8089
5990
  const departure = task.history.findLast(h => h.by === USER && h.planDeparture)?.planDeparture;
8090
5991
  const invalidatesDeparture = !!departure && (artifactChanged || next.localHead !== task.sdlc?.localHead && next.localHead !== undefined && next.localHead !== departure.head || next.reviewedHead !== task.sdlc?.reviewedHead && next.reviewedHead !== undefined && next.reviewedHead !== departure.head);
8091
- return this.commitSpecCarry(by, specCarry, task.id, by, "lifecycle", { sdlc: next }, undefined, { ...this.planObservation({ ...task, sdlc: next }), ...(invalidatesDeparture ? { planDepartureInvalidated: true } : {}), ...(deliverables ? { deliverables } : {}) });
5992
+ const recorded = this.commitSpecCarry(by, specCarry, task.id, by, "lifecycle", { sdlc: next }, undefined, { ...this.planObservation({ ...task, sdlc: next }), ...(invalidatesDeparture ? { planDepartureInvalidated: true } : {}), ...(deliverables ? { deliverables } : {}) });
5993
+ this.watchCi(recorded);
5994
+ return recorded;
8092
5995
  }
8093
5996
 
8094
5997
  /** The board as the merge queue and the guarded merge read it (#786): ids, dependencies, privacy, receipts, findings and plans. */
@@ -8151,14 +6054,6 @@ export class Tasks {
8151
6054
  return audit ? auditSummary({ audit: audit.id, task: audit.task, ref: audit.ref, profile: audit.profile, scoped: audit.scoped, at: audit.at }, audit.units, this.d.board.auditFindings(audit.id)) : undefined;
8152
6055
  }
8153
6056
 
8154
- private surveyToolInput<T>(command: "start" | "report", field: string, rule: string, read: () => T): T {
8155
- try { return surveyInputAt(field, rule, read); } catch (error) {
8156
- const problem = surveyInputProblem(error) ?? { field, rule };
8157
- const next = command === "report" ? "fix that field and resend hub_survey_report; tool description lists shape"
8158
- : "fix that field and resend ahub sdlc survey start; ahub help sdlc survey lists shape";
8159
- throw new PreEffectToolRefusal(`${problem.field}: ${problem.rule}; ${next}`);
8160
- }
8161
- }
8162
6057
  /** #1658: an over-limit or malformed report is refused before any effect, naming the field and its limit as a survey is. */
8163
6058
  private readbackToolInput(input: unknown): SpecReadbackReport {
8164
6059
  try { return parseSpecReadbackReport(input); } catch (error) {
@@ -8166,56 +6061,6 @@ export class Tasks {
8166
6061
  throw new PreEffectToolRefusal(`${problem.field}: ${problem.rule}; fix that field and resend hub_readback_report`);
8167
6062
  }
8168
6063
  }
8169
- private surveyStarting = false;
8170
- private surveyAdmit(by: PeerId, check: () => void): void {
8171
- check();
8172
- if ((this.d.sdlc?.config().mode ?? "off") === "off") throw new PreEffectToolRefusal("advisor surveys require lifecycle advise or enforce");
8173
- if (this.d.privateTurn?.(by) || this.d.reviewOnly?.(by) || this.d.requestAuthority?.(by)) throw new PreEffectToolRefusal("advisor surveys are unavailable in private or child sessions");
8174
- const held = this.studyHold(); if (held) throw new PreEffectToolRefusal(held);
8175
- }
8176
- private surveyTask(by: PeerId, id: unknown, write = false): { task: Task; survey: StoredSurvey } {
8177
- const task = this.need(this.studyNumber(id, "survey task")), survey = this.d.board.surveyOfTask(task.id, task.created);
8178
- if (!survey || survey.repo !== this.repositories.scope({}).key || this.repositories.scope(task.refs).key !== survey.repo) throw new PreEffectToolRefusal("survey is unavailable in this project");
8179
- const owner = task.owner === by && this.d.bus.isRostered(by) && this.isConfiguredPlanner(by);
8180
- const reviewer = task.reviewer === by && this.d.bus.isRostered(by) && !!this.d.roles?.[by]?.includes("reviewer");
8181
- if (write ? !owner || task.state !== "in_progress" : by !== USER && !owner && !reviewer && !(this.configuredManualConductor(by) && this.d.bus.isRostered(by)))
8182
- throw new PreEffectToolRefusal("survey reporting requires its assigned in-progress planner; readback requires its owner, reviewer, person or current conductor");
8183
- return { task, survey };
8184
- }
8185
- private surveyPrivate(task: Task, by?: PeerId): boolean {
8186
- return this.isPii(task) || task.signals.includes("pii") || task.signals.includes("pii_path") || !!(by && this.d.privateTurn?.(by));
8187
- }
8188
- /** The existing task routing chooses one planner; no worker, scanner, issue or fix is launched. */
8189
- async surveyStart(by: PeerId, input: unknown = {}, fence?: () => string | undefined): Promise<{ task: number; survey: number; ref: string; focus?: SurveyFocus }> {
8190
- const fields = this.surveyToolInput("start", "start", "must be a closed object with optional focus", () => surveyObject(input, ["focus"])), focus = fields.focus;
8191
- if (focus !== undefined && (typeof focus !== "string" || !(SURVEY_FOCUS as readonly string[]).includes(focus))) this.surveyToolInput("start", "focus", "must be bugs, tests, debt, deps, dx or docs", () => { throw new Error("invalid bounded survey data"); });
8192
- const check = this.requestCheck(by, fence), authority = () => {
8193
- this.surveyAdmit(by, check);
8194
- if (by !== USER && !(this.configuredManualConductor(by) && this.d.bus.isRostered(by))) throw new PreEffectToolRefusal("only the person or current unique conductor may start a survey");
8195
- };
8196
- authority();
8197
- if (this.observerExcluded(by) || this.reviewObserverTurn(by)) throw new PreEffectToolRefusal("survey start is unavailable from observer material");
8198
- if (this.surveyStarting) throw new PreEffectToolRefusal("a survey is already starting");
8199
- const repo = this.repositories.scope({}).key, source = this.d.auditSource;
8200
- if (!source) throw new PreEffectToolRefusal("survey source unavailable; start the hub from the project checkout");
8201
- const ref = source.head();
8202
- if (!ref || !/^[a-f0-9]{40}$/.test(ref) || source.resolve(ref) !== ref) throw new PreEffectToolRefusal("survey commit unavailable; select a checkout with a readable commit");
8203
- if (this.d.board.surveyOpen(repo)) throw new PreEffectToolRefusal("a survey is already open; finish or cancel it first");
8204
- const brief = `${surveyBrief({ ...(focus === undefined ? {} : { focus: focus as SurveyFocus }) })}\nPinned source commit: ${ref}\nRead this exact commit, including during vetting. Findings are declarations, never host proof of independent source review.\nSubmit candidates with hub_survey_report {id: <this task>, findings: [...]}; explicit vet decisions use vet: [...].\n${this.consideredBrief(repo, ref)}`;
8205
- if (!this.publicMetadataText(brief)) throw new PreEffectToolRefusal("survey brief is not public");
8206
- this.surveyStarting = true;
8207
- try { return await this.studyWrite(async () => {
8208
- const guard = () => { authority(); if (this.d.auditSource !== source || this.repositories.scope({}).key !== repo || this.d.board.surveyOpen(repo)) throw new PreEffectToolRefusal("survey source or open-survey admission changed"); };
8209
- guard();
8210
- let surveyID: number | undefined;
8211
- const task = await this.propose(by, { title: `Advisor survey${focus ? ` (${focus})` : ""} at ${ref.slice(0, 12)}`, detail: brief, class: "plan" }, undefined, undefined,
8212
- () => { guard(); return undefined; }, created => {
8213
- if (this.surveyPrivate(created, by)) throw new PreEffectToolRefusal("survey brief privacy was not cleared");
8214
- surveyID = this.d.board.surveyCreate({ task: created.id, taskCreated: created.created, repo, ref, ...(focus === undefined ? {} : { focus: focus as SurveyFocus }), by, at: this.d.now?.() ?? Date.now() });
8215
- });
8216
- return { task: task.id, survey: surveyID!, ref, ...(focus === undefined ? {} : { focus: focus as SurveyFocus }) };
8217
- }); } finally { this.surveyStarting = false; }
8218
- }
8219
6064
  private consideredChanges(repo: string, ref?: string): (entryRef?: string) => string[] | undefined {
8220
6065
  // ponytail: distinct refs still use synchronous reads within the existing ledger window per key; batch through an async audit port if histories outgrow interactive readback.
8221
6066
  const cache = new Map<string, string[] | undefined>(); let currentKnown: boolean | undefined;
@@ -8328,87 +6173,6 @@ export class Tasks {
8328
6173
  .catch(() => this.releaseNotice(`task #${task.id}: considered rejection ledger unavailable`));
8329
6174
  });
8330
6175
  }
8331
- surveyShow(by: PeerId, id: unknown) {
8332
- const check = this.requestCheck(by); this.surveyAdmit(by, check);
8333
- const { task, survey } = this.surveyTask(by, id);
8334
- if (this.surveyPrivate(task, by)) return { task: task.id, status: "private" as const };
8335
- const revision = this.d.board.statusRevision(), policy = JSON.stringify([this.d.roles, this.d.routing(), this.d.piiPaths]);
8336
- const full = by === USER || this.d.bus.isRostered(by) && (task.owner === by && this.isConfiguredPlanner(by) || task.reviewer === by && !!this.d.roles?.[by]?.includes("reviewer"));
8337
- const stored = this.d.board.surveyFindings(survey.id), changes = this.consideredChanges(survey.repo, survey.ref);
8338
- if (stored.some(row => !this.publicMetadataText(JSON.stringify(row.finding)) || this.signalsFor({ title: row.finding.id, detail: JSON.stringify(row.finding), refs: { paths: row.finding.paths } }).some(signal => signal === "pii" || signal === "pii_path"))) return { task: task.id, status: "private" as const };
8339
- const items = stored.map(row => {
8340
- const finding = full ? row.finding : publicSurveyFinding(row.finding), before = this.consideredBefore(task, row.finding, survey.ref, changes);
8341
- const details = this.consideredDetails(survey.repo, row.finding.id, row.finding.pass, survey.ref, changes);
8342
- return { ...finding, ...(row.decision ? { verdict: row.decision.verdict } : {}), ...before, rejected: details.items, rejectedComplete: details.complete };
8343
- });
8344
- this.surveyAdmit(by, check);
8345
- const now = this.surveyTask(by, id);
8346
- if (this.surveyPrivate(now.task, by)) return { task: task.id, status: "private" as const };
8347
- if (this.d.board.statusRevision() !== revision || now.task.history.length !== task.history.length || JSON.stringify([this.d.roles, this.d.routing(), this.d.piiPaths]) !== policy) throw new PreEffectToolRefusal("survey changed during readback; reload before reading");
8348
- return { task: task.id, survey: survey.id, ref: survey.ref, ...(survey.focus ? { focus: survey.focus } : {}), status: "available" as const, items };
8349
- }
8350
- async surveyReport(by: PeerId, input: unknown, fence?: () => string | undefined) {
8351
- const fields = this.surveyToolInput("report", "report", "must be a closed object with id and findings, vet or show", () => surveyObject(input, ["id", "findings", "vet", "show"]));
8352
- this.surveyToolInput("report", "id", "must be a positive integer survey task id", () => { if (!Number.isSafeInteger(fields.id) || (fields.id as number) < 1) throw new Error("invalid bounded survey data"); });
8353
- this.surveyToolInput("report", "show", "must be true for read-only show and cannot include findings or vet decisions", () => {
8354
- if (fields.show !== undefined && fields.show !== true || fields.show && (fields.findings !== undefined || fields.vet !== undefined)) throw new Error("invalid bounded survey data");
8355
- });
8356
- if (fields.show) { this.requestCheck(by, fence)(); return this.surveyShow(by, fields.id); }
8357
- const findings = fields.findings === undefined ? [] : this.surveyToolInput("report", "findings", "must match the documented finding array", () => parseSurveyFindings(fields.findings));
8358
- const decisions = fields.vet === undefined ? [] : this.surveyToolInput("report", "vet", "must match the documented vet array", () => parseSurveyVetDecisions(fields.vet));
8359
- const check = this.requestCheck(by, fence), guard = () => { this.surveyAdmit(by, check); return this.surveyTask(by, fields.id, true); };
8360
- const initial = guard();
8361
- if (this.surveyPrivate(initial.task, by) || this.observerExcluded(by) || this.reviewObserverTurn(by)) throw new PreEffectToolRefusal("survey writes unavailable during private or observer work");
8362
- if (!findings.length && !decisions.length) throw new PreEffectToolRefusal("report: needs findings or explicit vet decisions; fix that field and resend hub_survey_report; tool description lists shape");
8363
- const observerExcluded = this.observerExcluded(by); // Capture before any awaited screen; never forward observer material.
8364
- if (observerExcluded) throw new PreEffectToolRefusal("survey observer input is unavailable");
8365
- return this.studyWrite(async () => {
8366
- const { task, survey } = guard(), boardRevision = this.d.board.statusRevision(), policy = JSON.stringify([this.d.sdlc?.config().mode, this.d.roles, this.d.routing(), this.d.piiPaths]);
8367
- const current = () => {
8368
- const now = guard();
8369
- if (now.task.created !== task.created || now.task.history.length !== task.history.length || now.task.owner !== task.owner || this.surveyPrivate(now.task, by)
8370
- || this.d.board.statusRevision() !== boardRevision || JSON.stringify([this.d.sdlc?.config().mode, this.d.roles, this.d.routing(), this.d.piiPaths]) !== policy) throw new PreEffectToolRefusal("survey authority, privacy or policy changed; reload before reporting");
8371
- };
8372
- const existing = this.d.board.surveyFindings(survey.id), merged = new Map(existing.map(row => [row.finding.id, row.finding]));
8373
- for (const finding of findings) { const prior = merged.get(finding.id); if (prior && JSON.stringify(prior) !== JSON.stringify(finding)) throw new PreEffectToolRefusal("findings[].id: survey candidate id already records different content; fix that field and resend hub_survey_report; tool description lists shape"); merged.set(finding.id, finding); }
8374
- const text = JSON.stringify({ findings: this.surveyToolInput("report", "findings", "combined findings must remain within the documented bounds", () => parseSurveyFindings([...merged.values()])), decisions });
8375
- if (!this.publicMetadataText(text)) throw new PreEffectToolRefusal("survey metadata was not cleared as public");
8376
- if (this.screenOn() && (await this.screenCall(text)).label !== "clear") throw new PreEffectToolRefusal("survey metadata privacy screening was unavailable or refused");
8377
- current();
8378
- const changes = this.consideredChanges(survey.repo, survey.ref);
8379
- const cards: SurveyPreparedCard[] = [], rejections: ConsideredEntry[] = [], reconsiderations: ConsideredEntry[] = [];
8380
- const items: { id: string; rejectedBefore: boolean; change: "none" | "unchanged" | "changed" | "unknown"; suppressed: boolean }[] = [];
8381
- for (const decision of decisions) {
8382
- const finding = merged.get(decision.id); if (!finding) throw new PreEffectToolRefusal("vet[].id: vet decision names an unknown survey candidate; fix that field and resend hub_survey_report; tool description lists shape");
8383
- const before = this.consideredBefore(task, finding, survey.ref, changes); items.push({ id: finding.id, ...before });
8384
- const entry = (reason: string): ConsideredEntry => ({ repo: survey.repo, id: finding.id, pass: finding.pass, paths: finding.paths, reason, ref: survey.ref,
8385
- source: { task: task.id, created: task.created, kind: "survey" }, ...(finding.pass === "security" ? { withheld: true } : {}) });
8386
- if (decision.verdict === "rejected") { rejections.push(entry(decision.reason!)); continue; }
8387
- if (before.suppressed && !decision.reason) continue;
8388
- if (before.rejectedBefore && decision.reason) reconsiderations.push(entry(decision.reason));
8389
- const key = surveyFindingKey(survey.repo, finding.pass, finding.id), security = finding.pass === "security";
8390
- const history = this.d.board.surveyCardHistory(key), reopens = history.active ? undefined : history.closed;
8391
- current();
8392
- const reopenReason = security ? "explicit current vet; security details remain in the authorized survey"
8393
- : decision.reason ?? (before.change === "changed" ? "affected paths changed since the recorded rejection" : "explicit current vet; no applicable rejected finding remains");
8394
- const reopening = reopens === undefined ? {} : { reopens, reopenReason };
8395
- const draft = { title: security ? `Survey security finding ${finding.id}` : `Survey ${finding.confidence}: ${finding.id}`,
8396
- detail: `${key}\nSource survey task ${task.id} at ${survey.ref}.\n${finding.confidence === "low" ? "Read-only investigation. Do not edit files or execute a fix." : "Prepare a backlog plan. Do not execute a fix."}${security ? "\nSecurity details withheld; read the source survey with authorized task access." : `\nEvidence: ${finding.evidence}\nImpact: ${finding.impact}\nEffort: ${finding.effort}\nRisk: ${finding.risk}\nFix sketch: ${finding.fix_sketch}`}${reopens === undefined ? "" : `\nReopened from hub task ${reopens}: ${reopenReason}`}`,
8397
- refs: security ? {} : { paths: finding.paths } };
8398
- if (Buffer.byteLength(draft.detail) > SURVEY_LIMITS.cardBytes) throw new PreEffectToolRefusal("survey card exceeds its detail bound; shorten the finding or reconsideration reason");
8399
- const signals = this.signalsFor(draft);
8400
- if (this.isPii({ signals }) || signals.includes("pii") || signals.includes("pii_path") || !this.publicMetadataText(JSON.stringify(draft))) throw new PreEffectToolRefusal("survey candidate card is not public");
8401
- if (this.screenOn() && (await this.screenCall(JSON.stringify(draft))).label !== "clear") throw new PreEffectToolRefusal("survey card privacy screening was unavailable or refused");
8402
- current(); cards.push({ id: finding.id, key, ...draft, class: finding.confidence === "low" ? "triage" : "plan", signals, ...reopening });
8403
- }
8404
- current();
8405
- const result = this.d.board.surveyApply(survey.id, { findings, decisions, by, at: this.d.now?.() ?? Date.now(), cards, rejections, reconsiderations },
8406
- { boardRevision, taskCreated: task.created, taskFlowRevision: task.history.length, owner: task.owner! });
8407
- for (const id of result.createdIDs) this.incomingBacklog.add(id);
8408
- this.releaseNotice(`survey task ${task.id}: ${result.createdIDs.length} backlog candidates created`);
8409
- return { task: task.id, survey: survey.id, status: "recorded" as const, ...result, items };
8410
- });
8411
- }
8412
6176
 
8413
6177
  /** #1658: a read-back is a report for the person, so it is unavailable wherever a private or child session could carry text out. */
8414
6178
  private readbackAdmit(by: PeerId, check: () => void): void {
@@ -8722,6 +6486,44 @@ export class Tasks {
8722
6486
  return { ...this.auditView(full, true), ...(skipped.length ? { notUpdated: skipped } : {}) };
8723
6487
  }
8724
6488
 
6489
+ /**
6490
+ * #1856 T4: `ahub sdlc sync --close-settled-issues` runs only under roadmap apply authority (the person, or the unique conductor with roadmap.github_write = "conductor").
6491
+ * Returns the host-sampled repository; the refusal names the person's own command.
6492
+ */
6493
+ closeSettledGate(by: PeerId): string {
6494
+ try { this.roadmapApplyAuthority(by); return this.roadmapRepository(); }
6495
+ catch (error) {
6496
+ if (error instanceof PreEffectToolRefusal) throw new PreEffectToolRefusal(`${error.message}; the person runs ahub sdlc sync --close-settled-issues, then the same command with --apply --confirm <fingerprint>`);
6497
+ throw error;
6498
+ }
6499
+ }
6500
+
6501
+ /** One `gh issue close` of a settled issue, after the authority and origin are re-checked. Never touches a milestone. */
6502
+ async closeSettledIssue(by: PeerId, repo: string, issue: number): Promise<void> {
6503
+ if (this.closeSettledGate(by).toLowerCase() !== repo.toLowerCase() || !Number.isSafeInteger(issue) || issue <= 0) throw new PreEffectToolRefusal("roadmap GitHub origin changed; preview again with ahub sdlc sync --close-settled-issues");
6504
+ let result: Awaited<ReturnType<SdlcGh>>;
6505
+ try { result = await this.roadmapGh()(["issue", "close", String(issue), "--repo", repo, "--reason", "completed"], 10_000, undefined, 64 * 1024); }
6506
+ catch { throw new Error("issue close outcome is unknown; inspect the issue before retrying"); }
6507
+ if (result.code !== 0) throw new Error("issue close was not confirmed; inspect the issue before retrying");
6508
+ }
6509
+
6510
+ /**
6511
+ * #1856 T3: one sync repair written under the real actor. Only the person or the one configured conductor on the roster; the entry names that actor.
6512
+ * The writer is admitted past the owner and reviewer rule for exactly a link ({repo, issue}) or a bind ({repo, pr, localHead}), never a relink and never deliverables.
6513
+ */
6514
+ recordSyncRepair(by: PeerId, id: number, input: { repo: string; issue?: number; pr?: number; localHead?: string }): Task {
6515
+ if (by !== USER && (!this.configuredManualConductor(by) || !this.d.bus.isRostered(by)))
6516
+ throw new PreEffectToolRefusal("only the person or the current configured conductor may apply a sync; ask the person to run ahub sdlc sync --apply --confirm <fingerprint>");
6517
+ if (this.d.privateTurn?.(by)) throw new PreEffectToolRefusal("sync is unavailable in a private turn; finish that turn and retry ahub sdlc sync");
6518
+ const keys = Object.keys(input).sort().join(",");
6519
+ if (keys !== "issue,repo" && keys !== "localHead,pr,repo") throw new PreEffectToolRefusal("a sync repair is a link {repo, issue} or a bind {repo, pr, localHead}; record anything else with ahub sdlc record");
6520
+ const task = this.need(id, false, true), had = task.sdlc;
6521
+ if (had?.repo !== undefined && had.repo.toLowerCase() !== input.repo.toLowerCase() || input.issue !== undefined && had?.issue !== undefined)
6522
+ throw new PreEffectToolRefusal("a sync repair never relinks an established repository or issue; record the change with ahub sdlc record");
6523
+ if (input.pr !== undefined && had?.pr !== undefined && had.pr !== input.pr) throw new PreEffectToolRefusal("a sync repair never replaces a recorded PR; record the change with ahub sdlc record");
6524
+ return this.recordLifecycle(by, id, input, undefined, undefined, true);
6525
+ }
6526
+
8725
6527
  /** #1328 T3: approve a merge observed outside the hub, without attributing a verdict to a reviewer. */
8726
6528
  async adoptMerge(by: PeerId, id: unknown, pr: unknown, fence?: () => string | undefined): Promise<{ task: number; state: "approved" }> {
8727
6529
  const check = this.requestCheck(by, fence);
@@ -10180,7 +7982,8 @@ export class Tasks {
10180
7982
  this.warmRepository({ ...task, refs: { ...task.refs, ...checkedRefs } });
10181
7983
  this.assertSpecInspection(specInspection, { ...task, refs: storedRefs }, by);
10182
7984
  const pending = write(task.id, by, "done (checking)", { ...(refresh ? { state: "in_progress" as const } : {}), ...(refresh?.state === "approved" && !task.reviewer ? { reviewer: USER } : {}), codeSymbols: this.observedCodeSymbols({ ...task, refs: storedRefs }), refs: checkedRefs, ...(task.sdlc ? { sdlc: task.sdlc } : {}) }, summary, { withheld: withheld || undefined, ...(records ? { deliverables: records } : {}), ...(specInspection.report ? { specReport: specInspection.report, specRefBinding: this.specRefBinding({ refs: storedRefs }) } : {}) }, task.history.length, HOST_CODE_SYMBOLS);
10183
- if (refresh) { this.ciWatchers.cancel(pending.id); this.heldReviews.delete(pending.id); }
7985
+ if (refresh) this.heldReviews.delete(pending.id);
7986
+ this.watchCi(pending);
10184
7987
  this.releaseNotice(`task ${this.publicTitle(pending)} done by ${by}; its check is queued or running: ${command}`);
10185
7988
  const seen = { events: pending.history.length, owner: pending.owner };
10186
7989
  this.pendingChecks++;
@@ -10397,7 +8200,8 @@ export class Tasks {
10397
8200
  const next = this.d.board.update(task.id, by, "done", { codeSymbols: this.observedCodeSymbols({ ...task, refs: storedRefs }), state: reviewer ? "in_review" : "approved", ...(selection || refresh?.state === "approved" ? { reviewer: quotaWaiting ? null : reviewer ?? USER } : {}), ...(task.sdlc ? { sdlc: { ...withoutRisk(task.sdlc), stage: lifecycleStage(this.d.sdlc?.config() ?? sdlcConfig(undefined), reviewer ? "review" : "merge"), ...(risk ? { risk } : {}) } } : {}), refs: completedRefs }, checkOutput ? `${routedSummary ?? ""}\n${checkOutput}`.trim() : routedSummary, { ...(resolvedReviewComments?.length ? { resolvedReviewComments: this.reviewCommentResolve(by, task, resolvedReviewComments) } : {}), ...this.planObservation(task), withheld: withheld || undefined, ...(specInspection?.report ? { specReport: specInspection.report, specRefBinding: this.specRefBinding({ refs: storedRefs }) } : {}), ...(noWrites ? { noWrites: true as const } : {}), ...this.reviewMetadata(selection, { ...task, state: "in_review", refs: storedRefs }), ...(reviewCost ? { reviewCost } : {}), ...(requestHead ? { requestHead } : {}), ...(records ? { deliverables: records } : {}) }, task.history.length, HOST_CODE_SYMBOLS);
10398
8201
  this.queueReviewWritten(next);
10399
8202
  this.writePlannerNotices(next, capacity, next.state === "approved");
10400
- this.ciWatchers.cancel(next.id); this.heldReviews.delete(next.id); // a newer head or a move ends the old head's watcher (#785 P1b)
8203
+ this.heldReviews.delete(next.id);
8204
+ this.watchCi(next, !!reviewer && admission?.ready === true && admission.head === this.reviewHead(next));
10401
8205
  this.cohorts.closed(next.id); // its owner's next native turn end settles it in its cohort (issue #107)
10402
8206
  const memorySymbols = this.completionMemorySymbols(next);
10403
8207
  this.note(next, by, "finding", `Task #${next.id} done by ${by}: ${next.title}\nChanged-symbol memory anchors: ${memorySymbols.state === "known" ? memorySymbols.nodes.length : "unknown (no complete code facts)"}\n${summary ?? ""}`, withheld || reviewObserverExcluded, memorySymbols);
@@ -10411,7 +8215,6 @@ export class Tasks {
10411
8215
  else if (quotaWaiting) this.releaseNotice(`task ${this.publicTitle(next)}: waiting for reviewer quota reset`);
10412
8216
  else if (reviewer === USER) this.releaseNotice(`task ${this.publicTitle(next)} done by ${by}: review it in the ahub console (Tasks, select #${next.id}, press r) or with ahub review ${next.id} approved|changes_requested [note]`);
10413
8217
  else this.releaseNotice(`task ${this.publicTitle(next)}: could not send the review request to ${reviewer}`, () => this.sendReview(next, reviewer, "", admission));
10414
- if (reviewer && !quotaWaiting && !(admission?.ready && admission.head === this.reviewHead(next))) this.watchCi(next);
10415
8218
  return next;
10416
8219
  }
10417
8220
 
@@ -10721,39 +8524,107 @@ export class Tasks {
10721
8524
  } catch { /* optional bookkeeping never fails a review path */ }
10722
8525
  }
10723
8526
 
10724
- /** #785 P1b AC3: start the one watcher for this task's exact head. Not for private work, an unlinked PR or a lifecycle that is off; never throws. */
10725
- private watchCi(task: Task): void {
8527
+ private ciWatchTarget(task: Task): Omit<CiWatch, "deadlineAt"> | undefined {
8528
+ if (!this.d.sdlc || this.d.sdlc.config().mode === "off" || this.isPii(task)
8529
+ || !["in_progress", "in_review", "approved", "changes_requested"].includes(task.state) || task.sdlc?.mergeReadback?.state === "merged") return;
8530
+ const repo = task.sdlc?.repo, pr = task.sdlc?.pr, submitted = this.reviewHead(task);
8531
+ const recorded = task.history.findLast(entry => entry.event === "lifecycle" || entry.event === "done" || entry.event === "done (checking)");
8532
+ const ownerPhase = task.state === "in_progress" || task.state === "changes_requested";
8533
+ const useLocalHead = ownerPhase && recorded?.event !== "done (checking)" || recorded?.event === "lifecycle";
8534
+ const local = useLocalHead ? task.sdlc?.localHead : undefined;
8535
+ const head = local ?? submitted;
8536
+ if (!repo || !pr || !head || !/^[0-9a-f]{40}$/.test(head)) return;
8537
+ const phase = ownerPhase || head !== submitted ? "draft" : task.state === "approved" ? "approved" : "review";
8538
+ return { id: task.id, head, repo, pr, phase };
8539
+ }
8540
+
8541
+ private watchCi(task: Task, alreadyPassed = false): void {
10726
8542
  try {
10727
- const head = this.reviewHead(task), repo = task.sdlc?.repo, pr = task.sdlc?.pr;
10728
- if (!this.d.sdlc || this.d.sdlc.config().mode === "off" || this.isPii(task) || task.state !== "in_review" || !head || !/^[0-9a-f]{40}$/.test(head) || !repo || !pr) return;
10729
- this.ciWatchers.start({ id: task.id, head, repo, pr });
10730
- } catch { /* a watcher that cannot start leaves the review path as it was */ }
8543
+ const target = this.ciWatchTarget(task);
8544
+ if (target) this.ciWatchers.start(target, alreadyPassed);
8545
+ else this.ciWatchers.cancel(task.id);
8546
+ } catch { /* Optional bookkeeping never fails a task transition. */ }
10731
8547
  }
10732
8548
 
10733
- /** The watcher's own check before every read and every notice: the task must still be in review at this exact head and PR. */
10734
8549
  private ciWatchCurrent(watch: CiWatch): boolean {
8550
+ const task = this.d.board.get(watch.id), target = task && this.ciWatchTarget(task);
8551
+ return !!target && target.head === watch.head && target.repo === watch.repo && target.pr === watch.pr && target.phase === watch.phase;
8552
+ }
8553
+
8554
+ private async retryCiShard(watch: CiWatch, retry: CiShardRetry, completed: boolean, mergeable: boolean): Promise<CiRetryDecision> {
10735
8555
  const task = this.d.board.get(watch.id);
10736
- return !!task && task.state === "in_review" && !this.isPii(task) && this.reviewHead(task) === watch.head && task.sdlc?.repo === watch.repo && task.sdlc?.pr === watch.pr
10737
- && (this.d.sdlc?.config().mode ?? "off") !== "off";
8556
+ const limit = this.d.sdlc?.config().ciShardRetries ?? 0;
8557
+ if (!task || watch.phase === "draft" || !this.ciWatchCurrent(watch)
8558
+ || this.d.repository?.toLowerCase() !== watch.repo.toLowerCase() || !this.publicMetadataText(retry.job)) return "ineligible";
8559
+ const scope = `${watch.repo.toLowerCase()} PR #${watch.pr} head ${watch.head} job `;
8560
+ const key = `${scope}${retry.job} run `;
8561
+ const attemptKey = `${key}${retry.run} attempt ${retry.attempt}`;
8562
+ const attempts = task.history.flatMap(entry => {
8563
+ const note = entry.note;
8564
+ if (entry.by !== HUB || entry.event !== "ci shard rerun" || !note?.startsWith(scope)) return [];
8565
+ if (retry.aggregateOnly) {
8566
+ if (!note.includes(` run ${retry.run} attempt `) || !note.includes(`; aggregate ${retry.job};`)) return [];
8567
+ } else if (!note.startsWith(key)) return [];
8568
+ return [note];
8569
+ });
8570
+ const last = attempts.at(-1);
8571
+ if (last) {
8572
+ const stamp = retry.aggregateOnly ? /; aggregateStartedAt (\d+);/ : /; startedAt (\d+);/;
8573
+ const previous = Number(stamp.exec(last)?.[1]);
8574
+ if (!Number.isSafeInteger(previous) || retry.startedAt === undefined || retry.startedAt <= previous) {
8575
+ const reservation = last.split(";")[0];
8576
+ return task.history.some(entry => entry.by === HUB && entry.event === "ci shard rerun unconfirmed" && entry.note === reservation)
8577
+ ? "stale-unconfirmed" : "stale";
8578
+ }
8579
+ }
8580
+ if (!limit || !mergeable || attempts.length >= limit || retry.aggregateOnly || attempts.some(note => note.startsWith(`${attemptKey};`))) return last ? "final" : "ineligible";
8581
+ if (retry.startedAt === undefined) return "ineligible";
8582
+ if (!completed) return "waiting";
8583
+ const number = attempts.length + 1;
8584
+ const aggregateEvidence = retry.aggregateStartedAt === undefined ? "" : ` aggregateStartedAt ${retry.aggregateStartedAt};`;
8585
+ const evidence = `startedAt ${retry.startedAt}; aggregate ${retry.aggregate};${aggregateEvidence}`;
8586
+ // Save the check's own start before dispatch. GitHub stamps copied check rows with the current run attempt.
8587
+ this.d.board.update(task.id, HUB, "ci shard rerun", {}, `${attemptKey}; ${evidence} retry ${number} of ${limit}`, undefined, task.history.length);
8588
+ if (!this.ciWatchCurrent(watch)) return "reserved";
8589
+ let confirmed = false;
8590
+ try {
8591
+ const response = await (this.d.sdlc?.gh ?? sdlcGh)(["run", "rerun", String(retry.run), "--failed", "--repo", watch.repo], 10_000);
8592
+ confirmed = response.code === 0;
8593
+ } catch { /* The reserved attempt stays counted when dispatch cannot be confirmed. */ }
8594
+ if (!this.ciWatchCurrent(watch)) return "reserved";
8595
+ if (!confirmed) this.d.board.update(task.id, HUB, "ci shard rerun unconfirmed", {}, attemptKey);
8596
+ const outcome = confirmed ? "requested" : "unconfirmed";
8597
+ this.tellCi(watch, [task.owner, conductorPeer(this.d.roles) ?? USER], `ci_rerun: #${task.id} head ${watch.head} PR #${watch.pr} ${retry.job} retry ${number} of ${limit} ${outcome}`);
8598
+ return confirmed ? "confirmed" : "unconfirmed";
8599
+ }
8600
+
8601
+ private tellCi(watch: CiWatch, recipients: readonly (PeerId | null | undefined)[], line: string): void {
8602
+ for (const peer of new Set(recipients)) {
8603
+ if (!peer || peer === HUB) continue;
8604
+ if (peer === USER) { this.releaseNotice(line); continue; }
8605
+ this.releaseNotice(`task #${watch.id}: could not tell ${peer} the CI result`, () => this.d.bus.publish(newEnvelope(HUB, sanitize(`${line}\nRead hub_task_show for the task before acting.`), { to: [peer], kind: "task", priority: "status", refs: { task: String(watch.id), commit: watch.head } })));
8606
+ }
10738
8607
  }
10739
8608
 
10740
- /**
10741
- * #785 P1b: the result of the exact head's CI, told once to the owner and the reviewer (one ids-only task envelope each, `status` weight: `fyi` is recorded but never delivered to the peer),
10742
- * then a review held as premature is offered once more after a fresh readiness read. A deadline tells the console only.
10743
- */
10744
- private async ciCompleted(watch: CiWatch, outcome: CiOutcome): Promise<void> {
8609
+ /** #1801: report exact-head metadata only, with one set of recipients per phase. */
8610
+ private async ciCompleted(watch: CiWatch, outcome: CiOutcome, snapshot?: CiSnapshot): Promise<void> {
10745
8611
  const task = this.d.board.get(watch.id);
10746
8612
  if (!task || !this.ciWatchCurrent(watch)) return;
10747
8613
  const label = `#${task.id} head ${watch.head.slice(0, 12)}`;
10748
8614
  if (outcome === "deadline") { this.releaseNotice(`task ${label}: CI did not finish within the watch deadline; no further reads`); return; }
10749
- const line = `ci_completed: ${label} ${outcome}`;
10750
- for (const peer of new Set([task.owner, task.reviewer])) {
10751
- if (!peer || peer === HUB) continue;
10752
- if (peer === USER) { this.releaseNotice(`task ${label}: CI ${outcome} at its exact head`); continue; }
10753
- this.releaseNotice(`task ${label}: could not tell ${peer} the CI result`, () => this.d.bus.publish(newEnvelope(HUB, `${line}\nRead hub_task_show for the task before acting.`, { to: [peer], kind: "task", priority: "status", refs: { task: String(task.id), commit: watch.head } })));
10754
- }
10755
- if (outcome === "failed") return;
10756
- await this.reofferHeldReview(task, watch);
8615
+ const conductor = conductorPeer(this.d.roles) ?? USER;
8616
+ const headNotice = outcome === "conflicting" || outcome === "missing-run"
8617
+ || outcome === "failed" && snapshot?.retryWorkflowFailure === true;
8618
+ const recipients = headNotice ? [task.owner, conductor]
8619
+ : watch.phase === "approved" ? [task.reviewer, conductor] : watch.phase === "draft" ? [task.owner] : [task.owner, task.reviewer];
8620
+ const safeChecks = snapshot?.failedChecks?.filter(name => /^[a-z0-9 _().:/-]+$/i.test(name) && this.publicMetadataText(name));
8621
+ const details = outcome === "conflicting" ? `PR #${watch.pr} conflicts with main; GitHub runs no CI on it; rebase onto main and push once.`
8622
+ : outcome === "missing-run" ? `PR #${watch.pr} has no observed CI run for this head; check Actions and trigger CI for the current head.`
8623
+ : watch.phase === "approved" && outcome === "passed" ? `PR #${watch.pr} is merge ready; required checks passed and no review thread is unresolved.`
8624
+ : outcome === "failed" ? `PR #${watch.pr} failed ${safeChecks?.length ? safeChecks.join(", ") : "a required check"}.` : "";
8625
+ const line = `ci_completed: ${label} ${outcome}${details ? `\n${details}` : ""}`;
8626
+ this.tellCi(watch, recipients, line);
8627
+ if (watch.phase === "review" && (outcome === "passed" || outcome === "incomplete")) await this.reofferHeldReview(task, watch);
10757
8628
  }
10758
8629
 
10759
8630
  /** The held review of this exact head and request, once: only while it is still the same reviewer, head and revision, and a fresh admission says it is ready. */
@@ -11199,8 +9070,9 @@ export class Tasks {
11199
9070
  ? { ...saved, reopenedWithoutReason } : saved;
11200
9071
  if (verdict === "approved") {
11201
9072
  const capacity = this.capacityBefore(task);
11202
- this.ciWatchers.cancel(task.id); this.heldReviews.delete(task.id);
9073
+ this.heldReviews.delete(task.id);
11203
9074
  const next = this.d.board.update(task.id, by, "approved", { state: "approved", rejections: 0, ...(reviewedHead && task.sdlc ? { sdlc: { ...task.sdlc, reviewedHead, stage: lifecycleStage(this.d.sdlc?.config() ?? sdlcConfig(undefined), "merge") } } : {}) }, note, flag);
9075
+ this.watchCi(next);
11204
9076
  notifyAcceptedReopens();
11205
9077
  this.recordConsideredAfter(next, parsed.filter(finding => finding.disposition === "false_positive"), "review", findingHead ?? reviewedHead);
11206
9078
  this.writePlannerNotices(next, capacity, next.state === "approved");
@@ -11224,8 +9096,9 @@ export class Tasks {
11224
9096
  this.releaseNotice(`task #${next.id}: review saved but recurring-criterion proposal unavailable`, () => { this.proposeCriterionCandidates(next, by, withheld); this.proposeRemovalCandidates(by, withheld); });
11225
9097
  return result(next);
11226
9098
  }
11227
- this.ciWatchers.cancel(task.id); this.heldReviews.delete(task.id);
9099
+ this.heldReviews.delete(task.id);
11228
9100
  const rejected = this.d.board.update(task.id, by, "changes_requested", { state: "changes_requested", rejections: evidenceOnly ? task.rejections : task.rejections + 1 }, note, flag, task.history.length);
9101
+ this.watchCi(rejected);
11229
9102
  notifyAcceptedReopens();
11230
9103
  this.recordConsideredAfter(rejected, parsed.filter(finding => finding.disposition === "false_positive"), "review", findingHead ?? reviewedHead);
11231
9104
  void this.mirrorVerdict(rejected, by, "changes_requested", reviewedHead ?? rejected.sdlc?.reviewedHead, note, withheld || observerExcluded);
@@ -11469,9 +9342,9 @@ export class Tasks {
11469
9342
  * Budget relay: a paused peer's open work moves on. `local` first (it has no quota), then the class list, all through
11470
9343
  * the usual constraints. Tasks it was reviewing get another reviewer. Moves are reported, never taken back automatically.
11471
9344
  */
11472
- async reassignForPause(peer: PeerId, context: string | undefined, urgentOnly = false): Promise<{ id: number; title: string; to: PeerId | null; role: "owner" | "reviewer" }[]> {
9345
+ async reassignForPause(peer: PeerId, context: string | undefined, urgentOnly = false, also: readonly PeerId[] = []): Promise<{ id: number; title: string; to: PeerId | null; role: "owner" | "reviewer" }[]> {
11473
9346
  requireLocalTaskPeer(peer);
11474
- return this.reassignWork(peer, context, urgentOnly, false);
9347
+ return this.reassignWork(peer, context, urgentOnly, false, undefined, also);
11475
9348
  }
11476
9349
 
11477
9350
  /** Read-only preview using the same assignment constraints as the roster relay. */
@@ -11494,7 +9367,7 @@ export class Tasks {
11494
9367
  return this.reassignWork(peer, undefined, false, true, current);
11495
9368
  }
11496
9369
 
11497
- private async reassignWork(peer: PeerId, context: string | undefined, urgentOnly: boolean, roster: boolean, current?: () => void): Promise<{ id: number; title: string; to: PeerId | null; role: "owner" | "reviewer" }[]> {
9370
+ private async reassignWork(peer: PeerId, context: string | undefined, urgentOnly: boolean, roster: boolean, current?: () => void, also: readonly PeerId[] = []): Promise<{ id: number; title: string; to: PeerId | null; role: "owner" | "reviewer" }[]> {
11498
9371
  current?.();
11499
9372
  const moved: { id: number; title: string; to: PeerId | null; role: "owner" | "reviewer" }[] = [];
11500
9373
  const routing = this.d.routing(), why = roster ? `roster removal of ${peer}` : `budget pause of ${peer}`;
@@ -11508,13 +9381,13 @@ export class Tasks {
11508
9381
  if (task.owner === peer && (OPEN.includes(task.state) || roster && task.state === "in_review")) {
11509
9382
  const pii = this.isPii(task);
11510
9383
  const candidates = relayCandidates(routing.classes[task.class]?.peers ?? [], pii, { ...this.instanceRouting(), states: this.states() });
11511
- if (this.plannerPullRecord(task)?.pull && !assign(task, this.states(), routing, { candidates, exclude: [...this.excluded(task), peer], excludeOwners: this.plannerFull(task), waitsFor: this.waitsFor(task), ...this.weights(task.class, task) }).owner) continue;
9384
+ if (this.plannerPullRecord(task)?.pull && !assign(task, this.states(), routing, { candidates, exclude: [...this.excluded(task), peer, ...also], excludeOwners: this.plannerFull(task), waitsFor: this.waitsFor(task), ...this.weights(task.class, task) }).owner) continue;
11512
9385
  // Budget keeps its original release/unassign behaviour for ordinary work. Roster changes the state in
11513
9386
  // assignOwner's same owner write only after routing has found somebody to take it.
11514
9387
  const back = !roster && task.state === "in_progress" ? this.d.board.update(task.id, HUB, "released", { state: "proposed" }, why) : task;
11515
9388
  let next: Task;
11516
9389
  try {
11517
- next = await this.assignOwner(back, HUB, { current, candidates, exclude: [peer], event: "reassigned", reason: roster ? "manual" : "budget", note: why, ...(roster ? { roster: true } : { clearOnFail: true }), ...(context ? { context, contextWithheld } : {}) });
9390
+ next = await this.assignOwner(back, HUB, { current, candidates, exclude: [peer, ...also], event: "reassigned", reason: roster ? "manual" : "budget", note: why, ...(roster ? { roster: true } : { clearOnFail: true }), ...(context ? { context, contextWithheld } : {}) });
11518
9391
  } catch (e) {
11519
9392
  // The move is saved and its central #297 notice already spoke; relay the
11520
9393
  // remaining tasks and run the roster tail on the saved row as on success.
@@ -11532,7 +9405,7 @@ export class Tasks {
11532
9405
  current?.();
11533
9406
  moved.push({ id: task.id, title: this.publicTitle(task), to: next.owner, role: "owner" });
11534
9407
  } else if (task.reviewer === peer && !isClosedTaskState(task.state)) {
11535
- const a = assign(task, this.states(), routing, { ...(roster ? { exclude: [peer] } : {}), candidates: [], ...(task.owner ? { notReviewer: task.owner } : {}), ...this.weights(task.class, task) });
9408
+ const a = assign(task, this.states(), routing, { ...(roster ? { exclude: [peer] } : also.length ? { exclude: [peer, ...also] } : {}), candidates: [], ...(task.owner ? { notReviewer: task.owner } : {}), ...this.weights(task.class, task) });
11536
9409
  const reviewer = !a.reviewSelection?.quotaWait && a.reviewer && a.reviewer !== peer && a.reviewer !== task.owner ? a.reviewer : null;
11537
9410
  if (roster && !reviewer) {
11538
9411
  this.releaseNotice(`task ${this.publicTitle(task)}: its reviewer ${peer} is off roster and nobody else can review; the reviewer stays ${peer}; use ahub review ${task.id}`);
@@ -11602,7 +9475,7 @@ export class Tasks {
11602
9475
  * #802: what `remember` answered and whether it stored anything, so a caller never decides that from the wording. `saved` is a note in shared memory, `candidate` one held for a person's
11603
9476
  * review (stored, not yet evidence), `not_saved` a note nothing took. A refusal still throws and never reaches here.
11604
9477
  */
11605
- async rememberOutcome(by: PeerId, input: RememberInput, review?: Task): Promise<{ message: string; outcome: "saved" | "candidate" | "not_saved" }> {
9478
+ async rememberOutcome(by: PeerId, input: RememberInput, review?: Task, writerSession?: string): Promise<{ message: string; outcome: "saved" | "candidate" | "not_saved" }> {
11606
9479
  const requestCheck = this.requestCheck(by);
11607
9480
  const text = composeRememberText(input);
11608
9481
  const task = input.task !== undefined ? this.d.board.get(Number(input.task)) : undefined;
@@ -11633,7 +9506,7 @@ export class Tasks {
11633
9506
  const id = this.d.candidates.put({ project: this.d.store.project, ...proposal.input }, "public", proposal.origin);
11634
9507
  return { message: `candidate:${id}; a memory review proposes only, and a person accepts it with amem review; task #${review.id} changed no note`, outcome: "candidate" };
11635
9508
  }
11636
- const native = this.saveNative(by, kind, text, title, task, input.horizon === "long" || input.horizon === "short" ? input.horizon : undefined, input.scope === "shared" ? "shared" : "project");
9509
+ const native = this.saveNative(by, kind, text, title, task, input.horizon === "long" || input.horizon === "short" ? input.horizon : undefined, input.scope === "shared" ? "shared" : "project", undefined, captureSessionKey(writerSession));
11637
9510
  if (native && "refused" in native) throw new PreEffectToolRefusal(`${native.refused}; save it with horizon "short" or correct the machine/repository privacy policy, then retry`);
11638
9511
  if (task && this.d.memory) this.markMemoryReference(task, by);
11639
9512
  const res = !native && this.d.memory ? await this.d.memory.save({ text, ...(title ? { title } : {}), project: this.d.project, metadata: { peer: by, kind, ...(task ? { task: task.id } : {}) } }) : undefined;
@@ -11689,7 +9562,7 @@ export class Tasks {
11689
9562
  * long, decisions, contracts and fails are long-term. Fail-open: a store that cannot be written costs one notice.
11690
9563
  * The caller has screened the text for PII; never a PII task's.
11691
9564
  */
11692
- private saveNative(by: PeerId, kind: Kind, text: string, title: string, task: Task | undefined, horizon?: Tier, scope: Scope = "project", symbols?: MemorySymbolNodes): { id: string; tier: Tier; about: string[] } | { refused: string } | undefined {
9565
+ private saveNative(by: PeerId, kind: Kind, text: string, title: string, task: Task | undefined, horizon?: Tier, scope: Scope = "project", symbols?: MemorySymbolNodes, session?: string): { id: string; tier: Tier; about: string[] } | { refused: string } | undefined {
11693
9566
  const st = this.d.store;
11694
9567
  if (!st || (task && this.isPii(task))) return undefined;
11695
9568
  let longTerm = horizon === "long" || (horizon !== "short" && !!task && task.state === "approved" && PROMOTED_KINDS.includes(kind));
@@ -11716,7 +9589,7 @@ export class Tasks {
11716
9589
  } catch { return { refused: "machine privacy policy unavailable" }; }
11717
9590
  }
11718
9591
  if (task) this.markMemoryReference(task, by);
11719
- const id = st.store.note(row, horizon === "short");
9592
+ const id = st.store.note(row, { ownClock: horizon === "short", ...(session === undefined ? {} : { session }) });
11720
9593
  try { st.onNote?.(id); } catch { /* The native note is committed; an observer cannot make it fail. */ }
11721
9594
  return { id, tier, about: [...about] };
11722
9595
  } catch (e) {