forgedock 1.52.0 → 1.54.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 (233) hide show
  1. package/.claude-plugin/marketplace.json +51 -0
  2. package/README.md +8 -2
  3. package/bin/auth/app-manifest.mjs +89 -0
  4. package/bin/auth/app-manifest.test.mjs +75 -0
  5. package/bin/auth/app-token.mjs +256 -0
  6. package/bin/auth/app-token.test.mjs +232 -0
  7. package/bin/brand.mjs +7 -0
  8. package/bin/config-history.mjs +151 -0
  9. package/bin/config-schema.mjs +115 -0
  10. package/bin/demo.mjs +65 -11
  11. package/bin/engine/outcome-codes.mjs +9 -3
  12. package/bin/engine/telemetry-seam.mjs +11 -3
  13. package/bin/engine/telemetry-seam.test.mjs +17 -0
  14. package/bin/engine-cli.mjs +110 -36
  15. package/bin/experiment.mjs +58 -6
  16. package/bin/first-run.mjs +122 -0
  17. package/bin/forge-utils.mjs +6 -2
  18. package/bin/forgedock.mjs +138 -142
  19. package/bin/help-text.mjs +144 -0
  20. package/bin/hooks/pre-tool-use.mjs +7 -0
  21. package/bin/journey.mjs +82 -83
  22. package/bin/lean/acceptance.mjs +313 -0
  23. package/bin/lean/acceptance.test.mjs +215 -0
  24. package/bin/lean/account-watch.mjs +28 -0
  25. package/bin/lean/account-watch.test.mjs +30 -0
  26. package/bin/lean/activation.mjs +38 -0
  27. package/bin/lean/activation.test.mjs +36 -1
  28. package/bin/lean/basered.mjs +115 -0
  29. package/bin/lean/basered.test.mjs +66 -0
  30. package/bin/lean/batch-health.mjs +114 -7
  31. package/bin/lean/batch-health.test.mjs +87 -1
  32. package/bin/lean/batch.mjs +41 -2
  33. package/bin/lean/batch.test.mjs +115 -11
  34. package/bin/lean/branchlock.mjs +54 -0
  35. package/bin/lean/branchlock.test.mjs +49 -0
  36. package/bin/lean/ceiling.mjs +72 -0
  37. package/bin/lean/ceiling.test.mjs +54 -0
  38. package/bin/lean/checkpoint-reconcile.mjs +43 -0
  39. package/bin/lean/checkpoint-reconcile.test.mjs +95 -0
  40. package/bin/lean/ci-budget.mjs +366 -0
  41. package/bin/lean/ci-budget.test.mjs +167 -0
  42. package/bin/lean/conformance.e2e.test.mjs +8 -1
  43. package/bin/lean/conformance.mjs +269 -38
  44. package/bin/lean/conformance.test.mjs +280 -7
  45. package/bin/lean/context.mjs +35 -6
  46. package/bin/lean/context.test.mjs +27 -1
  47. package/bin/lean/depcache.mjs +25 -1
  48. package/bin/lean/depcache.test.mjs +26 -0
  49. package/bin/lean/e2e.mjs +18 -2
  50. package/bin/lean/e2e.test.mjs +26 -1
  51. package/bin/lean/effects.mjs +47 -14
  52. package/bin/lean/execution.mjs +19 -3
  53. package/bin/lean/execution.test.mjs +63 -0
  54. package/bin/lean/facts.mjs +3 -3
  55. package/bin/lean/facts.test.mjs +5 -0
  56. package/bin/lean/findinglabel.mjs +16 -0
  57. package/bin/lean/findinglabel.test.mjs +39 -0
  58. package/bin/lean/fixround.mjs +14 -0
  59. package/bin/lean/fixround.test.mjs +25 -2
  60. package/bin/lean/gh-assoc.test.mjs +2 -1
  61. package/bin/lean/integration.mjs +100 -9
  62. package/bin/lean/integration.test.mjs +98 -0
  63. package/bin/lean/issuewatch-parity.mjs +64 -0
  64. package/bin/lean/issuewatch-parity.test.mjs +127 -0
  65. package/bin/lean/issuewatch-release.mjs +6 -2
  66. package/bin/lean/issuewatch-release.test.mjs +17 -1
  67. package/bin/lean/issuewatch.mjs +45 -6
  68. package/bin/lean/issuewatch.test.mjs +3 -2
  69. package/bin/lean/lanelock.mjs +14 -0
  70. package/bin/lean/lean.mjs +473 -100
  71. package/bin/lean/lean.test.mjs +686 -33
  72. package/bin/lean/light.mjs +48 -7
  73. package/bin/lean/light.test.mjs +37 -3
  74. package/bin/lean/limits.test.mjs +142 -9
  75. package/bin/lean/mechfix.mjs +124 -0
  76. package/bin/lean/mechfix.test.mjs +75 -0
  77. package/bin/lean/orchestrate-cancel.test.mjs +143 -0
  78. package/bin/lean/orchestrate.mjs +116 -28
  79. package/bin/lean/phaseledger.mjs +47 -5
  80. package/bin/lean/phaseledger.test.mjs +30 -1
  81. package/bin/lean/postdeploy-check.test.mjs +39 -0
  82. package/bin/lean/precheck.mjs +23 -4
  83. package/bin/lean/precheck.test.mjs +14 -1
  84. package/bin/lean/prereq.mjs +28 -0
  85. package/bin/lean/prereq.test.mjs +20 -0
  86. package/bin/lean/probe.mjs +4 -2
  87. package/bin/lean/prodparity.mjs +52 -0
  88. package/bin/lean/prodparity.test.mjs +67 -0
  89. package/bin/lean/prompts.mjs +77 -19
  90. package/bin/lean/quota.mjs +39 -0
  91. package/bin/lean/recovery.test.mjs +11 -1
  92. package/bin/lean/relaxation.mjs +73 -0
  93. package/bin/lean/relaxation.test.mjs +54 -0
  94. package/bin/lean/release-io.test.mjs +42 -0
  95. package/bin/lean/release-postmerge.mjs +125 -0
  96. package/bin/lean/release-preflight.mjs +58 -0
  97. package/bin/lean/release-preflight.test.mjs +114 -0
  98. package/bin/lean/release-rehearsal.mjs +64 -0
  99. package/bin/lean/release-rehearsal.test.mjs +93 -0
  100. package/bin/lean/release-review.e2e.test.mjs +77 -0
  101. package/bin/lean/release-review.mjs +254 -0
  102. package/bin/lean/release-review.test.mjs +307 -0
  103. package/bin/lean/release-snapshot.mjs +188 -0
  104. package/bin/lean/release-snapshot.test.mjs +190 -0
  105. package/bin/lean/release.mjs +296 -0
  106. package/bin/lean/release.test.mjs +387 -0
  107. package/bin/lean/render.mjs +1 -1
  108. package/bin/lean/replan.mjs +184 -0
  109. package/bin/lean/replan.test.mjs +110 -0
  110. package/bin/lean/resume.mjs +9 -7
  111. package/bin/lean/resume.test.mjs +16 -0
  112. package/bin/lean/rotator.mjs +150 -31
  113. package/bin/lean/rotator.test.mjs +105 -2
  114. package/bin/lean/sandbox-remote.mjs +9 -2
  115. package/bin/lean/schedd.mjs +83 -5
  116. package/bin/lean/schedd.test.mjs +108 -7
  117. package/bin/lean/selfreview.mjs +94 -0
  118. package/bin/lean/selfreview.test.mjs +58 -1
  119. package/bin/lean/selftest-gate.mjs +22 -0
  120. package/bin/lean/selftest-gate.test.mjs +18 -1
  121. package/bin/lean/selftest-journey.mjs +234 -0
  122. package/bin/lean/selftest-journey.test.mjs +130 -0
  123. package/bin/lean/selftest-live.mjs +2 -1
  124. package/bin/lean/seqlease.mjs +35 -1
  125. package/bin/lean/seqlease.test.mjs +15 -0
  126. package/bin/lean/seqreserve.e2e.test.mjs +135 -0
  127. package/bin/lean/seqreserve.mjs +73 -0
  128. package/bin/lean/seqreserve.test.mjs +134 -0
  129. package/bin/lean/sequence.mjs +35 -6
  130. package/bin/lean/seqversioned.mjs +147 -0
  131. package/bin/lean/stagestamp.mjs +28 -0
  132. package/bin/lean/stagestamp.test.mjs +32 -0
  133. package/bin/lean/surfaces.mjs +75 -0
  134. package/bin/lean/surfaces.test.mjs +59 -0
  135. package/bin/lean/toolplace.mjs +28 -0
  136. package/bin/lean/toolplace.test.mjs +24 -0
  137. package/bin/lean/toolstats.mjs +3 -1
  138. package/bin/lean/toolstats.test.mjs +11 -0
  139. package/bin/lean/validatebest.mjs +28 -0
  140. package/bin/lean/validatebest.test.mjs +27 -0
  141. package/bin/lean/verifier.mjs +3 -2
  142. package/bin/lean/verify.mjs +2 -1
  143. package/bin/lean/verify.test.mjs +6 -0
  144. package/bin/pool/agent.mjs +27 -4
  145. package/bin/pool/docker.mjs +5 -0
  146. package/bin/pool/router.mjs +74 -28
  147. package/bin/prereqs.mjs +111 -0
  148. package/bin/replay-timelapse.mjs +149 -0
  149. package/bin/review-staging.mjs +123 -16
  150. package/bin/review-staging.test.mjs +18 -0
  151. package/bin/runner.mjs +43 -6
  152. package/bin/splash-install.mjs +157 -0
  153. package/bin/stats/aggregate.mjs +8 -1
  154. package/bin/stats/conformance-outcomes.mjs +289 -0
  155. package/bin/stats/conformance-outcomes.test.mjs +274 -0
  156. package/bin/stats/depth.mjs +275 -0
  157. package/bin/stats/depth.test.mjs +158 -0
  158. package/bin/stats/efficiency.mjs +26 -5
  159. package/bin/stats/efficiency.test.mjs +45 -1
  160. package/bin/stats/experiment.mjs +7 -5
  161. package/bin/stats/first-review.mjs +77 -0
  162. package/bin/stats/first-review.test.mjs +36 -0
  163. package/bin/stats/firstmerge.mjs +40 -0
  164. package/bin/stats/firstmerge.test.mjs +41 -0
  165. package/bin/stats/github-source.mjs +53 -15
  166. package/bin/stats/index.mjs +147 -9
  167. package/bin/stats/local-source.mjs +12 -0
  168. package/bin/stats/origin.mjs +80 -0
  169. package/bin/stats/origin.test.mjs +58 -0
  170. package/bin/stats/query.mjs +69 -0
  171. package/bin/stats/render.mjs +3 -1
  172. package/bin/stats/scoreboard.mjs +137 -0
  173. package/bin/stats/scoreboard.test.mjs +87 -0
  174. package/bin/stats/selffiled.mjs +52 -0
  175. package/bin/stats/selffiled.test.mjs +71 -0
  176. package/bin/stats/stats.test.mjs +80 -0
  177. package/bin/tui.mjs +3 -2
  178. package/commands/bootstrap.md +15 -14
  179. package/commands/deploy-pr.md +18 -3
  180. package/commands/forge-stats.md +1 -1
  181. package/commands/forgedock-ci-setup.md +28 -0
  182. package/commands/forgedock-init.md +4 -5
  183. package/commands/issue.md +2 -0
  184. package/commands/milestone.md +9 -1
  185. package/commands/orchestrate.md +1 -1
  186. package/commands/replay.md +2 -0
  187. package/commands/review-pr-agents/security.md +4 -0
  188. package/commands/review-pr-staging.md +6 -1
  189. package/commands/work-on/build.md +4 -6
  190. package/commands/work-on/close.md +8 -0
  191. package/docs/CONFIG.md +170 -18
  192. package/docs/ISSUE-WATCH.md +25 -0
  193. package/docs/OUTCOME-CODES.md +4 -0
  194. package/docs/REPLAY.md +9 -0
  195. package/docs/SELFTEST.md +11 -0
  196. package/docs/STATS.md +61 -0
  197. package/docs/TELEMETRY.md +1 -1
  198. package/docs/eval/README.md +6 -0
  199. package/docs/eval/adversarial-bench.md +68 -0
  200. package/docs/eval/corpus/adversarial-v1.json +285 -0
  201. package/docs/eval/feature-bench.md +42 -0
  202. package/docs/eval/feature-specs/crud-auth/journeys/notes-crud-isolated.mjs +21 -0
  203. package/docs/eval/feature-specs/crud-auth/journeys/register-login.mjs +12 -0
  204. package/docs/eval/feature-specs/crud-auth/spec.md +15 -0
  205. package/docs/site/start-a-new-project.md +2 -1
  206. package/package.json +5 -2
  207. package/plugins/forgedock-splash/.claude-plugin/plugin.json +10 -0
  208. package/plugins/forgedock-splash/README.md +27 -0
  209. package/plugins/forgedock-splash/hooks/hooks.json +1 -0
  210. package/plugins/forgedock-splash/hooks/register.tsx +74 -0
  211. package/plugins/forgedock-splash/hooks/scene.ts +222 -0
  212. package/plugins/forgedock-splash/types/index.d.ts +10 -0
  213. package/pool/README.md +1 -1
  214. package/pool/image/cs-cred +14 -1
  215. package/scripts/backfill-finding-labels.mjs +50 -0
  216. package/scripts/backfill-finding-labels.test.mjs +36 -0
  217. package/scripts/bench-adversarial.mjs +216 -0
  218. package/scripts/bench-feature.mjs +170 -0
  219. package/scripts/bench-lightlane.mjs +2 -2
  220. package/scripts/bootstrap-create.mjs +2 -2
  221. package/scripts/bootstrap-validate.mjs +35 -2
  222. package/scripts/check-spec-size.sh +4 -3
  223. package/scripts/check-spec-size.test.sh +3 -0
  224. package/scripts/doctor-pipeline-state.sh +21 -6
  225. package/scripts/file-deferred-followups.sh +59 -251
  226. package/scripts/file-deferred-followups.test.sh +85 -206
  227. package/scripts/followup-route.mjs +12 -0
  228. package/scripts/owner-route-parity.test.sh +17 -1
  229. package/scripts/plan-validate-live.mjs +40 -6
  230. package/scripts/review-pr-side-effects.test.sh +40 -0
  231. package/scripts/review-pr-staging-scope.test.sh +1 -1
  232. package/scripts/review-staging-post.sh +23 -0
  233. package/scripts/review-staging-post.test.sh +8 -0
@@ -0,0 +1,157 @@
1
+ /**
2
+ * bin/splash-install.mjs — default install of the forgedock-splash Claude Code
3
+ * plugin during `npx forgedock` setup (forge#5312).
4
+ *
5
+ * The plugin is staged, together with a generated local marketplace manifest
6
+ * named `forgedock-local`, into ~/.forge/splash-marketplace (the persisted
7
+ * toolset home, so the path survives npx cache changes). The `claude` CLI then
8
+ * registers that directory as a marketplace and installs the plugin at user
9
+ * scope. Every step is best-effort: nothing here ever throws or fails setup,
10
+ * and re-running setup retries and refreshes the staged copy.
11
+ */
12
+ import { execFileSync } from "child_process";
13
+ import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "fs";
14
+ import { join } from "path";
15
+ import { resolveClaudeConfigDir } from "./journey.mjs";
16
+
17
+ export const SPLASH_PLUGIN = "forgedock-splash";
18
+ export const LOCAL_MARKETPLACE = "forgedock-local";
19
+ const GITHUB_MARKETPLACE = "forgedock";
20
+ const TURN_OFF = `turn off: /plugin disable ${SPLASH_PLUGIN}`;
21
+
22
+ export const splashStageDir = (home) => join(home, ".forge", "splash-marketplace");
23
+
24
+ /** `--no-splash` or FORGEDOCK_NO_SPLASH=1 (also FORGEDOCK_SPLASH=0/false/off) opts out. */
25
+ export function splashOptedOut(argv = [], env = process.env) {
26
+ if (argv.includes("--no-splash")) return true;
27
+ if (/^(1|true|yes|on)$/i.test(env.FORGEDOCK_NO_SPLASH ?? "")) return true;
28
+ return /^(0|false|no|off)$/i.test(env.FORGEDOCK_SPLASH ?? "");
29
+ }
30
+
31
+ function readJson(path) {
32
+ try {
33
+ return JSON.parse(readFileSync(path, "utf-8"));
34
+ } catch {
35
+ return null;
36
+ }
37
+ }
38
+
39
+ /** Real `claude` runner; the plugin CLI reads CLAUDE_CONFIG_DIR and HOME from env. */
40
+ export function defaultSplashExec(cmd, args, env = process.env) {
41
+ return execFileSync(cmd, args, {
42
+ encoding: "utf-8",
43
+ stdio: ["ignore", "pipe", "pipe"],
44
+ timeout: 60000,
45
+ env,
46
+ shell: process.platform === "win32",
47
+ });
48
+ }
49
+
50
+ /**
51
+ * Plugin state from the user's settings.json `enabledPlugins`:
52
+ * "disabled" when any forgedock-splash@* entry is false, "installed" when one is true.
53
+ */
54
+ export function splashState({ home, env = process.env }) {
55
+ const settings = readJson(join(resolveClaudeConfigDir(env, home), "settings.json"));
56
+ const entries = Object.entries(settings?.enabledPlugins ?? {}).filter(([k]) => k.startsWith(`${SPLASH_PLUGIN}@`));
57
+ if (entries.some(([, v]) => v === false)) return "disabled";
58
+ return entries.some(([, v]) => v === true) ? "installed" : "not installed";
59
+ }
60
+
61
+ function knownMarketplaces(home, env) {
62
+ return readJson(join(resolveClaudeConfigDir(env, home), "plugins", "known_marketplaces.json")) ?? {};
63
+ }
64
+
65
+ /** True when the already-added GitHub-backed `forgedock` marketplace lists the plugin. */
66
+ function githubMarketplaceHasSplash(home, env) {
67
+ const entry = knownMarketplaces(home, env)[GITHUB_MARKETPLACE];
68
+ if (!entry?.installLocation) return false;
69
+ const manifest = readJson(join(entry.installLocation, ".claude-plugin", "marketplace.json"));
70
+ return Array.isArray(manifest?.plugins) && manifest.plugins.some((p) => p?.name === SPLASH_PLUGIN);
71
+ }
72
+
73
+ /** Copy the plugin (without tests/) and a generated local marketplace manifest into ~/.forge. */
74
+ export function stageSplash({ pkgRoot, home }) {
75
+ const src = join(pkgRoot, "plugins", SPLASH_PLUGIN);
76
+ if (!existsSync(join(src, ".claude-plugin", "plugin.json"))) return null;
77
+ const stage = splashStageDir(home);
78
+ rmSync(stage, { recursive: true, force: true });
79
+ mkdirSync(join(stage, ".claude-plugin"), { recursive: true });
80
+ cpSync(src, join(stage, "plugins", SPLASH_PLUGIN), {
81
+ recursive: true,
82
+ filter: (p) => !/[\\/]tests([\\/]|$)/.test(p.slice(src.length)),
83
+ });
84
+ const manifest = {
85
+ name: LOCAL_MARKETPLACE,
86
+ description: "ForgeDock splash plugin, installed locally by npx forgedock.",
87
+ owner: { name: "RapierCraft Studios" },
88
+ plugins: [{ name: SPLASH_PLUGIN, source: `./plugins/${SPLASH_PLUGIN}`, description: "ForgeDock startup splash for Claude Code." }],
89
+ };
90
+ writeFileSync(join(stage, ".claude-plugin", "marketplace.json"), JSON.stringify(manifest, null, 2) + "\n");
91
+ return stage;
92
+ }
93
+
94
+ /**
95
+ * Install or refresh the splash. Returns { status, line } where status is one of
96
+ * opted-out | disabled | no-source | no-claude | failed | installed | already-installed.
97
+ * Never throws.
98
+ */
99
+ export function installSplash({ pkgRoot, home, env = process.env, argv = [], exec = defaultSplashExec }) {
100
+ try {
101
+ if (splashOptedOut(argv, env)) return { status: "opted-out", line: "startup splash skipped (--no-splash)" };
102
+ const state = splashState({ home, env });
103
+ if (state === "disabled") {
104
+ return { status: "disabled", line: `startup splash left disabled re-enable: /plugin enable ${SPLASH_PLUGIN}` };
105
+ }
106
+ const stage = stageSplash({ pkgRoot, home });
107
+ if (!stage) return { status: "no-source", line: "" };
108
+ const run = (...args) => exec("claude", args, env);
109
+ try {
110
+ run("--version");
111
+ } catch {
112
+ return { status: "no-claude", line: "startup splash skipped: claude CLI not found re-run npx forgedock after installing Claude Code" };
113
+ }
114
+ let market = LOCAL_MARKETPLACE;
115
+ if (githubMarketplaceHasSplash(home, env)) {
116
+ market = GITHUB_MARKETPLACE;
117
+ try { run("plugin", "marketplace", "update", market); } catch { /* best-effort refresh */ }
118
+ } else if (LOCAL_MARKETPLACE in knownMarketplaces(home, env)) {
119
+ run("plugin", "marketplace", "update", market);
120
+ } else {
121
+ try {
122
+ run("plugin", "marketplace", "add", stage);
123
+ } catch {
124
+ run("plugin", "marketplace", "update", market); // already added under another record
125
+ }
126
+ }
127
+ const ref = `${SPLASH_PLUGIN}@${market}`;
128
+ if (state === "installed") {
129
+ try { run("plugin", "update", ref); } catch { /* best-effort refresh */ }
130
+ return { status: "already-installed", line: `startup splash already installed ${TURN_OFF}` };
131
+ }
132
+ run("plugin", "install", ref, "--scope", "user");
133
+ return { status: "installed", line: `startup splash installed ${TURN_OFF}` };
134
+ } catch (err) {
135
+ const why = String(err?.stderr || err?.message || err).split("\n")[0].slice(0, 120);
136
+ return { status: "failed", line: `startup splash skipped: ${why} re-run npx forgedock to retry` };
137
+ }
138
+ }
139
+
140
+ /** Remove the plugin and the local marketplace this installer added. Never throws. */
141
+ export function uninstallSplash({ home, env = process.env, exec = defaultSplashExec }) {
142
+ const lines = [];
143
+ const stage = splashStageDir(home);
144
+ const hadLocal = LOCAL_MARKETPLACE in knownMarketplaces(home, env) || existsSync(stage);
145
+ if (!hadLocal) return { removed: false, lines };
146
+ const run = (...args) => exec("claude", args, env);
147
+ let cli = true;
148
+ try { run("--version"); } catch { cli = false; }
149
+ if (cli) {
150
+ try { run("plugin", "uninstall", `${SPLASH_PLUGIN}@${LOCAL_MARKETPLACE}`); lines.push("Removed startup splash plugin"); } catch { /* not installed */ }
151
+ try { run("plugin", "marketplace", "remove", LOCAL_MARKETPLACE); lines.push(`Removed ${LOCAL_MARKETPLACE} marketplace`); } catch { /* not added */ }
152
+ } else {
153
+ lines.push(`claude CLI not found: run /plugin uninstall ${SPLASH_PLUGIN}@${LOCAL_MARKETPLACE} manually`);
154
+ }
155
+ try { rmSync(stage, { recursive: true, force: true }); } catch { /* best-effort */ }
156
+ return { removed: true, lines };
157
+ }
@@ -109,9 +109,16 @@ function flowSection(runs) {
109
109
  for (const r of runs) if (r.code) { codes[r.code] = (codes[r.code] ?? 0) + 1; coded++; }
110
110
  const top = Object.entries(codes).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
111
111
  .map(([code, count]) => ({ code, count, pct: count / coded }));
112
+ // #5339: verified = merged with no transferred or unverified requirement; an older run without the field counts as verified
113
+ const merged = runs.filter((r) => r.reason === "merged");
114
+ const isVerified = (r) => r.verified !== false;
115
+ const ms = new Map();
116
+ for (const r of merged) { const k = r.milestone ?? "(none)"; const g = ms.get(k) ?? { milestone: k, merged: 0, verified: 0 }; g.merged++; if (isVerified(r)) g.verified++; ms.set(k, g); }
112
117
  return {
113
118
  n,
114
- mergedPct: ratio(runs.filter((r) => r.reason === "merged").length, n),
119
+ mergedPct: ratio(merged.length, n),
120
+ verifiedPct: ratio(merged.filter(isVerified).length, n),
121
+ milestones: [...ms.values()].sort((a, b) => a.milestone.localeCompare(b.milestone)),
115
122
  needsHumanPct: ratio(runs.filter((r) => r.reason === "needs-human").length, n),
116
123
  remediationPct: ratio(runs.filter((r) => r.remediated).length, n),
117
124
  codesN: coded, codes: top,
@@ -0,0 +1,289 @@
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
+ import { pathDomains, riskClassOf, riskPathHits, parseEnforceDomains, parseRiskPaths } from "../lean/review-trigger.mjs";
17
+
18
+ export const DEFAULT_OUTCOME_MIN_N = 20;
19
+ export const DEFAULT_WINDOW_DAYS = 7;
20
+ export const DEFAULT_LOOKBACK_DAYS = 30;
21
+ export const PAGE_SIZE = 100;
22
+ export const SIGNALS = ["reverted", "reopened", "cited", "same_hunks"];
23
+ export const OUTCOME_INSUFFICIENT = "insufficient data";
24
+ export const HIGHER = "nonconforming merges show a higher defect rate";
25
+ export const NOT_HIGHER = "no higher defect rate shown for nonconforming merges";
26
+ const DAY = 86400000;
27
+ const ms = (ts) => { const t = Date.parse(ts ?? ""); return Number.isFinite(t) ? t : null; };
28
+ const r4 = (x) => Math.round(x * 1e4) / 1e4;
29
+ const esc = (s) => String(s).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
30
+
31
+ /** Wilson score interval [low, high] for k successes of n (z = 1.96, 95%); null when n is 0. */
32
+ export function wilson(k, n, z = 1.96) {
33
+ if (!n) return null;
34
+ const p = k / n, z2 = z * z, d = 1 + z2 / n;
35
+ const c = (p + z2 / (2 * n)) / d, h = (z * Math.sqrt((p * (1 - p)) / n + z2 / (4 * n * n))) / d;
36
+ return [r4(Math.max(0, c - h)), r4(Math.min(1, c + h))];
37
+ }
38
+
39
+ /** One 2x2 cell: n, defects, rate and interval; rate and interval are null (insufficient) under minN. */
40
+ export function cell(rows, minN) {
41
+ const n = rows.length, defects = rows.filter((r) => r.defect).length;
42
+ const insufficient = n < minN;
43
+ return { n, defects, rate: insufficient || !n ? null : r4(defects / n), interval: insufficient ? null : wilson(defects, n), insufficient };
44
+ }
45
+
46
+ /** "higher" when the nonconforming interval lies wholly above the conforming one; "insufficient data" when a cell is under min n. */
47
+ export function conclude(nonconforming, conforming) {
48
+ if (nonconforming.insufficient || conforming.insufficient || !nonconforming.interval || !conforming.interval) return OUTCOME_INSUFFICIENT;
49
+ return nonconforming.interval[0] > conforming.interval[1] ? HIGHER : NOT_HIGHER;
50
+ }
51
+
52
+ function twoByTwo(rows, minN) {
53
+ const nonconforming = cell(rows.filter((r) => r.state === "nonconforming"), minN), conforming = cell(rows.filter((r) => r.state === "conforms"), minN);
54
+ return { nonconforming, conforming, conclusion: conclude(nonconforming, conforming) };
55
+ }
56
+
57
+ /** Numbers that identify `p` as a cause: the PR and its closing issues. */
58
+ const refsOf = (p) => [p.number, ...(p.closingIssues ?? []).map((i) => i.number)].filter((x) => Number.isSafeInteger(x));
59
+ const text = (q) => `${q.title ?? ""}\n${q.body ?? ""}`;
60
+ const isRevert = (q) => /^revert\b/i.test(q.title ?? "");
61
+ export const isFix = (q) => /^(fix|hotfix|bugfix)\b/i.test(q.title ?? "") || /^revert\b/i.test(q.title ?? "");
62
+
63
+ /** True when a later PR `q` reverts `p`. */
64
+ export function reverts(q, p, repo) {
65
+ if (!isRevert(q)) return false;
66
+ const t = text(q);
67
+ if (repo && new RegExp(`Reverts\\s+${esc(repo)}#${p.number}\\b`, "i").test(t)) return true;
68
+ if (new RegExp(`(^|[^\\w/])#${p.number}\\b`).test(t)) return true;
69
+ return Boolean(p.title) && (q.title ?? "").includes(`"${p.title}"`);
70
+ }
71
+
72
+ /** True when a later PR `q` cites `p` (or its issue) as the cause: "fix ... #N" or "review-finding ... #N" on one line. */
73
+ export function cites(q, p) {
74
+ if (isRevert(q)) return false;
75
+ for (const n of refsOf(p)) {
76
+ const re = new RegExp(`(\\bfix(e[sd])?\\b|review[- ]finding)[^\\n]*?(^|[^\\w/])#${n}\\b`, "im");
77
+ if (re.test(text(q))) return true;
78
+ }
79
+ return false;
80
+ }
81
+
82
+ const blameMemo = new WeakMap();
83
+
84
+ /** Merge shas that a fix PR's old-side lines blame to, computed once per fix sha per git probe object (#5372); null when unresolved. */
85
+ function blamedBy(q, git) {
86
+ let memo = blameMemo.get(git);
87
+ if (!memo) blameMemo.set(git, (memo = new Map()));
88
+ if (memo.has(q.mergeSha)) return memo.get(q.mergeSha);
89
+ const ranges = q.mergeSha ? git.oldRanges(q.mergeSha) : null;
90
+ let entry = null;
91
+ if (ranges) {
92
+ entry = { shas: new Set(), unresolved: false };
93
+ for (const r of ranges) {
94
+ const shas = git.blame(`${q.mergeSha}^`, r.file, r.start, r.end);
95
+ if (shas == null) { entry.unresolved = true; continue; }
96
+ for (const s of shas) entry.shas.add(s);
97
+ }
98
+ }
99
+ memo.set(q.mergeSha, entry);
100
+ return entry;
101
+ }
102
+
103
+ /** Blame each fix PR once up front, reporting {phase: "same-hunks", done, total, etaMs} so a long run is not silent. */
104
+ export function warmSameHunks(fixes, git, onProgress, now = Date.now) {
105
+ const todo = fixes.filter((q) => q.mergeSha);
106
+ const t0 = now();
107
+ todo.forEach((q, i) => {
108
+ blamedBy(q, git);
109
+ const done = i + 1;
110
+ onProgress?.({ phase: "same-hunks", done, total: todo.length, etaMs: done < todo.length ? ((now() - t0) / done) * (todo.length - done) : 0 });
111
+ });
112
+ }
113
+
114
+ /**
115
+ * 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
116
+ * resolved without one (or there is none), null when git is missing or a needed probe could not resolve. Each fix PR is
117
+ * blamed once per git probe object, not once per lane PR.
118
+ */
119
+ export function sameHunks(p, laterFixes, git) {
120
+ if (!laterFixes.length) return false;
121
+ if (!git || !p.mergeSha) return null;
122
+ let unresolved = false;
123
+ for (const q of laterFixes) {
124
+ const entry = blamedBy(q, git);
125
+ if (!entry) { unresolved = true; continue; }
126
+ if (entry.shas.has(p.mergeSha)) return true;
127
+ if (entry.unresolved) unresolved = true;
128
+ }
129
+ return unresolved ? null : false;
130
+ }
131
+
132
+ /**
133
+ * The report core (pure). prs: merged PRs [{repo, number, title, body, mergedAt, mergeSha, closingIssues: [{number, reopenedAt: [ts]}]}];
134
+ * verdicts: Map from conformanceVerdicts (keys pr:N, issue:N). A PR whose window has not elapsed by `now` is pending and left
135
+ * out of the cells. A PR with no verdict is not a lane PR.
136
+ */
137
+ 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, surfacesOf = surfacesOfFiles, onProgress = null }) {
138
+ const win = windowDays * DAY;
139
+ const merged = prs.filter((p) => ms(p.mergedAt) != null).sort((a, b) => ms(a.mergedAt) - ms(b.mergedAt));
140
+ const sinceMs = ms(since);
141
+ if (git) warmSameHunks(merged.filter((q) => isFix(q) && (sinceMs == null || ms(q.mergedAt) >= sinceMs)), git, onProgress);
142
+ const rows = [];
143
+ let unjoined = 0, pending = 0, unresolved = 0;
144
+ for (const p of merged) {
145
+ const t = ms(p.mergedAt);
146
+ if (sinceMs != null && t < sinceMs) continue;
147
+ const v = verdicts.get(`pr:${p.number}`) ?? refsOf(p).slice(1).map((i) => verdicts.get(`issue:${i}`)).find(Boolean) ?? null;
148
+ if (!v) { unjoined++; continue; }
149
+ if (t + win > now) { pending++; continue; }
150
+ 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);
151
+ const signals = {
152
+ reverted: later.some((q) => reverts(q, p, p.repo)),
153
+ reopened: (p.closingIssues ?? []).some((i) => (i.reopenedAt ?? []).some((ts) => ms(ts) > t && ms(ts) <= t + win)),
154
+ cited: later.some((q) => cites(q, p)),
155
+ same_hunks: sameHunks(p, later.filter(isFix), git),
156
+ };
157
+ if (signals.same_hunks === null) unresolved++;
158
+ 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 ?? [],
159
+ source: v.source ?? null, signals, defect: SIGNALS.some((s) => signals[s] === true), ...(p.files?.length ? { surfaces: surfacesOf(p.files) } : {}) });
160
+ }
161
+ const repos = {};
162
+ for (const repo of [...new Set(rows.map((r) => r.repo ?? "unknown"))].sort()) {
163
+ const rs = rows.filter((r) => (r.repo ?? "unknown") === repo);
164
+ const kinds = [...new Set(rs.flatMap((r) => (r.state === "nonconforming" ? r.kinds : [])))].sort();
165
+ const confRows = rs.filter((r) => r.state === "conforms");
166
+ const by_kind = {};
167
+ for (const k of kinds) {
168
+ const nonconforming = cell(rs.filter((r) => r.state === "nonconforming" && r.kinds.includes(k)), minN), conforming = cell(confRows, minN);
169
+ by_kind[k] = { nonconforming, conforming, conclusion: conclude(nonconforming, conforming) };
170
+ }
171
+ const by_mode = {};
172
+ 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);
173
+ const by_surface = {};
174
+ for (const sf of [...new Set(rs.flatMap((r) => r.surfaces ?? []))].sort()) by_surface[sf] = twoByTwo(rs.filter((r) => r.surfaces?.includes(sf)), minN);
175
+ repos[repo] = { overall: twoByTwo(rs, minN), by_kind, by_mode, by_surface };
176
+ }
177
+ const overall = twoByTwo(rows, minN);
178
+ return {
179
+ window_days: windowDays, min_n: minN, since: since ?? null,
180
+ sources: { merged_prs: merged.length, lane_prs: rows.length, pending, unjoined, same_hunks_unresolved: unresolved, git: Boolean(git), graphql_calls: graphqlCalls },
181
+ repos, overall, conclusion: overall.conclusion, prs: rows,
182
+ };
183
+ }
184
+
185
+ /** #5283: the risk surfaces a PR's files touch: `domain:<d>` (review-roster path rules) and `risk:<class>` (built-in risk words). */
186
+ export function surfacesOfFiles(files = []) {
187
+ const domains = pathDomains(files) ?? [];
188
+ const classes = files.map(riskClassOf).filter(Boolean);
189
+ return [...new Set([...domains.map((d) => `domain:${d}`), ...classes.map((c) => `risk:${c}`)])].sort();
190
+ }
191
+
192
+ /**
193
+ * #5283: replay named PRs against a would-be enforcement config (review.enforce_domains / review.risk_paths), window-free.
194
+ * Per PR: `enforced` = a configured surface was hit and the shadow verdict is nonconforming (the lane would block);
195
+ * `flagged` = a configured surface was hit but the verdict would pass (enforce cannot block a passing review);
196
+ * `none` = no configured surface hit. `missing` lists numbers not among `prs`.
197
+ */
198
+ export function replayPrs({ prs = [], verdicts = new Map(), numbers = [], enforceDomains = [], riskPaths = [], surfacesOf = surfacesOfFiles }) {
199
+ const doms = parseEnforceDomains(enforceDomains), globs = parseRiskPaths(riskPaths);
200
+ const rows = [], missing = [];
201
+ for (const n of numbers) {
202
+ const p = prs.find((x) => x.number === n);
203
+ if (!p) { missing.push(n); continue; }
204
+ const v = verdicts.get(`pr:${n}`) ?? (p.closingIssues ?? []).map((i) => verdicts.get(`issue:${i.number}`)).find(Boolean) ?? null;
205
+ const surfaces = surfacesOf(p.files ?? []);
206
+ const hits = [...surfaces.filter((s) => s.startsWith("domain:") && doms.includes(s.slice(7))), ...riskPathHits(p.files ?? [], globs).map((f) => `path:${f}`)];
207
+ const state = v?.state ?? null;
208
+ rows.push({ repo: p.repo ?? null, pr: n, mode: v?.mode ?? null, state, surfaces, hits, outcome: !hits.length ? "none" : state === "nonconforming" ? "enforced" : "flagged" });
209
+ }
210
+ return { enforce_domains: doms, risk_paths: globs, prs: rows, missing };
211
+ }
212
+
213
+ export function renderReplay(r) {
214
+ const out = [`replay (enforce_domains: ${r.enforce_domains.join(",") || "-"}; risk_paths: ${r.risk_paths.join(",") || "-"})`, "", "| PR | mode | shadow verdict | surfaces | outcome |", "|---|---|---|---|---|",
215
+ ...r.prs.map((x) => `| #${x.pr} | ${x.mode ?? "n/a"} | ${x.state ?? "no verdict"} | ${x.surfaces.join(", ") || "-"} | ${x.outcome} |`)];
216
+ if (r.missing.length) out.push("", `not found in the fetched PRs (widen --since): ${r.missing.map((n) => `#${n}`).join(", ")}`);
217
+ return out.join("\n");
218
+ }
219
+
220
+ const pct = (x) => (x == null ? "n/a" : `${Math.round(x * 1000) / 10}%`);
221
+ const fmtCell = (c) => `${c.defects}/${c.n} ${pct(c.rate)}${c.interval ? ` [${pct(c.interval[0])}, ${pct(c.interval[1])}]` : ""}`;
222
+ const row = (label, x) => `| ${label} | ${fmtCell(x.nonconforming)} | ${fmtCell(x.conforming)} | ${x.conclusion} |`;
223
+ const HEAD = ["| group | nonconforming-merged defects/n rate [95% CI] | conforming-merged defects/n rate [95% CI] | verdict |", "|---|---|---|---|"];
224
+
225
+ export function renderConformanceOutcomes(r) {
226
+ const s = r.sources;
227
+ 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}`
228
+ + `, 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)` : ""}`];
229
+ for (const [repo, x] of Object.entries(r.repos)) {
230
+ out.push("", `## ${repo}`, "", ...HEAD, row("all", x.overall), ...Object.entries(x.by_mode).map(([m, y]) => row(`mode ${m}`, y)),
231
+ ...Object.entries(x.by_kind).map(([k, y]) => row(`kind ${k}`, y)), ...Object.entries(x.by_surface ?? {}).map(([k, y]) => row(`surface ${k}`, y)));
232
+ }
233
+ if (!Object.keys(r.repos).length) out.push("", "no merged lane PR with an elapsed window");
234
+ out.push("", `conclusion: ${r.conclusion}`);
235
+ return out.join("\n");
236
+ }
237
+
238
+ const QUERY = `query($q: String!, $first: Int!, $after: String) {
239
+ search(type: ISSUE, query: $q, first: $first, after: $after) {
240
+ pageInfo { hasNextPage endCursor }
241
+ nodes { ... on PullRequest { number title body mergedAt mergeCommit { oid } repository { nameWithOwner } files(first: 100) { nodes { path } }
242
+ closingIssuesReferences(first: 10) { nodes { number timelineItems(itemTypes: [REOPENED_EVENT], first: 10) { nodes { ... on ReopenedEvent { createdAt } } } } } } }
243
+ }
244
+ }`;
245
+
246
+ /** Sorted unique PR and closing-issue numbers of `prs`: the only items whose telemetry the report needs (#5363). */
247
+ export const joinedNumbers = (prs = []) => [...new Set(prs.flatMap(refsOf))].sort((a, b) => a - b);
248
+
249
+ /** One GraphQL search page -> normalized PRs. */
250
+ export function prsOfPage(data, repo) {
251
+ return (data?.data?.search?.nodes ?? []).filter((n) => Number.isSafeInteger(n?.number) && n.mergedAt).map((n) => ({
252
+ repo: n.repository?.nameWithOwner ?? repo, number: n.number, title: n.title ?? "", body: n.body ?? "", mergedAt: n.mergedAt, mergeSha: n.mergeCommit?.oid ?? null,
253
+ files: (n.files?.nodes ?? []).map((f) => f?.path).filter(Boolean),
254
+ closingIssues: (n.closingIssuesReferences?.nodes ?? []).filter((i) => Number.isSafeInteger(i?.number))
255
+ .map((i) => ({ number: i.number, reopenedAt: (i.timelineItems?.nodes ?? []).map((e) => e?.createdAt).filter(Boolean) })),
256
+ }));
257
+ }
258
+
259
+ /**
260
+ * Read-only GitHub input: merged PRs of `repo` since `since` (ISO; default DEFAULT_LOOKBACK_DAYS before now) up to now, so later
261
+ * reverts and fixes inside the window are in the candidate set. Exactly one `gh api graphql` search call per page of 100 PRs.
262
+ * GitHub search returns at most 1000 results: `capped` reports when that bound was hit.
263
+ */
264
+ const MIN_PAGE_SIZE = 25;
265
+ export async function gatherConformanceOutcomes({ repo, gh, since = null, now = Date.now() }) {
266
+ const from = (since ? new Date(ms(since) ?? now - DEFAULT_LOOKBACK_DAYS * DAY) : new Date(now - DEFAULT_LOOKBACK_DAYS * DAY)).toISOString().slice(0, 10);
267
+ const q = `repo:${repo} is:pr is:merged merged:>=${from}`;
268
+ const prs = [];
269
+ let after = null, calls = 0, capped = false, size = PAGE_SIZE;
270
+ for (;;) {
271
+ let data;
272
+ for (;;) { // #5363: a 502/timeout retries the same cursor with half the page (100 -> 50 -> 25), then fails
273
+ const args = ["api", "graphql", "-f", `query=${QUERY}`, "-f", `q=${q}`, "-F", `first=${size}`, ...(after ? ["-f", `after=${after}`] : [])];
274
+ calls++;
275
+ try { data = JSON.parse(String(await gh(args) ?? "").trim() || "{}"); break; } catch (err) {
276
+ if (!/\b50[234]\b|bad gateway|timed? ?out|timeout|ETIMEDOUT/i.test(String(err?.message ?? err))) throw err;
277
+ if (size <= MIN_PAGE_SIZE) throw new Error(`GitHub keeps failing the PR search at first=${size} (${String(err?.message ?? err).split("\n")[0]}); retry with a narrower --since`);
278
+ size = Math.max(MIN_PAGE_SIZE, Math.floor(size / 2));
279
+ }
280
+ }
281
+ if (Array.isArray(data.errors) && data.errors.length && !data.data) throw new Error(`GraphQL: ${data.errors.map((e) => e?.message).join("; ")}`);
282
+ prs.push(...prsOfPage(data, repo));
283
+ const pi = data?.data?.search?.pageInfo;
284
+ if (!pi?.hasNextPage || !pi.endCursor) break;
285
+ if (prs.length >= 1000) { capped = true; break; }
286
+ after = pi.endCursor;
287
+ }
288
+ return { prs, graphqlCalls: calls, since: `${from}T00:00:00Z`, capped };
289
+ }