forgedock 1.52.0 → 1.53.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 (93) hide show
  1. package/bin/engine/outcome-codes.mjs +3 -0
  2. package/bin/engine/telemetry-seam.mjs +4 -2
  3. package/bin/engine-cli.mjs +53 -16
  4. package/bin/experiment.mjs +58 -6
  5. package/bin/forge-utils.mjs +6 -2
  6. package/bin/forgedock.mjs +15 -1
  7. package/bin/lean/account-watch.mjs +28 -0
  8. package/bin/lean/account-watch.test.mjs +30 -0
  9. package/bin/lean/activation.mjs +20 -0
  10. package/bin/lean/activation.test.mjs +14 -1
  11. package/bin/lean/basered.mjs +115 -0
  12. package/bin/lean/basered.test.mjs +66 -0
  13. package/bin/lean/batch-health.mjs +40 -6
  14. package/bin/lean/batch-health.test.mjs +34 -1
  15. package/bin/lean/batch.mjs +41 -2
  16. package/bin/lean/batch.test.mjs +104 -2
  17. package/bin/lean/checkpoint-reconcile.mjs +43 -0
  18. package/bin/lean/checkpoint-reconcile.test.mjs +95 -0
  19. package/bin/lean/conformance.e2e.test.mjs +1 -1
  20. package/bin/lean/conformance.mjs +195 -22
  21. package/bin/lean/conformance.test.mjs +152 -5
  22. package/bin/lean/effects.mjs +8 -4
  23. package/bin/lean/execution.mjs +19 -3
  24. package/bin/lean/execution.test.mjs +39 -0
  25. package/bin/lean/findinglabel.mjs +16 -0
  26. package/bin/lean/findinglabel.test.mjs +39 -0
  27. package/bin/lean/issuewatch-release.mjs +6 -2
  28. package/bin/lean/issuewatch-release.test.mjs +16 -0
  29. package/bin/lean/issuewatch.mjs +11 -1
  30. package/bin/lean/lanelock.mjs +14 -0
  31. package/bin/lean/lean.mjs +165 -34
  32. package/bin/lean/lean.test.mjs +289 -9
  33. package/bin/lean/light.mjs +48 -7
  34. package/bin/lean/light.test.mjs +37 -3
  35. package/bin/lean/limits.test.mjs +142 -9
  36. package/bin/lean/orchestrate-cancel.test.mjs +143 -0
  37. package/bin/lean/orchestrate.mjs +96 -26
  38. package/bin/lean/postdeploy-check.test.mjs +39 -0
  39. package/bin/lean/prompts.mjs +8 -7
  40. package/bin/lean/quota.mjs +39 -0
  41. package/bin/lean/recovery.test.mjs +10 -0
  42. package/bin/lean/relaxation.mjs +73 -0
  43. package/bin/lean/relaxation.test.mjs +54 -0
  44. package/bin/lean/release-postmerge.mjs +119 -0
  45. package/bin/lean/release-rehearsal.mjs +63 -0
  46. package/bin/lean/release-rehearsal.test.mjs +93 -0
  47. package/bin/lean/release-review.e2e.test.mjs +77 -0
  48. package/bin/lean/release-review.mjs +198 -0
  49. package/bin/lean/release-review.test.mjs +180 -0
  50. package/bin/lean/release.mjs +228 -0
  51. package/bin/lean/release.test.mjs +292 -0
  52. package/bin/lean/rotator.mjs +150 -31
  53. package/bin/lean/rotator.test.mjs +105 -2
  54. package/bin/lean/sandbox-remote.mjs +9 -2
  55. package/bin/lean/schedd.mjs +49 -4
  56. package/bin/lean/schedd.test.mjs +87 -6
  57. package/bin/lean/verifier.mjs +3 -2
  58. package/bin/lean/verify.mjs +2 -1
  59. package/bin/lean/verify.test.mjs +6 -0
  60. package/bin/pool/agent.mjs +18 -4
  61. package/bin/pool/router.mjs +66 -24
  62. package/bin/review-staging.mjs +23 -0
  63. package/bin/stats/conformance-outcomes.mjs +208 -0
  64. package/bin/stats/conformance-outcomes.test.mjs +188 -0
  65. package/bin/stats/depth.mjs +218 -0
  66. package/bin/stats/depth.test.mjs +133 -0
  67. package/bin/stats/experiment.mjs +7 -5
  68. package/bin/stats/github-source.mjs +2 -2
  69. package/bin/stats/index.mjs +64 -2
  70. package/bin/stats/local-source.mjs +11 -0
  71. package/bin/stats/query.mjs +69 -0
  72. package/bin/stats/selffiled.mjs +52 -0
  73. package/bin/stats/selffiled.test.mjs +71 -0
  74. package/commands/orchestrate.md +1 -1
  75. package/commands/review-pr-agents/security.md +4 -0
  76. package/commands/review-pr-staging.md +2 -0
  77. package/commands/work-on/build.md +4 -6
  78. package/docs/CONFIG.md +65 -8
  79. package/docs/ISSUE-WATCH.md +2 -0
  80. package/docs/OUTCOME-CODES.md +3 -0
  81. package/docs/STATS.md +44 -0
  82. package/docs/TELEMETRY.md +1 -1
  83. package/package.json +1 -1
  84. package/pool/README.md +1 -1
  85. package/pool/image/cs-cred +14 -1
  86. package/scripts/backfill-finding-labels.mjs +50 -0
  87. package/scripts/backfill-finding-labels.test.mjs +36 -0
  88. package/scripts/doctor-pipeline-state.sh +21 -6
  89. package/scripts/file-deferred-followups.sh +59 -251
  90. package/scripts/file-deferred-followups.test.sh +85 -206
  91. package/scripts/followup-route.mjs +12 -0
  92. package/scripts/owner-route-parity.test.sh +17 -1
  93. package/scripts/review-pr-side-effects.test.sh +40 -0
@@ -0,0 +1,208 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #5210: `forgedock stats --conformance-outcomes`: do conformance blocks predict post-merge defects?
5
+ * Each merged lane PR (a merged PR with a conformance verdict, query.mjs conformanceVerdicts) is joined to four post-merge
6
+ * defect signals inside `windowDays` of its merge:
7
+ * reverted a later merged PR titled `Revert ...` that names the PR (`Reverts o/r#N`, `#N`) or its title
8
+ * reopened a closing issue of the PR reopened after the merge
9
+ * cited a later merged PR whose title or body cites the PR or its issue as the cause ("fix ... #N", "review-finding ... #N")
10
+ * same_hunks a later fix PR whose old-side lines git-blame to this PR's merge commit (local git, compounding.mjs gitProbes;
11
+ * null when git cannot resolve, e.g. the cwd is not a clone of the repo)
12
+ * It prints, per repo and per failure kind, the defect rate of nonconforming-merged versus conforming-merged lane PRs with n
13
+ * and a Wilson 95% interval; a cell under min n prints n/a. Read only: GitHub reads are one GraphQL search per page of 100
14
+ * merged PRs, no writes. The report core is pure; `gatherConformanceOutcomes` supplies the GitHub and git inputs.
15
+ */
16
+ export const DEFAULT_OUTCOME_MIN_N = 20;
17
+ export const DEFAULT_WINDOW_DAYS = 7;
18
+ export const DEFAULT_LOOKBACK_DAYS = 30;
19
+ export const PAGE_SIZE = 100;
20
+ export const SIGNALS = ["reverted", "reopened", "cited", "same_hunks"];
21
+ export const OUTCOME_INSUFFICIENT = "insufficient data";
22
+ export const HIGHER = "nonconforming merges show a higher defect rate";
23
+ export const NOT_HIGHER = "no higher defect rate shown for nonconforming merges";
24
+ const DAY = 86400000;
25
+ const ms = (ts) => { const t = Date.parse(ts ?? ""); return Number.isFinite(t) ? t : null; };
26
+ const r4 = (x) => Math.round(x * 1e4) / 1e4;
27
+ const esc = (s) => String(s).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
28
+
29
+ /** Wilson score interval [low, high] for k successes of n (z = 1.96, 95%); null when n is 0. */
30
+ export function wilson(k, n, z = 1.96) {
31
+ if (!n) return null;
32
+ const p = k / n, z2 = z * z, d = 1 + z2 / n;
33
+ const c = (p + z2 / (2 * n)) / d, h = (z * Math.sqrt((p * (1 - p)) / n + z2 / (4 * n * n))) / d;
34
+ return [r4(Math.max(0, c - h)), r4(Math.min(1, c + h))];
35
+ }
36
+
37
+ /** One 2x2 cell: n, defects, rate and interval; rate and interval are null (insufficient) under minN. */
38
+ export function cell(rows, minN) {
39
+ const n = rows.length, defects = rows.filter((r) => r.defect).length;
40
+ const insufficient = n < minN;
41
+ return { n, defects, rate: insufficient || !n ? null : r4(defects / n), interval: insufficient ? null : wilson(defects, n), insufficient };
42
+ }
43
+
44
+ /** "higher" when the nonconforming interval lies wholly above the conforming one; "insufficient data" when a cell is under min n. */
45
+ export function conclude(nonconforming, conforming) {
46
+ if (nonconforming.insufficient || conforming.insufficient || !nonconforming.interval || !conforming.interval) return OUTCOME_INSUFFICIENT;
47
+ return nonconforming.interval[0] > conforming.interval[1] ? HIGHER : NOT_HIGHER;
48
+ }
49
+
50
+ function twoByTwo(rows, minN) {
51
+ const nonconforming = cell(rows.filter((r) => r.state === "nonconforming"), minN), conforming = cell(rows.filter((r) => r.state === "conforms"), minN);
52
+ return { nonconforming, conforming, conclusion: conclude(nonconforming, conforming) };
53
+ }
54
+
55
+ /** Numbers that identify `p` as a cause: the PR and its closing issues. */
56
+ const refsOf = (p) => [p.number, ...(p.closingIssues ?? []).map((i) => i.number)].filter((x) => Number.isSafeInteger(x));
57
+ const text = (q) => `${q.title ?? ""}\n${q.body ?? ""}`;
58
+ const isRevert = (q) => /^revert\b/i.test(q.title ?? "");
59
+ const isFix = (q) => /^(fix|hotfix|bugfix)\b/i.test(q.title ?? "") || /^revert\b/i.test(q.title ?? "");
60
+
61
+ /** True when a later PR `q` reverts `p`. */
62
+ export function reverts(q, p, repo) {
63
+ if (!isRevert(q)) return false;
64
+ const t = text(q);
65
+ if (repo && new RegExp(`Reverts\\s+${esc(repo)}#${p.number}\\b`, "i").test(t)) return true;
66
+ if (new RegExp(`(^|[^\\w/])#${p.number}\\b`).test(t)) return true;
67
+ return Boolean(p.title) && (q.title ?? "").includes(`"${p.title}"`);
68
+ }
69
+
70
+ /** True when a later PR `q` cites `p` (or its issue) as the cause: "fix ... #N" or "review-finding ... #N" on one line. */
71
+ export function cites(q, p) {
72
+ if (isRevert(q)) return false;
73
+ for (const n of refsOf(p)) {
74
+ const re = new RegExp(`(\\bfix(e[sd])?\\b|review[- ]finding)[^\\n]*?(^|[^\\w/])#${n}\\b`, "im");
75
+ if (re.test(text(q))) return true;
76
+ }
77
+ return false;
78
+ }
79
+
80
+ /**
81
+ * Same-hunks: a later fix PR whose old-side lines blame to `p`'s merge commit. true on a hit, false when every later fix PR
82
+ * resolved without one (or there is none), null when git is missing or a needed probe could not resolve.
83
+ */
84
+ export function sameHunks(p, laterFixes, git) {
85
+ if (!laterFixes.length) return false;
86
+ if (!git || !p.mergeSha) return null;
87
+ let unresolved = false;
88
+ for (const q of laterFixes) {
89
+ const ranges = q.mergeSha ? git.oldRanges(q.mergeSha) : null;
90
+ if (!ranges) { unresolved = true; continue; }
91
+ for (const r of ranges) {
92
+ const shas = git.blame(`${q.mergeSha}^`, r.file, r.start, r.end);
93
+ if (shas == null) { unresolved = true; continue; }
94
+ if (shas.includes(p.mergeSha)) return true;
95
+ }
96
+ }
97
+ return unresolved ? null : false;
98
+ }
99
+
100
+ /**
101
+ * The report core (pure). prs: merged PRs [{repo, number, title, body, mergedAt, mergeSha, closingIssues: [{number, reopenedAt: [ts]}]}];
102
+ * verdicts: Map from conformanceVerdicts (keys pr:N, issue:N). A PR whose window has not elapsed by `now` is pending and left
103
+ * out of the cells. A PR with no verdict is not a lane PR.
104
+ */
105
+ export function conformanceOutcomes({ prs = [], verdicts = new Map(), minN = DEFAULT_OUTCOME_MIN_N, windowDays = DEFAULT_WINDOW_DAYS, now = Date.now(), git = null, graphqlCalls = null, since = null }) {
106
+ const win = windowDays * DAY;
107
+ const merged = prs.filter((p) => ms(p.mergedAt) != null).sort((a, b) => ms(a.mergedAt) - ms(b.mergedAt));
108
+ const sinceMs = ms(since);
109
+ const rows = [];
110
+ let unjoined = 0, pending = 0, unresolved = 0;
111
+ for (const p of merged) {
112
+ const t = ms(p.mergedAt);
113
+ if (sinceMs != null && t < sinceMs) continue;
114
+ const v = verdicts.get(`pr:${p.number}`) ?? refsOf(p).slice(1).map((i) => verdicts.get(`issue:${i}`)).find(Boolean) ?? null;
115
+ if (!v) { unjoined++; continue; }
116
+ if (t + win > now) { pending++; continue; }
117
+ const later = merged.filter((q) => q !== p && q.number !== p.number && (p.repo == null || q.repo == null || q.repo === p.repo) && ms(q.mergedAt) > t && ms(q.mergedAt) <= t + win);
118
+ const signals = {
119
+ reverted: later.some((q) => reverts(q, p, p.repo)),
120
+ reopened: (p.closingIssues ?? []).some((i) => (i.reopenedAt ?? []).some((ts) => ms(ts) > t && ms(ts) <= t + win)),
121
+ cited: later.some((q) => cites(q, p)),
122
+ same_hunks: sameHunks(p, later.filter(isFix), git),
123
+ };
124
+ if (signals.same_hunks === null) unresolved++;
125
+ rows.push({ repo: p.repo ?? null, pr: p.number, issue: v.issue ?? null, merged_at: p.mergedAt, mode: v.mode ?? null, state: v.state, kinds: v.kinds ?? [],
126
+ source: v.source ?? null, signals, defect: SIGNALS.some((s) => signals[s] === true) });
127
+ }
128
+ const repos = {};
129
+ for (const repo of [...new Set(rows.map((r) => r.repo ?? "unknown"))].sort()) {
130
+ const rs = rows.filter((r) => (r.repo ?? "unknown") === repo);
131
+ const kinds = [...new Set(rs.flatMap((r) => (r.state === "nonconforming" ? r.kinds : [])))].sort();
132
+ const confRows = rs.filter((r) => r.state === "conforms");
133
+ const by_kind = {};
134
+ for (const k of kinds) {
135
+ const nonconforming = cell(rs.filter((r) => r.state === "nonconforming" && r.kinds.includes(k)), minN), conforming = cell(confRows, minN);
136
+ by_kind[k] = { nonconforming, conforming, conclusion: conclude(nonconforming, conforming) };
137
+ }
138
+ const by_mode = {};
139
+ for (const m of [...new Set(rs.map((r) => r.mode ?? "unknown"))].sort()) by_mode[m] = twoByTwo(rs.filter((r) => (r.mode ?? "unknown") === m), minN);
140
+ repos[repo] = { overall: twoByTwo(rs, minN), by_kind, by_mode };
141
+ }
142
+ const overall = twoByTwo(rows, minN);
143
+ return {
144
+ window_days: windowDays, min_n: minN, since: since ?? null,
145
+ sources: { merged_prs: merged.length, lane_prs: rows.length, pending, unjoined, same_hunks_unresolved: unresolved, git: Boolean(git), graphql_calls: graphqlCalls },
146
+ repos, overall, conclusion: overall.conclusion, prs: rows,
147
+ };
148
+ }
149
+
150
+ const pct = (x) => (x == null ? "n/a" : `${Math.round(x * 1000) / 10}%`);
151
+ const fmtCell = (c) => `${c.defects}/${c.n} ${pct(c.rate)}${c.interval ? ` [${pct(c.interval[0])}, ${pct(c.interval[1])}]` : ""}`;
152
+ const row = (label, x) => `| ${label} | ${fmtCell(x.nonconforming)} | ${fmtCell(x.conforming)} | ${x.conclusion} |`;
153
+ const HEAD = ["| group | nonconforming-merged defects/n rate [95% CI] | conforming-merged defects/n rate [95% CI] | verdict |", "|---|---|---|---|"];
154
+
155
+ export function renderConformanceOutcomes(r) {
156
+ const s = r.sources;
157
+ const out = [`conformance outcomes: ${s.lane_prs} lane PRs of ${s.merged_prs} merged (${s.unjoined} without a verdict, ${s.pending} with an open ${r.window_days}d window), min n ${r.min_n}`
158
+ + `, same-hunks ${s.git ? `${s.same_hunks_unresolved} unresolved` : "n/a (no local clone of the repo)"}${s.graphql_calls != null ? `, ${s.graphql_calls} GraphQL call(s)` : ""}`];
159
+ for (const [repo, x] of Object.entries(r.repos)) {
160
+ out.push("", `## ${repo}`, "", ...HEAD, row("all", x.overall), ...Object.entries(x.by_mode).map(([m, y]) => row(`mode ${m}`, y)),
161
+ ...Object.entries(x.by_kind).map(([k, y]) => row(`kind ${k}`, y)));
162
+ }
163
+ if (!Object.keys(r.repos).length) out.push("", "no merged lane PR with an elapsed window");
164
+ out.push("", `conclusion: ${r.conclusion}`);
165
+ return out.join("\n");
166
+ }
167
+
168
+ const QUERY = `query($q: String!, $first: Int!, $after: String) {
169
+ search(type: ISSUE, query: $q, first: $first, after: $after) {
170
+ pageInfo { hasNextPage endCursor }
171
+ nodes { ... on PullRequest { number title body mergedAt mergeCommit { oid } repository { nameWithOwner }
172
+ closingIssuesReferences(first: 10) { nodes { number timelineItems(itemTypes: [REOPENED_EVENT], first: 10) { nodes { ... on ReopenedEvent { createdAt } } } } } } }
173
+ }
174
+ }`;
175
+
176
+ /** One GraphQL search page -> normalized PRs. */
177
+ export function prsOfPage(data, repo) {
178
+ return (data?.data?.search?.nodes ?? []).filter((n) => Number.isSafeInteger(n?.number) && n.mergedAt).map((n) => ({
179
+ repo: n.repository?.nameWithOwner ?? repo, number: n.number, title: n.title ?? "", body: n.body ?? "", mergedAt: n.mergedAt, mergeSha: n.mergeCommit?.oid ?? null,
180
+ closingIssues: (n.closingIssuesReferences?.nodes ?? []).filter((i) => Number.isSafeInteger(i?.number))
181
+ .map((i) => ({ number: i.number, reopenedAt: (i.timelineItems?.nodes ?? []).map((e) => e?.createdAt).filter(Boolean) })),
182
+ }));
183
+ }
184
+
185
+ /**
186
+ * Read-only GitHub input: merged PRs of `repo` since `since` (ISO; default DEFAULT_LOOKBACK_DAYS before now) up to now, so later
187
+ * reverts and fixes inside the window are in the candidate set. Exactly one `gh api graphql` search call per page of 100 PRs.
188
+ * GitHub search returns at most 1000 results: `capped` reports when that bound was hit.
189
+ */
190
+ export async function gatherConformanceOutcomes({ repo, gh, since = null, now = Date.now() }) {
191
+ const from = (since ? new Date(ms(since) ?? now - DEFAULT_LOOKBACK_DAYS * DAY) : new Date(now - DEFAULT_LOOKBACK_DAYS * DAY)).toISOString().slice(0, 10);
192
+ const q = `repo:${repo} is:pr is:merged merged:>=${from}`;
193
+ const prs = [];
194
+ let after = null, calls = 0, capped = false;
195
+ for (;;) {
196
+ const args = ["api", "graphql", "-f", `query=${QUERY}`, "-f", `q=${q}`, "-F", `first=${PAGE_SIZE}`, ...(after ? ["-f", `after=${after}`] : [])];
197
+ calls++;
198
+ const raw = await gh(args);
199
+ const data = JSON.parse(String(raw ?? "").trim() || "{}");
200
+ if (Array.isArray(data.errors) && data.errors.length && !data.data) throw new Error(`GraphQL: ${data.errors.map((e) => e?.message).join("; ")}`);
201
+ prs.push(...prsOfPage(data, repo));
202
+ const pi = data?.data?.search?.pageInfo;
203
+ if (!pi?.hasNextPage || !pi.endCursor) break;
204
+ if (prs.length >= 1000) { capped = true; break; }
205
+ after = pi.endCursor;
206
+ }
207
+ return { prs, graphqlCalls: calls, since: `${from}T00:00:00Z`, capped };
208
+ }
@@ -0,0 +1,188 @@
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 { conformanceOutcomes, gatherConformanceOutcomes, renderConformanceOutcomes, wilson, cites, reverts, sameHunks, OUTCOME_INSUFFICIENT, HIGHER, NOT_HIGHER, DEFAULT_OUTCOME_MIN_N } from "./conformance-outcomes.mjs";
6
+ import { conformanceVerdicts, verdictOf } from "./query.mjs";
7
+ import { summariseLog } from "./local-source.mjs";
8
+ import { buildReport, parseArgs, runStats } from "./index.mjs";
9
+
10
+ const DAY = 86400000;
11
+ const T0 = Date.parse("2026-10-01T00:00:00Z");
12
+ const at = (d) => new Date(T0 + d * DAY).toISOString();
13
+ const NOW = T0 + 60 * DAY;
14
+ const pr = (number, d, extra = {}) => ({ repo: "o/r", number, title: `feat: change ${number}`, body: "", mergedAt: at(d), mergeSha: `sha${number}`, closingIssues: [], ...extra });
15
+ const verdicts = (rows) => conformanceVerdicts({ records: rows.map(([prN, would, failures = [], mode = "shadow"]) => [
16
+ { event: "run_terminal", issue: prN + 1000, pr: prN, reason: "merged", conformance_mode: mode, ...(would ? { shadow_would: would } : {}), ts: at(0) },
17
+ ...(failures.length ? [{ event: "conformance_shadow", issue: prN + 1000, would, failures, ts: at(-0.1) }] : []),
18
+ ]).flat() });
19
+
20
+ describe("conformance outcomes: join (#5210 R1)", () => {
21
+ it("joins each merged lane PR to its last verdict, mode and the four signals inside the window only", () => {
22
+ const prs = [
23
+ pr(1, 0, { closingIssues: [{ number: 1001, reopenedAt: [at(3)] }] }), // reopened in window
24
+ pr(2, 0), pr(3, 0), pr(4, 0), pr(5, 0),
25
+ pr(6, 0, { closingIssues: [{ number: 1006, reopenedAt: [at(9)] }] }), // reopened outside the 7d window
26
+ pr(20, 1, { title: "Revert \"feat: change 2\"", body: "Reverts o/r#2" }),
27
+ pr(21, 2, { title: "fix: handle null", body: "Fixes a regression from #3" }),
28
+ pr(22, 3, { title: "chore: tidy", body: "review-finding of PR #4" }),
29
+ pr(23, 4, { title: "fix: loop bound", body: "unrelated" }), // same-hunks fix for #5 via git
30
+ pr(24, 12, { title: "fix: late", body: "fix for #6" }), // outside window
31
+ pr(25, 1, { title: "docs: mention #5", body: "" }), // a mention, not a cause
32
+ ];
33
+ const v = verdicts([[1, "conforms"], [2, "nonconforming", ["omission"]], [3, "conforms", [], "enforce"], [4, "nonconforming", ["scope_creep", "omission"]], [5, "conforms"], [6, "conforms"]]);
34
+ const git = { oldRanges: (sha) => (sha === "sha23" ? [{ file: "a.js", start: 1, end: 2 }] : []), blame: (rev, file) => (rev === "sha23^" && file === "a.js" ? ["sha5"] : []) };
35
+ const r = conformanceOutcomes({ prs, verdicts: v, now: NOW, git, minN: 1 });
36
+ const by = Object.fromEntries(r.prs.map((x) => [x.pr, x]));
37
+ assert.equal(r.sources.lane_prs, 6);
38
+ assert.equal(r.sources.unjoined, 6, "PRs without a verdict are not lane PRs");
39
+ assert.deepEqual(by[1].signals, { reverted: false, reopened: true, cited: false, same_hunks: false });
40
+ assert.equal(by[2].signals.reverted, true);
41
+ assert.deepEqual(by[2].kinds, ["omission"]);
42
+ assert.equal(by[3].signals.cited, true);
43
+ assert.equal(by[3].mode, "enforce");
44
+ assert.equal(by[4].signals.cited, true, "review-finding of PR #N");
45
+ assert.deepEqual(by[4].kinds, ["omission", "scope_creep"]);
46
+ assert.equal(by[5].signals.same_hunks, true);
47
+ assert.equal(by[5].signals.cited, false, "a docs mention is not a cause");
48
+ assert.deepEqual(by[6].signals, { reverted: false, reopened: false, cited: false, same_hunks: false }, "signals after the window do not count");
49
+ assert.equal(by[6].defect, false);
50
+ assert.equal(by[1].defect, true);
51
+ });
52
+
53
+ it("the latest verdict wins across batch rows, run logs and telemetry; a shadow run with no verdict has none", () => {
54
+ const v = conformanceVerdicts({
55
+ batchRows: [{ issue: 7, pr: 70, outcome: "merged", conformance: { mode: "shadow", would: "nonconforming", kinds: ["omission"] }, ts: "2026-10-01T00:00:00Z" }],
56
+ runs: [{ finished: true, issue: 7, pr: 70, reason: "merged", conformanceMode: "shadow", shadowWould: "conforms", conformanceFailures: [], endTs: "2026-10-02T00:00:00Z" }],
57
+ records: [{ event: "run_terminal", issue: 8, pr: 80, reason: "merged", conformance_mode: "shadow", ts: "2026-10-02T00:00:00Z" }],
58
+ });
59
+ assert.equal(v.get("pr:70").state, "conforms");
60
+ assert.equal(v.get("pr:70").source, "local");
61
+ assert.equal(v.get("pr:80"), undefined);
62
+ assert.deepEqual(verdictOf({ mode: "enforce", merged: true }), { mode: "enforce", state: "conforms", kinds: [] });
63
+ });
64
+
65
+ it("a PR whose window is still open is pending, not counted", () => {
66
+ const r = conformanceOutcomes({ prs: [pr(1, 58)], verdicts: verdicts([[1, "conforms"]]), now: NOW, minN: 1 });
67
+ assert.equal(r.sources.pending, 1);
68
+ assert.equal(r.sources.lane_prs, 0);
69
+ });
70
+
71
+ it("run logs expose pr, mode and the last verdict's failure codes", () => {
72
+ const s = summariseLog([{ event: "RUN_START", issue: 9, ts: at(0) }, { event: "CONFORMANCE", round: 1, state: "nonconforming", failures: ["regression"], mode: "shadow" },
73
+ { event: "CONFORMANCE_SHADOW", would: "nonconforming", failures: ["omission"] }, { event: "RUN_TERMINAL", reason: "merged", pr: 90, conformance_mode: "shadow", shadow_would: "nonconforming", ts: at(1) }]);
74
+ assert.equal(s.pr, 90);
75
+ assert.equal(s.conformanceMode, "shadow");
76
+ assert.deepEqual(s.conformanceFailures, ["omission"]);
77
+ });
78
+
79
+ it("signal helpers", () => {
80
+ assert.equal(reverts({ title: "Revert \"x\"", body: "Reverts o/r#12" }, { number: 12 }, "o/r"), true);
81
+ assert.equal(reverts({ title: "fix: x", body: "Reverts o/r#12" }, { number: 12 }, "o/r"), false);
82
+ assert.equal(cites({ title: "fix(x): y", body: "Closes #120" }, { number: 12, closingIssues: [] }), false, "#120 is not #12");
83
+ assert.equal(cites({ title: "fix(x): y (#12)", body: "" }, { number: 12, closingIssues: [] }), true);
84
+ assert.equal(sameHunks({ mergeSha: "a" }, [{ mergeSha: "b" }], null), null, "no git: unresolved");
85
+ assert.equal(sameHunks({ mergeSha: "a" }, [], null), false, "no later fix: false");
86
+ assert.equal(sameHunks({ mergeSha: "a" }, [{ mergeSha: "b" }], { oldRanges: () => null, blame: () => [] }), null);
87
+ });
88
+ });
89
+
90
+ describe("conformance outcomes: 2x2 and conclusion (#5210 R2)", () => {
91
+ const many = (start, n, would, defects, failures = []) => Array.from({ length: n }, (_, i) => {
92
+ const num = start + i;
93
+ return { p: pr(num, 0, i < defects ? { closingIssues: [{ number: num + 1000, reopenedAt: [at(1)] }] } : {}), v: [num, would, failures] };
94
+ });
95
+ it("defaults to min n 20 per cell and prints insufficient data below it", () => {
96
+ const xs = [...many(1, 19, "nonconforming", 10, ["omission"]), ...many(100, 30, "conforms", 1)];
97
+ const r = conformanceOutcomes({ prs: xs.map((x) => x.p), verdicts: verdicts(xs.map((x) => x.v)), now: NOW });
98
+ assert.equal(r.min_n, DEFAULT_OUTCOME_MIN_N);
99
+ assert.equal(r.min_n, 20);
100
+ assert.equal(r.overall.nonconforming.n, 19);
101
+ assert.equal(r.overall.nonconforming.rate, null);
102
+ assert.equal(r.overall.nonconforming.insufficient, true);
103
+ assert.equal(r.conclusion, OUTCOME_INSUFFICIENT);
104
+ const text = renderConformanceOutcomes(r);
105
+ assert.match(text, /\| all \| 10\/19 n\/a \|/);
106
+ assert.match(text.split("\n").at(-1), /^conclusion: insufficient data$/);
107
+ });
108
+ it("per repo, per mode and per failure kind with n, rate and a Wilson interval; higher when the intervals separate", () => {
109
+ const xs = [...many(1, 25, "nonconforming", 15, ["omission"]), ...many(30, 22, "nonconforming", 1, ["scope_creep"]), ...many(100, 40, "conforms", 2)];
110
+ const r = conformanceOutcomes({ prs: xs.map((x) => x.p), verdicts: verdicts(xs.map((x) => x.v)), now: NOW });
111
+ const o = r.repos["o/r"];
112
+ assert.deepEqual([o.by_kind.omission.nonconforming.n, o.by_kind.omission.nonconforming.defects, o.by_kind.omission.nonconforming.rate], [25, 15, 0.6]);
113
+ assert.deepEqual(o.by_kind.omission.nonconforming.interval, wilson(15, 25));
114
+ assert.equal(o.by_kind.omission.conclusion, HIGHER);
115
+ assert.equal(o.by_kind.scope_creep.conclusion, NOT_HIGHER);
116
+ assert.equal(o.overall.conforming.n, 40);
117
+ assert.ok(o.by_mode.shadow);
118
+ assert.equal(r.conclusion, HIGHER);
119
+ const text = renderConformanceOutcomes(r);
120
+ assert.match(text, /## o\/r/);
121
+ assert.match(text, /\| kind omission \| 15\/25 60% \[/);
122
+ assert.equal(text.split("\n").at(-1), `conclusion: ${HIGHER}`);
123
+ });
124
+ it("wilson matches the closed form and stays inside [0, 1]", () => {
125
+ assert.deepEqual(wilson(0, 10), [0, 0.2775]);
126
+ assert.deepEqual(wilson(10, 10), [0.7225, 1]);
127
+ assert.equal(wilson(0, 0), null);
128
+ });
129
+ });
130
+
131
+ /** gh stub: `api graphql` search pages over `total` merged PRs; records every call. */
132
+ function graphqlGh(total, calls = []) {
133
+ return async (args) => {
134
+ calls.push(args);
135
+ if (args[0] === "api" && args[1] === "graphql") {
136
+ const after = args.find((a) => a.startsWith("after="));
137
+ const start = after ? Number(after.slice(6)) : 0;
138
+ const nodes = Array.from({ length: Math.min(100, total - start) }, (_, i) => ({ number: start + i + 1, title: "t", body: "", mergedAt: at(0), mergeCommit: { oid: `s${start + i}` },
139
+ repository: { nameWithOwner: "o/r" }, closingIssuesReferences: { nodes: [] } }));
140
+ return JSON.stringify({ data: { search: { pageInfo: { hasNextPage: start + 100 < total, endCursor: String(start + 100) }, nodes } } });
141
+ }
142
+ return "[]";
143
+ };
144
+ }
145
+ const isWrite = (args) => args.some((a) => /^(-X|--method)$/.test(a)) || args.some((a) => /^query=\s*mutation\b/.test(a)) || ["comment", "edit", "create", "close", "reopen", "merge"].includes(args[1]);
146
+
147
+ describe("conformance outcomes: read only (#5210 R3)", () => {
148
+ it("one GraphQL call per 100 PRs and no write", async () => {
149
+ const calls = [];
150
+ const out = await gatherConformanceOutcomes({ repo: "o/r", gh: graphqlGh(250, calls), since: at(0), now: NOW });
151
+ assert.equal(out.prs.length, 250);
152
+ assert.equal(out.graphqlCalls, 3);
153
+ assert.equal(calls.length, 3);
154
+ assert.ok(calls.every((a) => a[0] === "api" && a[1] === "graphql" && !isWrite(a)));
155
+ assert.ok(calls[0].includes("q=repo:o/r is:pr is:merged merged:>=2026-10-01"));
156
+ });
157
+ it("runStats --conformance-outcomes --json: GitHub reads only, the report under query.conformance_outcomes", async () => {
158
+ const calls = [];
159
+ const gh = graphqlGh(120, calls);
160
+ let out = "";
161
+ const w = process.stdout.write;
162
+ process.stdout.write = (t) => { out += t; return true; };
163
+ let code;
164
+ try {
165
+ code = await runStats(["--conformance-outcomes", "--repo", "o/r", "--since", "2026-10-01", "--window-days", "5", "--json", "--no-cache", "--no-local"],
166
+ { gh, env: { HOME: "/nonexistent" }, now: () => NOW, git: null, releaseTimes: [], onProgress: () => {} });
167
+ } finally { process.stdout.write = w; }
168
+ assert.equal(code, 0);
169
+ const rep = JSON.parse(out).query.conformance_outcomes;
170
+ assert.equal(rep.window_days, 5);
171
+ assert.equal(rep.sources.merged_prs, 120);
172
+ assert.equal(rep.sources.graphql_calls, 2);
173
+ assert.equal(rep.conclusion, OUTCOME_INSUFFICIENT);
174
+ assert.equal(calls.filter((a) => a[1] === "graphql").length, 2);
175
+ assert.ok(calls.every((a) => !isWrite(a)), "no GitHub write");
176
+ });
177
+ it("buildReport bounds the crawl and uses min n 20 unless --min-n is passed", async () => {
178
+ const r = await buildReport({ ...parseArgs(["--conformance-outcomes", "--min-n", "3"]), repo: "o/r", cache: false, local: false },
179
+ { gh: graphqlGh(0), env: {}, now: () => NOW, git: null, releaseTimes: [], onProgress: () => {} });
180
+ assert.equal(r.query.conformance_outcomes.min_n, 3);
181
+ });
182
+ it("flag parsing", () => {
183
+ assert.equal(parseArgs(["--conformance-outcomes"]).conformanceOutcomes, true);
184
+ assert.equal(parseArgs(["--conformance-outcomes", "--window-days", "14"]).windowDays, 14);
185
+ assert.throws(() => parseArgs(["--window-days", "7"]), /needs --conformance-outcomes/);
186
+ assert.throws(() => parseArgs(["--conformance-outcomes", "--window-days", "0"]), /positive integer/);
187
+ });
188
+ });
@@ -0,0 +1,218 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * forge#5209: adaptive lane depth. `forgedock stats --depth` joins each lane's LIGHT_ELIGIBILITY verdict, reasons and
5
+ * signals (bin/lean/light.mjs) with its outcome: merged / needs-human, first pass, cost, wall and model time, review
6
+ * findings and conformance failures, and post-merge defect signals (a reopen, a revert, or a fix PR touching the same
7
+ * non-test files within 7 days). It answers whether, for lanes the light gate would have taken, the plan and review steps
8
+ * caught anything or only added cost, and whether the #5052 light-lane promotion criterion is met:
9
+ * light-shaped lanes (light or upgraded) cost <= 1.2x eligible full lanes of the same size, wall <= 1.3x model time, and
10
+ * a defect rate no worse than those full lanes; any cell under min-n is "insufficient data".
11
+ * Flipping lean.light.mode stays a config decision. No model, no clock (`now` is injected), no network except the injected gh.
12
+ *
13
+ * Sources: the run logs (~/.forge/runs/<issue>.jsonl, every RUN_START..RUN_TERMINAL slice); GitHub only for defect signals.
14
+ */
15
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
16
+ import { join } from "node:path";
17
+ import { firstPassOf } from "../lean/fixround.mjs";
18
+ import { classifyPath } from "../lean/routing.mjs";
19
+ import { DEFAULT_MIN_N } from "./aggregate.mjs";
20
+ import { sameRepo, WEEK_MS } from "./efficiency.mjs";
21
+
22
+ export const VERDICTS = Object.freeze(["eligible", "ambiguous", "ineligible"]);
23
+ export const PROMOTION = Object.freeze({ costRatio: 1.2, wallOverModel: 1.3 });
24
+ export const INSUFFICIENT = "insufficient data";
25
+
26
+ const num = (x) => (typeof x === "number" && Number.isFinite(x) ? x : null);
27
+ const costOf = (e) => num(e.cost_usd_delta) ?? num(e.cost_usd);
28
+ const r = (x, p = 1e4) => (num(x) == null ? null : Math.round(x * p) / p);
29
+ const per = (a, b) => (b > 0 ? a / b : null);
30
+ const ms = (ts) => { const t = Date.parse(ts ?? ""); return Number.isNaN(t) ? null : t; };
31
+ const median = (xs) => {
32
+ const v = xs.filter((x) => num(x) != null).sort((a, b) => a - b);
33
+ if (!v.length) return null;
34
+ const h = Math.floor(v.length / 2);
35
+ return v.length % 2 ? v[h] : (v[h - 1] + v[h]) / 2;
36
+ };
37
+ const codesOf = (xs) => [...new Set((Array.isArray(xs) ? xs : []).map((x) => String(x?.code ?? x ?? "").trim()).filter(Boolean))].sort();
38
+
39
+ function parseLog(text) {
40
+ const out = [];
41
+ for (const line of String(text ?? "").split("\n")) {
42
+ if (!line.trim()) continue;
43
+ try { const e = JSON.parse(line); if (e && typeof e === "object") out.push(e); } catch { /* torn line */ }
44
+ }
45
+ return out;
46
+ }
47
+
48
+ /**
49
+ * One row per RUN_START..RUN_TERMINAL slice of one run log that logged LIGHT_ELIGIBILITY. A slice whose repo is unknown is
50
+ * kept; `sinceMs` bounds the slice start (a slice without a start time is kept).
51
+ */
52
+ export function depthRows(events, { repo = null, sinceMs = null, issue = null } = {}) {
53
+ const out = [];
54
+ let cur = null;
55
+ const close = () => { if (cur?.elig && cur.term) out.push(finish(cur)); cur = null; };
56
+ for (const e of Array.isArray(events) ? events : []) {
57
+ if (!e || typeof e !== "object") continue;
58
+ if (e.event === "RUN_START") { close(); cur = { start: e, elig: null, term: null, shape: "full", attempts: [], findings: 0, conf: 0, pr: null }; continue; }
59
+ if (!cur) continue;
60
+ if (e.event === "LIGHT_ELIGIBILITY") cur.elig = e;
61
+ else if (e.event === "LIGHT_DONE") cur.shape = "light";
62
+ else if (e.event === "LIGHT_UPGRADE") cur.shape = "upgraded";
63
+ else if (e.event === "PHASE_ATTEMPT_USAGE") cur.attempts.push(e);
64
+ else if (e.event === "CONFORMANCE") {
65
+ cur.findings += Array.isArray(e.failures) ? e.failures.length : 0;
66
+ if (typeof e.state === "string" && e.state !== "conforms") cur.conf++;
67
+ } else if (e.event === "VERIFIER") cur.findings += num(e.findings) ?? 0;
68
+ else if (e.event === "PR_OPENED" && Number.isSafeInteger(e.pr)) cur.pr = e.pr;
69
+ else if (e.event === "RUN_TERMINAL") { cur.term = e; close(); }
70
+ }
71
+ close();
72
+ function finish(s) {
73
+ const impl = s.attempts.filter((a) => a.phase === "implement");
74
+ const t = s.term;
75
+ return { issue: Number.isSafeInteger(s.start.issue) ? s.start.issue : issue, repo: s.start.repo ?? null, startTs: s.start.ts ?? null, endTs: t.ts ?? null,
76
+ verdict: String(s.elig.verdict ?? "unknown"), mode: s.elig.mode ?? null, reasons: codesOf(s.elig.reasons), signals: codesOf(s.elig.signals),
77
+ shape: s.shape, outcome: t.reason ?? null, merged: t.reason === "merged", needsHuman: t.reason === "needs-human",
78
+ firstPass: firstPassOf(impl.map((a) => ({ trigger: a.trigger ?? null, restart_of: a.restart_of ?? null }))),
79
+ cost: s.attempts.reduce((n, a) => n + (costOf(a) ?? 0), 0), wallMs: num(t.wall_ms), modelMs: num(t.model_ms),
80
+ size: ["S", "M", "L"].includes(t.turns?.size) ? t.turns.size : null, pr: Number.isSafeInteger(t.pr) ? t.pr : s.pr,
81
+ findings: s.findings, conformanceFailures: s.conf };
82
+ }
83
+ return out.filter((x) => (!repo || !x.repo || sameRepo(x.repo, repo)) && (sinceMs == null || ms(x.startTs) == null || ms(x.startTs) >= sinceMs));
84
+ }
85
+
86
+ const lines = (raw) => String(raw ?? "").split("\n").filter((l) => l.trim()).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
87
+ const isFixPr = (p) => /^fix/i.test(String(p.title ?? "")) || (p.labels ?? []).some((l) => String(l).toLowerCase() === "bug");
88
+ const isRevertOf = (p, pr) => /^revert/i.test(String(p.title ?? "")) && new RegExp(`#${pr}(?!\\d)`).test(`${p.title ?? ""}\n${p.body ?? ""}`);
89
+ const nonTestFiles = (fs) => fs.filter((f) => classifyPath(f) !== "test");
90
+
91
+ /**
92
+ * Post-merge defect signals of merged rows with a PR, over the injected gh: Map issue -> {reopen, revert, fixPr, defect}.
93
+ * A gh failure gives the rows it could not read null fields (rendered n/a), never false.
94
+ */
95
+ export async function gatherDefects({ repo, gh, rows = [], windowMs = WEEK_MS } = {}) {
96
+ const out = new Map();
97
+ const merged = rows.filter((x) => x.merged && Number.isSafeInteger(x.pr) && ms(x.endTs) != null);
98
+ if (!gh || !repo || !merged.length) return out;
99
+ try {
100
+ const reopens = lines(await gh(["api", "--paginate", `repos/${repo}/issues/events?per_page=100`, "--jq", '.[] | select(.event == "reopened") | {issue: .issue.number, ts: .created_at}']));
101
+ const from = new Date(Math.min(...merged.map((x) => ms(x.endTs)))).toISOString().slice(0, 10);
102
+ const prs = lines(await gh(["api", "--paginate", `search/issues?q=${encodeURIComponent(`repo:${repo} is:pr is:merged merged:>=${from}`)}&per_page=100`,
103
+ "--jq", ".items[] | {number, title, body, labels: [.labels[].name], merged_at: .pull_request.merged_at}"]));
104
+ const files = new Map();
105
+ const filesOf = async (n) => {
106
+ if (!files.has(n)) files.set(n, String(await gh(["api", "--paginate", `repos/${repo}/pulls/${n}/files?per_page=100`, "--jq", ".[].filename"])).split("\n").map((l) => l.trim()).filter(Boolean));
107
+ return files.get(n);
108
+ };
109
+ for (const x of merged) {
110
+ const t0 = ms(x.endTs), inWin = (p) => p.number !== x.pr && ms(p.merged_at) != null && ms(p.merged_at) > t0 && ms(p.merged_at) <= t0 + windowMs;
111
+ const reopen = reopens.some((e) => e.issue === x.issue && (ms(e.ts) ?? 0) > t0);
112
+ const revert = prs.some((p) => inWin(p) && isRevertOf(p, x.pr));
113
+ let fixPr = false;
114
+ const cands = prs.filter((p) => inWin(p) && isFixPr(p));
115
+ if (cands.length) {
116
+ const own = new Set(nonTestFiles(await filesOf(x.pr)));
117
+ for (const p of cands) if (own.size && nonTestFiles(await filesOf(p.number)).some((f) => own.has(f))) { fixPr = true; break; }
118
+ }
119
+ out.set(x.issue, { reopen, revert, fixPr, defect: reopen || revert || fixPr });
120
+ }
121
+ } catch { // gh unavailable: the unread rows get null defect fields (n/a), never false
122
+ for (const x of merged) if (!out.has(x.issue)) out.set(x.issue, { reopen: null, revert: null, fixPr: null, defect: null });
123
+ }
124
+ return out;
125
+ }
126
+
127
+ /** The metrics of one group of rows; `defects` maps issue -> {defect}. */
128
+ export function depthCell(rows, defects = new Map()) {
129
+ const n = rows.length;
130
+ const fp = rows.filter((x) => typeof x.firstPass === "boolean");
131
+ const known = rows.filter((x) => x.merged && typeof defects.get(x.issue)?.defect === "boolean");
132
+ const ratios = rows.filter((x) => x.wallMs != null && x.modelMs > 0).map((x) => x.wallMs / x.modelMs);
133
+ return { n, merge_rate: r(per(rows.filter((x) => x.merged).length, n)), needs_human_rate: r(per(rows.filter((x) => x.needsHuman).length, n)),
134
+ first_pass_rate: r(per(fp.filter((x) => x.firstPass).length, fp.length)), median_cost_usd: r(median(rows.map((x) => x.cost)), 1e4),
135
+ median_wall_min: r(median(rows.map((x) => (x.wallMs == null ? null : x.wallMs / 60000))), 100), median_wall_over_model: r(median(ratios), 100),
136
+ findings_per_lane: r(per(rows.reduce((a, x) => a + x.findings, 0), n), 100), share_with_findings: r(per(rows.filter((x) => x.findings > 0).length, n)),
137
+ conformance_failure_rate: r(per(rows.filter((x) => x.conformanceFailures > 0).length, n)),
138
+ defects_n: known.length, defect_rate: known.length ? r(per(known.filter((x) => defects.get(x.issue).defect).length, known.length)) : null };
139
+ }
140
+
141
+ const check = (value, limit, nT, nC, minN, cmp) => {
142
+ if (nT < minN || (nC != null && nC < minN) || value == null) return { value: r(value, 100), limit, n_treatment: nT, ...(nC != null ? { n_control: nC } : {}), met: null, verdict: INSUFFICIENT };
143
+ const met = cmp(value, limit);
144
+ return { value: r(value, 100), limit, n_treatment: nT, ...(nC != null ? { n_control: nC } : {}), met, verdict: met ? "met" : "not met" };
145
+ };
146
+
147
+ /**
148
+ * The #5052 promotion verdict: treatment = light-shaped lanes (light or upgraded: the true cost of trying light);
149
+ * control = full-shape lanes the gate rated eligible, in the size buckets both cohorts have (#4491 matched sizes).
150
+ */
151
+ export function promotion(rows, defects = new Map(), minN = DEFAULT_MIN_N) {
152
+ const sz = (x) => x.size ?? "unknown";
153
+ const t0 = rows.filter((x) => x.shape === "light" || x.shape === "upgraded"), c0 = rows.filter((x) => x.shape === "full" && x.verdict === "eligible");
154
+ const sizes = [...new Set(t0.map(sz))].filter((s) => c0.some((x) => sz(x) === s)).sort();
155
+ const t = t0.filter((x) => sizes.includes(sz(x))), c = c0.filter((x) => sizes.includes(sz(x)));
156
+ const tc = depthCell(t, defects), cc = depthCell(c, defects);
157
+ const cost = check(tc.median_cost_usd != null && cc.median_cost_usd > 0 ? tc.median_cost_usd / cc.median_cost_usd : null, PROMOTION.costRatio, t.length, c.length, minN, (v, l) => v <= l);
158
+ const wallRows = t0.filter((x) => x.wallMs != null && x.modelMs > 0);
159
+ const wall = check(median(wallRows.map((x) => x.wallMs / x.modelMs)), PROMOTION.wallOverModel, wallRows.length, null, minN, (v, l) => v <= l);
160
+ const defect = tc.defect_rate != null && cc.defect_rate != null && tc.defects_n >= minN && cc.defects_n >= minN
161
+ ? { value: tc.defect_rate, limit: cc.defect_rate, n_treatment: tc.defects_n, n_control: cc.defects_n, met: tc.defect_rate <= cc.defect_rate, verdict: tc.defect_rate <= cc.defect_rate ? "met" : "not met" }
162
+ : { value: tc.defect_rate, limit: cc.defect_rate, n_treatment: tc.defects_n, n_control: cc.defects_n, met: null, verdict: INSUFFICIENT };
163
+ const checks = { cost, wall, defects: defect };
164
+ const vs = Object.values(checks).map((x) => x.met);
165
+ const met = vs.includes(false) ? false : vs.every((x) => x === true) ? true : INSUFFICIENT;
166
+ return { met, sizes, n_treatment: t.length, n_control: c.length, min_n: minN, checks, note: "flipping lean.light.mode: on stays a config decision" };
167
+ }
168
+
169
+ /** Pure report: per verdict, per reason/signal code, and the promotion verdict. */
170
+ export function depthReport({ rows = [], defects = new Map(), minN = DEFAULT_MIN_N, defectsSource = "github" } = {}) {
171
+ const byVerdict = {};
172
+ for (const v of [...VERDICTS, ...new Set(rows.map((x) => x.verdict).filter((v) => !VERDICTS.includes(v)))]) {
173
+ const xs = rows.filter((x) => x.verdict === v);
174
+ if (xs.length || VERDICTS.includes(v)) byVerdict[v] = depthCell(xs, defects);
175
+ }
176
+ const byCode = {};
177
+ for (const code of [...new Set(rows.flatMap((x) => [...x.reasons, ...x.signals]))].sort()) byCode[code] = depthCell(rows.filter((x) => x.reasons.includes(code) || x.signals.includes(code)), defects);
178
+ return { lanes: rows.length, min_n: minN, defects_source: defectsSource, by_verdict: byVerdict, by_code: byCode, promotion: promotion(rows, defects, minN) };
179
+ }
180
+
181
+ const pct = (x) => (x == null ? "n/a" : `${Math.round(x * 100)}%`);
182
+ const val = (x, unit = "") => (x == null ? "n/a" : `${x}${unit}`);
183
+ const cellLine = (label, c) => ` ${label}: n=${c.n}, merge ${pct(c.merge_rate)}, first-pass ${pct(c.first_pass_rate)}, needs-human ${pct(c.needs_human_rate)}, `
184
+ + `median cost ${c.median_cost_usd == null ? "n/a" : `$${c.median_cost_usd.toFixed(4)}`}, wall ${val(c.median_wall_min, " min")}, findings/lane ${val(c.findings_per_lane)} `
185
+ + `(${pct(c.share_with_findings)} with any), conformance failures ${pct(c.conformance_failure_rate)}, post-merge defects ${pct(c.defect_rate)} (n=${c.defects_n})`;
186
+
187
+ /** Text lines of depthReport. */
188
+ export function renderDepth(rep, { repo = null, since = null } = {}) {
189
+ const out = [`lane depth${repo ? ` ${repo}` : ""}${since ? ` since ${since}` : ""}: ${rep.lanes} lane(s) with a light-eligibility verdict; defect signals: ${rep.defects_source}`];
190
+ out.push("by verdict:");
191
+ for (const [v, c] of Object.entries(rep.by_verdict)) out.push(cellLine(v, c));
192
+ out.push("by reason/signal:");
193
+ const codes = Object.entries(rep.by_code);
194
+ if (!codes.length) out.push(" n/a");
195
+ for (const [k, c] of codes) out.push(cellLine(k, c));
196
+ const p = rep.promotion, ck = p.checks;
197
+ const fmt = (name, x, unit) => ` ${name}: ${x.verdict}${x.value == null ? "" : ` (${x.value}${unit} vs ${x.limit}${unit})`}, n treatment=${x.n_treatment}${x.n_control != null ? `, n control=${x.n_control}` : ""}`;
198
+ out.push(`light-lane promotion (#5052, min n ${p.min_n} per cell): ${p.met === true ? "met" : p.met === false ? "not met" : INSUFFICIENT}`
199
+ + ` (treatment light|upgraded n=${p.n_treatment}, control eligible full n=${p.n_control}, sizes ${p.sizes.length ? p.sizes.join(",") : "none"})`);
200
+ out.push(fmt("cost ratio", ck.cost, "x"), fmt("wall/model", ck.wall, "x"), fmt("defect rate", ck.defects, ""));
201
+ out.push(` ${p.note}`);
202
+ return out.join("\n");
203
+ }
204
+
205
+ /** Every run log under `runsDir` -> rows -> defects (gh, unless null) -> report. */
206
+ export async function buildDepth({ runsDir, repo = null, sinceMs = null, gh = null, minN = DEFAULT_MIN_N } = {}) {
207
+ const rows = [];
208
+ if (runsDir && existsSync(runsDir)) {
209
+ for (const f of readdirSync(runsDir).filter((x) => x.endsWith(".jsonl")).sort()) {
210
+ let text = "";
211
+ try { text = readFileSync(join(runsDir, f), "utf8"); } catch { continue; }
212
+ const n = /^(\d+)\.jsonl$/.exec(f);
213
+ rows.push(...depthRows(parseLog(text), { repo, sinceMs, issue: n ? Number(n[1]) : null }));
214
+ }
215
+ }
216
+ const defects = gh ? await gatherDefects({ repo, gh, rows }) : new Map();
217
+ return depthReport({ rows, defects, minN, defectsSource: gh ? "github" : "offline" });
218
+ }