forgedock 1.51.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 (103) 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 +61 -17
  4. package/bin/experiment.mjs +58 -6
  5. package/bin/forge-utils.mjs +6 -2
  6. package/bin/forgedock.mjs +25 -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 +205 -23
  21. package/bin/lean/conformance.test.mjs +164 -3
  22. package/bin/lean/context.mjs +27 -17
  23. package/bin/lean/context.test.mjs +15 -0
  24. package/bin/lean/effects.mjs +11 -7
  25. package/bin/lean/execution.mjs +19 -3
  26. package/bin/lean/execution.test.mjs +39 -0
  27. package/bin/lean/findinglabel.mjs +16 -0
  28. package/bin/lean/findinglabel.test.mjs +39 -0
  29. package/bin/lean/heavy.mjs +6 -3
  30. package/bin/lean/hostload.mjs +78 -0
  31. package/bin/lean/hostload.test.mjs +117 -0
  32. package/bin/lean/hotspots-remote.e2e.test.mjs +71 -0
  33. package/bin/lean/issuewatch-release.mjs +6 -2
  34. package/bin/lean/issuewatch-release.test.mjs +16 -0
  35. package/bin/lean/issuewatch.mjs +11 -1
  36. package/bin/lean/lanelock.mjs +14 -0
  37. package/bin/lean/lean.mjs +171 -36
  38. package/bin/lean/lean.test.mjs +302 -10
  39. package/bin/lean/light.mjs +48 -7
  40. package/bin/lean/light.test.mjs +37 -3
  41. package/bin/lean/limits.test.mjs +142 -9
  42. package/bin/lean/orchestrate-cancel.test.mjs +143 -0
  43. package/bin/lean/orchestrate.mjs +110 -26
  44. package/bin/lean/postdeploy-check.test.mjs +39 -0
  45. package/bin/lean/prompts.mjs +8 -7
  46. package/bin/lean/quota.mjs +39 -0
  47. package/bin/lean/recovery.test.mjs +10 -0
  48. package/bin/lean/relaxation.mjs +73 -0
  49. package/bin/lean/relaxation.test.mjs +54 -0
  50. package/bin/lean/release-postmerge.mjs +119 -0
  51. package/bin/lean/release-rehearsal.mjs +63 -0
  52. package/bin/lean/release-rehearsal.test.mjs +93 -0
  53. package/bin/lean/release-review.e2e.test.mjs +77 -0
  54. package/bin/lean/release-review.mjs +198 -0
  55. package/bin/lean/release-review.test.mjs +180 -0
  56. package/bin/lean/release.mjs +228 -0
  57. package/bin/lean/release.test.mjs +292 -0
  58. package/bin/lean/rotator.mjs +150 -31
  59. package/bin/lean/rotator.test.mjs +105 -2
  60. package/bin/lean/sandbox-remote.mjs +9 -2
  61. package/bin/lean/schedd.mjs +56 -6
  62. package/bin/lean/schedd.test.mjs +108 -6
  63. package/bin/lean/verifier.mjs +3 -2
  64. package/bin/lean/verify.mjs +2 -1
  65. package/bin/lean/verify.test.mjs +6 -0
  66. package/bin/pool/agent.mjs +18 -4
  67. package/bin/pool/router.mjs +68 -25
  68. package/bin/review-staging.mjs +23 -0
  69. package/bin/stats/conformance-outcomes.mjs +208 -0
  70. package/bin/stats/conformance-outcomes.test.mjs +188 -0
  71. package/bin/stats/depth.mjs +218 -0
  72. package/bin/stats/depth.test.mjs +133 -0
  73. package/bin/stats/experiment.mjs +7 -5
  74. package/bin/stats/github-source.mjs +2 -2
  75. package/bin/stats/index.mjs +64 -2
  76. package/bin/stats/local-source.mjs +11 -0
  77. package/bin/stats/query.mjs +69 -0
  78. package/bin/stats/selffiled.mjs +52 -0
  79. package/bin/stats/selffiled.test.mjs +71 -0
  80. package/commands/orchestrate.md +1 -1
  81. package/commands/review-pr-agents/security.md +4 -0
  82. package/commands/review-pr-staging.md +2 -0
  83. package/commands/work-on/build.md +4 -6
  84. package/docs/CONFIG.md +66 -8
  85. package/docs/ISSUE-WATCH.md +2 -0
  86. package/docs/OUTCOME-CODES.md +3 -0
  87. package/docs/STATS.md +44 -0
  88. package/docs/TELEMETRY.md +1 -1
  89. package/package.json +1 -1
  90. package/pool/README.md +1 -1
  91. package/pool/image/cs-cred +14 -1
  92. package/pool/install/install-agent.ps1 +6 -2
  93. package/scripts/backfill-finding-labels.mjs +50 -0
  94. package/scripts/backfill-finding-labels.test.mjs +36 -0
  95. package/scripts/doctor-pipeline-state.sh +21 -6
  96. package/scripts/file-deferred-followups.sh +60 -238
  97. package/scripts/file-deferred-followups.test.sh +99 -187
  98. package/scripts/followup-route.mjs +12 -0
  99. package/scripts/hotspots.sh +12 -8
  100. package/scripts/hotspots.test.sh +22 -0
  101. package/scripts/owner-route-parity.test.sh +17 -1
  102. package/scripts/prior-attempts.test.mjs +1 -1
  103. package/scripts/review-pr-side-effects.test.sh +40 -0
@@ -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
+ }
@@ -0,0 +1,133 @@
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[2] ?? "";
83
+ if (o.fail) throw new Error("gh down");
84
+ if (path.includes("issues/events")) return JSON.stringify({ issue: 2, ts: iso(T0 + 2 * DAY) });
85
+ if (path.startsWith("search/issues")) return [
86
+ { number: 300, title: "Revert \"feat: x (#101)\"", body: "", labels: [], merged_at: iso(T0 + DAY) },
87
+ { number: 301, title: "fix: y", body: "", labels: [], merged_at: iso(T0 + 2 * DAY) },
88
+ { number: 302, title: "fix: late", body: "", labels: [], merged_at: iso(T0 + 30 * DAY) },
89
+ ].map((x) => JSON.stringify(x)).join("\n");
90
+ const files = { 101: "src/a.js", 102: "src/b.js\ntest/b.test.js", 103: "src/c.js\ntest/shared.test.js", 301: "src/b.js\ntest/shared.test.js", 302: "src/c.js" };
91
+ const m = /pulls\/(\d+)\/files/.exec(path);
92
+ return m ? files[m[1]] ?? "" : "";
93
+ };
94
+
95
+ test("gatherDefects: reopen, revert and a same-file fix PR within 7 days; gh failure is null, never false", async () => {
96
+ const rows = rowsOf({ issue: 1 }, { issue: 2 }, { issue: 3 });
97
+ const d = await gatherDefects({ repo: "o/r", gh: fakeGh(), rows });
98
+ assert.deepEqual(d.get(1), { reopen: false, revert: true, fixPr: false, defect: true });
99
+ assert.deepEqual(d.get(2), { reopen: true, revert: false, fixPr: true, defect: true });
100
+ assert.deepEqual(d.get(3), { reopen: false, revert: false, fixPr: false, defect: false }, "test-only overlap and an out-of-window fix do not count");
101
+ const bad = await gatherDefects({ repo: "o/r", gh: fakeGh({ fail: true }), rows });
102
+ assert.deepEqual(bad.get(1), { reopen: null, revert: null, fixPr: null, defect: null });
103
+ assert.equal(depthReport({ rows, defects: bad, minN: 1 }).by_verdict.eligible.defect_rate, null);
104
+ });
105
+
106
+ test("renderDepth and buildDepth: verdict and promotion lines with n per cell from run logs", async () => {
107
+ const dir = tmpDir("depth-");
108
+ mkdirSync(join(dir, "runs"), { recursive: true });
109
+ writeFileSync(join(dir, "runs", "5.jsonl"), slice({ issue: 5, shape: "light" }).map((e) => JSON.stringify(e)).join("\n") + "\n{torn");
110
+ writeFileSync(join(dir, "runs", "6.jsonl"), slice({ issue: 6, verdict: "ambiguous", reasons: ["no_repro"], signals: ["no_repro"] }).map((e) => JSON.stringify(e)).join("\n"));
111
+ const rep = await buildDepth({ runsDir: join(dir, "runs"), repo: "o/r", gh: null });
112
+ assert.equal(rep.lanes, 2);
113
+ assert.equal(rep.defects_source, "offline");
114
+ const text = renderDepth(rep, { repo: "o/r" });
115
+ assert.match(text, /lane depth o\/r/);
116
+ assert.match(text, /^ eligible: n=1, merge 100%/m);
117
+ assert.match(text, /^ ambiguous: n=1/m);
118
+ assert.match(text, /^ ineligible: n=0/m);
119
+ assert.match(text, /^ no_repro: n=1/m);
120
+ assert.match(text, /light-lane promotion \(#5052, min n 10 per cell\): insufficient data \(treatment light\|upgraded n=0, control eligible full n=0/);
121
+ assert.match(text, /cost ratio: insufficient data/);
122
+ assert.match(text, /config decision/);
123
+ });
124
+
125
+ test("parseArgs accepts --depth and --depth --offline; --offline alone still needs --efficiency; HELP lists --depth", () => {
126
+ assert.equal(parseArgs(["--depth"]).depth, true);
127
+ const o = parseArgs(["--depth", "--offline", "--min-n", "3"]);
128
+ assert.deepEqual([o.depth, o.offline, o.minN], [true, true, 3]);
129
+ assert.equal(parseArgs(["--efficiency", "--offline"]).offline, true);
130
+ assert.throws(() => parseArgs(["--offline"]), /--offline need --efficiency/);
131
+ assert.throws(() => parseArgs(["--compare", "2026-01-01"]), /--compare and --offline need --efficiency/);
132
+ assert.match(HELP, /stats --depth/);
133
+ });
@@ -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
  }
@@ -78,10 +78,10 @@ export function runsFromRecords(records) {
78
78
  const key = `${r.repo}#${r.issue}#${r.run ?? ""}`;
79
79
  const run = byRun.get(key) ?? { source: "github", repo: r.repo ?? null, version: r.forge_version ?? null, issue: r.issue, run: r.run ?? null,
80
80
  finished: false, hydrated: false, usageEvents: 0, reason: null, code: null, remediated: false, startTs: null, endTs: null, wallMs: null,
81
- phases: {}, builderAttempts: [], experiment: null, arm: null, _first: null };
81
+ phases: {}, builderAttempts: [], experiment: null, arm: null, armOverrides: null, _first: null };
82
82
  byRun.set(key, run);
83
83
  if (!run._first || r.ts < run._first) run._first = r.ts;
84
- if (r.experiment != null && r.arm != null) { run.experiment = String(r.experiment); run.arm = String(r.arm); } // #4629
84
+ if (r.experiment != null && r.arm != null) { run.experiment = String(r.experiment); run.arm = String(r.arm); if (r.arm_overrides != null) run.armOverrides = String(r.arm_overrides); } // #4629, #5206
85
85
  if (r.event === "run_terminal") {
86
86
  run.finished = true; run.reason = r.reason ?? null; run.code = r.code ?? null; run.endTs = r.ts ?? null; run.wallMs = num(r.wall_ms); run.ledger = unflattenPhases(r); // #4908
87
87
  continue;
@@ -21,7 +21,12 @@ import { experimentReport, renderExperiment } from "./experiment.mjs";
21
21
  import { readExperiment } from "../experiment.mjs";
22
22
  import { compoundingReport, gatherCompounding, renderCompounding, DEFAULT_BUCKETS, DEFAULT_WINDOW_MS } from "./compounding.mjs";
23
23
  import { poolUtilisation, formatPoolLines } from "./pool.mjs";
24
+ import { gatherIssues, selfFiledReport, renderSelfFiled } from "./selffiled.mjs";
25
+ import { buildDepth, renderDepth } from "./depth.mjs";
24
26
  import { batchRoot } from "../lean/batch.mjs";
27
+ import { conformanceOutcomes, gatherConformanceOutcomes, renderConformanceOutcomes, DEFAULT_OUTCOME_MIN_N, DEFAULT_WINDOW_DAYS, DEFAULT_LOOKBACK_DAYS } from "./conformance-outcomes.mjs";
28
+ import { conformanceVerdicts, readBatchRows } from "./query.mjs";
29
+ import { gitProbes } from "./compounding.mjs";
25
30
 
26
31
  const here = dirname(fileURLToPath(import.meta.url));
27
32
 
@@ -30,8 +35,11 @@ export const HELP = `Usage: forgedock stats [--since <version|date>] [--repo <ow
30
35
  forgedock stats --experiment <id> [--require-met] [--min-n N] [--repo <owner/repo>] [--json]
31
36
  forgedock stats --by version [--post-metrics <pr>] [--min-n N] [--repo <owner/repo>] [--json]
32
37
  forgedock stats --pool [--window 7d,30d] [--repo <owner/repo>] [--json]
38
+ forgedock stats --self-filed [--repo <owner/repo>] [--since <date>] [--json]
33
39
  forgedock stats --compounding [--window 30d] [--bucket 100,500] [--since <date>] [--min-n N] [--repo <owner/repo>] [--json]
40
+ forgedock stats --conformance-outcomes [--repo <owner/repo>] [--since <date>] [--window-days 7] [--min-n 20] [--json]
34
41
  forgedock stats --efficiency [--batch <id>] [--window 7d,30d] [--compare <date|version>] [--offline] [--repo <owner/repo>] [--json]
42
+ forgedock stats --depth [--since <version|date>] [--min-n N] [--offline] [--repo <owner/repo>] [--json]
35
43
 
36
44
  Version-over-version report: Cost, Time, Flow, Review funnel, Gates and Issue flow per (version, repo), with a
37
45
  delta against the previous version and a low-n flag for samples under 10. Missing data prints n/a.
@@ -86,6 +94,18 @@ Efficiency (forge#4402; local batch dirs and run logs, gh only for merged issues
86
94
  their delta and full-lane cohorts matched per size (forge#4491)
87
95
  --offline skip the GitHub crawl for merged issues (issue quality and acceptance print n/a)
88
96
 
97
+ Self-filed issues (#5207; GitHub issues only):
98
+ --self-filed share of new issues the pipeline filed itself, by kind (follow-up, review-finding, staging-review,
99
+ rollup), against the 15% target; --since <date> bounds the window (default: the last 30 days)
100
+
101
+ Lane depth (forge#5209; local run logs, gh only for post-merge defect signals, no model):
102
+ --depth light-eligible versus ineligible lanes (LIGHT_ELIGIBILITY verdict) with merge, first-pass and
103
+ needs-human rates, median cost, wall time, review findings, conformance failures and post-merge
104
+ defects (reopen, revert, a fix PR touching the same files within 7 days), grouped by verdict and
105
+ by every reason/signal code, plus the #5052 light-lane promotion verdict: light-shaped lanes cost
106
+ <= 1.2x and wall <= 1.3x model time, defect rate <= eligible full lanes of the same size;
107
+ "insufficient data" under --min-n per cell. --offline skips the defect crawl (n/a)
108
+
89
109
  Compounding (forge#4696; GitHub + git of the current clone, no model):
90
110
  --compounding reintroduction rate (guarded fix reopened, or its lines blamed by a later guarded fix within 90 days),
91
111
  reopen-after-close rate, guard activity (guard_run, guard_broken, supersedes_accepted) and decision
@@ -93,6 +113,14 @@ Compounding (forge#4696; GitHub + git of the current clone, no model):
93
113
  bucket; n/a where no data is recorded. Pair with --efficiency --compare for $/merge and turns/merge
94
114
  --bucket <list> lane-age bucket upper bounds (default 100,500: lanes 1-100, 101-500, 501+)
95
115
 
116
+ Conformance outcomes (forge#5210; read only: one GraphQL search per 100 merged PRs, FORGE:TELEMETRY, local run and batch logs, git):
117
+ --conformance-outcomes each merged lane PR's last conformance verdict (mode, failure kinds) joined to post-merge defect
118
+ signals inside the window (reverted, closing issue reopened, cited by a later fix, a later fix
119
+ touching the same hunks via local git blame); defect rate, n and a Wilson 95% interval of
120
+ nonconforming-merged vs conforming-merged per repo, mode and failure kind; n/a under --min-n
121
+ (default ${DEFAULT_OUTCOME_MIN_N} per cell); the last line is the conclusion or "insufficient data"
122
+ --window-days N post-merge defect window in days (default ${DEFAULT_WINDOW_DAYS}); --since defaults to 30 days ago
123
+
96
124
  Builder model tiers (forge#4394; local run logs only, no GitHub crawl):
97
125
  --tiers merge, conformance and post-merge-rework rates, first-pass yield and cost per builder tier
98
126
  (mid, mid->top escalated, top) and routing class; --json for JSON
@@ -107,7 +135,7 @@ Lane profile baseline (forge#4436; local run logs only, every run of each issue,
107
135
  export function experimentExit(opts, report) { return opts.requireMet && report.targets_met !== true ? 1 : 0; }
108
136
 
109
137
  export function parseArgs(argv) {
110
- const o = { since: null, repo: null, edge: null, milestone: null, contextAb: false, exploreAb: false, tiers: false, compounding: false, bucket: null, laneProfile: false, issues: null, efficiency: false, pool: false, batch: null, windows: null, compare: null, by: null, experiment: null, emitEvent: false, requireMet: false, postMetrics: null, offline: false, json: false, refresh: false, compact: false, local: true, cache: true, minN: DEFAULT_MIN_N, releaseTimes: null, help: false };
138
+ const o = { depth: false, conformanceOutcomes: false, windowDays: null, since: null, repo: null, edge: null, milestone: null, contextAb: false, exploreAb: false, tiers: false, compounding: false, selfFiled: false, bucket: null, laneProfile: false, issues: null, efficiency: false, pool: false, batch: null, windows: null, compare: null, by: null, experiment: null, emitEvent: false, requireMet: false, postMetrics: null, offline: false, json: false, refresh: false, compact: false, local: true, cache: true, minN: DEFAULT_MIN_N, releaseTimes: null, help: false };
111
139
  const val = (i, name) => {
112
140
  const v = argv[i + 1];
113
141
  if (v == null || v.startsWith("--")) throw new Error(`${name} needs a value`);
@@ -127,10 +155,14 @@ export function parseArgs(argv) {
127
155
  else if (name === "--explore-ab") o.exploreAb = true;
128
156
  else if (name === "--tiers") o.tiers = true;
129
157
  else if (name === "--compounding") o.compounding = true;
158
+ else if (name === "--self-filed") o.selfFiled = true;
130
159
  else if (name === "--bucket") { const v = take(); if (!/^[1-9]\d*(,[1-9]\d*)*$/.test(v)) throw new Error("--bucket must be a comma list of lane counts"); const b = v.split(",").map(Number); if (b.some((x, i) => i && x <= b[i - 1])) throw new Error("--bucket must be increasing"); o.bucket = b; }
131
160
  else if (name === "--lane-profile") o.laneProfile = true;
132
161
  else if (name === "--issues") { const v = take(); if (!/^[1-9]\d*(,[1-9]\d*)*$/.test(v)) throw new Error("--issues must be a comma list of issue numbers"); o.issues = v.split(",").map(Number); }
162
+ else if (name === "--conformance-outcomes") o.conformanceOutcomes = true;
163
+ else if (name === "--window-days") { const v = take(); if (!/^[1-9]\d*$/.test(v)) throw new Error("--window-days must be a positive integer"); o.windowDays = Number(v); }
133
164
  else if (name === "--efficiency") o.efficiency = true;
165
+ else if (name === "--depth") o.depth = true;
134
166
  else if (name === "--pool") o.pool = true;
135
167
  else if (name === "--batch") { const v = take(); if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(v)) throw new Error(`invalid --batch id: ${v}`); o.batch = v; }
136
168
  else if (name === "--window") o.windows = parseWindows(take());
@@ -157,7 +189,9 @@ export function parseArgs(argv) {
157
189
  if (o.batch && !o.efficiency) throw new Error("--batch and --window need --efficiency");
158
190
  if (o.windows && !o.efficiency && !o.pool && !o.compounding) throw new Error("--batch and --window need --efficiency");
159
191
  if (o.bucket && !o.compounding) throw new Error("--bucket needs --compounding");
160
- if ((o.compare || o.offline) && !o.efficiency) throw new Error("--compare and --offline need --efficiency");
192
+ if (o.compare && !o.efficiency) throw new Error("--compare and --offline need --efficiency");
193
+ if (o.offline && !o.efficiency && !o.depth) throw new Error("--compare and --offline need --efficiency (--offline also works with --depth)");
194
+ if (o.windowDays != null && !o.conformanceOutcomes) throw new Error("--window-days needs --conformance-outcomes");
161
195
  if (o.postMetrics && !o.by) throw new Error("--post-metrics needs --by version");
162
196
  return o;
163
197
  }
@@ -272,6 +306,13 @@ export function readAlertConfig(cwd = process.cwd()) {
272
306
  export async function buildReport(opts, deps = {}) {
273
307
  const env = deps.env ?? process.env;
274
308
  const repo = opts.repo;
309
+ if (opts.selfFiled) { // #5207: GitHub issues only, no telemetry crawl
310
+ const p = parseSince(opts.since);
311
+ if (p.sinceVersion) throw new Error("--self-filed: --since must be a date (YYYY-MM-DD)");
312
+ const since = new Date(p.sinceMs ?? (deps.now?.() ?? Date.now()) - 30 * 86400000).toISOString().slice(0, 10);
313
+ const issues = await gatherIssues({ gh: deps.gh ?? defaultGh, repo, since });
314
+ return { repo, query: { self_filed: selfFiledReport({ issues, since, repo }) } };
315
+ }
275
316
  let releaseTimes = [];
276
317
  if (opts.releaseTimes) releaseTimes = parseReleaseTimes(readFileSync(opts.releaseTimes, "utf8"));
277
318
  else if (deps.releaseTimes) releaseTimes = deps.releaseTimes;
@@ -280,6 +321,11 @@ export async function buildReport(opts, deps = {}) {
280
321
  const pool = poolUtilisation({ batchRoot: deps.batchRoot ?? batchRoot(env), repo, windows: opts.windows ?? parseWindows("7d,30d"), now: deps.now?.() ?? Date.now() });
281
322
  return { repo, query: { pool } };
282
323
  }
324
+ if (opts.depth) { // forge#5209: run logs; gh only for post-merge defect signals
325
+ const st = sinceToTimestamp(opts.since, releaseTimes), sinceMs = st.since ? Date.parse(st.since) : null;
326
+ const depth = await buildDepth({ runsDir: deps.runsDir ?? runsDir(env), repo, sinceMs, gh: opts.offline ? null : (deps.gh ?? defaultGh), minN: opts.minN });
327
+ return { repo, query: { depth } };
328
+ }
283
329
  if (opts.efficiency) { // forge#4402: local batch dirs + run logs; gh only for merged issues
284
330
  const root = deps.batchRoot ?? batchRoot(env), rd = deps.runsDir ?? runsDir(env), now = deps.now?.() ?? Date.now(), gh = opts.offline ? null : (deps.gh ?? defaultGh);
285
331
  const efficiency = {};
@@ -305,6 +351,7 @@ export async function buildReport(opts, deps = {}) {
305
351
  return { repo, sources: { local: { runs: runs.length } }, query: { lane_profile: laneProfileReport(runs, { issues: opts.issues }) } };
306
352
  }
307
353
  const bound = sinceToTimestamp(opts.since, releaseTimes);
354
+ if (opts.conformanceOutcomes && !bound.since) bound.since = new Date((deps.now?.() ?? Date.now()) - DEFAULT_LOOKBACK_DAYS * 86400000).toISOString().replace(/\.\d{3}Z$/, "Z"); // #5210: bounded crawl
308
355
  if (bound.note) (deps.warn ?? ((m) => process.stderr.write(`forgedock stats: ${m}\n`)))(bound.note);
309
356
  const gh = await fetchGithubRecords({ repo, since: bound.since, refresh: opts.refresh, useCache: opts.cache, gh: deps.gh, env,
310
357
  onProgress: deps.onProgress, sleep: deps.sleep, now: deps.now });
@@ -313,6 +360,18 @@ export async function buildReport(opts, deps = {}) {
313
360
  const query = { ...(e ? { edge: { ...e, prs: edgeQuery(gh.records, e.from, e.to) } } : {}), ...(opts.milestone ? { mix: verdictMix(gh.records, gh.items, opts.milestone) } : {}) };
314
361
  return { repo, sources: { github: { items: gh.items.length, records: gh.records.length, cached: gh.fromCache } }, query };
315
362
  }
363
+ if (opts.conformanceOutcomes) { // forge#5210: read only; GraphQL search per 100 PRs + the telemetry records above + local logs + git
364
+ const now = deps.now?.() ?? Date.now();
365
+ const input = await (deps.gatherConformanceOutcomes ?? gatherConformanceOutcomes)({ repo, gh: deps.gh ?? defaultGh, since: bound.since, now });
366
+ const verdicts = conformanceVerdicts({ records: gh.records,
367
+ runs: opts.local ? (deps.localRuns ?? readLocalRuns(runsDir(env))).filter((r) => r.repo == null || r.repo === repo) : [],
368
+ batchRows: opts.local ? (deps.batchRows ?? readBatchRows({ batchRoot: deps.batchRoot ?? batchRoot(env), repo })) : [] });
369
+ const git = deps.git !== undefined ? deps.git : resolveRepo(null)?.toLowerCase() === repo.toLowerCase() ? gitProbes(process.cwd()) : null;
370
+ const report = conformanceOutcomes({ prs: input.prs, verdicts, minN: opts.minNSet ? opts.minN : DEFAULT_OUTCOME_MIN_N, windowDays: opts.windowDays ?? DEFAULT_WINDOW_DAYS,
371
+ now, git, graphqlCalls: input.graphqlCalls, since: input.since });
372
+ if (input.capped) report.sources.capped = true;
373
+ return { repo, sources: { github: { items: gh.items.length, records: gh.records.length, cached: gh.fromCache } }, query: { conformance_outcomes: report } };
374
+ }
316
375
  const model = toModel(repo, gh);
317
376
  if (opts.compounding) { // forge#4696: GitHub records + guards + git, no model
318
377
  const inputs = await (deps.gatherCompounding ?? gatherCompounding)({ repo, gh: deps.gh ?? defaultGh });
@@ -366,7 +425,10 @@ export async function runStats(argv, deps = {}) {
366
425
  if (report.query?.experiment) { process.stdout.write(`${opts.json ? renderJson(report) : renderExperiment(report.query.experiment)}\n`); return experimentExit(opts, report.query.experiment); }
367
426
  if (report.query?.lane_profile && !opts.json) { process.stdout.write(`${renderLaneProfiles(report.query.lane_profile)}\n`); return 0; }
368
427
  if (report.query?.tiers && !opts.json) { process.stdout.write(`${renderTiers(report.query.tiers)}\n`); return 0; }
428
+ if (report.query?.conformance_outcomes && !opts.json) { process.stdout.write(`${renderConformanceOutcomes(report.query.conformance_outcomes)}\n`); return 0; }
369
429
  if (report.query?.compounding && !opts.json) { process.stdout.write(`${renderCompounding(report.query.compounding)}\n`); return 0; }
430
+ if (report.query?.self_filed && !opts.json) { process.stdout.write(`${renderSelfFiled(report.query.self_filed)}\n`); return 0; }
431
+ if (report.query?.depth && !opts.json) { process.stdout.write(`${renderDepth(report.query.depth, { repo: report.repo, since: opts.since })}\n`); return 0; }
370
432
  if (report.query?.pool && !opts.json) { process.stdout.write(`${formatPoolLines(report.query.pool).join("\n")}\n`); return 0; }
371
433
  if (report.query?.efficiency && !opts.json) {
372
434
  const e = report.query.efficiency;
@@ -92,6 +92,10 @@ export function summariseLog(events, fallbackIssue = null) {
92
92
  builderRoute: routeOf(term, ev),
93
93
  conformanceRound: builderCalls.some((e) => e.trigger === "conformance" || e.trigger === "review"),
94
94
  shadowWould: typeof term?.shadow_would === "string" ? term.shadow_would : null,
95
+ // #5210: the per-PR verdict join of --conformance-outcomes (pr, mode, and the last verdict's failure codes)
96
+ pr: Number.isSafeInteger(term?.pr) ? term.pr : null,
97
+ conformanceMode: term?.conformance_mode === "enforce" || term?.conformance_mode === "shadow" ? term.conformance_mode : null,
98
+ conformanceFailures: lastConformanceFailures(ev),
95
99
  reachedReview: reviewCalls > 0 || typeof term?.shadow_would === "string",
96
100
  // #4394: routes of earlier runs in this log that ended merged: a later run of the same issue is post-merge rework
97
101
  reworkedMerges: earlierMergedRoutes(events.slice(0, s)),
@@ -104,6 +108,13 @@ export function summariseLog(events, fallbackIssue = null) {
104
108
  };
105
109
  }
106
110
 
111
+ /** #5210: failure codes of the slice's last CONFORMANCE_SHADOW event, else its last CONFORMANCE event; null when neither ran. */
112
+ function lastConformanceFailures(ev) {
113
+ const pick = (name) => [...ev].reverse().find((e) => e.event === name && Array.isArray(e.failures));
114
+ const e = pick("CONFORMANCE_SHADOW") ?? pick("CONFORMANCE");
115
+ return e ? e.failures.filter((f) => typeof f === "string" && f) : null;
116
+ }
117
+
107
118
  /** #4436: the one lane_profile of the usage records, "mixed" when they differ, null when none carries it. */
108
119
  function profileOf(usage) {
109
120
  const ps = new Set(usage.map((e) => e.lane_profile).filter((p) => typeof p === "string" && p));