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,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));
@@ -8,6 +8,10 @@
8
8
  * run_terminal: reason, pr, milestone, conformance_mode, shadow_would
9
9
  */
10
10
 
11
+ import { existsSync, readFileSync } from "node:fs";
12
+ import { join } from "node:path";
13
+ import { listBatches } from "../lean/batch.mjs";
14
+
11
15
  const list = (v) => (typeof v === "string" && v !== "none" ? v.split(",").filter(Boolean) : []);
12
16
  const day = (ts) => (typeof ts === "string" ? ts.slice(0, 10) : "unknown");
13
17
 
@@ -275,3 +279,68 @@ export function renderLaneProfiles(rep) {
275
279
  + `| Profile | Runs | Conformance rate (reviewed) | Shadow would-block |\n| --- | --- | --- | --- |\n${conf.length ? conf.join("\n") : "| none | 0 | | |"}\n\n`
276
280
  + `Issues with a finished run under every profile: ${rep?.issues_in_all?.length ? rep.issues_in_all.map((i) => `#${i}`).join(", ") : "none"}`;
277
281
  }
282
+
283
+ /**
284
+ * #5210: the last conformance verdict of each lane PR, for `forgedock stats --conformance-outcomes`. Sources, latest wins:
285
+ * FORGE:TELEMETRY `run_terminal` (pr, conformance_mode, shadow_would) plus the issue's last `conformance_shadow` failures;
286
+ * local run-log summaries (local-source summariseLog: pr, conformanceMode, shadowWould, conformanceFailures);
287
+ * batch report rows (`conformance: {mode, would, kinds}`, written by orchestrate from the lane result).
288
+ * would "conforms" is conforming, any other would is nonconforming (its failure codes are the kinds); an enforce merge with
289
+ * no would passed the enforced gate, so it conforms. A shadow run with no would never reached the gate: no verdict.
290
+ * Returns a Map keyed `pr:<n>` and `issue:<n>` of {issue, pr, mode, state, kinds, ts, source}.
291
+ */
292
+ const codes = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === "string" && x) : list(v));
293
+ export function verdictOf({ mode, would, merged, failures }) {
294
+ const m = mode === "enforce" || mode === "shadow" ? mode : null;
295
+ if (typeof would === "string" && would) return { mode: m, state: would === "conforms" ? "conforms" : "nonconforming", kinds: would === "conforms" ? [] : [...new Set(codes(failures))].sort() };
296
+ if (m === "enforce" && merged) return { mode: m, state: "conforms", kinds: [] };
297
+ return null;
298
+ }
299
+ export function conformanceVerdicts({ records = [], runs = [], batchRows = [] } = {}) {
300
+ const out = new Map();
301
+ const put = (v) => {
302
+ if (!v) return;
303
+ for (const k of [v.pr != null ? `pr:${v.pr}` : null, v.issue != null ? `issue:${v.issue}` : null]) {
304
+ if (!k) continue;
305
+ const cur = out.get(k);
306
+ if (!cur || String(v.ts ?? "") >= String(cur.ts ?? "")) out.set(k, v);
307
+ }
308
+ };
309
+ const int = (x) => (Number.isSafeInteger(Number(x)) && Number(x) > 0 ? Number(x) : null);
310
+ for (const row of batchRows) {
311
+ const c = row?.conformance;
312
+ if (!c || typeof c !== "object") continue;
313
+ const v = verdictOf({ mode: c.mode, would: c.would, merged: row.outcome === "merged", failures: c.kinds });
314
+ if (v) put({ issue: int(row.issue), pr: int(row.pr), ...v, ts: row.ts ?? row.created ?? "", source: "batch" });
315
+ }
316
+ for (const r of runs) {
317
+ if (!r?.finished) continue;
318
+ const v = verdictOf({ mode: r.conformanceMode, would: r.shadowWould, merged: r.reason === "merged", failures: r.conformanceFailures });
319
+ if (v) put({ issue: int(r.issue), pr: int(r.pr), ...v, ts: r.endTs ?? "", source: "local" });
320
+ }
321
+ const shadows = new Map();
322
+ for (const r of records) {
323
+ if (r?.event !== "conformance_shadow" || r.issue == null) continue;
324
+ const cur = shadows.get(r.issue);
325
+ if (!cur || String(r.ts ?? "") >= String(cur.ts ?? "")) shadows.set(r.issue, r);
326
+ }
327
+ for (const r of records) {
328
+ if (r?.event !== "run_terminal") continue;
329
+ const sh = shadows.get(r.issue);
330
+ const v = verdictOf({ mode: r.conformance_mode, would: r.shadow_would, merged: r.reason === "merged", failures: sh && String(sh.ts ?? "") <= String(r.ts ?? "￿") ? sh.failures : null });
331
+ if (v) put({ issue: int(r.issue), pr: int(r.pr), ...v, ts: r.ts ?? "", source: "github" });
332
+ }
333
+ return out;
334
+ }
335
+
336
+ /** #5210: report.json rows of the repo's local batches, each stamped with its batch's plan.created as `ts` (no network). */
337
+ export function readBatchRows({ batchRoot, repo = null } = {}) {
338
+ const readJson = (f) => { try { return JSON.parse(readFileSync(f, "utf8")); } catch { return null; } };
339
+ const rows = [];
340
+ for (const id of batchRoot && existsSync(batchRoot) ? listBatches(batchRoot) : []) {
341
+ const dir = join(batchRoot, id), plan = readJson(join(dir, "plan.json")) ?? {};
342
+ if (repo && plan.repo && String(plan.repo).toLowerCase() !== String(repo).toLowerCase()) continue;
343
+ for (const row of readJson(join(dir, "report.json"))?.rows ?? []) if (row && typeof row === "object") rows.push({ ...row, ts: typeof plan.created === "string" ? plan.created : "" });
344
+ }
345
+ return rows;
346
+ }
@@ -0,0 +1,52 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * forgedock stats --self-filed (#5207): the share of new issues the pipeline filed itself, by kind, against a 15% target.
5
+ * The kind comes from the deterministic markers and labels the pipeline writes (scripts/file-deferred-followups.sh,
6
+ * scripts/review-finalize.sh, bin/review-staging.mjs), never from the author: lane-created issues share the bot author.
7
+ */
8
+
9
+ export const SELF_FILED_KINDS = Object.freeze(["follow-up", "review-finding", "staging-review", "rollup"]);
10
+ export const SELF_FILED_TARGET = 0.15;
11
+ const ROLLUP_RE = /FORGE:(POSTDEPLOY_ROLLUP|EXTERNAL_BATCH|BACKLOG_BATCH|HOST_BATCH):/;
12
+ const labelNames = (issue) => (issue?.labels ?? []).map((l) => (typeof l === "string" ? l : l?.name)).filter(Boolean);
13
+
14
+ /** The pipeline-filed kind of one issue (precedence rollup, follow-up, staging-review, review-finding), else null. */
15
+ export function selfFiledKind(issue) {
16
+ const body = String(issue?.body ?? ""), title = String(issue?.title ?? "");
17
+ if (ROLLUP_RE.test(body)) return "rollup";
18
+ if (body.includes("FORGE:DEFERRED_FROM") || /^follow-up:/i.test(title)) return "follow-up";
19
+ const labels = labelNames(issue);
20
+ if (labels.includes("staging-review")) return "staging-review";
21
+ if (labels.includes("review-finding")) return "review-finding";
22
+ return null;
23
+ }
24
+
25
+ /** {repo, since, total, pipeline, share, by_kind, target, met}; share is null when no issue was opened in the window. */
26
+ export function selfFiledReport({ issues, since = null, repo = null }) {
27
+ const sinceMs = since ? Date.parse(since) : NaN;
28
+ const inWindow = (issues ?? []).filter((i) => Number.isNaN(sinceMs) || !i?.createdAt || Date.parse(i.createdAt) >= sinceMs);
29
+ const by_kind = Object.fromEntries(SELF_FILED_KINDS.map((k) => [k, 0]));
30
+ for (const i of inWindow) { const k = selfFiledKind(i); if (k) by_kind[k]++; }
31
+ const total = inWindow.length, pipeline = Object.values(by_kind).reduce((a, b) => a + b, 0);
32
+ const share = total ? pipeline / total : null;
33
+ return { repo, since, total, pipeline, share, by_kind, target: SELF_FILED_TARGET, met: share == null ? null : share < SELF_FILED_TARGET };
34
+ }
35
+
36
+ /** The issues created on/after `since` (YYYY-MM-DD). gh: async (args) => stdout. Unreadable output throws (never a silent 0%). */
37
+ export async function gatherIssues({ gh, repo, since }) {
38
+ const out = await gh(["issue", "list", "-R", repo, "--state", "all", "--search", `created:>=${since}`, "--limit", "1000", "--json", "number,title,body,labels,createdAt"]);
39
+ let issues;
40
+ try { issues = JSON.parse(String(out ?? "")); } catch { throw new Error(`self-filed: unreadable gh issue list output for ${repo}`); }
41
+ if (!Array.isArray(issues)) throw new Error(`self-filed: gh issue list for ${repo} did not return a list`);
42
+ return issues;
43
+ }
44
+
45
+ const pct = (x) => (x == null ? "n/a" : `${(x * 100).toFixed(1)}%`);
46
+ /** One line per kind plus the total share against the target. */
47
+ export function renderSelfFiled(r) {
48
+ const lines = [`self-filed issues, ${r.repo ?? "?"} since ${r.since ?? "?"}: ${r.total} new issue${r.total === 1 ? "" : "s"}`];
49
+ for (const k of SELF_FILED_KINDS) lines.push(` ${k.padEnd(15)} ${String(r.by_kind[k]).padStart(5)} ${pct(r.total ? r.by_kind[k] / r.total : null)}`);
50
+ lines.push(` ${"total".padEnd(15)} ${String(r.pipeline).padStart(5)} ${pct(r.share)} (target < ${pct(r.target)}: ${r.met == null ? "n/a" : r.met ? "met" : "not met"})`);
51
+ return lines.join("\n");
52
+ }
@@ -0,0 +1,71 @@
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 { selfFiledKind, selfFiledReport, gatherIssues, renderSelfFiled, SELF_FILED_KINDS, SELF_FILED_TARGET } from "./selffiled.mjs";
6
+ import { buildReport, parseArgs, runStats } from "./index.mjs";
7
+
8
+ const iss = (n, extra = {}) => ({ number: n, title: `issue ${n}`, body: "", labels: [], createdAt: "2026-11-01T00:00:00Z", ...extra });
9
+ const ISSUES = [
10
+ iss(1, { body: "x\n<!-- FORGE:POSTDEPLOY_ROLLUP: default -->\n### #4\n<!-- FORGE:DEFERRED_FROM: #4 -->" }), // rollup wins over follow-up
11
+ iss(2, { body: "<!-- FORGE:EXTERNAL_BATCH: b1 -->" }),
12
+ iss(3, { body: "<!-- FORGE:HOST_BATCH: b1 -->" }),
13
+ iss(4, { body: "<!-- FORGE:BACKLOG_BATCH: b0 -->" }),
14
+ iss(5, { body: "<!-- FORGE:DEFERRED_FROM: #9 -->", labels: [{ name: "review-finding" }] }), // follow-up wins over the label
15
+ iss(6, { title: "follow-up: 3 deferred item(s) from #9" }),
16
+ iss(7, { labels: [{ name: "staging-review" }, { name: "review-finding" }] }),
17
+ iss(8, { labels: ["review-finding"] }),
18
+ ...Array.from({ length: 12 }, (_, i) => iss(100 + i, { labels: [{ name: "bug" }] })),
19
+ iss(200, { createdAt: "2026-09-01T00:00:00Z", body: "<!-- FORGE:EXTERNAL_BATCH: old -->" }), // outside the window
20
+ ];
21
+
22
+ describe("stats --self-filed (#5207)", () => {
23
+ it("classifies by precedence rollup, follow-up, staging-review, review-finding, else null", () => {
24
+ assert.deepEqual(ISSUES.slice(0, 8).map(selfFiledKind), ["rollup", "rollup", "rollup", "rollup", "follow-up", "follow-up", "staging-review", "review-finding"]);
25
+ assert.equal(selfFiledKind(iss(9, { labels: [{ name: "bug" }] })), null);
26
+ assert.equal(selfFiledKind({}), null);
27
+ });
28
+ it("reports the share by kind against the 15% target", () => {
29
+ const r = selfFiledReport({ issues: ISSUES, since: "2026-10-08", repo: "o/r" });
30
+ assert.deepEqual(r.by_kind, { "follow-up": 2, "review-finding": 1, "staging-review": 1, rollup: 4 });
31
+ assert.equal(r.total, 20); assert.equal(r.pipeline, 8); assert.equal(r.share, 0.4);
32
+ assert.equal(r.target, SELF_FILED_TARGET); assert.equal(r.met, false);
33
+ assert.equal(selfFiledReport({ issues: ISSUES.slice(8, 20).concat(ISSUES[7]), since: "2026-10-08" }).met, true);
34
+ const none = selfFiledReport({ issues: [], since: "2026-10-08" });
35
+ assert.equal(none.share, null); assert.equal(none.met, null);
36
+ const out = renderSelfFiled(r);
37
+ for (const k of SELF_FILED_KINDS) assert.match(out, new RegExp(`^ ${k} +\\d+ `, "m"));
38
+ assert.match(out, /total +8 +40\.0% \(target < 15\.0%: not met\)/);
39
+ });
40
+ it("gatherIssues lists every state since the date; unreadable output is an error, never 0%", async () => {
41
+ const calls = [];
42
+ const gh = async (a) => { calls.push(a); return JSON.stringify(ISSUES); };
43
+ assert.equal((await gatherIssues({ gh, repo: "o/r", since: "2026-10-08" })).length, ISSUES.length);
44
+ assert.deepEqual(calls[0], ["issue", "list", "-R", "o/r", "--state", "all", "--search", "created:>=2026-10-08", "--limit", "1000", "--json", "number,title,body,labels,createdAt"]);
45
+ await assert.rejects(gatherIssues({ gh: async () => "rate limited", repo: "o/r", since: "2026-10-08" }), /unreadable/);
46
+ await assert.rejects(gatherIssues({ gh: async () => "{}", repo: "o/r", since: "2026-10-08" }), /did not return a list/);
47
+ });
48
+ it("wires --self-filed through parseArgs and buildReport (default window: 30 days)", async () => {
49
+ assert.equal(parseArgs(["--self-filed"]).selfFiled, true); assert.equal(parseArgs([]).selfFiled, false);
50
+ let seen;
51
+ const gh = async (a) => { seen = a; return JSON.stringify(ISSUES); };
52
+ const r = await buildReport({ ...parseArgs(["--self-filed"]), repo: "o/r" }, { gh, now: () => Date.parse("2026-11-07T00:00:00Z") });
53
+ assert.equal(seen[seen.indexOf("--search") + 1], "created:>=2026-10-08");
54
+ assert.equal(r.query.self_filed.pipeline, 8);
55
+ const d = await buildReport({ ...parseArgs(["--self-filed", "--since", "2026-11-02"]), repo: "o/r" }, { gh });
56
+ assert.equal(d.query.self_filed.since, "2026-11-02"); assert.equal(d.query.self_filed.total, 0);
57
+ await assert.rejects(buildReport({ ...parseArgs(["--self-filed", "--since", "1.2.0"]), repo: "o/r" }, { gh }), /must be a date/);
58
+ });
59
+ it("runStats prints the report, or exits 1 on unreadable gh output", async () => {
60
+ const write = process.stdout.write, err = process.stderr.write; let out = "";
61
+ process.stdout.write = (t) => { out += t; return true; }; process.stderr.write = () => true;
62
+ try {
63
+ assert.equal(await runStats(["--self-filed", "--repo", "o/r", "--since", "2026-10-08"], { gh: async () => JSON.stringify(ISSUES) }), 0);
64
+ assert.match(out, /self-filed issues, o\/r since 2026-10-08: 20 new issues/);
65
+ out = "";
66
+ assert.equal(await runStats(["--self-filed", "--repo", "o/r", "--json"], { gh: async () => JSON.stringify(ISSUES) }), 0);
67
+ assert.equal(JSON.parse(out).query.self_filed.target, 0.15);
68
+ assert.equal(await runStats(["--self-filed", "--repo", "o/r"], { gh: async () => "not json" }), 1);
69
+ } finally { process.stdout.write = write; process.stderr.write = err; }
70
+ });
71
+ });
@@ -105,7 +105,7 @@ remaining maintenance once no feature is pending; otherwise the rest ends `held
105
105
  `forgedock orchestrate --add <id> N...` (or `--resume <id> N...`), under its K and DAG; never start a second batch
106
106
  for them. After a decision (a `FORGE:DECISION` posted and `needs-human` removed), a blocked issue that already ended in the batch
107
107
  (`needs-human`, `invalid`, `skipped`, `dependency-*`, `ci-pending`, `deferred`) returns to it with
108
- `forgedock orchestrate --requeue <id> N... --reason "..."` (refused while it is labelled `needs-human` or closed; skipped dependents
108
+ `forgedock orchestrate --requeue <id> N... --reason "..."` (it also releases an issue shown as `paused (quota) until <ISO>`) (refused while it is labelled `needs-human` or closed; skipped dependents
109
109
  return to pending with it; a finished batch is reopened); `--add` on a `skipped` issue re-queues it (other ended issues still report `already in batch`). A dependency-skipped issue shows as `waiting on #X` while the batch runs (the blocker is re-checked each pass; merged or closed re-admits it, closed as not planned keeps it skipped) and ends `skipped` only if the blocker never resolved. Its pre-filter still closes already-fixed ones. The runner requeues `deferred` lanes by code (host busy and a full sandbox pool after their
110
110
  retry-in, uncapped, a usage limit holds admissions for that account (backend identity) until the reset, never capped, across every batch on
111
111
  the host; `forgedock limits show|clear <id>|--all` lists or drops holds; transient merge/push/idle failures back off; other
@@ -241,6 +241,9 @@ For each named volume found: determine its container mount point. Named volumes
241
241
  **Severity**: HIGH — filesystem writes fail silently at runtime with `PermissionError`; no startup crash, so the failure only surfaces when the code path executes.
242
242
  **Evidence**: When a container's runtime user changes from root to a non-root UID, Docker named volumes retain their existing ownership (root:root). Any code path that writes to a path under a named volume mount point will fail with `[Errno 13] Permission denied`. The fix is to add `chown -R <user>:<group> <mount_point>` to the entrypoint script before the privilege-drop `exec` call. <!-- Added: forge#323 -->
243
243
 
244
+ ### Step 2.10: Production side effects × frequency
245
+ If the diff adds or changes code that creates, mutates, deletes or sends production resources (accounts, payments, emails, DNS, side-effecting external calls) and it runs from a loop, cron, `schedule:`, probe/monitor or retry, state: (a) runs/day derived from the schedule; (b) downstream effects (metrics, emails, credits, billing); (c) idempotent or rate-bounded? Per-cycle or unbounded without explicit justification, or cleanup that leaves downstream effects: CONFIRMED HIGH, blocking.
246
+
244
247
  ## Step 3: Code Quality Scan
245
248
  1. **Error handling**: Exceptions swallowed silently, generic except clauses
246
249
  2. **Resource leaks**: Unclosed connections, files, async tasks not awaited
@@ -392,6 +395,7 @@ EOF
392
395
  | XSS | Step 2.6 | COVERED | |
393
396
  | Token privilege confusion | Step 2.7 | COVERED | |
394
397
  | Unbounded resource consumption | Step 2.8 | COVERED | |
398
+ | Per-cycle production side effects | Step 2.10 | COVERED | #5238 |
395
399
  | API information disclosure | Step 2.9 (a/b/c) | COVERED | #302 |
396
400
  | Port bind address exposure | Step 2.5A | COVERED | #296 |
397
401
  | Missing container USER directive | Step 2.5B | COVERED | #296 |
@@ -10,6 +10,8 @@ install: core
10
10
 
11
11
  # Staging Review
12
12
 
13
+ > **Default path:** `forgedock release [--repo R] [--merge] [--resume <id>]` runs the whole staging→default release (PR, review panel, findings, gate, promotion, post-merge) as one resumable job; issue-watch `mode: release` starts it for the deploy PR it opens. This spec is the manual fallback when the job is unavailable or you need to drive a step by hand.
14
+
13
15
  > **Skill names**: `{FORGE_SKILL_PREFIX}` is `forgedock:` (plugin install) or empty (`install.sh`), resolved once per run by `commands/work-on.md` § Skill Name Resolution. If the skill is not found under either name, STOP and report "skill not found" — never run the phase inline.
14
16
 
15
17
  **Trigger**: Invoked by the orchestrator via `Skill("{FORGE_SKILL_PREFIX}review-pr-staging", $ARGUMENTS)`, or directly with `$ARGUMENTS` = "staging", a PR number targeting main, or "staging:feature".