forgedock 1.52.0 → 1.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 (233) hide show
  1. package/.claude-plugin/marketplace.json +51 -0
  2. package/README.md +8 -2
  3. package/bin/auth/app-manifest.mjs +89 -0
  4. package/bin/auth/app-manifest.test.mjs +75 -0
  5. package/bin/auth/app-token.mjs +256 -0
  6. package/bin/auth/app-token.test.mjs +232 -0
  7. package/bin/brand.mjs +7 -0
  8. package/bin/config-history.mjs +151 -0
  9. package/bin/config-schema.mjs +115 -0
  10. package/bin/demo.mjs +65 -11
  11. package/bin/engine/outcome-codes.mjs +9 -3
  12. package/bin/engine/telemetry-seam.mjs +11 -3
  13. package/bin/engine/telemetry-seam.test.mjs +17 -0
  14. package/bin/engine-cli.mjs +110 -36
  15. package/bin/experiment.mjs +58 -6
  16. package/bin/first-run.mjs +122 -0
  17. package/bin/forge-utils.mjs +6 -2
  18. package/bin/forgedock.mjs +138 -142
  19. package/bin/help-text.mjs +144 -0
  20. package/bin/hooks/pre-tool-use.mjs +7 -0
  21. package/bin/journey.mjs +82 -83
  22. package/bin/lean/acceptance.mjs +313 -0
  23. package/bin/lean/acceptance.test.mjs +215 -0
  24. package/bin/lean/account-watch.mjs +28 -0
  25. package/bin/lean/account-watch.test.mjs +30 -0
  26. package/bin/lean/activation.mjs +38 -0
  27. package/bin/lean/activation.test.mjs +36 -1
  28. package/bin/lean/basered.mjs +115 -0
  29. package/bin/lean/basered.test.mjs +66 -0
  30. package/bin/lean/batch-health.mjs +114 -7
  31. package/bin/lean/batch-health.test.mjs +87 -1
  32. package/bin/lean/batch.mjs +41 -2
  33. package/bin/lean/batch.test.mjs +115 -11
  34. package/bin/lean/branchlock.mjs +54 -0
  35. package/bin/lean/branchlock.test.mjs +49 -0
  36. package/bin/lean/ceiling.mjs +72 -0
  37. package/bin/lean/ceiling.test.mjs +54 -0
  38. package/bin/lean/checkpoint-reconcile.mjs +43 -0
  39. package/bin/lean/checkpoint-reconcile.test.mjs +95 -0
  40. package/bin/lean/ci-budget.mjs +366 -0
  41. package/bin/lean/ci-budget.test.mjs +167 -0
  42. package/bin/lean/conformance.e2e.test.mjs +8 -1
  43. package/bin/lean/conformance.mjs +269 -38
  44. package/bin/lean/conformance.test.mjs +280 -7
  45. package/bin/lean/context.mjs +35 -6
  46. package/bin/lean/context.test.mjs +27 -1
  47. package/bin/lean/depcache.mjs +25 -1
  48. package/bin/lean/depcache.test.mjs +26 -0
  49. package/bin/lean/e2e.mjs +18 -2
  50. package/bin/lean/e2e.test.mjs +26 -1
  51. package/bin/lean/effects.mjs +47 -14
  52. package/bin/lean/execution.mjs +19 -3
  53. package/bin/lean/execution.test.mjs +63 -0
  54. package/bin/lean/facts.mjs +3 -3
  55. package/bin/lean/facts.test.mjs +5 -0
  56. package/bin/lean/findinglabel.mjs +16 -0
  57. package/bin/lean/findinglabel.test.mjs +39 -0
  58. package/bin/lean/fixround.mjs +14 -0
  59. package/bin/lean/fixround.test.mjs +25 -2
  60. package/bin/lean/gh-assoc.test.mjs +2 -1
  61. package/bin/lean/integration.mjs +100 -9
  62. package/bin/lean/integration.test.mjs +98 -0
  63. package/bin/lean/issuewatch-parity.mjs +64 -0
  64. package/bin/lean/issuewatch-parity.test.mjs +127 -0
  65. package/bin/lean/issuewatch-release.mjs +6 -2
  66. package/bin/lean/issuewatch-release.test.mjs +17 -1
  67. package/bin/lean/issuewatch.mjs +45 -6
  68. package/bin/lean/issuewatch.test.mjs +3 -2
  69. package/bin/lean/lanelock.mjs +14 -0
  70. package/bin/lean/lean.mjs +473 -100
  71. package/bin/lean/lean.test.mjs +686 -33
  72. package/bin/lean/light.mjs +48 -7
  73. package/bin/lean/light.test.mjs +37 -3
  74. package/bin/lean/limits.test.mjs +142 -9
  75. package/bin/lean/mechfix.mjs +124 -0
  76. package/bin/lean/mechfix.test.mjs +75 -0
  77. package/bin/lean/orchestrate-cancel.test.mjs +143 -0
  78. package/bin/lean/orchestrate.mjs +116 -28
  79. package/bin/lean/phaseledger.mjs +47 -5
  80. package/bin/lean/phaseledger.test.mjs +30 -1
  81. package/bin/lean/postdeploy-check.test.mjs +39 -0
  82. package/bin/lean/precheck.mjs +23 -4
  83. package/bin/lean/precheck.test.mjs +14 -1
  84. package/bin/lean/prereq.mjs +28 -0
  85. package/bin/lean/prereq.test.mjs +20 -0
  86. package/bin/lean/probe.mjs +4 -2
  87. package/bin/lean/prodparity.mjs +52 -0
  88. package/bin/lean/prodparity.test.mjs +67 -0
  89. package/bin/lean/prompts.mjs +77 -19
  90. package/bin/lean/quota.mjs +39 -0
  91. package/bin/lean/recovery.test.mjs +11 -1
  92. package/bin/lean/relaxation.mjs +73 -0
  93. package/bin/lean/relaxation.test.mjs +54 -0
  94. package/bin/lean/release-io.test.mjs +42 -0
  95. package/bin/lean/release-postmerge.mjs +125 -0
  96. package/bin/lean/release-preflight.mjs +58 -0
  97. package/bin/lean/release-preflight.test.mjs +114 -0
  98. package/bin/lean/release-rehearsal.mjs +64 -0
  99. package/bin/lean/release-rehearsal.test.mjs +93 -0
  100. package/bin/lean/release-review.e2e.test.mjs +77 -0
  101. package/bin/lean/release-review.mjs +254 -0
  102. package/bin/lean/release-review.test.mjs +307 -0
  103. package/bin/lean/release-snapshot.mjs +188 -0
  104. package/bin/lean/release-snapshot.test.mjs +190 -0
  105. package/bin/lean/release.mjs +296 -0
  106. package/bin/lean/release.test.mjs +387 -0
  107. package/bin/lean/render.mjs +1 -1
  108. package/bin/lean/replan.mjs +184 -0
  109. package/bin/lean/replan.test.mjs +110 -0
  110. package/bin/lean/resume.mjs +9 -7
  111. package/bin/lean/resume.test.mjs +16 -0
  112. package/bin/lean/rotator.mjs +150 -31
  113. package/bin/lean/rotator.test.mjs +105 -2
  114. package/bin/lean/sandbox-remote.mjs +9 -2
  115. package/bin/lean/schedd.mjs +83 -5
  116. package/bin/lean/schedd.test.mjs +108 -7
  117. package/bin/lean/selfreview.mjs +94 -0
  118. package/bin/lean/selfreview.test.mjs +58 -1
  119. package/bin/lean/selftest-gate.mjs +22 -0
  120. package/bin/lean/selftest-gate.test.mjs +18 -1
  121. package/bin/lean/selftest-journey.mjs +234 -0
  122. package/bin/lean/selftest-journey.test.mjs +130 -0
  123. package/bin/lean/selftest-live.mjs +2 -1
  124. package/bin/lean/seqlease.mjs +35 -1
  125. package/bin/lean/seqlease.test.mjs +15 -0
  126. package/bin/lean/seqreserve.e2e.test.mjs +135 -0
  127. package/bin/lean/seqreserve.mjs +73 -0
  128. package/bin/lean/seqreserve.test.mjs +134 -0
  129. package/bin/lean/sequence.mjs +35 -6
  130. package/bin/lean/seqversioned.mjs +147 -0
  131. package/bin/lean/stagestamp.mjs +28 -0
  132. package/bin/lean/stagestamp.test.mjs +32 -0
  133. package/bin/lean/surfaces.mjs +75 -0
  134. package/bin/lean/surfaces.test.mjs +59 -0
  135. package/bin/lean/toolplace.mjs +28 -0
  136. package/bin/lean/toolplace.test.mjs +24 -0
  137. package/bin/lean/toolstats.mjs +3 -1
  138. package/bin/lean/toolstats.test.mjs +11 -0
  139. package/bin/lean/validatebest.mjs +28 -0
  140. package/bin/lean/validatebest.test.mjs +27 -0
  141. package/bin/lean/verifier.mjs +3 -2
  142. package/bin/lean/verify.mjs +2 -1
  143. package/bin/lean/verify.test.mjs +6 -0
  144. package/bin/pool/agent.mjs +27 -4
  145. package/bin/pool/docker.mjs +5 -0
  146. package/bin/pool/router.mjs +74 -28
  147. package/bin/prereqs.mjs +111 -0
  148. package/bin/replay-timelapse.mjs +149 -0
  149. package/bin/review-staging.mjs +123 -16
  150. package/bin/review-staging.test.mjs +18 -0
  151. package/bin/runner.mjs +43 -6
  152. package/bin/splash-install.mjs +157 -0
  153. package/bin/stats/aggregate.mjs +8 -1
  154. package/bin/stats/conformance-outcomes.mjs +289 -0
  155. package/bin/stats/conformance-outcomes.test.mjs +274 -0
  156. package/bin/stats/depth.mjs +275 -0
  157. package/bin/stats/depth.test.mjs +158 -0
  158. package/bin/stats/efficiency.mjs +26 -5
  159. package/bin/stats/efficiency.test.mjs +45 -1
  160. package/bin/stats/experiment.mjs +7 -5
  161. package/bin/stats/first-review.mjs +77 -0
  162. package/bin/stats/first-review.test.mjs +36 -0
  163. package/bin/stats/firstmerge.mjs +40 -0
  164. package/bin/stats/firstmerge.test.mjs +41 -0
  165. package/bin/stats/github-source.mjs +53 -15
  166. package/bin/stats/index.mjs +147 -9
  167. package/bin/stats/local-source.mjs +12 -0
  168. package/bin/stats/origin.mjs +80 -0
  169. package/bin/stats/origin.test.mjs +58 -0
  170. package/bin/stats/query.mjs +69 -0
  171. package/bin/stats/render.mjs +3 -1
  172. package/bin/stats/scoreboard.mjs +137 -0
  173. package/bin/stats/scoreboard.test.mjs +87 -0
  174. package/bin/stats/selffiled.mjs +52 -0
  175. package/bin/stats/selffiled.test.mjs +71 -0
  176. package/bin/stats/stats.test.mjs +80 -0
  177. package/bin/tui.mjs +3 -2
  178. package/commands/bootstrap.md +15 -14
  179. package/commands/deploy-pr.md +18 -3
  180. package/commands/forge-stats.md +1 -1
  181. package/commands/forgedock-ci-setup.md +28 -0
  182. package/commands/forgedock-init.md +4 -5
  183. package/commands/issue.md +2 -0
  184. package/commands/milestone.md +9 -1
  185. package/commands/orchestrate.md +1 -1
  186. package/commands/replay.md +2 -0
  187. package/commands/review-pr-agents/security.md +4 -0
  188. package/commands/review-pr-staging.md +6 -1
  189. package/commands/work-on/build.md +4 -6
  190. package/commands/work-on/close.md +8 -0
  191. package/docs/CONFIG.md +170 -18
  192. package/docs/ISSUE-WATCH.md +25 -0
  193. package/docs/OUTCOME-CODES.md +4 -0
  194. package/docs/REPLAY.md +9 -0
  195. package/docs/SELFTEST.md +11 -0
  196. package/docs/STATS.md +61 -0
  197. package/docs/TELEMETRY.md +1 -1
  198. package/docs/eval/README.md +6 -0
  199. package/docs/eval/adversarial-bench.md +68 -0
  200. package/docs/eval/corpus/adversarial-v1.json +285 -0
  201. package/docs/eval/feature-bench.md +42 -0
  202. package/docs/eval/feature-specs/crud-auth/journeys/notes-crud-isolated.mjs +21 -0
  203. package/docs/eval/feature-specs/crud-auth/journeys/register-login.mjs +12 -0
  204. package/docs/eval/feature-specs/crud-auth/spec.md +15 -0
  205. package/docs/site/start-a-new-project.md +2 -1
  206. package/package.json +5 -2
  207. package/plugins/forgedock-splash/.claude-plugin/plugin.json +10 -0
  208. package/plugins/forgedock-splash/README.md +27 -0
  209. package/plugins/forgedock-splash/hooks/hooks.json +1 -0
  210. package/plugins/forgedock-splash/hooks/register.tsx +74 -0
  211. package/plugins/forgedock-splash/hooks/scene.ts +222 -0
  212. package/plugins/forgedock-splash/types/index.d.ts +10 -0
  213. package/pool/README.md +1 -1
  214. package/pool/image/cs-cred +14 -1
  215. package/scripts/backfill-finding-labels.mjs +50 -0
  216. package/scripts/backfill-finding-labels.test.mjs +36 -0
  217. package/scripts/bench-adversarial.mjs +216 -0
  218. package/scripts/bench-feature.mjs +170 -0
  219. package/scripts/bench-lightlane.mjs +2 -2
  220. package/scripts/bootstrap-create.mjs +2 -2
  221. package/scripts/bootstrap-validate.mjs +35 -2
  222. package/scripts/check-spec-size.sh +4 -3
  223. package/scripts/check-spec-size.test.sh +3 -0
  224. package/scripts/doctor-pipeline-state.sh +21 -6
  225. package/scripts/file-deferred-followups.sh +59 -251
  226. package/scripts/file-deferred-followups.test.sh +85 -206
  227. package/scripts/followup-route.mjs +12 -0
  228. package/scripts/owner-route-parity.test.sh +17 -1
  229. package/scripts/plan-validate-live.mjs +40 -6
  230. package/scripts/review-pr-side-effects.test.sh +40 -0
  231. package/scripts/review-pr-staging-scope.test.sh +1 -1
  232. package/scripts/review-staging-post.sh +23 -0
  233. package/scripts/review-staging-post.test.sh +8 -0
@@ -0,0 +1,158 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { test } from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import { mkdirSync, writeFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { tmpDir } from "../tests/_tmp.mjs";
8
+ import { INSUFFICIENT, buildDepth, depthReport, depthRows, gatherDefects, promotion, renderDepth } from "./depth.mjs";
9
+ import { parseArgs, HELP } from "./index.mjs";
10
+
11
+ const T0 = Date.parse("2026-10-01T00:00:00Z"), MIN = 60000, DAY = 86400000;
12
+ const iso = (ms) => new Date(ms).toISOString();
13
+
14
+ /** One synthetic RUN_START..RUN_TERMINAL slice. */
15
+ function slice({ issue = 1, repo = "o/r", at = T0, verdict = "eligible", reasons = [], signals = ["repro"], shape = "full", reason = "merged",
16
+ cost = 1, wall = 30 * MIN, model = 25 * MIN, size = "S", pr = 100 + issue, rework = false, conformance = [], verifier = 0, elig = true } = {}) {
17
+ const ev = [{ event: "RUN_START", issue, repo, ts: iso(at) }];
18
+ if (elig) ev.push({ event: "LIGHT_ELIGIBILITY", mode: "shadow", verdict, light: false, reasons: reasons.map((code) => ({ code, detail: "" })), signals: signals.map((code) => ({ code, detail: "" })) });
19
+ if (shape === "light") ev.push({ event: "LIGHT_DONE" });
20
+ if (shape === "upgraded") ev.push({ event: "LIGHT_UPGRADE", reasons: [] });
21
+ ev.push({ event: "PHASE_ATTEMPT_USAGE", phase: "implement", trigger: "build", cost_usd_delta: cost });
22
+ if (rework) ev.push({ event: "PHASE_ATTEMPT_USAGE", phase: "implement", trigger: "review", cost_usd: 0 });
23
+ for (const c of conformance) ev.push({ event: "CONFORMANCE", state: c.state, failures: c.failures });
24
+ if (verifier) ev.push({ event: "VERIFIER", findings: verifier });
25
+ ev.push({ event: "PR_OPENED", pr });
26
+ ev.push({ event: "RUN_TERMINAL", reason, ts: iso(at + wall), wall_ms: wall, model_ms: model, turns: { size } });
27
+ return ev;
28
+ }
29
+
30
+ test("depthRows: one row per slice with LIGHT_ELIGIBILITY and RUN_TERMINAL, filtered by repo and since", () => {
31
+ const ev = [...slice({ issue: 7, reasons: ["hotspot"], verdict: "ineligible", rework: true, conformance: [{ state: "fails", failures: [1, 2] }], verifier: 3 }),
32
+ ...slice({ issue: 7, elig: false }), ...slice({ issue: 7, at: T0 + DAY, shape: "light", reason: "needs-human", repo: "O/R" })];
33
+ const rows = depthRows(ev, { repo: "o/r" });
34
+ assert.equal(rows.length, 2);
35
+ const [a, b] = rows;
36
+ assert.deepEqual([a.issue, a.verdict, a.reasons, a.signals, a.shape, a.merged, a.firstPass, a.cost, a.findings, a.conformanceFailures, a.size, a.pr],
37
+ [7, "ineligible", ["hotspot"], ["repro"], "full", true, false, 1, 5, 1, "S", 107]);
38
+ assert.deepEqual([b.shape, b.needsHuman, b.merged, b.firstPass], ["light", true, false, true]);
39
+ assert.equal(depthRows(ev, { repo: "x/y" }).length, 0);
40
+ assert.equal(depthRows(ev, { sinceMs: T0 + DAY / 2 }).length, 1);
41
+ });
42
+
43
+ const rowsOf = (...slices) => slices.flatMap((s) => depthRows(slice(s)));
44
+
45
+ test("depthReport: verdict cells carry merge, first-pass, needs-human, median cost, wall, findings and defect rate", () => {
46
+ const rows = rowsOf({ issue: 1, cost: 1 }, { issue: 2, cost: 3, rework: true, verifier: 2 }, { issue: 3, cost: 2, reason: "needs-human" },
47
+ { issue: 4, verdict: "ineligible", reasons: ["size"], signals: ["size_M"] });
48
+ const defects = new Map([[1, { defect: true }], [2, { defect: false }]]);
49
+ const rep = depthReport({ rows, defects, minN: 1 });
50
+ const e = rep.by_verdict.eligible;
51
+ assert.deepEqual([e.n, e.merge_rate, e.needs_human_rate, e.median_cost_usd, e.median_wall_min, e.median_wall_over_model, e.findings_per_lane, e.share_with_findings, e.defect_rate, e.defects_n],
52
+ [3, 0.6667, 0.3333, 2, 30, 1.2, 0.67, 0.3333, 0.5, 2]);
53
+ assert.equal(e.first_pass_rate, 0.6667);
54
+ assert.equal(rep.by_verdict.ambiguous.n, 0);
55
+ assert.equal(rep.by_verdict.ineligible.n, 1);
56
+ assert.deepEqual(Object.keys(rep.by_code), ["repro", "size", "size_M"]);
57
+ assert.equal(rep.by_code.repro.n, 3);
58
+ assert.equal(rep.by_code.size.n, 1);
59
+ });
60
+
61
+ test("promotion: met, not met and insufficient data below min-n, with n per cell", () => {
62
+ const light = (i, o = {}) => ({ issue: i, shape: "light", cost: 1, wall: 12 * MIN, model: 10 * MIN, ...o });
63
+ const full = (i, o = {}) => ({ issue: 100 + i, cost: 1, ...o });
64
+ const rows = rowsOf(light(1), light(2), full(1), full(2), full(3, { size: "L" }));
65
+ const p = promotion(rows, new Map([[1, { defect: false }], [2, { defect: false }], [101, { defect: false }], [102, { defect: true }]]), 2);
66
+ assert.deepEqual(p.sizes, ["S"]);
67
+ assert.deepEqual([p.n_treatment, p.n_control], [2, 2], "size L control excluded");
68
+ assert.deepEqual([p.checks.cost.value, p.checks.cost.met, p.checks.cost.n_treatment, p.checks.cost.n_control], [1, true, 2, 2]);
69
+ assert.deepEqual([p.checks.wall.value, p.checks.wall.met], [1.2, true]);
70
+ assert.deepEqual([p.checks.defects.value, p.checks.defects.limit, p.checks.defects.met], [0, 0.5, true]);
71
+ assert.equal(p.met, true);
72
+ assert.match(p.note, /config decision/);
73
+ const costly = promotion(rowsOf(light(1, { cost: 5 }), light(2, { cost: 5 }), full(1), full(2)), new Map(), 2);
74
+ assert.equal(costly.checks.cost.met, false);
75
+ assert.equal(costly.checks.defects.verdict, INSUFFICIENT);
76
+ assert.equal(costly.met, false);
77
+ const few = promotion(rows, new Map(), 10);
78
+ assert.deepEqual([few.met, few.checks.cost.verdict, few.checks.cost.met, few.checks.wall.verdict], [INSUFFICIENT, INSUFFICIENT, null, INSUFFICIENT]);
79
+ });
80
+
81
+ const fakeGh = (o = {}) => async (args) => {
82
+ const path = args.find((x) => /^(search|repos)\//.test(x)) ?? "";
83
+ if (o.fail) throw new Error("gh down");
84
+ const ev = /issues\/(\d+)\/events/.exec(path);
85
+ if (ev) return ev[1] === "2" ? JSON.stringify({ issue: 2, ts: iso(T0 + 2 * DAY) }) : "";
86
+ if (path.startsWith("search/issues")) return [
87
+ { number: 300, title: "Revert \"feat: x (#101)\"", body: "", labels: [], merged_at: iso(T0 + DAY) },
88
+ { number: 301, title: "fix: y", body: "", labels: [], merged_at: iso(T0 + 2 * DAY) },
89
+ { number: 302, title: "fix: late", body: "", labels: [], merged_at: iso(T0 + 30 * DAY) },
90
+ { number: 303, title: "fix: rewrite z", body: "", labels: [], merged_at: iso(T0 + 2 * DAY) },
91
+ { number: 304, title: "fix: regression from #105", body: "", labels: [], merged_at: iso(T0 + 3 * DAY) },
92
+ ].map((x) => JSON.stringify(x)).join("\n");
93
+ const m = /pulls\/(\d+)$/.exec(path);
94
+ return m ? `sha${m[1]}` : "";
95
+ };
96
+ // Local git: fix PR 303 rewrites lines of PR 104; every other fix PR (301 touches a shared file) rewrites someone else's lines.
97
+ const fakeGit = { oldRanges: (sha) => [{ file: "src/shared.js", start: 1, end: 5 }], blame: (rev) => (rev === "sha303^" ? ["sha104"] : ["sha999"]) };
98
+
99
+ test("depth defect: unrelated fix on a shared file is not a defect, one rewriting the lane's lines is", async () => {
100
+ const rows = rowsOf({ issue: 3 }, { issue: 4 });
101
+ const d = await gatherDefects({ repo: "o/r", gh: fakeGh(), rows, git: fakeGit });
102
+ assert.deepEqual(d.get(3), { reopen: false, revert: false, cited: false, same_hunks: false, defect: false }, "fix 301/303 touch the shared file but not this PR's lines; 302 is out of window");
103
+ assert.deepEqual(d.get(4), { reopen: false, revert: false, cited: false, same_hunks: true, defect: true });
104
+ });
105
+
106
+ test("gatherDefects: reverted, reopened, cited and same_hunks; no git is n/a unless another signal; gh failure is null, never false", async () => {
107
+ const rows = rowsOf({ issue: 1 }, { issue: 2 }, { issue: 3 }, { issue: 5 });
108
+ const d = await gatherDefects({ repo: "o/r", gh: fakeGh(), rows, git: fakeGit });
109
+ assert.deepEqual(d.get(1), { reopen: false, revert: true, cited: false, same_hunks: false, defect: true });
110
+ assert.deepEqual(d.get(2), { reopen: true, revert: false, cited: false, same_hunks: false, defect: true });
111
+ assert.deepEqual(d.get(5), { reopen: false, revert: false, cited: true, same_hunks: false, defect: true });
112
+ const nogit = await gatherDefects({ repo: "o/r", gh: fakeGh(), rows });
113
+ assert.deepEqual(nogit.get(3), { reopen: false, revert: false, cited: false, same_hunks: null, defect: null }, "unresolved same_hunks is n/a, not a defect");
114
+ assert.equal(nogit.get(1).defect, true, "another signal still decides");
115
+ const rep = depthReport({ rows, defects: nogit, minN: 1 });
116
+ assert.equal(rep.defects_unresolved, 1);
117
+ assert.match(renderDepth(rep), /1 unresolved/);
118
+ const bad = await gatherDefects({ repo: "o/r", gh: fakeGh({ fail: true }), rows, git: fakeGit });
119
+ assert.deepEqual(bad.get(1), { reopen: null, revert: null, cited: null, same_hunks: null, defect: null });
120
+ assert.equal(depthReport({ rows, defects: bad, minN: 1 }).by_verdict.eligible.defect_rate, null);
121
+ });
122
+
123
+ test("gatherDefects (#5318): per-issue events, windowed search, a warm cache makes zero gh calls, progress is reported", async () => {
124
+ const dir = tmpDir("depth-cache-");
125
+ const env = { FORGE_STATS_CACHE_DIR: join(dir, "cache") };
126
+ const rows = rowsOf({ issue: 1 }, { issue: 2 }, { issue: 3 });
127
+ const now = T0 + 60 * DAY, git = fakeGit;
128
+ const calls = [];
129
+ const gh = async (args) => { calls.push(args[2]); return fakeGh()(args); };
130
+ const prog = [];
131
+ const cold = await gatherDefects({ repo: "o/r", gh, rows, now, env, useCache: true, git, onProgress: (p) => prog.push(p) });
132
+ assert.equal(cold.get(2).reopen, true);
133
+ assert.ok(!calls.some((c) => c.includes("/issues/events")), "no repo-wide events crawl");
134
+ assert.ok(calls.some((c) => /merged%3A\d{4}-\d{2}-\d{2}\.\./.test(c)), "search bounded to the merge window");
135
+ assert.equal(prog.at(-1).done, 3);
136
+ const n = calls.length;
137
+ const warm = await gatherDefects({ repo: "o/r", gh, rows, now, env, useCache: true, git });
138
+ assert.equal(calls.length, n, "warm run makes no gh calls");
139
+ assert.deepEqual([...warm], [...cold]);
140
+ await gatherDefects({ repo: "o/r", gh, rows, now, env, useCache: true, refresh: true, git });
141
+ assert.ok(calls.length > n, "--refresh re-reads");
142
+ const fresh = calls.length;
143
+ await gatherDefects({ repo: "o/r", gh, rows, now: T0 + DAY, env, useCache: true, git });
144
+ assert.ok(calls.length > fresh, "a row inside its window is never served from the cache");
145
+ });
146
+
147
+ test("depthReport recommendation: decision, eligible share, would-be saving and defect rate; rendered", () => {
148
+ const rows = rowsOf({ issue: 1, shape: "light", cost: 0.5 }, { issue: 2, cost: 2 }, { issue: 3, cost: 2 }, { issue: 4, verdict: "ineligible" });
149
+ const rep = depthReport({ rows, defects: new Map([[2, { defect: true }], [3, { defect: false }]]), minN: 1 });
150
+ const rc = rep.recommendation;
151
+ assert.equal(rc.eligible_n, 3);
152
+ assert.equal(rc.eligible_share, 0.75);
153
+ assert.equal(rc.would_be_saving_usd, 3, "2 eligible full lanes x (2 - 0.5)");
154
+ assert.equal(rc.eligible_defect_rate, 0.5);
155
+ assert.ok(["promote", "do not promote", INSUFFICIENT].includes(rc.decision));
156
+ assert.match(renderDepth(rep), /^recommendation: .*eligible share 75% \(n=3\), would-be saving \$3\.00/m);
157
+ assert.equal(depthReport({ rows: [], minN: 10 }).recommendation.decision, INSUFFICIENT);
158
+ });
@@ -17,6 +17,7 @@ import { join } from "node:path";
17
17
  import { citesFileLine } from "../lean/fixround.mjs";
18
18
  import { laneSize, SIZES } from "../lean/budget.mjs";
19
19
  import { probeResultOf } from "../lean/probe.mjs";
20
+ import { summarizeWaits } from "../lean/phaseledger.mjs";
20
21
  import { listBatches } from "../lean/batch.mjs";
21
22
  import { isTrustedComment } from "../engine/phases.mjs";
22
23
  import { noComments } from "../lean/render.mjs";
@@ -76,10 +77,10 @@ export function issueSlices(events) {
76
77
  else if (e.event === "LIGHT_UPGRADE") cur.shape = "upgraded";
77
78
  if (e.event === "PHASE_ATTEMPT_USAGE") {
78
79
  cur.attempts.push({ phase: e.phase ?? "other", trigger: e.trigger ?? null, restart_of: e.restart_of ?? null, model: e.model ?? null,
79
- turns: num(e.turns), cacheRead: num(e.usage?.cache_read_input_tokens), cost: costOf(e), durationMs: num(e.duration_ms), // #4491
80
+ turns: num(e.turns), cacheRead: num(e.usage?.cache_read_input_tokens), cost: costOf(e), durationMs: num(e.duration_ms), baseline: num(e.baseline_tokens), profile: typeof e.lane_profile === "string" ? e.lane_profile : null, // #4491, #5348
80
81
  ...(e.tools && typeof e.tools === "object" ? { calls: num(e.tools.calls), toolTurns: num(e.tools.turns), rereads: num(e.tools.rereads) } : {}) }); // #4410
81
82
  } else if (e.event === "RUN_TERMINAL") {
82
- cur.terminal = { reason: e.reason ?? null, code: e.code ?? null, ts: e.ts ?? null, size: SIZES.includes(e.turns?.size) ? e.turns.size : null };
83
+ cur.terminal = { reason: e.reason ?? null, code: e.code ?? null, ts: e.ts ?? null, size: SIZES.includes(e.turns?.size) ? e.turns.size : null, phases: e.phases && typeof e.phases === "object" ? e.phases : null };
83
84
  }
84
85
  }
85
86
  return out;
@@ -167,6 +168,10 @@ export function efficiencyMetrics({ entries = [], logs = new Map(), issues = nul
167
168
  for (const s of inScope(row, settleAt)) { const g = shapes[s.shape] ?? shapes.full; g.n++; g.cost_usd += sum(s.attempts.map((a) => a.cost)); }
168
169
  }
169
170
  for (const g of Object.values(shapes)) g.cost_usd = r(g.cost_usd, 1e6);
171
+ // #5348: first-turn baseline_tokens per session profile (full, memory-off, lane, narrow) over every attempt of every lane
172
+ const profiles = {};
173
+ for (const { row, settleAt } of entries) for (const s of inScope(row, settleAt)) for (const a of s.attempts) if (a.baseline != null) (profiles[a.profile ?? "unknown"] ??= []).push(a.baseline);
174
+ const baselineByProfile = Object.fromEntries(Object.entries(profiles).map(([k, xs]) => [k, { sessions: xs.length, median: median(xs) }]));
170
175
  const lanes = { ...shapes, upgrade_rate: r(per(shapes.upgraded.n, shapes.light.n + shapes.upgraded.n)) };
171
176
  for (const { row, settleAt } of entries) {
172
177
  if (row?.outcome !== "merged") continue;
@@ -179,7 +184,7 @@ export function efficiencyMetrics({ entries = [], logs = new Map(), issues = nul
179
184
  const term = [...slices].reverse().find((s) => s.terminal?.reason === "merged")?.terminal;
180
185
  merged.push({ issue: row.issue, slices: slices.length, cost: sum(atts.map((a) => a.cost)), implCost: sum(impl.map((a) => a.cost)),
181
186
  reviewCost: sum(atts.filter((a) => a.phase === "review").map((a) => a.cost)), implTurns: sum(impl.map((a) => a.turns)), implCache: sum(impl.map((a) => a.cacheRead)),
182
- size: term?.size ?? laneSize({ labels: info?.labels ?? [] }) ?? "unknown", impl, retries, info, tools: laneTools(impl), shape: slices.at(-1)?.shape ?? null, implWall: laneWall(impl) });
187
+ size: term?.size ?? laneSize({ labels: info?.labels ?? [] }) ?? "unknown", impl, retries, info, tools: laneTools(impl), shape: slices.at(-1)?.shape ?? null, implWall: laneWall(impl), phases: term?.phases ?? null });
183
188
  }
184
189
  const all = group(merged);
185
190
  const bySize = {};
@@ -231,8 +236,8 @@ export function efficiencyMetrics({ entries = [], logs = new Map(), issues = nul
231
236
  retries: { total, per_merge: r(per(total, merged.length), 100), by_cause: retries, lane_reruns: sum(merged.map((m) => Math.max(0, m.slices - 1))) },
232
237
  no_action: { lanes: sum(Object.values(noAction).map((g) => g.n)), cost_usd: r(sum(Object.values(noAction).map((g) => g.cost_usd)), 1e6),
233
238
  by_kind: Object.fromEntries(Object.entries(noAction).map(([k, g]) => [k, { ...g, cost_usd: r(g.cost_usd, 1e6) }])) },
234
- quality, acceptance, lanes,
235
- tool_calls_per_turn_p50: median(withTools.map((m) => m.tools.per_turn)), rereads_per_merge: withTools.length ? r(per(sum(withTools.map((m) => m.tools.rereads)), withTools.length), 100) : null,
239
+ quality, acceptance, lanes, baseline_by_profile: baselineByProfile, wait: summarizeWaits(merged.map((m) => m.phases)), // #5349: non-model time by phase and cause
240
+ tool_calls_per_turn_p50: median(withTools.map((m) => m.tools.per_turn)), tool_calls_per_turn_n: withTools.length, rereads_per_merge: withTools.length ? r(per(sum(withTools.map((m) => m.tools.rereads)), withTools.length), 100) : null,
236
241
  per_issue: merged.map((m) => ({ issue: m.issue, slices: m.slices, cost_usd: r(m.cost, 1e6), implement_usd: r(m.implCost, 1e6), implement_turns: m.implTurns,
237
242
  implement_cache_read: m.implCache, size: m.size, retries: m.retries, ...(m.shape ? { shape: m.shape } : {}), ...(m.info ? { quality: issueQuality(m.info.body).tag } : {}),
238
243
  ...(m.tools ? { implement_tool_calls_per_turn: m.tools.per_turn, implement_rereads: m.tools.rereads } : {}),
@@ -380,6 +385,9 @@ const int = (x) => (num(x) == null ? "n/a" : String(Math.round(x)));
380
385
  const g1 = (g) => `n=${g.n} ${usd(g.usd_per_merge)}/merge turns/merge ${f(g.turns_per_merge, 1)} context/turn ${int(g.context_per_turn)}`;
381
386
 
382
387
  /** The report lines of one scope (the batch report prints them unlabelled). */
388
+ /** #5347: a median of tool calls per turn under this means builders are back to one call per turn. */
389
+ export const CALLS_PER_TURN_ALERT = 1.5;
390
+
383
391
  export function formatEfficiencyLines(m, label = "") {
384
392
  const lines = [`efficiency${label ? ` (${label})` : ""}: merged ${m.merged}, ${usd(m.usd_per_merge)}/merge (implement ${usd(m.implement_usd)}, review ${usd(m.review_usd)}), turns/merge ${f(m.turns_per_merge, 1)}, context/turn ${int(m.context_per_turn)}`];
385
393
  const sizes = Object.entries(m.by_size ?? {});
@@ -397,13 +405,26 @@ export function formatEfficiencyLines(m, label = "") {
397
405
  : "acceptance (7d after promotion): n/a");
398
406
  if (a) lines.push(`unprobed merged issues (no acceptance probe declared): ${a.unprobed_issues?.length ? a.unprobed_issues.map((n) => `#${n}`).join(", ") : "none"}`); // #4908
399
407
  lines.push(`tools: calls/turn p50 ${f(m.tool_calls_per_turn_p50)}, re-reads (>=3x same path)/merge ${f(m.rereads_per_merge)}`); // #4410
408
+ if (num(m.tool_calls_per_turn_p50) != null && m.tool_calls_per_turn_p50 < CALLS_PER_TURN_ALERT && (m.tool_calls_per_turn_n ?? 0) >= 3) lines.push(`ALERT: calls/turn p50 ${f(m.tool_calls_per_turn_p50)} is below ${CALLS_PER_TURN_ALERT}: builders are not batching independent reads (#5347)`);
400
409
  const ln = m.lanes; // #4452
401
410
  lines.push(ln ? `lanes: ${LANE_SHAPES.map((k) => `${k} ${ln[k]?.n ?? 0} (${usd(ln[k]?.cost_usd ?? 0)})`).join(", ")}; upgrade rate ${ln.upgrade_rate == null ? "n/a"
402
411
  : `${Math.round(ln.upgrade_rate * 100)}% (${ln.upgraded?.n ?? 0}/${(ln.light?.n ?? 0) + (ln.upgraded?.n ?? 0)})`}` : "lanes: n/a");
403
412
  lines.push(rates(m)); // #4491
413
+ const bp = Object.entries(m.baseline_by_profile ?? {}); // #5348
414
+ lines.push(`baseline tokens by profile: ${bp.length ? bp.map(([k, g]) => `${k} n=${g.sessions} median ${int(g.median)}`).join("; ") : "n/a"}`);
415
+ lines.push(...waitLines(m.wait)); // #5349
404
416
  return lines;
405
417
  }
406
418
 
419
+ /** #5349: where the non-model time of merged lanes went, by phase and cause; n/a when no merged lane carries a wait breakdown. */
420
+ function waitLines(w) {
421
+ if (!w?.n) return ["wait (non-model time): n/a"];
422
+ const mins = (ms) => `${(ms / 60000).toFixed(1)}m`, causes = (c) => Object.entries(c).map(([k, v]) => `${k} ${mins(v)}`).join(", ") || "none";
423
+ const waiting = Math.max(0, w.total.ms - w.total.model_ms);
424
+ return [`wait (non-model time, ${w.n} merged lane${w.n === 1 ? "" : "s"}): ${mins(waiting)} of ${mins(w.total.ms)} wall (${w.total.ms > 0 ? Math.round((waiting / w.total.ms) * 100) : 0}%); ${causes(w.total.wait)}`,
425
+ ...Object.entries(w.phases).map(([id, g]) => ` wait ${id}: ${mins(Math.max(0, g.ms - g.model_ms))} of ${mins(g.ms)} (${causes(g.wait)}${Object.keys(g.pct ?? {}).length ? `; p50/p90 ${Object.entries(g.pct).map(([k, q]) => `${k} ${mins(q.p50)}/${mins(q.p90)}`).join(", ")}` : ""})`)];
426
+ }
427
+
407
428
  const pct = (x) => (num(x) == null ? "n/a" : `${Math.round(x * 100)}%`);
408
429
  const rates = (m) => `implement wall p50 ${m.implement_wall_p50_min == null ? "n/a" : `${f(m.implement_wall_p50_min, 1)} min`}, merge rate ${pct(m.merge_rate)}, conformance pass ${pct(m.conformance_pass_rate)}`;
409
430
  const sign = (x, d, unit = "") => (num(x) == null ? "n/a" : `${x > 0 ? "+" : ""}${x.toFixed(d)}${unit}`);
@@ -119,8 +119,10 @@ describe("#4402 efficiencyMetrics", () => {
119
119
  });
120
120
  it("renders n/a, never NaN, for an empty cohort", () => {
121
121
  const lines = formatEfficiencyLines(efficiencyMetrics({}));
122
- assert.equal(lines.length, 10);
122
+ assert.equal(lines.length, 12);
123
123
  assert.equal(lines[9], "implement wall p50 n/a, merge rate n/a, conformance pass n/a"); // #4491, appended
124
+ assert.equal(lines[10], "baseline tokens by profile: n/a"); // #5348
125
+ assert.equal(lines[11], "wait (non-model time): n/a"); // #5349
124
126
  assert.ok(!lines.some((l) => /NaN|undefined/.test(l)), lines.join("\n"));
125
127
  assert.match(lines[0], /^efficiency: merged 0, n\/a\/merge/);
126
128
  assert.equal(lines[6], "acceptance (7d after promotion): n/a");
@@ -366,3 +368,45 @@ describe("#4491 before/after compare", () => {
366
368
  assert.match(text, /^issue quality: n\/a \(no gh\/repo\)$/m);
367
369
  });
368
370
  });
371
+
372
+ describe("#5347 calls/turn alert", () => {
373
+ const lines = (p50, n) => formatEfficiencyLines({ ...efficiencyMetrics({}), tool_calls_per_turn_p50: p50, tool_calls_per_turn_n: n });
374
+ it("fires below the threshold with enough samples; silent above it, with few samples or no data", () => {
375
+ assert.ok(lines(1.03, 5).some((l) => /^ALERT: calls\/turn p50 1\.03/.test(l)));
376
+ assert.ok(!lines(2.1, 5).some((l) => l.startsWith("ALERT")));
377
+ assert.ok(!lines(1.03, 1).some((l) => l.startsWith("ALERT")));
378
+ assert.ok(!lines(null, 0).some((l) => l.startsWith("ALERT")));
379
+ });
380
+ });
381
+
382
+ describe("#5348 baseline tokens per session profile", () => {
383
+ const ev = (o) => ({ event: "PHASE_ATTEMPT_USAGE", phase: "implement", ...o });
384
+ const logs = new Map([[1, [{ event: "RUN_START", ts: "2026-10-01T00:00:00Z" },
385
+ ev({ trigger: "build", baseline_tokens: 30000, lane_profile: "lane" }), ev({ trigger: "enumerating", baseline_tokens: 9000, lane_profile: "narrow" }),
386
+ ev({ trigger: "duplicate", baseline_tokens: 11000, lane_profile: "narrow" }), ev({ trigger: "ci_red" }),
387
+ { event: "RUN_TERMINAL", reason: "merged", code: "completed" }]]]);
388
+ const m = efficiencyMetrics({ entries: [{ row: { issue: 1, outcome: "merged" }, settleAt: null }], logs, repo: "o/r", now: Date.parse("2026-10-02T00:00:00Z") });
389
+ it("reports sessions and median baseline per lane_profile; attempts without a baseline are skipped", () => {
390
+ assert.deepEqual(m.baseline_by_profile, { lane: { sessions: 1, median: 30000 }, narrow: { sessions: 2, median: 10000 } });
391
+ assert.equal(formatEfficiencyLines(m).find((l) => l.startsWith("baseline tokens")), "baseline tokens by profile: lane n=1 median 30000; narrow n=2 median 10000");
392
+ });
393
+ });
394
+
395
+ describe("#5349 wait attribution in the efficiency report", () => {
396
+ const phases = { plan: { ms: 600000, model_ms: 200000, wait: { heavy_queue: 100000, command: 300000 } }, implement: { ms: 300000, model_ms: 300000 } };
397
+ const logs = new Map([[1, [start("2026-10-22T10:00:00Z"), term("merged", null, { phases })]], [2, [start("2026-10-22T11:00:00Z"), term("merged", null)]]]);
398
+ const row = (issue) => ({ row: { issue, outcome: "merged" }, settleAt: null });
399
+ it("sums non-model time by phase and cause over merged lanes that carry a breakdown", () => {
400
+ const m = efficiencyMetrics({ entries: [row(1), row(2)], logs });
401
+ assert.equal(m.wait.n, 1);
402
+ assert.deepEqual(m.wait.phases.plan.wait, { heavy_queue: 100000, command: 300000 });
403
+ const out = formatEfficiencyLines(m).filter((l) => /wait/.test(l));
404
+ assert.match(out[0], /wait \(non-model time, 1 merged lane\): 6\.7m of 15\.0m wall \(44%\); heavy_queue 1\.7m, command 5\.0m/);
405
+ assert.match(out[1], /wait plan: 6\.7m of 10\.0m \(heavy_queue 1\.7m, command 5\.0m; p50\/p90 heavy_queue 1\.7m\/1\.7m/);
406
+ });
407
+ it("reports n/a for runs recorded before the breakdown existed", () => {
408
+ const m = efficiencyMetrics({ entries: [row(2)], logs });
409
+ assert.equal(m.wait.n, 0);
410
+ assert.ok(formatEfficiencyLines(m).includes("wait (non-model time): n/a"));
411
+ });
412
+ });
@@ -3,10 +3,11 @@
3
3
  /**
4
4
  * forge#4629: `forgedock stats --experiment <id>`. Finished runs tagged with the experiment id, grouped by arm; each metric
5
5
  * is null below the declared min n (release.mjs rule), a target is null when a value it needs is null, never a pass.
6
+ * forge#5206: `applied` per arm counts runs whose recorded arm_overrides match the arm's declared ones (a mismatch: the toggle did not apply).
6
7
  */
7
8
  import { aggregate } from "./aggregate.mjs";
8
9
  import { releaseMetrics } from "./release.mjs";
9
- import { benchRecord } from "../experiment.mjs";
10
+ import { benchRecord, overridesText } from "../experiment.mjs";
10
11
 
11
12
  const isNum = (x) => typeof x === "number" && Number.isFinite(x);
12
13
 
@@ -26,7 +27,8 @@ export function experimentReport(runs, exp) {
26
27
  const g = aggregate({ runs: rs }, { minN: exp.minN }).groups[0];
27
28
  const m = g ? releaseMetrics([g], { minN: exp.minN }).versions[0] : null;
28
29
  byArm[arm] = Object.fromEntries(exp.metrics.map((k) => [k, m?.[k] ?? null]));
29
- arms[arm] = { n: rs.length, ...byArm[arm] };
30
+ const expected = overridesText(exp.overrides?.[arm]) || "none";
31
+ arms[arm] = { n: rs.length, applied: rs.filter((r) => r.armOverrides === expected).length, ...byArm[arm] };
30
32
  }
31
33
  const targets = Object.fromEntries(exp.targets.map((t) => [t.text, evalTarget(t, byArm)]));
32
34
  const verdicts = Object.values(targets);
@@ -36,9 +38,9 @@ export function experimentReport(runs, exp) {
36
38
 
37
39
  const fmt = (v) => (v == null ? "n/a" : Number.isInteger(v) ? String(v) : v.toFixed(2));
38
40
  export function renderExperiment(r) {
39
- const keys = Object.keys(Object.values(r.arms)[0] ?? {}).filter((k) => k !== "n");
41
+ const keys = Object.keys(Object.values(r.arms)[0] ?? {}).filter((k) => k !== "n" && k !== "applied");
40
42
  const line = (c) => `| ${c.join(" | ")} |`;
41
- const rows = Object.entries(r.arms).map(([a, v]) => line([a, String(v.n), ...keys.map((k) => fmt(v[k]))]));
43
+ const rows = Object.entries(r.arms).map(([a, v]) => line([a, String(v.n), `${v.applied ?? 0}/${v.n}`, ...keys.map((k) => fmt(v[k]))]));
42
44
  const tg = Object.entries(r.targets).map(([t, v]) => `${t}: ${v.pass == null ? "n/a" : v.pass ? "met" : "missed"} (${fmt(v.value)} vs ${fmt(v.limit)})`);
43
- return [`Experiment ${r.id} (min n ${r.minN}; n/a below it)`, line(["arm", "n", ...keys]), line(["---", "---", ...keys.map(() => "---")]), ...rows, ...tg, `targets met: ${r.targets_met}`].join("\n");
45
+ return [`Experiment ${r.id} (min n ${r.minN}; n/a below it)`, line(["arm", "n", "applied", ...keys]), line(["---", "---", "---", ...keys.map(() => "---")]), ...rows, ...tg, `targets met: ${r.targets_met}`].join("\n");
44
46
  }
@@ -0,0 +1,77 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * forgedock stats --first-review (#5345): the clean-first-review rate. Each finished lane's `run_terminal` record carries
5
+ * `first_review` ({state, kinds, rounds, clean, incomplete, type, surfaces}, bin/lean/selfreview.mjs firstReviewRecord).
6
+ * Reports the rate and the review.incomplete share overall and per repo, change type and risk surface, the first-round
7
+ * finding kinds with the contract section each traces to, and the cells with a long clean record as light-lane
8
+ * candidates. Candidacy is report-only; a lane touching a risk surface (domain:*, risk:*) is never a candidate (#5283).
9
+ */
10
+ import { sectionOfKind } from "../lean/selfreview.mjs";
11
+
12
+ export const DEFAULT_FIRST_REVIEW_MIN_N = 20;
13
+ export const DEFAULT_CLEAN_STREAK = 20;
14
+ export const TARGET_CLEAN_RATE = 0.85;
15
+ export const TARGET_INCOMPLETE_RATE = 0.02;
16
+
17
+ const rate = (k, n) => (n ? Math.round((k / n) * 1000) / 1000 : null);
18
+ const isRisk = (surfaces) => surfaces.length > 0;
19
+
20
+ /** The first-round record of a run_terminal: the nested object, or the scalar `fr_*` fields the telemetry seam writes. */
21
+ function frOf(r) {
22
+ if (r?.first_review && typeof r.first_review === "object") return r.first_review;
23
+ if (r?.fr_state == null && r?.fr_clean == null) return null;
24
+ const list = (v) => (typeof v === "string" && v !== "none" ? v.split(",").filter(Boolean) : []);
25
+ return { state: r.fr_state, kinds: list(r.fr_kinds), rounds: r.fr_rounds, clean: Number(r.fr_clean) === 1, incomplete: Number(r.fr_incomplete) === 1, type: r.fr_type, surfaces: list(r.fr_surfaces) };
26
+ }
27
+
28
+ /** The latest first_review per issue (later run_terminal wins), oldest first. */
29
+ export function firstReviewLanes(records = [], repo = null) {
30
+ const byIssue = new Map();
31
+ for (const r of records) {
32
+ const f = r?.event === "run_terminal" ? frOf(r) : null;
33
+ if (!f || typeof f !== "object" || r.issue == null) continue;
34
+ const cur = byIssue.get(r.issue);
35
+ if (!cur || String(r.ts ?? "") >= String(cur.ts ?? "")) byIssue.set(r.issue, { issue: r.issue, ts: String(r.ts ?? ""), repo: r.repo ?? repo, merged: r.reason === "merged", state: f.state, kinds: Array.isArray(f.kinds) ? f.kinds : [], rounds: Number(f.rounds) || 1, clean: f.clean === true, incomplete: f.incomplete === true, type: f.type ?? "other", surfaces: Array.isArray(f.surfaces) ? f.surfaces : [] });
36
+ }
37
+ return [...byIssue.values()].sort((a, b) => a.ts.localeCompare(b.ts) || a.issue - b.issue);
38
+ }
39
+
40
+ function cellOf(lanes, { streak, minN }) {
41
+ const n = lanes.length, clean = lanes.filter((l) => l.clean).length, incomplete = lanes.filter((l) => l.incomplete).length;
42
+ const tail = lanes.slice(-streak);
43
+ const safe = lanes.filter((l) => !isRisk(l.surfaces));
44
+ const run = safe.slice(-streak);
45
+ return { n, clean, clean_rate: rate(clean, n), incomplete, incomplete_rate: rate(incomplete, n), enough: n >= minN,
46
+ light_candidate: safe.length === n && n >= minN && tail.length >= streak && tail.every((l) => l.clean) && run.length >= streak };
47
+ }
48
+
49
+ export function firstReviewReport({ records = [], repo = null, minN = DEFAULT_FIRST_REVIEW_MIN_N, streak = DEFAULT_CLEAN_STREAK } = {}) {
50
+ const lanes = firstReviewLanes(records, repo);
51
+ const opt = { streak, minN };
52
+ const group = (keys) => {
53
+ const m = new Map();
54
+ for (const l of lanes) for (const k of keys(l)) { if (!m.has(k)) m.set(k, []); m.get(k).push(l); }
55
+ return Object.fromEntries([...m.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => [k, cellOf(v, opt)]));
56
+ };
57
+ const kinds = {}, sections = {};
58
+ for (const l of lanes) for (const k of l.kinds) { kinds[k] = (kinds[k] ?? 0) + 1; const s = sectionOfKind(k); sections[s] = (sections[s] ?? 0) + 1; }
59
+ const overall = cellOf(lanes, opt);
60
+ const norm = (c) => ({ ...c, light_candidate: false }); // risk surfaces always keep the full independent review
61
+ const bySurface = Object.fromEntries(Object.entries(group((l) => (l.surfaces.length ? l.surfaces : ["none"]))).map(([k, c]) => [k, k === "none" ? c : norm(c)]));
62
+ return { repo, lanes: lanes.length, overall: { ...overall, light_candidate: false }, targets: { clean_rate: TARGET_CLEAN_RATE, incomplete_rate: TARGET_INCOMPLETE_RATE },
63
+ met: overall.n ? overall.clean_rate >= TARGET_CLEAN_RATE && overall.incomplete_rate <= TARGET_INCOMPLETE_RATE : null,
64
+ by_repo: group((l) => [l.repo ?? "unknown"]), by_type: group((l) => [l.type]), by_surface: bySurface,
65
+ first_round_kinds: kinds, finding_sections: sections, rounds: { one: lanes.filter((l) => l.rounds <= 1).length, two: lanes.filter((l) => l.rounds === 2).length, more: lanes.filter((l) => l.rounds > 2).length } };
66
+ }
67
+
68
+ const pct = (x) => (x == null ? "n/a" : `${(x * 100).toFixed(1)}%`);
69
+ export function renderFirstReview(r) {
70
+ if (!r.lanes) return `clean-first-review, ${r.repo ?? "?"}: no lanes with a first_review record yet (recorded by lanes on a release that carries #5345)`;
71
+ const o = r.overall, line = (k, c) => ` ${k.padEnd(28)} n=${String(c.n).padStart(4)} clean ${pct(c.clean_rate).padStart(6)} incomplete ${pct(c.incomplete_rate).padStart(6)}${c.light_candidate ? " light-lane candidate" : ""}`;
72
+ const out = [`clean-first-review, ${r.repo ?? "?"}: ${pct(o.clean_rate)} of ${o.n} lanes (target >= ${pct(r.targets.clean_rate)}), review.incomplete ${pct(o.incomplete_rate)} (target <= ${pct(r.targets.incomplete_rate)}): ${r.met ? "met" : "not met"}`,
73
+ `rounds: one ${r.rounds.one}, two ${r.rounds.two}, three or more ${r.rounds.more}`];
74
+ for (const [title, cells] of [["by repo", r.by_repo], ["by change type", r.by_type], ["by risk surface (always full review)", r.by_surface]]) out.push(title, ...Object.entries(cells).map(([k, c]) => line(k, c)));
75
+ out.push("first-round finding kinds", ...Object.entries(r.first_round_kinds).sort((a, b) => b[1] - a[1]).map(([k, n]) => ` ${k.padEnd(34)} ${n} (contract section: ${sectionOfKind(k)})`));
76
+ return out.join("\n");
77
+ }
@@ -0,0 +1,36 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { describe, it } from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import { firstReviewReport, firstReviewLanes, renderFirstReview } from "./first-review.mjs";
6
+
7
+ const rec = (issue, o = {}) => ({ event: "run_terminal", issue, ts: `2026-01-${String(issue % 28 + 1).padStart(2, "0")}`, repo: "o/r", reason: "merged", first_review: { state: "conforms", kinds: [], rounds: 1, clean: true, incomplete: false, type: "bug", surfaces: [], ...o } });
8
+
9
+ describe("stats --first-review (#5345)", () => {
10
+ it("reports rate, incomplete share, splits and first-round kinds with their contract section", () => {
11
+ const records = [rec(1), rec(2), rec(3, { clean: false, state: "fails", kinds: ["conformance.omission"], rounds: 2 }), rec(4, { clean: false, incomplete: true, state: "review.incomplete", type: "feature" })];
12
+ const r = firstReviewReport({ records, repo: "o/r", minN: 2 });
13
+ assert.equal(r.lanes, 4);
14
+ assert.equal(r.overall.clean_rate, 0.5);
15
+ assert.equal(r.overall.incomplete_rate, 0.25);
16
+ assert.equal(r.met, false);
17
+ assert.equal(r.by_type.bug.n, 3);
18
+ assert.equal(r.by_repo["o/r"].n, 4);
19
+ assert.equal(r.first_round_kinds["conformance.omission"], 1);
20
+ assert.equal(r.finding_sections.requirements, 1);
21
+ assert.match(renderFirstReview(r), /contract section: requirements/);
22
+ });
23
+ it("keeps the latest record per issue and ignores lanes without first_review", () => {
24
+ assert.equal(firstReviewLanes([rec(1), { event: "run_terminal", issue: 2 }, { ...rec(1, { clean: false }), ts: "2027-01-01" }]).length, 1);
25
+ assert.match(renderFirstReview(firstReviewReport({ records: [] })), /no lanes/);
26
+ });
27
+ it("a long clean streak is a light-lane candidate, but a risk surface never is", () => {
28
+ const safe = Array.from({ length: 5 }, (_, i) => rec(i + 1));
29
+ assert.equal(firstReviewReport({ records: safe, minN: 3, streak: 3 }).by_type.bug.light_candidate, true);
30
+ const risky = Array.from({ length: 5 }, (_, i) => rec(i + 1, { surfaces: ["risk:auth"] }));
31
+ const r = firstReviewReport({ records: risky, minN: 3, streak: 3 });
32
+ assert.equal(r.by_type.bug.light_candidate, false);
33
+ assert.equal(r.by_surface["risk:auth"].light_candidate, false);
34
+ assert.equal(r.overall.light_candidate, false);
35
+ });
36
+ });
@@ -0,0 +1,40 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * forgedock stats --first-merge (#5290): time from setup start to the first merged PR on a first-run repo.
5
+ * Start = the FORGE:FIRST_RUN marker in the issues `forgedock first-run` filed (earliest wins); merge = the earliest
6
+ * mergedAt among the PRs that closed those issues. GitHub is the register: no local state is read.
7
+ */
8
+ import { parseFirstRunMarker } from "../first-run.mjs";
9
+
10
+ const median = (xs) => { if (!xs.length) return null; const s = [...xs].sort((a, b) => a - b), m = s.length >> 1; return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2; };
11
+
12
+ /** issues: [{number, body, closedByPullRequestsReferences: [{mergedAt}]}] -> {repo, started, merged, minutes, median_minutes, target_minutes, met}. */
13
+ export function firstMergeReport({ issues, repo = null }) {
14
+ const marked = (issues ?? []).map((i) => ({ i, m: parseFirstRunMarker(i?.body) })).filter((x) => x.m);
15
+ if (!marked.length) return { repo, started: null, merged: null, minutes: null, median_minutes: null, target_minutes: 15, met: null, issues: 0 };
16
+ const started = Math.min(...marked.map((x) => Date.parse(x.m.started)));
17
+ const merges = marked.flatMap(({ i }) => (i.closedByPullRequestsReferences ?? []).map((p) => Date.parse(p?.mergedAt)).filter(Number.isFinite));
18
+ const merged = merges.length ? Math.min(...merges) : null;
19
+ const minutes = merged == null ? null : Math.max(0, (merged - started) / 60000);
20
+ return { repo, started: new Date(started).toISOString(), merged: merged == null ? null : new Date(merged).toISOString(), minutes, median_minutes: minutes, target_minutes: 15, met: minutes == null ? null : minutes <= 15, issues: marked.length };
21
+ }
22
+
23
+ /** Median over several repos' reports (those with a merge). */
24
+ export const medianMinutes = (reports) => median(reports.map((r) => r.minutes).filter((x) => x != null));
25
+
26
+ /** gh: async (args) => stdout. Unreadable output throws (never a silent "no data"). */
27
+ export async function gatherFirstRunIssues({ gh, repo }) {
28
+ const out = await gh(["issue", "list", "-R", repo, "--state", "all", "--search", "FORGE:FIRST_RUN in:body", "--limit", "100", "--json", "number,body,closedByPullRequestsReferences"]);
29
+ let issues;
30
+ try { issues = JSON.parse(String(out ?? "")); } catch { throw new Error(`first-merge: unreadable gh issue list output for ${repo}`); }
31
+ if (!Array.isArray(issues)) throw new Error(`first-merge: gh issue list for ${repo} did not return a list`);
32
+ return issues;
33
+ }
34
+
35
+ export function renderFirstMerge(r) {
36
+ if (r.repos) return `${r.repos.map(renderFirstMerge).join("\n")}\nmedian time to first merged PR over ${r.repos.length} repos: ${r.median_minutes == null ? "n/a" : `${r.median_minutes.toFixed(1)} min (target <= ${r.target_minutes}: ${r.met ? "met" : "not met"})`}`;
37
+ if (!r.started) return `time to first merged PR, ${r.repo ?? "?"}: no first-run issues found (run: npx forgedock first-run)`;
38
+ if (r.minutes == null) return `time to first merged PR, ${r.repo ?? "?"}: not merged yet (setup started ${r.started}, ${r.issues} first-run issue${r.issues === 1 ? "" : "s"})`;
39
+ return `time to first merged PR, ${r.repo ?? "?"}: ${r.minutes.toFixed(1)} min (target <= ${r.target_minutes}: ${r.met ? "met" : "not met"}); setup ${r.started}, merged ${r.merged}`;
40
+ }
@@ -0,0 +1,41 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { describe, it } from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import { firstMergeReport, medianMinutes, gatherFirstRunIssues, renderFirstMerge } from "./firstmerge.mjs";
6
+ import { parseArgs, buildReport } from "./index.mjs";
7
+ import { markerLine } from "../first-run.mjs";
8
+
9
+ const T0 = Date.UTC(2026, 10, 1, 10, 0, 0);
10
+ const iss = (n, startedMs, merges) => ({ number: n, body: `x\n${markerLine(startedMs)}`, closedByPullRequestsReferences: merges.map((m) => ({ mergedAt: new Date(m).toISOString() })) });
11
+
12
+ describe("stats --first-merge (#5290)", () => {
13
+ it("measures earliest start to earliest merge", () => {
14
+ const r = firstMergeReport({ repo: "o/r", issues: [iss(1, T0, [T0 + 12 * 60000]), iss(2, T0 + 60000, [T0 + 9 * 60000]), { number: 3, body: "plain" }] });
15
+ assert.equal(r.minutes, 9);
16
+ assert.equal(r.met, true);
17
+ assert.equal(r.issues, 2);
18
+ });
19
+ it("is not met over 15 minutes and null when unmerged or absent", () => {
20
+ assert.equal(firstMergeReport({ issues: [iss(1, T0, [T0 + 20 * 60000])] }).met, false);
21
+ assert.equal(firstMergeReport({ issues: [iss(1, T0, [])] }).minutes, null);
22
+ assert.equal(firstMergeReport({ issues: [] }).started, null);
23
+ });
24
+ it("takes the median across repos", () => {
25
+ assert.equal(medianMinutes([{ minutes: 5 }, { minutes: 20 }, { minutes: 9 }, { minutes: null }]), 9);
26
+ });
27
+ it("buildReport reads GitHub only and rejects unreadable output", async () => {
28
+ assert.equal(parseArgs(["--first-merge"]).firstMerge, true);
29
+ const rep = await buildReport({ firstMerge: true, repo: "o/r" }, { gh: async () => JSON.stringify([iss(1, T0, [T0 + 600000])]) });
30
+ assert.equal(rep.query.first_merge.minutes, 10);
31
+ assert.match(renderFirstMerge(rep.query.first_merge), /10\.0 min.*met/);
32
+ await assert.rejects(gatherFirstRunIssues({ gh: async () => "oops", repo: "o/r" }), /unreadable/);
33
+ });
34
+ it("--repo a,b reports the median across repos", async () => {
35
+ const by = { "o/a": [iss(1, T0, [T0 + 5 * 60000])], "o/b": [iss(1, T0, [T0 + 25 * 60000])], "o/c": [iss(1, T0, [T0 + 9 * 60000])] };
36
+ const gh = async (a) => JSON.stringify(by[a[a.indexOf("-R") + 1]]);
37
+ const rep = await buildReport({ firstMerge: true, repo: "o/a,o/b,o/c" }, { gh });
38
+ assert.equal(rep.query.first_merge.median_minutes, 9);
39
+ assert.match(renderFirstMerge(rep.query.first_merge), /median time to first merged PR over 3 repos: 9\.0 min/);
40
+ });
41
+ });