@staix/agent-hub 0.50.0 → 0.52.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (350) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/README.md +1 -1
  3. package/docs/adding-an-ai-tool.md +26 -4
  4. package/docs/agent-notes/README.md +1 -0
  5. package/docs/agent-notes/adapters.md +4 -3
  6. package/docs/agent-notes/budget.md +8 -2
  7. package/docs/agent-notes/daemon.md +13 -8
  8. package/docs/agent-notes/local-worker.md +3 -3
  9. package/docs/agent-notes/security-review.md +6 -5
  10. package/docs/agent-notes/tasks.md +10 -3
  11. package/docs/agent-notes/tests.md +4 -3
  12. package/docs/cooperbench.md +1 -1
  13. package/docs/design/adapters.md +21 -0
  14. package/docs/design/cli-output-inventory.md +165 -150
  15. package/docs/design/cli-output.md +4 -3
  16. package/docs/design/guidance-probes.md +1 -0
  17. package/docs/design/roadmap.md +3 -1
  18. package/docs/design/task-board.md +35 -0
  19. package/docs/dogfood.md +21 -3
  20. package/docs/events.md +4 -2
  21. package/docs/memory.md +5 -3
  22. package/docs/operations.md +259 -19
  23. package/docs/quickstart.md +29 -2
  24. package/docs/roadmap.json +20 -20
  25. package/docs/roadmap.md +2 -2
  26. package/docs/roles.md +1 -1
  27. package/docs/sdlc.md +29 -5
  28. package/docs/security.md +11 -5
  29. package/docs/specs/2026-09-19-agent-hub-design.md +44 -0
  30. package/docs/specs/2026-09-19-multi-project-design.md +4 -0
  31. package/docs/specs/2026-09-20-upgrade-recovery-design.md +17 -0
  32. package/docs/specs/mcp-endpoint.md +63 -0
  33. package/docs/verification/2026-11-29-agy-1.5.20.md +33 -0
  34. package/docs/verification/2026-11-29-claude-profile-hook.md +12 -0
  35. package/docs/verification/2026-11-29-idle-daemon-footprint.md +75 -0
  36. package/docs/verification/2026-11-29-kimi-281-reviewer-compat.md +38 -0
  37. package/docs/verification/2026-11-29-kimi-tui-281.md +12 -0
  38. package/docs/verification/2026-11-30-0.51.0.md +91 -0
  39. package/docs/verification/2026-11-30-account-switch-1806.md +445 -0
  40. package/docs/verification/2026-11-30-capability-listing-shape-1808.md +45 -0
  41. package/docs/verification/2026-11-30-upgrade-keep-1807.md +174 -0
  42. package/docs/verification/2026-12-01-1811-confirmation-receipt.md +19 -0
  43. package/docs/verification/2026-12-01-1811-orca-agent-list.md +20 -0
  44. package/docs/verification/2026-12-01-1811-orca-pane-key.md +21 -0
  45. package/docs/verification/2026-12-02-1819-claude-process-after-renewal.md +54 -0
  46. package/docs/verification/2026-12-02-agy-1.5.21.md +74 -0
  47. package/docs/verification/2026-12-02-claude-implementer-2.1.334.md +44 -0
  48. package/docs/verification/2026-12-02-cli-import-graph.md +33 -0
  49. package/docs/verification/2026-12-03-0.52.0.md +150 -0
  50. package/docs/verification/2026-12-03-codex-0173-reviewer-isolation.md +53 -0
  51. package/docs/verification/2026-12-03-codex-0173-reviewer-tool-call.md +34 -0
  52. package/docs/verification/2026-12-03-jcode-1.3.0.md +25 -0
  53. package/docs/verification/agy/README.md +17 -0
  54. package/docs/verification/agy/cli-surface.ts +68 -0
  55. package/docs/verification/agy/interactive-bridge.ts +92 -0
  56. package/docs/verification/agy/interactive-session.ts +131 -0
  57. package/docs/verification/agy/launcher-nonce.ts +215 -0
  58. package/docs/verification/agy/native-hooks.ts +210 -0
  59. package/docs/verification/agy/originals/agent-hub-681/cli-surface.ts +87 -0
  60. package/docs/verification/agy/originals/agent-hub-681/native-hooks-adapted.ts +91 -0
  61. package/docs/verification/agy/originals/agent-hub-681/tui-actual.ts +200 -0
  62. package/docs/verification/agy/originals/agent-hub-684/probe.ts +107 -0
  63. package/docs/verification/agy/originals.json +25 -0
  64. package/docs/verification/agy/permission-new-functions.ts +128 -0
  65. package/docs/verification/agy/run-probe.py +108 -0
  66. package/docs/verification/agy/runtime.ts +171 -0
  67. package/docs/verification/agy/tmux-helper-control.ts +6 -0
  68. package/docs/verification/agy/tmux-session.ts +235 -0
  69. package/docs/verified.json +87 -42
  70. package/package.json +3 -3
  71. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  72. package/plugins/agent-hub/compat.json +157 -0
  73. package/plugins/agent-hub/kimi-hook.js +1416 -24985
  74. package/plugins/agent-hub/server.js +17415 -32755
  75. package/scripts/check-docs.mjs +1 -1
  76. package/src/adapters/acp.ts +13 -13
  77. package/src/adapters/agy/definition.ts +9 -26
  78. package/src/adapters/agy/entry.ts +2 -0
  79. package/src/adapters/channel-peer.ts +3 -1
  80. package/src/adapters/claude-channel-evidence.ts +7 -3
  81. package/src/adapters/claude-channel.ts +38 -257
  82. package/src/adapters/claude-implementer.ts +3 -1
  83. package/src/adapters/codex-appserver.ts +77 -15
  84. package/src/adapters/compat.ts +78 -14
  85. package/src/adapters/configured-acp.ts +23 -163
  86. package/src/adapters/configured-adapter-policy.ts +160 -0
  87. package/src/adapters/configured-pull-entry.ts +53 -0
  88. package/src/adapters/configured-pull.ts +38 -0
  89. package/src/adapters/conformance/fakes/app-server.ts +9 -2
  90. package/src/adapters/declaration-catalog.ts +25 -0
  91. package/src/adapters/declaration-data.ts +342 -0
  92. package/src/adapters/declaration-resolution.ts +53 -0
  93. package/src/adapters/definitions/builtin-metadata.ts +62 -84
  94. package/src/adapters/definitions/jcode-launch.ts +13 -0
  95. package/src/adapters/definitions/native-adapter-policy.ts +390 -0
  96. package/src/adapters/definitions/native-cli-claude-launch.ts +6 -3
  97. package/src/adapters/definitions/native-cli-codex-launch.ts +2 -1
  98. package/src/adapters/definitions/native-cli-entry-claude.ts +17 -2
  99. package/src/adapters/definitions/native-cli-entry-codex.ts +2 -0
  100. package/src/adapters/definitions/native-cli-entry-jcode.ts +6 -2
  101. package/src/adapters/definitions/native-cli-entry-kimi.ts +2 -0
  102. package/src/adapters/definitions/native-cli-entry-pi.ts +2 -0
  103. package/src/adapters/definitions/native-cli-entry-qwen.ts +2 -0
  104. package/src/adapters/definitions/native-cli-entry-types.ts +12 -3
  105. package/src/adapters/definitions/native-cli-jcode-home-init.ts +1 -1
  106. package/src/adapters/definitions/native-cli-launch-common.ts +2 -2
  107. package/src/adapters/definitions/native-cli-preview-common.ts +1 -1
  108. package/src/adapters/definitions/native-cli-retained.ts +1 -1
  109. package/src/adapters/definitions/native-config-defaults.ts +1 -1
  110. package/src/adapters/definitions/native-configuration.ts +18 -0
  111. package/src/adapters/definitions/native-help.ts +24 -0
  112. package/src/adapters/definitions/native-launch-declarations.ts +34 -0
  113. package/src/adapters/definitions/native-launch-policy.ts +4 -0
  114. package/src/adapters/definitions/native-launch-settings.ts +72 -0
  115. package/src/adapters/definitions/native-light-cli.ts +18 -0
  116. package/src/adapters/definitions/native-light-preview.ts +10 -0
  117. package/src/adapters/definitions/native-wrapper-launch.ts +10 -0
  118. package/src/adapters/definitions/qwen.ts +6 -29
  119. package/src/adapters/definitions/reviewer-variants.ts +7 -8
  120. package/src/adapters/external-declarations.ts +31 -0
  121. package/src/adapters/external-modules.ts +4 -29
  122. package/src/adapters/jcode.ts +19 -12
  123. package/src/adapters/native-capabilities.ts +18 -8
  124. package/src/adapters/native-facts-hooks.ts +12 -0
  125. package/src/adapters/native-proof-ports.ts +1 -1
  126. package/src/adapters/presets.ts +136 -0
  127. package/src/adapters/qwen-dual.ts +2 -2
  128. package/src/adapters/registry-types.ts +3 -0
  129. package/src/adapters/registry.ts +20 -81
  130. package/src/adapters/reviewer-print.ts +26 -9
  131. package/src/adapters/role-eligibility.ts +2 -1
  132. package/src/cli/accounts-import.ts +72 -0
  133. package/src/cli/agents-latest-table.ts +88 -0
  134. package/src/cli/agents-latest.ts +22 -0
  135. package/src/cli/agents-output.ts +10 -0
  136. package/src/cli/agents-presets.ts +100 -0
  137. package/src/cli/agents.ts +1 -1
  138. package/src/cli/attention.ts +3 -2
  139. package/src/cli/autonomy-homes.ts +7 -2
  140. package/src/cli/autonomy-offline.ts +1 -1
  141. package/src/cli/bench.ts +1 -1
  142. package/src/cli/budget-renew-guidance.ts +129 -0
  143. package/src/cli/claude-homes.ts +9 -5
  144. package/src/cli/claude-profile-hook.ts +31 -11
  145. package/src/cli/command-context.ts +3 -0
  146. package/src/cli/command-table.ts +123 -0
  147. package/src/cli/commands/accounts.ts +8 -0
  148. package/src/cli/commands/agents.ts +18 -0
  149. package/src/cli/commands/answer.ts +28 -0
  150. package/src/cli/commands/ask.ts +17 -0
  151. package/src/cli/commands/autonomy.ts +83 -0
  152. package/src/cli/commands/backlog.ts +46 -0
  153. package/src/cli/commands/bench.ts +60 -0
  154. package/src/cli/commands/board.ts +48 -0
  155. package/src/cli/commands/broker.ts +9 -0
  156. package/src/cli/commands/budget.ts +96 -0
  157. package/src/cli/commands/capabilities.ts +12 -0
  158. package/src/cli/commands/check-path.ts +55 -0
  159. package/src/cli/commands/completion.ts +8 -0
  160. package/src/cli/commands/console.ts +12 -0
  161. package/src/cli/commands/daemon.ts +8 -0
  162. package/src/cli/commands/deliverables.ts +25 -0
  163. package/src/cli/commands/doctor.ts +249 -0
  164. package/src/cli/commands/down.ts +3 -0
  165. package/src/cli/commands/export.ts +15 -0
  166. package/src/cli/commands/facts.ts +15 -0
  167. package/src/cli/commands/goal.ts +22 -0
  168. package/src/cli/commands/guidance.ts +102 -0
  169. package/src/cli/commands/help.ts +17 -0
  170. package/src/cli/commands/host.ts +45 -0
  171. package/src/cli/commands/init.ts +121 -0
  172. package/src/cli/commands/instructed.ts +19 -0
  173. package/src/cli/commands/instruction-hook.ts +15 -0
  174. package/src/cli/commands/intake.ts +24 -0
  175. package/src/cli/commands/kill.ts +15 -0
  176. package/src/cli/commands/learn.ts +23 -0
  177. package/src/cli/commands/lineage.ts +30 -0
  178. package/src/cli/commands/logs.ts +21 -0
  179. package/src/cli/commands/manager.ts +15 -0
  180. package/src/cli/commands/memory.ts +21 -0
  181. package/src/cli/commands/model.ts +25 -0
  182. package/src/cli/commands/models.ts +40 -0
  183. package/src/cli/commands/native.ts +39 -0
  184. package/src/cli/commands/pause.ts +5 -0
  185. package/src/cli/commands/peer.ts +32 -0
  186. package/src/cli/commands/permission.ts +26 -0
  187. package/src/cli/commands/permit.ts +12 -0
  188. package/src/cli/commands/pet.ts +24 -0
  189. package/src/cli/commands/projects.ts +49 -0
  190. package/src/cli/commands/queue.ts +70 -0
  191. package/src/cli/commands/recovery-run.ts +13 -0
  192. package/src/cli/commands/recovery.ts +130 -0
  193. package/src/cli/commands/release.ts +23 -0
  194. package/src/cli/commands/releases.ts +91 -0
  195. package/src/cli/commands/remember.ts +6 -0
  196. package/src/cli/commands/report.ts +27 -0
  197. package/src/cli/commands/research.ts +53 -0
  198. package/src/cli/commands/reset.ts +89 -0
  199. package/src/cli/commands/restart.ts +5 -0
  200. package/src/cli/commands/results.ts +31 -0
  201. package/src/cli/commands/resume.ts +5 -0
  202. package/src/cli/commands/review.ts +24 -0
  203. package/src/cli/commands/roadmap.ts +21 -0
  204. package/src/cli/commands/role.ts +34 -0
  205. package/src/cli/commands/roles.ts +30 -0
  206. package/src/cli/commands/room.ts +14 -0
  207. package/src/cli/commands/roster.ts +48 -0
  208. package/src/cli/commands/route.ts +9 -0
  209. package/src/cli/commands/say.ts +21 -0
  210. package/src/cli/commands/schedule.ts +17 -0
  211. package/src/cli/commands/sdlc.ts +321 -0
  212. package/src/cli/commands/settings.ts +148 -0
  213. package/src/cli/commands/setup.ts +89 -0
  214. package/src/cli/commands/shared-refusals.ts +25 -0
  215. package/src/cli/commands/smoke.ts +44 -0
  216. package/src/cli/commands/source.ts +64 -0
  217. package/src/cli/commands/specs.ts +13 -0
  218. package/src/cli/commands/status.ts +28 -0
  219. package/src/cli/commands/stop.ts +17 -0
  220. package/src/cli/commands/structure.ts +60 -0
  221. package/src/cli/commands/study.ts +39 -0
  222. package/src/cli/commands/tail.ts +19 -0
  223. package/src/cli/commands/task.ts +114 -0
  224. package/src/cli/commands/title.ts +17 -0
  225. package/src/cli/commands/turns.ts +10 -0
  226. package/src/cli/commands/ui.ts +47 -0
  227. package/src/cli/commands/undo.ts +77 -0
  228. package/src/cli/commands/up.ts +39 -0
  229. package/src/cli/commands/upgrade.ts +5 -0
  230. package/src/cli/commands/usage.ts +33 -0
  231. package/src/cli/commands/version.ts +5 -0
  232. package/src/cli/commands/watch.ts +30 -0
  233. package/src/cli/commands/worktrees.ts +31 -0
  234. package/src/cli/conductor-recovery.ts +1 -1
  235. package/src/cli/console-state.ts +5 -138
  236. package/src/cli/console-versions.ts +1 -1
  237. package/src/cli/facts-hook.ts +11 -4
  238. package/src/cli/help.ts +44 -20
  239. package/src/cli/identity.ts +27 -4
  240. package/src/cli/init-prompt.ts +1 -1
  241. package/src/cli/init-settings.ts +4 -35
  242. package/src/cli/init.ts +1 -1
  243. package/src/cli/json-text-spans.ts +57 -0
  244. package/src/cli/launch-check.ts +156 -0
  245. package/src/cli/launch.ts +19 -70
  246. package/src/cli/light-dispatch.ts +29 -0
  247. package/src/cli/main.js +8 -1
  248. package/src/cli/main.ts +257 -2799
  249. package/src/cli/memory.ts +1 -1
  250. package/src/cli/orca-probe.ts +119 -0
  251. package/src/cli/output.ts +45 -3
  252. package/src/cli/preview.ts +11 -6
  253. package/src/cli/recovery-launch.ts +1 -1
  254. package/src/cli/recovery-version-preflight.ts +28 -9
  255. package/src/cli/replace-process.ts +22 -0
  256. package/src/cli/report-layout.ts +142 -0
  257. package/src/cli/roadmap-usage.ts +16 -0
  258. package/src/cli/roadmap.ts +3 -16
  259. package/src/cli/sdlc-doctor.ts +27 -0
  260. package/src/cli/sdlc-output.ts +55 -1
  261. package/src/cli/setup-homes.ts +2 -2
  262. package/src/cli/start-agents-run.ts +85 -7
  263. package/src/cli/start-check.ts +28 -0
  264. package/src/cli/statusline-tee.ts +25 -4
  265. package/src/cli/terminal-recovery.ts +53 -10
  266. package/src/cli/upgrade-interactive.ts +1 -0
  267. package/src/cli/upgrade-runtime.ts +12 -1
  268. package/src/cli/upgrade.ts +4 -15
  269. package/src/cli/warn-line.ts +1 -1
  270. package/src/hub/accounts.ts +148 -0
  271. package/src/hub/addons.ts +20 -0
  272. package/src/hub/agent-drift.ts +2 -1
  273. package/src/hub/budget-projection.ts +39 -7
  274. package/src/hub/budget.ts +231 -16
  275. package/src/hub/channel-project.ts +3 -3
  276. package/src/hub/ci-watch.ts +311 -79
  277. package/src/hub/conductor-peer.ts +24 -0
  278. package/src/hub/conductor.ts +2 -21
  279. package/src/hub/config-apply.ts +25 -14
  280. package/src/hub/config-edit.ts +1 -1
  281. package/src/hub/config-tier.ts +2 -0
  282. package/src/hub/config.ts +535 -0
  283. package/src/hub/control-client.ts +49 -1
  284. package/src/hub/daemon.ts +492 -569
  285. package/src/hub/delivery-public.ts +11 -0
  286. package/src/hub/events.ts +3 -0
  287. package/src/hub/home-tag.ts +12 -0
  288. package/src/hub/host.ts +217 -0
  289. package/src/hub/hub-check.ts +125 -0
  290. package/src/hub/hub-tools.ts +2 -1
  291. package/src/hub/instance-budget.ts +2 -2
  292. package/src/hub/instance-config.ts +15 -126
  293. package/src/hub/instances.ts +22 -6
  294. package/src/hub/instruction-receipt.ts +2 -2
  295. package/src/hub/kimi-usage.ts +38 -11
  296. package/src/hub/lifecycle.ts +86 -4
  297. package/src/hub/mcp-bridge-core.ts +98 -0
  298. package/src/hub/mcp-channel-push.ts +20 -0
  299. package/src/hub/mcp-endpoint-serve.ts +178 -0
  300. package/src/hub/mcp-endpoint.ts +226 -0
  301. package/src/hub/mcp-tool-call.ts +181 -0
  302. package/src/hub/operational-settings.ts +2 -0
  303. package/src/hub/orca-env.ts +6 -0
  304. package/src/hub/orca-state.ts +84 -0
  305. package/src/hub/path-policy.ts +1 -1
  306. package/src/hub/peers.ts +5 -1
  307. package/src/hub/permission-mode.ts +5 -41
  308. package/src/hub/permission-paths.ts +41 -0
  309. package/src/hub/project.ts +20 -0
  310. package/src/hub/protocol-window.ts +58 -0
  311. package/src/hub/quota-origin.ts +20 -0
  312. package/src/hub/recovery-policy.ts +1 -1
  313. package/src/hub/registry.ts +36 -2
  314. package/src/hub/releases-inventory.ts +198 -0
  315. package/src/hub/report.ts +1 -1
  316. package/src/hub/research.ts +1 -1
  317. package/src/hub/review-brief.ts +47 -2
  318. package/src/hub/roster.ts +6 -3
  319. package/src/hub/routing.ts +9 -2
  320. package/src/hub/runtime-capture-prune.ts +25 -3
  321. package/src/hub/runtime-prune-health.ts +8 -1
  322. package/src/hub/sdlc-check.ts +205 -0
  323. package/src/hub/sdlc-release-authorization.ts +42 -21
  324. package/src/hub/sdlc-release-diagnostics.ts +5 -0
  325. package/src/hub/sdlc-release-policy.ts +21 -7
  326. package/src/hub/sdlc-release.ts +80 -20
  327. package/src/hub/sdlc-sync.ts +146 -0
  328. package/src/hub/sdlc.ts +38 -5
  329. package/src/hub/settings.ts +7 -4
  330. package/src/hub/start-agents.ts +1 -1
  331. package/src/hub/start-mode.ts +11 -4
  332. package/src/hub/structure-budget.ts +131 -0
  333. package/src/hub/structure-scan.ts +149 -0
  334. package/src/hub/tasks-experiment.ts +455 -0
  335. package/src/hub/tasks-guidance.ts +606 -0
  336. package/src/hub/tasks-roadmap-plan.ts +419 -0
  337. package/src/hub/tasks-roadmap.ts +491 -0
  338. package/src/hub/tasks-study.ts +661 -0
  339. package/src/hub/tasks-survey.ts +192 -0
  340. package/src/hub/tasks.ts +457 -2584
  341. package/src/hub/terminal-open.ts +5 -3
  342. package/src/hub/tooling.ts +3 -19
  343. package/src/hub/usage-rollup.ts +9 -3
  344. package/src/local/tools.ts +5 -0
  345. package/src/ui/index.html +1 -1
  346. package/src/ui/needs.ts +17 -5
  347. package/src/ui/peer-palette.ts +2 -4
  348. package/src/ui/plugin.ts +1 -1
  349. package/templates/presets/agents.json +60 -0
  350. package/templates/presets/confirmation-matrix.json +8 -8
@@ -0,0 +1,419 @@
1
+ // #1830 S4b: the roadmap placement, triage, decomposition and import methods of `Tasks`, moved whole beside `tasks-roadmap.ts`. Same shape: an explicit `RoadmapPlanHost` of `Tasks` callbacks, delegating methods left in `Tasks`,
2
+ // no board write outside a `Tasks` callback, and the in-flight publish and accept sets live on the instance, never at module level.
3
+ import { parseMilestoneInput, milestoneId, milestoneLinkRef, type Milestone, type MilestoneSuggestion, type DecomposePart, type DecomposeIntake, type MilestoneDecomposition, type DecompositionAccept } from "./roadmap.ts";
4
+ import { milestoneViews, type MilestoneView } from "./roadmap-view.ts";
5
+ import { computeUnplaced, type UnplacedResult } from "./roadmap-unplaced.ts";
6
+ import { buildTriagePrompt, parseTriage, TRIAGE_BATCH, type TriageItem } from "./roadmap-triage.ts";
7
+ import { buildDecomposePrompt, parseDecomposition, planPartPublish, DECOMPOSE_ITEMS, DECOMPOSE_PATHS, type DecomposeItem, type PublishDraft, type PublishPlanPart } from "./roadmap-decompose.ts";
8
+ import { createHash } from "node:crypto";
9
+ import { types } from "node:util";
10
+ import { readGitHubIssuePages, readGitHubMilestonePages } from "./github-import.ts";
11
+ import { HOST_ROADMAP_DRAFT, CLASSES, type TaskClass } from "./board.ts";
12
+ import { HUB, sanitize, USER, type PeerId } from "./envelope.ts";
13
+ import { PreEffectToolRefusal } from "./tool-refusal.ts";
14
+ import { type SdlcGh } from "./sdlc.ts";
15
+ import type { Task, TaskPlan, TaskRefs, SpecTaskReport } from "./board.ts";
16
+ import type { MilestonePatch, MilestoneState } from "./roadmap.ts";
17
+ import type { RoadmapSnapshot } from "./roadmap-view.ts";
18
+ import type { SpecsCheckReport, SpecsCoverReport } from "./specs.ts";
19
+ import type { GitHubSource } from "./github-import.ts";
20
+ import type { PiiVerdict } from "./inference.ts";
21
+ import type { TaskRepositories } from "./task-repository.ts";
22
+ import type { Tasks, TasksDeps } from "./tasks.ts";
23
+
24
+ /** What the moved methods call back into `Tasks` for: each member is the `Tasks` member of that name, unchanged. */
25
+ export interface RoadmapPlanHost {
26
+ readonly incomingBacklog: Set<number>;
27
+ readonly isPii: (task: Pick<Task, "signals">) => boolean;
28
+ milestoneShow(by: PeerId, id: number): MilestoneView;
29
+ propose(by: PeerId, input: { title?: string; detail?: string; class?: string; role?: unknown; reason?: unknown; refs?: TaskRefs; plan?: TaskPlan; owner?: PeerId; after?: unknown; urgent?: unknown; needs_network?: unknown; needs_worktree?: unknown; backlog?: unknown; draft?: unknown; goal?: unknown; [HOST_ROADMAP_DRAFT]?: unknown }, external?: GitHubSource, created?: () => void, fence?: () => string | undefined, hostCreatedHook?: (task: Task) => void): Promise<Task>;
30
+ readonly publicMetadataText: (text: string) => boolean;
31
+ publicView(task: Task, fullHistory?: boolean): Record<string, unknown>;
32
+ releaseNotice(line: string, run?: () => unknown): void;
33
+ roadmapApplyAuthority(by: PeerId): void;
34
+ roadmapCurrent(id: unknown, state?: MilestoneState): Milestone;
35
+ roadmapGh(run?: SdlcGh): SdlcGh;
36
+ roadmapParsed<T>(read: () => T): T;
37
+ roadmapReadAuthority(by: PeerId): void;
38
+ roadmapRepo(raw: unknown): string | undefined;
39
+ roadmapRepository(): string;
40
+ roadmapResult(by: PeerId, id: number): MilestoneView;
41
+ roadmapScreen(fields: MilestonePatch): Promise<void>;
42
+ roadmapSnapshot(by: PeerId, specs?: () => SpecsCheckReport | SpecsCoverReport | undefined): RoadmapSnapshot;
43
+ roadmapWriteAuthority(by: PeerId): () => void;
44
+ screenCall(text: string): Promise<PiiVerdict>;
45
+ readonly screenOn: () => boolean;
46
+ }
47
+
48
+ export class RoadmapPlanDomain {
49
+ constructor(private readonly d: TasksDeps, private readonly host: RoadmapPlanHost) {}
50
+ private readonly roadmapPublishes = new Set<number>();
51
+ private readonly decompositionAccepts = new Map<string, Promise<unknown>>();
52
+
53
+
54
+ /** Issues, tasks and specs that no live milestone places, each with its reason. Private tasks are counted and never named. */
55
+ async roadmapUnplaced(by: PeerId, input: { repo?: unknown } = {}, run?: SdlcGh): Promise<UnplacedResult & { repo: string | null }> {
56
+ this.host.roadmapReadAuthority(by);
57
+ const repo = this.host.roadmapRepo(input.repo);
58
+ let issues: Awaited<ReturnType<typeof readGitHubIssuePages>> | undefined;
59
+ try { issues = await readGitHubIssuePages({ ...(repo === undefined ? {} : { repo }) }, this.host.roadmapGh(run)); } catch { issues = undefined; }
60
+ this.host.roadmapReadAuthority(by);
61
+ let specs: { id: string; title: string; status: string | null }[] | undefined;
62
+ try { const list = this.d.specsList?.(); if (list && !list.truncated && list.errors === 0) specs = list.specs; } catch { specs = undefined; }
63
+ const snapshot = this.host.roadmapSnapshot(by);
64
+ const result = computeUnplaced({ milestones: snapshot.milestones, links: snapshot.links, tasks: snapshot.tasks, issues, specs, issueOf: snapshot.issueOf, privateTask: snapshot.privateTask, publicText: snapshot.publicText });
65
+ return { ...result, repo: issues?.repo ?? repo ?? null };
66
+ }
67
+
68
+ /** Pending and settled suggestions as a caller may read them: public text only. */
69
+ milestoneSuggestions(by: PeerId, state?: MilestoneSuggestion["state"]): MilestoneSuggestion[] {
70
+ this.host.roadmapReadAuthority(by);
71
+ return this.d.board.suggestions(state).filter(row => this.suggestionPublic(row));
72
+ }
73
+
74
+ suggestionPublic(row: MilestoneSuggestion): boolean {
75
+ const text = [row.ref, row.citeItem, row.citeMilestone ?? "", row.proposal?.title ?? "", row.proposal?.outcome ?? ""].join("\n");
76
+ if (!this.host.publicMetadataText(text)) return false;
77
+ if (row.kind !== "task") return true;
78
+ const task = this.d.board.get(Number(row.ref));
79
+ return task !== undefined && !this.host.isPii(task) && !task.signals.includes("pii");
80
+ }
81
+
82
+ /**
83
+ * Ask the hub's model where unplaced items belong. The model sees only public text, answers are checked against what it was shown
84
+ * (ids offered, cited words present), saved as pending suggestions, and nothing is linked: that is `roadmapAccept`.
85
+ */
86
+ async roadmapTriage(by: PeerId, input: { repo?: unknown } = {}, run?: SdlcGh): Promise<{ suggestions: MilestoneSuggestion[]; asked: number; dropped: number; partial: boolean; unavailable: string | null }> {
87
+ const current = this.host.roadmapWriteAuthority(by);
88
+ const unplaced = await this.roadmapUnplaced(by, input, run);
89
+ current();
90
+ const snapshot = this.host.roadmapSnapshot(by), views = milestoneViews(snapshot);
91
+ const pending = new Set(this.d.board.suggestions("pending").map(row => `${row.kind}:${row.ref}`));
92
+ const items: TriageItem[] = [
93
+ ...unplaced.tasks.map(row => ({ kind: "task" as const, ref: String(row.id), text: row.title })),
94
+ ...unplaced.issues.map(row => ({ kind: "issue" as const, ref: row.ref, text: row.title })),
95
+ ...unplaced.specs.map(row => ({ kind: "spec" as const, ref: row.id, text: row.title })),
96
+ ].filter(item => !pending.has(`${item.kind}:${item.ref}`));
97
+ const live = views.filter(view => view.state !== "done" && view.state !== "dropped" && view.title !== "[withheld]");
98
+ const batch = items.slice(0, TRIAGE_BATCH);
99
+ const done = (suggestions: MilestoneSuggestion[], dropped: number, unavailable: string | null) => ({ suggestions, asked: batch.length, dropped, partial: unplaced.partial || items.length > batch.length, unavailable });
100
+ if (!batch.length) return done([], 0, null);
101
+ if (!this.d.roadmapModel) return done([], 0, "no hub model is configured for roadmap triage");
102
+ const prompt = buildTriagePrompt(batch, live.map(view => ({ id: view.id, title: view.title, outcome: view.outcome })));
103
+ const answer = await this.d.roadmapModel(prompt.system, prompt.user, () => { try { current(); return true; } catch { return false; } });
104
+ current();
105
+ if (!answer) return done([], 0, "the hub model gave no answer; retry ahub roadmap triage later");
106
+ const parsed = parseTriage(answer, prompt), saved: MilestoneSuggestion[] = [], at = this.d.now?.() ?? Date.now();
107
+ for (const row of parsed.suggestions) {
108
+ // Re-screen at the write: what is stored is public planning text only, and a milestone that has since settled is not a target.
109
+ if (row.milestone !== null) { const target = this.d.board.milestone(row.milestone); if (!target || ["done", "dropped"].includes(target.state)) continue; }
110
+ const text = [row.ref, row.citeItem, row.citeMilestone ?? "", row.proposal?.title ?? "", row.proposal?.outcome ?? ""].join("\n");
111
+ if (!this.host.publicMetadataText(text)) continue;
112
+ if (this.host.screenOn() && (await this.host.screenCall(text)).label !== "clear") continue;
113
+ current();
114
+ // A model's answer, attributed to the hub (never to the asker), is advisory data: no ask or memory path reads this table.
115
+ const made = this.d.board.addSuggestion(row, "hub", at);
116
+ if (made) saved.push(made);
117
+ }
118
+ return done(saved, parsed.dropped + parsed.suggestions.length - saved.length, null);
119
+ }
120
+
121
+ /**
122
+ * R2 (#1480) part 1: ask the hub's model how one milestone decomposes. The model sees only the milestone's public text, the
123
+ * 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
124
+ * model answer. Nothing is intaken, linked, published or accepted here.
125
+ */
126
+ async roadmapDecompose(by: PeerId, rawId: unknown, run?: SdlcGh): Promise<{ milestone: number; parts: DecomposePart[]; dropped: number; saved: MilestoneDecomposition | null; unavailable: string | null }> {
127
+ const current = this.host.roadmapWriteAuthority(by);
128
+ const id = this.host.roadmapParsed(() => milestoneId(rawId)), view = this.host.milestoneShow(by, id);
129
+ current();
130
+ 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");
131
+ const done = (parts: DecomposePart[], dropped: number, saved: MilestoneDecomposition | null, unavailable: string | null) => ({ milestone: id, parts, dropped, saved, unavailable });
132
+ const publicText = (value: string): boolean => { try { return this.host.publicMetadataText(value); } catch { return false; } };
133
+ let rows: { id: string; title: string; status: string | null; type?: string; paths?: string[] }[] | undefined;
134
+ try { const list = this.d.specsList?.(); if (list && !list.truncated && list.errors === 0) rows = list.specs; } catch { rows = undefined; }
135
+ const linked = new Set(view.specs.map(row => row.id));
136
+ // Every field that enters the prompt passes the same public screen R3's unplaced list uses; a spec that fails it is not
137
+ // offered at all, exactly as an unplaced spec is dropped from triage.
138
+ const summaries = (rows ?? []).filter(row => linked.has(row.id)
139
+ && [row.id, row.title, ...(row.type ? [row.type] : []), ...(row.status ? [row.status] : []), ...(row.paths ?? []).slice(0, DECOMPOSE_PATHS)].every(publicText));
140
+ // The milestone's own context is the goal and architecture specs it links; when it links only other types, those are its context.
141
+ const top = summaries.filter(row => row.type === "goal" || row.type === "architecture");
142
+ const specs: DecomposeItem[] = (top.length ? top : summaries).map(row => ({ ref: row.id, label: `spec ${row.id}`,
143
+ text: `${row.title} (${row.type || "spec"}${row.status ? `, ${row.status}` : ""})${row.paths?.length ? ` covers: ${row.paths.slice(0, DECOMPOSE_PATHS).join(", ")}` : ""}` }));
144
+ // Titles for linked issues come from the same bounded page read R3 uses. A ref outside that repository, an unreadable
145
+ // 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
146
+ // links are the only source of refs.
147
+ const refs = view.issues.map(row => row.ref), first = refs.length ? /^([^#]+)#[1-9][0-9]*$/.exec(refs[0]!)![1]! : undefined;
148
+ const titles = new Map<string, string>();
149
+ if (first !== undefined) {
150
+ try { const page = await readGitHubIssuePages({ repo: first }, this.host.roadmapGh(run)); current(); for (const row of page.rows) if (publicText(row.title)) titles.set(`${page.repo}#${row.number}`, row.title); }
151
+ catch { /* unavailable titles are not an empty list: the ref is still offered */ }
152
+ }
153
+ const issues: DecomposeItem[] = refs.map(ref => ({ ref, label: `issue ${ref}`, text: titles.get(ref) ?? "" }));
154
+ if (!specs.length && !issues.length) return done([], 0, null, "the milestone links no spec or issue to decompose from");
155
+ if (!this.d.roadmapModel) return done([], 0, null, "no hub model is configured for roadmap decompose");
156
+ const prompt = buildDecomposePrompt({ milestone: { id, title: view.title, outcome: view.outcome }, specs: specs.slice(0, DECOMPOSE_ITEMS), issues: issues.slice(0, DECOMPOSE_ITEMS) });
157
+ const answer = await this.d.roadmapModel(prompt.system, prompt.user, () => { try { current(); return true; } catch { return false; } });
158
+ current();
159
+ if (!answer) return done([], 0, null, "the hub model gave no answer; retry ahub roadmap decompose later");
160
+ const parsed = parseDecomposition(answer, prompt), kept: DecomposePart[] = [];
161
+ for (const part of parsed.parts) {
162
+ // Re-screen at the write, exactly as triage does: what is stored is public planning text only.
163
+ const text = [part.title, part.detail, ...part.cites].join("\n");
164
+ if (!this.host.publicMetadataText(text)) continue;
165
+ if (this.host.screenOn() && (await this.host.screenCall(text)).label !== "clear") continue;
166
+ current(); kept.push(part);
167
+ }
168
+ const dropped = parsed.dropped + parsed.parts.length - kept.length;
169
+ if (!kept.length) return done([], dropped, null, null);
170
+ const saved = this.d.board.addDecomposition({ milestone: id, parts: kept }, HUB, this.d.now?.() ?? Date.now());
171
+ return done(kept, dropped, saved, null);
172
+ }
173
+
174
+ /**
175
+ * R2 (#1480) part 2: accept one proposed part as a held intake draft. The draft is the existing intake hold (`draft` and
176
+ * `backlog`): nothing offers, pulls or routes it until the person approves it with `ahub intake approve`, and this path grants
177
+ * no new release authority. It carries the milestone link and the part's `spec`/`task` kind, each part is accepted on its own,
178
+ * 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
179
+ * reads `[withheld]` and no notice repeats the part's words. One accept per part runs at a time: a concurrent caller waits for
180
+ * the attempt in flight and then reads the accept row, so two accepts of one part cannot make two drafts.
181
+ */
182
+ async roadmapDecomposePart(by: PeerId, rawId: unknown, rawPart: unknown): Promise<{ milestone: number; part: number; intake: DecomposeIntake; task: Record<string, unknown>; created: boolean }> {
183
+ const current = this.host.roadmapWriteAuthority(by);
184
+ const id = this.host.roadmapParsed(() => milestoneId(rawId)), part = this.host.roadmapParsed(() => milestoneId(rawPart));
185
+ const view = this.host.milestoneShow(by, id);
186
+ current();
187
+ 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");
188
+ const pending = this.d.board.pendingDecomposition(id);
189
+ if (!pending) throw new PreEffectToolRefusal(`milestone ${id} has no pending decomposition; run ahub roadmap decompose ${id} first`);
190
+ 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`);
191
+ const chosen = pending.parts[part - 1]!;
192
+ // A retry reads the draft the first accept made, and records the link again if an interrupted tail lost it.
193
+ const earlier = this.roadmapAcceptedPart(by, id, pending.id, part);
194
+ if (earlier) return earlier;
195
+ const taskClass = CLASSES.includes(chosen.class as TaskClass) ? chosen.class as TaskClass : undefined;
196
+ if (!taskClass) throw new PreEffectToolRefusal(`part ${part} names no hub task class; run ahub roadmap decompose ${id} to replace the answer`);
197
+ // A milestone settled while its answer was pending refuses here, before any write. The same check runs again where the link
198
+ // is written, and there it is best-effort: the draft is durable by then.
199
+ this.host.roadmapCurrent(id);
200
+ current();
201
+ // One accept per part: a concurrent caller of the same part waits for the attempt in flight and then reads the accept row.
202
+ const key = `${pending.id}:${part}`, running = this.decompositionAccepts.get(key);
203
+ if (running) {
204
+ await running.catch(() => undefined);
205
+ const after = this.roadmapAcceptedPart(by, id, pending.id, part);
206
+ if (after) return after;
207
+ 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`);
208
+ }
209
+ const attempt = this.acceptDecompositionPartOnce(by, id, part, pending, chosen, taskClass);
210
+ this.decompositionAccepts.set(key, attempt);
211
+ try { return await attempt; } finally { if (this.decompositionAccepts.get(key) === attempt) this.decompositionAccepts.delete(key); }
212
+ }
213
+
214
+ /** The accept row's own draft, while that task exists: the retry's answer, with the milestone link recorded again. */
215
+ roadmapAcceptedPart(by: PeerId, id: number, decomposition: number, part: number): { milestone: number; part: number; intake: DecomposeIntake; task: Record<string, unknown>; created: boolean } | undefined {
216
+ const accepted = this.d.board.decompositionAccept(decomposition, part), earlier = accepted ? this.d.board.get(accepted.task) : undefined;
217
+ if (!accepted || !earlier) return undefined;
218
+ // Idempotent, so a missing link heals here; a milestone settled since refuses that as a notice, never as the caller's refusal.
219
+ this.host.releaseNotice(`task #${earlier.id}: milestone ${id} part ${part} accepted without its milestone link`, () => {
220
+ const milestone = this.host.roadmapCurrent(id);
221
+ this.d.board.linkMilestone(id, "task", String(earlier.id), by, milestone.revision, this.d.now?.() ?? Date.now());
222
+ });
223
+ return { milestone: id, part, intake: accepted.intake, task: this.host.publicView(earlier), created: false };
224
+ }
225
+
226
+ /** One accept attempt: the durable draft, then a tail that records the hold and never refuses the caller. */
227
+ 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 }> {
228
+ const draft = await this.host.propose(by, { [HOST_ROADMAP_DRAFT]: true, title: chosen.title, detail: this.decompositionDraftDetail(chosen, id, part, pending.parts.length), class: taskClass, backlog: true, draft: true });
229
+ // 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
230
+ // accept row, the milestone link and the notice are best-effort in that order.
231
+ this.host.incomingBacklog.delete(draft.id);
232
+ this.host.releaseNotice(`task #${draft.id}: milestone ${id} part ${part} accepted without its accept record`, () => {
233
+ this.d.board.acceptDecompositionPart({ decomposition: pending.id, milestone: id, part, task: draft.id, intake: chosen.intake }, by, this.d.now?.() ?? Date.now());
234
+ });
235
+ this.host.releaseNotice(`task #${draft.id}: milestone ${id} part ${part} accepted without its milestone link`, () => {
236
+ const milestone = this.host.roadmapCurrent(id);
237
+ this.d.board.linkMilestone(id, "task", String(draft.id), by, milestone.revision, this.d.now?.() ?? Date.now());
238
+ });
239
+ this.host.releaseNotice(`task #${draft.id}: milestone ${id} part ${part} accepted as a held intake draft`);
240
+ return { milestone: id, part, intake: chosen.intake, task: this.host.publicView(this.d.board.get(draft.id) ?? draft), created: true };
241
+ }
242
+
243
+ /** The held draft's detail: the part's own words, then the one line a person reads before releasing it. */
244
+ decompositionDraftDetail(part: DecomposePart, milestone: number, index: number, total: number): string {
245
+ const kind = part.intake === "spec" ? "needs its own spec issue before implementation" : "a mechanical chore that goes straight to a task";
246
+ return [part.detail, `Milestone ${milestone} part ${index} of ${total}: ${kind}. Cites: ${part.cites.join(", ")}.`, `Held until released: ahub intake approve`].join("\n\n");
247
+ }
248
+
249
+ /**
250
+ * R2 (#1480) part 3: publish the milestone's held drafts to GitHub. `--publish` plans one issue per held `spec` part from a
251
+ * complete reading of the holds and writes nothing; apply creates each issue through one gh call and links it to the
252
+ * milestone: R1's own `issue` link, and the R4 membership field the create carries when the mirror has a binding, so this
253
+ * 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
254
+ * is only counted, and a refused or unconfirmed call leaves the draft held and names the failure.
255
+ */
256
+ async roadmapDecomposePublish(by: PeerId, rawId: unknown, input: { apply?: boolean; confirm?: string } = {}): Promise<{
257
+ milestone: number; repo: string; githubMilestone: number | null; parts: PublishPlanPart[]; calls: string[][];
258
+ skippedPrivate: number; skippedUnknown: number; fingerprint: string; applied: boolean; created: { part: number; task: number; issue: number }[];
259
+ }> {
260
+ const current = this.host.roadmapWriteAuthority(by);
261
+ if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some(key => key !== "apply" && key !== "confirm")
262
+ || input.apply !== undefined && typeof input.apply !== "boolean"
263
+ || input.confirm !== undefined && (typeof input.confirm !== "string" || !/^[a-f0-9]{64}$/.test(input.confirm)))
264
+ throw new PreEffectToolRefusal("invalid roadmap publish options; preview with ahub roadmap decompose <id> --publish before applying");
265
+ if (input.apply && input.confirm === undefined) throw new PreEffectToolRefusal("roadmap decompose --apply needs its preview fingerprint; preview with ahub roadmap decompose <id> --publish first");
266
+ if (input.apply) this.host.roadmapApplyAuthority(by);
267
+ const id = this.host.roadmapParsed(() => milestoneId(rawId)), view = this.host.milestoneShow(by, id);
268
+ 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");
269
+ // A milestone settled while its drafts are held refuses here, before any read of GitHub or any write.
270
+ this.host.roadmapCurrent(id);
271
+ current();
272
+ const repo = this.host.roadmapRepository(), config = this.d.roadmapConfig?.() ?? { github_mirror: false, github_write: "off" as const };
273
+ // The GitHub milestone comes from the mirror binding, never from an argument; with the mirror off nothing is attached.
274
+ const githubMilestone = config.github_mirror ? this.d.board.mirrorMilestone(repo, id) ?? null : null;
275
+ const drafts: PublishDraft[] = [], held = new Map<number, DecompositionAccept>();
276
+ let skippedPrivate = 0, skippedUnknown = 0;
277
+ for (const accept of this.d.board.decompositionAcceptsFor(id)) {
278
+ const task = this.d.board.get(accept.task);
279
+ if (!task) continue;
280
+ const part = this.d.board.decomposition(accept.decomposition)?.parts[accept.part - 1];
281
+ // Without the answer a part's own words are gone; the draft stays held and the preview says to propose the parts again.
282
+ const text = part ? [part.title, part.detail, ...part.cites].join("\n") : "";
283
+ let privatePart = true;
284
+ try { privatePart = this.host.isPii(task) || !part || !this.host.publicMetadataText(text); } catch { privatePart = true; }
285
+ if (part && !privatePart && this.host.screenOn()) { const label = (await this.host.screenCall(text)).label; current(); privatePart = label !== "clear"; }
286
+ if (!part) { skippedUnknown++; continue; }
287
+ if (privatePart) { skippedPrivate++; continue; }
288
+ held.set(task.id, accept);
289
+ drafts.push({ part: accept.part, task: task.id, intake: accept.intake, title: part.title, detail: part.detail, cites: part.cites,
290
+ published: this.d.board.decompositionPublish(accept.decomposition, accept.part) ?? null,
291
+ hold: task.draft === true && task.state === "backlog" ? "held" : "released" });
292
+ }
293
+ const planned = planPartPublish({ project: this.d.project, repo, milestone: id, githubMilestone, parts: drafts });
294
+ const fingerprint = createHash("sha256").update(JSON.stringify({ repo, milestone: id, githubMilestone, calls: planned.calls })).digest("hex");
295
+ const reply = { milestone: id, repo, githubMilestone, ...planned, skippedPrivate, skippedUnknown, fingerprint, applied: false as boolean, created: [] as { part: number; task: number; issue: number }[] };
296
+ if (!input.apply) return reply;
297
+ if (input.confirm !== fingerprint) throw new PreEffectToolRefusal(`roadmap publish preview changed; run ahub roadmap decompose ${id} --publish and retry with --confirm ${fingerprint}`);
298
+ current(); this.host.roadmapApplyAuthority(by); if (this.host.roadmapRepository() !== repo) throw new PreEffectToolRefusal("roadmap GitHub origin changed; preview the publish again");
299
+ // A retried call whose first attempt is still creating must not POST every planned issue again: `INSERT OR IGNORE` would keep
300
+ // the first publish row and GitHub would keep both issues. One apply per milestone, refused with the next step it can take.
301
+ if (this.roadmapPublishes.has(id))
302
+ throw new PreEffectToolRefusal(`a publish for milestone ${id} is already running; wait for it to finish and run ahub roadmap decompose ${id} --publish again`);
303
+ this.roadmapPublishes.add(id);
304
+ try {
305
+ const creating = planned.parts.filter(row => row.action === "create"), created = reply.created;
306
+ for (const [index, call] of planned.calls.entries()) {
307
+ const row = creating[index]!, accept = held.get(row.task)!;
308
+ // A part an earlier attempt already recorded has its issue: never POST it a second time.
309
+ if (this.d.board.decompositionPublish(accept.decomposition, row.part) !== undefined) continue;
310
+ 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`;
311
+ let result: Awaited<ReturnType<SdlcGh>>;
312
+ try { result = await this.host.roadmapGh()(call, 10_000, undefined, 64 * 1024); }
313
+ 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`); }
314
+ if (result.code !== 0 || Buffer.byteLength(result.stdout) > 64 * 1024) throw new Error(refused);
315
+ let issue: number;
316
+ try {
317
+ const made = JSON.parse(result.stdout) as Record<string, unknown>;
318
+ issue = milestoneId(made.number);
319
+ if (made.title !== call.find(value => value.startsWith("title="))?.slice(6)
320
+ || typeof made.html_url !== "string" || made.html_url.toLowerCase() !== `https://github.com/${repo}/issues/${issue}`) throw new Error("mismatch");
321
+ } 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`); }
322
+ // The issue exists, so nothing below may refuse the caller: the publish record and the milestone link are best effort.
323
+ this.host.releaseNotice(`milestone ${id} part ${row.part}: issue ${repo}#${issue} created without its publish record`, () => {
324
+ this.d.board.recordDecompositionPublish({ decomposition: accept.decomposition, milestone: id, part: row.part, issue }, by, this.d.now?.() ?? Date.now());
325
+ });
326
+ this.host.releaseNotice(`milestone ${id} part ${row.part}: issue ${repo}#${issue} created without its milestone link`, () => {
327
+ const milestone = this.host.roadmapCurrent(id);
328
+ this.d.board.linkMilestone(id, "issue", `${repo}#${issue}`, by, milestone.revision, this.d.now?.() ?? Date.now());
329
+ });
330
+ created.push({ part: row.part, task: row.task, issue });
331
+ }
332
+ reply.applied = true;
333
+ return reply;
334
+ } finally { this.roadmapPublishes.delete(id); }
335
+ }
336
+
337
+ /** Apply one suggestion through R1's own writers. A "new milestone" suggestion creates it first; a retry never creates a second. */
338
+ async roadmapAccept(by: PeerId, rawId: unknown): Promise<{ suggestion: MilestoneSuggestion; milestone: MilestoneView }> {
339
+ const current = this.host.roadmapWriteAuthority(by);
340
+ const id = this.host.roadmapParsed(() => milestoneId(rawId)), row = this.d.board.suggestion(id);
341
+ if (!row) throw new PreEffectToolRefusal("roadmap suggestion does not exist; use ahub roadmap triage");
342
+ if (row.state !== "pending") throw new PreEffectToolRefusal(`roadmap suggestion was already ${row.state}; run ahub roadmap triage for current suggestions`);
343
+ if (!this.suggestionPublic(row)) throw new PreEffectToolRefusal("roadmap suggestion text is no longer public; reject it with ahub roadmap reject");
344
+ let target = row.milestone ?? this.d.board.suggestionCreated(id);
345
+ if (target === undefined) {
346
+ const proposal = row.proposal;
347
+ if (!proposal) throw new PreEffectToolRefusal("roadmap suggestion has no target; reject it with ahub roadmap reject");
348
+ const fields = this.host.roadmapParsed(() => parseMilestoneInput({ title: proposal.title, outcome: proposal.outcome }));
349
+ await this.host.roadmapScreen(fields); current();
350
+ const made = this.d.board.newMilestone(fields, by, this.d.now?.() ?? Date.now());
351
+ this.d.board.setSuggestionCreated(id, made.id); target = made.id;
352
+ }
353
+ const milestone = this.host.roadmapCurrent(target);
354
+ const ref = this.host.roadmapParsed(() => milestoneLinkRef(row.kind, row.ref));
355
+ 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");
356
+ current();
357
+ this.d.board.linkMilestone(target, row.kind, ref, by, milestone.revision, this.d.now?.() ?? Date.now());
358
+ const settled = this.d.board.settleSuggestion(id, "accepted", by, this.d.now?.() ?? Date.now());
359
+ return { suggestion: settled, milestone: this.host.roadmapResult(by, target) };
360
+ }
361
+
362
+ roadmapReject(by: PeerId, rawId: unknown): MilestoneSuggestion {
363
+ this.host.roadmapWriteAuthority(by);
364
+ const id = this.host.roadmapParsed(() => milestoneId(rawId));
365
+ return this.d.board.settleSuggestion(id, "rejected", by, this.d.now?.() ?? Date.now());
366
+ }
367
+
368
+ /**
369
+ * One-time import of open GitHub milestones as `proposed` milestones, linking their open issues. A dry run unless `apply`.
370
+ * A repeat finds each milestone's import mark and each link, so a second `apply` changes nothing. Nothing is ever written to GitHub.
371
+ */
372
+ async roadmapImportGitHub(by: PeerId, input: { repo?: unknown; apply?: unknown } = {}, run?: SdlcGh): Promise<{
373
+ 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;
374
+ }> {
375
+ const current = this.host.roadmapWriteAuthority(by);
376
+ if (by !== USER) throw new PreEffectToolRefusal("GitHub milestone import is a console command; ask the person to run ahub roadmap import-github");
377
+ 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");
378
+ const apply = input.apply === true, gh = this.host.roadmapGh(run), repoInput = this.host.roadmapRepo(input.repo);
379
+ const milestonePages = await readGitHubMilestonePages({ ...(repoInput === undefined ? {} : { repo: repoInput }) }, gh);
380
+ const issuePages = await readGitHubIssuePages({ repo: milestonePages.repo }, gh);
381
+ current();
382
+ const issuesOf = new Map<number, string[]>();
383
+ for (const row of issuePages.rows) if (row.milestone !== null) issuesOf.set(row.milestone, [...(issuesOf.get(row.milestone) ?? []), `${issuePages.repo}#${row.number}`]);
384
+ const out: { number: number; title: string; milestone: number | null; action: "create" | "exists"; issues: string[]; newLinks: number }[] = [];
385
+ let created = 0, linked = 0, withheld = 0;
386
+ for (const source of milestonePages.rows) {
387
+ const description = source.description || `Imported from GitHub milestone ${milestonePages.repo}#milestone/${source.number}`;
388
+ let fields: ReturnType<typeof parseMilestoneInput>;
389
+ try { fields = parseMilestoneInput({ title: source.title, outcome: description.slice(0, 4000), ...(source.due ? { target: source.due } : {}) }); }
390
+ catch { withheld++; continue; }
391
+ const prior = this.d.board.importedMilestone(milestonePages.repo, source.number), existing = prior === undefined ? undefined : this.d.board.milestone(prior);
392
+ const refs = (issuesOf.get(source.number) ?? []).filter(ref => this.host.publicMetadataText(ref));
393
+ const have = new Set(existing ? this.d.board.milestoneLinks(existing.id).filter(link => link.kind === "issue").map(link => link.ref) : []);
394
+ const newRefs = refs.filter(ref => !have.has(ref));
395
+ const text = `${fields.title}\n${fields.outcome}`;
396
+ if (!this.host.publicMetadataText(text)) { withheld++; continue; }
397
+ 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 };
398
+ if (apply) {
399
+ // The model screen runs on apply only, for a milestone about to be created; a dry run lists what passes the pattern screen.
400
+ if (!existing && this.host.screenOn() && (await this.host.screenCall(text)).label !== "clear") { withheld++; continue; }
401
+ current();
402
+ const made = this.d.board.importMilestone(milestonePages.repo, source.number, fields, by, this.d.now?.() ?? Date.now());
403
+ if (made.created) created++;
404
+ row.milestone = made.milestone.id;
405
+ for (const ref of newRefs) {
406
+ const live = this.d.board.milestone(made.milestone.id)!;
407
+ // A settled milestone is final: an import never reopens or relinks it.
408
+ if (["done", "dropped"].includes(live.state)) break;
409
+ const before = this.d.board.milestoneLinks(made.milestone.id).length;
410
+ this.d.board.linkMilestone(made.milestone.id, "issue", ref, by, live.revision, this.d.now?.() ?? Date.now());
411
+ if (this.d.board.milestoneLinks(made.milestone.id).length > before) linked++;
412
+ }
413
+ }
414
+ out.push(row);
415
+ }
416
+ return { repo: milestonePages.repo, apply, partial: milestonePages.partial || issuePages.partial, milestones: out, created, linked, withheld };
417
+ }
418
+
419
+ }