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
@@ -8,6 +8,10 @@
8
8
  * run_terminal: reason, pr, milestone, conformance_mode, shadow_would
9
9
  */
10
10
 
11
+ import { existsSync, readFileSync } from "node:fs";
12
+ import { join } from "node:path";
13
+ import { listBatches } from "../lean/batch.mjs";
14
+
11
15
  const list = (v) => (typeof v === "string" && v !== "none" ? v.split(",").filter(Boolean) : []);
12
16
  const day = (ts) => (typeof ts === "string" ? ts.slice(0, 10) : "unknown");
13
17
 
@@ -275,3 +279,68 @@ export function renderLaneProfiles(rep) {
275
279
  + `| Profile | Runs | Conformance rate (reviewed) | Shadow would-block |\n| --- | --- | --- | --- |\n${conf.length ? conf.join("\n") : "| none | 0 | | |"}\n\n`
276
280
  + `Issues with a finished run under every profile: ${rep?.issues_in_all?.length ? rep.issues_in_all.map((i) => `#${i}`).join(", ") : "none"}`;
277
281
  }
282
+
283
+ /**
284
+ * #5210: the last conformance verdict of each lane PR, for `forgedock stats --conformance-outcomes`. Sources, latest wins:
285
+ * FORGE:TELEMETRY `run_terminal` (pr, conformance_mode, shadow_would) plus the issue's last `conformance_shadow` failures;
286
+ * local run-log summaries (local-source summariseLog: pr, conformanceMode, shadowWould, conformanceFailures);
287
+ * batch report rows (`conformance: {mode, would, kinds}`, written by orchestrate from the lane result).
288
+ * would "conforms" is conforming, any other would is nonconforming (its failure codes are the kinds); an enforce merge with
289
+ * no would passed the enforced gate, so it conforms. A shadow run with no would never reached the gate: no verdict.
290
+ * Returns a Map keyed `pr:<n>` and `issue:<n>` of {issue, pr, mode, state, kinds, ts, source}.
291
+ */
292
+ const codes = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === "string" && x) : list(v));
293
+ export function verdictOf({ mode, would, merged, failures }) {
294
+ const m = mode === "enforce" || mode === "shadow" ? mode : null;
295
+ if (typeof would === "string" && would) return { mode: m, state: would === "conforms" ? "conforms" : "nonconforming", kinds: would === "conforms" ? [] : [...new Set(codes(failures))].sort() };
296
+ if (m === "enforce" && merged) return { mode: m, state: "conforms", kinds: [] };
297
+ return null;
298
+ }
299
+ export function conformanceVerdicts({ records = [], runs = [], batchRows = [] } = {}) {
300
+ const out = new Map();
301
+ const put = (v) => {
302
+ if (!v) return;
303
+ for (const k of [v.pr != null ? `pr:${v.pr}` : null, v.issue != null ? `issue:${v.issue}` : null]) {
304
+ if (!k) continue;
305
+ const cur = out.get(k);
306
+ if (!cur || String(v.ts ?? "") >= String(cur.ts ?? "")) out.set(k, v);
307
+ }
308
+ };
309
+ const int = (x) => (Number.isSafeInteger(Number(x)) && Number(x) > 0 ? Number(x) : null);
310
+ for (const row of batchRows) {
311
+ const c = row?.conformance;
312
+ if (!c || typeof c !== "object") continue;
313
+ const v = verdictOf({ mode: c.mode, would: c.would, merged: row.outcome === "merged", failures: c.kinds });
314
+ if (v) put({ issue: int(row.issue), pr: int(row.pr), ...v, ts: row.ts ?? row.created ?? "", source: "batch" });
315
+ }
316
+ for (const r of runs) {
317
+ if (!r?.finished) continue;
318
+ const v = verdictOf({ mode: r.conformanceMode, would: r.shadowWould, merged: r.reason === "merged", failures: r.conformanceFailures });
319
+ if (v) put({ issue: int(r.issue), pr: int(r.pr), ...v, ts: r.endTs ?? "", source: "local" });
320
+ }
321
+ const shadows = new Map();
322
+ for (const r of records) {
323
+ if (r?.event !== "conformance_shadow" || r.issue == null) continue;
324
+ const cur = shadows.get(r.issue);
325
+ if (!cur || String(r.ts ?? "") >= String(cur.ts ?? "")) shadows.set(r.issue, r);
326
+ }
327
+ for (const r of records) {
328
+ if (r?.event !== "run_terminal") continue;
329
+ const sh = shadows.get(r.issue);
330
+ const v = verdictOf({ mode: r.conformance_mode, would: r.shadow_would, merged: r.reason === "merged", failures: sh && String(sh.ts ?? "") <= String(r.ts ?? "￿") ? sh.failures : null });
331
+ if (v) put({ issue: int(r.issue), pr: int(r.pr), ...v, ts: r.ts ?? "", source: "github" });
332
+ }
333
+ return out;
334
+ }
335
+
336
+ /** #5210: report.json rows of the repo's local batches, each stamped with its batch's plan.created as `ts` (no network). */
337
+ export function readBatchRows({ batchRoot, repo = null } = {}) {
338
+ const readJson = (f) => { try { return JSON.parse(readFileSync(f, "utf8")); } catch { return null; } };
339
+ const rows = [];
340
+ for (const id of batchRoot && existsSync(batchRoot) ? listBatches(batchRoot) : []) {
341
+ const dir = join(batchRoot, id), plan = readJson(join(dir, "plan.json")) ?? {};
342
+ if (repo && plan.repo && String(plan.repo).toLowerCase() !== String(repo).toLowerCase()) continue;
343
+ for (const row of readJson(join(dir, "report.json"))?.rows ?? []) if (row && typeof row === "object") rows.push({ ...row, ts: typeof plan.created === "string" ? plan.created : "" });
344
+ }
345
+ return rows;
346
+ }
@@ -41,7 +41,9 @@ function sections(g) {
41
41
  out.push("### Lane wall time by phase", ...(L?.n ? [...table(["phase", "n", "p50", "p90"], Object.entries(L.phases).map(([p, v]) => [p, String(v.n), dur(v.p50), dur(v.p90)])), `Largest: ${L.largest.phase} (${Math.round(L.largest.share * 100)}% of ledger time)`] : [NA]), "");
42
42
  const f = g.flow;
43
43
  out.push("### Flow", ...table(["metric", "value"], [
44
- ["merged", pct(f.mergedPct)], ["needs-human", pct(f.needsHumanPct)], ["remediation rate", pct(f.remediationPct)],
44
+ ["merged", pct(f.mergedPct)], ["verified (merged, no transferred/unverified requirement)", pct(f.verifiedPct)],
45
+ ...(f.milestones ?? []).map((m) => [`milestone ${m.milestone}: merged / verified`, `${m.merged} / ${m.verified}`]),
46
+ ["needs-human", pct(f.needsHumanPct)], ["remediation rate", pct(f.remediationPct)],
45
47
  ["top outcome codes (n=" + f.codesN + ")", f.codes.slice(0, 5).map((x) => `${x.code} ${x.count} (${pct(x.pct)})`).join(", ") || NA],
46
48
  ...(g.firstPass ? [["first-pass rate", `${pct(g.firstPass.rate)} (${g.firstPass.firstPass}/${g.firstPass.n} lanes that reached the build, ${g.firstPass.unknown} unknown)`]] : []),
47
49
  // #4375: the same rate split by whether the context pack carried pitfalls matching the issue's files
@@ -0,0 +1,137 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * forge#5341: feature scoreboard. `forgedock stats --milestone <id|title>` grades a whole milestone, not one issue:
5
+ * - journey status at ship per epic (#5336 FORGE:ACCEPTANCE comments: pass, fail or never-ran, with the head and time)
6
+ * - minutes from the first lane merge to the first green end-to-end run (journey record)
7
+ * - defects found after the last planned child merged, by class (release-review, post-deploy, hotfix, other)
8
+ * - rework share: issues that fix or redo a sibling of the same milestone
9
+ * - operator interventions: hand PRs (head branch is not a lane branch), manual merges (PRs labelled manual-merge) and needs-human issues, plus needs-human run logs
10
+ * Deterministic: GitHub (milestone issues, PRs, epic comments) and optional local run logs; no model, no clock; the gh runner is
11
+ * injected. A missing signal is null (printed n/a), never 0.
12
+ */
13
+ import { readEpics, acceptanceResultOf } from "../lean/acceptance.mjs";
14
+ import { listMilestones } from "../lean/lane.mjs";
15
+
16
+ export const DEFECT_CLASSES = Object.freeze(["release-review", "post-deploy", "hotfix", "other"]);
17
+ const LANE_BRANCH_RE = /^(?:feat|fix|chore|docs|refactor|perf|test)\/issue-\d+/;
18
+ const REWORK_RE = /\b(?:fix(?:es|ed)?|redo|rework|regress\w*|follow-?up|revert\w*)\b[^\n#]*#(\d+)/gi;
19
+ const labelsOf = (i) => (i.labels ?? []).map((l) => (typeof l === "string" ? l : l?.name)).filter(Boolean);
20
+ const has = (i, re) => labelsOf(i).some((l) => re.test(l)) || re.test(String(i.title ?? ""));
21
+ const ms = (t) => { const v = Date.parse(t); return Number.isFinite(v) ? v : null; };
22
+
23
+ /** The defect class of an issue from its labels or title, or null when it is no defect. */
24
+ export function defectClass(i) {
25
+ if (has(i, /release[- ]review/i)) return "release-review";
26
+ if (has(i, /post[- ]deploy/i)) return "post-deploy";
27
+ if (has(i, /hotfix/i)) return "hotfix";
28
+ return labelsOf(i).some((l) => /^(?:bug|defect|regression)$/i.test(l)) ? "other" : null;
29
+ }
30
+
31
+ /** Journey status of one epic's comments: {status: pass|fail|never-ran, head, at, journeys, first_green_at}. */
32
+ export function journeyStatus(epic) {
33
+ const recs = (epic.comments ?? []).map((c) => { const r = acceptanceResultOf(c.body); return r ? { ...r, at: r.at ?? c.created_at } : null; }).filter(Boolean)
34
+ .filter((r) => r.site !== "post-deploy").sort((a, b) => (ms(a.at) ?? 0) - (ms(b.at) ?? 0));
35
+ const last = recs.at(-1);
36
+ const green = recs.find((r) => r.result === "pass");
37
+ return { epic: epic.number, journeys: epic.declared?.journeys?.length ?? 0, status: last ? last.result : "never-ran", head: last?.head ?? null, at: last?.at ?? null, runs: recs.length, first_green_at: green?.at ?? null };
38
+ }
39
+
40
+ /**
41
+ * Pure scoreboard. milestone {number, title, state, closed_at}; issues: the milestone's issues and PRs (GitHub issues API);
42
+ * prs: [{number, merged_at, head_ref}] for the milestone's PRs; epics: readEpics rows; runs: local run summaries (optional).
43
+ */
44
+ export function scoreboard({ milestone, issues = [], prs = [], epics = [], runs = [] }) {
45
+ const plain = issues.filter((i) => !i.pull_request);
46
+ const isEpic = (i) => labelsOf(i).includes("epic");
47
+ const children = plain.filter((i) => !isEpic(i));
48
+ const nums = new Set(children.map((i) => i.number));
49
+ const planned = children.filter((i) => !defectClass(i));
50
+ const mergeTimes = (prs.length ? prs.map((p) => ms(p.merged_at)) : planned.filter((i) => i.state === "closed").map((i) => ms(i.closed_at))).filter((t) => t != null).sort((a, b) => a - b);
51
+ const closedPlanned = planned.map((i) => ms(i.closed_at)).filter((t) => t != null).sort((a, b) => a - b);
52
+ const lastChild = planned.length && planned.every((i) => i.state === "closed") ? closedPlanned.at(-1) ?? null : null;
53
+ const firstMerge = mergeTimes[0] ?? null;
54
+ const journeys = epics.map(journeyStatus);
55
+ const greens = journeys.map((j) => ms(j.first_green_at)).filter((t) => t != null);
56
+ const firstGreen = greens.length ? Math.min(...greens) : null;
57
+ const defects = Object.fromEntries(DEFECT_CLASSES.map((c) => [c, 0]));
58
+ const defectIssues = [];
59
+ for (const i of children) {
60
+ const c = defectClass(i);
61
+ if (c && lastChild != null && (ms(i.created_at) ?? 0) > lastChild) { defects[c]++; defectIssues.push(i.number); }
62
+ }
63
+ const rework = new Set();
64
+ for (const i of children) {
65
+ if (labelsOf(i).includes("rework")) rework.add(i.number);
66
+ for (const m of String(i.body ?? "").matchAll(REWORK_RE)) if (Number(m[1]) !== i.number && nums.has(Number(m[1]))) rework.add(i.number);
67
+ }
68
+ const handPrs = prs.filter((p) => p.head_ref && !LANE_BRANCH_RE.test(p.head_ref) && !/^milestone\//.test(p.head_ref)).map((p) => p.number);
69
+ const manualMerges = issues.filter((i) => i.pull_request && labelsOf(i).some((l) => /^(?:manual[- ]merge|merged[- ]by[- ]hand)$/i.test(l))).map((i) => i.number);
70
+ const needsHuman = children.filter((i) => labelsOf(i).includes("needs-human")).map((i) => i.number);
71
+ const mine = runs.filter((r) => nums.has(Number(r.issue)));
72
+ const costs = mine.map((r) => r.usd ?? r.cost_usd).filter((x) => Number.isFinite(x));
73
+ return {
74
+ milestone: { number: milestone.number, title: milestone.title, state: milestone.state ?? null },
75
+ children: children.length, merged: mergeTimes.length || null,
76
+ journeys,
77
+ journey_status_at_ship: !journeys.length ? null : journeys.every((j) => j.status === "pass") ? "pass" : journeys.some((j) => j.status === "fail") ? "fail" : "never-ran",
78
+ minutes_first_merge_to_first_green: firstMerge != null && firstGreen != null ? Math.max(0, Math.round((firstGreen - firstMerge) / 60000)) : null,
79
+ last_child_merged_at: lastChild != null ? new Date(lastChild).toISOString() : null,
80
+ defects_after_last_child: lastChild != null ? { total: defectIssues.length, by_class: defects, issues: defectIssues } : null,
81
+ rework: children.length ? { issues: [...rework].sort((a, b) => a - b), share: Math.round((rework.size / children.length) * 1e4) / 1e4 } : null,
82
+ interventions: { hand_prs: handPrs, needs_human_issues: needsHuman, manual_merges: manualMerges, needs_human_runs: mine.filter((r) => r.reason === "needs-human").length, total: handPrs.length + manualMerges.length + needsHuman.length },
83
+ cost_usd: costs.length ? Math.round(costs.reduce((a, b) => a + b, 0) * 100) / 100 : null,
84
+ };
85
+ }
86
+
87
+ const jsonl = (raw) => String(raw ?? "").split("\n").map((l) => l.trim()).filter(Boolean).flatMap((l) => { try { return [JSON.parse(l)]; } catch { return []; } });
88
+
89
+ /** The milestone whose number or title is `ref`, or null. */
90
+ export async function findMilestoneByRef({ io, repo, ref }) {
91
+ const r = String(ref);
92
+ return (await listMilestones({ gh: io.gh, repo, state: "all" })).find((m) => String(m.number) === r || m.title === r) ?? null;
93
+ }
94
+
95
+ /** Read a milestone (number or title) with its issues, PRs and epics through an injected `io.gh`; null when it does not exist. */
96
+ export async function gatherScoreboard({ io, repo, ref, runs = [] }) {
97
+ const milestone = await findMilestoneByRef({ io, repo, ref });
98
+ if (!milestone) return null;
99
+ const issues = jsonl(await io.gh(["api", `repos/${repo}/issues?milestone=${milestone.number}&state=all&per_page=100`, "--paginate", "--jq", ".[] | @json"]));
100
+ const prs = [];
101
+ for (const p of issues.filter((i) => i.pull_request)) {
102
+ const row = jsonl(await io.gh(["api", `repos/${repo}/pulls/${p.number}`, "--jq", "{number, merged_at, head_ref: .head.ref} | @json"]))[0];
103
+ if (row) prs.push(row);
104
+ }
105
+ const epics = await readEpics({ io, repo, milestone });
106
+ return scoreboard({ milestone: { ...milestone, state: milestone.state }, issues, prs, epics, runs });
107
+ }
108
+
109
+ const NA = "n/a";
110
+ const fmt = (x, f = String) => (x == null ? NA : f(x));
111
+
112
+ export function renderScoreboard(s) {
113
+ if (!s) return "Feature scoreboard: milestone not found.";
114
+ const d = s.defects_after_last_child, iv = s.interventions;
115
+ return [`## Feature scoreboard: ${s.milestone.title} (#${s.milestone.number})`, "",
116
+ "| metric | value |", "|---|---|",
117
+ `| children | ${s.children} (merged ${fmt(s.merged)}) |`,
118
+ `| journey status at ship | ${fmt(s.journey_status_at_ship)} |`,
119
+ `| first lane merge to first green journey | ${fmt(s.minutes_first_merge_to_first_green, (m) => `${m}m`)} |`,
120
+ `| defects after last child | ${d ? `${d.total} (${DEFECT_CLASSES.map((c) => `${c} ${d.by_class[c]}`).join(", ")})` : NA} |`,
121
+ `| rework share | ${s.rework ? `${Math.round(s.rework.share * 100)}% (${s.rework.issues.length} issues)` : NA} |`,
122
+ `| operator interventions | ${iv.total} (hand PRs ${iv.hand_prs.length}, manual merges ${iv.manual_merges.length}, needs-human ${iv.needs_human_issues.length}) |`,
123
+ `| cost | ${fmt(s.cost_usd, (x) => `$${x.toFixed(2)}`)} |`,
124
+ ...(s.journeys.length ? ["", "| epic | journeys | status | head | at |", "|---|---|---|---|---|", ...s.journeys.map((j) => `| #${j.epic} | ${j.journeys} | ${j.status} | ${j.head ? String(j.head).slice(0, 7) : NA} | ${j.at ?? NA} |`)] : [])].join("\n");
125
+ }
126
+
127
+ /**
128
+ * Promotion gate for a default flag that touches milestone lanes: it passes only while the latest feature-benchmark scorecard
129
+ * has no regression and, when a shipped-milestone scoreboard is given, its journeys are not red. {ok, reasons}.
130
+ */
131
+ export function scoreboardGate({ bench = null, board = null } = {}) {
132
+ const reasons = [];
133
+ if (!bench) reasons.push("no feature benchmark scorecard recorded");
134
+ else if (bench.regression) reasons.push(`feature benchmark regressed: ${bench.regression}`);
135
+ if (board && board.journey_status_at_ship && board.journey_status_at_ship !== "pass") reasons.push(`milestone ${board.milestone.title}: journeys ${board.journey_status_at_ship} at ship`);
136
+ return { ok: !reasons.length, reasons };
137
+ }
@@ -0,0 +1,87 @@
1
+ import { describe, it } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { defectClass, scoreboard, gatherScoreboard, renderScoreboard, scoreboardGate } from "./scoreboard.mjs";
4
+ import { renderAcceptanceComment } from "../lean/acceptance.mjs";
5
+ import { buildReport, parseArgs } from "./index.mjs";
6
+
7
+ const iss = (number, o = {}) => ({ number, state: "closed", title: `t${number}`, body: "", labels: [], created_at: "2026-11-01T00:00:00Z", closed_at: "2026-11-02T00:00:00Z", ...o });
8
+ const ms = { number: 7, title: "Feature X", state: "closed" };
9
+ const acc = (head, at, result) => ({ body: renderAcceptanceComment({ head, at, site: "milestone", rows: [{ name: "j", result, exit: result === "pass" ? 0 : 1, ms: 1, output: "x" }] }), created_at: at });
10
+ const epicRow = (comments) => ({ number: 1, state: "open", declared: { journeys: [{ name: "j", when: "milestone" }] }, comments });
11
+ const ISSUES = [
12
+ iss(1, { labels: [{ name: "epic" }] }),
13
+ iss(2, { closed_at: "2026-11-02T00:00:00Z" }),
14
+ iss(3, { closed_at: "2026-11-03T00:00:00Z" }),
15
+ iss(4, { body: "Fixes #2 after the redo", closed_at: "2026-11-04T00:00:00Z" }),
16
+ iss(5, { labels: [{ name: "bug" }, { name: "post-deploy" }], created_at: "2026-11-06T00:00:00Z" }),
17
+ iss(6, { title: "hotfix: crash", labels: [{ name: "needs-human" }], created_at: "2026-11-07T00:00:00Z" }),
18
+ iss(8, { labels: [{ name: "bug" }], created_at: "2026-11-01T12:00:00Z" }), // before the last child: not a defect after it
19
+ iss(20, { pull_request: {}, closed_at: "2026-11-02T00:00:00Z" }),
20
+ ];
21
+ const PRS = [{ number: 20, merged_at: "2026-11-02T00:00:00Z", head_ref: "feat/issue-2-x" }, { number: 21, merged_at: "2026-11-03T00:00:00Z", head_ref: "hand-fix" }];
22
+
23
+ describe("feature scoreboard", () => {
24
+ it("counts PRs labelled manual-merge as operator interventions", () => {
25
+ const s = scoreboard({ milestone: ms, issues: [iss(2), iss(30, { pull_request: {}, labels: [{ name: "manual-merge" }] })], prs: [] });
26
+ assert.deepEqual(s.interventions.manual_merges, [30]);
27
+ assert.equal(s.interventions.total, 1);
28
+ });
29
+ it("classifies defects by label or title", () => {
30
+ assert.equal(defectClass(iss(1, { labels: ["release-review"] })), "release-review");
31
+ assert.equal(defectClass(iss(1, { title: "hotfix: x" })), "hotfix");
32
+ assert.equal(defectClass(iss(1, { labels: ["bug"] })), "other");
33
+ assert.equal(defectClass(iss(1)), null);
34
+ });
35
+ it("a shipped milestone: journey status, time to first green, defects by class, rework, interventions", () => {
36
+ const epics = [epicRow([acc("a".repeat(40), "2026-11-04T00:00:00Z", "fail"), acc("b".repeat(40), "2026-11-05T00:00:00Z", "pass")])];
37
+ const s = scoreboard({ milestone: ms, issues: ISSUES, prs: PRS, epics });
38
+ assert.equal(s.journey_status_at_ship, "pass");
39
+ assert.equal(s.minutes_first_merge_to_first_green, 3 * 1440);
40
+ assert.equal(s.last_child_merged_at, "2026-11-04T00:00:00.000Z");
41
+ assert.deepEqual(s.defects_after_last_child.by_class, { "release-review": 0, "post-deploy": 1, hotfix: 1, other: 0 });
42
+ assert.deepEqual(s.rework.issues, [4]);
43
+ assert.deepEqual(s.interventions.hand_prs, [21]);
44
+ assert.deepEqual(s.interventions.needs_human_issues, [6]);
45
+ });
46
+ it("red and never-run journeys are not pass; missing data is null, not 0", () => {
47
+ assert.equal(scoreboard({ milestone: ms, issues: ISSUES, epics: [epicRow([acc("a".repeat(40), "2026-11-04T00:00:00Z", "fail")])] }).journey_status_at_ship, "fail");
48
+ const never = scoreboard({ milestone: ms, issues: ISSUES, epics: [epicRow([])] });
49
+ assert.equal(never.journey_status_at_ship, "never-ran");
50
+ assert.equal(never.minutes_first_merge_to_first_green, null);
51
+ const open = scoreboard({ milestone: ms, issues: [iss(2, { state: "open", closed_at: null })], epics: [] });
52
+ assert.equal(open.defects_after_last_child, null);
53
+ assert.equal(open.journey_status_at_ship, null);
54
+ assert.match(renderScoreboard(open), /n\/a/);
55
+ });
56
+ it("run logs add cost and needs-human runs", () => {
57
+ const s = scoreboard({ milestone: ms, issues: ISSUES, runs: [{ issue: 2, usd: 1.5, reason: "merged" }, { issue: 3, usd: 0.25, reason: "needs-human" }, { issue: 99, usd: 9 }] });
58
+ assert.equal(s.cost_usd, 1.75);
59
+ assert.equal(s.interventions.needs_human_runs, 1);
60
+ });
61
+ it("gate: refuses a regressed benchmark, a missing one and red journeys", () => {
62
+ assert.equal(scoreboardGate({ bench: { regression: null } }).ok, true);
63
+ assert.equal(scoreboardGate({ bench: null }).ok, false);
64
+ assert.equal(scoreboardGate({ bench: { regression: "x" } }).ok, false);
65
+ assert.equal(scoreboardGate({ bench: { regression: null }, board: { milestone: ms, journey_status_at_ship: "fail" } }).ok, false);
66
+ });
67
+ it("gatherScoreboard and stats --milestone read the board through gh alone", async () => {
68
+ const acceptanceComment = acc("b".repeat(40), "2026-11-05T00:00:00Z", "pass");
69
+ const gh = async (args) => {
70
+ const a = args.join(" ");
71
+ if (a.includes("/milestones")) return JSON.stringify(ms) + "\n";
72
+ if (a.includes("/pulls/")) return JSON.stringify(PRS[0]) + "\n";
73
+ if (a.includes("/issues?milestone=7&state=all")) return ISSUES.map((i) => JSON.stringify(i)).join("\n");
74
+ if (a.includes("labels=epic")) return JSON.stringify([{ number: 1, state: "open", body: "", user: { login: "bot", type: "Bot" }, author_association: "NONE" }]);
75
+ if (a.includes("/issues/1/comments")) return JSON.stringify({ ...acceptanceComment, user: { login: "bot", type: "Bot" }, author_association: "NONE" }) + "\n";
76
+ return "";
77
+ };
78
+ const s = await gatherScoreboard({ io: { gh }, repo: "o/r", ref: "Feature X" });
79
+ assert.equal(s.milestone.number, 7);
80
+ assert.equal(s.children, 6);
81
+ assert.equal((await gatherScoreboard({ io: { gh }, repo: "o/r", ref: "nope" })), null);
82
+ const report = await buildReport({ minN: 10, ...parseArgs(["--milestone", "7"]), repo: "o/r", local: false, cache: false }, { gh, releaseTimes: [], env: {} });
83
+ assert.equal(report.query.scoreboard.milestone.title, "Feature X");
84
+ assert.ok(report.query.mix, "the verdict mix stays");
85
+ assert.match(renderScoreboard(report.query.scoreboard), /Feature scoreboard: Feature X/);
86
+ });
87
+ });
@@ -0,0 +1,52 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * forgedock stats --self-filed (#5207): the share of new issues the pipeline filed itself, by kind, against a 15% target.
5
+ * The kind comes from the deterministic markers and labels the pipeline writes (scripts/file-deferred-followups.sh,
6
+ * scripts/review-finalize.sh, bin/review-staging.mjs), never from the author: lane-created issues share the bot author.
7
+ */
8
+
9
+ export const SELF_FILED_KINDS = Object.freeze(["follow-up", "review-finding", "staging-review", "rollup"]);
10
+ export const SELF_FILED_TARGET = 0.15;
11
+ const ROLLUP_RE = /FORGE:(POSTDEPLOY_ROLLUP|EXTERNAL_BATCH|BACKLOG_BATCH|HOST_BATCH):/;
12
+ const labelNames = (issue) => (issue?.labels ?? []).map((l) => (typeof l === "string" ? l : l?.name)).filter(Boolean);
13
+
14
+ /** The pipeline-filed kind of one issue (precedence rollup, follow-up, staging-review, review-finding), else null. */
15
+ export function selfFiledKind(issue) {
16
+ const body = String(issue?.body ?? ""), title = String(issue?.title ?? "");
17
+ if (ROLLUP_RE.test(body)) return "rollup";
18
+ if (body.includes("FORGE:DEFERRED_FROM") || /^follow-up:/i.test(title)) return "follow-up";
19
+ const labels = labelNames(issue);
20
+ if (labels.includes("staging-review")) return "staging-review";
21
+ if (labels.includes("review-finding")) return "review-finding";
22
+ return null;
23
+ }
24
+
25
+ /** {repo, since, total, pipeline, share, by_kind, target, met}; share is null when no issue was opened in the window. */
26
+ export function selfFiledReport({ issues, since = null, repo = null }) {
27
+ const sinceMs = since ? Date.parse(since) : NaN;
28
+ const inWindow = (issues ?? []).filter((i) => Number.isNaN(sinceMs) || !i?.createdAt || Date.parse(i.createdAt) >= sinceMs);
29
+ const by_kind = Object.fromEntries(SELF_FILED_KINDS.map((k) => [k, 0]));
30
+ for (const i of inWindow) { const k = selfFiledKind(i); if (k) by_kind[k]++; }
31
+ const total = inWindow.length, pipeline = Object.values(by_kind).reduce((a, b) => a + b, 0);
32
+ const share = total ? pipeline / total : null;
33
+ return { repo, since, total, pipeline, share, by_kind, target: SELF_FILED_TARGET, met: share == null ? null : share < SELF_FILED_TARGET };
34
+ }
35
+
36
+ /** The issues created on/after `since` (YYYY-MM-DD). gh: async (args) => stdout. Unreadable output throws (never a silent 0%). */
37
+ export async function gatherIssues({ gh, repo, since }) {
38
+ const out = await gh(["issue", "list", "-R", repo, "--state", "all", "--search", `created:>=${since}`, "--limit", "1000", "--json", "number,title,body,labels,createdAt"]);
39
+ let issues;
40
+ try { issues = JSON.parse(String(out ?? "")); } catch { throw new Error(`self-filed: unreadable gh issue list output for ${repo}`); }
41
+ if (!Array.isArray(issues)) throw new Error(`self-filed: gh issue list for ${repo} did not return a list`);
42
+ return issues;
43
+ }
44
+
45
+ const pct = (x) => (x == null ? "n/a" : `${(x * 100).toFixed(1)}%`);
46
+ /** One line per kind plus the total share against the target. */
47
+ export function renderSelfFiled(r) {
48
+ const lines = [`self-filed issues, ${r.repo ?? "?"} since ${r.since ?? "?"}: ${r.total} new issue${r.total === 1 ? "" : "s"}`];
49
+ for (const k of SELF_FILED_KINDS) lines.push(` ${k.padEnd(15)} ${String(r.by_kind[k]).padStart(5)} ${pct(r.total ? r.by_kind[k] / r.total : null)}`);
50
+ lines.push(` ${"total".padEnd(15)} ${String(r.pipeline).padStart(5)} ${pct(r.share)} (target < ${pct(r.target)}: ${r.met == null ? "n/a" : r.met ? "met" : "not met"})`);
51
+ return lines.join("\n");
52
+ }
@@ -0,0 +1,71 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { describe, it } from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import { selfFiledKind, selfFiledReport, gatherIssues, renderSelfFiled, SELF_FILED_KINDS, SELF_FILED_TARGET } from "./selffiled.mjs";
6
+ import { buildReport, parseArgs, runStats } from "./index.mjs";
7
+
8
+ const iss = (n, extra = {}) => ({ number: n, title: `issue ${n}`, body: "", labels: [], createdAt: "2026-11-01T00:00:00Z", ...extra });
9
+ const ISSUES = [
10
+ iss(1, { body: "x\n<!-- FORGE:POSTDEPLOY_ROLLUP: default -->\n### #4\n<!-- FORGE:DEFERRED_FROM: #4 -->" }), // rollup wins over follow-up
11
+ iss(2, { body: "<!-- FORGE:EXTERNAL_BATCH: b1 -->" }),
12
+ iss(3, { body: "<!-- FORGE:HOST_BATCH: b1 -->" }),
13
+ iss(4, { body: "<!-- FORGE:BACKLOG_BATCH: b0 -->" }),
14
+ iss(5, { body: "<!-- FORGE:DEFERRED_FROM: #9 -->", labels: [{ name: "review-finding" }] }), // follow-up wins over the label
15
+ iss(6, { title: "follow-up: 3 deferred item(s) from #9" }),
16
+ iss(7, { labels: [{ name: "staging-review" }, { name: "review-finding" }] }),
17
+ iss(8, { labels: ["review-finding"] }),
18
+ ...Array.from({ length: 12 }, (_, i) => iss(100 + i, { labels: [{ name: "bug" }] })),
19
+ iss(200, { createdAt: "2026-09-01T00:00:00Z", body: "<!-- FORGE:EXTERNAL_BATCH: old -->" }), // outside the window
20
+ ];
21
+
22
+ describe("stats --self-filed (#5207)", () => {
23
+ it("classifies by precedence rollup, follow-up, staging-review, review-finding, else null", () => {
24
+ assert.deepEqual(ISSUES.slice(0, 8).map(selfFiledKind), ["rollup", "rollup", "rollup", "rollup", "follow-up", "follow-up", "staging-review", "review-finding"]);
25
+ assert.equal(selfFiledKind(iss(9, { labels: [{ name: "bug" }] })), null);
26
+ assert.equal(selfFiledKind({}), null);
27
+ });
28
+ it("reports the share by kind against the 15% target", () => {
29
+ const r = selfFiledReport({ issues: ISSUES, since: "2026-10-08", repo: "o/r" });
30
+ assert.deepEqual(r.by_kind, { "follow-up": 2, "review-finding": 1, "staging-review": 1, rollup: 4 });
31
+ assert.equal(r.total, 20); assert.equal(r.pipeline, 8); assert.equal(r.share, 0.4);
32
+ assert.equal(r.target, SELF_FILED_TARGET); assert.equal(r.met, false);
33
+ assert.equal(selfFiledReport({ issues: ISSUES.slice(8, 20).concat(ISSUES[7]), since: "2026-10-08" }).met, true);
34
+ const none = selfFiledReport({ issues: [], since: "2026-10-08" });
35
+ assert.equal(none.share, null); assert.equal(none.met, null);
36
+ const out = renderSelfFiled(r);
37
+ for (const k of SELF_FILED_KINDS) assert.match(out, new RegExp(`^ ${k} +\\d+ `, "m"));
38
+ assert.match(out, /total +8 +40\.0% \(target < 15\.0%: not met\)/);
39
+ });
40
+ it("gatherIssues lists every state since the date; unreadable output is an error, never 0%", async () => {
41
+ const calls = [];
42
+ const gh = async (a) => { calls.push(a); return JSON.stringify(ISSUES); };
43
+ assert.equal((await gatherIssues({ gh, repo: "o/r", since: "2026-10-08" })).length, ISSUES.length);
44
+ assert.deepEqual(calls[0], ["issue", "list", "-R", "o/r", "--state", "all", "--search", "created:>=2026-10-08", "--limit", "1000", "--json", "number,title,body,labels,createdAt"]);
45
+ await assert.rejects(gatherIssues({ gh: async () => "rate limited", repo: "o/r", since: "2026-10-08" }), /unreadable/);
46
+ await assert.rejects(gatherIssues({ gh: async () => "{}", repo: "o/r", since: "2026-10-08" }), /did not return a list/);
47
+ });
48
+ it("wires --self-filed through parseArgs and buildReport (default window: 30 days)", async () => {
49
+ assert.equal(parseArgs(["--self-filed"]).selfFiled, true); assert.equal(parseArgs([]).selfFiled, false);
50
+ let seen;
51
+ const gh = async (a) => { seen = a; return JSON.stringify(ISSUES); };
52
+ const r = await buildReport({ ...parseArgs(["--self-filed"]), repo: "o/r" }, { gh, now: () => Date.parse("2026-11-07T00:00:00Z") });
53
+ assert.equal(seen[seen.indexOf("--search") + 1], "created:>=2026-10-08");
54
+ assert.equal(r.query.self_filed.pipeline, 8);
55
+ const d = await buildReport({ ...parseArgs(["--self-filed", "--since", "2026-11-02"]), repo: "o/r" }, { gh });
56
+ assert.equal(d.query.self_filed.since, "2026-11-02"); assert.equal(d.query.self_filed.total, 0);
57
+ await assert.rejects(buildReport({ ...parseArgs(["--self-filed", "--since", "1.2.0"]), repo: "o/r" }, { gh }), /must be a date/);
58
+ });
59
+ it("runStats prints the report, or exits 1 on unreadable gh output", async () => {
60
+ const write = process.stdout.write, err = process.stderr.write; let out = "";
61
+ process.stdout.write = (t) => { out += t; return true; }; process.stderr.write = () => true;
62
+ try {
63
+ assert.equal(await runStats(["--self-filed", "--repo", "o/r", "--since", "2026-10-08"], { gh: async () => JSON.stringify(ISSUES) }), 0);
64
+ assert.match(out, /self-filed issues, o\/r since 2026-10-08: 20 new issues/);
65
+ out = "";
66
+ assert.equal(await runStats(["--self-filed", "--repo", "o/r", "--json"], { gh: async () => JSON.stringify(ISSUES) }), 0);
67
+ assert.equal(JSON.parse(out).query.self_filed.target, 0.15);
68
+ assert.equal(await runStats(["--self-filed", "--repo", "o/r"], { gh: async () => "not json" }), 1);
69
+ } finally { process.stdout.write = write; process.stderr.write = err; }
70
+ });
71
+ });
@@ -376,6 +376,68 @@ describe("cache", () => {
376
376
  await fetchGithubRecords({ repo: "o/r", gh, useCache: false, env: ENV, rateCheck: true, now: () => 1_000_000_000, sleep: async (ms) => { slept.push(ms); } });
377
377
  assert.ok(slept.length > 0 && slept[0] === 101000, `slept ${slept}`);
378
378
  });
379
+ it("comments scan never requests past page 300 and completes when gh 422s beyond it (#5363)", async () => {
380
+ const comments = Array.from({ length: 30050 }, (_, i) => telemetryComment(1 + (i % 5), `e${i}`, "x", ts(1 + Math.floor(i / 100))));
381
+ const base = storeGh(mkItems(5), { comments });
382
+ const pages = [];
383
+ const gh = (args) => {
384
+ const m = /issues\/comments\?.*page=(\d+)/.exec(args.join(" "));
385
+ if (m) { pages.push(Number(m[1])); if (Number(m[1]) > 300) throw new Error("gh: HTTP 422: pagination is limited for this resource"); }
386
+ return base.gh(args);
387
+ };
388
+ const r = await fetchGithubRecords({ repo: "o/r", gh, useCache: false, env: ENV });
389
+ assert.ok(Math.max(...pages) <= 300 && pages.length > 300);
390
+ assert.equal(r.items.length, 5);
391
+ });
392
+ it("a 422 pagination error names a --since bound to retry with (#5363)", async () => {
393
+ const gh = (args) => { if (/issues\/comments\?/.test(args.join(" "))) throw new Error("HTTP 422: pagination is limited for this resource"); return "[]"; };
394
+ await assert.rejects(fetchGithubRecords({ repo: "o/r", gh, useCache: false, env: ENV, since: ts(1) }), /narrower --since/);
395
+ });
396
+ it("numbers mode crawls only the given issues: no listing, no comments scan, cache untouched (#5363)", async () => {
397
+ const env = { ...ENV, FORGE_STATS_CACHE_DIR: join(td, "cache-numbers") };
398
+ const comments = [telemetryComment(2, "e1", "x", ts(2)), telemetryComment(4, "e2", "x", ts(3))];
399
+ const h = storeGh(mkItems(50), { comments });
400
+ const events = [];
401
+ const r = await fetchGithubRecords({ repo: "o/r", gh: h.gh, env, numbers: [4, 2, 2], onProgress: (e) => events.push(e) });
402
+ assert.deepEqual(r.items.map((i) => i.number).sort((a, b) => a - b), [2, 4]);
403
+ assert.equal(r.records.length, 2);
404
+ assert.ok(h.calls.every((c) => /issues\/(2|4)(\/comments)?$/.test(c)), h.calls.join(","));
405
+ assert.ok(events.some((e) => e.phase === "telemetry" && e.total === 2));
406
+ assert.throws(() => readFileSync(join(cacheDir("o/r", env), "cache.json"), "utf8"));
407
+ });
408
+ it("--conformance-outcomes crawls only the joined PR and closing-issue numbers (#5363)", async () => {
409
+ const calls = [];
410
+ const gh = (args) => {
411
+ calls.push(args.join(" "));
412
+ if (/issues\/\d+\/comments/.test(args.join(" "))) return "[]";
413
+ const m = /issues\/(\d+)$/.exec(args.join(" "));
414
+ return m ? JSON.stringify({ number: Number(m[1]), state: "closed", labels: [], created_at: ts(1), updated_at: ts(2) }) : "[]";
415
+ };
416
+ const input = { prs: [{ number: 9, closingIssues: [{ number: 3 }] }, { number: 4, closingIssues: [] }] };
417
+ await buildReport({ repo: "o/r", conformanceOutcomes: true, local: false, cache: false, minN: 10, since: "2026-10-01" },
418
+ { gh, env: ENV, releaseTimes: [], gatherConformanceOutcomes: async () => input, now: () => Date.UTC(2026, 10, 10), git: null });
419
+ const crawl = calls.filter((c) => /issues/.test(c));
420
+ assert.ok(crawl.length > 0 && crawl.every((c) => /issues\/(3|4|9)(\/comments)?$/.test(c)), crawl.join(","));
421
+ });
422
+ it("budget: AlterLab-scale conformance crawl costs two calls per joined issue, no comments scan or listing (#5363, R1 instrumentation)", async () => {
423
+ let n = 0;
424
+ const gh = (args) => {
425
+ const a = args.join(" "); n++;
426
+ if (/issues\/\d+\/comments/.test(a)) return "[]";
427
+ const m = /issues\/(\d+)$/.exec(a);
428
+ if (m) return JSON.stringify({ number: Number(m[1]), state: "closed", labels: [], created_at: ts(1), updated_at: ts(2) });
429
+ throw new Error(`unexpected call: ${a}`);
430
+ };
431
+ const prs = Array.from({ length: 400 }, (_, i) => ({ number: 5000 + i, closingIssues: [{ number: 100 + i }] }));
432
+ await buildReport({ repo: "o/r", conformanceOutcomes: true, local: false, cache: false, minN: 10, since: "2026-10-01" },
433
+ { gh, env: ENV, releaseTimes: [], gatherConformanceOutcomes: async () => ({ prs }), now: () => Date.UTC(2026, 10, 10), git: null });
434
+ assert.ok(n <= 2 * 800, `calls ${n}`);
435
+ });
436
+ it("progress printer shows an ETA when one is known (#5363)", () => {
437
+ const out = [];
438
+ makeProgressPrinter((x) => out.push(x), () => 0)({ phase: "telemetry", done: 1, total: 4, etaMs: 3000 });
439
+ assert.match(out[0], /1\/4 \(eta 3s\)/);
440
+ });
379
441
  it("never skips an item updated mid-crawl (keyset crawl, not page-number pagination)", async () => {
380
442
  const env = { ...ENV, FORGE_STATS_CACHE_DIR: join(td, "cache-midcrawl") };
381
443
  const ts = (n) => new Date(Date.UTC(2026, 9, 1) + n * 60000).toISOString().replace(/\.\d{3}Z$/, "Z");
@@ -536,6 +598,13 @@ describe("context-pack A/B over run logs (forge#4275)", () => {
536
598
  { event: "RUN_TERMINAL", reason, code: "x", context_pack: mode, lane_type: lt },
537
599
  ];
538
600
 
601
+ it("#5334 summariseLog counts an interrupted run's killed-attempt usage (turns, tokens, estimated cost)", () => {
602
+ const s = summariseLog([{ event: "RUN_START", issue: 3 },
603
+ { event: "PHASE_ATTEMPT_USAGE", phase: "implement", turns: 41, usage: { output_tokens: 900, cache_read_input_tokens: 7e6 }, cost_usd: 1.5, cost_usd_delta: 1.5, cost_estimated: true, duration_ms: 60000 },
604
+ { event: "RUN_TERMINAL", reason: "deferred", code: "run.interrupted", model_ms: 60000 }]);
605
+ assert.equal(s.costUsd, 1.5); assert.equal(s.builderTurns, 41); assert.equal(s.cacheReadTokens, 7e6); assert.equal(s.usageEvents, 1);
606
+ });
607
+
539
608
  it("summariseLog carries mode, lane type, builder turns, cache tokens, cost and first-pass", () => {
540
609
  const s = summariseLog(log("on", "child"));
541
610
  assert.deepEqual(s.contextPack, { mode: "on", laneType: "child", ab: false, light: false });
@@ -973,3 +1042,14 @@ describe("env.tool_missing per release (forge#4414)", () => {
973
1042
  assert.equal(after.groups[0].flow.codesN, 2);
974
1043
  });
975
1044
  });
1045
+
1046
+ describe("merged vs verified (#5339)", () => {
1047
+ const run = (n, extra) => ({ source: "local", repo: "o/r", version: "2.0.0", issue: n, run: `r${n}`, finished: true, hydrated: false, usageEvents: 1, reason: "merged", code: null, remediated: false, startTs: null, endTs: null, wallMs: 1, phases: {}, ...extra });
1048
+ it("a merged lane with a transferred requirement is merged but not verified; milestones are split; older runs count as verified", () => {
1049
+ const runs = [run(1, { milestone: "M1", verified: true }), run(2, { milestone: "M1", verified: false }), run(3, { milestone: "M2" }), run(4, { reason: "needs-human" })];
1050
+ const g = aggregate({ runs }, { releaseTimes: [] }).groups.find((x) => x.version === "2.0.0");
1051
+ assert.equal(g.flow.mergedPct, 0.75);
1052
+ assert.equal(g.flow.verifiedPct, 0.5);
1053
+ assert.deepEqual(g.flow.milestones, [{ milestone: "M1", merged: 2, verified: 1 }, { milestone: "M2", merged: 1, verified: 1 }]);
1054
+ });
1055
+ });
package/bin/tui.mjs CHANGED
@@ -14,6 +14,7 @@
14
14
  */
15
15
 
16
16
  import readline from "readline";
17
+ import { TAGLINE } from "./brand.mjs";
17
18
 
18
19
  // ---------------------------------------------------------------------------
19
20
  // ANSI detection — computed once at module load
@@ -1625,7 +1626,7 @@ function gradientText(text, start, end) {
1625
1626
  * Default tagline — used when no context is given, or the given context has
1626
1627
  * no mapped entry in LOGO_TAGLINES.
1627
1628
  */
1628
- const DEFAULT_TAGLINE = "GitHub as a knowledge graph for AI agents";
1629
+ const DEFAULT_TAGLINE = TAGLINE;
1629
1630
 
1630
1631
  /**
1631
1632
  * Context-specific taglines shown under the logo. Keyed by the invoking
@@ -1634,7 +1635,7 @@ const DEFAULT_TAGLINE = "GitHub as a knowledge graph for AI agents";
1634
1635
  * caller.
1635
1636
  */
1636
1637
  const LOGO_TAGLINES = {
1637
- install: "lighting the forge",
1638
+ install: TAGLINE,
1638
1639
  update: "tempering the blade",
1639
1640
  uninstall: "banking the coals",
1640
1641
  doctor: "inspecting the anvil",
@@ -1,5 +1,5 @@
1
1
  ---
2
- description: Guided idea-to-backlog setup for a brand-new project — interview, defaults, doubts, spike doc, validated orchestrate-ready backlog
2
+ description: Guided idea-to-backlog setup for a new project: interview, defaults, doubts, spike doc, validated orchestrate-ready backlog
3
3
  argument-hint: "<free text | path to docs> [--dry-run] [--spike <path>]"
4
4
  ---
5
5
  <!-- SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios -->
@@ -9,7 +9,7 @@ argument-hint: "<free text | path to docs> [--dry-run] [--spike <path>]"
9
9
 
10
10
  **Input**: $ARGUMENTS
11
11
 
12
- This spec holds only judgment. All GitHub writes run in `scripts/bootstrap-create.mjs`. Templates live in `$(forge_root)/templates/bootstrap/`.
12
+ Judgment only; writes run in `scripts/bootstrap-create.mjs`.
13
13
 
14
14
  ```bash
15
15
  type forge_resolve >/dev/null 2>&1 || { setopt nonomatch 2>/dev/null || true; FORGE_SOURCED_ROOT='${CLAUDE_PLUGIN_ROOT}'; for _r in "$(cygpath -u "${FORGEDOCK_HOME:-}" 2>/dev/null || printf %s "${FORGEDOCK_HOME:-}")" '${CLAUDE_PLUGIN_ROOT}' "${FORGE_ROOT:-}" "${FORGE_HOME:-}" "$(readlink -f "$HOME/.claude/commands/work-on.md" 2>/dev/null | sed 's|/commands/work-on\.md$||')" "$(head -n 1 "${CODEX_HOME:-$HOME/.codex}/forge-home" 2>/dev/null)" "$HOME/.claude/plugins/marketplaces/forgedock" "${CLAUDE_CONFIG_DIR:-$HOME/.claude}"/plugins/cache/forgedock/forgedock/* "$HOME/.claude"/plugins/cache/forgedock/forgedock/*; do case "$_r" in /*) [ -f "$_r/scripts/lib/forge-resolve.sh" ] && { . "$_r/scripts/lib/forge-resolve.sh"; break; };; esac; done; type forge_resolve >/dev/null 2>&1 || forge_resolve() { :; }; }
@@ -19,19 +19,20 @@ BOOT_TPL="$(forge_root)/templates/bootstrap"; VALIDATE=$(forge_resolve bootstrap
19
19
 
20
20
  1. **Read the input.** Use the free text, or read each doc at the given path(s).
21
21
  2. **Interview** from `interview.md`. Cover each aspect briefly; skip what the input answers.
22
- 3. **Fill the blanks.** Default every unanswered aspect with a one-line rationale, using the closest `stack-profiles.md` preset. Show them in ONE editable "Here's what I assumed" list and apply the user's edits.
23
- 4. **Ask only genuine doubts** (architecture or cost: native vs PWA, data residency, self-host vs managed DB, product name, repo owner). Ask with AskUserQuestion, at most 4 multiple-choice questions per batch, each with a recommended option. Everything else stays a default. Headless (no AskUserQuestion, e.g. `npx forgedock bootstrap`): take each recommended option and list it under "Here's what I assumed".
24
- 5. **Spike doc.** Write `technical-spike.md` to `--spike` (default `docs/engineering/technical-spike.md`); set the plan's `spikeDoc` to that path. Fill every section and give each decision an ADR-style `**Rationale**:` line.
22
+ 3. **Fill the blanks.** Default every unanswered aspect with a one-line rationale from the closest `stack-profiles.md` preset. Show them in ONE editable "Here's what I assumed" list; apply edits.
23
+ 4. **Ask only genuine doubts** (architecture or cost: native vs PWA, data residency, self-host vs managed DB, repo owner). Use AskUserQuestion: at most 4 multiple-choice questions per batch, each with a recommended option. Everything else stays a default. Headless (no AskUserQuestion, e.g. `npx forgedock bootstrap`): take each recommended option, list it under "Here's what I assumed".
24
+ 5. **Spike doc.** Write `technical-spike.md` to `--spike` (default `docs/engineering/technical-spike.md`); set the plan's `spikeDoc` to that path. Fill every section; each decision gets a `**Rationale**:` line.
25
25
  6. **Plan JSON** in `$TMPDIR` (shape: header of `bootstrap-validate.mjs` and `bootstrap-create.mjs`):
26
26
  - Milestones as dependency layers, foundation first: each depends only on earlier ones (#4659).
27
- - A thin deployable slice (CI deploy workflow, staging env, seed) in milestone 1 or 2, never last.
28
- - A `SPIKE` parent issue.
29
- - Sub-issues from `issue-body.md` with planned paths, `[type:*]` tags, `priority` and `component`.
27
+ - Milestone 1 has one `"skeleton": true` issue owning scaffold (CI, test harness, dependency bootstrap, first runnable build) and one #5336 journey; others depend on it.
28
+ - A thin deployable slice (CI deploy, staging, seed) in milestone 1 or 2, never last.
29
+ - A `SPIKE` parent (epic) with a `forge-acceptance` journey (`acceptance check`).
30
+ - Sub-issues from `issue-body.md`: planned paths, `[type:*]` tags, `priority`, `component`.
30
31
  - `"ui": true` issues carry the full design spec. `"hero": true` issues route to `/design`.
31
- - One `needs-human-issue.md` issue per credential, account or external input, with `gates:` (#4660). Code issues reference it as `#{{KEY}}`, never depend on it, and name the mock that keeps dev and CI green.
32
+ - One `needs-human-issue.md` issue per credential, account or external input, with `gates:` (#4660). Code issues cite it as `#{{KEY}}`, never depend on it, and name the mock keeping dev and CI green.
32
33
  - Sub-issues point at the spike via `**Parent**` only, never `Depends on`.
33
- - `guardrails` and `domainRules` from the interview.
34
- 7. **Validate.** Run `node "$VALIDATE" <plan>`. Fix the plan until it exits 0. Heed `deploy-last` warnings. Never create from an invalid plan.
35
- 8. **Create.** Run `node "$CREATE" <plan>`, adding `--dry-run` when the input has it (preview only, GitHub untouched). It reuses existing issues, so on an error re-run it to resume.
36
- 9. **Hand off.** Print the script's hand-off verbatim: created (links), needs a human (links), and the `/orchestrate` command per milestone, in order.
37
- 10. Later: `npx forgedock plan validate --live` (#4659).
34
+ - `guardrails`, `domainRules` from the interview.
35
+ 7. **Validate.** Run `node "$VALIDATE" <plan>`; fix until it exits 0; heed `deploy-last`. Never create from an invalid plan.
36
+ 8. **Create.** Run `node "$CREATE" <plan>`, adding `--dry-run` when the input has it (preview only, GitHub untouched). It reuses existing issues: re-run to resume.
37
+ 9. **Hand off.** Print the script's hand-off verbatim: created, needs a human, and the `/orchestrate` command per milestone, in order.
38
+ 10. Later: `npx forgedock plan validate --live`.