@staix/agent-hub 0.52.0 → 0.54.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 (196) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +4 -3
  3. package/docs/addons/open-code-review.md +3 -6
  4. package/docs/agent-notes/README.md +1 -1
  5. package/docs/agent-notes/adapters.md +5 -4
  6. package/docs/agent-notes/budget.md +2 -2
  7. package/docs/agent-notes/bus.md +1 -0
  8. package/docs/agent-notes/daemon.md +6 -5
  9. package/docs/agent-notes/models.md +1 -1
  10. package/docs/agent-notes/tasks.md +3 -3
  11. package/docs/agent-notes/tests.md +4 -4
  12. package/docs/contracts/companion-cli-v2.json +90 -0
  13. package/docs/contracts/companion-cli-v3.json +348 -0
  14. package/docs/design/adapters.md +1 -1
  15. package/docs/design/agent-hub-architecture.md +8 -5
  16. package/docs/design/bus.md +1 -1
  17. package/docs/design/cli-output-inventory.md +4 -2
  18. package/docs/design/execution-reference.md +1 -1
  19. package/docs/design/guidance-experiments.md +1 -0
  20. package/docs/design/guidance-probes.md +1 -0
  21. package/docs/design/model-routes.md +20 -5
  22. package/docs/design/roadmap.md +6 -4
  23. package/docs/design/task-board.md +21 -2
  24. package/docs/dogfood.md +13 -6
  25. package/docs/events.md +1 -1
  26. package/docs/memory.md +2 -2
  27. package/docs/operations.md +158 -50
  28. package/docs/quickstart.md +14 -2
  29. package/docs/security.md +17 -9
  30. package/docs/specs/2026-09-19-agent-hub-design.md +5 -3
  31. package/docs/specs/2026-09-19-multi-project-design.md +1 -1
  32. package/docs/specs/2026-09-20-upgrade-recovery-design.md +24 -0
  33. package/docs/specs/2026-12-04-arev-adoption-design.md +84 -0
  34. package/docs/specs/mcp-endpoint.md +15 -4
  35. package/docs/specs/relay-contract.md +38 -0
  36. package/docs/verification/2026-12-04-host-shared-receipts.md +43 -0
  37. package/docs/verification/2026-12-05-0.53.0.md +101 -0
  38. package/docs/verification/2026-12-05-agy-1.5.24.md +55 -0
  39. package/docs/verification/2026-12-05-claude-implementer-2.1.337.md +43 -0
  40. package/docs/verification/2026-12-06-0.54.0.md +76 -0
  41. package/docs/verification/2026-12-06-codex-0174-reviewer-isolation.md +43 -0
  42. package/docs/verification/2026-12-06-codex-0174-reviewer-tool-call.md +34 -0
  43. package/docs/verification/2026-12-06-compat-codex-capabilities-0.174.0.md +25 -0
  44. package/docs/verification/2026-12-06-compat-pi-1.8.0.md +23 -0
  45. package/docs/verified.json +38 -29
  46. package/package.json +9 -3
  47. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  48. package/plugins/agent-hub/.mcp.json +1 -1
  49. package/plugins/agent-hub/compat.json +9 -5
  50. package/plugins/agent-hub/kimi-hook.js +892 -874
  51. package/plugins/agent-hub/relay-launcher.js +24 -0
  52. package/plugins/agent-hub/server.js +27271 -25146
  53. package/src/adapters/acp-session-model.ts +1 -1
  54. package/src/adapters/acp.ts +5 -4
  55. package/src/adapters/agy/definition.ts +1 -1
  56. package/src/adapters/agy/hooks.ts +1 -1
  57. package/src/adapters/channel-peer.ts +3 -1
  58. package/src/adapters/claude-channel-evidence.ts +26 -1
  59. package/src/adapters/claude-channel.ts +27 -30
  60. package/src/adapters/claude-connection-policy.ts +62 -0
  61. package/src/adapters/claude-relay.ts +255 -0
  62. package/src/adapters/codex-review-isolation.ts +1 -2
  63. package/src/adapters/compat.ts +28 -18
  64. package/src/adapters/definitions/native-cli-preview-pi.ts +2 -1
  65. package/src/adapters/definitions/native-config-defaults.ts +1 -1
  66. package/src/adapters/definitions/native-context.ts +1 -2
  67. package/src/adapters/definitions/native-factories.ts +4 -1
  68. package/src/adapters/definitions/native-quota.ts +1 -1
  69. package/src/adapters/definitions/native-recovery.ts +3 -1
  70. package/src/adapters/external-modules.ts +2 -2
  71. package/src/adapters/kimi-review.ts +1 -1
  72. package/src/adapters/kimi-tui-facts.ts +1 -1
  73. package/src/adapters/local-worker.ts +3 -3
  74. package/src/adapters/native-capabilities.ts +1 -1
  75. package/src/adapters/pi.ts +26 -7
  76. package/src/adapters/registry-types.ts +2 -0
  77. package/src/adapters/relay-launcher.ts +27 -0
  78. package/src/adapters/reviewer-mcp.ts +1 -1
  79. package/src/cli/agents.ts +20 -8
  80. package/src/cli/agy-mcp.ts +1 -1
  81. package/src/cli/claude-profile-hook.ts +1 -1
  82. package/src/cli/command-table.ts +1 -0
  83. package/src/cli/commands/agents.ts +18 -1
  84. package/src/cli/commands/doctor.ts +18 -4
  85. package/src/cli/commands/launch-line.ts +32 -0
  86. package/src/cli/commands/status.ts +14 -3
  87. package/src/cli/help.ts +7 -4
  88. package/src/cli/identity.ts +1 -1
  89. package/src/cli/init-roles.ts +1 -1
  90. package/src/cli/init-settings.ts +1 -1
  91. package/src/cli/launch-line-plan.ts +82 -0
  92. package/src/cli/launch-line-project.ts +13 -0
  93. package/src/cli/main.ts +10 -9
  94. package/src/cli/pi-steps-warning.ts +14 -0
  95. package/src/cli/recovery-package.ts +60 -6
  96. package/src/cli/reset.ts +1 -1
  97. package/src/cli/shell-quote.ts +1 -3
  98. package/src/cli/upgrade-interactive.ts +7 -2
  99. package/src/cli/upgrade-keep-plan.ts +47 -0
  100. package/src/cli/upgrade-restore-state.ts +1 -1
  101. package/src/cli/upgrade-runtime.ts +119 -18
  102. package/src/cli/upgrade.ts +17 -2
  103. package/src/hub/accounts.ts +8 -4
  104. package/src/hub/action-class.ts +1 -3
  105. package/src/hub/adec-triage.ts +105 -0
  106. package/src/hub/autonomy.ts +1 -1
  107. package/src/hub/board.ts +3 -27
  108. package/src/hub/bus.ts +39 -6
  109. package/src/hub/capabilities.ts +1 -1
  110. package/src/hub/channel-project-base.ts +46 -0
  111. package/src/hub/channel-project.ts +21 -46
  112. package/src/hub/config-apply.ts +1 -1
  113. package/src/hub/config-edit.ts +1 -1
  114. package/src/hub/config-tier.ts +1 -1
  115. package/src/hub/config.ts +2 -2
  116. package/src/hub/confirmation-matrix.ts +1 -1
  117. package/src/hub/control/board-messages.ts +415 -0
  118. package/src/hub/control/dashboard-messages.ts +221 -0
  119. package/src/hub/control/delivery-messages.ts +356 -0
  120. package/src/hub/control/dispatch.ts +114 -0
  121. package/src/hub/control/hub-tool-helpers.ts +243 -0
  122. package/src/hub/control/hub-tools.ts +147 -0
  123. package/src/hub/control/native-messages.ts +665 -0
  124. package/src/hub/control/operations-messages.ts +269 -0
  125. package/src/hub/control/peer-messages.ts +126 -0
  126. package/src/hub/control/recovery-messages.ts +391 -0
  127. package/src/hub/control/recovery-operation.ts +480 -0
  128. package/src/hub/control/scope.ts +460 -0
  129. package/src/hub/control/sdlc-messages.ts +373 -0
  130. package/src/hub/control/task-ops-more.ts +245 -0
  131. package/src/hub/control/task-ops.ts +553 -0
  132. package/src/hub/control/ui-actions.ts +241 -0
  133. package/src/hub/control-write-trace.ts +1 -4
  134. package/src/hub/daemon.ts +485 -4324
  135. package/src/hub/delivery-hints.ts +2 -0
  136. package/src/hub/delivery-journal.ts +17 -6
  137. package/src/hub/events.ts +2 -1
  138. package/src/hub/execution-reference.ts +1 -1
  139. package/src/hub/host.ts +41 -9
  140. package/src/hub/hub-tools.ts +3 -4
  141. package/src/hub/invocations.ts +1 -1
  142. package/src/hub/lifecycle.ts +4 -3
  143. package/src/hub/mcp-endpoint-serve.ts +4 -3
  144. package/src/hub/mcp-endpoint.ts +15 -6
  145. package/src/hub/memory-profile-check.ts +1 -1
  146. package/src/hub/no-writes.ts +1 -1
  147. package/src/hub/peers.ts +2 -0
  148. package/src/hub/pi-exit-policy.ts +27 -0
  149. package/src/hub/progress.ts +1 -1
  150. package/src/hub/project-runtime-state.ts +17 -4
  151. package/src/hub/project-runtime.ts +3 -1
  152. package/src/hub/protocol-window.ts +1 -1
  153. package/src/hub/recovery-continuity.ts +3 -3
  154. package/src/hub/recovery-kept-roster.ts +50 -0
  155. package/src/hub/review-anchor.ts +13 -181
  156. package/src/hub/review-brief.ts +78 -28
  157. package/src/hub/review-findings.ts +15 -193
  158. package/src/hub/review-ledger.ts +162 -0
  159. package/src/hub/review-material.ts +3 -3
  160. package/src/hub/reviewer-pool.ts +4 -2
  161. package/src/hub/roadmap-issue-states.ts +65 -14
  162. package/src/hub/roadmap-sync.ts +39 -14
  163. package/src/hub/routing.ts +9 -0
  164. package/src/hub/runtime-capture-prune.ts +8 -2
  165. package/src/hub/runtime-package-assets.ts +3 -0
  166. package/src/hub/sdlc-release-policy.ts +1 -2
  167. package/src/hub/settings.ts +1 -1
  168. package/src/hub/spec-ack-tool.ts +4 -0
  169. package/src/hub/spec-report-history.ts +36 -0
  170. package/src/hub/specs.ts +1 -4
  171. package/src/hub/supervision.ts +33 -6
  172. package/src/hub/tasks-audit.ts +390 -0
  173. package/src/hub/tasks-backlog.ts +522 -0
  174. package/src/hub/tasks-handoff.ts +208 -0
  175. package/src/hub/tasks-release.ts +257 -0
  176. package/src/hub/tasks-roadmap.ts +17 -3
  177. package/src/hub/tasks-specs.ts +672 -0
  178. package/src/hub/tasks-types.ts +334 -0
  179. package/src/hub/tasks.ts +286 -1961
  180. package/src/hub/upgrade-session-contract.ts +11 -0
  181. package/src/local/probe-sandbox.ts +1 -2
  182. package/src/local/probe-workspace.ts +1 -1
  183. package/src/models/route/config.ts +4 -4
  184. package/src/models/route/decision.ts +18 -10
  185. package/src/models/route/observation-signals.ts +1 -2
  186. package/src/models/route/runtime.ts +8 -5
  187. package/src/npm-artifact.ts +76 -0
  188. package/src/omniroute/client.ts +6 -0
  189. package/src/pi/extension.ts +5 -2
  190. package/src/pi/install.ts +77 -0
  191. package/src/pi/pin.ts +49 -0
  192. package/src/primitives.ts +14 -0
  193. package/src/version.ts +2 -0
  194. package/templates/adec/README.md +10 -6
  195. package/templates/config.json +1 -1
  196. package/templates/specs.block.md +1 -0
@@ -1,193 +1,15 @@
1
- import { types } from "node:util";
2
- import { sanitize } from "./envelope.ts";
3
- import { parseReviewAnchor } from "./review-anchor.ts";
4
- import type { ReviewAnchor } from "@staix/agent-console/contract";
5
-
6
- /** #1403 A1: the four things a security finding must name: who is lower-trust, the control meant to hold, the resource affected and the result observed. */
7
- export interface FindingBoundary { principal: string; control: string; resource: string; result: string }
8
- export interface ReviewFinding {
9
- id: string;
10
- pass: "bugs" | "security" | "compliance";
11
- severity: "important" | "nit";
12
- path?: string;
13
- disposition: "open" | "fixed" | "false_positive" | "accepted";
14
- rationale?: string;
15
- reopen_reason?: string;
16
- anchor?: ReviewAnchor;
17
- /** #1403 A1, important security findings only (an enabled lifecycle). `needs_validation` is a source-grounded hypothesis blocked on `blocker`; it never blocks approval. */
18
- state?: "confirmed" | "needs_validation";
19
- boundary?: FindingBoundary;
20
- blocker?: string;
21
- /** #1403 B4 (an enabled lifecycle). Absent reads as `introduced`; an open `pre_existing` Important never blocks and never carries across heads. */
22
- origin?: "introduced" | "pre_existing";
23
- }
24
- /**
25
- * How `parseReviewFindings` treats the #1403 fields. `off` (the default, lifecycle off): they are unknown fields, refused as before. `required` (advise and enforce): accepted, and an
26
- * open important security finding must carry `state` and `boundary`. `stored`: a report this hub already validated, read back: the shapes are checked, nothing is required again.
27
- */
28
- export type FindingContract = "off" | "required" | "stored";
29
- export interface ReviewFindingSet { head?: string; items: ReviewFinding[] }
30
- /** `openImportant` counts only findings that block approval; `needsValidation` and `preExisting` (open Important that do not) appear only when nonzero, so an off-mode readback is unchanged. */
31
- export interface ReviewFindingTally { important: number; nit: number; openImportant: number; openNit: number; fixed: number; falsePositive: number; accepted: number; needsValidation?: number; preExisting?: number }
32
- export const DEFAULT_MAX_NITS = 5;
33
- const MAX_ITEMS = 64, MAX_BYTES = 64 * 1024;
34
- const fail = (reason: string): never => { throw new Error("review findings: " + reason); };
35
- const BASE_FIELDS = ["id", "pass", "severity", "path", "disposition", "rationale", "anchor"], SECURITY_FIELDS = ["state", "boundary", "blocker", "origin"];
36
- const BOUNDARY_FIELDS = ["principal", "control", "resource", "result"] as const;
37
- function fields(raw: unknown, allowed: readonly string[] = BASE_FIELDS): Record<string, PropertyDescriptor> {
38
- if (!raw || typeof raw !== "object" || types.isProxy(raw) || Array.isArray(raw)
39
- || ![Object.prototype, null].includes(Object.getPrototypeOf(raw)) || Object.getOwnPropertySymbols(raw).length) return fail("plain own-data finding required");
40
- const descriptors: Record<string, PropertyDescriptor> = Object.assign(Object.create(null), Object.getOwnPropertyDescriptors(raw));
41
- if (Object.values(descriptors).some(field => !Object.hasOwn(field, "value") || !field.enumerable)) return fail("accessors and hidden fields refused");
42
- if (Object.keys(descriptors).some(key => !allowed.includes(key))) return fail("unknown finding field");
43
- return descriptors;
44
- }
45
- function text(raw: unknown, max: number, path: boolean): string {
46
- if (typeof raw !== "string" || !raw.trim() || Buffer.byteLength(raw) > max
47
- || path && /[\p{Cc}\p{Cf}]/u.test(raw)) return fail("invalid bounded finding text");
48
- const clean = sanitize(raw.trim());
49
- if (Buffer.byteLength(clean) > max) return fail("sanitized finding text exceeds its bound");
50
- return clean;
51
- }
52
- function boundaryOf(raw: unknown): FindingBoundary {
53
- const given = fields(raw, BOUNDARY_FIELDS);
54
- if (BOUNDARY_FIELDS.some(key => given[key] === undefined)) return fail("boundary needs principal, control, resource and result");
55
- return Object.fromEntries(BOUNDARY_FIELDS.map(key => [key, text(given[key]!.value, 512, false)])) as unknown as FindingBoundary;
56
- }
57
- const NEEDS_SECURITY_FIELDS = "an important security finding needs state (confirmed or needs_validation) and boundary {principal, control, resource, result}: the lower-trust principal, the control that was meant to hold, the resource affected and the result observed; a missing best practice or a guessed deployment fact is not a finding";
58
- /** Supplied findings are validated independently of lifecycle mode, before any board effect. */
59
- export function parseReviewFindings(raw: unknown, options: { person: boolean; maxNits: number; contract?: FindingContract; reopenReason?: boolean }): ReviewFinding[] {
60
- if (typeof options.person !== "boolean" || !Number.isSafeInteger(options.maxNits) || options.maxNits < 0 || options.maxNits > MAX_ITEMS) return fail("invalid finding authority or nit limit");
61
- const contract = options.contract ?? "off";
62
- if (contract !== "off" && contract !== "required" && contract !== "stored") return fail("invalid finding contract");
63
- if (raw === undefined) return [];
64
- if (!Array.isArray(raw) || types.isProxy(raw) || Object.getPrototypeOf(raw) !== Array.prototype
65
- || Object.getOwnPropertySymbols(raw).length || raw.length > MAX_ITEMS) return fail("at most 64 own-data findings required");
66
- const descriptors: Record<string, PropertyDescriptor> = Object.assign(Object.create(null), Object.getOwnPropertyDescriptors(raw));
67
- if (Object.keys(descriptors).length !== raw.length + 1) return fail("dense finding array required");
68
- const ids = new Set<string>();
69
- const result = Array.from({ length: raw.length }, (_, index): ReviewFinding => {
70
- const entry = descriptors[String(index)];
71
- if (!entry || !Object.hasOwn(entry, "value") || !entry.enumerable) return fail("finding array accessors refused");
72
- const item = fields(entry.value, contract === "off" ? BASE_FIELDS : [...BASE_FIELDS, ...SECURITY_FIELDS, ...(contract === "stored" || options.reopenReason ? ["reopen_reason"] : [])]), id: unknown = item.id?.value, pass: unknown = item.pass?.value;
73
- const severity: unknown = item.severity?.value, disposition: unknown = item.disposition?.value;
74
- if (typeof id !== "string" || !/^[A-Za-z0-9._:-]+$/.test(id) || Buffer.byteLength(id) > 96 || ids.has(id)) return fail("invalid or duplicate finding id");
75
- ids.add(id);
76
- if (pass !== "bugs" && pass !== "security" && pass !== "compliance") return fail("invalid finding pass");
77
- if (severity !== "important" && severity !== "nit") return fail("invalid finding severity");
78
- if (disposition !== "open" && disposition !== "fixed" && disposition !== "false_positive" && disposition !== "accepted") return fail("invalid finding disposition");
79
- const path = item.path ? text(item.path.value, 512, true) : undefined;
80
- const rationale = item.rationale ? text(item.rationale.value, 2048, false) : undefined;
81
- const reopenReason = item.reopen_reason ? text(item.reopen_reason.value, 512, false) : undefined;
82
- const anchor = item.anchor ? parseReviewAnchor(item.anchor.value) : undefined;
83
- if (path !== undefined && anchor && path !== anchor.path) return fail("path and anchor.path differ; use the same task-scoped file path");
84
- if (disposition === "accepted" && (!options.person || !rationale)) return fail("accepted findings require a person and rationale");
85
- // #1403: only an enabled lifecycle reaches here with these fields (off refused them as unknown above).
86
- const state: unknown = item.state?.value, origin: unknown = item.origin?.value;
87
- if (item.state && state !== "confirmed" && state !== "needs_validation") return fail("invalid finding state");
88
- if (item.origin && origin !== "introduced" && origin !== "pre_existing") return fail("invalid finding origin");
89
- const boundary = item.boundary ? boundaryOf(item.boundary.value) : undefined;
90
- const blocker = item.blocker ? text(item.blocker.value, 512, false) : undefined;
91
- if ((state !== undefined || boundary !== undefined || blocker !== undefined) && !(pass === "security" && severity === "important")) return fail("state, boundary and blocker apply only to important security findings");
92
- if (contract === "required" && pass === "security" && severity === "important" && disposition === "open") {
93
- if (state === undefined || boundary === undefined) return fail(NEEDS_SECURITY_FIELDS);
94
- if (state === "needs_validation" && blocker === undefined) return fail("a needs_validation finding names its blocker: the missing fact that settles it");
95
- if (state === "confirmed" && blocker !== undefined) return fail("a confirmed finding carries no blocker; use needs_validation for a hypothesis blocked on a named fact");
96
- }
97
- return { id, pass, severity, disposition, ...(path !== undefined ? { path } : {}), ...(rationale !== undefined ? { rationale } : {}), ...(anchor ? { anchor } : {}), ...(reopenReason === undefined ? {} : { reopen_reason: reopenReason }),
98
- ...(state !== undefined ? { state } : {}), ...(boundary !== undefined ? { boundary } : {}), ...(blocker !== undefined ? { blocker } : {}), ...(origin !== undefined ? { origin } : {}) } as ReviewFinding;
99
- });
100
- if (result.filter(item => item.severity === "nit").length > options.maxNits) return fail("nit limit exceeded");
101
- if (Buffer.byteLength(JSON.stringify(result)) > MAX_BYTES) return fail("finding report exceeds 64 KiB");
102
- return result;
103
- }
104
-
105
- /**
106
- * #1436: a positional finding id is a review-local label (N1, F5, B1, nit-1, 3): a reviewer numbers its findings per review, so the same label on two tasks names two unrelated findings.
107
- * Only a label word or a single letter followed by digits counts, so a semantic id (compliance:hub-task-id-written-as-github-ref, sha256-pin) still can recur across tasks. REVIEW.md asks for semantic ids.
108
- */
109
- export function positionalFindingId(id: string): boolean {
110
- const local = id.replace(/^(?:bugs|security|compliance)[-_.:]/i, "");
111
- return /^(?:[a-z]|nits?|imp(?:ortant)?|finding|issue|bug|comment|note|item|sec|fix|review)?[-_.:]?\d{1,4}$/i.test(local);
112
- }
113
-
114
- /** Prefer live artifact identity, skipping malformed historical candidates rather than hiding a valid fallback. */
115
- export function findingHead(receipt?: { head?: string; reviewedHead?: string; localHead?: string }, evidence?: { head: string }, commit?: string): string | undefined {
116
- return [evidence?.head, receipt?.head, receipt?.reviewedHead, receipt?.localHead, commit]
117
- .find((head): head is string => typeof head === "string" && /^[a-f0-9]{40}$/.test(head));
118
- }
119
-
120
- /** An open Important blocks approval unless it is a hypothesis awaiting a named fact (`needs_validation`) or debt the change did not introduce (`pre_existing`). */
121
- export const blocksApproval = (item: ReviewFinding): boolean =>
122
- item.severity === "important" && item.disposition === "open" && item.state !== "needs_validation" && item.origin !== "pre_existing";
123
- /** What carries across heads: Important, except debt the reviewed change did not introduce. */
124
- const carries = (item: ReviewFinding): boolean => item.severity === "important" && item.origin !== "pre_existing";
125
- const SECURITY_KEYS = ["state", "boundary", "blocker", "origin"] as const;
126
- /**
127
- * A later report of an id, over its earlier one. The #1403 fields belong to the report that states them: a later report that omits `state`, `boundary`, `blocker` or `origin` has none of them
128
- * (an omitted origin means introduced), so a reclassification (a hypothesis re-reported as a bug, a pre_existing one re-reported as introduced) blocks as reported. The one exception: a report
129
- * that still says open cannot lower a finding that blocks approval, so that finding keeps its severity and its own four fields; only an explicit disposition settles it.
130
- */
131
- function merged(prior: ReviewFinding | undefined, item: ReviewFinding): ReviewFinding {
132
- const next: ReviewFinding = { ...prior, ...item };
133
- if (item.reopen_reason === undefined) delete next.reopen_reason;
134
- for (const key of SECURITY_KEYS) if (item[key] === undefined) delete next[key];
135
- if (prior && blocksApproval(prior) && item.disposition === "open" && !blocksApproval(item)) {
136
- next.severity = "important";
137
- for (const key of SECURITY_KEYS) { if (prior[key] === undefined) delete next[key]; else Object.assign(next, { [key]: prior[key] }); }
138
- }
139
- return next;
140
- }
141
- /**
142
- * Nits belong only to their head bucket, including the explicit undefined bucket.
143
- * Open Important is an obligation across heads until an explicit disposition resolves its ID globally.
144
- */
145
- export function findingsForHead(sets: readonly ReviewFindingSet[], head?: string): ReviewFinding[] {
146
- interface Entry { item: ReviewFinding; order: number }
147
- const current = new Map<string, Entry>(), important = new Map<string, Entry>();
148
- let order = 0;
149
- for (const set of sets) for (const item of set.items) {
150
- const key = item.id, position = order++;
151
- if (set.head === head) current.set(key, { item: { ...current.get(key)?.item, ...item }, order: position });
152
- const prior = important.get(key);
153
- if (carries(item)) {
154
- important.set(key, { item: merged(prior?.item, item), order: position });
155
- } else if (prior && (prior.item.disposition === "open" || item.disposition !== "open")) {
156
- // A nit/open reclassification (a nit, or #1403 pre_existing) cannot discharge Important. An explicit disposition can.
157
- important.set(key, { item: { ...merged(prior.item, item), severity: "important" }, order: position });
158
- }
159
- }
160
- for (const [key, entry] of important) {
161
- if (entry.item.disposition === "open") current.set(key, entry);
162
- else {
163
- const seen = current.get(key);
164
- // Settling on B also settles older A when A is queried again. A later new nit/open remains a head-local nit.
165
- if (seen?.item.disposition === "open" && seen.order <= entry.order) current.delete(key);
166
- }
167
- }
168
- return [...current.values()].map(entry => ({ ...entry.item }));
169
- }
170
- export function findingTally(items: readonly ReviewFinding[]): ReviewFindingTally {
171
- const tally: ReviewFindingTally = { important: 0, nit: 0, openImportant: 0, openNit: 0, fixed: 0, falsePositive: 0, accepted: 0 };
172
- for (const item of items) {
173
- tally[item.severity]++;
174
- if (item.disposition === "open") {
175
- if (item.severity === "nit") tally.openNit++;
176
- else if (blocksApproval(item)) tally.openImportant++;
177
- else if (item.state === "needs_validation") tally.needsValidation = (tally.needsValidation ?? 0) + 1;
178
- else tally.preExisting = (tally.preExisting ?? 0) + 1;
179
- } else tally[item.disposition === "false_positive" ? "falsePositive" : item.disposition]++;
180
- }
181
- return tally;
182
- }
183
-
184
- /**
185
- * #1403: the open Important findings that do not block approval and so get one follow-up card on approval, over every report of the task (a hypothesis or debt is head-local or settled later, so
186
- * the current head's view would lose it). `validation`: needs_validation, which wins over pre_existing; `preExisting`: debt the change did not introduce.
187
- */
188
- export function findingFollowUps(sets: readonly ReviewFindingSet[]): { validation: ReviewFinding[]; preExisting: ReviewFinding[] } {
189
- const latest = new Map<string, ReviewFinding>();
190
- for (const set of sets) for (const item of set.items) latest.set(item.id, merged(latest.get(item.id), item));
191
- const open = [...latest.values()].filter(item => item.severity === "important" && item.disposition === "open");
192
- return { validation: open.filter(item => item.state === "needs_validation"), preExisting: open.filter(item => item.state !== "needs_validation" && item.origin === "pre_existing") };
193
- }
1
+ export {
2
+ blocksApproval,
3
+ DEFAULT_MAX_NITS,
4
+ findingFollowUps,
5
+ findingHead,
6
+ findingsForHead,
7
+ findingTally,
8
+ parseReviewFindings,
9
+ positionalFindingId,
10
+ type FindingBoundary,
11
+ type FindingContract,
12
+ type ReviewFinding,
13
+ type ReviewFindingSet,
14
+ type ReviewFindingTally,
15
+ } from "@staix/agent-review/core";
@@ -0,0 +1,162 @@
1
+ // #1874 V4 step 5: a head-bound hub verdict is recorded in the AREV ledger, so `arev gate` answers for a hub-reviewed head
2
+ // the way it does for any other. Only the AREV core writes the ledger (`recordReview`, `resolveFinding`, `appendPacketEvent`);
3
+ // this module builds the report from what the hub already validated and never touches the ledger files itself.
4
+ import {
5
+ appendPacketEvent, buildPacket, packetSettings, readLedger, recordReview, resolveFinding, Refusal,
6
+ type PacketBundle, type RecordFinding, type ReviewFinding,
7
+ } from "@staix/agent-review/core";
8
+
9
+ export interface HubReviewRecord {
10
+ task: number;
11
+ /** The reviewed head: a full commit SHA. */
12
+ head: string;
13
+ /** The PR the packet is built for, when the task links one. */
14
+ pr?: number;
15
+ reviewer: string;
16
+ /** The reviewer's model family (`familyOf`); a person's verdict is `human`. */
17
+ family: string;
18
+ implementer?: string;
19
+ implementerFamily?: string;
20
+ verdict: "approved" | "changes_requested";
21
+ findings: ReviewFinding[];
22
+ /** The `unmet` items of the verdict, in the reviewer's words. */
23
+ unmet: string[];
24
+ /** hub_review's coverage argument, as given (any shape). */
25
+ coverage: unknown;
26
+ /** The verdict is a person's: only a person's `accepted` is written, and as a resolution. */
27
+ person: boolean;
28
+ }
29
+
30
+ interface HubLedgerTarget {
31
+ cwd: string;
32
+ base: string;
33
+ /** The hub's path policy: a subject that touches a withheld path is not recorded, so no such path is named in the ledger. */
34
+ privatePath(path: string): boolean;
35
+ }
36
+
37
+ export type LedgerOutcome = { kind: "recorded"; id: string } | { kind: "resolved"; count: number } | { kind: "unchanged" } | { kind: "skipped"; why: string };
38
+
39
+ const SLUG_MAX = 60;
40
+ const unmetSlug = (item: string): string => item.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, SLUG_MAX).replace(/-+$/g, "") || "item";
41
+
42
+ /** One blocking finding per unmet item that no structured finding already carries, with a semantic id (never positional). */
43
+ function unmetFindings(unmet: readonly string[], taken: ReadonlySet<string>): RecordFinding[] {
44
+ const used = new Set(taken), out: RecordFinding[] = [];
45
+ for (const item of unmet) {
46
+ const base = `compliance:unmet-${unmetSlug(item)}`;
47
+ let id = base;
48
+ for (let n = 2; used.has(id); n++) id = `${base}-${n}`;
49
+ used.add(id);
50
+ out.push({ id, term: "compliance", severity: "blocking", disposition: "open", origin: "introduced", text: item });
51
+ }
52
+ return out;
53
+ }
54
+
55
+ const REJECTED_ID = "compliance:changes-requested";
56
+
57
+ function coverageOf(packet: PacketBundle["packet"], given: unknown): { reviewed: string[]; skipped: { path: string; reason: string }[] } {
58
+ const c = given && typeof given === "object" && !Array.isArray(given) ? given as { reviewed?: unknown; skipped?: unknown } : {};
59
+ const reviewed = Array.isArray(c.reviewed) ? c.reviewed.filter((p): p is string => typeof p === "string") : [];
60
+ const skipped = Array.isArray(c.skipped) ? c.skipped.flatMap((s: { path?: unknown; reason?: unknown } | null) =>
61
+ s && typeof s.path === "string" && typeof s.reason === "string" && s.reason.trim() ? [{ path: s.path, reason: s.reason }] : []) : [];
62
+ const accounted = new Set([...reviewed, ...skipped.map(s => s.path)]);
63
+ // A unit the verdict did not account for is recorded as skipped, never as reviewed: the gate then names it, which is the truth.
64
+ for (const unit of packet.units) if (!accounted.has(unit.path)) skipped.push({ path: unit.path, reason: "not accounted for in the verdict's coverage" });
65
+ return { reviewed, skipped };
66
+ }
67
+
68
+ function toRecordFinding(task: number, item: ReviewFinding, input: HubReviewRecord, target: HubLedgerTarget): RecordFinding {
69
+ const open = item.disposition === "accepted" ? "open" : item.disposition;
70
+ const path = item.path && !target.privatePath(item.path) ? item.path : undefined;
71
+ return {
72
+ id: item.id, term: item.pass, severity: item.severity === "important" ? "blocking" : "advisory",
73
+ ...(path ? { path } : {}),
74
+ text: item.rationale ?? `${item.pass} finding ${item.id}`,
75
+ disposition: open, origin: item.origin === "pre_existing" ? "pre_existing" : "introduced",
76
+ ...(item.rationale ? { rationale: item.rationale } : {}),
77
+ // A false_positive needs evidence in the ledger; the filed verdict is the hub's evidence.
78
+ ...(open === "false_positive" ? { evidence: [`hub task ${task} review by ${input.reviewer}`] } : {}),
79
+ };
80
+ }
81
+
82
+ /**
83
+ * Record `input` for its head, or append the resolutions it carries, through the AREV core. Idempotent: the same verdict twice is one
84
+ * record. Throws an Error naming the cause and the next step when the ledger cannot be written; the verdict on the board stands.
85
+ */
86
+ export function recordHubReview(input: HubReviewRecord, target: HubLedgerTarget): LedgerOutcome {
87
+ const { cwd } = target;
88
+ let bundle: PacketBundle;
89
+ try { bundle = buildPacket(cwd, { kind: "range", base: target.base, head: input.head, ...(input.pr === undefined ? {} : { pr: input.pr }) }); }
90
+ catch (error) { throw new Error(`the AREV packet for ${input.head} could not be built (${reason(error)}); run arev packet and arev record by hand`); }
91
+ const packet = bundle.packet;
92
+ if (packet.subject.head !== input.head) throw new Error(`the AREV packet names head ${packet.subject.head}, not ${input.head}; nothing was recorded`);
93
+ const named = [...packet.units.map(u => u.path), ...packet.excluded.map(e => e.path)];
94
+ // A subject with a withheld path can never be recorded: a skip, not a failure, so nothing is queued for a retry.
95
+ if (named.some(path => target.privatePath(path))) return { kind: "skipped", why: "the subject changes paths the hub withholds, so no AREV record is written; record the review by hand with arev record" };
96
+ try {
97
+ const events = readLedger(cwd);
98
+ const existing = events.findLast(e => e.type === "record" && e.record.packet.id === packet.id);
99
+ const structured = new Set(input.findings.map(f => f.id));
100
+ const known = existing?.type === "record" ? new Set(existing.record.findings.map(f => f.id)) : undefined;
101
+ const unmet = unmetFindings(input.unmet, structured);
102
+ const resolvable = known !== undefined && input.findings.every(f => known.has(f.id)) && unmet.every(f => known.has(f.id));
103
+ if (known !== undefined && resolvable && existing?.type === "record") return resolveKnown(cwd, input, packet.subject.head, events, existing.record);
104
+
105
+ const accepted = input.findings.filter(f => f.disposition === "accepted");
106
+ const findings = [...input.findings.map(f => toRecordFinding(input.task, f, input, target)), ...unmet];
107
+ if (input.verdict === "changes_requested" && !findings.some(f => f.severity === "blocking" && f.disposition === "open")) {
108
+ // A rejection that names no open blocking finding would pass `arev gate`; the verdict itself is the finding.
109
+ findings.push({ id: REJECTED_ID, term: "compliance", severity: "blocking", disposition: "open", origin: "introduced", text: "The reviewer requested changes without a structured finding." });
110
+ }
111
+ const sameFamily = input.implementerFamily !== undefined && input.implementerFamily === input.family;
112
+ const report = {
113
+ v: 1, packet: { id: packet.id, subject: { head: packet.subject.head } },
114
+ reviewer: { id: input.reviewer, modelFamily: input.family, started: "self", sameFamilyFallback: sameFamily, ...(input.implementer ? { implementer: input.implementer } : {}) },
115
+ coverage: coverageOf(packet, input.coverage), findings, verdict: input.verdict, call: { ok: true },
116
+ };
117
+ // A retry is idempotent: a record at this packet that carries every finding takes the resolve branch above, so it never doubles.
118
+ if (!events.some(e => e.type === "packet" && e.packet.id === packet.id)) appendPacketEvent(cwd, bundle, packetSettings(cwd, bundle));
119
+ const done = recordReview(cwd, report, { label: `hub task ${input.task}`, ...(input.implementer ? { implementer: input.implementer } : {}) });
120
+ // `accepted` is a person's decision and a report cannot carry it: the finding is recorded open, then resolved.
121
+ if (input.person) for (const f of accepted) resolveFinding(cwd, f.id, { as: "accepted", person: true, head: input.head, ...(input.pr === undefined ? {} : { pr: input.pr }), ...(f.rationale ? { rationale: f.rationale } : { rationale: `accepted by the person in hub task ${input.task}` }) });
122
+ return { kind: "recorded", id: done.id };
123
+ } catch (error) {
124
+ if (error instanceof Refusal) throw new Error(`the AREV ledger refused the record (${error.message}); next: ${error.next}`);
125
+ throw error;
126
+ }
127
+ }
128
+
129
+ function resolveKnown(cwd: string, input: HubReviewRecord, head: string, events: ReturnType<typeof readLedger>, record: { findings: RecordFinding[] }): LedgerOutcome {
130
+ let count = 0;
131
+ const settled = new Set<string>();
132
+ for (const f of input.findings) {
133
+ if (f.disposition === "open") continue;
134
+ // Accepting is the person's; a peer's `accepted` is not a ledger resolution.
135
+ if (f.disposition === "accepted" && !input.person) continue;
136
+ const already = events.some(e => e.type === "resolve" && e.head === head && e.finding === f.id && e.as === f.disposition);
137
+ if (already) continue;
138
+ resolveFinding(cwd, f.id, {
139
+ as: f.disposition, person: input.person, head, ...(input.pr === undefined ? {} : { pr: input.pr }),
140
+ ...(f.disposition === "false_positive" ? { evidence: [`hub task ${input.task} review by ${input.reviewer}`] } : {}),
141
+ ...(f.rationale ? { rationale: f.rationale } : f.disposition === "accepted" ? { rationale: `accepted by the person in hub task ${input.task}` } : {}),
142
+ });
143
+ settled.add(f.id);
144
+ count++;
145
+ }
146
+ // An approval at a head the hub rejected before: the blocking findings of that rejection that this verdict no longer carries open are
147
+ // settled by it, so `arev gate` agrees with the board. The filed verdict is the evidence.
148
+ if (input.verdict === "approved") {
149
+ const carried = new Set(input.findings.filter(f => f.disposition === "open").map(f => f.id));
150
+ for (const f of record.findings) {
151
+ if (f.severity !== "blocking" || f.disposition !== "open" || carried.has(f.id) || settled.has(f.id)) continue;
152
+ if (events.some(e => e.type === "resolve" && e.head === head && e.finding === f.id)) continue;
153
+ resolveFinding(cwd, f.id, { as: "fixed", person: input.person, head, ...(input.pr === undefined ? {} : { pr: input.pr }),
154
+ rationale: `settled by the approval of ${input.reviewer} in hub task ${input.task}` });
155
+ count++;
156
+ }
157
+ }
158
+ return count ? { kind: "resolved", count } : { kind: "unchanged" };
159
+ }
160
+
161
+ const reason = (error: unknown): string => (error instanceof Error ? error.message : "unknown error").replace(/\s+/g, " ").slice(0, REASON_CHARS);
162
+ const REASON_CHARS = 200;
@@ -1,13 +1,13 @@
1
+ import type { ReviewMaterial } from "@staix/agent-review/core";
1
2
  import { createHash } from "node:crypto";
2
3
  import { extname, join } from "node:path";
3
4
  import { projectionPath, snapshotBytes, PROJECTED_DIFF_BYTES } from "./projected-diff.ts";
4
5
  import type { Repo } from "./snapshots.ts";
5
6
  import type { TextProjections } from "./text-projection.ts";
6
7
 
8
+ export type { ReviewMaterial } from "@staix/agent-review/core";
9
+
7
10
  export interface ReviewReadRequest { path: string; side?: "base" | "head" }
8
- export type ReviewMaterial =
9
- | { state: "available"; path: string; side: "base" | "head"; text: string; rawHash: string; contentHash: string; projection?: { name: string; version: string } }
10
- | { state: "unavailable"; path: string; side: "base" | "head" };
11
11
  export interface ReviewMaterialBatch { head: string; materials: ReviewMaterial[] }
12
12
  export interface ReviewMaterialOptions {
13
13
  repo: Repo;
@@ -1,3 +1,4 @@
1
+ import { chooseHost } from "@staix/agent-review/core";
1
2
  import { reviewBudgetAdmission, type ReviewBudgetSnapshot } from "./review-budget.ts";
2
3
  export type ReviewerPoolReason = "rotation" | "implementer skip" | "unavailable skip" | "same-family fallback";
3
4
  export interface ReviewerPoolCandidate { id: string; kind: string; family: string; blocked?: string }
@@ -50,8 +51,9 @@ export function selectReviewerPool(input: ReviewerPoolInput): ReviewerPoolSelect
50
51
  };
51
52
  if (!declaredKinds.length) return finish({ reviewer: null, blocked: "no reviewer can run" });
52
53
  const seed = Number.isSafeInteger(input.seed) ? input.seed : 0;
53
- const start = ((seed % declaredKinds.length) + declaredKinds.length) % declaredKinds.length;
54
- const rotated = [...declaredKinds.slice(start), ...declaredKinds.slice(0, start)];
54
+ const key = seed < 0 ? (seed % declaredKinds.length + declaredKinds.length) % declaredKinds.length : seed;
55
+ // An exhaustive host walk supplies the rotation order. Apply hub admission to the instances within each kind below.
56
+ const rotated = chooseHost(key, "", new Set<string>(), declaredKinds).considered.map(row => row.host);
55
57
  const slots = rotated.flatMap(kind => {
56
58
  const declared = input.candidates.filter(candidate => candidate.kind === kind).sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
57
59
  return declared;
@@ -1,27 +1,78 @@
1
- import { readPlanIssueMetadata, type SdlcGh } from "./sdlc.ts";
1
+ import type { SdlcGh } from "./sdlc.ts";
2
2
 
3
3
  type IssueState = "open" | "closed";
4
4
 
5
+ const ROADMAP_ISSUE_CEILING = 1000;
6
+ export const GRAPHQL_CHUNK = 50;
7
+
8
+ interface GraphqlIssue { number: number; state: "OPEN" | "CLOSED"; milestone: number | null }
9
+
10
+ /** One literal read-only query for up to 50 integer issue aliases of one repository (`graphqlQueryOnly`-compatible). */
11
+ function graphqlIssueArgs(repo: string, numbers: readonly number[]): string[] {
12
+ const slash = repo.indexOf("/");
13
+ if (slash < 1 || numbers.length < 1 || numbers.length > GRAPHQL_CHUNK || numbers.some(n => !Number.isSafeInteger(n) || n < 1)) throw new Error("invalid graphql issue chunk");
14
+ const fields = numbers.map(n => `i${n}:issue(number:${n}){number url state milestone{number}}`).join(" ");
15
+ return ["api", "graphql", "--hostname", "github.com", "-f", `query=query($owner:String!,$name:String!){repository(owner:$owner,name:$name){${fields}}}`, "-f", `owner=${repo.slice(0, slash)}`, "-f", `name=${repo.slice(slash + 1)}`];
16
+ }
17
+
18
+ /**
19
+ * Read one chunk. A null node (missing issue or a pull request) is absent from the map; a failed, oversized or malformed
20
+ * chunk, or a node whose number or canonical URL differs, is undefined so no ref of the chunk is resolved.
21
+ */
22
+ export async function readGraphqlIssueChunk(repo: string, numbers: readonly number[], gh: SdlcGh, timeout: number): Promise<Map<number, GraphqlIssue> | undefined> {
23
+ try {
24
+ const result = await gh(graphqlIssueArgs(repo, numbers), timeout, undefined, 2 * 1024 * 1024);
25
+ if (Buffer.byteLength(result.stdout) > 2 * 1024 * 1024) return undefined;
26
+ // gh exits 1 whenever an aliased issue is null and still prints the data: accept that only when every error is NOT_FOUND for a null member of this chunk.
27
+ const root = JSON.parse(result.stdout) as { data?: { repository?: Record<string, unknown> | null }; errors?: unknown };
28
+ const node = root?.data?.repository;
29
+ if (!node || typeof node !== "object" || Array.isArray(node)) return undefined;
30
+ const errors = root.errors === undefined ? [] : root.errors;
31
+ if (!Array.isArray(errors) || result.code !== 0 && errors.length === 0) return undefined;
32
+ for (const error of errors) {
33
+ const path = (error as { path?: unknown })?.path, key = Array.isArray(path) && path.length === 2 && path[0] === "repository" ? path[1] : undefined;
34
+ if ((error as { type?: unknown })?.type !== "NOT_FOUND" || typeof key !== "string" || !numbers.some(n => `i${n}` === key) || node[key] !== null) return undefined;
35
+ }
36
+ const out = new Map<number, GraphqlIssue>();
37
+ for (const n of numbers) {
38
+ const row = node[`i${n}`];
39
+ if (row === null) continue;
40
+ if (!row || typeof row !== "object" || Array.isArray(row)) return undefined;
41
+ const r = row as Record<string, unknown>, ms = r.milestone;
42
+ if (r.number !== n || typeof r.url !== "string" || r.url.toLowerCase() !== `https://github.com/${repo.toLowerCase()}/issues/${n}` || r.state !== "OPEN" && r.state !== "CLOSED") return undefined;
43
+ if (ms !== null && (!ms || typeof ms !== "object" || !Number.isSafeInteger((ms as Record<string, unknown>).number))) return undefined;
44
+ out.set(n, { number: n, state: r.state, milestone: ms === null ? null : (ms as { number: number }).number });
45
+ }
46
+ return out;
47
+ } catch { return undefined; }
48
+ }
49
+
5
50
  /** Live evidence for one roadmap snapshot. Missing keys are unknown. */
6
51
  export async function roadmapIssueStates(refs: ReadonlySet<string>, gh: SdlcGh, current: () => void): Promise<Map<string, IssueState>> {
7
- const pending = [...refs].sort().slice(0, 100), states = new Map<string, IssueState>();
52
+ const pending = [...refs].sort().slice(0, ROADMAP_ISSUE_CEILING), states = new Map<string, IssueState>();
53
+ const groups = new Map<string, number[]>();
54
+ for (const ref of pending) {
55
+ const match = /^([A-Za-z0-9][A-Za-z0-9-]{0,38}\/[A-Za-z0-9_.-]{1,100})#([1-9][0-9]*)$/.exec(ref);
56
+ if (!match) continue;
57
+ const key = match[1]!.toLowerCase(), list = groups.get(key) ?? [];
58
+ list.push(Number(match[2])); groups.set(key, list);
59
+ }
60
+ const chunks: { repo: string; numbers: number[] }[] = [];
61
+ for (const [repo, list] of groups) for (let i = 0; i < list.length; i += GRAPHQL_CHUNK) chunks.push({ repo, numbers: list.slice(i, i + GRAPHQL_CHUNK) });
8
62
  const deadline = performance.now() + 20_000;
9
63
  let next = 0, stopped = false;
10
64
  const worker = async () => {
11
65
  try {
12
- while (!stopped && next < pending.length && performance.now() < deadline) {
13
- const ref = pending[next++]!;
14
- const match = /^([^#]+)#([1-9][0-9]*)$/.exec(ref);
15
- if (!match) continue;
66
+ while (!stopped && next < chunks.length && performance.now() < deadline) {
67
+ const chunk = chunks[next++]!;
16
68
  current();
17
- const value = await readPlanIssueMetadata(match[1]!, Number(match[2]), (args, timeout, cwd, cap) => {
18
- const remaining = deadline - performance.now();
19
- return remaining > 0
20
- ? gh([...args.slice(0, 2), "--hostname", "github.com", ...args.slice(2)], Math.min(timeout ?? remaining, remaining), cwd, cap)
21
- : Promise.resolve({ code: 1, stdout: "" });
22
- });
69
+ const left = deadline - performance.now();
70
+ const found = left > 0 ? await readGraphqlIssueChunk(chunk.repo, chunk.numbers, gh, Math.min(10_000, left)) : undefined;
23
71
  current();
24
- if (value && performance.now() < deadline) states.set(ref, value.state === "CLOSED" ? "closed" : "open");
72
+ if (found && performance.now() < deadline) for (const [n, issue] of found) {
73
+ // Keys keep the caller's spelling: match by lowercase repo.
74
+ for (const ref of pending) if (ref.toLowerCase() === `${chunk.repo}#${n}`) states.set(ref, issue.state === "CLOSED" ? "closed" : "open");
75
+ }
25
76
  }
26
77
  } catch (error) {
27
78
  stopped = true;
@@ -29,7 +80,7 @@ export async function roadmapIssueStates(refs: ReadonlySet<string>, gh: SdlcGh,
29
80
  }
30
81
  };
31
82
  // Drain already started reads before surfacing a revoked snapshot.
32
- const results = await Promise.allSettled(Array.from({ length: Math.min(4, pending.length) }, worker));
83
+ const results = await Promise.allSettled(Array.from({ length: Math.min(4, chunks.length) }, worker));
33
84
  for (const result of results) if (result.status === "rejected") throw result.reason;
34
85
  return states;
35
86
  }
@@ -1,6 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { githubRepo, milestoneId, milestoneMembershipField } from "./roadmap.ts";
3
3
  import type { SdlcGh } from "./sdlc.ts";
4
+ import { GRAPHQL_CHUNK, readGraphqlIssueChunk } from "./roadmap-issue-states.ts";
4
5
 
5
6
  export interface MirrorIssue { number: number; milestone: number | null }
6
7
  export interface MirrorMilestone { number: number; title: string; state: "open" | "closed" }
@@ -8,17 +9,21 @@ export interface MirrorDesired { title: string; state: "open" | "closed"; issues
8
9
  export interface MirrorPlan { calls: string[][]; fingerprint: string }
9
10
  export interface MirrorSnapshot { milestones: (MirrorMilestone & MarkerMilestone)[]; issues: MirrorIssue[] }
10
11
 
11
- /** Complete bounded metadata-only pages. A failed or full last page refuses every write plan. */
12
- export async function readMirrorSnapshot(repoInput: string, run: SdlcGh): Promise<MirrorSnapshot> {
12
+ export interface MirrorScope { boundNumbers: readonly number[]; markers: readonly { marker: string; title: string }[]; desiredIssues: readonly number[] }
13
+
14
+ /** Scoped, complete, bounded metadata reads. A failed or full last page, or a failed chunk, refuses every write plan. */
15
+ export async function readMirrorSnapshot(repoInput: string, scope: MirrorScope, run: SdlcGh): Promise<MirrorSnapshot> {
13
16
  const repo = githubRepo(repoInput), deadline = performance.now() + 20_000;
14
- const pages = async (kind: "milestones" | "issues"): Promise<Record<string, unknown>[]> => {
17
+ if (scope.markers.length > 100) throw new Error("roadmap mirror exceeds 100 unbound milestones; narrow the roadmap before syncing");
18
+ if (scope.boundNumbers.length > 100) throw new Error("roadmap mirror exceeds 100 bound milestones; narrow the roadmap before syncing");
19
+ if (scope.desiredIssues.length > 1000) throw new Error("roadmap mirror exceeds 1,000 desired issues; narrow the roadmap before syncing");
20
+ const pages = async (path: string, kind: "milestones" | "issues"): Promise<Record<string, unknown>[]> => {
15
21
  const rows: Record<string, unknown>[] = [], seen = new Set<number>();
16
- // ponytail: this all-state inventory has a 1000-row ceiling including pull requests; page milestone members and desired issues separately to remove it.
17
22
  for (let page = 1; page <= 10; page++) {
18
23
  const left = deadline - performance.now();
19
24
  if (left <= 0) throw new Error("roadmap mirror inventory timed out");
20
25
  const projection = kind === "milestones" ? "[.[]|{number,title,state,description,html_url}]" : "[.[]|{number,html_url,milestone:(.milestone|if . == null then null else {number} end),pull_request:(.pull_request!=null)}]";
21
- const result = await run(["api", `repos/${repo}/${kind}?state=all&per_page=100&page=${page}`, "--hostname", "github.com", "--jq", projection], Math.min(left, 10_000), undefined, 2 * 1024 * 1024);
26
+ const result = await run(["api", `repos/${repo}/${path}${path.includes("?") ? "&" : "?"}per_page=100&page=${page}`, "--hostname", "github.com", "--jq", projection], Math.min(left, 10_000), undefined, 2 * 1024 * 1024);
22
27
  if (performance.now() > deadline || result.code !== 0 || Buffer.byteLength(result.stdout) > 2 * 1024 * 1024) throw new Error("roadmap mirror inventory unavailable");
23
28
  const raw: unknown = JSON.parse(result.stdout);
24
29
  if (!Array.isArray(raw) || raw.length > 100) throw new Error("roadmap mirror inventory malformed");
@@ -32,18 +37,38 @@ export async function readMirrorSnapshot(repoInput: string, run: SdlcGh): Promis
32
37
  }
33
38
  throw new Error("roadmap mirror inventory incomplete");
34
39
  };
35
- const milestones = (await pages("milestones")).map(row => {
40
+ const milestones = (await pages("milestones?state=all", "milestones")).map(row => {
36
41
  if (typeof row.title !== "string" || row.title.length > 300 || row.state !== "open" && row.state !== "closed" || row.description !== null && typeof row.description !== "string" || typeof row.html_url !== "string" || row.html_url.toLowerCase() !== `https://github.com/${repo}/milestone/${milestoneId(row.number)}`) throw new Error("roadmap mirror milestone malformed");
37
42
  return { number: milestoneId(row.number), title: row.title, state: row.state, description: row.description } as MirrorMilestone & MarkerMilestone;
38
43
  });
39
- const issueRows = await pages("issues");
40
- if (issueRows.some(row => typeof row.pull_request !== "boolean")) throw new Error("roadmap mirror issue malformed");
41
- const issues = issueRows.filter(row => row.pull_request === false).map(row => {
42
- const value = row.milestone;
43
- if (value !== null && (!value || typeof value !== "object" || Array.isArray(value)) || typeof row.html_url !== "string" || row.html_url.toLowerCase() !== `https://github.com/${repo}/issues/${milestoneId(row.number)}`) throw new Error("roadmap mirror issue malformed");
44
- return { number: milestoneId(row.number), milestone: value === null ? null : milestoneId((value as Record<string, unknown>).number) };
45
- });
46
- return { milestones, issues };
44
+ const targets = new Set<number>(scope.boundNumbers.map(milestoneId));
45
+ for (const { marker, title } of scope.markers) {
46
+ const found = recoverMirrorBinding(marker, title, milestones);
47
+ if (found.kind === "bind") targets.add(found.number);
48
+ }
49
+ const byNumber = new Map<number, MirrorIssue>();
50
+ // ponytail: one sequential gh call chain per target milestone under the single 20 s deadline; the scope allows 100 milestones, so a slow host fails closed as timed out. Upgrade: bounded concurrency as in roadmapIssueStates.
51
+ for (const target of [...targets].sort((a, b) => a - b)) {
52
+ if (!milestones.some(row => row.number === target)) continue; // planning refuses a recorded milestone that is missing
53
+ const issueRows = await pages(`issues?milestone=${target}&state=all`, "issues");
54
+ if (issueRows.some(row => typeof row.pull_request !== "boolean")) throw new Error("roadmap mirror issue malformed");
55
+ for (const row of issueRows.filter(item => item.pull_request === false)) {
56
+ const value = row.milestone;
57
+ if (value !== null && (!value || typeof value !== "object" || Array.isArray(value)) || typeof row.html_url !== "string" || row.html_url.toLowerCase() !== `https://github.com/${repo}/issues/${milestoneId(row.number)}`) throw new Error("roadmap mirror issue malformed");
58
+ const id = milestoneId(row.number);
59
+ if (byNumber.has(id)) throw new Error("roadmap mirror inventory duplicated");
60
+ byNumber.set(id, { number: id, milestone: value === null ? null : milestoneId((value as Record<string, unknown>).number) });
61
+ }
62
+ }
63
+ const rest = [...new Set(scope.desiredIssues.map(milestoneId))].filter(id => !byNumber.has(id)).sort((a, b) => a - b);
64
+ for (let i = 0; i < rest.length; i += GRAPHQL_CHUNK) {
65
+ const left = deadline - performance.now();
66
+ if (left <= 0) throw new Error("roadmap mirror inventory timed out");
67
+ const found = await readGraphqlIssueChunk(repo, rest.slice(i, i + GRAPHQL_CHUNK), run, Math.min(left, 10_000));
68
+ if (!found || performance.now() > deadline) throw new Error("roadmap mirror inventory unavailable");
69
+ for (const [id, issue] of found) byNumber.set(id, { number: id, milestone: issue.milestone });
70
+ }
71
+ return { milestones, issues: [...byNumber.values()] };
47
72
  }
48
73
 
49
74
  export interface MarkerMilestone { number: number; title: string; description: string | null }