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
@@ -2,7 +2,7 @@
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  import { createServer } from "node:http";
4
4
  import { randomBytes } from "node:crypto";
5
- import { readFileSync, readdirSync } from "node:fs";
5
+ import { readFileSync, readdirSync, statSync } from "node:fs";
6
6
  import { homedir } from "node:os";
7
7
  import { execFile, spawn } from "node:child_process";
8
8
  import { promisify } from "node:util";
@@ -96,7 +96,10 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
96
96
  // Claude access token for sandboxes (#5165): among the logins with 30+ minutes left, the one with the lowest tokenbaton
97
97
  // usage (validity breaks ties). Only the short-lived access token is shared; refresh tokens stay here, so this host
98
98
  // keeps refreshing its own sessions.
99
- function claudeToken() {
99
+ // #5205: the account last handed to each agent, and accounts a lane reported limited (n -> until ms), excluded until then.
100
+ const handed = new Map(), limited = new Map(); // handed: agent -> accounts handed to it
101
+ const MAX_LIMIT_MS = 7 * 86400000; // a reported reset is clamped to now+7d
102
+ function claudeToken(req = null) {
100
103
  const dirs = cfg.claude_config_dirs ?? readdirSync(homedir()).filter((d) => /^\.claude(-\d+)?$/.test(d)).map((d) => join(homedir(), d));
101
104
  const logins = [];
102
105
  for (const d of dirs) {
@@ -108,13 +111,28 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
108
111
  }
109
112
  const src = usageSource(cfg);
110
113
  const usage = readUsage(src, logins.map((l) => l.n).filter((n) => n !== null));
111
- const pick = pickClaudeLogin({ logins, usage, ceilingPct: cfg.usage_ceiling_pct ?? 95, now: now() });
114
+ for (const [k, u] of limited) if (!(u > now())) limited.delete(k);
115
+ const pick = pickClaudeLogin({ logins, usage, ceilingPct: cfg.usage_ceiling_pct ?? 95, now: now(), limited });
112
116
  if (pick.status === 503) throw Object.assign(new Error("no Claude login on the router host with 30+ minutes left"), { status: 503 });
113
117
  if (pick.status === 429) { log.warn?.(`claude login: every account at or above the usage ceiling; ${pick.body.reason}`); return pick; }
114
118
  if (pick.fallback) log.warn?.(`claude login: no usage source (${src}), falling back to longest validity`);
115
119
  const { login, pct } = pick;
116
- log.info?.(`claude login selected: account=${login.n ?? "default"} usage=${pct ?? "unknown"}% expires_at=${new Date(login.expiresAt).toISOString()}`);
117
- return { status: 200, body: { token: login.accessToken, expires_at: new Date(login.expiresAt).toISOString() } };
120
+ log.info?.(`claude login selected: account=${login.n ?? "default"} usage=${pct ?? "unknown"}%${pick.stale ? " (stale)" : ""} expires_at=${new Date(login.expiresAt).toISOString()}`);
121
+ const agent = req ? agentFor(req) : null;
122
+ if (agent && login.n !== null) handed.set(agent, (handed.get(agent) ?? new Set()).add(login.n));
123
+ return { status: 200, body: { token: login.accessToken, expires_at: new Date(login.expiresAt).toISOString(), account: login.n ?? null } };
124
+ }
125
+ /** #5205: a sandbox on this agent hit a usage limit: the account it reports (one handed to this agent) is excluded until reset_at (default now+1h, at most now+7d). */
126
+ function claudeLimited(req, body) {
127
+ const agent = agentFor(req), n = body?.account;
128
+ if (!Number.isInteger(n)) return { status: 400, body: { error: "account required (the number from the credential response)" } };
129
+ if (!agent || !handed.get(agent)?.has(n)) return { status: 404, body: { error: "that claude account was not handed to this agent" } };
130
+ const t = Date.parse(String(body?.reset_at ?? "")), e = Number(body?.reset_at);
131
+ const at = body?.reset_at !== null && body?.reset_at !== "" && Number.isFinite(e) ? e * 1000 : t; // epoch s, or an ISO time
132
+ const until = Number.isFinite(at) && at > now() ? Math.min(at, now() + MAX_LIMIT_MS) : now() + 3600000;
133
+ limited.set(n, Math.max(until, limited.get(n) ?? 0));
134
+ log.info?.(`claude login limited: account=${n} agent=${agent} until=${new Date(until).toISOString()}`);
135
+ return { status: 200, body: { account: n, until: new Date(until).toISOString() } };
118
136
  }
119
137
  const agentCall = (a, method, path, body, timeoutMs) => call(a.url, method, path, { body, token: a.token, timeoutMs, fetchFn });
120
138
 
@@ -242,6 +260,7 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
242
260
  const q = (s) => `'${String(s).replace(/'/g, "''")}'`;
243
261
  const int = (k) => { const v = Number(url?.searchParams.get(k)); return Number.isInteger(v) && v > 0 ? v : 0; };
244
262
  const sizing = `${int("cpus") ? ` -AllowCpus ${int("cpus")}` : ""}${int("mem") ? ` -AllowMemGb ${int("mem")}` : ""}`;
263
+ const net = ["nat", "mirrored"].includes(url?.searchParams.get("net")) ? ` -Networking ${url.searchParams.get("net")}` : "";
245
264
  return [
246
265
  "$ErrorActionPreference = 'Stop'",
247
266
  `$RouterUrl = ${q(cfg.public_url)}`,
@@ -251,7 +270,7 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
251
270
  "New-Item -ItemType Directory -Path $tmp | Out-Null",
252
271
  "Invoke-WebRequest -UseBasicParsing \"$RouterUrl/bootstrap/bundle.tar.gz?token=$EnrollToken\" -OutFile (Join-Path $tmp 'bundle.tar.gz')",
253
272
  "tar.exe -xzf (Join-Path $tmp 'bundle.tar.gz') -C $tmp",
254
- `& (Join-Path $tmp 'pool\\install\\install-agent.ps1') -RouterUrl $RouterUrl -EnrollToken $EnrollToken -BundlePath (Join-Path $tmp 'bundle.tar.gz')${sizing}`,
273
+ `& (Join-Path $tmp 'pool\\install\\install-agent.ps1') -RouterUrl $RouterUrl -EnrollToken $EnrollToken -BundlePath (Join-Path $tmp 'bundle.tar.gz')${sizing}${net}`,
255
274
  "",
256
275
  ].join("\r\n");
257
276
  }
@@ -294,7 +313,8 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
294
313
  [route("GET", "/agents"), fd(async () => ({ status: 200, body: { agents: await capacities(), sandboxes: sbx() } }))],
295
314
  [route("POST", "/codes"), fd(async () => ({ status: 200, body: issueCode() }))],
296
315
  [route("GET", "/agent/creds/github"), { fn: async () => ({ status: 200, body: { token: await githubToken() } }), auth: "agent" }],
297
- [route("GET", "/agent/creds/claude"), { fn: async () => claudeToken(), auth: "agent" }],
316
+ [route("GET", "/agent/creds/claude"), { fn: async (_p, _b, _u, req) => claudeToken(req), auth: "agent" }],
317
+ [route("POST", "/agent/creds/claude/limited"), { fn: async (_p, body, _u, req) => claudeLimited(req, body), auth: "agent" }], // #5205
298
318
  [route("POST", "/agent/relay/:id"), { fn: async (p, body, _u, req) => relayPost(req, p, body), auth: "agent" }], // #4778
299
319
  [route("GET", "/agent/relay/:id/:rid"), { fn: async (p, _b, _u, req) => relayPoll(req, p), auth: "agent" }],
300
320
  [route("GET", "/agent/bundle"), { fn: async () => ({ bundle: true }), auth: "agent" }],
@@ -373,47 +393,70 @@ export function usageSource(cfg, env = process.env) {
373
393
  export function parseLiveUsage(text) {
374
394
  const f = String(text ?? "").trim().split(/\s+/).map(Number);
375
395
  if (f.length < 4 || !f.slice(0, 4).every(Number.isFinite)) return null;
376
- return { fiveHourPct: f[0], fiveHourResetMs: f[1] * 1000, weeklyPct: f[2], weeklyResetMs: f[3] * 1000 };
396
+ return { fiveHourPct: f[0], fiveHourResetMs: f[1] * 1000, weeklyPct: f[2], weeklyResetMs: f[3] * 1000, updatedMs: Number.isFinite(f[4]) && f[4] > 0 ? f[4] * 1000 : 0 };
377
397
  }
378
398
 
399
+ /** #5236: a `live.<n>` sample older than this is unknown for the 5-hour window (updated 0 or absent: age unknown). */
400
+ export const SAMPLE_MAX_AGE_MS = 30 * 60000;
401
+
379
402
  /** Map account n -> parsed `live.<n>` for the given accounts; unreadable or malformed files are left out. */
380
- export function readUsage(dir, ns, readFile = (p) => readFileSync(p, "utf8")) {
403
+ export function readUsage(dir, ns, readFile = (p) => readFileSync(p, "utf8"), mtime = (p) => statSync(p).mtimeMs) {
381
404
  const out = new Map();
382
- for (const n of ns) { try { const u = parseLiveUsage(readFile(join(dir, `live.${n}`))); if (u) out.set(n, u); } catch { /* no usage for n */ } }
405
+ for (const n of ns) {
406
+ let u = null;
407
+ try { u = parseLiveUsage(readFile(join(dir, `live.${n}`))); } catch { u = null; }
408
+ // #5236: tokenbaton's polled endpoint figure `used.<n>` (a percent; the file mtime is its age), feature-detected.
409
+ try {
410
+ const p = join(dir, `used.${n}`), pct = Number(String(readFile(p)).trim().split(/\s+/)[0]), at = mtime(p);
411
+ if (Number.isFinite(pct) && pct >= 0 && Number.isFinite(at)) u = { ...(u ?? {}), polledPct: pct, polledAtMs: at };
412
+ } catch { /* no polled figure for n */ }
413
+ if (u) out.set(n, u);
414
+ }
383
415
  return out;
384
416
  }
385
417
 
386
418
  /**
387
419
  * Pick the Claude login to hand out (#5165). Candidates have 30+ minutes of validity. A login with known usage is
388
- * excluded at or above `ceilingPct` 5-hour use or 100% weekly use (a passed reset counts as 0, like the local rotator);
389
- * the rest rank by 5-hour use, then validity. Logins with unknown usage follow. No usage at all: longest validity,
390
- * `fallback: true`. Every candidate excluded: a typed 429 carrying the earliest reset.
391
- * @returns {{status: 200, login, pct, fallback} | {status: 429, retryAfter, body} | {status: 503}}
420
+ * excluded at or above `ceilingPct` 5-hour use or 100% weekly use; the rest rank by 5-hour use, then validity. Logins
421
+ * with unknown usage follow, including stale samples whose reset has passed (#5205: unknown, never 0%). Accounts in
422
+ * `limited` (n -> until ms, reported by a lane) are excluded until then. No usage at all: longest validity,
423
+ * `fallback: true`. Every candidate excluded: a typed 429 carrying the earliest reset (limited untils included).
424
+ * @returns {{status: 200, login, pct, fallback, stale} | {status: 429, retryAfter, body} | {status: 503}}
392
425
  */
393
- export function pickClaudeLogin({ logins, usage, ceilingPct = 95, now }) {
426
+ export function pickClaudeLogin({ logins, usage, ceilingPct = 95, now, limited = new Map(), maxAgeMs = SAMPLE_MAX_AGE_MS }) {
394
427
  const valid = logins.filter((l) => l.accessToken && l.expiresAt > now + 30 * 60000);
395
428
  if (!valid.length) return { status: 503 };
396
- const used = (pct, resetMs) => (resetMs <= now ? 0 : pct);
429
+ const used = (pct, resetMs) => (resetMs <= now ? null : pct); // #5205: a passed reset is unknown
397
430
  const byValidity = (a, b) => b.expiresAt - a.expiresAt;
398
431
  const known = [], unknown = [], blocked = [];
399
432
  for (const l of valid) {
433
+ const lim = l.n !== null && l.n !== undefined ? Number(limited?.get?.(l.n)) : NaN;
434
+ if (Number.isFinite(lim) && lim > now) { blocked.push(lim); continue; }
400
435
  const u = l.n !== null && l.n !== undefined ? usage.get(l.n) : undefined;
401
- if (!u) { unknown.push(l); continue; }
402
- const five = used(u.fiveHourPct, u.fiveHourResetMs), week = used(u.weeklyPct, u.weeklyResetMs);
403
- if (five >= ceilingPct || week >= 100) {
436
+ if (!u) { unknown.push({ l, stale: false }); continue; }
437
+ // #5236: a 5-hour figure older than maxAgeMs is unknown (a future reset does not make an old sample fresh); the
438
+ // weekly figure holds until its reset. A newer polled `used.<n>` replaces the 5-hour figure.
439
+ const has = Number.isFinite(u.fiveHourPct) && Number.isFinite(u.weeklyPct);
440
+ const aged = has && u.updatedMs > 0 && now - u.updatedMs > maxAgeMs;
441
+ const polled = Number.isFinite(u.polledPct) && now - u.polledAtMs <= maxAgeMs && u.polledAtMs > (u.updatedMs ?? 0) ? u.polledPct : null;
442
+ const five = polled !== null ? polled : has && !aged ? used(u.fiveHourPct, u.fiveHourResetMs) : null;
443
+ const week = has ? used(u.weeklyPct, u.weeklyResetMs) : null;
444
+ const fiveFull = five !== null && five >= ceilingPct, weekFull = week !== null && week >= 100;
445
+ if (fiveFull || weekFull) {
404
446
  const r = [];
405
- if (five >= ceilingPct) r.push(u.fiveHourResetMs);
406
- if (week >= 100) r.push(u.weeklyResetMs);
447
+ if (fiveFull) r.push(has && u.fiveHourResetMs > now ? u.fiveHourResetMs : has && u.weeklyResetMs > now ? u.weeklyResetMs : now + 3600000);
448
+ if (weekFull) r.push(u.weeklyResetMs);
407
449
  blocked.push(Math.max(...r));
408
- } else known.push({ l, pct: five });
450
+ } else if (five === null || week === null) unknown.push({ l, stale: true });
451
+ else known.push({ l, pct: five });
409
452
  }
410
453
  if (known.length) {
411
454
  known.sort((a, b) => a.pct - b.pct || byValidity(a.l, b.l));
412
- return { status: 200, login: known[0].l, pct: known[0].pct, fallback: false };
455
+ return { status: 200, login: known[0].l, pct: known[0].pct, fallback: false, stale: false };
413
456
  }
414
457
  if (unknown.length) {
415
- unknown.sort(byValidity);
416
- return { status: 200, login: unknown[0], pct: null, fallback: !blocked.length };
458
+ unknown.sort((a, b) => byValidity(a.l, b.l));
459
+ return { status: 200, login: unknown[0].l, pct: null, fallback: !blocked.length && !unknown.some((x) => x.stale), stale: unknown[0].stale };
417
460
  }
418
461
  const resetMs = Math.min(...blocked), at = new Date(resetMs).toISOString();
419
462
  return { status: 429, retryAfter: Math.max(1, Math.ceil((resetMs - now) / 1000)),
@@ -585,3 +585,26 @@ export async function reviewStagingFromCli(argv, io = defaultIo()) {
585
585
  return 1;
586
586
  }
587
587
  }
588
+
589
+ /** The real io of the CLI, for a library caller that overrides only `out`/`err`/`cwd`/`env` (#5212). */
590
+ export const reviewStagingIo = defaultIo;
591
+
592
+ /**
593
+ * Library entry (#5212): any mode of the CLI, run with `--json`, without printing. Returns `{code, data, lines}`: `data` is the
594
+ * parsed `--json` object (manifest, finalize state or summary; null when the run stopped before printing one) and `lines` the
595
+ * diagnostics a CLI run would have written to stderr, with a stop's reason last. The CLI path is untouched.
596
+ */
597
+ export async function reviewStagingJson(argv, io = defaultIo()) {
598
+ const out = [], lines = [];
599
+ const cap = { ...io, out: (s) => out.push(s), err: (s) => lines.push(s) };
600
+ let code;
601
+ try {
602
+ code = await main([...argv.filter((x) => x !== "--json"), "--json"], cap);
603
+ } catch (e) {
604
+ if (e instanceof Stop) return { code: e.code, data: null, lines: [...lines, ...e.lines] };
605
+ throw e;
606
+ }
607
+ let data = null;
608
+ try { data = JSON.parse(out[out.length - 1]); } catch { /* no object printed */ }
609
+ return { code, data, lines };
610
+ }
@@ -0,0 +1,208 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #5210: `forgedock stats --conformance-outcomes`: do conformance blocks predict post-merge defects?
5
+ * Each merged lane PR (a merged PR with a conformance verdict, query.mjs conformanceVerdicts) is joined to four post-merge
6
+ * defect signals inside `windowDays` of its merge:
7
+ * reverted a later merged PR titled `Revert ...` that names the PR (`Reverts o/r#N`, `#N`) or its title
8
+ * reopened a closing issue of the PR reopened after the merge
9
+ * cited a later merged PR whose title or body cites the PR or its issue as the cause ("fix ... #N", "review-finding ... #N")
10
+ * same_hunks a later fix PR whose old-side lines git-blame to this PR's merge commit (local git, compounding.mjs gitProbes;
11
+ * null when git cannot resolve, e.g. the cwd is not a clone of the repo)
12
+ * It prints, per repo and per failure kind, the defect rate of nonconforming-merged versus conforming-merged lane PRs with n
13
+ * and a Wilson 95% interval; a cell under min n prints n/a. Read only: GitHub reads are one GraphQL search per page of 100
14
+ * merged PRs, no writes. The report core is pure; `gatherConformanceOutcomes` supplies the GitHub and git inputs.
15
+ */
16
+ export const DEFAULT_OUTCOME_MIN_N = 20;
17
+ export const DEFAULT_WINDOW_DAYS = 7;
18
+ export const DEFAULT_LOOKBACK_DAYS = 30;
19
+ export const PAGE_SIZE = 100;
20
+ export const SIGNALS = ["reverted", "reopened", "cited", "same_hunks"];
21
+ export const OUTCOME_INSUFFICIENT = "insufficient data";
22
+ export const HIGHER = "nonconforming merges show a higher defect rate";
23
+ export const NOT_HIGHER = "no higher defect rate shown for nonconforming merges";
24
+ const DAY = 86400000;
25
+ const ms = (ts) => { const t = Date.parse(ts ?? ""); return Number.isFinite(t) ? t : null; };
26
+ const r4 = (x) => Math.round(x * 1e4) / 1e4;
27
+ const esc = (s) => String(s).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
28
+
29
+ /** Wilson score interval [low, high] for k successes of n (z = 1.96, 95%); null when n is 0. */
30
+ export function wilson(k, n, z = 1.96) {
31
+ if (!n) return null;
32
+ const p = k / n, z2 = z * z, d = 1 + z2 / n;
33
+ const c = (p + z2 / (2 * n)) / d, h = (z * Math.sqrt((p * (1 - p)) / n + z2 / (4 * n * n))) / d;
34
+ return [r4(Math.max(0, c - h)), r4(Math.min(1, c + h))];
35
+ }
36
+
37
+ /** One 2x2 cell: n, defects, rate and interval; rate and interval are null (insufficient) under minN. */
38
+ export function cell(rows, minN) {
39
+ const n = rows.length, defects = rows.filter((r) => r.defect).length;
40
+ const insufficient = n < minN;
41
+ return { n, defects, rate: insufficient || !n ? null : r4(defects / n), interval: insufficient ? null : wilson(defects, n), insufficient };
42
+ }
43
+
44
+ /** "higher" when the nonconforming interval lies wholly above the conforming one; "insufficient data" when a cell is under min n. */
45
+ export function conclude(nonconforming, conforming) {
46
+ if (nonconforming.insufficient || conforming.insufficient || !nonconforming.interval || !conforming.interval) return OUTCOME_INSUFFICIENT;
47
+ return nonconforming.interval[0] > conforming.interval[1] ? HIGHER : NOT_HIGHER;
48
+ }
49
+
50
+ function twoByTwo(rows, minN) {
51
+ const nonconforming = cell(rows.filter((r) => r.state === "nonconforming"), minN), conforming = cell(rows.filter((r) => r.state === "conforms"), minN);
52
+ return { nonconforming, conforming, conclusion: conclude(nonconforming, conforming) };
53
+ }
54
+
55
+ /** Numbers that identify `p` as a cause: the PR and its closing issues. */
56
+ const refsOf = (p) => [p.number, ...(p.closingIssues ?? []).map((i) => i.number)].filter((x) => Number.isSafeInteger(x));
57
+ const text = (q) => `${q.title ?? ""}\n${q.body ?? ""}`;
58
+ const isRevert = (q) => /^revert\b/i.test(q.title ?? "");
59
+ const isFix = (q) => /^(fix|hotfix|bugfix)\b/i.test(q.title ?? "") || /^revert\b/i.test(q.title ?? "");
60
+
61
+ /** True when a later PR `q` reverts `p`. */
62
+ export function reverts(q, p, repo) {
63
+ if (!isRevert(q)) return false;
64
+ const t = text(q);
65
+ if (repo && new RegExp(`Reverts\\s+${esc(repo)}#${p.number}\\b`, "i").test(t)) return true;
66
+ if (new RegExp(`(^|[^\\w/])#${p.number}\\b`).test(t)) return true;
67
+ return Boolean(p.title) && (q.title ?? "").includes(`"${p.title}"`);
68
+ }
69
+
70
+ /** True when a later PR `q` cites `p` (or its issue) as the cause: "fix ... #N" or "review-finding ... #N" on one line. */
71
+ export function cites(q, p) {
72
+ if (isRevert(q)) return false;
73
+ for (const n of refsOf(p)) {
74
+ const re = new RegExp(`(\\bfix(e[sd])?\\b|review[- ]finding)[^\\n]*?(^|[^\\w/])#${n}\\b`, "im");
75
+ if (re.test(text(q))) return true;
76
+ }
77
+ return false;
78
+ }
79
+
80
+ /**
81
+ * Same-hunks: a later fix PR whose old-side lines blame to `p`'s merge commit. true on a hit, false when every later fix PR
82
+ * resolved without one (or there is none), null when git is missing or a needed probe could not resolve.
83
+ */
84
+ export function sameHunks(p, laterFixes, git) {
85
+ if (!laterFixes.length) return false;
86
+ if (!git || !p.mergeSha) return null;
87
+ let unresolved = false;
88
+ for (const q of laterFixes) {
89
+ const ranges = q.mergeSha ? git.oldRanges(q.mergeSha) : null;
90
+ if (!ranges) { unresolved = true; continue; }
91
+ for (const r of ranges) {
92
+ const shas = git.blame(`${q.mergeSha}^`, r.file, r.start, r.end);
93
+ if (shas == null) { unresolved = true; continue; }
94
+ if (shas.includes(p.mergeSha)) return true;
95
+ }
96
+ }
97
+ return unresolved ? null : false;
98
+ }
99
+
100
+ /**
101
+ * The report core (pure). prs: merged PRs [{repo, number, title, body, mergedAt, mergeSha, closingIssues: [{number, reopenedAt: [ts]}]}];
102
+ * verdicts: Map from conformanceVerdicts (keys pr:N, issue:N). A PR whose window has not elapsed by `now` is pending and left
103
+ * out of the cells. A PR with no verdict is not a lane PR.
104
+ */
105
+ export function conformanceOutcomes({ prs = [], verdicts = new Map(), minN = DEFAULT_OUTCOME_MIN_N, windowDays = DEFAULT_WINDOW_DAYS, now = Date.now(), git = null, graphqlCalls = null, since = null }) {
106
+ const win = windowDays * DAY;
107
+ const merged = prs.filter((p) => ms(p.mergedAt) != null).sort((a, b) => ms(a.mergedAt) - ms(b.mergedAt));
108
+ const sinceMs = ms(since);
109
+ const rows = [];
110
+ let unjoined = 0, pending = 0, unresolved = 0;
111
+ for (const p of merged) {
112
+ const t = ms(p.mergedAt);
113
+ if (sinceMs != null && t < sinceMs) continue;
114
+ const v = verdicts.get(`pr:${p.number}`) ?? refsOf(p).slice(1).map((i) => verdicts.get(`issue:${i}`)).find(Boolean) ?? null;
115
+ if (!v) { unjoined++; continue; }
116
+ if (t + win > now) { pending++; continue; }
117
+ const later = merged.filter((q) => q !== p && q.number !== p.number && (p.repo == null || q.repo == null || q.repo === p.repo) && ms(q.mergedAt) > t && ms(q.mergedAt) <= t + win);
118
+ const signals = {
119
+ reverted: later.some((q) => reverts(q, p, p.repo)),
120
+ reopened: (p.closingIssues ?? []).some((i) => (i.reopenedAt ?? []).some((ts) => ms(ts) > t && ms(ts) <= t + win)),
121
+ cited: later.some((q) => cites(q, p)),
122
+ same_hunks: sameHunks(p, later.filter(isFix), git),
123
+ };
124
+ if (signals.same_hunks === null) unresolved++;
125
+ rows.push({ repo: p.repo ?? null, pr: p.number, issue: v.issue ?? null, merged_at: p.mergedAt, mode: v.mode ?? null, state: v.state, kinds: v.kinds ?? [],
126
+ source: v.source ?? null, signals, defect: SIGNALS.some((s) => signals[s] === true) });
127
+ }
128
+ const repos = {};
129
+ for (const repo of [...new Set(rows.map((r) => r.repo ?? "unknown"))].sort()) {
130
+ const rs = rows.filter((r) => (r.repo ?? "unknown") === repo);
131
+ const kinds = [...new Set(rs.flatMap((r) => (r.state === "nonconforming" ? r.kinds : [])))].sort();
132
+ const confRows = rs.filter((r) => r.state === "conforms");
133
+ const by_kind = {};
134
+ for (const k of kinds) {
135
+ const nonconforming = cell(rs.filter((r) => r.state === "nonconforming" && r.kinds.includes(k)), minN), conforming = cell(confRows, minN);
136
+ by_kind[k] = { nonconforming, conforming, conclusion: conclude(nonconforming, conforming) };
137
+ }
138
+ const by_mode = {};
139
+ for (const m of [...new Set(rs.map((r) => r.mode ?? "unknown"))].sort()) by_mode[m] = twoByTwo(rs.filter((r) => (r.mode ?? "unknown") === m), minN);
140
+ repos[repo] = { overall: twoByTwo(rs, minN), by_kind, by_mode };
141
+ }
142
+ const overall = twoByTwo(rows, minN);
143
+ return {
144
+ window_days: windowDays, min_n: minN, since: since ?? null,
145
+ sources: { merged_prs: merged.length, lane_prs: rows.length, pending, unjoined, same_hunks_unresolved: unresolved, git: Boolean(git), graphql_calls: graphqlCalls },
146
+ repos, overall, conclusion: overall.conclusion, prs: rows,
147
+ };
148
+ }
149
+
150
+ const pct = (x) => (x == null ? "n/a" : `${Math.round(x * 1000) / 10}%`);
151
+ const fmtCell = (c) => `${c.defects}/${c.n} ${pct(c.rate)}${c.interval ? ` [${pct(c.interval[0])}, ${pct(c.interval[1])}]` : ""}`;
152
+ const row = (label, x) => `| ${label} | ${fmtCell(x.nonconforming)} | ${fmtCell(x.conforming)} | ${x.conclusion} |`;
153
+ const HEAD = ["| group | nonconforming-merged defects/n rate [95% CI] | conforming-merged defects/n rate [95% CI] | verdict |", "|---|---|---|---|"];
154
+
155
+ export function renderConformanceOutcomes(r) {
156
+ const s = r.sources;
157
+ const out = [`conformance outcomes: ${s.lane_prs} lane PRs of ${s.merged_prs} merged (${s.unjoined} without a verdict, ${s.pending} with an open ${r.window_days}d window), min n ${r.min_n}`
158
+ + `, same-hunks ${s.git ? `${s.same_hunks_unresolved} unresolved` : "n/a (no local clone of the repo)"}${s.graphql_calls != null ? `, ${s.graphql_calls} GraphQL call(s)` : ""}`];
159
+ for (const [repo, x] of Object.entries(r.repos)) {
160
+ out.push("", `## ${repo}`, "", ...HEAD, row("all", x.overall), ...Object.entries(x.by_mode).map(([m, y]) => row(`mode ${m}`, y)),
161
+ ...Object.entries(x.by_kind).map(([k, y]) => row(`kind ${k}`, y)));
162
+ }
163
+ if (!Object.keys(r.repos).length) out.push("", "no merged lane PR with an elapsed window");
164
+ out.push("", `conclusion: ${r.conclusion}`);
165
+ return out.join("\n");
166
+ }
167
+
168
+ const QUERY = `query($q: String!, $first: Int!, $after: String) {
169
+ search(type: ISSUE, query: $q, first: $first, after: $after) {
170
+ pageInfo { hasNextPage endCursor }
171
+ nodes { ... on PullRequest { number title body mergedAt mergeCommit { oid } repository { nameWithOwner }
172
+ closingIssuesReferences(first: 10) { nodes { number timelineItems(itemTypes: [REOPENED_EVENT], first: 10) { nodes { ... on ReopenedEvent { createdAt } } } } } } }
173
+ }
174
+ }`;
175
+
176
+ /** One GraphQL search page -> normalized PRs. */
177
+ export function prsOfPage(data, repo) {
178
+ return (data?.data?.search?.nodes ?? []).filter((n) => Number.isSafeInteger(n?.number) && n.mergedAt).map((n) => ({
179
+ repo: n.repository?.nameWithOwner ?? repo, number: n.number, title: n.title ?? "", body: n.body ?? "", mergedAt: n.mergedAt, mergeSha: n.mergeCommit?.oid ?? null,
180
+ closingIssues: (n.closingIssuesReferences?.nodes ?? []).filter((i) => Number.isSafeInteger(i?.number))
181
+ .map((i) => ({ number: i.number, reopenedAt: (i.timelineItems?.nodes ?? []).map((e) => e?.createdAt).filter(Boolean) })),
182
+ }));
183
+ }
184
+
185
+ /**
186
+ * Read-only GitHub input: merged PRs of `repo` since `since` (ISO; default DEFAULT_LOOKBACK_DAYS before now) up to now, so later
187
+ * reverts and fixes inside the window are in the candidate set. Exactly one `gh api graphql` search call per page of 100 PRs.
188
+ * GitHub search returns at most 1000 results: `capped` reports when that bound was hit.
189
+ */
190
+ export async function gatherConformanceOutcomes({ repo, gh, since = null, now = Date.now() }) {
191
+ const from = (since ? new Date(ms(since) ?? now - DEFAULT_LOOKBACK_DAYS * DAY) : new Date(now - DEFAULT_LOOKBACK_DAYS * DAY)).toISOString().slice(0, 10);
192
+ const q = `repo:${repo} is:pr is:merged merged:>=${from}`;
193
+ const prs = [];
194
+ let after = null, calls = 0, capped = false;
195
+ for (;;) {
196
+ const args = ["api", "graphql", "-f", `query=${QUERY}`, "-f", `q=${q}`, "-F", `first=${PAGE_SIZE}`, ...(after ? ["-f", `after=${after}`] : [])];
197
+ calls++;
198
+ const raw = await gh(args);
199
+ const data = JSON.parse(String(raw ?? "").trim() || "{}");
200
+ if (Array.isArray(data.errors) && data.errors.length && !data.data) throw new Error(`GraphQL: ${data.errors.map((e) => e?.message).join("; ")}`);
201
+ prs.push(...prsOfPage(data, repo));
202
+ const pi = data?.data?.search?.pageInfo;
203
+ if (!pi?.hasNextPage || !pi.endCursor) break;
204
+ if (prs.length >= 1000) { capped = true; break; }
205
+ after = pi.endCursor;
206
+ }
207
+ return { prs, graphqlCalls: calls, since: `${from}T00:00:00Z`, capped };
208
+ }
@@ -0,0 +1,188 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { describe, it } from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import { conformanceOutcomes, gatherConformanceOutcomes, renderConformanceOutcomes, wilson, cites, reverts, sameHunks, OUTCOME_INSUFFICIENT, HIGHER, NOT_HIGHER, DEFAULT_OUTCOME_MIN_N } from "./conformance-outcomes.mjs";
6
+ import { conformanceVerdicts, verdictOf } from "./query.mjs";
7
+ import { summariseLog } from "./local-source.mjs";
8
+ import { buildReport, parseArgs, runStats } from "./index.mjs";
9
+
10
+ const DAY = 86400000;
11
+ const T0 = Date.parse("2026-10-01T00:00:00Z");
12
+ const at = (d) => new Date(T0 + d * DAY).toISOString();
13
+ const NOW = T0 + 60 * DAY;
14
+ const pr = (number, d, extra = {}) => ({ repo: "o/r", number, title: `feat: change ${number}`, body: "", mergedAt: at(d), mergeSha: `sha${number}`, closingIssues: [], ...extra });
15
+ const verdicts = (rows) => conformanceVerdicts({ records: rows.map(([prN, would, failures = [], mode = "shadow"]) => [
16
+ { event: "run_terminal", issue: prN + 1000, pr: prN, reason: "merged", conformance_mode: mode, ...(would ? { shadow_would: would } : {}), ts: at(0) },
17
+ ...(failures.length ? [{ event: "conformance_shadow", issue: prN + 1000, would, failures, ts: at(-0.1) }] : []),
18
+ ]).flat() });
19
+
20
+ describe("conformance outcomes: join (#5210 R1)", () => {
21
+ it("joins each merged lane PR to its last verdict, mode and the four signals inside the window only", () => {
22
+ const prs = [
23
+ pr(1, 0, { closingIssues: [{ number: 1001, reopenedAt: [at(3)] }] }), // reopened in window
24
+ pr(2, 0), pr(3, 0), pr(4, 0), pr(5, 0),
25
+ pr(6, 0, { closingIssues: [{ number: 1006, reopenedAt: [at(9)] }] }), // reopened outside the 7d window
26
+ pr(20, 1, { title: "Revert \"feat: change 2\"", body: "Reverts o/r#2" }),
27
+ pr(21, 2, { title: "fix: handle null", body: "Fixes a regression from #3" }),
28
+ pr(22, 3, { title: "chore: tidy", body: "review-finding of PR #4" }),
29
+ pr(23, 4, { title: "fix: loop bound", body: "unrelated" }), // same-hunks fix for #5 via git
30
+ pr(24, 12, { title: "fix: late", body: "fix for #6" }), // outside window
31
+ pr(25, 1, { title: "docs: mention #5", body: "" }), // a mention, not a cause
32
+ ];
33
+ const v = verdicts([[1, "conforms"], [2, "nonconforming", ["omission"]], [3, "conforms", [], "enforce"], [4, "nonconforming", ["scope_creep", "omission"]], [5, "conforms"], [6, "conforms"]]);
34
+ const git = { oldRanges: (sha) => (sha === "sha23" ? [{ file: "a.js", start: 1, end: 2 }] : []), blame: (rev, file) => (rev === "sha23^" && file === "a.js" ? ["sha5"] : []) };
35
+ const r = conformanceOutcomes({ prs, verdicts: v, now: NOW, git, minN: 1 });
36
+ const by = Object.fromEntries(r.prs.map((x) => [x.pr, x]));
37
+ assert.equal(r.sources.lane_prs, 6);
38
+ assert.equal(r.sources.unjoined, 6, "PRs without a verdict are not lane PRs");
39
+ assert.deepEqual(by[1].signals, { reverted: false, reopened: true, cited: false, same_hunks: false });
40
+ assert.equal(by[2].signals.reverted, true);
41
+ assert.deepEqual(by[2].kinds, ["omission"]);
42
+ assert.equal(by[3].signals.cited, true);
43
+ assert.equal(by[3].mode, "enforce");
44
+ assert.equal(by[4].signals.cited, true, "review-finding of PR #N");
45
+ assert.deepEqual(by[4].kinds, ["omission", "scope_creep"]);
46
+ assert.equal(by[5].signals.same_hunks, true);
47
+ assert.equal(by[5].signals.cited, false, "a docs mention is not a cause");
48
+ assert.deepEqual(by[6].signals, { reverted: false, reopened: false, cited: false, same_hunks: false }, "signals after the window do not count");
49
+ assert.equal(by[6].defect, false);
50
+ assert.equal(by[1].defect, true);
51
+ });
52
+
53
+ it("the latest verdict wins across batch rows, run logs and telemetry; a shadow run with no verdict has none", () => {
54
+ const v = conformanceVerdicts({
55
+ batchRows: [{ issue: 7, pr: 70, outcome: "merged", conformance: { mode: "shadow", would: "nonconforming", kinds: ["omission"] }, ts: "2026-10-01T00:00:00Z" }],
56
+ runs: [{ finished: true, issue: 7, pr: 70, reason: "merged", conformanceMode: "shadow", shadowWould: "conforms", conformanceFailures: [], endTs: "2026-10-02T00:00:00Z" }],
57
+ records: [{ event: "run_terminal", issue: 8, pr: 80, reason: "merged", conformance_mode: "shadow", ts: "2026-10-02T00:00:00Z" }],
58
+ });
59
+ assert.equal(v.get("pr:70").state, "conforms");
60
+ assert.equal(v.get("pr:70").source, "local");
61
+ assert.equal(v.get("pr:80"), undefined);
62
+ assert.deepEqual(verdictOf({ mode: "enforce", merged: true }), { mode: "enforce", state: "conforms", kinds: [] });
63
+ });
64
+
65
+ it("a PR whose window is still open is pending, not counted", () => {
66
+ const r = conformanceOutcomes({ prs: [pr(1, 58)], verdicts: verdicts([[1, "conforms"]]), now: NOW, minN: 1 });
67
+ assert.equal(r.sources.pending, 1);
68
+ assert.equal(r.sources.lane_prs, 0);
69
+ });
70
+
71
+ it("run logs expose pr, mode and the last verdict's failure codes", () => {
72
+ const s = summariseLog([{ event: "RUN_START", issue: 9, ts: at(0) }, { event: "CONFORMANCE", round: 1, state: "nonconforming", failures: ["regression"], mode: "shadow" },
73
+ { event: "CONFORMANCE_SHADOW", would: "nonconforming", failures: ["omission"] }, { event: "RUN_TERMINAL", reason: "merged", pr: 90, conformance_mode: "shadow", shadow_would: "nonconforming", ts: at(1) }]);
74
+ assert.equal(s.pr, 90);
75
+ assert.equal(s.conformanceMode, "shadow");
76
+ assert.deepEqual(s.conformanceFailures, ["omission"]);
77
+ });
78
+
79
+ it("signal helpers", () => {
80
+ assert.equal(reverts({ title: "Revert \"x\"", body: "Reverts o/r#12" }, { number: 12 }, "o/r"), true);
81
+ assert.equal(reverts({ title: "fix: x", body: "Reverts o/r#12" }, { number: 12 }, "o/r"), false);
82
+ assert.equal(cites({ title: "fix(x): y", body: "Closes #120" }, { number: 12, closingIssues: [] }), false, "#120 is not #12");
83
+ assert.equal(cites({ title: "fix(x): y (#12)", body: "" }, { number: 12, closingIssues: [] }), true);
84
+ assert.equal(sameHunks({ mergeSha: "a" }, [{ mergeSha: "b" }], null), null, "no git: unresolved");
85
+ assert.equal(sameHunks({ mergeSha: "a" }, [], null), false, "no later fix: false");
86
+ assert.equal(sameHunks({ mergeSha: "a" }, [{ mergeSha: "b" }], { oldRanges: () => null, blame: () => [] }), null);
87
+ });
88
+ });
89
+
90
+ describe("conformance outcomes: 2x2 and conclusion (#5210 R2)", () => {
91
+ const many = (start, n, would, defects, failures = []) => Array.from({ length: n }, (_, i) => {
92
+ const num = start + i;
93
+ return { p: pr(num, 0, i < defects ? { closingIssues: [{ number: num + 1000, reopenedAt: [at(1)] }] } : {}), v: [num, would, failures] };
94
+ });
95
+ it("defaults to min n 20 per cell and prints insufficient data below it", () => {
96
+ const xs = [...many(1, 19, "nonconforming", 10, ["omission"]), ...many(100, 30, "conforms", 1)];
97
+ const r = conformanceOutcomes({ prs: xs.map((x) => x.p), verdicts: verdicts(xs.map((x) => x.v)), now: NOW });
98
+ assert.equal(r.min_n, DEFAULT_OUTCOME_MIN_N);
99
+ assert.equal(r.min_n, 20);
100
+ assert.equal(r.overall.nonconforming.n, 19);
101
+ assert.equal(r.overall.nonconforming.rate, null);
102
+ assert.equal(r.overall.nonconforming.insufficient, true);
103
+ assert.equal(r.conclusion, OUTCOME_INSUFFICIENT);
104
+ const text = renderConformanceOutcomes(r);
105
+ assert.match(text, /\| all \| 10\/19 n\/a \|/);
106
+ assert.match(text.split("\n").at(-1), /^conclusion: insufficient data$/);
107
+ });
108
+ it("per repo, per mode and per failure kind with n, rate and a Wilson interval; higher when the intervals separate", () => {
109
+ const xs = [...many(1, 25, "nonconforming", 15, ["omission"]), ...many(30, 22, "nonconforming", 1, ["scope_creep"]), ...many(100, 40, "conforms", 2)];
110
+ const r = conformanceOutcomes({ prs: xs.map((x) => x.p), verdicts: verdicts(xs.map((x) => x.v)), now: NOW });
111
+ const o = r.repos["o/r"];
112
+ assert.deepEqual([o.by_kind.omission.nonconforming.n, o.by_kind.omission.nonconforming.defects, o.by_kind.omission.nonconforming.rate], [25, 15, 0.6]);
113
+ assert.deepEqual(o.by_kind.omission.nonconforming.interval, wilson(15, 25));
114
+ assert.equal(o.by_kind.omission.conclusion, HIGHER);
115
+ assert.equal(o.by_kind.scope_creep.conclusion, NOT_HIGHER);
116
+ assert.equal(o.overall.conforming.n, 40);
117
+ assert.ok(o.by_mode.shadow);
118
+ assert.equal(r.conclusion, HIGHER);
119
+ const text = renderConformanceOutcomes(r);
120
+ assert.match(text, /## o\/r/);
121
+ assert.match(text, /\| kind omission \| 15\/25 60% \[/);
122
+ assert.equal(text.split("\n").at(-1), `conclusion: ${HIGHER}`);
123
+ });
124
+ it("wilson matches the closed form and stays inside [0, 1]", () => {
125
+ assert.deepEqual(wilson(0, 10), [0, 0.2775]);
126
+ assert.deepEqual(wilson(10, 10), [0.7225, 1]);
127
+ assert.equal(wilson(0, 0), null);
128
+ });
129
+ });
130
+
131
+ /** gh stub: `api graphql` search pages over `total` merged PRs; records every call. */
132
+ function graphqlGh(total, calls = []) {
133
+ return async (args) => {
134
+ calls.push(args);
135
+ if (args[0] === "api" && args[1] === "graphql") {
136
+ const after = args.find((a) => a.startsWith("after="));
137
+ const start = after ? Number(after.slice(6)) : 0;
138
+ const nodes = Array.from({ length: Math.min(100, total - start) }, (_, i) => ({ number: start + i + 1, title: "t", body: "", mergedAt: at(0), mergeCommit: { oid: `s${start + i}` },
139
+ repository: { nameWithOwner: "o/r" }, closingIssuesReferences: { nodes: [] } }));
140
+ return JSON.stringify({ data: { search: { pageInfo: { hasNextPage: start + 100 < total, endCursor: String(start + 100) }, nodes } } });
141
+ }
142
+ return "[]";
143
+ };
144
+ }
145
+ const isWrite = (args) => args.some((a) => /^(-X|--method)$/.test(a)) || args.some((a) => /^query=\s*mutation\b/.test(a)) || ["comment", "edit", "create", "close", "reopen", "merge"].includes(args[1]);
146
+
147
+ describe("conformance outcomes: read only (#5210 R3)", () => {
148
+ it("one GraphQL call per 100 PRs and no write", async () => {
149
+ const calls = [];
150
+ const out = await gatherConformanceOutcomes({ repo: "o/r", gh: graphqlGh(250, calls), since: at(0), now: NOW });
151
+ assert.equal(out.prs.length, 250);
152
+ assert.equal(out.graphqlCalls, 3);
153
+ assert.equal(calls.length, 3);
154
+ assert.ok(calls.every((a) => a[0] === "api" && a[1] === "graphql" && !isWrite(a)));
155
+ assert.ok(calls[0].includes("q=repo:o/r is:pr is:merged merged:>=2026-10-01"));
156
+ });
157
+ it("runStats --conformance-outcomes --json: GitHub reads only, the report under query.conformance_outcomes", async () => {
158
+ const calls = [];
159
+ const gh = graphqlGh(120, calls);
160
+ let out = "";
161
+ const w = process.stdout.write;
162
+ process.stdout.write = (t) => { out += t; return true; };
163
+ let code;
164
+ try {
165
+ code = await runStats(["--conformance-outcomes", "--repo", "o/r", "--since", "2026-10-01", "--window-days", "5", "--json", "--no-cache", "--no-local"],
166
+ { gh, env: { HOME: "/nonexistent" }, now: () => NOW, git: null, releaseTimes: [], onProgress: () => {} });
167
+ } finally { process.stdout.write = w; }
168
+ assert.equal(code, 0);
169
+ const rep = JSON.parse(out).query.conformance_outcomes;
170
+ assert.equal(rep.window_days, 5);
171
+ assert.equal(rep.sources.merged_prs, 120);
172
+ assert.equal(rep.sources.graphql_calls, 2);
173
+ assert.equal(rep.conclusion, OUTCOME_INSUFFICIENT);
174
+ assert.equal(calls.filter((a) => a[1] === "graphql").length, 2);
175
+ assert.ok(calls.every((a) => !isWrite(a)), "no GitHub write");
176
+ });
177
+ it("buildReport bounds the crawl and uses min n 20 unless --min-n is passed", async () => {
178
+ const r = await buildReport({ ...parseArgs(["--conformance-outcomes", "--min-n", "3"]), repo: "o/r", cache: false, local: false },
179
+ { gh: graphqlGh(0), env: {}, now: () => NOW, git: null, releaseTimes: [], onProgress: () => {} });
180
+ assert.equal(r.query.conformance_outcomes.min_n, 3);
181
+ });
182
+ it("flag parsing", () => {
183
+ assert.equal(parseArgs(["--conformance-outcomes"]).conformanceOutcomes, true);
184
+ assert.equal(parseArgs(["--conformance-outcomes", "--window-days", "14"]).windowDays, 14);
185
+ assert.throws(() => parseArgs(["--window-days", "7"]), /needs --conformance-outcomes/);
186
+ assert.throws(() => parseArgs(["--conformance-outcomes", "--window-days", "0"]), /positive integer/);
187
+ });
188
+ });