@staix/agent-hub 0.51.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 (299) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +1 -1
  3. package/docs/adding-an-ai-tool.md +24 -2
  4. package/docs/agent-notes/adapters.md +1 -0
  5. package/docs/agent-notes/budget.md +8 -2
  6. package/docs/agent-notes/daemon.md +13 -8
  7. package/docs/agent-notes/security-review.md +6 -5
  8. package/docs/agent-notes/tasks.md +5 -2
  9. package/docs/agent-notes/tests.md +4 -3
  10. package/docs/cooperbench.md +1 -1
  11. package/docs/design/adapters.md +4 -0
  12. package/docs/design/cli-output-inventory.md +162 -152
  13. package/docs/design/cli-output.md +4 -3
  14. package/docs/design/guidance-probes.md +1 -0
  15. package/docs/design/roadmap.md +2 -0
  16. package/docs/design/task-board.md +1 -0
  17. package/docs/dogfood.md +14 -0
  18. package/docs/events.md +4 -2
  19. package/docs/memory.md +5 -3
  20. package/docs/operations.md +210 -16
  21. package/docs/quickstart.md +12 -2
  22. package/docs/roles.md +1 -1
  23. package/docs/sdlc.md +26 -3
  24. package/docs/security.md +11 -5
  25. package/docs/specs/2026-09-19-agent-hub-design.md +43 -0
  26. package/docs/specs/2026-09-19-multi-project-design.md +4 -0
  27. package/docs/specs/2026-09-20-upgrade-recovery-design.md +17 -0
  28. package/docs/specs/mcp-endpoint.md +63 -0
  29. package/docs/verification/2026-11-30-capability-listing-shape-1808.md +45 -0
  30. package/docs/verification/2026-11-30-upgrade-keep-1807.md +174 -0
  31. package/docs/verification/2026-12-01-1811-confirmation-receipt.md +19 -0
  32. package/docs/verification/2026-12-01-1811-orca-agent-list.md +20 -0
  33. package/docs/verification/2026-12-01-1811-orca-pane-key.md +21 -0
  34. package/docs/verification/2026-12-02-1819-claude-process-after-renewal.md +54 -0
  35. package/docs/verification/2026-12-02-agy-1.5.21.md +74 -0
  36. package/docs/verification/2026-12-02-claude-implementer-2.1.334.md +44 -0
  37. package/docs/verification/2026-12-02-cli-import-graph.md +33 -0
  38. package/docs/verification/2026-12-03-0.52.0.md +150 -0
  39. package/docs/verification/2026-12-03-codex-0173-reviewer-isolation.md +53 -0
  40. package/docs/verification/2026-12-03-codex-0173-reviewer-tool-call.md +34 -0
  41. package/docs/verification/2026-12-03-jcode-1.3.0.md +25 -0
  42. package/docs/verification/agy/README.md +17 -0
  43. package/docs/verification/agy/cli-surface.ts +68 -0
  44. package/docs/verification/agy/interactive-bridge.ts +92 -0
  45. package/docs/verification/agy/interactive-session.ts +131 -0
  46. package/docs/verification/agy/launcher-nonce.ts +215 -0
  47. package/docs/verification/agy/native-hooks.ts +210 -0
  48. package/docs/verification/agy/originals/agent-hub-681/cli-surface.ts +87 -0
  49. package/docs/verification/agy/originals/agent-hub-681/native-hooks-adapted.ts +91 -0
  50. package/docs/verification/agy/originals/agent-hub-681/tui-actual.ts +200 -0
  51. package/docs/verification/agy/originals/agent-hub-684/probe.ts +107 -0
  52. package/docs/verification/agy/originals.json +25 -0
  53. package/docs/verification/agy/permission-new-functions.ts +128 -0
  54. package/docs/verification/agy/run-probe.py +108 -0
  55. package/docs/verification/agy/runtime.ts +171 -0
  56. package/docs/verification/agy/tmux-helper-control.ts +6 -0
  57. package/docs/verification/agy/tmux-session.ts +235 -0
  58. package/docs/verified.json +82 -41
  59. package/package.json +3 -3
  60. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  61. package/plugins/agent-hub/compat.json +157 -0
  62. package/plugins/agent-hub/kimi-hook.js +621 -865
  63. package/plugins/agent-hub/server.js +17423 -32962
  64. package/src/adapters/agy/definition.ts +7 -24
  65. package/src/adapters/channel-peer.ts +3 -1
  66. package/src/adapters/claude-channel.ts +38 -257
  67. package/src/adapters/claude-implementer.ts +3 -1
  68. package/src/adapters/codex-appserver.ts +77 -15
  69. package/src/adapters/compat.ts +74 -11
  70. package/src/adapters/configured-acp.ts +23 -163
  71. package/src/adapters/configured-adapter-policy.ts +160 -0
  72. package/src/adapters/configured-pull-entry.ts +53 -0
  73. package/src/adapters/configured-pull.ts +38 -0
  74. package/src/adapters/conformance/fakes/app-server.ts +9 -2
  75. package/src/adapters/declaration-catalog.ts +25 -0
  76. package/src/adapters/declaration-data.ts +342 -0
  77. package/src/adapters/declaration-resolution.ts +53 -0
  78. package/src/adapters/definitions/builtin-metadata.ts +61 -83
  79. package/src/adapters/definitions/jcode-launch.ts +13 -0
  80. package/src/adapters/definitions/native-adapter-policy.ts +390 -0
  81. package/src/adapters/definitions/native-cli-claude-launch.ts +3 -2
  82. package/src/adapters/definitions/native-cli-codex-launch.ts +2 -1
  83. package/src/adapters/definitions/native-cli-entry-jcode.ts +4 -2
  84. package/src/adapters/definitions/native-cli-entry-types.ts +9 -2
  85. package/src/adapters/definitions/native-cli-launch-common.ts +2 -2
  86. package/src/adapters/definitions/native-cli-retained.ts +1 -1
  87. package/src/adapters/definitions/native-configuration.ts +18 -0
  88. package/src/adapters/definitions/native-help.ts +24 -0
  89. package/src/adapters/definitions/native-launch-declarations.ts +34 -0
  90. package/src/adapters/definitions/native-launch-policy.ts +4 -0
  91. package/src/adapters/definitions/native-launch-settings.ts +72 -0
  92. package/src/adapters/definitions/native-light-cli.ts +18 -0
  93. package/src/adapters/definitions/native-light-preview.ts +10 -0
  94. package/src/adapters/definitions/native-wrapper-launch.ts +10 -0
  95. package/src/adapters/definitions/qwen.ts +6 -29
  96. package/src/adapters/definitions/reviewer-variants.ts +7 -8
  97. package/src/adapters/external-declarations.ts +31 -0
  98. package/src/adapters/external-modules.ts +4 -29
  99. package/src/adapters/jcode.ts +3 -12
  100. package/src/adapters/native-capabilities.ts +18 -8
  101. package/src/adapters/native-proof-ports.ts +1 -1
  102. package/src/adapters/presets.ts +136 -0
  103. package/src/adapters/qwen-dual.ts +2 -2
  104. package/src/adapters/registry-types.ts +3 -0
  105. package/src/adapters/registry.ts +20 -81
  106. package/src/adapters/reviewer-print.ts +26 -9
  107. package/src/adapters/role-eligibility.ts +2 -1
  108. package/src/cli/accounts-import.ts +72 -0
  109. package/src/cli/agents-latest-table.ts +88 -0
  110. package/src/cli/agents-latest.ts +22 -0
  111. package/src/cli/agents-output.ts +10 -0
  112. package/src/cli/agents-presets.ts +100 -0
  113. package/src/cli/agents.ts +1 -1
  114. package/src/cli/attention.ts +3 -2
  115. package/src/cli/autonomy-homes.ts +7 -2
  116. package/src/cli/budget-renew-guidance.ts +129 -0
  117. package/src/cli/claude-homes.ts +9 -5
  118. package/src/cli/command-context.ts +3 -0
  119. package/src/cli/command-table.ts +123 -0
  120. package/src/cli/commands/accounts.ts +8 -0
  121. package/src/cli/commands/agents.ts +18 -0
  122. package/src/cli/commands/answer.ts +28 -0
  123. package/src/cli/commands/ask.ts +17 -0
  124. package/src/cli/commands/autonomy.ts +83 -0
  125. package/src/cli/commands/backlog.ts +46 -0
  126. package/src/cli/commands/bench.ts +60 -0
  127. package/src/cli/commands/board.ts +48 -0
  128. package/src/cli/commands/broker.ts +9 -0
  129. package/src/cli/commands/budget.ts +96 -0
  130. package/src/cli/commands/capabilities.ts +12 -0
  131. package/src/cli/commands/check-path.ts +55 -0
  132. package/src/cli/commands/completion.ts +8 -0
  133. package/src/cli/commands/console.ts +12 -0
  134. package/src/cli/commands/daemon.ts +8 -0
  135. package/src/cli/commands/deliverables.ts +25 -0
  136. package/src/cli/commands/doctor.ts +249 -0
  137. package/src/cli/commands/down.ts +3 -0
  138. package/src/cli/commands/export.ts +15 -0
  139. package/src/cli/commands/facts.ts +15 -0
  140. package/src/cli/commands/goal.ts +22 -0
  141. package/src/cli/commands/guidance.ts +102 -0
  142. package/src/cli/commands/help.ts +17 -0
  143. package/src/cli/commands/host.ts +45 -0
  144. package/src/cli/commands/init.ts +121 -0
  145. package/src/cli/commands/instructed.ts +19 -0
  146. package/src/cli/commands/instruction-hook.ts +15 -0
  147. package/src/cli/commands/intake.ts +24 -0
  148. package/src/cli/commands/kill.ts +15 -0
  149. package/src/cli/commands/learn.ts +23 -0
  150. package/src/cli/commands/lineage.ts +30 -0
  151. package/src/cli/commands/logs.ts +21 -0
  152. package/src/cli/commands/manager.ts +15 -0
  153. package/src/cli/commands/memory.ts +21 -0
  154. package/src/cli/commands/model.ts +25 -0
  155. package/src/cli/commands/models.ts +40 -0
  156. package/src/cli/commands/native.ts +39 -0
  157. package/src/cli/commands/pause.ts +5 -0
  158. package/src/cli/commands/peer.ts +32 -0
  159. package/src/cli/commands/permission.ts +26 -0
  160. package/src/cli/commands/permit.ts +12 -0
  161. package/src/cli/commands/pet.ts +24 -0
  162. package/src/cli/commands/projects.ts +49 -0
  163. package/src/cli/commands/queue.ts +70 -0
  164. package/src/cli/commands/recovery-run.ts +13 -0
  165. package/src/cli/commands/recovery.ts +130 -0
  166. package/src/cli/commands/release.ts +23 -0
  167. package/src/cli/commands/releases.ts +9 -0
  168. package/src/cli/commands/remember.ts +6 -0
  169. package/src/cli/commands/report.ts +27 -0
  170. package/src/cli/commands/research.ts +53 -0
  171. package/src/cli/commands/reset.ts +89 -0
  172. package/src/cli/commands/restart.ts +5 -0
  173. package/src/cli/commands/results.ts +31 -0
  174. package/src/cli/commands/resume.ts +5 -0
  175. package/src/cli/commands/review.ts +24 -0
  176. package/src/cli/commands/roadmap.ts +21 -0
  177. package/src/cli/commands/role.ts +34 -0
  178. package/src/cli/commands/roles.ts +30 -0
  179. package/src/cli/commands/room.ts +14 -0
  180. package/src/cli/commands/roster.ts +48 -0
  181. package/src/cli/commands/route.ts +9 -0
  182. package/src/cli/commands/say.ts +21 -0
  183. package/src/cli/commands/schedule.ts +17 -0
  184. package/src/cli/commands/sdlc.ts +321 -0
  185. package/src/cli/commands/settings.ts +148 -0
  186. package/src/cli/commands/setup.ts +89 -0
  187. package/src/cli/commands/shared-refusals.ts +25 -0
  188. package/src/cli/commands/smoke.ts +44 -0
  189. package/src/cli/commands/source.ts +64 -0
  190. package/src/cli/commands/specs.ts +13 -0
  191. package/src/cli/commands/status.ts +28 -0
  192. package/src/cli/commands/stop.ts +17 -0
  193. package/src/cli/commands/structure.ts +60 -0
  194. package/src/cli/commands/study.ts +39 -0
  195. package/src/cli/commands/tail.ts +19 -0
  196. package/src/cli/commands/task.ts +114 -0
  197. package/src/cli/commands/title.ts +17 -0
  198. package/src/cli/commands/turns.ts +10 -0
  199. package/src/cli/commands/ui.ts +47 -0
  200. package/src/cli/commands/undo.ts +77 -0
  201. package/src/cli/commands/up.ts +39 -0
  202. package/src/cli/commands/upgrade.ts +5 -0
  203. package/src/cli/commands/usage.ts +33 -0
  204. package/src/cli/commands/version.ts +5 -0
  205. package/src/cli/commands/watch.ts +30 -0
  206. package/src/cli/commands/worktrees.ts +31 -0
  207. package/src/cli/console-state.ts +5 -138
  208. package/src/cli/console-versions.ts +1 -1
  209. package/src/cli/help.ts +37 -15
  210. package/src/cli/identity.ts +23 -4
  211. package/src/cli/launch-check.ts +1 -2
  212. package/src/cli/launch.ts +13 -82
  213. package/src/cli/light-dispatch.ts +29 -0
  214. package/src/cli/main.js +8 -1
  215. package/src/cli/main.ts +233 -2816
  216. package/src/cli/orca-probe.ts +119 -0
  217. package/src/cli/output.ts +31 -2
  218. package/src/cli/preview.ts +10 -5
  219. package/src/cli/recovery-version-preflight.ts +28 -9
  220. package/src/cli/replace-process.ts +22 -0
  221. package/src/cli/report-layout.ts +142 -0
  222. package/src/cli/roadmap-usage.ts +16 -0
  223. package/src/cli/roadmap.ts +3 -16
  224. package/src/cli/sdlc-doctor.ts +27 -0
  225. package/src/cli/sdlc-output.ts +55 -1
  226. package/src/cli/setup-homes.ts +1 -1
  227. package/src/cli/start-agents-run.ts +1 -1
  228. package/src/cli/statusline-tee.ts +25 -4
  229. package/src/cli/terminal-recovery.ts +53 -10
  230. package/src/cli/upgrade-interactive.ts +1 -0
  231. package/src/cli/upgrade-runtime.ts +11 -0
  232. package/src/cli/upgrade.ts +4 -15
  233. package/src/hub/accounts.ts +148 -0
  234. package/src/hub/addons.ts +20 -0
  235. package/src/hub/agent-drift.ts +2 -1
  236. package/src/hub/budget-projection.ts +39 -7
  237. package/src/hub/budget.ts +231 -16
  238. package/src/hub/channel-project.ts +3 -3
  239. package/src/hub/conductor-peer.ts +24 -0
  240. package/src/hub/conductor.ts +2 -21
  241. package/src/hub/config-apply.ts +24 -13
  242. package/src/hub/config-edit.ts +1 -1
  243. package/src/hub/config-tier.ts +2 -0
  244. package/src/hub/config.ts +31 -14
  245. package/src/hub/control-client.ts +48 -0
  246. package/src/hub/daemon.ts +421 -61
  247. package/src/hub/events.ts +3 -0
  248. package/src/hub/home-tag.ts +12 -0
  249. package/src/hub/host.ts +217 -0
  250. package/src/hub/hub-tools.ts +2 -1
  251. package/src/hub/instance-budget.ts +2 -2
  252. package/src/hub/instance-config.ts +15 -126
  253. package/src/hub/instances.ts +22 -6
  254. package/src/hub/instruction-receipt.ts +2 -2
  255. package/src/hub/kimi-usage.ts +38 -11
  256. package/src/hub/lifecycle.ts +86 -4
  257. package/src/hub/mcp-bridge-core.ts +98 -0
  258. package/src/hub/mcp-channel-push.ts +20 -0
  259. package/src/hub/mcp-endpoint-serve.ts +178 -0
  260. package/src/hub/mcp-endpoint.ts +226 -0
  261. package/src/hub/mcp-tool-call.ts +181 -0
  262. package/src/hub/operational-settings.ts +2 -0
  263. package/src/hub/orca-env.ts +6 -0
  264. package/src/hub/orca-state.ts +84 -0
  265. package/src/hub/peers.ts +5 -1
  266. package/src/hub/permission-mode.ts +2 -1
  267. package/src/hub/project.ts +20 -0
  268. package/src/hub/protocol-window.ts +58 -0
  269. package/src/hub/quota-origin.ts +20 -0
  270. package/src/hub/registry.ts +36 -2
  271. package/src/hub/report.ts +1 -1
  272. package/src/hub/research.ts +1 -1
  273. package/src/hub/review-brief.ts +47 -2
  274. package/src/hub/roster.ts +6 -3
  275. package/src/hub/routing.ts +9 -2
  276. package/src/hub/sdlc-check.ts +205 -0
  277. package/src/hub/sdlc-sync.ts +146 -0
  278. package/src/hub/sdlc.ts +33 -4
  279. package/src/hub/settings.ts +7 -4
  280. package/src/hub/start-agents.ts +1 -1
  281. package/src/hub/start-mode.ts +11 -4
  282. package/src/hub/structure-budget.ts +131 -0
  283. package/src/hub/structure-scan.ts +149 -0
  284. package/src/hub/tasks-experiment.ts +455 -0
  285. package/src/hub/tasks-guidance.ts +606 -0
  286. package/src/hub/tasks-roadmap-plan.ts +419 -0
  287. package/src/hub/tasks-roadmap.ts +491 -0
  288. package/src/hub/tasks-study.ts +661 -0
  289. package/src/hub/tasks-survey.ts +192 -0
  290. package/src/hub/tasks.ts +319 -2548
  291. package/src/hub/terminal-open.ts +5 -3
  292. package/src/hub/tooling.ts +3 -19
  293. package/src/hub/usage-rollup.ts +9 -3
  294. package/src/local/tools.ts +5 -0
  295. package/src/ui/index.html +1 -1
  296. package/src/ui/needs.ts +17 -5
  297. package/src/ui/peer-palette.ts +2 -4
  298. package/templates/presets/agents.json +60 -0
  299. package/templates/presets/confirmation-matrix.json +8 -8
@@ -17,3 +17,61 @@ export function negotiateProtocol(local: ProtocolWindow, remote: ProtocolWindow)
17
17
  const highest = Math.min(a.v, b.v);
18
18
  return highest >= Math.max(a.vMin, b.vMin) ? highest : undefined;
19
19
  }
20
+
21
+ export interface BridgeWindowSettings {
22
+ bridge_window_days: number;
23
+ bridge_window_min: number;
24
+ }
25
+
26
+ export const DEFAULT_BRIDGE_WINDOW: Readonly<BridgeWindowSettings> = {
27
+ bridge_window_days: 90,
28
+ bridge_window_min: 3,
29
+ };
30
+
31
+ /** Published stable tags grouped by their literal control protocol; the last release sets the age cutoff. */
32
+ export const BRIDGE_PROTOCOL_RELEASES = [
33
+ [4, "v0.1.0", "2026-09-19", "v0.1.0", "2026-09-19"],
34
+ [5, "v0.2.0", "2026-09-19", "v0.2.0", "2026-09-19"],
35
+ [6, "v0.3.0", "2026-09-19", "v0.3.2", "2026-09-19"],
36
+ [7, "v0.4.0", "2026-09-19", "v0.4.0", "2026-09-19"],
37
+ [8, "v0.5.0", "2026-09-20", "v0.5.0", "2026-09-20"],
38
+ [9, "v0.6.0", "2026-09-20", "v0.6.4", "2026-09-20"],
39
+ [10, "v0.7.0", "2026-09-20", "v0.12.0", "2026-10-01"],
40
+ [11, "v0.12.1", "2026-10-01", "v0.12.2", "2026-10-02"],
41
+ [12, "v0.12.3", "2026-10-02", "v0.12.3", "2026-10-02"],
42
+ [13, "v0.12.4", "2026-10-03", "v0.12.15", "2026-10-07"],
43
+ [14, "v0.12.16", "2026-10-09", "v0.12.16", "2026-10-09"],
44
+ [15, "v0.12.17", "2026-10-09", "v0.12.19", "2026-10-09"],
45
+ [16, "v0.12.20", "2026-10-09", "v0.25.0", "2026-11-01"],
46
+ [17, "v0.26.0", "2026-11-01", "v0.52.0", "2026-12-03"],
47
+ ] as const;
48
+
49
+ export function bridgeWindowSettings(raw: unknown): BridgeWindowSettings {
50
+ if (raw === undefined) return { ...DEFAULT_BRIDGE_WINDOW };
51
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)
52
+ || Object.keys(raw).some(key => !Object.hasOwn(DEFAULT_BRIDGE_WINDOW, key))) {
53
+ throw new Error("upgrade accepts only bridge_window_days and bridge_window_min");
54
+ }
55
+ const settings = { ...DEFAULT_BRIDGE_WINDOW };
56
+ for (const key of Object.keys(settings) as (keyof BridgeWindowSettings)[]) {
57
+ const value = (raw as Record<string, unknown>)[key];
58
+ if (value === undefined) continue;
59
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
60
+ throw new Error(`upgrade.${key} must be a nonnegative integer`);
61
+ }
62
+ settings[key] = value;
63
+ }
64
+ return settings;
65
+ }
66
+
67
+ /** Compute the release-history interval, clamped at the supplied implementation floor. */
68
+ export function bridgeProtocolWindow(settings: BridgeWindowSettings, implementedFloor: number, now: number): ProtocolWindow {
69
+ const current = BRIDGE_PROTOCOL_RELEASES.at(-1)![0];
70
+ if (!protocolWindow(current, implementedFloor) || !Number.isFinite(now)) throw new Error("invalid bridge window boundary");
71
+ const cutoff = now - settings.bridge_window_days * 86_400_000;
72
+ const byAge = settings.bridge_window_days === 0 ? current
73
+ : BRIDGE_PROTOCOL_RELEASES.find(([, , first, , last]) => Date.parse(first) <= now && Date.parse(last) >= cutoff)?.[0] ?? current;
74
+ const countIndex = Math.max(0, BRIDGE_PROTOCOL_RELEASES.length - 1 - settings.bridge_window_min);
75
+ const byCount = BRIDGE_PROTOCOL_RELEASES[countIndex]![0];
76
+ return { v: current, vMin: Math.max(implementedFloor, Math.min(byAge, byCount)) };
77
+ }
@@ -0,0 +1,20 @@
1
+ import { randomUUID } from "node:crypto";
2
+
3
+ /** A host-local ordering mark. Persisted marks name a runtime generation, never an account or path. */
4
+ export interface QuotaStamp {
5
+ runtime: string;
6
+ order: number;
7
+ }
8
+
9
+ const runtime = randomUUID();
10
+ let order = 0;
11
+
12
+ export function stampQuotaBoundary(): QuotaStamp {
13
+ return { runtime, order: ++order };
14
+ }
15
+
16
+ /** A reading must originate in this hub run. An earlier run's durable renewal predates our owned spawns. */
17
+ export function quotaStampAfter(previous: QuotaStamp, observed: QuotaStamp): boolean {
18
+ return observed.runtime === runtime
19
+ && (previous.runtime !== runtime || observed.order > previous.order);
20
+ }
@@ -30,8 +30,8 @@ export interface Project {
30
30
  * #226: `pid_signature` holds "<instance id> <signature>". An older daemon's claim rewrites instance_id and pid but not
31
31
  * this column, so a signature counts only for the instance that wrote it: under another instance the claim is unsigned.
32
32
  */
33
- export const PROJECT_COLUMNS = "id, root, state_dir as stateDir, base_port as basePort, instance_id as instanceId, pid";
34
- export function projectFromRow(raw: Record<string, unknown>): Project {
33
+ const PROJECT_COLUMNS = "id, root, state_dir as stateDir, base_port as basePort, instance_id as instanceId, pid";
34
+ function projectFromRow(raw: Record<string, unknown>): Project {
35
35
  const { pid_signature: signed, ...row } = raw;
36
36
  const project = { ...row } as unknown as Project;
37
37
  const prefix = `${project.instanceId} `;
@@ -64,6 +64,8 @@ export class Registry {
64
64
  base_port INTEGER NOT NULL UNIQUE, instance_id TEXT, pid INTEGER, claimed_at INTEGER
65
65
  )`);
66
66
  this.db.run("CREATE TABLE IF NOT EXISTS registry_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)");
67
+ // #1779 T3a: one host process per runtime root, claimed here so a second starter cannot take over a live host's socket.
68
+ this.db.run("CREATE TABLE IF NOT EXISTS host_claims (runtime_root TEXT PRIMARY KEY, host_id TEXT NOT NULL, pid INTEGER NOT NULL, pid_signature TEXT, claimed_at INTEGER NOT NULL)");
67
69
  const columns = this.db.query("PRAGMA table_info(projects)").all() as { name: string }[];
68
70
  if (!columns.some((c) => c.name === "pid_signature")) {
69
71
  try { this.db.run("ALTER TABLE projects ADD COLUMN pid_signature TEXT"); }
@@ -156,6 +158,25 @@ export class Registry {
156
158
  return claimed;
157
159
  }
158
160
 
161
+ /**
162
+ * #1779 T3a: claim the host of a runtime root. Atomic in one immediate transaction: the claim is refused while another host's process is live or uncertain,
163
+ * and taken over only when that process is gone. Only the winner may remove a stale socket file and listen; a loser joins the answering host or fails closed.
164
+ */
165
+ claimHost(runtimeRoot: string, hostId: string, pid: number, signature?: string): { claimed: true } | { claimed: false; holderPid: number } {
166
+ let outcome: { claimed: true } | { claimed: false; holderPid: number } = { claimed: true };
167
+ const tx = this.db.transaction(() => {
168
+ const row = this.db.query("SELECT host_id, pid, pid_signature FROM host_claims WHERE runtime_root = ?").get(runtimeRoot) as { host_id: string; pid: number; pid_signature: string | null } | null;
169
+ if (row && row.host_id !== hostId && processLiveness(row.pid, row.pid_signature) !== "gone") { outcome = { claimed: false, holderPid: row.pid }; return; }
170
+ this.db.query("INSERT OR REPLACE INTO host_claims (runtime_root, host_id, pid, pid_signature, claimed_at) VALUES (?, ?, ?, ?, ?)").run(runtimeRoot, hostId, pid, signature ?? null, Date.now());
171
+ });
172
+ this.runtimeCaptureLocked(tx);
173
+ return outcome;
174
+ }
175
+
176
+ releaseHost(runtimeRoot: string, hostId: string): void {
177
+ this.db.query("DELETE FROM host_claims WHERE runtime_root = ? AND host_id = ?").run(runtimeRoot, hostId);
178
+ }
179
+
159
180
  release(id: string, instanceId: string): void {
160
181
  this.db.query("UPDATE projects SET instance_id = NULL, pid = NULL, pid_signature = NULL, claimed_at = NULL WHERE id = ? AND instance_id = ?").run(id, instanceId);
161
182
  }
@@ -233,3 +254,16 @@ export class Registry {
233
254
  runTx(tx as Tx);
234
255
  }
235
256
  }
257
+
258
+ /** Registry reads for planning must not create a registry or run migrations. */
259
+ export function registeredProjects(home = hubHome()): Project[] {
260
+ const path = join(home, "registry.db");
261
+ if (!existsSync(path)) return [];
262
+ const db = new Database(path, { readonly: true });
263
+ try {
264
+ db.run(`PRAGMA busy_timeout = ${REGISTRY_DB_BUSY_TIMEOUT_MS}`);
265
+ // #226: a registry no current release opened yet has no signature column, and this read never migrates.
266
+ const signed = (db.query("PRAGMA table_info(projects)").all() as { name: string }[]).some((c) => c.name === "pid_signature");
267
+ return (db.query(`SELECT ${PROJECT_COLUMNS}${signed ? ", pid_signature" : ""} FROM projects ORDER BY root`).all() as Record<string, unknown>[]).map(projectFromRow);
268
+ } finally { db.close(); }
269
+ }
package/src/hub/report.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { definitionOf } from "../adapters/registry.ts";
1
+ import { builtinDeclarationOf as definitionOf } from "../adapters/declaration-catalog.ts";
2
2
  import type { StampedEvent } from "./events.ts";
3
3
  import { addPersonEvent, emptyPersonCounts, isPersonEvent, personCoverage, personFigures, personTask, startsAttribution, UNKNOWN_PERSON_FIGURES, type PersonCounts, type PersonFigures } from "./person-figures.ts";
4
4
 
@@ -5,7 +5,7 @@ import { join } from "node:path";
5
5
  import { isModelEvidence, MODEL_EVIDENCE, parseEventLine, turnEdits, type TurnEdits, readEvents, scanEventLines, type ModelEvidence, type RoleIdentity, type StampedEvent } from "./events.ts";
6
6
  import { safeModelLabel } from "../omniroute/usage.ts";
7
7
  import { hubHome } from "./project.ts";
8
- import { ADDONS, addonState, type Addon, type AddonName } from "./tooling.ts";
8
+ import { ADDONS, addonState, type Addon, type AddonName } from "./addons.ts";
9
9
  import { MIN_ATTEMPTS, mulberry32 } from "./bench.ts";
10
10
  import { UNKNOWN_MEMORY_FIGURES } from "./research-memory.ts";
11
11
  import { addPersonEvent, emptyPersonCounts, isPersonEvent, personCoverage, personFigures, personTask, startsAttribution, type PersonCounts } from "./person-figures.ts";
@@ -1,3 +1,6 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { checkStructureBudget, updateStructureBaseline, type StructureRules } from "./structure-budget.ts";
3
+ import { parseStructureBaseline, scanStructureRevision } from "./structure-scan.ts";
1
4
  import type { CodeFactResult, CodeSymbol } from "./code-facts.ts";
2
5
  import { sanitize } from "./envelope.ts";
3
6
  import { childEnv } from "./child-process.ts";
@@ -47,6 +50,7 @@ export interface ReviewBrief {
47
50
  unlisted: string[];
48
51
  /** #1645 T4: the tier this head was filed at and what it still owes, already rendered by `risk-tier.ts`; absent without a `[risk]` table. */
49
52
  risk?: string;
53
+ structure?: string[];
50
54
  }
51
55
 
52
56
  /** A bounded, public summary of the design specs affected by one exact task head. */
@@ -64,7 +68,7 @@ export function renderSpecTaskReport(report: SpecTaskReport): string {
64
68
  if (report.complete && report.errors === 0 && report.unchanged.length === 0 && report.changed.length === 0) lines.push("No covering specs were found for the changed files.");
65
69
  return sanitize(lines.join("\n"));
66
70
  }
67
- export interface BriefPolicy { privatePath(path: string): boolean; nameable(text: string): boolean }
71
+ export interface BriefPolicy { privatePath(path: string): boolean; nameable(text: string): boolean; structureRules?(config: unknown): StructureRules | undefined }
68
72
 
69
73
  const MAX_FILES = 500, RULE_BYTES = 32_000, MAX_RULE_FILES = 8;
70
74
  const LOCKFILES = new Set(["bun.lock", "bun.lockb", "package-lock.json", "yarn.lock", "pnpm-lock.yaml", "Cargo.lock", "poetry.lock", "uv.lock", "go.sum", "composer.lock", "Gemfile.lock"]);
@@ -154,7 +158,47 @@ export function buildReviewBrief(cwd: string, head: unknown, policy: BriefPolicy
154
158
  if (plain.status !== 0 || typeof plain.stdout !== "string") return { unavailable: `the name list of ${head} could not be read` };
155
159
  const listed = new Set(shown.flatMap(g => g.paths)), hidden = new Set(groups.filter(g => !shown.includes(g)).flatMap(g => g.paths));
156
160
  const unlisted = plain.stdout.split("\0").filter(path => path && !listed.has(path) && !hidden.has(path));
157
- return { head: commit, base: from, mergeBase, reviewable, excluded, withheld, rules: [...ruleText].map(([source, text]) => ({ source, text })), rulesMissing: [...rulesMissing].map(([source, reason]) => ({ source, reason })), ruleGroups: [...byKey.values()], unlisted };
161
+ const structure = reviewStructure(cwd, mergeBase, commit, policy);
162
+ return { ...(structure?.length ? { structure } : {}), head: commit, base: from, mergeBase, reviewable, excluded, withheld, rules: [...ruleText].map(([source, text]) => ({ source, text })), rulesMissing: [...rulesMissing].map(([source, reason]) => ({ source, reason })), ruleGroups: [...byKey.values()], unlisted };
163
+ }
164
+
165
+ function reviewStructure(cwd: string, base: string, head: string, policy: BriefPolicy): string[] | undefined {
166
+ if (!policy.structureRules) return;
167
+ try {
168
+ const config = git(cwd, ["show", `${base}:.agenthub/sdlc.toml`]);
169
+ if (config.status !== 0 || typeof config.stdout !== "string") return;
170
+ const rules = policy.structureRules(Bun.TOML.parse(config.stdout));
171
+ if (!rules) return;
172
+ const visible = (path: string) => !policy.privatePath(path) && policy.nameable(path);
173
+ if (!visible(rules.baseline)) return;
174
+ const baselineFile = git(cwd, ["show", `${base}:${rules.baseline}`]);
175
+ const baseline = baselineFile.status === 0 ? parseStructureBaseline(baselineFile.stdout) : undefined;
176
+ const run = (args: string[], input?: string) => {
177
+ const result = hubGitSync(["-C", cwd, ...args], { input, env: childEnv(process.env), maxBuffer: 16 * 1024 * 1024, timeout: 15_000 });
178
+ return result.status === 0 && Buffer.isBuffer(result.stdout) ? result.stdout : undefined;
179
+ };
180
+ const before = scanStructureRevision(rules, base, run, visible);
181
+ const after = before && scanStructureRevision(rules, head, run, visible);
182
+ if (!before || !after) return;
183
+ const previous = updateStructureBaseline(rules, undefined, before);
184
+ const result = checkStructureBudget(rules, previous, after);
185
+ const rows = [...result.findings, ...result.warnings].filter(finding => {
186
+ if (finding.kind === "growth") return baseline && Object.hasOwn(baseline.sizes, finding.path)
187
+ && after.some(file => file.path === finding.path && file.lines > previous.sizes[finding.path]!.lines);
188
+ return !finding.detail.startsWith("Stale ");
189
+ }).map(finding => `- ${finding.path}: ${finding.detail}. ${finding.next}`)
190
+ .filter(line => policy.nameable(line));
191
+ if (!rows.length) return;
192
+ const ripwire = Bun.which("ripwire");
193
+ if (ripwire) {
194
+ const range = `--quality-delta=${base}..${head}`;
195
+ const advisory = spawnSync(ripwire, [".", range], { cwd, env: childEnv(process.env), encoding: "utf8", timeout: 5_000, maxBuffer: 16 * 1024 });
196
+ if (advisory.status === 0 && policy.nameable(advisory.stdout)) rows.push(`Ripwire advisory: ripwire . ${range}`);
197
+ }
198
+ return rows;
199
+ } catch {
200
+ return;
201
+ }
158
202
  }
159
203
 
160
204
  function numstat(cwd: string, head: string, base: string, attrSource: string): Map<string, { insertions: number; deletions: number; binary: boolean }> | undefined {
@@ -230,6 +274,7 @@ export function renderReviewBrief(brief: ReviewBrief): string {
230
274
  ...(brief.unlisted.length ? ["Not in the brief's list, read directly:", ...brief.unlisted.map(path => `- ${path}`)] : []),
231
275
  ...brief.ruleGroups.filter(g => g.sources.length).map(g => `Rules ${g.sources.join(" + ")} apply to: ${brief.ruleGroups.length === 1 ? "every reviewable file" : g.paths.join(", ")}`),
232
276
  ...(brief.rulesMissing.length ? ["Configured rules not loaded (read them in the repository):", ...brief.rulesMissing.map(m => `- ${m.source}: ${m.reason}`)] : []),
277
+ ...(brief.structure?.length ? ["Structure changes:", ...brief.structure] : []),
233
278
  ...brief.rules.map(r => `--- ${r.source} ---\n${r.text.trimEnd()}`),
234
279
  `Coverage: pass hub_review coverage {reviewed: [paths], skipped: [{path, reason}]} naming every reviewable path above.`,
235
280
  ].join("\n");
package/src/hub/roster.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { definitionOf as builtinDefinitionOf, type ProjectAdapterCatalog, type KindMap } from "../adapters/registry.ts";
1
+ import { builtinDeclarationOf as builtinDefinitionOf, createProjectDeclarationCatalog as builtinCatalog } from "../adapters/declaration-catalog.ts";
2
+ import type { ProjectAdapterCatalog, KindMap } from "../adapters/registry-types.ts";
2
3
  import { validateInstances } from "./instances.ts";
3
- import { defaultRosterEnabled as builtinDefaultRosterEnabled, createProjectAdapterCatalog as builtinCatalog } from "../adapters/registry.ts";
4
4
 
5
5
  export type PeerRoster = Partial<Record<string, boolean>>;
6
6
 
@@ -45,7 +45,10 @@ export function peerRosterConfig(value: unknown, instances?: KindMap, catalog?:
45
45
  /** External ids keep their existing admission rules; Pi's legacy switch is only its default. */
46
46
  export function rosterAllows(roster: PeerRoster, peer: string, piEnabled: boolean, instances: KindMap | undefined, catalog: ProjectAdapterCatalog, inertUnknown = false): boolean {
47
47
  const definitionOf = catalog.definitionOf;
48
- const defaultRosterEnabled = (id: string, enabled: boolean) => !builtinDefinitionOf(id) ? catalog.definitionOf(id)?.defaultOnRoster ?? false : builtinDefaultRosterEnabled(id, enabled);
48
+ const defaultRosterEnabled = (id: string, enabled: boolean) => {
49
+ const builtin = builtinDefinitionOf(id);
50
+ return builtin?.enabledSwitchStartOnly ? enabled : catalog.definitionOf(id)?.defaultOnRoster ?? false;
51
+ };
49
52
  const definition = definitionOf(peer, instances);
50
53
  if (!definition) return !inertUnknown || !Object.hasOwn(roster, peer); // Only a captured module scope makes unresolved rows inert; legacy external clients keep their admission rules.
51
54
  return roster[peer] ?? (definition.kind === peer ? defaultRosterEnabled(peer, piEnabled) : true);
@@ -2,7 +2,12 @@ import { contextHeadroom, type ContextAdmission } from "./context-window.ts";
2
2
  import { queueBackpressure, type QueueBackpressureCode, type QueueBackpressurePolicy, type QueuePressure } from "./queue-backpressure.ts";
3
3
  import { selectReviewerPool, type ReviewerPoolSelection } from "./reviewer-pool.ts";
4
4
  import type { ReviewBudgetSnapshot } from "./review-budget.ts";
5
- import { ADAPTERS, definitionOf, kindOf, familyOf, type ProjectAdapterCatalog } from "../adapters/registry.ts";
5
+ import type { ProjectAdapterCatalog } from "../adapters/registry-types.ts";
6
+
7
+ const runtimeAdapters = () => require("../adapters/registry.ts") as typeof import("../adapters/registry.ts");
8
+ const definitionOf: typeof import("../adapters/registry.ts").definitionOf = (...args) => runtimeAdapters().definitionOf(...args);
9
+ const kindOf: typeof import("../adapters/registry.ts").kindOf = (...args) => runtimeAdapters().kindOf(...args);
10
+ const familyOf: typeof import("../adapters/registry.ts").familyOf = (...args) => runtimeAdapters().familyOf(...args);
6
11
  import { readFileSync, statSync } from "node:fs";
7
12
  import { join, resolve } from "node:path";
8
13
  import { CLASSES, type Task, type TaskClass } from "./board.ts";
@@ -169,7 +174,7 @@ function orderSiblingSlots(peers: PeerId[], states: Readonly<Record<string, Peer
169
174
 
170
175
  /** The quota/roster relay keeps its native preference order, then the class's original tail. */
171
176
  export function relayCandidates(classPeers: readonly PeerId[], pii: boolean, opts: InstanceRoutingOptions & { states?: Readonly<Record<string, PeerState>> } = {}): PeerId[] {
172
- const preferred = (opts.adapterCatalog?.definitions ?? ADAPTERS).filter(adapter => adapter.routing?.handoffPriority !== undefined)
177
+ const preferred = (opts.adapterCatalog?.definitions ?? runtimeAdapters().ADAPTERS).filter(adapter => adapter.routing?.handoffPriority !== undefined)
173
178
  .sort((a, b) => a.routing!.handoffPriority! - b.routing!.handoffPriority!);
174
179
  const candidates = [
175
180
  ...preferred.filter(adapter => !pii || adapter.trust.onPrem).map(adapter => adapter.kind),
@@ -512,6 +517,8 @@ export function assign(
512
517
  if (isRemotePeerId(peer)) return deny("policy", "remote peers cannot hold local roles");
513
518
  const definition = (opts.adapterCatalog?.definitionOf ?? definitionOf)(peer, opts.instances);
514
519
  if (definition?.start.daemonPort === "configured-print") return deny("policy", "print peers return advisory answers and cannot own tasks or submit verdicts");
520
+ // #1809: `tasks: false` (a configured pull kind) is read here, never the transport, so allowing pull ownership later is a validation change.
521
+ if (definition?.tasks === false) return deny("policy", "a pull peer owns no task: its declaration has tasks: false");
515
522
  const ceiling = definition?.routing?.allowedRoles;
516
523
  const requiredRole = role === "reviewer" ? "reviewer" : ownerRoleOfClass(task.class);
517
524
  if (ceiling && !ceiling.includes(requiredRole)) return deny("policy", "adapter role ceiling excludes this assignment");
@@ -0,0 +1,205 @@
1
+ // #1856 T2: `ahub sdlc check`, a read-only audit of the lifecycle's moving parts. Pure over injected reads: it never writes, every GitHub read shares one deadline, a private task is only counted.
2
+ import { requiredCheckNames, type SdlcConfig, type SdlcGh, type SdlcMode } from "./sdlc.ts";
3
+
4
+ type CheckState = "ok" | "warn" | "fail" | "unknown";
5
+ type CheckSection = "config" | "repository" | "bindings" | "roadmap";
6
+ const CHECK_SECTIONS: readonly CheckSection[] = ["config", "repository", "bindings", "roadmap"];
7
+ /** A non-ok row always carries its cause and a runnable next step. */
8
+ interface SdlcCheckRow { section: CheckSection; id: string; state: CheckState; detail: string; cause?: string; next?: string }
9
+ interface SdlcCheckTask {
10
+ id: number; state: string; /** Public title only (`Tasks.publicTitle`). */ title: string; pii: boolean; branch?: string;
11
+ sdlc?: { repo?: string; issue?: number; pr?: number; localHead?: string };
12
+ }
13
+ interface RoadmapFinding { rule: number; milestone: number | null; items: string[]; cause: string; remedy: string }
14
+ interface SdlcCheckInput {
15
+ /** Skips every GitHub read and every check that needs one (`ahub doctor` uses this). */
16
+ offline: boolean;
17
+ /** The mode and required checks the running hub loaded. */
18
+ running: { mode: SdlcMode; requiredChecks: readonly string[]; /** The list that applies to this repository (a `repos` override included); defaults to requiredChecks. */ effectiveChecks?: readonly string[] };
19
+ /** The file on disk: parsed, or the parse failure; `present` is false when the file does not exist. */
20
+ file: () => { present: boolean; config: SdlcConfig };
21
+ /** Rostered holders of each flow role as the loader settled them. */
22
+ holders: Record<"planner" | "reviewer" | "conductor", readonly string[]>;
23
+ repository: string | undefined;
24
+ gh: SdlcGh;
25
+ /** The check names the latest completed default-branch workflow run produced (init's bounded discovery). */
26
+ discover: (gh: SdlcGh) => Promise<{ names: readonly string[]; source: string; reason?: string }>;
27
+ securityScan: () => { configured: boolean; counts?: Record<string, number | null> };
28
+ /** Unsettled tasks only; the caller lists proposed, in_progress, in_review and changes_requested. */
29
+ tasks: readonly SdlcCheckTask[];
30
+ /** Present only when milestones or a tracked docs/roadmap.json exist. */
31
+ roadmap?: {
32
+ drift: () => Promise<{ findings: RoadmapFinding[]; unknown: number[]; truncated?: true }>;
33
+ /** `Tasks.roadmapUnplaced`: milestone placement with issue inheritance already applied. */
34
+ unplaced: () => Promise<{ tasks: readonly { id: number }[]; issues: readonly { ref: string }[]; partial: boolean; unavailable: readonly string[]; more: { issues: number; tasks: number } }>;
35
+ };
36
+ now?: () => number;
37
+ deadlineMs?: number;
38
+ }
39
+ export interface SdlcCheckReport {
40
+ /** True when no row failed; the control reply keeps its own `ok`. */ passed: boolean; offline: boolean; deadlineMs: number; rows: SdlcCheckRow[];
41
+ counts: Record<CheckState, number>; /** Private unsettled tasks, never described. */ withheld: number;
42
+ }
43
+
44
+ const CHECK_DEADLINE_MS = 20_000;
45
+ const READ_MS = 8_000, READ_BYTES = 512 * 1024, LIST = 100, SHOWN = 8;
46
+ const short = (text: string, max = 160) => (text.length > max ? `${text.slice(0, max - 1)}…` : text).replace(/[\u0000-\u001f\u007f]/g, " ");
47
+ const ids = (list: readonly number[]) => `${list.slice(0, SHOWN).map(id => `#${id}`).join(", ")}${list.length > SHOWN ? ` and ${list.length - SHOWN} more` : ""}`;
48
+ /** Exactly one unqualified `#N` in a title; `owner/repo#N` and several numbers stay unnamed. */
49
+ function titleIssue(title: string): number | undefined {
50
+ const found = [...title.matchAll(/(?<![A-Za-z0-9_/.-])#([1-9][0-9]*)\b/g)].map(match => Number(match[1]));
51
+ const unique = [...new Set(found)];
52
+ return unique.length === 1 && Number.isSafeInteger(unique[0]) ? unique[0] : undefined;
53
+ }
54
+
55
+ export async function runSdlcCheck(input: SdlcCheckInput): Promise<SdlcCheckReport> {
56
+ const now = input.now ?? (() => performance.now()), deadlineMs = input.deadlineMs ?? CHECK_DEADLINE_MS, deadline = now() + deadlineMs;
57
+ const rows: SdlcCheckRow[] = [];
58
+ const add = (section: CheckSection, id: string, state: CheckState, detail: string, cause?: string, next?: string) => {
59
+ if (state !== "ok" && (!cause || !next)) throw new Error(`sdlc check row ${id} needs a cause and a next step`);
60
+ rows.push({ section, id, state, detail: short(detail, 240), ...(cause ? { cause: short(cause, 400) } : {}), ...(next ? { next: short(next, 240) } : {}) });
61
+ };
62
+ // One shared allowance for every GitHub read; an exhausted deadline is an unknown row, never a hang.
63
+ const gh: SdlcGh = async (args, timeoutMs, cwd, maxBytes) => {
64
+ if (input.offline) throw new Error("offline");
65
+ const remaining = deadline - now();
66
+ if (remaining <= 0) throw new Error("deadline");
67
+ return input.gh(args, Math.min(timeoutMs ?? READ_MS, remaining), cwd, maxBytes);
68
+ };
69
+ const read = async (args: string[]): Promise<unknown | undefined> => {
70
+ try { const reply = await gh(args, READ_MS, undefined, READ_BYTES); if (reply.code !== 0 || Buffer.byteLength(reply.stdout) >= READ_BYTES) return undefined; return JSON.parse(reply.stdout); }
71
+ catch { return undefined; }
72
+ };
73
+
74
+ // 1. Lifecycle config and roles.
75
+ let file: { present: boolean; config: SdlcConfig } | undefined, parseError: string | undefined;
76
+ try { file = input.file(); } catch (error) { parseError = error instanceof Error ? error.message : "unreadable"; }
77
+ if (!file) add("config", "sdlc.toml", "fail", ".agenthub/sdlc.toml does not parse", parseError!, "fix .agenthub/sdlc.toml, then run ahub restart; the running hub keeps its last good configuration until then");
78
+ else if (!file.present) add("config", "sdlc.toml", "warn", "no .agenthub/sdlc.toml", "the lifecycle is off without the file", "ahub init --sdlc advise --dry-run");
79
+ else add("config", "sdlc.toml", "ok", `parses; mode ${file.config.mode}`);
80
+ if (file) {
81
+ const mode = file.config.mode;
82
+ if (mode === "off" && file.present) add("config", "mode", "warn", "mode is off", "no lifecycle gates or receipts run in mode off", "ahub init --sdlc advise --dry-run");
83
+ else if (mode !== "off") add("config", "mode", "ok", `mode ${mode}`);
84
+ const sameChecks = JSON.stringify([...file.config.requiredChecks]) === JSON.stringify([...input.running.requiredChecks]);
85
+ if (mode !== input.running.mode || !sameChecks) add("config", "restart", "warn", `the running hub holds mode ${input.running.mode}, the file says ${mode}${sameChecks ? "" : " and other required_checks"}`, "an edit of .agenthub/sdlc.toml applies only after a restart", "ahub restart");
86
+ else add("config", "restart", "ok", "the running hub matches the file");
87
+ }
88
+ for (const role of ["planner", "reviewer", "conductor"] as const) {
89
+ const holders = input.holders[role];
90
+ if (holders.length) add("config", `role ${role}`, "ok", `${role} ${holders.join(", ")}`);
91
+ else add("config", `role ${role}`, "warn", `no rostered ${role}`,
92
+ role === "conductor" ? "no rostered peer holds the conductor role, so the person conducts from ahub console" : role === "planner" ? "no rostered planner is eligible, so plan work falls back to the first eligible rostered kind or has none" : "no rostered reviewer can run, so reviews go to the person",
93
+ "ahub roles, then ahub roster add <peer> for a peer that can hold it");
94
+ }
95
+
96
+ // 2. Repository and required checks (skipped offline).
97
+ const enabled = input.running.mode !== "off", repo = input.repository;
98
+ if (!input.offline) {
99
+ if (!repo) add("repository", "origin", "warn", "no GitHub origin", "origin does not name a GitHub owner/repo, so CI, PR and issue reads cannot run", "git remote add origin <https://github.com/owner/repo.git>");
100
+ else add("repository", "origin", "ok", repo);
101
+ if (repo) {
102
+ let auth: boolean | undefined;
103
+ try { auth = (await gh(["auth", "status"], READ_MS)).code === 0; } catch { auth = undefined; }
104
+ if (auth === true) add("repository", "gh auth", "ok", "gh is authenticated");
105
+ else if (auth === false) add("repository", "gh auth", enabled ? "fail" : "warn", "gh is not authenticated", "gh auth status failed, so no GitHub read below can run", "gh auth login");
106
+ else add("repository", "gh auth", "unknown", "gh auth could not be read", "the 20 s GitHub deadline passed or gh is missing", "gh auth status");
107
+ }
108
+ const required = input.running.effectiveChecks ?? input.running.requiredChecks;
109
+ if (!required.length) add("repository", "required_checks", enabled ? "warn" : "ok", enabled ? "required_checks is empty" : "required_checks is empty (mode off)",
110
+ "with no required check the merge and review gates have nothing to compare CI against", "ahub sdlc configure --required-checks check,lint");
111
+ else if (repo) {
112
+ let found: Awaited<ReturnType<SdlcCheckInput["discover"]>> | undefined;
113
+ try { found = await input.discover(gh); } catch { found = undefined; }
114
+ if (!found || !found.names.length) add("repository", "required_checks", "unknown", `${required.length} required, none compared`, found?.reason ?? "the default branch's check names could not be read", "gh run list --branch main --limit 1, or pass the names to ahub sdlc configure --required-checks");
115
+ else {
116
+ const names = new Set(found.names), unmatched = requiredCheckNames(repo, required).filter(name => !names.has(name));
117
+ if (unmatched.length) add("repository", "required_checks", "warn", `${unmatched.length} of ${required.length} required checks not produced by ${found.source}`, `no completed default-branch job is named ${unmatched.map(name => `"${short(name, 60)}"`).join(", ")}; the gate would wait for a check that never reports`, `ahub sdlc configure --required-checks ${found.names.join(",")}`);
118
+ else add("repository", "required_checks", "ok", `${required.length} required checks all produced (${found.source})`);
119
+ }
120
+ }
121
+ const scan = input.securityScan();
122
+ if (scan.configured) {
123
+ const counts = scan.counts;
124
+ if (!counts) add("repository", "security_scan", "unknown", "no recorded scan", "[security_scan] is configured and no scan has run yet", "ahub sdlc status shows the scan counts once one has run");
125
+ else {
126
+ const unknown = Object.entries(counts).filter(([, value]) => value === null || value === undefined).map(([source]) => source);
127
+ if (unknown.length) add("repository", "security_scan", "warn", `${unknown.length} source${unknown.length === 1 ? "" : "s"} unknown`, `the latest scan could not read ${unknown.join(", ")}`, "ahub sdlc status");
128
+ else add("repository", "security_scan", "ok", "all sources read in the latest scan");
129
+ }
130
+ }
131
+ }
132
+
133
+ // 3. Active task bindings (non-private, unsettled).
134
+ const visible = input.tasks.filter(task => !task.pii), withheld = input.tasks.length - visible.length;
135
+ const noIssue = visible.filter(task => !task.sdlc?.issue && titleIssue(task.title) !== undefined).map(task => task.id);
136
+ if (noIssue.length) add("bindings", "issue binding", "warn", `${noIssue.length} task${noIssue.length === 1 ? "" : "s"} name an issue but record none: ${ids(noIssue)}`, "sdlc.issue is empty although the title names one #N, so milestone inheritance and issue links are missing",
137
+ `ahub sdlc record ${noIssue[0]} '{"repo":"${repo ?? "owner/repo"}","issue":${titleIssue(visible.find(task => task.id === noIssue[0])!.title)}}'`);
138
+ else add("bindings", "issue binding", "ok", visible.length ? "every task that names an issue records it" : "no unsettled task");
139
+ if (input.offline) add("bindings", "pr binding", "unknown", "not read offline", "PR bindings need GitHub, and this view makes no network call", "ahub sdlc check");
140
+ else if (!repo) add("bindings", "pr binding", "unknown", "not read", "no GitHub origin to read PRs from", "git remote add origin <https://github.com/owner/repo.git>");
141
+ else {
142
+ const prs = await read(["pr", "list", "--repo", repo, "--state", "all", "--limit", String(LIST), "--json", "number,state,headRefName,headRefOid"]) as { number: number; state: string; headRefName: string; headRefOid: string }[] | undefined;
143
+ if (!Array.isArray(prs)) add("bindings", "pr binding", "unknown", "PRs not read", "the GitHub PR list was unavailable or past the deadline", `gh pr list --repo ${repo} --state all`);
144
+ else {
145
+ const byNumber = new Map(prs.map(pr => [pr.number, pr])), unbound: number[] = [], lagging: number[] = [], merged: { id: number; pr: number }[] = [];
146
+ for (const task of visible) {
147
+ const bound = task.sdlc?.pr === undefined ? undefined : byNumber.get(task.sdlc.pr);
148
+ if (task.sdlc?.pr !== undefined && bound?.state === "MERGED" && task.state !== "approved") merged.push({ id: task.id, pr: task.sdlc.pr });
149
+ if (bound?.state === "OPEN" && task.sdlc?.localHead !== undefined && task.sdlc.localHead !== bound.headRefOid) lagging.push(task.id);
150
+ const open = task.branch ? prs.find(pr => pr.state === "OPEN" && pr.headRefName === task.branch) : undefined;
151
+ if (open && task.sdlc?.pr === undefined) unbound.push(task.id);
152
+ }
153
+ const note = prs.length >= LIST ? ` (the latest ${LIST} PRs were read)` : "";
154
+ if (unbound.length) add("bindings", "pr binding", "warn", `${unbound.length} open PR${unbound.length === 1 ? "" : "s"} not recorded on the task: ${ids(unbound)}${note}`, "the task's branch has an open PR and no sdlc.pr, so ci-watch observes nothing", `ahub sdlc record ${unbound[0]} '{"pr":<number>,"localHead":"<head sha>"}'`);
155
+ else add("bindings", "pr binding", "ok", `every open PR of a task branch is recorded${note}`);
156
+ if (lagging.length) add("bindings", "head binding", "warn", `${lagging.length} task${lagging.length === 1 ? "" : "s"} record an older head than the open PR: ${ids(lagging)}`, "sdlc.localHead lags the PR's head, so ci-watch watches a superseded commit", `ahub sdlc record ${lagging[0]} '{"localHead":"<current head sha>"}'`);
157
+ else add("bindings", "head binding", "ok", "recorded heads match their open PRs");
158
+ if (merged.length) add("bindings", "merged PR", "warn", `${merged.length} linked PR${merged.length === 1 ? "" : "s"} already merged: ${ids(merged.map(row => row.id))}`, "the PR merged on GitHub and the task still waits for adopt-merge", `ahub sdlc adopt-merge ${merged[0]!.id} --pr ${merged[0]!.pr}`);
159
+ else add("bindings", "merged PR", "ok", "no linked PR is merged and waiting");
160
+ }
161
+ }
162
+ if (withheld) add("bindings", "private tasks", "ok", `${withheld} private task${withheld === 1 ? "" : "s"} withheld`);
163
+
164
+ // 4. Roadmap and issue hygiene, only when the project has one.
165
+ if (input.roadmap && !input.offline) {
166
+ let unplaced: Awaited<ReturnType<NonNullable<SdlcCheckInput["roadmap"]>["unplaced"]>> | undefined;
167
+ try {
168
+ const remaining = deadline - now();
169
+ unplaced = remaining > 0 ? await Promise.race([input.roadmap.unplaced(), new Promise<undefined>(accept => setTimeout(() => accept(undefined), remaining))]) : undefined;
170
+ } catch { unplaced = undefined; }
171
+ if (!unplaced) {
172
+ add("roadmap", "unplaced tasks", "unknown", "placement not read", "the roadmap placement read was unavailable or past the 20 s deadline", "ahub roadmap unplaced");
173
+ add("roadmap", "unplaced issues", "unknown", "placement not read", "the roadmap placement read was unavailable or past the 20 s deadline", "ahub roadmap unplaced");
174
+ } else {
175
+ const visibleIds = new Set(visible.map(task => task.id)), taskIds = unplaced.tasks.map(task => task.id).filter(id => visibleIds.has(id));
176
+ if (taskIds.length) add("roadmap", "unplaced tasks", "warn", `${taskIds.length} unsettled task${taskIds.length === 1 ? "" : "s"} in no milestone: ${ids(taskIds)}${unplaced.more.tasks ? " (at least; more were cut)" : ""}`, "no milestone holds the task directly or through its issue, so the roadmap omits it", "ahub roadmap unplaced");
177
+ else add("roadmap", "unplaced tasks", "ok", "every unsettled task is in a milestone, directly or through its issue");
178
+ if (unplaced.unavailable.includes("issues")) add("roadmap", "unplaced issues", "unknown", "open issues not read", "the GitHub issue list was unavailable or past the deadline", "ahub roadmap unplaced");
179
+ else if (unplaced.issues.length) add("roadmap", "unplaced issues", "warn", `${unplaced.issues.length + unplaced.more.issues} open issue${unplaced.issues.length + unplaced.more.issues === 1 ? "" : "s"} in no milestone: ${unplaced.issues.slice(0, SHOWN).map(issue => issue.ref).join(", ")}${unplaced.partial ? " (partial read)" : ""}`, "the roadmap shows only issues linked to a milestone", "ahub roadmap unplaced");
180
+ else if (unplaced.partial) add("roadmap", "unplaced issues", "unknown", "issue read was partial", "the issue list or placement read was partial", "ahub roadmap unplaced");
181
+ else add("roadmap", "unplaced issues", "ok", "every open issue is in a milestone");
182
+ }
183
+ let drift: Awaited<ReturnType<NonNullable<SdlcCheckInput["roadmap"]>["drift"]>> | undefined;
184
+ try {
185
+ const remaining = deadline - now();
186
+ drift = remaining > 0 ? await Promise.race([input.roadmap.drift(), new Promise<undefined>(accept => setTimeout(() => accept(undefined), remaining))]) : undefined;
187
+ } catch { drift = undefined; }
188
+ if (!drift) add("roadmap", "roadmap drift", "unknown", "drift not read", "the roadmap check was unavailable or past the 20 s deadline", "ahub roadmap check");
189
+ else {
190
+ const lagging = drift.findings.filter(finding => finding.rule === 2), mismatch = drift.findings.filter(finding => finding.rule === 8), other = drift.findings.filter(finding => ![2, 8].includes(finding.rule));
191
+ if (lagging.length) add("roadmap", "settled issues open", "warn", `${lagging.length} merged task${lagging.length === 1 ? "" : "s"} with an issue still open past 24 h`, lagging[0]!.cause, lagging[0]!.remedy);
192
+ else add("roadmap", "settled issues open", drift.unknown.some(rule => rule === 1 || rule === 2) ? "unknown" : "ok", "no merged task leaves its issue open past 24 h", ...(drift.unknown.some(rule => rule === 1 || rule === 2) ? ["an issue state or merge time was unavailable", "ahub roadmap check"] as const : []));
193
+ if (mismatch.length) add("roadmap", "roadmap export", "warn", "docs/roadmap.json or docs/roadmap.md differs from the board", mismatch[0]!.cause, mismatch[0]!.remedy);
194
+ else add("roadmap", "roadmap export", drift.unknown.includes(8) ? "unknown" : "ok", drift.unknown.includes(8) ? "export not compared" : "export matches the board", ...(drift.unknown.includes(8) ? ["the roadmap export could not be read", "ahub roadmap check"] as const : []));
195
+ if (other.length) add("roadmap", "roadmap drift", "warn", `${other.length} other roadmap finding${other.length === 1 ? "" : "s"}${drift.truncated ? " (truncated)" : ""}`, other[0]!.cause, other[0]!.remedy);
196
+ }
197
+ }
198
+
199
+ const counts: Record<CheckState, number> = { ok: 0, warn: 0, fail: 0, unknown: 0 };
200
+ for (const row of rows) counts[row.state]++;
201
+ return { passed: counts.fail === 0, offline: input.offline, deadlineMs, rows, counts, withheld };
202
+ }
203
+
204
+ /** CLI output standard v1: exit 1 on a fail row; warn and unknown change nothing. */
205
+ export const sdlcCheckExitCode = (report: Pick<SdlcCheckReport, "counts">): 0 | 1 => report.counts.fail > 0 ? 1 : 0;