@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
@@ -4,7 +4,7 @@ export type ReleaseVersionPolicy =
4
4
  | { source: "package.json" }
5
5
  | { source: "release-notes"; notesPath: string }
6
6
  | { source: "none" };
7
- export type ReleaseDocsPolicy = { source: "checker" } | { source: "none" };
7
+ export type ReleaseDocsPolicy = { source: "checker" } | { source: "none" } | { source: "command"; path: string; blob?: string };
8
8
  export interface ReleasePolicy { version: ReleaseVersionPolicy; docs: ReleaseDocsPolicy }
9
9
 
10
10
  export const DEFAULT_RELEASE_POLICY: ReleasePolicy = {
@@ -40,12 +40,21 @@ export function parseReleasePolicy(config: unknown): ReleasePolicy {
40
40
  throw new Error("release.version in committed .agenthub/config.json must be package.json, release-notes or none");
41
41
  }
42
42
  const rawDocs = release.docs === undefined ? "checker" : release.docs;
43
- if (rawDocs !== "checker" && rawDocs !== "none") throw new Error("release.docs in committed .agenthub/config.json must be checker or none");
43
+ let docs: ReleaseDocsPolicy;
44
+ if (rawDocs === "checker" || rawDocs === "none") docs = { source: rawDocs };
45
+ else {
46
+ const command = record(rawDocs), path = command?.command;
47
+ if (!command || Object.keys(command).length !== 1 || typeof path !== "string" || path.length > 1024
48
+ || /[\p{Cc}\\:*?\[\]]/u.test(path) || path.split("/").some(part => !part || part === "." || part === ".." || part.startsWith("-"))) {
49
+ throw new Error('release.docs in committed .agenthub/config.json must be checker, none or { "command": "<safe repository-relative path>" }');
50
+ }
51
+ docs = { source: "command", path };
52
+ }
44
53
  const notesPath = checkedNotesPath(release.notesPath === undefined ? DEFAULT_RELEASE_NOTES_PATH : release.notesPath);
45
54
  return {
46
55
  version: rawVersion === "release-notes" ? { source: rawVersion, notesPath }
47
56
  : rawVersion === "none" ? { source: rawVersion } : { source: rawVersion },
48
- docs: rawDocs === "none" ? { source: rawDocs } : { source: rawDocs },
57
+ docs,
49
58
  };
50
59
  }
51
60
 
@@ -61,15 +70,15 @@ function treeEntry(git: ReleaseGit, commit: string, path: string): TreeEntry | u
61
70
  return { mode: match[1]!, type: match[2]!, oid: match[3]!, path: match[4]! };
62
71
  }
63
72
 
64
- function regularBlob(git: ReleaseGit, commit: string, path: string): boolean {
73
+ function regularBlob(git: ReleaseGit, commit: string, path: string): TreeEntry | undefined {
65
74
  const parts = path.split("/");
66
75
  for (let index = 1; index < parts.length; index++) {
67
76
  const parent = parts.slice(0, index).join("/");
68
77
  const entry = treeEntry(git, commit, parent);
69
- if (!entry || entry.mode !== "040000" || entry.type !== "tree") return false;
78
+ if (!entry || entry.mode !== "040000" || entry.type !== "tree") return undefined;
70
79
  }
71
80
  const file = treeEntry(git, commit, path);
72
- return !!file && (file.mode === "100644" || file.mode === "100755") && file.type === "blob";
81
+ return file && (file.mode === "100644" || file.mode === "100755") && file.type === "blob" ? file : undefined;
73
82
  }
74
83
 
75
84
  /** Read policy only from the candidate commit. Missing shared config means the legacy defaults; unreadable data fails closed. */
@@ -91,10 +100,15 @@ export function readCommittedReleasePolicy(git: ReleaseGit, commit: string): Rel
91
100
  if (policy.docs.source === "none" && regularBlob(git, commit, "docs/verified.json")) {
92
101
  throw new Error("release.docs is none but the candidate commits docs/verified.json; remove release.docs from .agenthub/config.json or delete the manifest, then authorize again");
93
102
  }
103
+ if (policy.docs.source === "command") {
104
+ const file = regularBlob(git, commit, policy.docs.path);
105
+ if (!file) throw new Error(`project checker ${policy.docs.path} must be a regular file at the candidate commit; commit the checker and authorize again`);
106
+ return { ...policy, docs: { ...policy.docs, blob: file.oid } };
107
+ }
94
108
  return policy;
95
109
  }
96
110
 
97
111
  /** Ensure every directory component and the final notes path are committed as non-symlink tree/blob entries. */
98
112
  export function hasCommittedReleaseNotes(git: ReleaseGit, commit: string, path: string): boolean {
99
- try { return regularBlob(git, commit, path); } catch { return false; }
113
+ try { return !!regularBlob(git, commit, path); } catch { return false; }
100
114
  }
@@ -1,10 +1,13 @@
1
1
  import type { Task } from "./board.ts";
2
2
  import type { Release } from "./planning.ts";
3
3
  import { spawn } from "node:child_process";
4
- import { existsSync } from "node:fs";
4
+ import { existsSync, lstatSync } from "node:fs";
5
+ import { dirname, join } from "node:path";
5
6
  import { fileURLToPath } from "node:url";
6
7
  import { childEnv, stopOwnedProcess } from "./child-process.ts";
7
- import { hubGitSync } from "./git.ts";
8
+ import { hubGitSync, hubGitEnv } from "./git.ts";
9
+ import { realPath } from "./project.ts";
10
+ import type { ReleaseDocsPolicy } from "./sdlc-release-policy.ts";
8
11
  import type { SdlcGh } from "./sdlc.ts";
9
12
  // Standalone document evidence does not need lifecycle/review code; load the default remote reader only when used.
10
13
  let importDiagnosticShown = false;
@@ -21,15 +24,18 @@ const sdlcGh: SdlcGh = async (...args) => {
21
24
  try { return await reader.sdlcGh(...args); }
22
25
  catch { return { code: 1, stdout: "" }; }
23
26
  };
24
- export interface DocEvidence { schemaVersion: 1; head?: string; version?: string; documents: { path?: string; state: "fresh" | "stale" | "nonancestor" | "unknown"; verifiedAgainst?: string; commits?: number; dirty?: boolean }[]; errors: number; fresh: boolean; }
27
+ export interface DocEvidence { schemaVersion: 1; head?: string; version?: string; documents: { path?: string; state: "fresh" | "stale" | "nonancestor" | "unknown"; verifiedAgainst?: string; commits?: number; dirty?: boolean }[]; errors: number; fresh: boolean; messages?: string[]; }
25
28
  export type ReleaseReportSource = "package.json" | "release-notes" | "none" | "unknown";
26
- export type ReleaseReportDocsSource = "checker" | "none" | "unknown";
29
+ export type ReleaseReportDocsSource = "checker" | "none" | "command" | "unknown";
30
+ type ProjectChecker = Extract<ReleaseDocsPolicy, { source: "command" }>;
27
31
  export type ReleaseReportAuthorizationState = "matched" | "missing" | "stale" | "unavailable";
28
32
  export interface ReleaseReportPolicy {
29
33
  versionSource: ReleaseReportSource;
30
34
  docsSource: ReleaseReportDocsSource;
31
35
  authorization: ReleaseReportAuthorizationState;
32
36
  version?: string;
37
+ /** Host-only checker selection. Public readiness copies only the policy summary. */
38
+ checker?: ProjectChecker;
33
39
  }
34
40
  export interface ReleaseReadiness { /** #1403 A4: the newest security audit as counts only (ref, profile, partial, unit states, finding tallies); never a path, a finding or a blocker. */ securityAudit?: import("./security-audit.ts").AuditSummary; /** #481 AC12: interval, approval-to-release lead time and hotfix rate over shipped releases, filled by Tasks.releaseReadiness. */ releaseMetrics?: ReturnType<typeof releaseMetrics>; releasePolicy?: ReleaseReportPolicy; repo: string; head?: string; version?: string; tag?: string; tagCommit?: string; commits: string[]; mergedPrs: { pr: number; commit: string }[]; documents?: DocEvidence; liveIssues: { id: number; state: "open" | "closed" | "unknown" }[]; blockers: string[]; sourceReady: boolean; native: "unverified"; ready: false; }
35
41
  export type ReleaseGit = (args: string[]) => { code: number; stdout: string };
@@ -43,32 +49,70 @@ function tagMatches(target: unknown, commit: string): boolean {
43
49
  const oid = parsed?.oid ?? parsed?.target?.oid;
44
50
  return typeof oid === "string" && SHA.test(oid) && oid === commit;
45
51
  }
46
- /** Package-owned checker only; no caller-supplied program or document text is executed. */
52
+ /** The bundled checker or the candidate's verified regular project checker may run. */
47
53
  /** #1120: why no evidence could be read, apart from evidence that says the documents are stale. */
48
54
  export type DocEvidenceRead = { evidence: DocEvidence } | { unavailable: string };
49
55
  const CHECKER_PATH = fileURLToPath(new URL("../../scripts/check-docs.mjs", import.meta.url));
50
- const CHECKER_MISSING = "the documentation checker scripts/check-docs.mjs is missing from the running hub, which predates the fix that carries it into captured runtimes; record consent from a hub started from a checkout or a release that carries the checker (docs/sdlc.md, release preparation)";
51
- const CHECKER_FAILED = "the documentation checker in the running hub did not finish with readable evidence (it timed out, crashed or printed unreadable output); run `node scripts/check-docs.mjs --json --committed` in the candidate checkout to see why, then retry";
56
+ const CHECKER_MISSING = "the documentation checker scripts/check-docs.mjs is missing from the running hub (bundled checker); record consent from a hub started from a checkout or a release that carries the checker (docs/sdlc.md, release preparation)";
57
+ function checkerName(command?: ProjectChecker): string {
58
+ return command ? `project checker ${command.path}` : "bundled checker";
59
+ }
60
+
61
+ async function checkerCommand(root: string, command?: ProjectChecker): Promise<string> {
62
+ const { shellQuote } = await import("../cli/shell-quote.ts");
63
+ return command
64
+ ? `cd ${shellQuote(root)} && ${shellQuote(process.execPath)} ${shellQuote(join(root, command.path))} ${shellQuote(root)} --json --committed`
65
+ : `cd ${shellQuote(dirname(dirname(CHECKER_PATH)))} && node scripts/check-docs.mjs --json --committed ${shellQuote(root)}`;
66
+ }
67
+
68
+ export async function documentationRefusal(root: string, evidence?: DocEvidence, command?: ProjectChecker): Promise<string> {
69
+ const message = evidence?.messages?.[0];
70
+ const reason = message ? (await import("./sdlc-release-diagnostics.ts")).releaseDiagnostic(message) : undefined;
71
+ return `${checkerName(command)}${reason ? `: ${reason}` : ""}; run \`${await checkerCommand(root, command)}\`, restamp the stale documents in a committed change, then authorize again`;
72
+ }
73
+
74
+ export function verifiedProjectChecker(root: string, command: ProjectChecker): string | undefined {
75
+ if (!command.blob || !SHA.test(command.blob)) return;
76
+ try {
77
+ const canonical = realPath(root), path = join(canonical, command.path);
78
+ if (realPath(path) !== path || !lstatSync(path).isFile()) return;
79
+ const hash = hubGitSync(["hash-object", "--no-filters", "--", path], {
80
+ cwd: canonical, env: hubGitEnv(process.env, { repositoryIsolation: true }), encoding: "utf8",
81
+ timeout: 1000, maxBuffer: 1024,
82
+ });
83
+ if (hash.status === 0 && hash.stdout?.trim() === command.blob) return path;
84
+ } catch { /* unavailable checkout evidence */ }
85
+ }
52
86
  export async function readDocEvidence(root: string, timeoutMs = 10_000): Promise<DocEvidence | undefined> {
53
87
  const read = await readDocEvidenceDetailed(root, timeoutMs);
54
88
  return "evidence" in read ? read.evidence : undefined;
55
89
  }
56
- export function readDocEvidenceDetailed(root: string, timeoutMs = 10_000, checker = CHECKER_PATH): Promise<DocEvidenceRead> {
57
- if (!existsSync(checker)) return Promise.resolve({ unavailable: CHECKER_MISSING });
58
- return new Promise(resolve => {
59
- const child = spawn(process.execPath, [checker, root, "--json", "--committed"], { cwd: root, env: childEnv(), detached: true, stdio: ["ignore", "pipe", "ignore"] });
90
+ export async function readDocEvidenceDetailed(root: string, timeoutMs = 10_000, checker: string | ProjectChecker = CHECKER_PATH): Promise<DocEvidenceRead> {
91
+ const command = typeof checker === "string" ? undefined : checker;
92
+ const program = typeof checker === "string" ? checker : verifiedProjectChecker(root, checker);
93
+ if (!program) return Promise.resolve({ unavailable: `project documentation checker ${command!.path} differs from the candidate commit; restore it before running ahub sdlc authorize-release` });
94
+ if (!existsSync(program) && !command) return Promise.resolve({ unavailable: CHECKER_MISSING });
95
+ const failureMessage = async () => `${checkerName(command)} did not finish with readable evidence (it timed out, crashed or printed unreadable output); run \`${await checkerCommand(root, command)}\` to see why, then retry`;
96
+ return new Promise((resolve, reject) => {
97
+ const failed = () => { void failureMessage().then(unavailable => resolve({ unavailable }), reject); };
98
+ const child = spawn(process.execPath, [program, root, "--json", "--committed"], { cwd: root, env: childEnv(), detached: true, stdio: ["ignore", "pipe", "ignore"] });
60
99
  let output = "", invalid = false;
61
100
  const stop = () => { invalid = true; void stopOwnedProcess(child, { group: true }).catch(() => {}); };
62
101
  const timer = setTimeout(stop, Math.max(1, Math.min(10_000, timeoutMs)));
63
102
  child.stdout?.setEncoding("utf8"); child.stdout?.on("data", chunk => { output += chunk; if (Buffer.byteLength(output) > 256 * 1024) { output = ""; stop(); } });
64
- child.once("error", () => { invalid = true; clearTimeout(timer); resolve({ unavailable: CHECKER_FAILED }); });
103
+ child.once("error", () => { invalid = true; clearTimeout(timer); failed(); });
65
104
  child.once("close", (code, signal) => {
66
- clearTimeout(timer); if (invalid || signal || (code !== 0 && code !== 1)) return resolve({ unavailable: CHECKER_FAILED });
105
+ clearTimeout(timer); if (invalid || signal || (code !== 0 && code !== 1)) return failed();
67
106
  try {
68
107
  const data = JSON.parse(output);
69
- if (data.schemaVersion !== 1 || !Array.isArray(data.documents) || data.documents.length > 128 || !Number.isSafeInteger(data.errors) || data.errors < 0 || typeof data.fresh !== "boolean" || (data.head !== undefined && !SHA.test(data.head)) || (data.version !== undefined && !VERSION.test(data.version)) || data.documents.some((d: {state?:string}) => !["fresh","stale","nonancestor","unknown"].includes(d.state ?? ""))) return resolve({ unavailable: CHECKER_FAILED });
108
+ if (data.schemaVersion !== 1 || !Array.isArray(data.documents) || data.documents.length > 128 || !Number.isSafeInteger(data.errors) || data.errors < 0 || typeof data.fresh !== "boolean" || (data.head !== undefined && !SHA.test(data.head)) || (data.version !== undefined && !VERSION.test(data.version)) || data.documents.some((d: {state?:string}) => !["fresh","stale","nonancestor","unknown"].includes(d.state ?? ""))) return failed();
109
+ if (data.messages !== undefined && (!Array.isArray(data.messages) || data.messages.length > 3
110
+ || data.messages.some((message: unknown) => typeof message !== "string" || message.length > 300)))
111
+ return failed();
112
+ if (command && (!data.head || !data.version || data.documents.some((row: DocEvidence["documents"][number]) => typeof row.dirty !== "boolean")))
113
+ return failed();
70
114
  resolve({ evidence: data });
71
- } catch { resolve({ unavailable: CHECKER_FAILED }); }
115
+ } catch { failed(); }
72
116
  });
73
117
  });
74
118
  }
@@ -152,10 +196,25 @@ export async function readReleaseReadiness(root: string, repo: string, liveIssue
152
196
  const skipDocs = report.releasePolicy?.docsSource === "none" || report.releasePolicy?.authorization === "unavailable"
153
197
  || !!report.releasePolicy && report.releasePolicy.versionSource !== "package.json" && report.releasePolicy.authorization !== "matched";
154
198
  const left = deadline - performance.now();
155
- report.documents = !skipDocs && left > 0 ? await (readers.docs ?? ((dir, ms) => readDocEvidenceDetailed(dir, ms, readers.checker).then(read => "evidence" in read ? read.evidence : undefined)))(root,Math.min(10_000,left)) : undefined;
156
- const checkerMissing = !skipDocs && !readers.docs && !existsSync(readers.checker ?? CHECKER_PATH); // #1120: a hub without the checker says so instead of calling the documents stale
157
- if (checkerMissing) report.blockers.push("documentation checker unavailable in the running hub: " + CHECKER_MISSING);
158
- else if (!skipDocs && (!report.documents || report.documents.head !== head || !report.documents.fresh || report.documents.errors || report.documents.documents.some(d => d.state !== "fresh"))) report.blockers.push("documentation freshness or ancestry is unknown or stale");
199
+ const command = releasePolicy?.checker;
200
+ let unavailable: string | undefined;
201
+ if (!skipDocs && left > 0) {
202
+ if (releasePolicy?.docsSource === "command" && !command) unavailable = "project checker identity unavailable; commit the checker and authorize again";
203
+ else if (readers.docs && !command) report.documents = await readers.docs(root, Math.min(10_000, left));
204
+ else {
205
+ const read = await readDocEvidenceDetailed(root, Math.min(10_000, left), command ?? readers.checker);
206
+ if ("unavailable" in read) unavailable = read.unavailable;
207
+ else report.documents = read.evidence;
208
+ }
209
+ }
210
+ if (unavailable) report.blockers.push("documentation checker unavailable in the running hub: " + unavailable);
211
+ else if (!skipDocs && (!report.documents || report.documents.head !== head || command && report.documents.version !== report.version
212
+ || !report.documents.fresh || report.documents.errors || report.documents.documents.some(d => d.state !== "fresh" || command && d.dirty))) {
213
+ report.blockers.push(command || report.documents?.messages?.length
214
+ ? `documentation freshness or ancestry is unknown or stale: ${await documentationRefusal(root, report.documents, command)}`
215
+ : "documentation freshness or ancestry is unknown or stale");
216
+ }
217
+ if (report.documents) delete report.documents.messages;
159
218
  if (!liveIssues.length) report.blockers.push("native verification ledger unspecified");
160
219
  for (const id of liveIssues) {
161
220
  const reply = await gh(["issue","view",String(id),"--repo",repo,"--json","number,state"]); let state: "open"|"closed"|"unknown" = "unknown";
@@ -193,7 +252,8 @@ export async function readReleaseReadiness(root: string, repo: string, liveIssue
193
252
  try { current = readers.reportPolicy(head, repo); } catch { /* a report recheck failure is stale authorization */ }
194
253
  const prior = report.releasePolicy;
195
254
  if (!current || current.authorization !== "matched" || current.versionSource !== prior.versionSource
196
- || current.docsSource !== prior.docsSource || current.version !== report.version) {
255
+ || current.docsSource !== prior.docsSource || current.version !== report.version
256
+ || JSON.stringify(current.checker) !== JSON.stringify(command)) {
197
257
  report.releasePolicy = { ...prior, authorization: "stale" };
198
258
  if (prior.versionSource !== "package.json") report.version = undefined;
199
259
  report.sourceReady = false;
@@ -0,0 +1,146 @@
1
+ // #1856 T3: the board receipt repairs `ahub sdlc sync` plans. Pure over injected reads: it writes nothing, and the same function re-runs before an apply.
2
+ import { createHash } from "node:crypto";
3
+ import type { SdlcGh } from "./sdlc.ts";
4
+
5
+ type SyncState = "proposed" | "in_progress" | "in_review" | "changes_requested" | string;
6
+ interface SyncTask {
7
+ id: number; state: SyncState; /** Public title only (`Tasks.publicTitle`); empty for a private task. */ title: string; pii: boolean;
8
+ refsRepo?: string; /** The task's own branch and its instance worktree branch. */ branches: readonly string[]; historyLength: number;
9
+ sdlc?: { repo?: string; issue?: number; pr?: number; localHead?: string; reviewedHead?: string };
10
+ }
11
+ type SyncOperation =
12
+ | { kind: "link"; task: number; repo: string; issue: number; reason: string }
13
+ | { kind: "bind"; task: number; repo: string; pr: number; localHead: string; reason: string }
14
+ | { kind: "adopt"; task: number; repo: string; pr: number; reason: string };
15
+ interface SyncPlan {
16
+ /** #1856 T4: the generated roadmap files to refresh in the caller's worktree (never a milestone state), and why it is not planned. */
17
+ roadmap?: { files: string[]; digest: string }; roadmapSkipped?: string;
18
+ /** Settled issues the preview would close, and the ones it skipped with the reason. */
19
+ closes: { issue: number; repo: string; tasks: number[]; reason: string }[]; closeSkipped: { issue: number; reason: string }[];
20
+ operations: SyncOperation[]; ambiguous: { task: number; reason: string }[]; headMoved: { task: number; pr: number; head: string; recorded: string }[];
21
+ /** Reads that did not complete: no operation of that kind is planned from them. */ unavailable: string[];
22
+ withheld: number; fingerprint: string; repository: string | undefined; deadlineMs: number;
23
+ }
24
+ interface SyncInput {
25
+ repository: string | undefined; /** Names who may apply, so authority drift changes the fingerprint. */ authority: string;
26
+ gh: SdlcGh; tasks: readonly SyncTask[]; now?: () => number; deadlineMs?: number;
27
+ /** The caller's `--write-roadmap`: whether the generated files are tracked in its worktree, and the hub's rendering of them. */
28
+ roadmap?: { tracked: boolean; render: () => Promise<{ json: string; markdown: string }> };
29
+ /** The caller's `--close-settled-issues`, already admitted by roadmap apply authority. Every board card with an issue, private ones as blockers only. */
30
+ closeSettled?: { cards: readonly { id: number; state: string; pii: boolean; repo?: string; issue?: number; pr?: number }[] };
31
+ }
32
+
33
+ const CLOSE_CAP = 20, SYNC_DEADLINE_MS = 30_000, READ_MS = 10_000, READ_BYTES = 1024 * 1024, ACTIVE = new Set(["in_progress", "in_review", "changes_requested"]), SHA = /^[a-f0-9]{40}$/;
34
+ const OPEN_PRS = (owner: string, name: string) => `query{repository(owner:${JSON.stringify(owner)},name:${JSON.stringify(name)}){pullRequests(states:OPEN,first:100,orderBy:{field:UPDATED_AT,direction:DESC}){nodes{number isDraft headRefName headRefOid url}}}}`;
35
+
36
+ /** Every unqualified `#N` in a public title (not `owner/repo#N`, not part of a word). */
37
+ const titleIssues = (title: string): number[] => [...new Set([...title.matchAll(/(?<![\w/#-])#(\d{1,9})(?!\w)/g)].map(match => Number(match[1])))];
38
+
39
+ export async function planSdlcSync(input: SyncInput): Promise<SyncPlan> {
40
+ const now = input.now ?? (() => performance.now()), deadlineMs = input.deadlineMs ?? SYNC_DEADLINE_MS, deadline = now() + deadlineMs;
41
+ const gh = async (args: string[]) => {
42
+ const remaining = deadline - now();
43
+ if (remaining <= 0) throw new Error("deadline");
44
+ return input.gh(args, Math.min(READ_MS, remaining), undefined, READ_BYTES);
45
+ };
46
+ const json = async (args: string[]): Promise<unknown | undefined> => {
47
+ try { const reply = await gh(args); return reply.code === 0 && Buffer.byteLength(reply.stdout) < READ_BYTES ? JSON.parse(reply.stdout) : undefined; } catch { return undefined; }
48
+ };
49
+ const repo = input.repository, operations: SyncOperation[] = [], ambiguous: SyncPlan["ambiguous"] = [], headMoved: SyncPlan["headMoved"] = [], unavailable: string[] = [];
50
+ const visible = input.tasks.filter(task => !task.pii), withheld = input.tasks.length - visible.length;
51
+
52
+ // Title-primary issue link: exactly one unqualified #N in the title, whatever the detail cites.
53
+ if (repo) for (const task of visible) {
54
+ if (task.sdlc?.issue !== undefined || (task.refsRepo !== undefined && task.refsRepo.toLowerCase() !== repo.toLowerCase())) continue;
55
+ const named = titleIssues(task.title);
56
+ if (named.length === 1) operations.push({ kind: "link", task: task.id, repo, issue: named[0]!, reason: `the title names #${named[0]} and the task records no issue` });
57
+ else if (named.length > 1) ambiguous.push({ task: task.id, reason: `the title names ${named.map(n => `#${n}`).join(" and ")}; record the right one with ahub sdlc record ${task.id} '{"repo":"${repo}","issue":<n>}'` });
58
+ }
59
+
60
+ const [owner, name] = repo?.split("/") ?? [];
61
+ const wantsPrs = !!repo && visible.some(task => ACTIVE.has(task.state) || task.sdlc?.pr !== undefined);
62
+ let open: { number: number; headRefName: string; headRefOid: string }[] | undefined, merged: { number: number; headRefOid: string }[] | undefined;
63
+ const needMerged = !!repo && (visible.some(task => task.sdlc?.pr !== undefined) || !!input.closeSettled);
64
+ if (owner && name && (wantsPrs || needMerged)) {
65
+ if (wantsPrs) {
66
+ const data = await json(["api", "graphql", "-f", `query=${OPEN_PRS(owner, name)}`]) as { data?: { repository?: { pullRequests?: { nodes?: unknown } } } } | undefined;
67
+ const nodes = data?.data?.repository?.pullRequests?.nodes;
68
+ if (Array.isArray(nodes)) open = nodes.filter((node): node is { number: number; headRefName: string; headRefOid: string } => !!node && typeof node.number === "number" && typeof node.headRefName === "string" && typeof node.headRefOid === "string" && SHA.test(node.headRefOid));
69
+ else unavailable.push("open pull requests");
70
+ }
71
+ if (needMerged) {
72
+ const list = await json(["pr", "list", "--repo", repo!, "--state", "merged", "--limit", "100", "--json", "number,headRefOid"]);
73
+ if (Array.isArray(list)) merged = list.filter((row): row is { number: number; headRefOid: string } => !!row && typeof row.number === "number" && typeof row.headRefOid === "string");
74
+ else unavailable.push("merged pull requests");
75
+ }
76
+ }
77
+
78
+ if (open && repo) {
79
+ const byNumber = new Map(open.map(pr => [pr.number, pr]));
80
+ const claims = new Map<number, number[]>(), chosen = new Map<number, { number: number; headRefOid: string }>();
81
+ for (const task of visible.filter(item => ACTIVE.has(item.state))) {
82
+ const recorded = task.sdlc?.pr;
83
+ if (recorded !== undefined) {
84
+ const pr = byNumber.get(recorded), localHead = task.sdlc?.localHead;
85
+ if (!pr || pr.headRefOid === localHead || (task.sdlc?.repo !== undefined && task.sdlc.repo.toLowerCase() !== repo.toLowerCase())) continue;
86
+ // A review is bound to its reviewed head: report the movement and never write over it.
87
+ if (task.state === "in_review") headMoved.push({ task: task.id, pr: pr.number, head: pr.headRefOid, recorded: localHead ?? "none" });
88
+ else operations.push({ kind: "bind", task: task.id, repo, pr: pr.number, localHead: pr.headRefOid, reason: `PR #${pr.number} is open at a newer head than the recorded one` });
89
+ continue;
90
+ }
91
+ const matches = open.filter(pr => task.branches.includes(pr.headRefName));
92
+ if (matches.length > 1) ambiguous.push({ task: task.id, reason: `${matches.length} open PRs match its branch (${matches.map(pr => `#${pr.number}`).join(", ")}); record the right one with ahub sdlc record ${task.id} '{"pr":<n>,"localHead":"<head sha>"}'` });
93
+ else if (matches.length === 1) { chosen.set(task.id, matches[0]!); claims.set(matches[0]!.number, [...claims.get(matches[0]!.number) ?? [], task.id]); }
94
+ }
95
+ for (const [taskId, pr] of chosen) {
96
+ const rivals = claims.get(pr.number)!;
97
+ if (rivals.length > 1) ambiguous.push({ task: taskId, reason: `PR #${pr.number} matches the branches of tasks ${rivals.join(", ")}; record the right owner with ahub sdlc record <task> '{"pr":${pr.number},"localHead":"${pr.headRefOid}"}'` });
98
+ else operations.push({ kind: "bind", task: taskId, repo, pr: pr.number, localHead: pr.headRefOid, reason: `PR #${pr.number} is the one open PR on its branch` });
99
+ }
100
+ }
101
+
102
+ if (merged && repo) {
103
+ const byNumber = new Map(merged.map(pr => [pr.number, pr]));
104
+ for (const task of visible) {
105
+ const recorded = task.sdlc?.pr, head = task.sdlc?.reviewedHead ?? task.sdlc?.localHead;
106
+ if (recorded === undefined || task.state === "approved" || !(task.state === "proposed" || ACTIVE.has(task.state))) continue;
107
+ const pr = byNumber.get(recorded);
108
+ if (pr && head && pr.headRefOid === head) operations.push({ kind: "adopt", task: task.id, repo: task.sdlc?.repo ?? repo, pr: recorded, reason: `PR #${recorded} merged at the recorded head` });
109
+ }
110
+ }
111
+
112
+ // #1856 T4: close an issue only when a linked task is approved at a merged PR, none is unsettled and the live body has no open checklist item.
113
+ const closes: SyncPlan["closes"] = [], closeSkipped: SyncPlan["closeSkipped"] = [];
114
+ if (input.closeSettled && repo) {
115
+ const mergedNumbers = new Set((merged ?? []).map(pr => pr.number)), here = (card: { repo?: string }) => card.repo === undefined || card.repo.toLowerCase() === repo.toLowerCase();
116
+ const cards = input.closeSettled.cards.filter(card => card.issue !== undefined && here(card));
117
+ const issues = [...new Set(cards.filter(card => !card.pii && card.state === "approved" && card.pr !== undefined && mergedNumbers.has(card.pr)).map(card => card.issue!))].sort((a, b) => a - b);
118
+ for (const issue of issues.slice(0, CLOSE_CAP)) {
119
+ const linked = cards.filter(card => card.issue === issue);
120
+ const unsettled = linked.filter(card => card.state !== "approved" && card.state !== "cancelled");
121
+ if (unsettled.length) { closeSkipped.push({ issue, reason: `${unsettled.length} linked task${unsettled.length === 1 ? " is" : "s are"} still unsettled` }); continue; }
122
+ const view = await json(["issue", "view", String(issue), "--repo", repo, "--json", "body,state"]) as { body?: unknown; state?: unknown } | undefined;
123
+ if (!view || typeof view.body !== "string") { closeSkipped.push({ issue, reason: "the live issue could not be read" }); unavailable.includes("issue bodies") || unavailable.push("issue bodies"); continue; }
124
+ if (view.state !== "OPEN") continue;
125
+ if (/^\s*(?:[-*+]|\d+[.)])\s+\[ \]/m.test(view.body)) { closeSkipped.push({ issue, reason: "the issue body has an unchecked item" }); continue; }
126
+ closes.push({ issue, repo, tasks: linked.filter(card => !card.pii).map(card => card.id), reason: "linked tasks are approved with a merged PR and the body has no open item" });
127
+ }
128
+ if (issues.length > CLOSE_CAP) closeSkipped.push({ issue: 0, reason: `${issues.length - CLOSE_CAP} more candidates not read; rerun after these` });
129
+ // A private card that names the issue blocks closing it without ever being described.
130
+ }
131
+ let roadmap: SyncPlan["roadmap"], roadmapSkipped: string | undefined;
132
+ if (input.roadmap) {
133
+ if (!input.roadmap.tracked) roadmapSkipped = "docs/roadmap.json is not tracked in this worktree";
134
+ else {
135
+ try { const files = await input.roadmap.render(); roadmap = { files: ["docs/roadmap.json", "docs/roadmap.md"], digest: createHash("sha256").update(JSON.stringify([files.json, files.markdown])).digest("hex") }; }
136
+ catch { roadmapSkipped = "the roadmap could not be rendered; run ahub roadmap export"; unavailable.push("roadmap"); }
137
+ }
138
+ }
139
+
140
+ operations.sort((left, right) => left.task - right.task || left.kind.localeCompare(right.kind));
141
+ ambiguous.sort((left, right) => left.task - right.task); headMoved.sort((left, right) => left.task - right.task);
142
+ // The fingerprint binds the plan, the origin, the authority and every considered card's history length, so board drift changes it.
143
+ const board = visible.map(task => [task.id, task.state, task.historyLength]);
144
+ const fingerprint = createHash("sha256").update(JSON.stringify({ repo: repo ?? null, authority: input.authority, operations, ambiguous, headMoved, withheld, board, roadmap: roadmap ?? null, closes })).digest("hex");
145
+ return { operations, ambiguous, headMoved, unavailable, withheld, fingerprint, repository: repo, deadlineMs, closes, closeSkipped, ...(roadmap ? { roadmap } : {}), ...(roadmapSkipped ? { roadmapSkipped } : {}) };
146
+ }
package/src/hub/sdlc.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { StructureRules } from "./structure-budget.ts";
1
2
  import { parseIssueLabels, parseRedFirst, testIntegrityBlockers, type RedFirstReceipt, type TestIntegrity } from "./test-integrity.ts";
2
3
  import { planConformanceBlockers, type PlanConformance } from "./plan-conformance.ts";
3
4
  import { riskPolicy, type RiskPolicy, type RiskRecord } from "./risk-tier.ts";
@@ -47,7 +48,7 @@ export const AUTO_MERGE_MODES: readonly AutoMergeMode[] = ["off", "dry-run", "on
47
48
  export interface SecurityScanConfig { everyH: number; sources: SecuritySource[]; repo?: string }
48
49
  /** #786: one repository's own gate: its required checks (before the top-level list) and its own merge mode. */
49
50
  export interface RepoMergePolicy { requiredChecks?: string[]; autoMerge?: AutoMergeMode }
50
- export interface SdlcConfig { workflow?: "gsd-lite"; maxNits?: number; /** #481 S7: optional control bands per metric; absent means none. */ bands?: BandsConfig; /** #481 S7: the scheduled security-scan baseline; absent means none is scheduled. */ securityScan?: SecurityScanConfig; /** #481 S5: the one check a configuration PR needs; no default, the person names it. */ evalCheck?: string; /** #481 S5: patterns that mark a PR as a configuration change; absent reads as the defaults in eval-gate.ts, an empty list turns the gate off. */ configPaths?: string[]; /** #1403 A2: sensitive paths that need a recorded security pass, and the review companions that apply; absent means the feature is off. */ security?: SecurityPolicy; /** #1645 T1: paths that make a filed change high or low; absent means no tier is derived and nothing else changes. */ risk?: RiskPolicy; mode: SdlcMode; requiredChecks: string[]; /** #786: absent reads as "off"; written only when the file names it. */ autoMerge?: AutoMergeMode; /** #786: per-repository tables, keyed by lowercase owner/name. */ repos?: Record<string, RepoMergePolicy>; stages: SdlcStage[]; definitions?: Record<string, StageDefinition>; deprecations?: string[]; }
51
+ export interface SdlcConfig { workflow?: "gsd-lite"; maxNits?: number; /** #481 S7: optional control bands per metric; absent means none. */ bands?: BandsConfig; /** #481 S7: the scheduled security-scan baseline; absent means none is scheduled. */ securityScan?: SecurityScanConfig; /** #481 S5: the one check a configuration PR needs; no default, the person names it. */ evalCheck?: string; /** #481 S5: patterns that mark a PR as a configuration change; absent reads as the defaults in eval-gate.ts, an empty list turns the gate off. */ configPaths?: string[]; /** #1403 A2: sensitive paths that need a recorded security pass, and the review companions that apply; absent means the feature is off. */ security?: SecurityPolicy; /** #1645 T1: paths that make a filed change high or low; absent means no tier is derived and nothing else changes. */ risk?: RiskPolicy; structure?: StructureRules; mode: SdlcMode; requiredChecks: string[]; ciShardRetries?: number; /** #786: absent reads as "off"; written only when the file names it. */ autoMerge?: AutoMergeMode; /** #786: per-repository tables, keyed by lowercase owner/name. */ repos?: Record<string, RepoMergePolicy>; stages: SdlcStage[]; definitions?: Record<string, StageDefinition>; deprecations?: string[]; }
51
52
  export interface PlanReviewReceipt {
52
53
  planner: string;
53
54
  planAuthor?: string | null;
@@ -208,12 +209,43 @@ function mergeRepos(value: unknown): Record<string, RepoMergePolicy> | undefined
208
209
  return result;
209
210
  }
210
211
 
212
+ function structureRules(value: unknown): StructureRules {
213
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("sdlc.structure: expected a table");
214
+ const raw = value as Record<string, unknown>;
215
+ for (const key of Object.keys(raw)) {
216
+ if (!["roots", "max_lines", "max_bytes", "shared", "baseline", "grow"].includes(key)) {
217
+ throw new Error(`sdlc.structure.${key}: unknown field`);
218
+ }
219
+ }
220
+ const roots = configPathList(raw.roots, "sdlc.structure.roots");
221
+ if (!roots.length || roots.some(root => /[*?]/.test(root))) {
222
+ throw new Error("sdlc.structure.roots: name at least one literal repository-relative root");
223
+ }
224
+ const shared = configPathList(raw.shared, "sdlc.structure.shared");
225
+ const [baseline] = configPathList([raw.baseline], "sdlc.structure.baseline");
226
+ if (!baseline || /[*?]/.test(baseline)) throw new Error("sdlc.structure.baseline: expected a literal repository-relative path");
227
+ const positive = (key: "max_lines" | "max_bytes"): number => {
228
+ const limit = raw[key];
229
+ if (typeof limit !== "number" || !Number.isSafeInteger(limit) || limit <= 0) {
230
+ throw new Error(`sdlc.structure.${key}: expected a positive integer`);
231
+ }
232
+ return limit;
233
+ };
234
+ const grow = raw.grow;
235
+ if (grow !== "warn" && grow !== "refuse") throw new Error("sdlc.structure.grow: expected warn or refuse");
236
+ return { roots, maxLines: positive("max_lines"), maxBytes: positive("max_bytes"), shared, baseline, grow };
237
+ }
238
+
211
239
  /** `version` is the running hub's, which closes the #481 S8 window; the daemon and Tasks pass it. Without one the window is open. */
212
240
  export function sdlcConfig(value: unknown, version?: string): SdlcConfig {
213
241
  if (value === undefined) return { mode: "off", requiredChecks: [], stages: [...SDLC_STAGES] };
214
242
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("sdlc: expected a table");
215
243
  const raw = value as Record<string, unknown>;
216
- for (const key of Object.keys(raw)) if (!["mode", "required_checks", "stages", "workflow", "definitions", "max_nits", "bands", "auto_merge", "repos", "eval_check", "config_paths", "security_scan", "security", "risk"].includes(key)) throw new Error(`sdlc.${key}: unknown field`);
244
+ for (const key of Object.keys(raw)) if (!["mode", "required_checks", "stages", "workflow", "definitions", "max_nits", "bands", "auto_merge", "repos", "eval_check", "config_paths", "security_scan", "security", "risk", "structure", "ci_shard_retries"].includes(key)) throw new Error(`sdlc.${key}: unknown field`);
245
+ const ciShardRetries = raw.ci_shard_retries;
246
+ if (ciShardRetries !== undefined && (typeof ciShardRetries !== "number" || !Number.isSafeInteger(ciShardRetries) || ciShardRetries < 0 || ciShardRetries > 3)) {
247
+ throw new Error("sdlc.ci_shard_retries: expected an integer from 0 to 3; set it in .agenthub/sdlc.toml and restart the hub (0 disables automatic retries)");
248
+ }
217
249
  const maxNits = raw.max_nits === undefined ? DEFAULT_MAX_NITS : raw.max_nits;
218
250
  if (typeof maxNits !== "number" || !Number.isSafeInteger(maxNits) || maxNits < 0 || maxNits > 64) throw new Error("sdlc.max_nits: expected an integer from 0 to 64");
219
251
  const bands = bandsConfig(raw.bands), bandConfig = Object.keys(bands).length ? { bands } : {};
@@ -222,6 +254,7 @@ export function sdlcConfig(value: unknown, version?: string): SdlcConfig {
222
254
  ...(raw.config_paths === undefined ? {} : { configPaths: configPathList(raw.config_paths, "sdlc.config_paths") }),
223
255
  };
224
256
  const findingConfig = { ...(raw.max_nits === undefined ? {} : { maxNits }), ...bandConfig, ...evalConfig, ...(raw.security_scan === undefined ? {} : { securityScan: securityScanConfig(raw.security_scan) }), ...(raw.security === undefined ? {} : { security: securityPolicy(raw.security) }), ...(raw.risk === undefined ? {} : { risk: riskPolicy(raw.risk) }) };
257
+ const structure = raw.structure === undefined ? {} : { structure: structureRules(raw.structure) };
225
258
  const mode = raw.mode ?? "off";
226
259
  if (mode !== "off" && mode !== "advise" && mode !== "enforce") throw new Error("sdlc.mode: expected off, advise or enforce");
227
260
  // ponytail: the #481 S8 window is a fixed version; delete `workflow`, the phase aliases and their tests once it passes.
@@ -233,11 +266,11 @@ export function sdlcConfig(value: unknown, version?: string): SdlcConfig {
233
266
  const phaseAlias = { allowed: window, used: false };
234
267
  const checks = checkList(raw.required_checks ?? [], "sdlc.required_checks");
235
268
  // #786: absent keys add nothing to the config, so the off-mode default keeps its #257 shape byte for byte.
236
- const mergeConfig = { ...(raw.auto_merge === undefined ? {} : { autoMerge: autoMergeMode(raw.auto_merge, "sdlc.auto_merge") }), ...(raw.repos === undefined ? {} : { repos: mergeRepos(raw.repos)! }) };
269
+ const mergeConfig = { ...(ciShardRetries === undefined ? {} : { ciShardRetries }), ...(raw.auto_merge === undefined ? {} : { autoMerge: autoMergeMode(raw.auto_merge, "sdlc.auto_merge") }), ...(raw.repos === undefined ? {} : { repos: mergeRepos(raw.repos)! }) };
237
270
  if (raw.definitions !== undefined) {
238
271
  const custom = definitions(raw.definitions, raw.stages, phaseAlias);
239
272
  if (phaseAlias.used) notes.push(`the sdlc phase gate is deprecated and stops loading in ${RETIRED_WORKFLOW_FROM} (#481): name it criteria`);
240
- return { mode, ...findingConfig, ...mergeConfig, requiredChecks: [...checks] as string[], ...custom, ...(workflow === "gsd-lite" ? { workflow } : {}), ...(notes.length ? { deprecations: notes } : {}) };
273
+ return { mode, ...findingConfig, ...structure, ...mergeConfig, requiredChecks: [...checks] as string[], ...custom, ...(workflow === "gsd-lite" ? { workflow } : {}), ...(notes.length ? { deprecations: notes } : {}) };
241
274
  }
242
275
  // Off keeps the #257 seven stages byte for byte; an enabled lifecycle defaults to the playbook (#481 S0).
243
276
  const given = raw.stages ?? (mode === "off" ? [...SDLC_STAGES] : [...PLAYBOOK_STAGES]);
@@ -245,7 +278,7 @@ export function sdlcConfig(value: unknown, version?: string): SdlcConfig {
245
278
  // An enabled #257 list keeps its order under canonical ids, so implement/verify stay read-only aliases there too.
246
279
  const stages = mode !== "off" && exactly(SDLC_STAGES) ? SDLC_STAGES.map(canonicalStage) : given;
247
280
  if (!exactly(SDLC_STAGES) && !exactly(PLAYBOOK_STAGES)) throw new Error(`sdlc.stages: use ${PLAYBOOK_STAGES.join(", ")} in that order (or the #257 list ${SDLC_STAGES.join(", ")}); other lists need definitions`);
248
- return { mode, ...findingConfig, ...mergeConfig, requiredChecks: [...checks] as string[], stages: [...stages as string[]], ...(workflow === "gsd-lite" ? { workflow } : {}), ...(notes.length ? { deprecations: notes } : {}) };
281
+ return { mode, ...findingConfig, ...structure, ...mergeConfig, requiredChecks: [...checks] as string[], stages: [...stages as string[]], ...(workflow === "gsd-lite" ? { workflow } : {}), ...(notes.length ? { deprecations: notes } : {}) };
249
282
  }
250
283
 
251
284
  export function loadSdlc(cwd: string, version?: string): SdlcConfig {
@@ -1,8 +1,11 @@
1
+ import { DECLARATION_START_MODE_PEERS } from "../adapters/declaration-catalog.ts";
1
2
  import { OPERATIONAL_NUMBERS } from "./operational-settings.ts";
2
3
  import { QUEUE_BACKPRESSURE_LIMITS } from "./queue-backpressure.ts";
3
4
  import { operationalRosterSetting, operationalSetting } from "./operational-authority.ts";
4
5
  import { ACTION_CLASSES } from "./action-class.ts";
5
- import { definitionOf, type KindMap, type ProjectAdapterCatalog, ADAPTERS, PLANNER_PEERS, SUPPORTED_PEERS, START_MODE_PEERS } from "../adapters/registry.ts";
6
+ import { builtinDeclarationOf as definitionOf, DECLARATION_PLANNER_PEERS as PLANNER_PEERS, DECLARATION_SUPPORTED_PEERS as SUPPORTED_PEERS } from "../adapters/declaration-catalog.ts";
7
+ import { NATIVE_CONFIGURATION } from "../adapters/definitions/native-configuration.ts";
8
+ import type { KindMap, ProjectAdapterCatalog } from "../adapters/registry-types.ts";
6
9
  import { createHash } from "node:crypto";
7
10
  import { types } from "node:util";
8
11
  import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
@@ -84,8 +87,8 @@ export const SETTINGS: readonly SettingDef[] = [
84
87
  ...SETTING_PEERS.filter(peer => !definitionOf(peer)?.permission.unmanaged).map((peer): SettingDef => ({ key: `permission.${peer}`, group: "Permissions", label: `${peer}: mode now`, type: "enum", values: PERMISSION_MODES, store: "runtime", applies: "live", risk: "raises", floor: "ask", path: [peer] })),
85
88
  ...SETTING_PEERS.filter(peer => !definitionOf(peer)?.permission.unmanaged).map((peer): SettingDef => ({ key: `permission_modes.${peer}`, group: "Permissions", label: `${peer}: mode at next peer start`, type: "enum", values: PERMISSION_MODES, store: "config", applies: "next use", risk: "raises", floor: "ask", path: ["permission_modes", peer] })),
86
89
  { key: "start.agents", group: "Start", label: "Agents ahub up starts (none for an empty list)", type: "peers", store: "config", applies: "next use", risk: "raises", path: ["start", "agents"] },
87
- ...START_MODE_PEERS.map((peer): SettingDef => ({ key: `peers.${peer}.start_mode`, group: "Start", label: `${peer}: start mode (tui unless set)`, type: "enum", values: START_MODES, store: "config", applies: "next use", risk: "raises", floor: "tui", path: ["peers", peer, "start_mode"] })),
88
- ...ADAPTERS.flatMap(adapter => adapter.configuration?.settings ?? []),
90
+ ...DECLARATION_START_MODE_PEERS.map((peer): SettingDef => ({ key: `peers.${peer}.start_mode`, group: "Start", label: `${peer}: start mode (tui unless set)`, type: "enum", values: START_MODES, store: "config", applies: "next use", risk: "raises", floor: "tui", path: ["peers", peer, "start_mode"] })),
91
+ ...NATIVE_CONFIGURATION.flatMap(configuration => configuration.settings ?? []),
89
92
  { key: "routing.stay_switch", group: "Routing", label: "Stay or switch (hub/auto and stage routes)", type: "enum", values: ["off", "shadow", "enforce"], store: "routing", applies: "live", risk: "raises", path: ["stay_switch"] },
90
93
  ...CLASSES.flatMap(perClass),
91
94
  { key: "visuals.retention_days", group: "Switches", label: "Unbound visual retention (days)", type: "integer", min: 1, max: 3650, store: "config", applies: "live", risk: "raises", floor: 1, path: ["visuals", "retention_days"] },
@@ -109,7 +112,7 @@ export const SETTINGS: readonly SettingDef[] = [
109
112
  * Never editable from settings, whatever the session: these choose what the hub executes or where secrets and task
110
113
  * text go. A key equal to an entry, or below it, is refused by name.
111
114
  */
112
- export const NEVER_EDITABLE = ["invocation", "kimi_cmd", "qwen_cmd", "jcode_cmd", "jcode_home", "jcode_mcp_allow", "jcode_provider_profile", "codex_bin", "pi.cmd", "checks", "mlx", "omniroute", "memory.worker_url", "local.read_allow", "local.bash_network", "local.network_allow", "bench.enabled", "terminal", "schedules", "folder_triggers", "corpus", "rooms", "instances", "adapters", "adapter_modules", "local.doc_read", "local.web_fetch"] as const;
115
+ export const NEVER_EDITABLE = ["invocation", "kimi_cmd", "qwen_cmd", "jcode_cmd", "jcode_home", "jcode_mcp_allow", "jcode_provider_profile", "codex_bin", "pi.cmd", "checks", "mlx", "omniroute", "memory.worker_url", "local.read_allow", "local.bash_network", "local.network_allow", "bench.enabled", "terminal", "schedules", "folder_triggers", "corpus", "rooms", "instances", "adapters", "accounts", "adapter_modules", "local.doc_read", "local.web_fetch"] as const;
113
116
 
114
117
  /**
115
118
  * The one key `ahub learn accept` writes (#514b): the active profile's review checklist, which replaces as a unit. It is NOT a row of `SETTINGS` and `settingDef` does NOT resolve it, so
@@ -1,4 +1,4 @@
1
- import { SUPPORTED_PEERS, definitionOf } from "../adapters/registry.ts";
1
+ import { DECLARATION_SUPPORTED_PEERS as SUPPORTED_PEERS, builtinDeclarationOf as definitionOf } from "../adapters/declaration-catalog.ts";
2
2
 
3
3
  /**
4
4
  * #608 (agent-hub#1040): the agents `ahub up` asks the hub to start, `start.agents`. Pure and free of file-system
@@ -1,4 +1,5 @@
1
- import { definitionOf, SUPPORTED_PEERS, START_MODE_PEERS as REGISTRY_START_MODE_PEERS, type ProjectAdapterCatalog, type KindMap } from "../adapters/registry.ts";
1
+ import { builtinDeclarationOf as definitionOf, DECLARATION_SUPPORTED_PEERS } from "../adapters/declaration-catalog.ts";
2
+ import type { ProjectAdapterCatalog, KindMap } from "../adapters/registry-types.ts";
2
3
 
3
4
  /**
4
5
  * #269: how a peer comes up when the hub starts it: its own TUI in a terminal, or headless. A person who types
@@ -11,9 +12,10 @@ export type StartMode = typeof START_MODES[number];
11
12
  // ponytail: released coordinators source-probe this exact literal before restoring headless Kimi.
12
13
  // Keep it until those readers negotiate the registry capability.
13
14
  /** The peers with both forms. Kimi's TUI is pull-only; Claude has only a TUI and local only headless. */
15
+ // used-by: src/adapters/definitions/native-recovery.ts
14
16
  export const START_MODE_PEERS = ["pi", "codex", "kimi", "jcode"] as const;
15
17
  /** Every peer the hub can start itself. */
16
- export const STARTABLE_PEERS = SUPPORTED_PEERS;
18
+ export const STARTABLE_PEERS = DECLARATION_SUPPORTED_PEERS;
17
19
  export type StartablePeer = typeof STARTABLE_PEERS[number];
18
20
  export const isStartablePeer = (value: unknown): value is StartablePeer => typeof value === "string" && !!definitionOf(value)?.start.conductorStartable;
19
21
 
@@ -27,7 +29,7 @@ export function peerStartConfig(value: unknown, instances?: KindMap, catalog?: P
27
29
  for (const [peer, block] of Object.entries(value)) {
28
30
  const configured = !!catalog?.definitionOf(peer) && !definitionOf(peer);
29
31
  const extra = (catalog?.definitionOf ?? definitionOf)(peer, instances)?.kind !== peer && !!(catalog?.definitionOf ?? definitionOf)(peer, instances);
30
- if (!(REGISTRY_START_MODE_PEERS as readonly string[]).includes(peer) && !extra && !configured) throw new Error(`peers.${peer}: only ${REGISTRY_START_MODE_PEERS.join(" and ")} have a start mode`);
32
+ if (!(START_MODE_PEERS as readonly string[]).includes(peer) && !extra && !configured) throw new Error(`peers.${peer}: only ${START_MODE_PEERS.join(" and ")} have a start mode`);
31
33
  if (!block || typeof block !== "object" || Array.isArray(block)) throw new Error(`peers.${peer} must be an object`);
32
34
  if (Object.keys(block).some(key => key !== "start_mode")) throw new Error(`peers.${peer}: unsupported setting`);
33
35
  const mode = (block as { start_mode?: unknown }).start_mode;
@@ -41,7 +43,12 @@ export function peerStartConfig(value: unknown, instances?: KindMap, catalog?: P
41
43
  /** The mode a start of `peer` takes when nothing more specific was asked: `tui` wherever the peer has one. */
42
44
  export function startModeOf(peers: PeerStartConfig | undefined, peer: string, instances?: KindMap, catalog?: ProjectAdapterCatalog): StartMode {
43
45
  if ((catalog?.definitionOf ?? definitionOf)(peer, instances)?.kind !== peer && (catalog?.definitionOf ?? definitionOf)(peer, instances)) return peers?.[peer]?.start_mode ?? "headless";
44
- if ((REGISTRY_START_MODE_PEERS as readonly string[]).includes(peer)) return peers?.[peer]?.start_mode ?? definitionOf(peer)?.start.defaultForm ?? "tui";
46
+ if ((START_MODE_PEERS as readonly string[]).includes(peer)) {
47
+ // Without a project settings snapshot or a catalog, retain the public runtime default lookup.
48
+ const resolve = catalog?.definitionOf ?? (peers === undefined
49
+ ? (require("../adapters/registry.ts") as typeof import("../adapters/registry.ts")).definitionOf : definitionOf);
50
+ return peers?.[peer]?.start_mode ?? resolve(peer)?.start.defaultForm ?? "tui";
51
+ }
45
52
  return (catalog?.definitionOf ?? definitionOf)(peer)?.start.defaultForm ?? "headless";
46
53
  }
47
54