forgedock 1.71.0 → 1.72.1

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 (53) hide show
  1. package/bin/config-schema.mjs +1 -1
  2. package/bin/engine/outcome-codes.mjs +5 -4
  3. package/bin/init-detect.mjs +35 -2
  4. package/bin/lean/admit.mjs +152 -0
  5. package/bin/lean/admit.test.mjs +120 -0
  6. package/bin/lean/attempts.mjs +1 -1
  7. package/bin/lean/batch.mjs +8 -0
  8. package/bin/lean/batch.test.mjs +17 -0
  9. package/bin/lean/concurrency.mjs +7 -2
  10. package/bin/lean/concurrency.test.mjs +16 -3
  11. package/bin/lean/conformance.mjs +2 -0
  12. package/bin/lean/conformance.test.mjs +9 -0
  13. package/bin/lean/effects.mjs +22 -0
  14. package/bin/lean/failure-census.mjs +1 -1
  15. package/bin/lean/heavy.mjs +20 -6
  16. package/bin/lean/heavy.test.mjs +24 -3
  17. package/bin/lean/lean.mjs +97 -5
  18. package/bin/lean/lean.test.mjs +38 -0
  19. package/bin/lean/orchestrate-envhold.test.mjs +14 -0
  20. package/bin/lean/orchestrate-heldroot.test.mjs +32 -0
  21. package/bin/lean/orchestrate.mjs +33 -11
  22. package/bin/lean/queuecause.mjs +42 -0
  23. package/bin/lean/release-cigreen.mjs +18 -4
  24. package/bin/lean/release-cigreen.test.mjs +23 -0
  25. package/bin/lean/release-review.mjs +24 -10
  26. package/bin/lean/release-review.test.mjs +65 -0
  27. package/bin/lean/release.mjs +1 -1
  28. package/bin/lean/release.test.mjs +19 -0
  29. package/bin/lean/schedd.mjs +24 -1
  30. package/bin/lean/schedd.test.mjs +38 -0
  31. package/bin/pool/agent.mjs +61 -18
  32. package/bin/pool/docker-dns.mjs +39 -0
  33. package/bin/pool/docker.mjs +7 -3
  34. package/bin/pool/engine-placement.test.mjs +2 -2
  35. package/bin/pool/image-manifest.test.mjs +13 -0
  36. package/bin/pool/lane-image.mjs +56 -15
  37. package/bin/pool/lane-tools.mjs +26 -12
  38. package/bin/pool/lane-tools.test.mjs +63 -1
  39. package/bin/pool/project-layer.mjs +2 -2
  40. package/bin/pool/router.mjs +2 -1
  41. package/bin/review-staging.mjs +14 -11
  42. package/bin/review-staging.test.mjs +20 -1
  43. package/bin/stats/escapes.mjs +124 -0
  44. package/bin/stats/index.mjs +5 -1
  45. package/bin/stats/quality-ledger.mjs +49 -0
  46. package/bin/stats/quality-ledger.test.mjs +84 -0
  47. package/bin/stats/weekly.mjs +230 -0
  48. package/docs/OUTCOME-CODES.md +2 -1
  49. package/package.json +1 -1
  50. package/pool/README.md +2 -0
  51. package/pool/image/Dockerfile +4 -1
  52. package/pool/image/lane-tools-sets.json +6 -0
  53. package/scripts/lane-variants.mjs +51 -0
@@ -12,7 +12,7 @@ import { join, posix } from "node:path";
12
12
  import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
13
13
  import { tmpdir } from "node:os";
14
14
  import { detect, pyHint, depCommands } from "../lean/depcache.mjs";
15
- import { isLaneToolsTagOf } from "./lane-tools.mjs";
15
+ import { isLaneToolsTagOf, buildErrorTail } from "./lane-tools.mjs";
16
16
 
17
17
  const JS = new Set(["pnpm", "npm", "yarn"]);
18
18
  const MANIFESTS = ["package.json", "pnpm-workspace.yaml", ".npmrc", ".yarnrc.yml", "pyproject.toml", ".python-version"];
@@ -116,7 +116,7 @@ async function buildLayer({ tag, baseImage, deps, docker, buildTimeoutMs }) {
116
116
  const timeout = new Promise((_, rej) => { timer = setTimeout(() => rej(new Error(`build timed out after ${buildTimeoutMs}ms`)), buildTimeoutMs); });
117
117
  await Promise.race([docker.build(dir, tag, {}), timeout]);
118
118
  } catch (e) {
119
- throw new Error(`project layer ${tag} build failed: ${String(e.stderr || e.message).slice(0, 300)}`);
119
+ throw new Error(`project layer ${tag} build failed: ${buildErrorTail(e)}`);
120
120
  } finally { clearTimeout(timer); rmSync(dir, { recursive: true, force: true }); }
121
121
  return tag;
122
122
  }
@@ -360,7 +360,8 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
360
360
  const elastic = c.elastic_lanes === true && Number.isFinite(c.cpus_free_elastic) && Number.isFinite(c.mem_free_gb_elastic); // #6047: base reservations plus held heavy tokens
361
361
  const cpusFree = prio === "normal" && Number.isFinite(c.cpus_free_unreserved) ? c.cpus_free_unreserved : elastic ? c.cpus_free_elastic : c.cpus_free;
362
362
  const memFree = prio === "normal" && Number.isFinite(c.mem_free_unreserved_gb) ? c.mem_free_unreserved_gb : elastic ? c.mem_free_gb_elastic : c.mem_free_gb;
363
- return cpusFree >= size.cpus && memFree >= size.mem_gb;
363
+ const eb = elastic && c.elastic_base && Number.isFinite(c.elastic_base.cpus) && Number.isFinite(c.elastic_base.mem_gb) ? c.elastic_base : null; // #6204: elastic hosts charge a lane its measured footprint
364
+ return cpusFree >= (eb ? Math.min(size.cpus, eb.cpus) : size.cpus) && memFree >= (eb ? Math.min(size.mem_gb, eb.mem_gb) : size.mem_gb);
364
365
  };
365
366
  const headroom = (c, spec) => (spec?.priority === "borrow" && Number.isFinite(c.cpus_free_unreserved) ? c.cpus_free_unreserved : 0);
366
367
  // #5949: the dispatcher seeds a repo mirror before launch. The agent that will own the sandbox is picked here (the placing agent
@@ -152,7 +152,7 @@ export function readConfig(io) {
152
152
  try { cfg = parseForgeYaml(io.readFile(path)) ?? {}; } catch { /* absent config: owner/repo check below fails */ }
153
153
  const owner = cfg.project?.owner, repo = cfg.project?.repo;
154
154
  if (!owner || !repo) throw new Stop(1, [`review-staging: project.owner/project.repo not set in ${path}`]);
155
- return { ghRepo: `${owner}/${repo}`, defaultBranch: cfg.branches?.default || "main", stagingBranch: cfg.branches?.staging || "staging", featurePattern: typeof cfg.branches?.feature_pattern === "string" && cfg.branches.feature_pattern.includes("{slug}") ? cfg.branches.feature_pattern : null, configPath: path, extraRequiredChecks: Array.isArray(cfg.gate?.required_checks) ? cfg.gate.required_checks.map((x) => String(x).trim()).filter(Boolean) : [], sandboxRepo: SANDBOX_RE.test(String(cfg.selftest?.sandbox_repo ?? "").trim()) ? String(cfg.selftest.sandbox_repo).trim() : "", sandboxRaw: String(cfg.selftest?.sandbox_repo ?? "").trim() };
155
+ return { blockSeverity: ["CRITICAL", "HIGH", "MEDIUM"].includes(String(cfg.release?.block_severity ?? "").trim().toUpperCase()) ? String(cfg.release.block_severity).trim().toUpperCase() : "HIGH", ghRepo: `${owner}/${repo}`, defaultBranch: cfg.branches?.default || "main", stagingBranch: cfg.branches?.staging || "staging", featurePattern: typeof cfg.branches?.feature_pattern === "string" && cfg.branches.feature_pattern.includes("{slug}") ? cfg.branches.feature_pattern : null, configPath: path, extraRequiredChecks: Array.isArray(cfg.gate?.required_checks) ? cfg.gate.required_checks.map((x) => String(x).trim()).filter(Boolean) : [], sandboxRepo: SANDBOX_RE.test(String(cfg.selftest?.sandbox_repo ?? "").trim()) ? String(cfg.selftest.sandbox_repo).trim() : "", sandboxRaw: String(cfg.selftest?.sandbox_repo ?? "").trim() };
156
156
  }
157
157
 
158
158
  /** Same derivation as commands/review-pr-staging.md Phase -1 (and scripts/lib/fence-bootstrap.sh). */
@@ -596,12 +596,13 @@ export function ciState(checks, required = []) {
596
596
  return { pending, failing: names((k) => k.bucket === "fail" || k.bucket === "cancel").filter((n) => !pending.includes(n)), green: !pending.length && !rows.length };
597
597
  }
598
598
 
599
- /** Pre-dispatch CI read: `null` when green (or the PR has no checks), else `{pending, failing}`. An unreadable read fails closed. */
600
- async function ciNotGreen(io, c, pr, env) {
599
+ /** Pre-dispatch CI read: `null` when green (or no checks are required), else `{pending, failing}`. An unreadable read fails closed. */
600
+ export async function ciNotGreen(io, c, pr, env) {
601
601
  const r = await io.run("gh", ["pr", "checks", String(pr), "-R", c.ghRepo, "--json", "name,bucket,link"], { env, cwd: io.cwd });
602
- const checks = r.code === 0 || r.code === 8 ? parseChecks(r.stdout) : null;
602
+ let checks = r.code === 0 || r.code === 8 ? parseChecks(r.stdout) : null;
603
+ // Right after a push no checks are registered yet: that is "required checks pending", not green (ciState then compares against the required set).
604
+ if (!checks && /no checks reported/i.test(`${r.stderr ?? ""}${r.stdout ?? ""}`)) checks = [];
603
605
  if (!checks) {
604
- if (/no checks reported/i.test(`${r.stderr ?? ""}${r.stdout ?? ""}`)) return null;
605
606
  return { pending: [], failing: ["checks unreadable"] };
606
607
  }
607
608
  const read = await requiredChecksRead({ gh: io.gh, repo: c.ghRepo, lane: c.defaultBranch });
@@ -642,14 +643,16 @@ export function countFailingChecks(checks) {
642
643
  return classifyChecks(checks).blocking;
643
644
  }
644
645
 
645
- /** Phase 8 verdict from the deterministic inputs (CI, test gate, CONFIRMED CRITICAL/HIGH). */
646
- export function stagingVerdict({ ciFailing, testGateInvalid, acceptanceBlocked = null, confirmedCritical, confirmedHigh }) {
646
+ /** Phase 8 verdict from the deterministic inputs (CI, test gate, CONFIRMED findings at or above `blockSeverity`, default HIGH; CRITICAL always blocks). */
647
+ export function stagingVerdict({ ciFailing, testGateInvalid, acceptanceBlocked = null, confirmedCritical, confirmedHigh, confirmedMedium = 0, blockSeverity = "HIGH" }) {
647
648
  if (acceptanceBlocked) return { verdict: "BLOCK DEPLOY", why: `feature acceptance blocked: ${acceptanceBlocked}` };
648
649
  if (ciFailing > 0) return { verdict: "BLOCK DEPLOY", why: `CI failing (${ciFailing} required check(s) red; forgedock/verify, forge/deploy-gate and the gate-marker check excluded)` };
649
650
  if (testGateInvalid) return { verdict: "BLOCK DEPLOY", why: "test-gate result missing/invalid (fail closed)" };
650
651
  if (confirmedCritical > 0) return { verdict: "BLOCK DEPLOY", why: `${confirmedCritical} CONFIRMED CRITICAL finding(s)` };
651
- if (confirmedHigh > 0) return { verdict: "NEEDS FIXES FIRST", why: `${confirmedHigh} CONFIRMED HIGH finding(s)` };
652
- return { verdict: "APPROVE FOR DEPLOY", why: "no CI failure, no blocking test gate, no CONFIRMED CRITICAL/HIGH finding" };
652
+ const sev = String(blockSeverity).toUpperCase();
653
+ if (confirmedHigh > 0 && sev !== "CRITICAL") return { verdict: "NEEDS FIXES FIRST", why: `${confirmedHigh} CONFIRMED HIGH finding(s)` };
654
+ if (confirmedMedium > 0 && sev === "MEDIUM") return { verdict: "NEEDS FIXES FIRST", why: `${confirmedMedium} CONFIRMED MEDIUM finding(s)` };
655
+ return { verdict: "APPROVE FOR DEPLOY", why: `no CI failure, no blocking test gate, no CONFIRMED finding at or above ${sev === "CRITICAL" || sev === "MEDIUM" ? sev : "HIGH"}` };
653
656
  }
654
657
 
655
658
  /**
@@ -696,7 +699,7 @@ async function summary(a, io) {
696
699
  }
697
700
 
698
701
  const acceptanceBlocked = await acceptanceBlock(io, c, pr, tg);
699
- const v = stagingVerdict({ ciFailing, testGateInvalid: tg.invalid, acceptanceBlocked, confirmedCritical: st.confirmedCritical, confirmedHigh: st.confirmedHigh });
702
+ const v = stagingVerdict({ ciFailing, testGateInvalid: tg.invalid, acceptanceBlocked, confirmedCritical: st.confirmedCritical, confirmedHigh: st.confirmedHigh, confirmedMedium: st.confirmedMedium, blockSeverity: c.blockSeverity });
700
703
  const pass = v.verdict === "APPROVE FOR DEPLOY";
701
704
  const marker = pass ? "FORGE:GATE_PASS" : "FORGE:GATE_FAILURE";
702
705
  const bundle = (st.bundle ?? []).join(" ");
@@ -721,7 +724,7 @@ async function summary(a, io) {
721
724
  "| Domain | Result | Notes |",
722
725
  "|--------|--------|-------|",
723
726
  `| CI | ${ciFailing > 0 ? "FAIL" : "PASS"} | ${ciFailing} failing required check(s), forgedock/verify, forge/deploy-gate and the gate-marker check excluded${warnings.length ? `; ${warnings.length} non-required check(s) red, non-blocking warning: ${warnings.join(", ")}` : ""} |`,
724
- `| Findings | ${st.confirmedCritical} CRITICAL / ${st.confirmedHigh} HIGH (CONFIRMED) | per-domain verdicts are in the FORGE:REVIEW-AGENT comments |`,
727
+ `| Findings | ${st.confirmedCritical} CRITICAL / ${st.confirmedHigh} HIGH / ${st.confirmedMedium ?? 0} MEDIUM (CONFIRMED) | blocks at ${c.blockSeverity ?? "HIGH"} and above; per-domain verdicts are in the FORGE:REVIEW-AGENT comments |`,
725
728
  `| **Test Gate** | \`${tg.verdict}\` | \`${tg.reason || "Phase 6.5 not run"}\` |`,
726
729
  ...(acceptanceBlocked ? [`| **Feature acceptance** | \`BLOCK\` | ${acceptanceBlocked.replace(/\|/g, "/")} |`] : []),
727
730
  "",
@@ -2,7 +2,7 @@
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  import { describe, it } from "node:test";
4
4
  import assert from "node:assert/strict";
5
- import { stagingVerdict } from "./review-staging.mjs";
5
+ import { stagingVerdict, ciNotGreen } from "./review-staging.mjs";
6
6
 
7
7
  const ok = { ciFailing: 0, testGateInvalid: false, confirmedCritical: 0, confirmedHigh: 0 };
8
8
 
@@ -16,3 +16,22 @@ describe("stagingVerdict feature acceptance (#5336)", () => {
16
16
  assert.match(v.why, /feature acceptance blocked: Test Gate SKIP/);
17
17
  });
18
18
  });
19
+
20
+ describe("ciNotGreen: no checks reported yet", () => {
21
+ const mk = (required) => ({
22
+ cwd: ".",
23
+ run: async () => ({ code: 1, stdout: "", stderr: "no checks reported on the 'x' branch" }),
24
+ gh: async (args) => {
25
+ if (String(args.join(" ")).includes("required_status_checks") && !args.includes("--paginate")) return JSON.stringify({ contexts: required });
26
+ return "";
27
+ },
28
+ });
29
+ const c = { ghRepo: "o/r", defaultBranch: "main", extraRequiredChecks: [] };
30
+ it("is pending (not green) when required checks are not registered yet", async () => {
31
+ const st = await ciNotGreen(mk(["build"]), c, 1, {});
32
+ assert.deepEqual(st?.pending, ["build"]);
33
+ });
34
+ it("stays green when no checks are required", async () => {
35
+ assert.equal(await ciNotGreen(mk([]), c, 1, {}), null);
36
+ });
37
+ });
@@ -0,0 +1,124 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * `forgedock stats escapes [--days 14] [--repo R] [--json]` (#6203): the escape linker. For lane PRs merged in the window, find
5
+ * later fix or revert PRs and bug issues that cite the lane PR number or its issue (within WINDOW_DAYS of the merge), plus
6
+ * reopen events on the lane's issue. Deterministic, gh reads only, no model. A citation count is a lower bound on the true
7
+ * escape rate. Results merge into ~/.forge/stats-cache/escapes-<owner>__<repo>.json, which the weekly scorecard reads.
8
+ */
9
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
10
+ import { dirname, join } from "node:path";
11
+ import { defaultGh, isValidRepo } from "./github-source.mjs";
12
+ import { resolveRepo } from "./index.mjs";
13
+ import { forgeHome } from "./weekly.mjs";
14
+
15
+ export const WINDOW_DAYS = 14;
16
+ const DAY = 86400000;
17
+ const labelsOf = (x) => (x.labels ?? []).map((l) => String(l?.name ?? l).toLowerCase());
18
+ const cites = (text, n) => new RegExp(`(^|[^\\w/])#${n}(?!\\d)`).test(String(text ?? ""));
19
+
20
+ /** The lane's issue number: from the lane branch, else a `Closes #N` in the body. */
21
+ export function laneIssueOf(pr) {
22
+ const b = /^feat\/issue-(\d+)(-|$)/.exec(pr.headRefName ?? "")?.[1];
23
+ if (b) return Number(b);
24
+ const c = /\b(?:closes|fixes|resolves)\s+#(\d+)/i.exec(pr.body ?? "")?.[1];
25
+ return c ? Number(c) : null;
26
+ }
27
+ export const isFixPr = (p) => /^(revert|fix|hotfix)\b/i.test(p.title ?? "") || /^(fix|revert|hotfix)\//i.test(p.headRefName ?? "");
28
+ export const isBugIssue = (i) => labelsOf(i).some((l) => /^(bug|regression|revert|type:bug)$/.test(l) || l.includes("regression"));
29
+ const CAUSAL = /regress|introduc|broke|breaks|caused|revert|follow.?up|fallout|missed|incomplete|hotfix|left behind|undid/i;
30
+ /** A citation of #n that blames it: the number sits within 100 chars of a causal word (a bare mention in a tracker does not count). */
31
+ export const blames = (text, n) => {
32
+ const t = String(text ?? ""), re = new RegExp(`(^|[^\\w/])#${n}(?!\\d)`, "g");
33
+ for (let m; (m = re.exec(t));) if (CAUSAL.test(t.slice(Math.max(0, m.index - 100), m.index + 100))) return true;
34
+ return false;
35
+ };
36
+
37
+ /** Pure link step: lane PRs, candidate PRs and issues, reopen counts -> per-PR escape records. */
38
+ export function linkEscapes({ lanePrs, candPrs, candIssues, reopens = new Map(), windowDays = WINDOW_DAYS }) {
39
+ return lanePrs.map((p) => {
40
+ const issue = laneIssueOf(p), t0 = Date.parse(p.mergedAt), t1 = t0 + windowDays * DAY, links = [];
41
+ const hit = (x, kind) => {
42
+ if (x.number === p.number || x.number === issue) return;
43
+ const created = Date.parse(x.createdAt);
44
+ if (!(created > t0 && created <= t1)) return;
45
+ // fix/revert PRs may cite the lane PR directly; every other citation (the lane's issue, or a bug issue) must blame it
46
+ const direct = kind !== "bug_issue" && (cites(x.title, p.number) || cites(x.body, p.number));
47
+ const blamed = blames(x.title, p.number) || blames(x.body, p.number) || (issue && (blames(x.title, issue) || blames(x.body, issue)));
48
+ if (direct || blamed) links.push({ kind, number: x.number });
49
+ };
50
+ for (const x of candPrs) if (isFixPr(x)) hit(x, /^revert/i.test(x.title ?? "") ? "revert_pr" : "fix_pr");
51
+ for (const x of candIssues) if (isBugIssue(x)) hit(x, "bug_issue");
52
+ const reopened = issue ? (reopens.get(issue) ?? 0) : 0;
53
+ return { pr: p.number, issue, mergedAt: p.mergedAt, links, reopened, escaped: links.length > 0 || reopened > 0 };
54
+ });
55
+ }
56
+
57
+ const readdirSyncSafe = (d) => { try { return readdirSync(d); } catch { return []; } };
58
+ const cachePath = (home, repo) => join(home, "stats-cache", `escapes-${String(repo).replace("/", "__")}.json`);
59
+ /** Map "PR number" -> escaped boolean for the weekly scorecard; null without a cache. */
60
+ export function readEscapeCache({ home = forgeHome(), repo = null } = {}) {
61
+ const repos = repo ? [repo] : [];
62
+ const m = new Map();
63
+ for (const r of repos.length ? repos : []) { try { for (const [pr, v] of Object.entries(JSON.parse(readFileSync(cachePath(home, r), "utf8")).prs ?? {})) m.set(Number(pr), Boolean(v.escaped)); } catch { /* none */ } }
64
+ if (!repo) { // no repo given: every cached repo
65
+ try { for (const f of readdirSyncSafe(join(home, "stats-cache"))) if (f.startsWith("escapes-")) for (const [pr, v] of Object.entries(JSON.parse(readFileSync(join(home, "stats-cache", f), "utf8")).prs ?? {})) m.set(Number(pr), Boolean(v.escaped)); } catch { /* none */ }
66
+ }
67
+ return m.size ? m : null;
68
+ }
69
+
70
+ export async function gatherEscapes({ repo, days = WINDOW_DAYS, gh = defaultGh, now = Date.now(), windowDays = WINDOW_DAYS } = {}) {
71
+ const day = (ms) => new Date(ms).toISOString().slice(0, 10);
72
+ const from = day(now - days * DAY), upto = day(now - 0);
73
+ const j = async (args) => JSON.parse(await gh(args) || "[]");
74
+ const merged = await j(["pr", "list", "-R", repo, "--state", "merged", "--search", `merged:>=${from}`, "--limit", "1000", "--json", "number,title,body,headRefName,mergedAt"]);
75
+ const lanePrs = merged.filter((p) => laneIssueOf(p) != null && /^feat\/issue-\d+/.test(p.headRefName ?? ""));
76
+ const candFrom = from;
77
+ const candPrs = await j(["pr", "list", "-R", repo, "--state", "all", "--search", `created:>=${candFrom}`, "--limit", "1000", "--json", "number,title,body,headRefName,createdAt"]);
78
+ const candIssues = await j(["issue", "list", "-R", repo, "--state", "all", "--search", `created:>=${candFrom}`, "--limit", "1000", "--json", "number,title,body,labels,createdAt"]);
79
+ const reopens = new Map(), issues = [...new Set(lanePrs.map(laneIssueOf))];
80
+ let i = 0;
81
+ await Promise.all(Array.from({ length: 6 }, async () => {
82
+ for (;;) {
83
+ const n = issues[i++]; if (n === undefined) return;
84
+ const pr = lanePrs.find((p) => laneIssueOf(p) === n), t0 = Date.parse(pr.mergedAt);
85
+ try {
86
+ const ev = JSON.parse(await gh(["api", `repos/${repo}/issues/${n}/events`, "--paginate", "--jq", "[.[] | select(.event==\"reopened\") | .created_at]"]).then((s) => `[${String(s).replace(/\]\s*\[/g, ",").replace(/^\[|\]$/g, "")}]`) || "[]");
87
+ reopens.set(n, ev.filter((t) => Date.parse(t) > t0 && Date.parse(t) <= t0 + windowDays * DAY).length);
88
+ } catch { /* a missing events read is not a reopen */ }
89
+ }
90
+ }));
91
+ return { upto, records: linkEscapes({ lanePrs, candPrs, candIssues, reopens, windowDays }) };
92
+ }
93
+
94
+ export function summarise(records) {
95
+ const done = records.filter((r) => Date.parse(r.mergedAt) <= Date.now() - WINDOW_DAYS * DAY), esc = (rs) => rs.filter((r) => r.escaped).length;
96
+ return { lane_prs: records.length, escaped: esc(records), escape_pct: records.length ? esc(records) / records.length : null,
97
+ matured_prs: done.length, matured_escaped: esc(done), matured_escape_pct: done.length ? esc(done) / done.length : null,
98
+ by_kind: records.flatMap((r) => r.links.map((l) => l.kind)).reduce((a, k) => ({ ...a, [k]: (a[k] ?? 0) + 1 }), {}), reopened: records.filter((r) => r.reopened > 0).length };
99
+ }
100
+
101
+ export function renderEscapes(records, repo, days) {
102
+ const s = summarise(records), p = (v) => (v == null ? "n/a" : `${(v * 100).toFixed(1)}%`);
103
+ const lines = [`Escapes for ${repo}: lane PRs merged in the last ${days}d, linked to fix/revert PRs and bug issues citing the PR or its issue within ${WINDOW_DAYS}d, plus reopens.`,
104
+ `lane PRs ${s.lane_prs} escaped ${s.escaped} escape ${p(s.escape_pct)} (matured ${WINDOW_DAYS}d+: ${s.matured_escaped}/${s.matured_prs} = ${p(s.matured_escape_pct)}) reopened ${s.reopened}`,
105
+ `links by kind: ${Object.entries(s.by_kind).map(([k, n]) => `${k} ${n}`).join(", ") || "none"}. Citation-based, so a lower bound.`];
106
+ for (const r of records.filter((x) => x.escaped)) lines.push(` PR #${r.pr} (issue ${r.issue ?? "?"}): ${r.links.map((l) => `${l.kind} #${l.number}`).join(", ")}${r.reopened ? ` reopened x${r.reopened}` : ""}`);
107
+ return `${lines.join("\n")}\n`;
108
+ }
109
+
110
+ export async function runEscapes(argv, deps = {}) {
111
+ const val = (n) => { const i = argv.indexOf(n); return i >= 0 ? argv[i + 1] : null; };
112
+ const days = Number(val("--days") ?? WINDOW_DAYS), repo = resolveRepo(val("--repo"));
113
+ if (!isValidRepo(repo) || !(days > 0)) { process.stderr.write("forgedock stats escapes [--days N] [--repo owner/repo] [--json]\n"); return 2; }
114
+ const { records } = await gatherEscapes({ repo, days, gh: deps.gh ?? defaultGh, now: deps.now?.() ?? Date.now() });
115
+ if (!deps.noCache) { // merge into the cache: a re-run replaces the PRs it covers (the linker is deterministic) and keeps older ones
116
+ const home = deps.home ?? forgeHome(), file = cachePath(home, repo);
117
+ let prs = {}; try { prs = JSON.parse(readFileSync(file, "utf8")).prs ?? {}; } catch { /* new cache */ }
118
+ for (const r of records) prs[r.pr] = r;
119
+ if (!existsSync(dirname(file))) mkdirSync(dirname(file), { recursive: true });
120
+ writeFileSync(file, JSON.stringify({ repo, updated: new Date().toISOString(), prs }));
121
+ }
122
+ (deps.out ?? ((s) => process.stdout.write(s)))(argv.includes("--json") ? `${JSON.stringify({ repo, days, ...summarise(records), records }, null, 2)}\n` : renderEscapes(records, repo, days));
123
+ return 0;
124
+ }
@@ -38,7 +38,9 @@ import { gitProbes } from "./compounding.mjs";
38
38
 
39
39
  const here = dirname(fileURLToPath(import.meta.url));
40
40
 
41
- export const HELP = `Usage: forgedock stats [--since <version|date>] [--repo <owner/repo>] [--json] [--refresh]
41
+ export const HELP = `Usage: forgedock stats escapes [--days 14] [--repo <owner/repo>] [--json] (lane PRs later fixed/reverted/reopened)
42
+ forgedock stats scorecard --weekly [--repo <owner/repo>] [--json] (by week and engine version)
43
+ forgedock stats [--since <version|date>] [--repo <owner/repo>] [--json] [--refresh]
42
44
  [--compact] [--no-local] [--no-cache] [--min-n N] [--release-times FILE]
43
45
  forgedock stats --experiment <id> [--require-met] [--min-n N] [--repo <owner/repo>] [--json]
44
46
  forgedock stats --by version [--post-metrics <pr>] [--min-n N] [--repo <owner/repo>] [--json]
@@ -533,6 +535,8 @@ export async function buildReport(opts, deps = {}) {
533
535
  }
534
536
 
535
537
  export async function runStats(argv, deps = {}) {
538
+ if (argv[0] === "escapes") return (await import("./escapes.mjs")).runEscapes(argv.slice(1), deps); // #6203
539
+ if (argv[0] === "scorecard" && argv.includes("--weekly")) return (await import("./weekly.mjs")).runWeekly(argv.slice(1), deps); // #6203
536
540
  let opts;
537
541
  try { opts = parseArgs(argv); } catch (err) {
538
542
  process.stderr.write(`forgedock stats: ${err.message}\n\n${HELP}`);
@@ -0,0 +1,49 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Quality ledger (#6203): the per-merge MERGE_LEDGER telemetry record, plus the pure helpers the weekly scorecard and the
5
+ * escape linker share. No model calls; everything is derived from run-log / batch-row / GitHub facts that already exist.
6
+ */
7
+ const isNum = (x) => typeof x === "number" && Number.isFinite(x);
8
+ const TEST_PATH_RE = /(^|\/)(tests?|__tests__|spec|e2e)\/|\.(test|spec)\.[cm]?[jt]sx?$|_test\.(go|py)$|(^|\/)test_[^/]+\.py$|Tests?\.(java|kt|cs)$/i;
9
+ export const isTestFile = (p) => TEST_PATH_RE.test(String(p ?? ""));
10
+
11
+ /** Test files added or changed in a diff, from `git diff --name-status` lines or plain names. */
12
+ export function testDelta(files = []) {
13
+ const list = (files ?? []).map((f) => String(f ?? "").trim()).filter(Boolean);
14
+ const tests = list.filter(isTestFile);
15
+ return { files_changed: list.length, test_files: tests.length };
16
+ }
17
+
18
+ const isBotLogin = (l) => /\[bot\]$|^github-actions$|^dependabot$/i.test(String(l ?? ""));
19
+ /** Operator actions visible on the issue during the run: comments by a non-bot author that are not FORGE machine comments. */
20
+ export function humanTouches(comments = [], sinceMs = 0) {
21
+ return (comments ?? []).filter((c) => {
22
+ if (!c || c.__mine === true) return false;
23
+ const login = c.author?.login ?? c.user?.login ?? null;
24
+ if (!login || isBotLogin(login)) return false;
25
+ if (/^\s*<!--\s*FORGE:/.test(String(c.body ?? ""))) return false;
26
+ const at = Date.parse(c.createdAt ?? c.created_at ?? "");
27
+ return !Number.isFinite(at) || at >= sinceMs;
28
+ }).length;
29
+ }
30
+
31
+ /**
32
+ * The MERGE_LEDGER record. first_pass: merged without a recovery run, a relaunch (attempt > 1) or a builder rework round
33
+ * (reviewer, CI, precheck, conformance...) after the first build; null when the builder triggers are not measurable.
34
+ * cost_usd is THIS run's total (one number per run); the scorecard sums distinct runs per lane, never cumulative rows.
35
+ */
36
+ export function buildMergeLedger({ firstPass = null, recovered = false, attempt = 1, ciVerifies = 0, ciFixRounds = 0, files = [], comments = [], sinceMs = 0, costUsd = 0, phases = {}, wallMs = null, engineVersion = null, tier = null, model = null, pr = null } = {}) {
37
+ const clean = firstPass === true && !recovered && !(attempt > 1) && !ciFixRounds;
38
+ const byPhase = {};
39
+ for (const [id, v] of Object.entries(phases ?? {})) if (isNum(v?.ms)) byPhase[id] = Math.round(v.ms);
40
+ return {
41
+ event: "MERGE_LEDGER", ...(Number.isInteger(pr) ? { pr } : {}),
42
+ first_pass: firstPass == null && !recovered && !(attempt > 1) ? null : clean,
43
+ human_touch: humanTouches(comments, sinceMs),
44
+ test_files: testDelta(files).test_files, files_changed: testDelta(files).files_changed,
45
+ ci_attempts: Math.max(0, Math.round(ciVerifies)), ci_fix_rounds: Math.max(0, Math.round(ciFixRounds)),
46
+ cost_usd: Math.round((costUsd || 0) * 1e6) / 1e6, ...(isNum(wallMs) ? { wall_ms: Math.round(wallMs) } : {}), wall_ms_by_phase: byPhase,
47
+ engine_version: engineVersion ?? null, model_tier: tier ?? null, ...(model && model !== "default" ? { model } : {}), attempt, recovered: Boolean(recovered),
48
+ };
49
+ }
@@ -0,0 +1,84 @@
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 { buildMergeLedger, humanTouches, testDelta } from "./quality-ledger.mjs";
6
+ import { createQueueClock } from "../lean/queuecause.mjs";
7
+ import { mergeRecords, queueByCause, spendIncrements, versionAt, weekOf, weeklyScorecard } from "./weekly.mjs";
8
+ import { blames, laneIssueOf, linkEscapes } from "./escapes.mjs";
9
+
10
+ const T0 = Date.parse("2026-11-23T00:00:00Z"), M = 60000;
11
+
12
+ describe("MERGE_LEDGER record", () => {
13
+ it("counts test files and non-bot human comments after the run start", () => {
14
+ assert.deepEqual(testDelta(["bin/a.mjs", "bin/a.test.mjs", "tests/x.py"]), { files_changed: 3, test_files: 2 });
15
+ const c = [{ author: { login: "dev" }, createdAt: "2026-11-23T01:00:00Z", body: "do it" }, { author: { login: "bot[bot]" }, createdAt: "2026-11-23T01:00:00Z", body: "x" }, { author: { login: "dev" }, createdAt: "2026-11-22T01:00:00Z", body: "old" }, { __mine: true, author: { login: "dev" }, body: "mine" }, { author: { login: "dev" }, createdAt: "2026-11-23T02:00:00Z", body: "<!-- FORGE:STATUS -->" }];
16
+ assert.equal(humanTouches(c, T0), 1);
17
+ });
18
+ it("first_pass needs no recovery, relaunch or CI fix round", () => {
19
+ const base = { firstPass: true, costUsd: 1.5, phases: { plan: { ms: 10 } }, engineVersion: "1.71.0", tier: "mid" };
20
+ assert.equal(buildMergeLedger(base).first_pass, true);
21
+ assert.equal(buildMergeLedger({ ...base, ciFixRounds: 1 }).first_pass, false);
22
+ assert.equal(buildMergeLedger({ ...base, recovered: true }).first_pass, false);
23
+ assert.equal(buildMergeLedger({ ...base, attempt: 2 }).first_pass, false);
24
+ assert.equal(buildMergeLedger({ ...base, firstPass: null }).first_pass, null);
25
+ const r = buildMergeLedger(base);
26
+ assert.deepEqual([r.cost_usd, r.engine_version, r.model_tier, r.wall_ms_by_phase], [1.5, "1.71.0", "mid", { plan: 10 }]);
27
+ });
28
+ });
29
+
30
+ describe("queue clock", () => {
31
+ it("accrues per cause, is not reset by a requeue and stops while running", () => {
32
+ const c = createQueueClock();
33
+ c.tick([1], () => "hold", 0);
34
+ c.tick([1], () => "capacity", 10 * M); // 10 min of hold
35
+ const first = c.take(1, 25 * M); // 15 min of capacity, lane starts
36
+ assert.deepEqual(first.causes, { hold: 10 * M, capacity: 15 * M });
37
+ c.tick([1], () => "dependency", 100 * M); // requeued later: the running time is not queue time
38
+ const second = c.take(1, 130 * M);
39
+ assert.equal(second.causes.dependency, 30 * M);
40
+ assert.equal(second.causes.hold, 10 * M);
41
+ const restored = createQueueClock(JSON.parse(JSON.stringify(c.toJSON())));
42
+ assert.equal(restored.take(1, 0).causes.hold, 10 * M);
43
+ });
44
+ });
45
+
46
+ describe("weekly scorecard", () => {
47
+ it("dedupes cumulative recovery rows", () => {
48
+ const rows = [{ t: 1, cost_usd: 1 }, { t: 2, cost_usd: 3 }, { t: 3, cost_usd: 3 }, { t: 4, cost_usd: 0.5 }];
49
+ assert.equal(spendIncrements(rows).reduce((s, x) => s + x.usd, 0), 3.5);
50
+ });
51
+ it("splits queue wait by cause with pause overlay and holds", () => {
52
+ const merged = { t: T0 + 100 * M, wall_ms: 10 * M, outcome: "merged" };
53
+ const q = queueByCause([merged], merged, T0, { pause: [[T0, T0 + 20 * M]], breaker: [], hold: [[T0 + 20 * M, Infinity]] });
54
+ assert.equal(q.causes.pause, 20 * M); assert.equal(q.causes.hold, 70 * M); assert.equal(q.total, 90 * M);
55
+ });
56
+ it("attributes the version through upgrade rows and builds the weekly rows", () => {
57
+ const rows = [{ t: T0, outcome: "added", issue: null, detail: "#1" }, { t: T0 + 50 * M, outcome: "readmitted", issue: 9, detail: "re-admitted: engine version changed v1.60.0 → v1.61.0" },
58
+ { t: T0 + 90 * M, outcome: "merged", issue: 1, pr: 11, cost_usd: 2, wall_ms: 30 * M, first_pass: true, detail: "PR #11" }, { t: T0 + 95 * M, outcome: "needs-human", issue: 2, cost_usd: 1, wall_ms: M }];
59
+ assert.equal(versionAt(rows, "1.70.0", T0), "1.60.0");
60
+ const recs = mergeRecords([{ id: "b20261123-000000-1", repo: "o/r", created: T0, engineVersion: "1.70.0", rows }]);
61
+ const [w] = weeklyScorecard(recs).filter((x) => x.merges);
62
+ assert.equal(weekOf(T0), "2026-11-23");
63
+ assert.deepEqual([w.version, w.merges, w.usd_per_merge, w.first_pass_pct, w.issue_to_merge_median_min], ["1.61.0", 1, 3, 1, 90]);
64
+ const all = weeklyScorecard(recs).reduce((s, x) => s + x.non_merged_spend_pct, 0);
65
+ assert.ok(all > 0);
66
+ });
67
+ });
68
+
69
+ describe("escape linker", () => {
70
+ const lane = { number: 100, title: "feat: x", body: "Closes #50", headRefName: "feat/issue-50-lean", mergedAt: "2026-11-01T00:00:00Z" };
71
+ it("finds the lane issue and only blaming citations", () => {
72
+ assert.equal(laneIssueOf(lane), 50);
73
+ assert.equal(blames("this regressed in #100", 100), true);
74
+ assert.equal(blames("tracker: #100 #101 #102", 100), false);
75
+ });
76
+ it("links fix PRs, bug issues and reopens inside the window only", () => {
77
+ const [r] = linkEscapes({ lanePrs: [lane],
78
+ candPrs: [{ number: 110, title: "fix: bug from #100", body: "", headRefName: "fix/x", createdAt: "2026-11-03T00:00:00Z" }, { number: 111, title: "fix: late #100", body: "", headRefName: "fix/y", createdAt: "2026-12-01T00:00:00Z" }, { number: 112, title: "feat: #100", body: "", headRefName: "feat/z", createdAt: "2026-11-03T00:00:00Z" }],
79
+ candIssues: [{ number: 120, title: "crash", body: "broke after #50", labels: [{ name: "bug" }], createdAt: "2026-11-02T00:00:00Z" }, { number: 121, title: "idea", body: "broke after #50", labels: [], createdAt: "2026-11-02T00:00:00Z" }], reopens: new Map([[50, 1]]) });
80
+ assert.deepEqual(r.links.map((l) => l.number), [110, 120]);
81
+ assert.equal(r.reopened, 1); assert.equal(r.escaped, true);
82
+ assert.equal(linkEscapes({ lanePrs: [lane], candPrs: [], candIssues: [] })[0].escaped, false);
83
+ });
84
+ });