@staix/agent-hub 0.44.0 → 0.46.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 (168) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/README.md +12 -11
  3. package/docs/adding-an-ai-tool.md +1 -0
  4. package/docs/agent-notes/adapters.md +35 -6
  5. package/docs/agent-notes/budget.md +2 -1
  6. package/docs/agent-notes/daemon.md +5 -1
  7. package/docs/agent-notes/local-worker.md +1 -1
  8. package/docs/agent-notes/security-review.md +3 -2
  9. package/docs/agent-notes/tasks.md +6 -2
  10. package/docs/agent-notes/tests.md +4 -3
  11. package/docs/design/adapters.md +20 -2
  12. package/docs/design/agent-hub-architecture.md +12 -0
  13. package/docs/design/agent-hub.md +1 -1
  14. package/docs/design/cli-output.md +2 -0
  15. package/docs/design/roadmap.md +158 -4
  16. package/docs/design/supervision.md +21 -1
  17. package/docs/design/task-board.md +32 -4
  18. package/docs/dogfood.md +28 -4
  19. package/docs/events.md +7 -3
  20. package/docs/influences.md +7 -0
  21. package/docs/memory.md +4 -4
  22. package/docs/operations.md +151 -36
  23. package/docs/quickstart.md +16 -4
  24. package/docs/research.md +16 -0
  25. package/docs/roadmap.json +4 -0
  26. package/docs/roadmap.md +9 -0
  27. package/docs/sdlc.md +15 -3
  28. package/docs/security.md +9 -7
  29. package/docs/smoke.md +1 -1
  30. package/docs/verification/2026-11-05-hardcoded-values-classification-rules.md +28 -0
  31. package/docs/verification/2026-11-19-claude-implementer-2.1.328.md +49 -0
  32. package/docs/verification/2026-11-20-claude-implementer-2.1.329.md +49 -0
  33. package/docs/verification/2026-11-20-sdlc-metrics-diagnosis.md +7 -0
  34. package/docs/verification/2026-11-21-0.45.0.md +69 -0
  35. package/docs/verification/2026-11-22-agy-1.5.14.md +27 -0
  36. package/docs/verification/2026-11-22-claude-instruction-hook.md +35 -0
  37. package/docs/verification/2026-11-22-codex-0171-reviewer-isolation.md +47 -0
  38. package/docs/verification/2026-11-22-instructed-ipc.md +9 -0
  39. package/docs/verification/2026-11-22-jcode-1.0.3.md +71 -0
  40. package/docs/verification/2026-11-22-jcode-separate-home.md +14 -0
  41. package/docs/verification/2026-11-22-qwen-0283-acp.md +28 -0
  42. package/docs/verification/2026-11-22-qwen-0283-dual-output.md +33 -0
  43. package/docs/verification/2026-11-22-roadmap-r5-view-receipt.md +63 -0
  44. package/docs/verification/2026-11-23-0.46.0.md +44 -0
  45. package/docs/verification/assets/1483-r5-detail-1440-light.png +0 -0
  46. package/docs/verification/assets/1483-r5-detail-390-light.png +0 -0
  47. package/docs/verification/assets/1483-r5-view-1440-dark.png +0 -0
  48. package/docs/verification/assets/1483-r5-view-1440-light.png +0 -0
  49. package/docs/verification/assets/1483-r5-view-390-dark.png +0 -0
  50. package/docs/verification/assets/1483-r5-view-390-light.png +0 -0
  51. package/docs/verification/assets/1483-r5-view-820-dark.png +0 -0
  52. package/docs/verification/assets/1483-r5-view-820-light.png +0 -0
  53. package/docs/verified.json +33 -27
  54. package/package.json +3 -2
  55. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  56. package/plugins/agent-hub/kimi-hook.js +4743 -4048
  57. package/plugins/agent-hub/kimi-review-policy-worker.js +5 -5
  58. package/plugins/agent-hub/server.js +1641 -1265
  59. package/plugins/agent-hub/skills/ahub/SKILL.md +17 -0
  60. package/plugins/agent-hub/skills/ahub-manage/SKILL.md +37 -0
  61. package/plugins/agent-hub/skills/ahub-status/SKILL.md +14 -0
  62. package/plugins/agent-hub/skills/ahub-use/SKILL.md +12 -0
  63. package/scripts/check-docs.mjs +9 -1
  64. package/src/adapters/acp.ts +11 -1
  65. package/src/adapters/claude-channel.ts +2 -1
  66. package/src/adapters/compat.ts +15 -14
  67. package/src/adapters/definitions/builtin-metadata.ts +2 -2
  68. package/src/adapters/definitions/native-cli-claude-setup.ts +9 -1
  69. package/src/adapters/definitions/native-cli-doctor.ts +8 -5
  70. package/src/adapters/definitions/native-cli-jcode-home-init.ts +158 -0
  71. package/src/adapters/definitions/native-cli-jcode-home.ts +72 -0
  72. package/src/adapters/definitions/native-cli-jcode-mcp.ts +20 -0
  73. package/src/adapters/definitions/native-cli-skills.ts +29 -0
  74. package/src/adapters/definitions/native-context.ts +10 -0
  75. package/src/adapters/jcode.ts +10 -0
  76. package/src/adapters/local-worker.ts +3 -2
  77. package/src/adapters/pi.ts +15 -4
  78. package/src/cli/claude-profile-hook.ts +40 -3
  79. package/src/cli/console-state.ts +58 -27
  80. package/src/cli/console-usage.ts +5 -3
  81. package/src/cli/console.ts +35 -4
  82. package/src/cli/help.ts +17 -10
  83. package/src/cli/identity.ts +4 -2
  84. package/src/cli/instruction-hook.ts +28 -0
  85. package/src/cli/jcode-mcp.ts +2 -1
  86. package/src/cli/main.js +8 -0
  87. package/src/cli/main.ts +149 -23
  88. package/src/cli/output-standard.ts +3 -55
  89. package/src/cli/output.ts +8 -2
  90. package/src/cli/recovery-package.ts +62 -13
  91. package/src/cli/roadmap-write.ts +59 -0
  92. package/src/cli/roadmap.ts +115 -4
  93. package/src/cli/sdlc-output.ts +4 -0
  94. package/src/cli/setup-homes.ts +1 -0
  95. package/src/cli/setup.ts +1 -1
  96. package/src/cli/skills-install.ts +463 -0
  97. package/src/cli/task-output.ts +1 -1
  98. package/src/cli/upgrade-presentation-flags.ts +1 -1
  99. package/src/cli/upgrade-runtime.ts +10 -6
  100. package/src/hub/agent-mem-range.ts +43 -0
  101. package/src/hub/board.ts +144 -5
  102. package/src/hub/budget-projection.ts +99 -0
  103. package/src/hub/check-runner.ts +25 -1
  104. package/src/hub/claude-launch-proof.ts +5 -1
  105. package/src/hub/conductor.ts +8 -3
  106. package/src/hub/config-apply.ts +6 -3
  107. package/src/hub/config-tier.ts +1 -1
  108. package/src/hub/config-trust.ts +1 -1
  109. package/src/hub/context-window.ts +1 -1
  110. package/src/hub/control-client.ts +9 -2
  111. package/src/hub/cost-governance.ts +11 -7
  112. package/src/hub/daemon.ts +707 -53
  113. package/src/hub/dogfood-read.ts +4 -2
  114. package/src/hub/edit-guard.ts +100 -0
  115. package/src/hub/events.ts +80 -9
  116. package/src/hub/execution-budget.ts +29 -8
  117. package/src/hub/facts.ts +57 -4
  118. package/src/hub/hub-tools.ts +3 -1
  119. package/src/hub/inference.ts +1 -1
  120. package/src/hub/instances.ts +10 -1
  121. package/src/hub/instructed-exact.ts +95 -0
  122. package/src/hub/instructed-intent.ts +64 -0
  123. package/src/hub/instructed-ipc.ts +33 -0
  124. package/src/hub/instructed-runtime.ts +19 -0
  125. package/src/hub/instruction-receipt.ts +218 -0
  126. package/src/hub/lifecycle.ts +6 -1
  127. package/src/hub/log-rotation.ts +130 -0
  128. package/src/hub/manager.ts +46 -3
  129. package/src/hub/memory-profile.ts +137 -21
  130. package/src/hub/no-writes.ts +1 -0
  131. package/src/hub/operational-authority.ts +3 -2
  132. package/src/hub/operational-settings.ts +2 -2
  133. package/src/hub/recovery-store.ts +49 -21
  134. package/src/hub/registry.ts +1 -1
  135. package/src/hub/research-experiments.ts +132 -0
  136. package/src/hub/research-quality.ts +8 -2
  137. package/src/hub/research-record.ts +35 -0
  138. package/src/hub/research.ts +128 -28
  139. package/src/hub/roadmap-check.ts +65 -0
  140. package/src/hub/roadmap-decompose.ts +139 -0
  141. package/src/hub/roadmap-export.ts +27 -0
  142. package/src/hub/roadmap-sync.ts +97 -0
  143. package/src/hub/roadmap.ts +59 -1
  144. package/src/hub/routing.ts +18 -1
  145. package/src/hub/runtime-capture-prune.ts +2 -1
  146. package/src/hub/sdlc-branch-ci.ts +128 -0
  147. package/src/hub/sdlc-merge.ts +6 -3
  148. package/src/hub/sdlc-metrics.ts +19 -5
  149. package/src/hub/sdlc.ts +73 -5
  150. package/src/hub/settings.ts +3 -1
  151. package/src/hub/snapshots.ts +13 -1
  152. package/src/hub/startup-event-seeds.ts +21 -15
  153. package/src/hub/startup-timing.ts +3 -1
  154. package/src/hub/supervision-proposals.ts +10 -2
  155. package/src/hub/supervision-rules.ts +26 -3
  156. package/src/hub/supervision.ts +7 -0
  157. package/src/hub/task-pr.ts +47 -0
  158. package/src/hub/task-worktree.ts +18 -11
  159. package/src/hub/tasks.ts +694 -44
  160. package/src/hub/ui.ts +6 -2
  161. package/src/hub/usage-rollup.ts +77 -22
  162. package/src/local/tools.ts +13 -1
  163. package/src/memory/client.ts +3 -2
  164. package/src/pi/extension.ts +15 -3
  165. package/src/pi/tool-receipts.ts +26 -0
  166. package/src/ui/index.html +342 -8
  167. package/src/ui/plugin.ts +6 -2
  168. package/src/ui/roadmap-model.ts +70 -0
@@ -0,0 +1,97 @@
1
+ import { createHash } from "node:crypto";
2
+ import { githubRepo, milestoneId, milestoneMembershipField } from "./roadmap.ts";
3
+ import type { SdlcGh } from "./sdlc.ts";
4
+
5
+ export interface MirrorIssue { number: number; milestone: number | null }
6
+ export interface MirrorMilestone { number: number; title: string; state: "open" | "closed" }
7
+ export interface MirrorDesired { title: string; state: "open" | "closed"; issues: number[]; marker: string }
8
+ export interface MirrorPlan { calls: string[][]; fingerprint: string }
9
+ export interface MirrorSnapshot { milestones: (MirrorMilestone & MarkerMilestone)[]; issues: MirrorIssue[] }
10
+
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> {
13
+ const repo = githubRepo(repoInput), deadline = performance.now() + 20_000;
14
+ const pages = async (kind: "milestones" | "issues"): Promise<Record<string, unknown>[]> => {
15
+ 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
+ for (let page = 1; page <= 10; page++) {
18
+ const left = deadline - performance.now();
19
+ if (left <= 0) throw new Error("roadmap mirror inventory timed out");
20
+ 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);
22
+ if (performance.now() > deadline || result.code !== 0 || Buffer.byteLength(result.stdout) > 2 * 1024 * 1024) throw new Error("roadmap mirror inventory unavailable");
23
+ const raw: unknown = JSON.parse(result.stdout);
24
+ if (!Array.isArray(raw) || raw.length > 100) throw new Error("roadmap mirror inventory malformed");
25
+ for (const item of raw) {
26
+ if (!item || typeof item !== "object" || Array.isArray(item)) throw new Error("roadmap mirror inventory malformed");
27
+ const row = item as Record<string, unknown>, id = milestoneId(row.number);
28
+ if (seen.has(id)) throw new Error("roadmap mirror inventory duplicated");
29
+ seen.add(id); rows.push(row);
30
+ }
31
+ if (raw.length < 100) return rows;
32
+ }
33
+ throw new Error("roadmap mirror inventory incomplete");
34
+ };
35
+ const milestones = (await pages("milestones")).map(row => {
36
+ 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
+ return { number: milestoneId(row.number), title: row.title, state: row.state, description: row.description } as MirrorMilestone & MarkerMilestone;
38
+ });
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 };
47
+ }
48
+
49
+ export interface MarkerMilestone { number: number; title: string; description: string | null }
50
+ export type MirrorRecovery = (
51
+ | { kind: "create" }
52
+ | { kind: "bind"; number: number }
53
+ | { kind: "ambiguous"; numbers: number[] }
54
+ ) & { titleConflicts: number[] };
55
+
56
+ /** Resolve a lost create response without ever inferring identity from a title. */
57
+ export function recoverMirrorBinding(marker: string, title: string, remote: readonly MarkerMilestone[]): MirrorRecovery {
58
+ if (!/^<!-- ahub-roadmap:[A-Za-z0-9._-]+:[1-9][0-9]* -->$/.test(marker)) throw new Error("invalid roadmap marker");
59
+ const marked = remote.filter(row => row.description?.includes(marker)).map(row => milestoneId(row.number)).sort((a, b) => a - b);
60
+ const titleConflicts = remote.filter(row => row.title === title && !row.description?.includes(marker)).map(row => milestoneId(row.number)).sort((a, b) => a - b);
61
+ if (marked.length > 1) return { kind: "ambiguous", numbers: marked, titleConflicts };
62
+ if (marked.length === 1) return { kind: "bind", number: marked[0]!, titleConflicts };
63
+ return { kind: "create", titleConflicts };
64
+ }
65
+
66
+ /** Plan one public milestone against a complete, host-validated snapshot. Never applies it. */
67
+ export function planRoadmapMirror(repoInput: string, desired: MirrorDesired, remote: MirrorMilestone | null, issues: readonly MirrorIssue[]): MirrorPlan {
68
+ const repo = githubRepo(repoInput);
69
+ if (!/^<!-- ahub-roadmap:[A-Za-z0-9._-]+:[1-9][0-9]* -->$/.test(desired.marker)) throw new Error("invalid roadmap marker");
70
+ if (typeof desired.title !== "string" || !desired.title.trim() || desired.title.length > 300 || /[\p{Cc}\p{Cf}]/u.test(desired.title)
71
+ || !["open", "closed"].includes(desired.state)) throw new Error("invalid public milestone");
72
+ const desiredIds = new Set(desired.issues.map(milestoneId));
73
+ if (desiredIds.size !== desired.issues.length) throw new Error("duplicate issue membership");
74
+ const calls: string[][] = [];
75
+ if (remote === null) {
76
+ // The server assigns the number. A later preview plans membership separately.
77
+ calls.push(["api", `repos/${repo}/milestones`, "--hostname", "github.com", "--method", "POST", "-f", `title=${desired.title}`, "-f", `state=${desired.state}`, "-f", `description=${desired.marker}`]);
78
+ } else {
79
+ const number = milestoneId(remote.number);
80
+ if (remote.state !== "open" && remote.state !== "closed") throw new Error("invalid remote milestone state");
81
+ if (remote.title !== desired.title || remote.state !== desired.state)
82
+ calls.push(["api", `repos/${repo}/milestones/${number}`, "--hostname", "github.com", "--method", "PATCH", "-f", `title=${desired.title}`, "-f", `state=${desired.state}`]);
83
+ const seen = new Set<number>();
84
+ for (const issue of [...issues].sort((a, b) => a.number - b.number)) {
85
+ const id = milestoneId(issue.number);
86
+ if (seen.has(id)) throw new Error("duplicate remote issue");
87
+ seen.add(id);
88
+ if (issue.milestone !== null) milestoneId(issue.milestone);
89
+ if (desiredIds.has(id) && issue.milestone !== number)
90
+ calls.push(["api", `repos/${repo}/issues/${id}`, "--hostname", "github.com", "--method", "PATCH", ...milestoneMembershipField(number)]);
91
+ else if (!desiredIds.has(id) && issue.milestone === number)
92
+ calls.push(["api", `repos/${repo}/issues/${id}`, "--hostname", "github.com", "--method", "PATCH", "-F", "milestone=null"]);
93
+ }
94
+ if ([...desiredIds].some(id => !seen.has(id))) throw new Error("issue membership snapshot is incomplete");
95
+ }
96
+ return { calls, fingerprint: createHash("sha256").update(JSON.stringify(calls)).digest("hex") };
97
+ }
@@ -3,6 +3,13 @@ export const MILESTONE_STATES = ["proposed", "planned", "active", "done", "dropp
3
3
  export const MILESTONE_HORIZONS = ["now", "next", "later"] as const;
4
4
  export const MILESTONE_LINK_KINDS = ["spec", "issue", "task", "release"] as const;
5
5
  export const MILESTONE_HISTORY_LIMIT = 256;
6
+ export interface RoadmapConfig { github_mirror: boolean; github_write: "off" | "conductor" }
7
+ export function roadmapConfig(raw: unknown): RoadmapConfig {
8
+ if (raw === undefined) return { github_mirror: false, github_write: "off" };
9
+ const row = object(raw);
10
+ if (Object.keys(row).some(key => key !== "github_mirror" && key !== "github_write") || row.github_mirror !== undefined && typeof row.github_mirror !== "boolean" || row.github_write !== undefined && row.github_write !== "off" && row.github_write !== "conductor") throw new Error("roadmap config requires github_mirror boolean and github_write off or conductor");
11
+ return { github_mirror: row.github_mirror === true, github_write: row.github_write === "conductor" ? "conductor" : "off" };
12
+ }
6
13
  export const MILESTONE_LIMITS = Object.freeze({ title: 300, outcome: 4000, spec: 160, issue: 300, actor: 64 });
7
14
  export type MilestoneState = typeof MILESTONE_STATES[number];
8
15
  export type MilestoneHorizon = typeof MILESTONE_HORIZONS[number];
@@ -10,6 +17,8 @@ export type MilestoneLinkKind = typeof MILESTONE_LINK_KINDS[number];
10
17
  export interface MilestoneHistoryEntry {
11
18
  at: number; by: string; event: "created" | "edited" | "linked" | "unlinked" | "ordered" | "state";
12
19
  fields?: string[]; kind?: MilestoneLinkKind;
20
+ /** #1622 family 4: the same three keys task history carries for an instructed person verdict. Only on a `state` entry; the write path restricts them to done and dropped. */
21
+ instructed?: true; instructedPeer?: string; instructionReceipt?: string;
13
22
  }
14
23
  export interface MilestoneInput {
15
24
  title: string; outcome: string; state?: MilestoneState; horizon?: MilestoneHorizon; order?: number;
@@ -92,7 +101,7 @@ export function milestoneHistory(raw: unknown): MilestoneHistoryEntry[] {
92
101
  if (!Array.isArray(raw) || raw.length > MILESTONE_HISTORY_LIMIT) throw new Error("roadmap history is full or invalid");
93
102
  return raw.map(value => {
94
103
  const row = object(value);
95
- if (Object.keys(row).some(key => !["at", "by", "event", "fields", "kind"].includes(key)) || !["created", "edited", "linked", "unlinked", "ordered", "state"].includes(String(row.event))) throw new Error("roadmap history event is invalid");
104
+ if (Object.keys(row).some(key => !["at", "by", "event", "fields", "kind", "instructed", "instructedPeer", "instructionReceipt"].includes(key)) || !["created", "edited", "linked", "unlinked", "ordered", "state"].includes(String(row.event))) throw new Error("roadmap history event is invalid");
96
105
  const entry: MilestoneHistoryEntry = { at: milestoneId(row.at), by: milestoneActor(row.by), event: row.event as MilestoneHistoryEntry["event"] };
97
106
  if (row.fields !== undefined) {
98
107
  if (!Array.isArray(row.fields) || row.fields.length > FIELDS.length || new Set(row.fields).size !== row.fields.length || row.fields.some(field => !(FIELDS as readonly unknown[]).includes(field))) throw new Error("roadmap history fields are invalid");
@@ -102,10 +111,26 @@ export function milestoneHistory(raw: unknown): MilestoneHistoryEntry[] {
102
111
  if (!(MILESTONE_LINK_KINDS as readonly unknown[]).includes(row.kind)) throw new Error("roadmap history link kind is invalid");
103
112
  entry.kind = row.kind as MilestoneLinkKind;
104
113
  }
114
+ const provenance = ["instructed", "instructedPeer", "instructionReceipt"].filter(key => row[key] !== undefined);
115
+ if (provenance.length) {
116
+ // All three together, on a state entry that names exactly the state field; anything else is a forged or truncated record.
117
+ if (provenance.length !== 3 || row.instructed !== true || row.event !== "state" || !Array.isArray(row.fields) || row.fields.length !== 1 || row.fields[0] !== "state"
118
+ || typeof row.instructedPeer !== "string" || row.instructedPeer.length > MILESTONE_LIMITS.actor || !/^[a-z][a-z0-9-]*$/.test(row.instructedPeer)
119
+ || typeof row.instructionReceipt !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(row.instructionReceipt)) throw new Error("roadmap history instructed provenance is invalid");
120
+ entry.instructed = true; entry.instructedPeer = row.instructedPeer; entry.instructionReceipt = row.instructionReceipt;
121
+ }
105
122
  return entry;
106
123
  });
107
124
  }
108
125
 
126
+ /**
127
+ * R4 (#1482) and R2 part 3 (#1480): the one typed GitHub milestone-membership field. `planRoadmapMirror` attaches an existing
128
+ * issue with it and a decomposition publish carries it on the issue it creates, so both reach GitHub through one construction.
129
+ */
130
+ export function milestoneMembershipField(milestone: number): [string, string] {
131
+ return ["-F", `milestone=${milestoneId(milestone)}`];
132
+ }
133
+
109
134
  /** R3: a qualified GitHub repository, lower-cased the way issue refs are. */
110
135
  export function githubRepo(raw: unknown): string {
111
136
  if (typeof raw !== "string" || raw.length > MILESTONE_LIMITS.issue || !/^[A-Za-z0-9][A-Za-z0-9-]{0,38}\/[A-Za-z0-9_.-]{1,100}$/.test(raw)) throw new Error("roadmap repo needs owner/name");
@@ -125,3 +150,36 @@ export interface MilestoneSuggestion {
125
150
  citeMilestone: string | null; citeItem: string;
126
151
  state: SuggestionState; by: string; created: number; settled: number | null; settledBy: string | null;
127
152
  }
153
+
154
+ /**
155
+ * R2 (#1480): a model-written decomposition of one milestone. Advisory data like a suggestion: it is stored apart from the
156
+ * roadmap, no accept path links anything from part 1, and a later intake reads it by id.
157
+ */
158
+ export const DECOMPOSE_INTAKES = ["spec", "task"] as const;
159
+ export const DECOMPOSITION_STATES = ["pending", "accepted", "rejected", "superseded"] as const;
160
+ export const DECOMPOSE_LIMITS = Object.freeze({ parts: 8, title: 300, detail: 1200, cites: 16 });
161
+ export type DecomposeIntake = typeof DECOMPOSE_INTAKES[number];
162
+ export type DecompositionState = typeof DECOMPOSITION_STATES[number];
163
+ export interface DecomposePart {
164
+ title: string;
165
+ /** What the part changes and how it is verified. */
166
+ detail: string;
167
+ /** A hub task class, named `class` as a `hub_backlog_split` part names it. */
168
+ class: string;
169
+ /** `spec`: the part changes behaviour and needs its own spec issue; `task`: a mechanical chore that goes straight to a task. */
170
+ intake: DecomposeIntake;
171
+ /** Ids copied from what the model was shown: linked spec ids and issue refs. */
172
+ cites: string[];
173
+ }
174
+ export interface MilestoneDecomposition {
175
+ id: number; milestone: number; parts: DecomposePart[]; state: DecompositionState;
176
+ by: string; created: number; settled: number | null; settledBy: string | null;
177
+ }
178
+
179
+ /**
180
+ * R2 part 2 (#1480): one proposed part accepted as a held intake draft. Keyed by the pending row it came from and the part's
181
+ * 1-based position, so a second accept of the same part finds this row instead of making a second draft.
182
+ */
183
+ export interface DecompositionAccept {
184
+ decomposition: number; milestone: number; part: number; task: number; intake: DecomposeIntake; by: string; at: number;
185
+ }
@@ -145,7 +145,7 @@ function siblingOrder(states: Readonly<Record<string, PeerState>>, opts: Instanc
145
145
  return (a, b) => Number(states[a] !== "idle") - Number(states[b] !== "idle") || count(opts.wip, a) - count(opts.wip, b) || count(opts.load, a) - count(opts.load, b);
146
146
  }
147
147
  /** A class kind expands once; an explicitly declared instance remains an exact id. */
148
- function expandClassPeers(peers: readonly PeerId[], states: Readonly<Record<string, PeerState>>, opts: InstanceRoutingOptions): PeerId[] {
148
+ export function expandClassPeers(peers: readonly PeerId[], states: Readonly<Record<string, PeerState>>, opts: InstanceRoutingOptions): PeerId[] {
149
149
  if (!hasInstances(opts)) return [...peers];
150
150
  return [...new Set(peers.flatMap(peer => {
151
151
  const kind = (opts.adapterCatalog?.kindOf ?? kindOf)(peer, opts.instances);
@@ -365,6 +365,23 @@ export function implementers(history: readonly { by: PeerId; event: string }[] |
365
365
  return new Set((history ?? []).filter(entry => (entry.event === "accepted" || entry.event === "done") && entry.by !== "user").map(entry => entry.by));
366
366
  }
367
367
 
368
+ /**
369
+ * #1626 C: `ahub doctor`'s routing row. The caller passes the peers it found rostered with implementer work; a peer that no
370
+ * `[classes.*].peers` list names can never be offered a task automatically, so the row says which peers those are and where the
371
+ * class lists live. Pure, and a warning rather than a failure: routing and the file facts come in from the caller.
372
+ */
373
+ export function classListRow(implementers: readonly PeerId[], routing: Routing, file: string, present: boolean): { ok: boolean | undefined; detail: string } {
374
+ const listed = new Set<string>();
375
+ for (const policy of Object.values(routing.classes)) for (const peer of policy?.peers ?? []) listed.add(peer);
376
+ const missing = [...new Set(implementers)].filter(peer => !listed.has(peer)).sort();
377
+ if (!missing.length) return { ok: true, detail: "every rostered implementer is in a class peer list" };
378
+ const classes = Object.keys(routing.classes).sort();
379
+ const lists = classes.length ? classes.map(name => `[classes.${name}].peers`).join(", ") : "[classes.implement].peers";
380
+ const where = present ? file : `${file} (no such file yet, so the shipped default is in use: create it)`;
381
+ const them = missing.length === 1 ? "it" : "them";
382
+ return { ok: undefined, detail: `${missing.join(", ")} can implement but no [classes.*].peers list names ${them}, so the hub never offers ${them} a task automatically; add ${missing.join(", ")} to one of the class peer lists in ${where} (${lists})` };
383
+ }
384
+
368
385
  export interface PlannerWalkInput {
369
386
  /** The settled planner holders, sorted by id. The walk sorts again, so an unsorted input cannot change the result. */
370
387
  planners: readonly PeerId[];
@@ -276,8 +276,9 @@ function captureLayout(root: string): void {
276
276
  if (optionalInfo(join(root, "scripts"))) knownLayout(join(root, "scripts"), [], ["check-docs.mjs"]);
277
277
  const modules = join(root, "node_modules");
278
278
  if (optionalInfo(modules)) {
279
- knownLayout(modules, ["@staix"], []); const scope = join(modules, "@staix"); knownLayout(scope, ["agent-mem"], []);
279
+ knownLayout(modules, ["@staix"], []); const scope = join(modules, "@staix"); knownLayout(scope, ["agent-mem"], [], ["cli-output"]);
280
280
  knownLayout(join(scope, "agent-mem"), ["src", "bin"], ["package.json", "README.md", "LICENSE"]);
281
+ if (optionalInfo(join(scope, "cli-output"))) knownLayout(join(scope, "cli-output"), ["src"], ["package.json", "README.md", "LICENSE"]);
281
282
  }
282
283
  }
283
284
  function verifyQuarantine(root: string, capture: Capture): void {
@@ -0,0 +1,128 @@
1
+ import type { SdlcGh } from "./sdlc.ts";
2
+
3
+ /** Bounded GitHub evidence; missing or ambiguous coverage never becomes a count. */
4
+ export interface BranchCi {
5
+ runs: { id: number; attempt: number }[];
6
+ fullGateRuns: number;
7
+ successfulGateRuns: number;
8
+ failedGateRuns: number;
9
+ cancelledGateRuns: number;
10
+ otherGateRuns: number;
11
+ macosShardRuns: number;
12
+ firstPass: 0 | 1 | null;
13
+ }
14
+
15
+ type Row = Record<string, any>;
16
+ const PAGE_SIZE = 100;
17
+ const PAGE_LIMIT = 10;
18
+ const TIMEOUT = 10_000;
19
+ const CAP = 256 * 1024;
20
+ const integer = (v: unknown): v is number => Number.isSafeInteger(v) && (v as number) > 0;
21
+ const timestamp = (v: unknown): number => typeof v === "string" ? Date.parse(v) : NaN;
22
+
23
+ /** Read all pages, failing closed on an error, malformed page, changed total or a bounded overflow. */
24
+ async function pages(run: SdlcGh, endpoint: string, fields: string[], projection: string, key?: string): Promise<Row[] | undefined> {
25
+ const all: Row[] = []; let total: number | undefined;
26
+ for (let page = 1; page <= PAGE_LIMIT; page++) {
27
+ const reply = await run(["api", "-X", "GET", endpoint, ...fields, "-F", `per_page=${PAGE_SIZE}`, "-F", `page=${page}`, "--jq", projection], TIMEOUT, undefined, CAP);
28
+ if (reply.code !== 0) return;
29
+ const parsed = JSON.parse(reply.stdout), rows = key ? parsed?.[key] : parsed;
30
+ if (!Array.isArray(rows) || rows.length > PAGE_SIZE || rows.some(row => !row || typeof row !== "object")) return;
31
+ if (key) {
32
+ if (!Number.isSafeInteger(parsed.total_count) || parsed.total_count < 0 || (total !== undefined && total !== parsed.total_count)) return;
33
+ total = parsed.total_count;
34
+ }
35
+ all.push(...rows);
36
+ if (total !== undefined ? all.length === total : rows.length < PAGE_SIZE) return all;
37
+ if (total !== undefined && (all.length > total || rows.length < PAGE_SIZE)) return;
38
+ }
39
+ }
40
+
41
+ /** Associate PR workflow runs by verified same-repository branch and lifetime, not pull_requests (often empty). */
42
+ export async function readBranchCi(repo: string, number: number, firstHead: string | undefined, run: SdlcGh): Promise<BranchCi | undefined> {
43
+ try {
44
+ const response = await run(["api", `repos/${repo}/pulls/${number}`, "--jq", "{number,state,created_at,merged_at,head:{ref:.head.ref,repo:{full_name:.head.repo.full_name}},base:{repo:{full_name:.base.repo.full_name}}}"], TIMEOUT, undefined, CAP);
45
+ if (response.code !== 0) return;
46
+ const pr = JSON.parse(response.stdout), branch = pr?.head?.ref, start = timestamp(pr?.created_at), end = timestamp(pr?.merged_at);
47
+ if (pr.number !== number || pr.state !== "closed" || typeof branch !== "string" || !branch || !Number.isFinite(start) || !Number.isFinite(end) || end < start
48
+ || pr.head?.repo?.full_name?.toLowerCase() !== repo.toLowerCase() || pr.base?.repo?.full_name?.toLowerCase() !== repo.toLowerCase()) return;
49
+ const owner = repo.split("/")[0];
50
+ const prs = await pages(run, `repos/${repo}/pulls`, ["-f", "state=all", "-f", `head=${owner}:${branch}`], "[.[]|{number,created_at,closed_at}]");
51
+ if (!prs || !prs.some(row => row.number === number)) return;
52
+ for (const other of prs) {
53
+ if (other.number === number) continue;
54
+ const created = timestamp(other.created_at), closed = other.closed_at === null ? Infinity : timestamp(other.closed_at);
55
+ if (!Number.isFinite(created) || !(Number.isFinite(closed) || closed === Infinity)) return;
56
+ if (created <= end && closed >= start) return;
57
+ }
58
+ const rows = await pages(run, `repos/${repo}/actions/runs`, ["-f", `branch=${branch}`, "-f", "event=pull_request"], "{total_count,workflow_runs:[.workflow_runs[]|{id,path,created_at,head_sha,status,conclusion,run_attempt,pull_requests:[.pull_requests[].number]}]}", "workflow_runs");
59
+ if (!rows) return;
60
+ if (rows.some(row => typeof row.path !== "string" || !Number.isFinite(timestamp(row.created_at)) || !Array.isArray(row.pull_requests) || row.pull_requests.some((value: unknown) => !integer(value)))) return;
61
+ const checks = rows.filter(row => row.path === ".github/workflows/check.yml" && timestamp(row.created_at) >= start && timestamp(row.created_at) <= end && (row.pull_requests.length === 0 || row.pull_requests.includes(number)));
62
+ if (checks.some(row => row.pull_requests.some((value: number) => value !== number))) return;
63
+ // ponytail: inspect at most one page of check runs and ten attempts each; raise the bounds with a provider-side summary.
64
+ if (checks.length > PAGE_SIZE || checks.some(row => !integer(row.id) || !integer(row.run_attempt) || row.run_attempt > PAGE_LIMIT || !/^[a-f0-9]{40}$/.test(row.head_sha) || typeof row.status !== "string")) return;
65
+ if (new Set(checks.map(row => row.id)).size !== checks.length) return;
66
+ const timeline = await pages(run, `repos/${repo}/issues/${number}/timeline`, [], "[.[]|{event,created_at}]");
67
+ if (!timeline) return;
68
+ const changes = timeline.filter(row => row.event === "ready_for_review" || row.event === "converted_to_draft").map(row => ({ event: row.event, at: timestamp(row.created_at) })).sort((a, b) => a.at - b.at);
69
+ if (changes.some(change => !Number.isFinite(change.at))) return;
70
+ const initialDraft = changes.length > 0 && changes[0]!.event === "ready_for_review";
71
+ let finalDraft = initialDraft;
72
+ for (const change of changes) {
73
+ if ((change.event === "ready_for_review") !== finalDraft) return;
74
+ finalDraft = change.event === "converted_to_draft";
75
+ }
76
+ if (finalDraft) return;
77
+ const draftAt = (at: number): boolean | undefined => {
78
+ let draft = initialDraft;
79
+ for (const change of changes) {
80
+ if (change.at === at) return;
81
+ if (change.at > at) break;
82
+ if ((change.event === "ready_for_review") !== draft) return;
83
+ draft = change.event === "converted_to_draft";
84
+ }
85
+ return draft;
86
+ };
87
+ let macosShardRuns = 0, firstPass: 0 | 1 | null = null, firstDecided = false;
88
+ const observedRuns: { id: number; attempt: number; conclusion: string }[] = [];
89
+ const ordered = checks.sort((a, b) => timestamp(a.created_at) - timestamp(b.created_at) || a.id - b.id);
90
+ const firstHeadTimes = ordered.filter(row => firstHead && row.head_sha === firstHead).map(row => timestamp(row.created_at));
91
+ const firstOrderAmbiguous = new Set(firstHeadTimes).size !== firstHeadTimes.length;
92
+ for (const check of ordered) {
93
+ let atMerge: { id: number; attempt: number; conclusion: string } | undefined;
94
+ let previousStarted = -Infinity;
95
+ for (let attempt = 1; attempt <= check.run_attempt; attempt++) {
96
+ const attemptReply = await run(["api", `repos/${repo}/actions/runs/${check.id}/attempts/${attempt}`, "--jq", "{id,run_attempt,status,conclusion,run_started_at,updated_at}"], TIMEOUT, undefined, CAP);
97
+ if (attemptReply.code !== 0) return;
98
+ const observed = JSON.parse(attemptReply.stdout), started = timestamp(observed.run_started_at), updated = timestamp(observed.updated_at);
99
+ if (observed.id !== check.id || observed.run_attempt !== attempt || !Number.isFinite(started) || !Number.isFinite(updated) || started < previousStarted || updated < started || started === end || updated === end) return;
100
+ previousStarted = started;
101
+ if (started > end) continue;
102
+ if (observed.status !== "completed" || typeof observed.conclusion !== "string" || updated > end) return;
103
+ atMerge = { id: check.id, attempt, conclusion: observed.conclusion };
104
+ const jobs = await pages(run, `repos/${repo}/actions/runs/${check.id}/attempts/${attempt}/jobs`, [], "{total_count,jobs:[.jobs[]|{name,status,conclusion,runner_id}]}", "jobs");
105
+ if (!jobs || jobs.some(job => typeof job.name !== "string")) return;
106
+ const shards = jobs.filter(job => /^check \(macos-latest\) shard [1-4]\/4$/.test(job.name));
107
+ if (shards.some(job => job.status !== "completed" || typeof job.conclusion !== "string" || !(job.runner_id === null || job.runner_id === 0 || integer(job.runner_id)) || (job.runner_id === null || job.runner_id === 0) && job.conclusion !== "skipped" && job.conclusion !== "cancelled")) return;
108
+ const ran = shards.filter(job => job.conclusion !== "skipped" && integer(job.runner_id));
109
+ macosShardRuns += ran.length;
110
+ if (attempt !== 1 || firstDecided || !firstHead || check.head_sha !== firstHead) continue;
111
+ const draft = draftAt(timestamp(check.created_at));
112
+ if (draft === undefined) return;
113
+ if (draft || ran.length === 0 || observed.status !== "completed" || observed.conclusion === "cancelled") continue;
114
+ if (observed.conclusion === "success") firstPass = 1;
115
+ else if (observed.conclusion === "failure" || observed.conclusion === "timed_out") firstPass = 0;
116
+ else return;
117
+ firstDecided = true;
118
+ }
119
+ if (!atMerge) return;
120
+ observedRuns.push(atMerge);
121
+ }
122
+ const successfulGateRuns = observedRuns.filter(row => row.conclusion === "success").length;
123
+ const failedGateRuns = observedRuns.filter(row => row.conclusion === "failure" || row.conclusion === "timed_out").length;
124
+ const cancelledGateRuns = observedRuns.filter(row => row.conclusion === "cancelled").length;
125
+ return { runs: observedRuns.map(row => ({ id: row.id, attempt: row.attempt })), fullGateRuns: observedRuns.length,
126
+ successfulGateRuns, failedGateRuns, cancelledGateRuns, otherGateRuns: observedRuns.length - successfulGateRuns - failedGateRuns - cancelledGateRuns, macosShardRuns, firstPass: firstOrderAmbiguous ? null : firstPass };
127
+ } catch { return; }
128
+ }
@@ -27,6 +27,7 @@ export interface MergeInput {
27
27
  tasks: DeliveryTask[];
28
28
  run: SdlcGh;
29
29
  readableMetadata?: (path: string) => boolean;
30
+ firstSubmittedHead?: string;
30
31
  /** Final synchronous authority and queue-input fence, after fresh gates and immediately before the gh call. */
31
32
  beforeMerge?: (queue: MergeQueue | undefined) => string | undefined;
32
33
  /** Post-run host fence and durable progress record. False or a throw withholds cleanup. No remote text is supplied. */
@@ -51,7 +52,9 @@ export interface MergeOutcome {
51
52
  }
52
53
 
53
54
  export const MERGE_READBACK_INTERVAL_MS = 5 * 60_000;
54
- export const MERGE_READBACK_DEADLINE_MS = 8_000;
55
+ // ponytail: 60 s bounds paged branch and job readbacks; lower it once a single bounded provider read supplies the same evidence.
56
+ export const MERGE_READBACK_DEADLINE_MS = 60_000;
57
+ export const INLINE_MERGE_READBACK_DEADLINE_MS = 8_000;
55
58
  const SHA = /^[0-9a-f]{40}$/;
56
59
  const REPO = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
57
60
  /**
@@ -305,11 +308,11 @@ export async function guardedMerge(input: MergeInput & { mode: AutoMergeMode }):
305
308
  if (input.recordMerge) {
306
309
  // #481 S7: the merged PR's review and CI figures, read once now that the merge is observed. After the merge there is nothing left to race, so this await is fine;
307
310
  // its own bound keeps a slow GitHub from holding the record, and a failed read records no cost (unknown), never a zero.
308
- const costDeadline = performance.now() + 8000;
311
+ const costDeadline = performance.now() + INLINE_MERGE_READBACK_DEADLINE_MS;
309
312
  const cost = result.state === "merged" ? await readPrCostHistory(decision.repo, decision.pr, (args, timeout, cwd, cap) => {
310
313
  const left = costDeadline - performance.now();
311
314
  return left > 0 ? input.run(args, Math.min(timeout ?? 10_000, left), cwd, cap) : Promise.resolve({ code: 1, stdout: "" });
312
- }).then(mergeCostFrom, () => undefined) : undefined;
315
+ }, undefined, undefined, input.firstSubmittedHead).then(mergeCostFrom, () => undefined) : undefined;
313
316
  let record: MergeRecord={repo:decision.repo,pr:decision.pr,head:decision.head,at:Date.now(),...result,...(cost?{cost}:{}),cleanup:"not_started",ownerNotice:"not_started"};
314
317
  const save = () => {try {return input.recordMerge!({...record});}catch{return false;}};
315
318
  if (!save()) {record={...record,cleanup:"skipped",reason:"authority_changed"};save();}
@@ -38,6 +38,12 @@ export interface TaskSample {
38
38
  review_rounds_at_merge: number | null;
39
39
  ci_runs_at_merge: number | null;
40
40
  github_reviews_at_merge: number | null;
41
+ full_gate_runs: number | null;
42
+ successful_gate_runs: number | null;
43
+ failed_gate_runs: number | null;
44
+ cancelled_gate_runs: number | null;
45
+ other_gate_runs: number | null;
46
+ macos_shard_runs: number | null;
41
47
  }
42
48
 
43
49
  export interface Summary { n: number; unknown: number; mean: number | null; median: number | null; p90: number | null; max: number | null }
@@ -102,7 +108,7 @@ function staleHeadRounds(history: MetricTask["history"]): number | null {
102
108
  }
103
109
 
104
110
  /** One task's values from its own history. A private task never reaches here. */
105
- export function taskSample(task: MetricTask, extra: { mergedAt?: number; ciReruns?: number | null; ciRuns?: number | null; reviews?: number | null } = {}): TaskSample {
111
+ export function taskSample(task: MetricTask, extra: { mergedAt?: number; ciReruns?: number | null; ciRuns?: number | null; reviews?: number | null; firstPass?: 0 | 1 | null; fullGateRuns?: number | null; successfulGateRuns?: number | null; failedGateRuns?: number | null; cancelledGateRuns?: number | null; otherGateRuns?: number | null; macosShardRuns?: number | null } = {}): TaskSample {
106
112
  const history = [...task.history].filter(entry => Number.isFinite(entry.at) && entry.at >= 0).sort((a, b) => a.at - b.at);
107
113
  const view: MetricTask = { id: task.id, history };
108
114
  const accepted = first(view, ["accepted"]);
@@ -119,6 +125,7 @@ export function taskSample(task: MetricTask, extra: { mergedAt?: number; ciRerun
119
125
  const latestRun = doneHead ? history.slice(0, firstDone).findLast(entry => entry.event === "check run passed" || entry.event === "check run failed") : undefined;
120
126
  const isolatedCheck = latestRun?.requestHead === doneHead ? latestRun : undefined;
121
127
  const ci = completionCheck ?? isolatedCheck;
128
+ const hasHubCheck = history.some(entry => ["check passed", "check failed", "check run passed", "check run failed"].includes(entry.event));
122
129
  const approvedAt = history.find(entry => entry.event === "approved")?.at ?? null;
123
130
  return {
124
131
  id: task.id,
@@ -132,11 +139,17 @@ export function taskSample(task: MetricTask, extra: { mergedAt?: number; ciRerun
132
139
  // Rework grows with every round, so it is a value only once the task is approved: a task still in flight has no final one, and a
133
140
  // provisional point would move at each verdict and could start a second breach episode inside one shift.
134
141
  rework_rounds: dones.length && approvedAt !== null ? history.filter(entry => entry.event === "changes_requested" && entry.evidenceOnly !== true).length : null,
135
- first_pass_check: ci ? (ci.event === "check passed" || ci.event === "check run passed" ? 1 : 0) : null,
142
+ first_pass_check: ci ? (ci.event === "check passed" || ci.event === "check run passed" ? 1 : 0) : hasHubCheck ? null : extra.firstPass ?? null,
136
143
  same_head_ci_reruns: extra.ciReruns === undefined ? null : extra.ciReruns,
137
144
  // Counted only for a merged PR whose figures were read: a done before the merge is one review round.
138
145
  review_rounds_at_merge: extra.mergedAt !== undefined && Number.isFinite(extra.mergedAt) ? dones.filter(entry => entry.at <= extra.mergedAt!).length : null,
139
146
  ci_runs_at_merge: extra.ciRuns === undefined ? null : extra.ciRuns,
147
+ full_gate_runs: extra.fullGateRuns ?? null,
148
+ successful_gate_runs: extra.successfulGateRuns ?? null,
149
+ failed_gate_runs: extra.failedGateRuns ?? null,
150
+ cancelled_gate_runs: extra.cancelledGateRuns ?? null,
151
+ other_gate_runs: extra.otherGateRuns ?? null,
152
+ macos_shard_runs: extra.macosShardRuns ?? null,
140
153
  github_reviews_at_merge: extra.reviews === undefined ? null : extra.reviews,
141
154
  stale_head_re_reviews: approvedAt !== null ? staleHeadRounds(history) : null,
142
155
  };
@@ -218,7 +231,7 @@ export interface MetricsReport {
218
231
  first_pass_check: { n: number; unknown: number; rate: number | null };
219
232
  same_head_ci_reruns: Summary;
220
233
  stale_head_re_reviews: Summary;
221
- review_rounds_at_merge: Summary; ci_runs_at_merge: Summary; github_reviews_at_merge: Summary;
234
+ review_rounds_at_merge: Summary; ci_runs_at_merge: Summary; github_reviews_at_merge: Summary; full_gate_runs: Summary; successful_gate_runs: Summary; failed_gate_runs: Summary; cancelled_gate_runs: Summary; other_gate_runs: Summary; macos_shard_runs: Summary;
222
235
  };
223
236
  /** Merged PRs whose review and CI figures were read at merge, and how many of the counted tasks have none (unknown, never 0). */
224
237
  merged: { read: number; unknown: number };
@@ -235,9 +248,9 @@ const rate = (values: readonly (number | null)[]) => {
235
248
  * The whole report from board tasks. `since` keeps samples that count at or after it; `mergedAt` and `ciReruns` come from bounded
236
249
  * PR readbacks keyed by task id and are optional. Private tasks are counted as withheld and read for nothing else.
237
250
  */
238
- export function sdlcMetrics(tasks: readonly MetricTask[], opts: { since?: number; bands?: BandsConfig; stalls?: StallCounts; mergedAt?: Readonly<Record<number, number>>; ciReruns?: Readonly<Record<number, number | null>>; ciRuns?: Readonly<Record<number, number | null>>; reviews?: Readonly<Record<number, number | null>>; external?: Partial<Record<BandMetric, readonly SeriesPoint[]>> } = {}): MetricsReport {
251
+ export function sdlcMetrics(tasks: readonly MetricTask[], opts: { since?: number; bands?: BandsConfig; stalls?: StallCounts; mergedAt?: Readonly<Record<number, number>>; ciReruns?: Readonly<Record<number, number | null>>; ciRuns?: Readonly<Record<number, number | null>>; reviews?: Readonly<Record<number, number | null>>; firstPass?: Readonly<Record<number, 0 | 1 | null>>; fullGateRuns?: Readonly<Record<number, number | null>>; successfulGateRuns?: Readonly<Record<number, number | null>>; failedGateRuns?: Readonly<Record<number, number | null>>; cancelledGateRuns?: Readonly<Record<number, number | null>>; otherGateRuns?: Readonly<Record<number, number | null>>; macosShardRuns?: Readonly<Record<number, number | null>>; external?: Partial<Record<BandMetric, readonly SeriesPoint[]>> } = {}): MetricsReport {
239
252
  const visible = tasks.filter(task => !task.private);
240
- const all = visible.map(task => taskSample(task, { mergedAt: opts.mergedAt?.[task.id], ciReruns: opts.ciReruns?.[task.id], ciRuns: opts.ciRuns?.[task.id], reviews: opts.reviews?.[task.id] }));
253
+ const all = visible.map(task => taskSample(task, { mergedAt: opts.mergedAt?.[task.id], ciReruns: opts.ciReruns?.[task.id], ciRuns: opts.ciRuns?.[task.id], reviews: opts.reviews?.[task.id], firstPass: opts.firstPass?.[task.id], fullGateRuns: opts.fullGateRuns?.[task.id], successfulGateRuns: opts.successfulGateRuns?.[task.id], failedGateRuns: opts.failedGateRuns?.[task.id], cancelledGateRuns: opts.cancelledGateRuns?.[task.id], otherGateRuns: opts.otherGateRuns?.[task.id], macosShardRuns: opts.macosShardRuns?.[task.id] }));
241
254
  const samples = opts.since === undefined ? all : all.filter(sample => sample.at >= opts.since!);
242
255
  const bands: BandResult[] | "off" = opts.bands && Object.keys(opts.bands).length
243
256
  ? BAND_METRICS.flatMap(metric => opts.bands![metric] ? [controlEpisode(EXTERNAL_METRICS.includes(metric) ? [...(opts.external?.[metric] ?? [])] : series(samples, metric as TaskMetric), metric, opts.bands![metric]!)] : [])
@@ -252,6 +265,7 @@ export function sdlcMetrics(tasks: readonly MetricTask[], opts: { since?: number
252
265
  stale_head_re_reviews: summarize(samples.map(s => s.stale_head_re_reviews)),
253
266
  review_rounds_at_merge: summarize(samples.map(s => s.review_rounds_at_merge)), ci_runs_at_merge: summarize(samples.map(s => s.ci_runs_at_merge)),
254
267
  github_reviews_at_merge: summarize(samples.map(s => s.github_reviews_at_merge)),
268
+ full_gate_runs: summarize(samples.map(s => s.full_gate_runs)), successful_gate_runs: summarize(samples.map(s => s.successful_gate_runs)), failed_gate_runs: summarize(samples.map(s => s.failed_gate_runs)), cancelled_gate_runs: summarize(samples.map(s => s.cancelled_gate_runs)), other_gate_runs: summarize(samples.map(s => s.other_gate_runs)), macos_shard_runs: summarize(samples.map(s => s.macos_shard_runs)),
255
269
  },
256
270
  merged: { read: samples.filter(s => s.ci_runs_at_merge !== null || s.github_reviews_at_merge !== null).length, unknown: samples.filter(s => s.ci_runs_at_merge === null && s.github_reviews_at_merge === null).length },
257
271
  stalls: opts.stalls ?? { open: 0, byKind: {}, doneWithoutWrites: 0 }, bands,
package/src/hub/sdlc.ts CHANGED
@@ -13,6 +13,7 @@ import { join } from "node:path";
13
13
  import { spawn } from "node:child_process";
14
14
  import { childEnv, stopOwnedProcess } from "./child-process.ts";
15
15
  import { hostExecutable } from "./host-executable.ts";
16
+ import { readBranchCi } from "./sdlc-branch-ci.ts";
16
17
 
17
18
  /** The off-mode default (#257). Off output, receipts and schemas keep this shape. */
18
19
  export const SDLC_STAGES = ["spec", "plan", "implement", "review", "verify", "merge", "release"] as const;
@@ -634,6 +635,8 @@ export function requiredCiBlocker(required: readonly string[], checks: PrEvidenc
634
635
  /** A complete resolved-thread snapshot already proves there is no pending unanswered bot thread. */
635
636
  export function reviewReadinessFromEvidence(evidence: PrEvidence | undefined, expected: string | undefined, required: readonly string[], repository?: string): ReviewReadiness | undefined {
636
637
  if (!evidence || evidence.unresolved !== 0) return undefined;
638
+ // A draft's failed aggregate needs job-step evidence, which this compact snapshot does not carry.
639
+ if (evidence.draft === true && evidence.checks.some(check => check.name === "check (macos-latest)" && check.state === "failed")) return undefined;
637
640
  const checks = requiredCheckNames(repository, required);
638
641
  if (!checks.length) return { ready: false, blockers: ["required checks unknown: set required_checks in .agenthub/sdlc.toml"], checks };
639
642
  if (!checks.every(name => evidence.checks.some(check => check.name === name)) || evidence.checks.some(check => check.state === "unknown")) return undefined;
@@ -647,7 +650,30 @@ export function reviewReadinessFromEvidence(evidence: PrEvidence | undefined, ex
647
650
  }
648
651
 
649
652
  /** `checks` (#824) names the required checks that were judged, so a fresh reviewer can be told which ones passed at this head; absent when the read was unknown. */
650
- export interface ReviewReadiness { head?: string; ready: boolean; blockers: string[]; reusedRun?: number; checks?: string[] }
653
+ export interface ReviewReadiness { head?: string; ready: boolean; blockers: string[]; reusedRun?: number; checks?: string[]; deferred?: string[]; draftApprovalEligible?: boolean }
654
+
655
+ /** Only this repository's actual draft-deferral step can explain its failed macOS aggregate. */
656
+ async function draftMacosDeferred(repository: string, head: string, node: any, run: SdlcGh): Promise<boolean> {
657
+ if (repository.toLowerCase() !== "staixbwlb/agent-hub" || node?.name !== "check (macos-latest)"
658
+ || node.status !== "COMPLETED" || node.conclusion !== "FAILURE"
659
+ || node.checkSuite?.workflowRun?.workflow?.resourcePath !== "/STAIxBWLB/agent-hub/actions/workflows/check.yml") return false;
660
+ const url = typeof node.detailsUrl === "string" ? node.detailsUrl : "";
661
+ const match = /^https:\/\/github\.com\/STAIxBWLB\/agent-hub\/actions\/runs\/(\d+)\/job\/(\d+)$/.exec(url);
662
+ if (!match) return false;
663
+ const result = await run(["api", `repos/${repository}/actions/jobs/${match[2]}`], 10_000, undefined, 64 * 1024);
664
+ if (result.code !== 0 || Buffer.byteLength(result.stdout) > 64 * 1024) return false;
665
+ try {
666
+ const job = JSON.parse(result.stdout), steps = job.steps;
667
+ if (String(job.id) !== match[2] || String(job.run_id) !== match[1] || job.head_sha !== head
668
+ || job.name !== node.name || job.status !== "completed" || job.conclusion !== "failure" || !Array.isArray(steps)) return false;
669
+ const deferred = steps.filter((step: any) => step?.name === "macOS shards deferred for a draft PR");
670
+ const stacked = steps.filter((step: any) => step?.name === "macOS shards deferred for a stacked PR");
671
+ return deferred.length === 1 && deferred[0].status === "completed" && deferred[0].conclusion === "failure"
672
+ && stacked.length === 1 && stacked[0].conclusion === "skipped"
673
+ && steps.filter((step: any) => step?.conclusion === "failure").length === 1
674
+ && steps.every((step: any) => step?.status === "completed" && ["success", "skipped", "failure"].includes(step.conclusion));
675
+ } catch { return false; }
676
+ }
651
677
  /** Metadata-only pre-review admission; no remote body or comment text is requested. */
652
678
  export async function readReviewReadiness(receipt: SdlcReceipt, expected: string | undefined, run: SdlcGh = sdlcGh, requiredChecks: readonly string[] = []): Promise<ReviewReadiness> {
653
679
  const unknown = (): ReviewReadiness => ({ ready: false, blockers: ["review readiness unavailable"] });
@@ -655,7 +681,7 @@ export async function readReviewReadiness(receipt: SdlcReceipt, expected: string
655
681
  const full = requiredCheckNames(receipt.repo, requiredChecks);
656
682
  if (!full.length) return { ready: false, blockers: ["required checks unknown: set required_checks in .agenthub/sdlc.toml"], checks: full };
657
683
  const [owner, name] = receipt.repo.split("/");
658
- const query = "query($owner:String!,$name:String!,$number:Int!){repository(owner:$owner,name:$name){pullRequest(number:$number){headRefOid state commits(last:1){nodes{commit{oid tree{oid} statusCheckRollup{contexts(first:100){nodes{... on CheckRun{name status conclusion startedAt checkSuite{workflowRun{workflow{resourcePath}}}} ... on StatusContext{context state}} pageInfo{hasNextPage}}}}}} reviewThreads(first:100){nodes{isResolved comments(first:100){nodes{author{__typename} createdAt} pageInfo{hasNextPage}}} pageInfo{hasNextPage}}}}}";
684
+ const query = "query($owner:String!,$name:String!,$number:Int!){repository(owner:$owner,name:$name){pullRequest(number:$number){headRefOid state isDraft reviewDecision reviewRequests(first:100){nodes{__typename} pageInfo{hasNextPage}} commits(last:1){nodes{commit{oid tree{oid} statusCheckRollup{contexts(first:100){nodes{... on CheckRun{name status conclusion startedAt detailsUrl checkSuite{workflowRun{workflow{resourcePath}}}} ... on StatusContext{context state}} pageInfo{hasNextPage}}}}}} reviewThreads(first:100){nodes{isResolved comments(first:100){nodes{author{__typename} createdAt} pageInfo{hasNextPage}}} pageInfo{hasNextPage}}}}}";
659
685
  try {
660
686
  const deadline = performance.now() + 20_000;
661
687
  const bounded: SdlcGh = (args, timeout, cwd, cap) => performance.now() < deadline
@@ -688,6 +714,25 @@ export async function readReviewReadiness(receipt: SdlcReceipt, expected: string
688
714
  }) : [];
689
715
  const ciBlocker = requiredCiBlocker(full, checkEvidence, completeChecks);
690
716
  if (ciBlocker) blockers.push(ciBlocker);
717
+ let deferred: string[] | undefined;
718
+ const mac = "check (macos-latest)";
719
+ const macNodes = requiredNodes.filter(node => (node as { name?: unknown })?.name === mac);
720
+ if (pr.isDraft === true && !blockers.some(blocker => blocker !== ciBlocker) && ciBlocker
721
+ && [mac, "check (ubuntu-latest)", "seeded guards"].every(name => full.includes(name)) && macNodes.length === 1
722
+ && !requiredCiBlocker(full.filter(name => name !== mac), checkEvidence, completeChecks)
723
+ && checkEvidence.filter(check => check.name === mac).length === 1
724
+ && checkEvidence.find(check => check.name === mac)?.state === "failed"
725
+ && await draftMacosDeferred(receipt.repo, pr.headRefOid, macNodes[0], bounded)) {
726
+ // The proof is fetched separately; the PR may have changed while it was read.
727
+ const after = await bounded(args, 10_000, undefined, 512 * 1024);
728
+ try {
729
+ const refreshed = JSON.parse(after.stdout);
730
+ if (after.code === 0 && !refreshed.errors && JSON.stringify(refreshed.data?.repository?.pullRequest) === JSON.stringify(pr)) {
731
+ blockers.splice(blockers.indexOf(ciBlocker), 1);
732
+ deferred = [mac];
733
+ }
734
+ } catch { /* Incomplete evidence never admits review. */ }
735
+ }
691
736
  if (ciBlocker && contexts?.pageInfo?.hasNextPage === false && Array.isArray(nodes)
692
737
  && full.every(name => { const matches = (nodes as { name?: string; conclusion?: string }[]).filter(node => node?.name === name); return matches.length === 1 && matches[0]?.conclusion === "SKIPPED"; }) && sha(commit?.tree?.oid)) {
693
738
  reusedRun = await identicalTreeGate(receipt.repo, commit.tree.oid, bounded, full);
@@ -718,7 +763,12 @@ export async function readReviewReadiness(receipt: SdlcReceipt, expected: string
718
763
  }
719
764
  if (unanswered) blockers.push("bot review threads unanswered");
720
765
  }
721
- return { head: pr.headRefOid, ready: blockers.length === 0, blockers: [...new Set(blockers)], checks: [...full], ...(reusedRun !== undefined ? { reusedRun } : {}) };
766
+ const requests = pr.reviewRequests;
767
+ const draftApprovalEligible = !!deferred && Object.hasOwn(pr, "reviewDecision")
768
+ && [null, "APPROVED", "REVIEW_REQUIRED"].includes(pr.reviewDecision)
769
+ && requests?.pageInfo?.hasNextPage === false && parsePrEvidence({ headRefOid: pr.headRefOid, state: pr.state, files: [], statusCheckRollup: [], reviewRequests: requests.nodes }).pendingReviews !== null
770
+ && threads?.pageInfo?.hasNextPage === false && Array.isArray(threads.nodes) && threads.nodes.every((thread: { isResolved?: unknown }) => thread?.isResolved === true);
771
+ return { head: pr.headRefOid, ready: blockers.length === 0, blockers: [...new Set(blockers)], checks: full.filter(name => !deferred?.includes(name)), ...(deferred ? { deferred, draftApprovalEligible } : {}), ...(reusedRun !== undefined ? { reusedRun } : {}) };
722
772
  } catch { return unknown(); }
723
773
  }
724
774
 
@@ -745,7 +795,7 @@ async function identicalTreeGate(repository: string, tree: string, run: SdlcGh,
745
795
  }
746
796
 
747
797
  /** PR cost evidence excludes titles, bodies and comment text; unknown/truncated coverage never becomes zero. */
748
- export async function readPrCostHistory(repository: string, number: number, run: SdlcGh = sdlcGh, snapshot?: unknown, expectedHead?: string): Promise<import("./cost-governance.ts").CostPr | undefined> {
798
+ export async function readPrCostHistory(repository: string, number: number, run: SdlcGh = sdlcGh, snapshot?: unknown, expectedHead?: string, firstSubmittedHead?: string, recordedHeadInventory = false): Promise<import("./cost-governance.ts").CostPr | undefined> {
749
799
  if (!repo(repository) || !id(number)) return;
750
800
  const [owner, name] = repository.split("/");
751
801
  try {
@@ -775,7 +825,25 @@ export async function readPrCostHistory(repository: string, number: number, run:
775
825
  const linked = runs.workflow_runs.filter((row: { head_sha?: string; pull_requests?: number[] }) => heads.has(row.head_sha ?? "") || Array.isArray(row.pull_requests) && row.pull_requests.includes(number));
776
826
  if (linked.some((row: { id?: number; run_attempt?: number }) => !id(row.id) || !id(row.run_attempt))) return result;
777
827
  result.ciRuns = linked.map((row: { id: number; run_attempt: number }) => ({ id: row.id, attempt: row.run_attempt }));
778
- result.complete = reviewComplete && commitComplete && runs.total_count === runs.workflow_runs.length;
828
+ // The dogfood reader supplies a separately validated, complete recorded-head inventory for its bounded time window.
829
+ if (recordedHeadInventory && runs.total_count === runs.workflow_runs.length) {
830
+ result.complete = reviewComplete && commitComplete;
831
+ return result;
832
+ }
833
+ const directComplete = runs.total_count === runs.workflow_runs.length && runs.workflow_runs.every((row: { pull_requests?: number[] }) => Array.isArray(row.pull_requests) && row.pull_requests.length > 0 && row.pull_requests.every(id));
834
+ if (directComplete) {
835
+ result.ciRuns = runs.workflow_runs.filter((row: { pull_requests: number[] }) => row.pull_requests.includes(number)).map((row: { id: number; run_attempt: number }) => ({ id: row.id, attempt: row.run_attempt }));
836
+ result.complete = reviewComplete && commitComplete;
837
+ }
838
+ const branch = await readBranchCi(repository, number, firstSubmittedHead, run);
839
+ const sameDirectRuns = !directComplete || branch && result.ciRuns?.length === branch.runs.length && result.ciRuns.every(row => branch.runs.some(candidate => candidate.id === row.id));
840
+ if (branch && sameDirectRuns) {
841
+ result.ciRuns = branch.runs;
842
+ result.fullGateRuns = branch.fullGateRuns; result.cancelledGateRuns = branch.cancelledGateRuns;
843
+ result.successfulGateRuns = branch.successfulGateRuns; result.failedGateRuns = branch.failedGateRuns; result.otherGateRuns = branch.otherGateRuns;
844
+ result.macosShardRuns = branch.macosShardRuns; result.firstPass = branch.firstPass;
845
+ result.complete = reviewComplete && commitComplete;
846
+ }
779
847
  return result;
780
848
  } catch { return; }
781
849
  }