forgedock 1.53.0 → 1.54.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (186) 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 +258 -0
  6. package/bin/auth/app-token.test.mjs +240 -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 +6 -3
  12. package/bin/engine/telemetry-seam.mjs +8 -2
  13. package/bin/engine/telemetry-seam.test.mjs +17 -0
  14. package/bin/engine-cli.mjs +57 -20
  15. package/bin/first-run.mjs +122 -0
  16. package/bin/forgedock.mjs +128 -146
  17. package/bin/help-text.mjs +144 -0
  18. package/bin/hooks/pre-tool-use.mjs +7 -0
  19. package/bin/journey.mjs +82 -83
  20. package/bin/lean/acceptance.mjs +313 -0
  21. package/bin/lean/acceptance.test.mjs +215 -0
  22. package/bin/lean/activation.mjs +18 -0
  23. package/bin/lean/activation.test.mjs +23 -1
  24. package/bin/lean/batch-health.mjs +74 -1
  25. package/bin/lean/batch-health.test.mjs +54 -1
  26. package/bin/lean/batch.test.mjs +11 -9
  27. package/bin/lean/branchlock.mjs +54 -0
  28. package/bin/lean/branchlock.test.mjs +49 -0
  29. package/bin/lean/ceiling.mjs +72 -0
  30. package/bin/lean/ceiling.test.mjs +54 -0
  31. package/bin/lean/ci-budget.mjs +366 -0
  32. package/bin/lean/ci-budget.test.mjs +167 -0
  33. package/bin/lean/conformance.e2e.test.mjs +7 -0
  34. package/bin/lean/conformance.mjs +77 -19
  35. package/bin/lean/conformance.test.mjs +129 -3
  36. package/bin/lean/context.mjs +35 -6
  37. package/bin/lean/context.test.mjs +27 -1
  38. package/bin/lean/depcache.mjs +25 -1
  39. package/bin/lean/depcache.test.mjs +26 -0
  40. package/bin/lean/e2e.mjs +18 -2
  41. package/bin/lean/e2e.test.mjs +26 -1
  42. package/bin/lean/effects.mjs +40 -11
  43. package/bin/lean/execution.test.mjs +24 -0
  44. package/bin/lean/facts.mjs +3 -3
  45. package/bin/lean/facts.test.mjs +5 -0
  46. package/bin/lean/fixround.mjs +14 -0
  47. package/bin/lean/fixround.test.mjs +25 -2
  48. package/bin/lean/gh-assoc.test.mjs +2 -1
  49. package/bin/lean/integration.mjs +100 -9
  50. package/bin/lean/integration.test.mjs +98 -0
  51. package/bin/lean/issuewatch-parity.mjs +64 -0
  52. package/bin/lean/issuewatch-parity.test.mjs +127 -0
  53. package/bin/lean/issuewatch-release.test.mjs +1 -1
  54. package/bin/lean/issuewatch.mjs +34 -5
  55. package/bin/lean/issuewatch.test.mjs +3 -2
  56. package/bin/lean/lean.mjs +316 -74
  57. package/bin/lean/lean.test.mjs +397 -24
  58. package/bin/lean/mechfix.mjs +136 -0
  59. package/bin/lean/mechfix.test.mjs +95 -0
  60. package/bin/lean/orchestrate.mjs +20 -2
  61. package/bin/lean/phaseledger.mjs +47 -5
  62. package/bin/lean/phaseledger.test.mjs +30 -1
  63. package/bin/lean/precheck.mjs +23 -4
  64. package/bin/lean/precheck.test.mjs +14 -1
  65. package/bin/lean/prereq.mjs +28 -0
  66. package/bin/lean/prereq.test.mjs +20 -0
  67. package/bin/lean/probe.mjs +4 -2
  68. package/bin/lean/prodparity.mjs +52 -0
  69. package/bin/lean/prodparity.test.mjs +67 -0
  70. package/bin/lean/prompts.mjs +69 -12
  71. package/bin/lean/recovery.test.mjs +1 -1
  72. package/bin/lean/release-io.test.mjs +42 -0
  73. package/bin/lean/release-postmerge.mjs +6 -0
  74. package/bin/lean/release-preflight.mjs +58 -0
  75. package/bin/lean/release-preflight.test.mjs +114 -0
  76. package/bin/lean/release-rehearsal.mjs +8 -7
  77. package/bin/lean/release-review.mjs +67 -11
  78. package/bin/lean/release-review.test.mjs +128 -1
  79. package/bin/lean/release-snapshot.mjs +188 -0
  80. package/bin/lean/release-snapshot.test.mjs +190 -0
  81. package/bin/lean/release.mjs +87 -13
  82. package/bin/lean/release.test.mjs +104 -0
  83. package/bin/lean/render.mjs +1 -1
  84. package/bin/lean/replan.mjs +184 -0
  85. package/bin/lean/replan.test.mjs +110 -0
  86. package/bin/lean/resume.mjs +9 -7
  87. package/bin/lean/resume.test.mjs +16 -0
  88. package/bin/lean/schedd.mjs +34 -1
  89. package/bin/lean/schedd.test.mjs +21 -1
  90. package/bin/lean/selfreview.mjs +94 -0
  91. package/bin/lean/selfreview.test.mjs +58 -1
  92. package/bin/lean/selftest-gate.mjs +22 -0
  93. package/bin/lean/selftest-gate.test.mjs +18 -1
  94. package/bin/lean/selftest-journey.mjs +234 -0
  95. package/bin/lean/selftest-journey.test.mjs +130 -0
  96. package/bin/lean/selftest-live.mjs +2 -1
  97. package/bin/lean/seqlease.mjs +35 -1
  98. package/bin/lean/seqlease.test.mjs +15 -0
  99. package/bin/lean/seqreserve.e2e.test.mjs +135 -0
  100. package/bin/lean/seqreserve.mjs +73 -0
  101. package/bin/lean/seqreserve.test.mjs +134 -0
  102. package/bin/lean/sequence.mjs +35 -6
  103. package/bin/lean/seqversioned.mjs +147 -0
  104. package/bin/lean/stagestamp.mjs +28 -0
  105. package/bin/lean/stagestamp.test.mjs +32 -0
  106. package/bin/lean/surfaces.mjs +75 -0
  107. package/bin/lean/surfaces.test.mjs +59 -0
  108. package/bin/lean/toolplace.mjs +28 -0
  109. package/bin/lean/toolplace.test.mjs +24 -0
  110. package/bin/lean/toolstats.mjs +3 -1
  111. package/bin/lean/toolstats.test.mjs +11 -0
  112. package/bin/lean/validatebest.mjs +28 -0
  113. package/bin/lean/validatebest.test.mjs +27 -0
  114. package/bin/pool/agent.mjs +9 -0
  115. package/bin/pool/docker.mjs +5 -0
  116. package/bin/pool/router.mjs +8 -4
  117. package/bin/prereqs.mjs +111 -0
  118. package/bin/replay-timelapse.mjs +149 -0
  119. package/bin/review-staging.mjs +100 -16
  120. package/bin/review-staging.test.mjs +18 -0
  121. package/bin/runner.mjs +49 -7
  122. package/bin/splash-install.mjs +157 -0
  123. package/bin/stats/aggregate.mjs +8 -1
  124. package/bin/stats/conformance-outcomes.mjs +100 -19
  125. package/bin/stats/conformance-outcomes.test.mjs +87 -1
  126. package/bin/stats/depth.mjs +88 -31
  127. package/bin/stats/depth.test.mjs +63 -38
  128. package/bin/stats/efficiency.mjs +26 -5
  129. package/bin/stats/efficiency.test.mjs +45 -1
  130. package/bin/stats/first-review.mjs +77 -0
  131. package/bin/stats/first-review.test.mjs +36 -0
  132. package/bin/stats/firstmerge.mjs +40 -0
  133. package/bin/stats/firstmerge.test.mjs +41 -0
  134. package/bin/stats/github-source.mjs +51 -13
  135. package/bin/stats/index.mjs +91 -15
  136. package/bin/stats/local-source.mjs +1 -0
  137. package/bin/stats/origin.mjs +80 -0
  138. package/bin/stats/origin.test.mjs +58 -0
  139. package/bin/stats/render.mjs +3 -1
  140. package/bin/stats/scoreboard.mjs +137 -0
  141. package/bin/stats/scoreboard.test.mjs +87 -0
  142. package/bin/stats/stats.test.mjs +80 -0
  143. package/bin/tui.mjs +3 -2
  144. package/commands/bootstrap.md +15 -14
  145. package/commands/deploy-pr.md +18 -3
  146. package/commands/forge-stats.md +1 -1
  147. package/commands/forgedock-ci-setup.md +28 -0
  148. package/commands/forgedock-init.md +4 -5
  149. package/commands/issue.md +2 -0
  150. package/commands/milestone.md +9 -1
  151. package/commands/replay.md +2 -0
  152. package/commands/review-pr-staging.md +4 -1
  153. package/commands/work-on/close.md +8 -0
  154. package/docs/CI.md +1 -1
  155. package/docs/CONFIG.md +105 -10
  156. package/docs/ISSUE-WATCH.md +23 -0
  157. package/docs/OUTCOME-CODES.md +1 -0
  158. package/docs/REPLAY.md +9 -0
  159. package/docs/SELFTEST.md +11 -0
  160. package/docs/STATS.md +19 -2
  161. package/docs/eval/README.md +6 -0
  162. package/docs/eval/adversarial-bench.md +68 -0
  163. package/docs/eval/corpus/adversarial-v1.json +285 -0
  164. package/docs/eval/feature-bench.md +42 -0
  165. package/docs/eval/feature-specs/crud-auth/journeys/notes-crud-isolated.mjs +21 -0
  166. package/docs/eval/feature-specs/crud-auth/journeys/register-login.mjs +12 -0
  167. package/docs/eval/feature-specs/crud-auth/spec.md +15 -0
  168. package/docs/site/start-a-new-project.md +2 -1
  169. package/package.json +5 -2
  170. package/plugins/forgedock-splash/.claude-plugin/plugin.json +10 -0
  171. package/plugins/forgedock-splash/README.md +27 -0
  172. package/plugins/forgedock-splash/hooks/hooks.json +1 -0
  173. package/plugins/forgedock-splash/hooks/register.tsx +74 -0
  174. package/plugins/forgedock-splash/hooks/scene.ts +222 -0
  175. package/plugins/forgedock-splash/types/index.d.ts +10 -0
  176. package/scripts/bench-adversarial.mjs +216 -0
  177. package/scripts/bench-feature.mjs +170 -0
  178. package/scripts/bench-lightlane.mjs +2 -2
  179. package/scripts/bootstrap-create.mjs +2 -2
  180. package/scripts/bootstrap-validate.mjs +35 -2
  181. package/scripts/check-spec-size.sh +4 -3
  182. package/scripts/check-spec-size.test.sh +3 -0
  183. package/scripts/plan-validate-live.mjs +40 -6
  184. package/scripts/review-pr-staging-scope.test.sh +1 -1
  185. package/scripts/review-staging-post.sh +23 -0
  186. package/scripts/review-staging-post.test.sh +8 -0
@@ -0,0 +1,40 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * forgedock stats --first-merge (#5290): time from setup start to the first merged PR on a first-run repo.
5
+ * Start = the FORGE:FIRST_RUN marker in the issues `forgedock first-run` filed (earliest wins); merge = the earliest
6
+ * mergedAt among the PRs that closed those issues. GitHub is the register: no local state is read.
7
+ */
8
+ import { parseFirstRunMarker } from "../first-run.mjs";
9
+
10
+ const median = (xs) => { if (!xs.length) return null; const s = [...xs].sort((a, b) => a - b), m = s.length >> 1; return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2; };
11
+
12
+ /** issues: [{number, body, closedByPullRequestsReferences: [{mergedAt}]}] -> {repo, started, merged, minutes, median_minutes, target_minutes, met}. */
13
+ export function firstMergeReport({ issues, repo = null }) {
14
+ const marked = (issues ?? []).map((i) => ({ i, m: parseFirstRunMarker(i?.body) })).filter((x) => x.m);
15
+ if (!marked.length) return { repo, started: null, merged: null, minutes: null, median_minutes: null, target_minutes: 15, met: null, issues: 0 };
16
+ const started = Math.min(...marked.map((x) => Date.parse(x.m.started)));
17
+ const merges = marked.flatMap(({ i }) => (i.closedByPullRequestsReferences ?? []).map((p) => Date.parse(p?.mergedAt)).filter(Number.isFinite));
18
+ const merged = merges.length ? Math.min(...merges) : null;
19
+ const minutes = merged == null ? null : Math.max(0, (merged - started) / 60000);
20
+ return { repo, started: new Date(started).toISOString(), merged: merged == null ? null : new Date(merged).toISOString(), minutes, median_minutes: minutes, target_minutes: 15, met: minutes == null ? null : minutes <= 15, issues: marked.length };
21
+ }
22
+
23
+ /** Median over several repos' reports (those with a merge). */
24
+ export const medianMinutes = (reports) => median(reports.map((r) => r.minutes).filter((x) => x != null));
25
+
26
+ /** gh: async (args) => stdout. Unreadable output throws (never a silent "no data"). */
27
+ export async function gatherFirstRunIssues({ gh, repo }) {
28
+ const out = await gh(["issue", "list", "-R", repo, "--state", "all", "--search", "FORGE:FIRST_RUN in:body", "--limit", "100", "--json", "number,body,closedByPullRequestsReferences"]);
29
+ let issues;
30
+ try { issues = JSON.parse(String(out ?? "")); } catch { throw new Error(`first-merge: unreadable gh issue list output for ${repo}`); }
31
+ if (!Array.isArray(issues)) throw new Error(`first-merge: gh issue list for ${repo} did not return a list`);
32
+ return issues;
33
+ }
34
+
35
+ export function renderFirstMerge(r) {
36
+ if (r.repos) return `${r.repos.map(renderFirstMerge).join("\n")}\nmedian time to first merged PR over ${r.repos.length} repos: ${r.median_minutes == null ? "n/a" : `${r.median_minutes.toFixed(1)} min (target <= ${r.target_minutes}: ${r.met ? "met" : "not met"})`}`;
37
+ if (!r.started) return `time to first merged PR, ${r.repo ?? "?"}: no first-run issues found (run: npx forgedock first-run)`;
38
+ if (r.minutes == null) return `time to first merged PR, ${r.repo ?? "?"}: not merged yet (setup started ${r.started}, ${r.issues} first-run issue${r.issues === 1 ? "" : "s"})`;
39
+ return `time to first merged PR, ${r.repo ?? "?"}: ${r.minutes.toFixed(1)} min (target <= ${r.target_minutes}: ${r.met ? "met" : "not met"}); setup ${r.started}, merged ${r.merged}`;
40
+ }
@@ -0,0 +1,41 @@
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 { firstMergeReport, medianMinutes, gatherFirstRunIssues, renderFirstMerge } from "./firstmerge.mjs";
6
+ import { parseArgs, buildReport } from "./index.mjs";
7
+ import { markerLine } from "../first-run.mjs";
8
+
9
+ const T0 = Date.UTC(2026, 10, 1, 10, 0, 0);
10
+ const iss = (n, startedMs, merges) => ({ number: n, body: `x\n${markerLine(startedMs)}`, closedByPullRequestsReferences: merges.map((m) => ({ mergedAt: new Date(m).toISOString() })) });
11
+
12
+ describe("stats --first-merge (#5290)", () => {
13
+ it("measures earliest start to earliest merge", () => {
14
+ const r = firstMergeReport({ repo: "o/r", issues: [iss(1, T0, [T0 + 12 * 60000]), iss(2, T0 + 60000, [T0 + 9 * 60000]), { number: 3, body: "plain" }] });
15
+ assert.equal(r.minutes, 9);
16
+ assert.equal(r.met, true);
17
+ assert.equal(r.issues, 2);
18
+ });
19
+ it("is not met over 15 minutes and null when unmerged or absent", () => {
20
+ assert.equal(firstMergeReport({ issues: [iss(1, T0, [T0 + 20 * 60000])] }).met, false);
21
+ assert.equal(firstMergeReport({ issues: [iss(1, T0, [])] }).minutes, null);
22
+ assert.equal(firstMergeReport({ issues: [] }).started, null);
23
+ });
24
+ it("takes the median across repos", () => {
25
+ assert.equal(medianMinutes([{ minutes: 5 }, { minutes: 20 }, { minutes: 9 }, { minutes: null }]), 9);
26
+ });
27
+ it("buildReport reads GitHub only and rejects unreadable output", async () => {
28
+ assert.equal(parseArgs(["--first-merge"]).firstMerge, true);
29
+ const rep = await buildReport({ firstMerge: true, repo: "o/r" }, { gh: async () => JSON.stringify([iss(1, T0, [T0 + 600000])]) });
30
+ assert.equal(rep.query.first_merge.minutes, 10);
31
+ assert.match(renderFirstMerge(rep.query.first_merge), /10\.0 min.*met/);
32
+ await assert.rejects(gatherFirstRunIssues({ gh: async () => "oops", repo: "o/r" }), /unreadable/);
33
+ });
34
+ it("--repo a,b reports the median across repos", async () => {
35
+ const by = { "o/a": [iss(1, T0, [T0 + 5 * 60000])], "o/b": [iss(1, T0, [T0 + 25 * 60000])], "o/c": [iss(1, T0, [T0 + 9 * 60000])] };
36
+ const gh = async (a) => JSON.stringify(by[a[a.indexOf("-R") + 1]]);
37
+ const rep = await buildReport({ firstMerge: true, repo: "o/a,o/b,o/c" }, { gh });
38
+ assert.equal(rep.query.first_merge.median_minutes, 9);
39
+ assert.match(renderFirstMerge(rep.query.first_merge), /median time to first merged PR over 3 repos: 9\.0 min/);
40
+ });
41
+ });
@@ -83,7 +83,7 @@ export function runsFromRecords(records) {
83
83
  if (!run._first || r.ts < run._first) run._first = r.ts;
84
84
  if (r.experiment != null && r.arm != null) { run.experiment = String(r.experiment); run.arm = String(r.arm); if (r.arm_overrides != null) run.armOverrides = String(r.arm_overrides); } // #4629, #5206
85
85
  if (r.event === "run_terminal") {
86
- run.finished = true; run.reason = r.reason ?? null; run.code = r.code ?? null; run.endTs = r.ts ?? null; run.wallMs = num(r.wall_ms); run.ledger = unflattenPhases(r); // #4908
86
+ run.finished = true; run.reason = r.reason ?? null; run.code = r.code ?? null; run.endTs = r.ts ?? null; run.milestone = typeof r.milestone === "string" && r.milestone ? r.milestone : null; run.verified = r.verified == null ? null : Number(r.verified) === 1; run.wallMs = num(r.wall_ms); run.ledger = unflattenPhases(r); // #4908, #5339 (milestone, verified)
87
87
  continue;
88
88
  }
89
89
  const id = r.phase ?? "other";
@@ -121,6 +121,8 @@ const PAGE_SIZE = 100;
121
121
  // crawl or a small clock skew is re-listed. Re-reads are idempotent: items are keyed by issue number.
122
122
  const WATERMARK_OVERLAP_MS = 5 * 60 * 1000;
123
123
  const MAX_LIST_REQUESTS = 100000;
124
+ // GitHub refuses page-number pagination of the repo-wide comments endpoint past about 30k items (page 301 at 100 per page).
125
+ const MAX_COMMENT_PAGE = 300;
124
126
 
125
127
  /** Shift an ISO-8601 timestamp by `ms`; an unparsable value is returned unchanged. */
126
128
  export function shiftIso(ts, ms) {
@@ -207,19 +209,52 @@ async function waitForRate(gh, sleep, now) {
207
209
  * and PRs that carry at least one trusted FORGE:TELEMETRY comment in that window. Items without one cost nothing more.
208
210
  */
209
211
  async function scanWindowComments(call, repo, from, env, onPage) {
210
- const base = ["per_page=100", ...(from ? [`since=${sinceParam(from)}`] : [])];
211
212
  const numbers = new Set();
212
- for (let p = 1; p < MAX_LIST_REQUESTS; p++) {
213
- const page = parsePages(await call(["api", `repos/${repo}/issues/comments?${[...base, `page=${p}`].join("&")}`]));
214
- for (const c of page) {
215
- if (!MARKER_RE.test(c?.body ?? "") || !isTrusted(c, env)) continue;
216
- const m = /\/issues\/(\d+)$/.exec(c.issue_url ?? "");
217
- if (m) numbers.add(Number(m[1]));
213
+ let cursor = from, pages = 0;
214
+ for (;;) {
215
+ const base = ["per_page=100", ...(cursor ? [`since=${sinceParam(cursor)}`] : [])];
216
+ let page = [];
217
+ for (let p = 1; p <= MAX_COMMENT_PAGE; p++) {
218
+ let raw;
219
+ try { raw = await call(["api", `repos/${repo}/issues/comments?${[...base, `page=${p}`].join("&")}`]); } catch (err) {
220
+ if (/pagination is limited|HTTP 422/.test(String(err?.message ?? err))) throw new Error(`GitHub's comments pagination cap was hit; retry with a narrower --since (after ${cursor ?? "the start"})`);
221
+ throw err;
222
+ }
223
+ page = parsePages(raw);
224
+ for (const c of page) {
225
+ if (!MARKER_RE.test(c?.body ?? "") || !isTrusted(c, env)) continue;
226
+ const m = /\/issues\/(\d+)$/.exec(c.issue_url ?? "");
227
+ if (m) numbers.add(Number(m[1]));
228
+ }
229
+ onPage(++pages);
230
+ if (page.length < PAGE_SIZE) return numbers;
218
231
  }
219
- onPage(p);
220
- if (page.length < PAGE_SIZE) break;
232
+ // The endpoint refuses pages past ~30k items: restart one page-1 walk from the newest update seen, never request past the cap.
233
+ const next = page.reduce((m, c) => (c?.updated_at && (!m || c.updated_at > m) ? c.updated_at : m), null);
234
+ if (!next || (cursor && next <= cursor)) throw new Error(`GitHub's comments pagination cap was hit and cannot advance; retry with --since later than ${cursor ?? "the start"}`);
235
+ cursor = next;
221
236
  }
222
- return numbers;
237
+ }
238
+
239
+ /**
240
+ * Targeted crawl (#5363): only the given issue/PR numbers are read (metadata plus all comments), with no repo-wide comments
241
+ * scan and no issue listing. Coverage is partial, so the cache is neither read nor written (its watermark would lie).
242
+ */
243
+ async function fetchNumbers({ repo, numbers, gh, env, onProgress, concurrency, now }) {
244
+ const list = [...new Set(numbers.filter((n) => Number.isSafeInteger(n) && n > 0))].sort((a, b) => a - b);
245
+ const items = [], t0 = now();
246
+ let apiCalls = 0, done = 0;
247
+ const eta = () => (done > 0 && done < list.length ? Math.round(((now() - t0) / done) * (list.length - done)) : 0);
248
+ await pool(list, concurrency, async (n) => {
249
+ const [it] = parsePages(await gh(["api", `repos/${repo}/issues/${n}`]));
250
+ const records = parseTelemetryComments(parsePages(await gh(["api", "--paginate", `repos/${repo}/issues/${n}/comments`])), env);
251
+ apiCalls += 2;
252
+ if (it && Number.isInteger(it.number)) items.push({ ...meta(it), records });
253
+ onProgress({ phase: "telemetry", done: ++done, total: list.length, etaMs: eta() });
254
+ });
255
+ const seen = new Set(), records = [];
256
+ for (const it of items) for (const r of it.records) if (!seen.has(r.eid)) { seen.add(r.eid); records.push(r); }
257
+ return { items, records, fetched: list.length, fromCache: false, apiCalls, coveredFrom: null };
223
258
  }
224
259
 
225
260
  /**
@@ -232,8 +267,9 @@ async function scanWindowComments(call, repo, from, env, onPage) {
232
267
  */
233
268
  export async function fetchGithubRecords({ repo, since = null, refresh = false, useCache = true, gh = defaultGh, env = process.env,
234
269
  onProgress = () => {}, concurrency = DEFAULT_CONCURRENCY, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), now = Date.now,
235
- rateCheck = gh === defaultGh } = {}) {
270
+ rateCheck = gh === defaultGh, numbers = null } = {}) {
236
271
  if (!isValidRepo(repo)) throw new Error(`invalid repo: ${repo}`);
272
+ if (Array.isArray(numbers)) return fetchNumbers({ repo, numbers, gh, env, onProgress, concurrency, now });
237
273
  const cache = useCache && !refresh ? loadCache(repo, env) : emptyCache();
238
274
  const start = since ?? null;
239
275
  const hasCover = cache.watermark != null;
@@ -271,6 +307,7 @@ export async function fetchGithubRecords({ repo, since = null, refresh = false,
271
307
  saveCache(repo, { ...emptyCache(), watermark: extend ? (pending.size > 0 ? scanResume() : cap(watermark)) : cache.watermark, coveredFrom: extend ? newFloor : cache.coveredFrom, items }, env);
272
308
  };
273
309
  try {
310
+ const t0 = now();
274
311
  const telemetry = [...await scanWindowComments(call, repo, crawlFrom, env, (p) => onProgress({ phase: "comments", done: p, total: null }))];
275
312
  // A telemetry run spans several comment parts and the window holds only the touched ones, so each such issue's full
276
313
  // comment list is re-read once (bounded pool) and replaces its records.
@@ -280,7 +317,8 @@ export async function fetchGithubRecords({ repo, since = null, refresh = false,
280
317
  await pool(telemetry, concurrency, async (n) => {
281
318
  recordsOf.set(n, parseTelemetryComments(parsePages(await call(["api", "--paginate", `repos/${repo}/issues/${n}/comments`])), env));
282
319
  fetched++;
283
- onProgress({ phase: "telemetry", done: ++done, total: telemetry.length });
320
+ done++;
321
+ onProgress({ phase: "telemetry", done, total: telemetry.length, etaMs: done < telemetry.length ? Math.round(((now() - t0) / done) * (telemetry.length - done)) : 0 });
284
322
  });
285
323
  const listed = new Set();
286
324
  let processed = 0;
@@ -22,9 +22,13 @@ import { readExperiment } from "../experiment.mjs";
22
22
  import { compoundingReport, gatherCompounding, renderCompounding, DEFAULT_BUCKETS, DEFAULT_WINDOW_MS } from "./compounding.mjs";
23
23
  import { poolUtilisation, formatPoolLines } from "./pool.mjs";
24
24
  import { gatherIssues, selfFiledReport, renderSelfFiled } from "./selffiled.mjs";
25
+ import { firstReviewReport, renderFirstReview } from "./first-review.mjs";
26
+ import { firstMergeReport, gatherFirstRunIssues, medianMinutes, renderFirstMerge } from "./firstmerge.mjs";
27
+ import { gatherOriginIssues, originReport, renderOrigin } from "./origin.mjs";
25
28
  import { buildDepth, renderDepth } from "./depth.mjs";
29
+ import { gatherScoreboard, renderScoreboard } from "./scoreboard.mjs";
26
30
  import { batchRoot } from "../lean/batch.mjs";
27
- import { conformanceOutcomes, gatherConformanceOutcomes, renderConformanceOutcomes, DEFAULT_OUTCOME_MIN_N, DEFAULT_WINDOW_DAYS, DEFAULT_LOOKBACK_DAYS } from "./conformance-outcomes.mjs";
31
+ import { conformanceOutcomes, gatherConformanceOutcomes, joinedNumbers, renderConformanceOutcomes, replayPrs, renderReplay, DEFAULT_OUTCOME_MIN_N, DEFAULT_WINDOW_DAYS, DEFAULT_LOOKBACK_DAYS } from "./conformance-outcomes.mjs";
28
32
  import { conformanceVerdicts, readBatchRows } from "./query.mjs";
29
33
  import { gitProbes } from "./compounding.mjs";
30
34
 
@@ -35,7 +39,10 @@ export const HELP = `Usage: forgedock stats [--since <version|date>] [--repo <ow
35
39
  forgedock stats --experiment <id> [--require-met] [--min-n N] [--repo <owner/repo>] [--json]
36
40
  forgedock stats --by version [--post-metrics <pr>] [--min-n N] [--repo <owner/repo>] [--json]
37
41
  forgedock stats --pool [--window 7d,30d] [--repo <owner/repo>] [--json]
42
+ forgedock stats --first-review [--repo <owner/repo>] [--since <date>] [--min-n 20] [--json]
43
+ forgedock stats --first-merge [--repo <owner/repo>[,<owner/repo>...]] [--json]
38
44
  forgedock stats --self-filed [--repo <owner/repo>] [--since <date>] [--json]
45
+ forgedock stats --origin [--repo <owner/repo>] [--since <date>] [--json]
39
46
  forgedock stats --compounding [--window 30d] [--bucket 100,500] [--since <date>] [--min-n N] [--repo <owner/repo>] [--json]
40
47
  forgedock stats --conformance-outcomes [--repo <owner/repo>] [--since <date>] [--window-days 7] [--min-n 20] [--json]
41
48
  forgedock stats --efficiency [--batch <id>] [--window 7d,30d] [--compare <date|version>] [--offline] [--repo <owner/repo>] [--json]
@@ -71,7 +78,9 @@ thresholds under forge.yaml stats.alerts.*. Nothing is printed when none fired o
71
78
 
72
79
  Audit queries (forge#4165; JSON, from structure_delta / run_terminal telemetry, no comment bodies read):
73
80
  --edge FROM:TO merged PRs that added the dependency or import edge FROM -> TO (e.g. @s/web:@s/db)
74
- --milestone M conformance verdict mix and per-day structure series for milestone M
81
+ --milestone M feature scoreboard of milestone M (number or title: journey status at ship, first merge to first green journey, defects
82
+ after the last child by class, rework share, interventions; forge#5341) plus the conformance verdict mix and
83
+ per-day structure series (--json: query.scoreboard, query.mix)
75
84
 
76
85
  Context-pack A/B (forge#4275; local run logs only, no GitHub crawl):
77
86
  --context-ab first-pass yield, builder turns, cache tokens and cost per lane type (rerun, child,
@@ -86,7 +95,8 @@ Pool (forge#4549; local batch reports, no gh):
86
95
 
87
96
  Efficiency (forge#4402; local batch dirs and run logs, gh only for merged issues' bodies, labels and probes):
88
97
  --efficiency $/merge, turns/merge, context/turn per size and model, retries/merge by cause, no-action
89
- lanes, issue quality vs cost and the acceptance pass rate 7 days after promotion
98
+ lanes, issue quality vs cost and the acceptance pass rate 7 days after promotion,
99
+ non-model (wait) time by phase and cause
90
100
  --batch <id> also report one batch (~/.forge/batches/<id>, FORGEDOCK_BATCH_DIR)
91
101
  --window <list> trailing windows over the repo's batches (default 7d,30d)
92
102
  --compare <date|v> before/after A/B around a deploy (date or release tag): equal-span cohorts of batches either side,
@@ -94,7 +104,13 @@ Efficiency (forge#4402; local batch dirs and run logs, gh only for merged issues
94
104
  their delta and full-lane cohorts matched per size (forge#4491)
95
105
  --offline skip the GitHub crawl for merged issues (issue quality and acceptance print n/a)
96
106
 
107
+ Issue origin (#5294; GitHub issues and telemetry):
108
+ --origin requested vs pipeline-generated issues (production, review-finding, follow-up; unknown stays unknown),
109
+ how the pipeline-originated ones closed and their share of cost; --since <date> (default: last 30 days)
110
+
97
111
  Self-filed issues (#5207; GitHub issues only):
112
+ --first-review clean-first-review rate by repo, change type and risk surface, with first-round finding kinds (#5345)
113
+ --first-merge setup start to first merged PR on a first-run repo, against the 15 min target (#5290)
98
114
  --self-filed share of new issues the pipeline filed itself, by kind (follow-up, review-finding, staging-review,
99
115
  rollup), against the 15% target; --since <date> bounds the window (default: the last 30 days)
100
116
 
@@ -104,7 +120,10 @@ Lane depth (forge#5209; local run logs, gh only for post-merge defect signals, n
104
120
  defects (reopen, revert, a fix PR touching the same files within 7 days), grouped by verdict and
105
121
  by every reason/signal code, plus the #5052 light-lane promotion verdict: light-shaped lanes cost
106
122
  <= 1.2x and wall <= 1.3x model time, defect rate <= eligible full lanes of the same size;
107
- "insufficient data" under --min-n per cell. --offline skips the defect crawl (n/a)
123
+ "insufficient data" under --min-n per cell. --offline skips the defect crawl (n/a);
124
+ --since defaults to the last 30 days; defect results of closed windows are cached
125
+ (--no-cache / --refresh), progress goes to stderr; the output ends with a recommendation
126
+ (promote, do not promote, insufficient data) with eligible share and would-be saving
108
127
 
109
128
  Compounding (forge#4696; GitHub + git of the current clone, no model):
110
129
  --compounding reintroduction rate (guarded fix reopened, or its lines blamed by a later guarded fix within 90 days),
@@ -119,6 +138,9 @@ Conformance outcomes (forge#5210; read only: one GraphQL search per 100 merged P
119
138
  touching the same hunks via local git blame); defect rate, n and a Wilson 95% interval of
120
139
  nonconforming-merged vs conforming-merged per repo, mode and failure kind; n/a under --min-n
121
140
  (default ${DEFAULT_OUTCOME_MIN_N} per cell); the last line is the conclusion or "insufficient data"
141
+ --replay <pr,...> with --conformance-outcomes: per named PR, its mode, shadow verdict and risk surfaces, and whether the
142
+ --enforce-domains <list> / --risk-paths <globs> config would have enforced (nonconforming), only flagged
143
+ (verdict would pass) or not touched it; the cells also gain per-surface rows (domain:*, risk:*)
122
144
  --window-days N post-merge defect window in days (default ${DEFAULT_WINDOW_DAYS}); --since defaults to 30 days ago
123
145
 
124
146
  Builder model tiers (forge#4394; local run logs only, no GitHub crawl):
@@ -135,7 +157,7 @@ Lane profile baseline (forge#4436; local run logs only, every run of each issue,
135
157
  export function experimentExit(opts, report) { return opts.requireMet && report.targets_met !== true ? 1 : 0; }
136
158
 
137
159
  export function parseArgs(argv) {
138
- const o = { depth: false, conformanceOutcomes: false, windowDays: null, since: null, repo: null, edge: null, milestone: null, contextAb: false, exploreAb: false, tiers: false, compounding: false, selfFiled: false, bucket: null, laneProfile: false, issues: null, efficiency: false, pool: false, batch: null, windows: null, compare: null, by: null, experiment: null, emitEvent: false, requireMet: false, postMetrics: null, offline: false, json: false, refresh: false, compact: false, local: true, cache: true, minN: DEFAULT_MIN_N, releaseTimes: null, help: false };
160
+ const o = { depth: false, conformanceOutcomes: false, windowDays: null, since: null, repo: null, edge: null, milestone: null, contextAb: false, exploreAb: false, tiers: false, compounding: false, selfFiled: false, origin: false, firstMerge: false, bucket: null, laneProfile: false, issues: null, efficiency: false, pool: false, batch: null, windows: null, compare: null, by: null, experiment: null, emitEvent: false, requireMet: false, postMetrics: null, offline: false, json: false, refresh: false, compact: false, local: true, cache: true, minN: DEFAULT_MIN_N, releaseTimes: null, help: false };
139
161
  const val = (i, name) => {
140
162
  const v = argv[i + 1];
141
163
  if (v == null || v.startsWith("--")) throw new Error(`${name} needs a value`);
@@ -156,11 +178,17 @@ export function parseArgs(argv) {
156
178
  else if (name === "--tiers") o.tiers = true;
157
179
  else if (name === "--compounding") o.compounding = true;
158
180
  else if (name === "--self-filed") o.selfFiled = true;
181
+ else if (name === "--first-merge") o.firstMerge = true;
182
+ else if (name === "--first-review") o.firstReview = true;
183
+ else if (name === "--origin") o.origin = true;
159
184
  else if (name === "--bucket") { const v = take(); if (!/^[1-9]\d*(,[1-9]\d*)*$/.test(v)) throw new Error("--bucket must be a comma list of lane counts"); const b = v.split(",").map(Number); if (b.some((x, i) => i && x <= b[i - 1])) throw new Error("--bucket must be increasing"); o.bucket = b; }
160
185
  else if (name === "--lane-profile") o.laneProfile = true;
161
186
  else if (name === "--issues") { const v = take(); if (!/^[1-9]\d*(,[1-9]\d*)*$/.test(v)) throw new Error("--issues must be a comma list of issue numbers"); o.issues = v.split(",").map(Number); }
162
187
  else if (name === "--conformance-outcomes") o.conformanceOutcomes = true;
163
188
  else if (name === "--window-days") { const v = take(); if (!/^[1-9]\d*$/.test(v)) throw new Error("--window-days must be a positive integer"); o.windowDays = Number(v); }
189
+ else if (name === "--replay") { const v = take(); if (!/^[1-9]\d*(,[1-9]\d*)*$/.test(v)) throw new Error("--replay must be a comma list of PR numbers"); o.replay = v.split(",").map(Number); }
190
+ else if (name === "--enforce-domains") o.enforceDomains = take();
191
+ else if (name === "--risk-paths") o.riskPaths = take();
164
192
  else if (name === "--efficiency") o.efficiency = true;
165
193
  else if (name === "--depth") o.depth = true;
166
194
  else if (name === "--pool") o.pool = true;
@@ -192,6 +220,8 @@ export function parseArgs(argv) {
192
220
  if (o.compare && !o.efficiency) throw new Error("--compare and --offline need --efficiency");
193
221
  if (o.offline && !o.efficiency && !o.depth) throw new Error("--compare and --offline need --efficiency (--offline also works with --depth)");
194
222
  if (o.windowDays != null && !o.conformanceOutcomes) throw new Error("--window-days needs --conformance-outcomes");
223
+ if ((o.replay || o.enforceDomains || o.riskPaths) && !o.conformanceOutcomes) throw new Error("--replay, --enforce-domains and --risk-paths need --conformance-outcomes");
224
+ if ((o.enforceDomains || o.riskPaths) && !o.replay) throw new Error("--enforce-domains and --risk-paths need --replay");
195
225
  if (o.postMetrics && !o.by) throw new Error("--post-metrics needs --by version");
196
226
  return o;
197
227
  }
@@ -245,12 +275,12 @@ export function comparePivot(v, releaseTimes = []) {
245
275
  /** Throttled stderr progress printer (never stdout, so --json stays parseable). */
246
276
  export function makeProgressPrinter(write = (t) => process.stderr.write(t), now = Date.now) {
247
277
  let last = 0, lastPhase = null;
248
- return ({ phase, done, total }) => {
278
+ return ({ phase, done, total, etaMs }) => {
249
279
  const t = now();
250
280
  const final = total != null && done >= total;
251
281
  if (phase === lastPhase && !final && t - last < 2000) return;
252
282
  last = t; lastPhase = phase;
253
- write(`forgedock stats: ${phase} ${done}${total != null ? `/${total}` : ""}\n`);
283
+ write(`forgedock stats: ${phase} ${done}${total != null ? `/${total}` : ""}${etaMs ? ` (eta ${Math.ceil(etaMs / 1000)}s)` : ""}\n`);
254
284
  };
255
285
  }
256
286
 
@@ -306,6 +336,15 @@ export function readAlertConfig(cwd = process.cwd()) {
306
336
  export async function buildReport(opts, deps = {}) {
307
337
  const env = deps.env ?? process.env;
308
338
  const repo = opts.repo;
339
+ if (opts.firstMerge) { // #5290: GitHub issues + closing PRs only
340
+ const gh = deps.gh ?? defaultGh;
341
+ const repos = String(repo).split(",");
342
+ const reports = [];
343
+ for (const r of repos) reports.push(firstMergeReport({ issues: await gatherFirstRunIssues({ gh, repo: r }), repo: r }));
344
+ if (repos.length === 1) return { repo, query: { first_merge: reports[0] } };
345
+ const med = medianMinutes(reports);
346
+ return { repo, query: { first_merge: { repo, repos: reports, median_minutes: med, target_minutes: 15, met: med == null ? null : med <= 15 } } };
347
+ }
309
348
  if (opts.selfFiled) { // #5207: GitHub issues only, no telemetry crawl
310
349
  const p = parseSince(opts.since);
311
350
  if (p.sinceVersion) throw new Error("--self-filed: --since must be a date (YYYY-MM-DD)");
@@ -313,6 +352,15 @@ export async function buildReport(opts, deps = {}) {
313
352
  const issues = await gatherIssues({ gh: deps.gh ?? defaultGh, repo, since });
314
353
  return { repo, query: { self_filed: selfFiledReport({ issues, since, repo }) } };
315
354
  }
355
+ if (opts.origin) { // #5294: GitHub issues plus trusted telemetry runs for cost
356
+ const p = parseSince(opts.since);
357
+ if (p.sinceVersion) throw new Error("--origin: --since must be a date (YYYY-MM-DD)");
358
+ const since = new Date(p.sinceMs ?? (deps.now?.() ?? Date.now()) - 30 * 86400000).toISOString().slice(0, 10);
359
+ const gh = deps.gh ?? defaultGh;
360
+ const issues = await gatherOriginIssues({ gh, repo, since });
361
+ const fetched = await fetchGithubRecords({ repo, since: `${since}T00:00:00Z`, refresh: opts.refresh, useCache: opts.cache, gh: deps.gh, env, onProgress: deps.onProgress, sleep: deps.sleep, now: deps.now });
362
+ return { repo, query: { origin: originReport({ issues, runs: toModel(repo, fetched).runs, since, repo }) } };
363
+ }
316
364
  let releaseTimes = [];
317
365
  if (opts.releaseTimes) releaseTimes = parseReleaseTimes(readFileSync(opts.releaseTimes, "utf8"));
318
366
  else if (deps.releaseTimes) releaseTimes = deps.releaseTimes;
@@ -322,8 +370,15 @@ export async function buildReport(opts, deps = {}) {
322
370
  return { repo, query: { pool } };
323
371
  }
324
372
  if (opts.depth) { // forge#5209: run logs; gh only for post-merge defect signals
325
- const st = sinceToTimestamp(opts.since, releaseTimes), sinceMs = st.since ? Date.parse(st.since) : null;
326
- const depth = await buildDepth({ runsDir: deps.runsDir ?? runsDir(env), repo, sinceMs, gh: opts.offline ? null : (deps.gh ?? defaultGh), minN: opts.minN });
373
+ const st = sinceToTimestamp(opts.since, releaseTimes), nowMs = deps.now?.() ?? Date.now();
374
+ let sinceMs = st.since ? Date.parse(st.since) : null;
375
+ if (sinceMs == null) { // #5318: no --since must not crawl all history
376
+ sinceMs = nowMs - DEFAULT_LOOKBACK_DAYS * 86400000;
377
+ (deps.warn ?? ((t) => process.stderr.write(`${t}\n`)))(`--depth: no --since, using the last ${DEFAULT_LOOKBACK_DAYS} days (pass --since <date> for more)`);
378
+ }
379
+ const depth = await buildDepth({ runsDir: deps.runsDir ?? runsDir(env), repo, sinceMs, gh: opts.offline ? null : (deps.gh ?? defaultGh), minN: opts.minN,
380
+ now: nowMs, env, useCache: opts.cache, refresh: opts.refresh, onProgress: deps.onProgress,
381
+ git: deps.git !== undefined ? deps.git : resolveRepo(null)?.toLowerCase() === repo.toLowerCase() ? gitProbes(process.cwd()) : null });
327
382
  return { repo, query: { depth } };
328
383
  }
329
384
  if (opts.efficiency) { // forge#4402: local batch dirs + run logs; gh only for merged issues
@@ -353,23 +408,33 @@ export async function buildReport(opts, deps = {}) {
353
408
  const bound = sinceToTimestamp(opts.since, releaseTimes);
354
409
  if (opts.conformanceOutcomes && !bound.since) bound.since = new Date((deps.now?.() ?? Date.now()) - DEFAULT_LOOKBACK_DAYS * 86400000).toISOString().replace(/\.\d{3}Z$/, "Z"); // #5210: bounded crawl
355
410
  if (bound.note) (deps.warn ?? ((m) => process.stderr.write(`forgedock stats: ${m}\n`)))(bound.note);
411
+ // #5363: the merged lane PRs come first (one GraphQL search per 100), so only their PRs and closing issues are crawled.
412
+ const input = opts.conformanceOutcomes ? await (deps.gatherConformanceOutcomes ?? gatherConformanceOutcomes)({ repo, gh: deps.gh ?? defaultGh, since: bound.since, now: deps.now?.() ?? Date.now() }) : null;
356
413
  const gh = await fetchGithubRecords({ repo, since: bound.since, refresh: opts.refresh, useCache: opts.cache, gh: deps.gh, env,
357
- onProgress: deps.onProgress, sleep: deps.sleep, now: deps.now });
414
+ onProgress: deps.onProgress, sleep: deps.sleep, now: deps.now, ...(input ? { numbers: joinedNumbers(input.prs) } : {}) });
358
415
  if (opts.edge || opts.milestone) { // forge#4165: audit query instead of the version report
359
416
  const e = opts.edge ? parseEdge(opts.edge) : null;
360
417
  const query = { ...(e ? { edge: { ...e, prs: edgeQuery(gh.records, e.from, e.to) } } : {}), ...(opts.milestone ? { mix: verdictMix(gh.records, gh.items, opts.milestone) } : {}) };
418
+ if (opts.milestone) { // forge#5341: the feature scoreboard from GitHub plus the local run logs; best-effort, absent when the milestone is unknown
419
+ try {
420
+ const runs = opts.local ? (deps.localRuns ?? readLocalRuns(runsDir(env))).filter((r) => r.repo == null || r.repo === repo) : [];
421
+ const board = await gatherScoreboard({ io: { gh: deps.gh ?? defaultGh }, repo, ref: opts.milestone, runs });
422
+ if (board) query.scoreboard = board;
423
+ } catch (e) { (deps.warn ?? ((m) => process.stderr.write(`forgedock stats: ${m}\n`)))(`--milestone: scoreboard unavailable: ${e.message}`); }
424
+ }
361
425
  return { repo, sources: { github: { items: gh.items.length, records: gh.records.length, cached: gh.fromCache } }, query };
362
426
  }
427
+ if (opts.firstReview) return { repo, sources: { github: { items: gh.items.length, records: gh.records.length, cached: gh.fromCache } }, query: { first_review: firstReviewReport({ records: gh.records, repo, minN: opts.minNSet ? opts.minN : undefined }) } }; // #5345
363
428
  if (opts.conformanceOutcomes) { // forge#5210: read only; GraphQL search per 100 PRs + the telemetry records above + local logs + git
364
429
  const now = deps.now?.() ?? Date.now();
365
- const input = await (deps.gatherConformanceOutcomes ?? gatherConformanceOutcomes)({ repo, gh: deps.gh ?? defaultGh, since: bound.since, now });
366
430
  const verdicts = conformanceVerdicts({ records: gh.records,
367
431
  runs: opts.local ? (deps.localRuns ?? readLocalRuns(runsDir(env))).filter((r) => r.repo == null || r.repo === repo) : [],
368
432
  batchRows: opts.local ? (deps.batchRows ?? readBatchRows({ batchRoot: deps.batchRoot ?? batchRoot(env), repo })) : [] });
369
433
  const git = deps.git !== undefined ? deps.git : resolveRepo(null)?.toLowerCase() === repo.toLowerCase() ? gitProbes(process.cwd()) : null;
370
434
  const report = conformanceOutcomes({ prs: input.prs, verdicts, minN: opts.minNSet ? opts.minN : DEFAULT_OUTCOME_MIN_N, windowDays: opts.windowDays ?? DEFAULT_WINDOW_DAYS,
371
- now, git, graphqlCalls: input.graphqlCalls, since: input.since });
435
+ now, git, graphqlCalls: input.graphqlCalls, since: input.since, onProgress: deps.onProgress });
372
436
  if (input.capped) report.sources.capped = true;
437
+ if (opts.replay) report.replay = replayPrs({ prs: input.prs, verdicts, numbers: opts.replay, enforceDomains: opts.enforceDomains ?? "", riskPaths: opts.riskPaths ?? "" });
373
438
  return { repo, sources: { github: { items: gh.items.length, records: gh.records.length, cached: gh.fromCache } }, query: { conformance_outcomes: report } };
374
439
  }
375
440
  const model = toModel(repo, gh);
@@ -408,8 +473,9 @@ export async function runStats(argv, deps = {}) {
408
473
  process.stderr.write(`forgedock stats: --require-met needs --experiment <id>\n`);
409
474
  return 2;
410
475
  }
411
- opts.repo = resolveRepo(opts.repo);
412
- if (!opts.repo || !isValidRepo(opts.repo)) {
476
+ const multi = opts.firstMerge && opts.repo?.includes(","); // #5290: --repo a/x,b/y reports the median across repos
477
+ if (!multi) opts.repo = resolveRepo(opts.repo);
478
+ if (!opts.repo || !(multi ? opts.repo.split(",").every(isValidRepo) : isValidRepo(opts.repo))) {
413
479
  process.stderr.write(`forgedock stats: could not resolve a valid owner/repo (pass --repo owner/repo)\n`);
414
480
  return 2;
415
481
  }
@@ -423,10 +489,14 @@ export async function runStats(argv, deps = {}) {
423
489
  }
424
490
  if (report.query?.experiment && opts.emitEvent) await (deps.emitExperiment ?? (async (r, x) => (await import("../engine-cli.mjs")).experimentEventSink(r, x)))(opts.repo, report.query.experiment);
425
491
  if (report.query?.experiment) { process.stdout.write(`${opts.json ? renderJson(report) : renderExperiment(report.query.experiment)}\n`); return experimentExit(opts, report.query.experiment); }
492
+ if (report.query?.scoreboard && !opts.json) { process.stdout.write(`${renderScoreboard(report.query.scoreboard)}\n`); return 0; }
426
493
  if (report.query?.lane_profile && !opts.json) { process.stdout.write(`${renderLaneProfiles(report.query.lane_profile)}\n`); return 0; }
494
+ if (report.query?.first_review && !opts.json) { process.stdout.write(`${renderFirstReview(report.query.first_review)}\n`); return 0; }
427
495
  if (report.query?.tiers && !opts.json) { process.stdout.write(`${renderTiers(report.query.tiers)}\n`); return 0; }
428
- if (report.query?.conformance_outcomes && !opts.json) { process.stdout.write(`${renderConformanceOutcomes(report.query.conformance_outcomes)}\n`); return 0; }
496
+ if (report.query?.conformance_outcomes && !opts.json) { const co = report.query.conformance_outcomes; process.stdout.write(`${renderConformanceOutcomes(co)}${co.replay ? `\n\n${renderReplay(co.replay)}` : ""}\n`); return 0; }
429
497
  if (report.query?.compounding && !opts.json) { process.stdout.write(`${renderCompounding(report.query.compounding)}\n`); return 0; }
498
+ if (report.query?.first_merge && !opts.json) { process.stdout.write(`${renderFirstMerge(report.query.first_merge)}\n`); return 0; }
499
+ if (report.query?.origin && !opts.json) { process.stdout.write(`${renderOrigin(report.query.origin)}\n`); return 0; }
430
500
  if (report.query?.self_filed && !opts.json) { process.stdout.write(`${renderSelfFiled(report.query.self_filed)}\n`); return 0; }
431
501
  if (report.query?.depth && !opts.json) { process.stdout.write(`${renderDepth(report.query.depth, { repo: report.repo, since: opts.since })}\n`); return 0; }
432
502
  if (report.query?.pool && !opts.json) { process.stdout.write(`${formatPoolLines(report.query.pool).join("\n")}\n`); return 0; }
@@ -441,6 +511,12 @@ export async function runStats(argv, deps = {}) {
441
511
  if (report.query?.context_ab && !opts.json) { process.stdout.write(`${renderContextAb(report.query.context_ab)}\n`); return 0; }
442
512
  if (report.query?.explore_ab && !opts.json) { process.stdout.write(`${renderExploreAb(report.query.explore_ab)}\n`); return 0; }
443
513
  process.stdout.write(`${opts.json || report.query ? renderJson(report) : opts.compact ? renderCompact(report) : renderMarkdown(report)}\n`);
514
+ if (!opts.json && !report.query) { // #5290: activation metric on the default report; best-effort, silent when absent
515
+ try {
516
+ const fm = firstMergeReport({ issues: await gatherFirstRunIssues({ gh: deps.gh ?? defaultGh, repo: opts.repo }), repo: opts.repo });
517
+ if (fm.started) process.stdout.write(`\n${renderFirstMerge(fm)}\n`);
518
+ } catch { /* no first-run data */ }
519
+ }
444
520
  return 0;
445
521
  } catch (err) {
446
522
  process.stderr.write(`forgedock stats: ${err.message}\n`);
@@ -66,6 +66,7 @@ export function summariseLog(events, fallbackIssue = null) {
66
66
  source: "local", repo: start.repo ?? null, version: start.version ?? null, issue: start.issue ?? fallbackIssue, run: start.run ?? null,
67
67
  finished, hydrated: start.hydrated === true, usageEvents,
68
68
  reason: finished ? ev[t].reason ?? null : null, code: finished ? ev[t].code ?? null : null,
69
+ milestone: typeof term?.milestone === "string" && term.milestone ? term.milestone : null, verified: typeof term?.verified === "boolean" ? term.verified : null, // #5339
69
70
  remediated: ev.some((e) => e.event === "PHASE_COMMIT" && e.phase === "remediate"),
70
71
  startTs, endTs, wallMs: finished && !Number.isNaN(a) && !Number.isNaN(b) ? Math.max(0, b - a) : null,
71
72
  phases,
@@ -0,0 +1,80 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * forgedock stats --origin (#5294): requested vs pipeline-generated work. Every issue opened in the window is classed by
5
+ * deterministic markers and labels (selfFiledKind, the FORGE:PRODWATCH marker, the author's bot flag), never guessed:
6
+ * an issue without positive evidence stays "unknown". Pipeline-originated issues also report how they closed and their
7
+ * cost share, from the trusted FORGE:TELEMETRY runs (an issue with no recorded cost is counted apart, never as $0).
8
+ */
9
+ import { selfFiledKind } from "./selffiled.mjs";
10
+
11
+ export const ORIGINS = Object.freeze(["requested", "production", "review-finding", "follow-up", "unknown"]);
12
+ export const PIPELINE_ORIGINS = Object.freeze(["production", "review-finding", "follow-up"]);
13
+ export const OUTCOMES = Object.freeze(["merged", "closed-invalid", "other-closed", "open"]);
14
+ const PRODWATCH_RE = /<!--\s*FORGE:PRODWATCH\b/;
15
+ const INVALID_LABELS = new Set(["invalid", "duplicate", "wontfix"]);
16
+ const labelNames = (issue) => (issue?.labels ?? []).map((l) => (typeof l === "string" ? l : l?.name)).filter(Boolean);
17
+
18
+ /** requested | production | review-finding | follow-up | unknown. Pipeline markers win; a human (non-bot) author is the requested evidence. */
19
+ export function originKind(issue) {
20
+ if (PRODWATCH_RE.test(String(issue?.body ?? "")) || labelNames(issue).includes("prod-watch")) return "production";
21
+ const k = selfFiledKind(issue);
22
+ if (k === "review-finding" || k === "staging-review") return "review-finding";
23
+ if (k === "follow-up" || k === "rollup") return "follow-up";
24
+ const a = issue?.author;
25
+ return a && a.is_bot === false ? "requested" : "unknown";
26
+ }
27
+
28
+ /** merged | closed-invalid | other-closed | open. `run` is the issue's telemetry run (reason "merged" wins over a bare close). */
29
+ export function outcomeOf(issue, run = null) {
30
+ if (String(issue?.state ?? "").toUpperCase() !== "CLOSED") return "open";
31
+ const reason = String(issue?.stateReason ?? "").toUpperCase();
32
+ if (run?.reason === "merged") return "merged";
33
+ if (reason === "NOT_PLANNED" || reason === "DUPLICATE" || labelNames(issue).some((l) => INVALID_LABELS.has(l))) return "closed-invalid";
34
+ return reason === "COMPLETED" ? "merged" : "other-closed";
35
+ }
36
+
37
+ const runUsd = (run) => {
38
+ const v = Object.values(run?.phases ?? {}).map((p) => p.usd).filter((x) => Number.isFinite(x));
39
+ return v.length ? v.reduce((a, b) => a + b, 0) : null;
40
+ };
41
+
42
+ /** {repo, since, total, by_origin:{o:{count, cost_usd, cost_unknown, outcomes}}, cost_usd, pipeline:{count, cost_usd, cost_share}}. */
43
+ export function originReport({ issues, runs = [], since = null, repo = null }) {
44
+ const sinceMs = since ? Date.parse(since) : NaN;
45
+ const inWindow = (issues ?? []).filter((i) => !i?.isPr && (Number.isNaN(sinceMs) || !i?.createdAt || Date.parse(i.createdAt) >= sinceMs));
46
+ const runOf = new Map((runs ?? []).filter((r) => r?.issue != null).map((r) => [Number(r.issue), r]));
47
+ const by_origin = Object.fromEntries(ORIGINS.map((o) => [o, { count: 0, cost_usd: 0, cost_unknown: 0, outcomes: Object.fromEntries(OUTCOMES.map((x) => [x, 0])) }]));
48
+ for (const i of inWindow) {
49
+ const o = by_origin[originKind(i)], run = runOf.get(Number(i.number));
50
+ o.count++;
51
+ o.outcomes[outcomeOf(i, run)]++;
52
+ const usd = runUsd(run);
53
+ if (usd == null) o.cost_unknown++; else o.cost_usd += usd;
54
+ }
55
+ const cost_usd = ORIGINS.reduce((a, k) => a + by_origin[k].cost_usd, 0);
56
+ const pCount = PIPELINE_ORIGINS.reduce((a, k) => a + by_origin[k].count, 0), pCost = PIPELINE_ORIGINS.reduce((a, k) => a + by_origin[k].cost_usd, 0);
57
+ return { repo, since, total: inWindow.length, by_origin, cost_usd, pipeline: { count: pCount, cost_usd: pCost, cost_share: cost_usd > 0 ? pCost / cost_usd : null } };
58
+ }
59
+
60
+ /** Issues created on/after `since` with state and close reason. gh: async (args) => stdout. Unreadable output throws. */
61
+ export async function gatherOriginIssues({ gh, repo, since }) {
62
+ const out = await gh(["issue", "list", "-R", repo, "--state", "all", "--search", `created:>=${since}`, "--limit", "1000", "--json", "number,title,body,labels,createdAt,closedAt,state,stateReason,author"]);
63
+ let issues;
64
+ try { issues = JSON.parse(String(out ?? "")); } catch { throw new Error(`origin: unreadable gh issue list output for ${repo}`); }
65
+ if (!Array.isArray(issues)) throw new Error(`origin: gh issue list for ${repo} did not return a list`);
66
+ return issues;
67
+ }
68
+
69
+ const pct = (x) => (x == null ? "n/a" : `${(x * 100).toFixed(1)}%`);
70
+ const usd = (x) => `$${x.toFixed(2)}`;
71
+ export function renderOrigin(r) {
72
+ const lines = [`issue origin, ${r.repo ?? "?"} since ${r.since ?? "?"}: ${r.total} issue${r.total === 1 ? "" : "s"}`,
73
+ ` ${"origin".padEnd(15)} ${"count".padStart(5)} ${"cost".padStart(9)} ${"no-cost".padStart(7)} outcomes (merged/invalid/other/open)`];
74
+ for (const k of ORIGINS) {
75
+ const o = r.by_origin[k];
76
+ lines.push(` ${k.padEnd(15)} ${String(o.count).padStart(5)} ${usd(o.cost_usd).padStart(9)} ${String(o.cost_unknown).padStart(7)} ${OUTCOMES.map((x) => o.outcomes[x]).join("/")}`);
77
+ }
78
+ lines.push(` pipeline-originated: ${r.pipeline.count} issue${r.pipeline.count === 1 ? "" : "s"}, ${usd(r.pipeline.cost_usd)} of ${usd(r.cost_usd)} (${pct(r.pipeline.cost_share)} of recorded cost)`);
79
+ return lines.join("\n");
80
+ }
@@ -0,0 +1,58 @@
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 { originKind, outcomeOf, originReport, gatherOriginIssues, renderOrigin } from "./origin.mjs";
6
+ import { buildReport, parseArgs } from "./index.mjs";
7
+
8
+ const human = { login: "a", is_bot: false }, bot = { login: "forge", is_bot: true };
9
+ const iss = (n, extra = {}) => ({ number: n, title: `issue ${n}`, body: "", labels: [], createdAt: "2026-11-01T00:00:00Z", state: "CLOSED", stateReason: "COMPLETED", author: bot, ...extra });
10
+ const run = (n, usd, reason = "merged") => ({ issue: n, reason, phases: { implement: { usd } } });
11
+
12
+ describe("stats --origin (#5294)", () => {
13
+ it("classifies by markers first, human author as requested, else unknown", () => {
14
+ assert.equal(originKind(iss(1, { body: "<!-- FORGE:PRODWATCH source=x -->", author: human })), "production");
15
+ assert.equal(originKind(iss(2, { labels: ["review-finding"], author: human })), "review-finding");
16
+ assert.equal(originKind(iss(3, { labels: [{ name: "staging-review" }] })), "review-finding");
17
+ assert.equal(originKind(iss(4, { body: "<!-- FORGE:DEFERRED_FROM: #1 -->" })), "follow-up");
18
+ assert.equal(originKind(iss(5, { author: human })), "requested");
19
+ assert.equal(originKind(iss(6)), "unknown");
20
+ assert.equal(originKind(iss(7, { author: undefined })), "unknown");
21
+ });
22
+ it("classifies outcomes", () => {
23
+ assert.equal(outcomeOf(iss(1, { state: "OPEN", stateReason: null })), "open");
24
+ assert.equal(outcomeOf(iss(1, { stateReason: "NOT_PLANNED" })), "closed-invalid");
25
+ assert.equal(outcomeOf(iss(1, { stateReason: "COMPLETED", labels: ["duplicate"] })), "closed-invalid");
26
+ assert.equal(outcomeOf(iss(1, { stateReason: "COMPLETED" })), "merged");
27
+ assert.equal(outcomeOf(iss(1, { stateReason: null }), run(1, 1)), "merged");
28
+ assert.equal(outcomeOf(iss(1, { stateReason: null })), "other-closed");
29
+ });
30
+ const ISSUES = [iss(1, { author: human }), iss(2, { labels: ["review-finding"] }), iss(3, { labels: ["review-finding"], stateReason: "NOT_PLANNED" }),
31
+ iss(4, { body: "<!-- FORGE:DEFERRED_FROM: #1 -->", state: "OPEN", stateReason: null }), iss(5), iss(6, { createdAt: "2026-09-01T00:00:00Z" }), iss(7, { isPr: true })];
32
+ it("counts, cost share, unknown cost and window", () => {
33
+ const r = originReport({ issues: ISSUES, runs: [run(1, 6), run(2, 2), run(3, 2, "failed")], since: "2026-10-01", repo: "o/r" });
34
+ assert.equal(r.total, 5);
35
+ assert.deepEqual(Object.fromEntries(Object.entries(r.by_origin).map(([k, v]) => [k, v.count])), { requested: 1, production: 0, "review-finding": 2, "follow-up": 1, unknown: 1 });
36
+ assert.equal(r.by_origin["review-finding"].cost_usd, 4);
37
+ assert.equal(r.by_origin["review-finding"].outcomes["closed-invalid"], 1);
38
+ assert.equal(r.by_origin["follow-up"].cost_unknown, 1);
39
+ assert.equal(r.by_origin["follow-up"].outcomes.open, 1);
40
+ assert.equal(r.cost_usd, 10);
41
+ assert.equal(r.pipeline.cost_share, 0.4);
42
+ assert.match(renderOrigin(r), /pipeline-originated: 3 issues, \$4\.00 of \$10\.00 \(40\.0%/);
43
+ });
44
+ it("no recorded cost gives a null share, not 0", () => {
45
+ assert.equal(originReport({ issues: [iss(1)], runs: [] }).pipeline.cost_share, null);
46
+ });
47
+ it("gatherOriginIssues throws on unreadable output", async () => {
48
+ await assert.rejects(gatherOriginIssues({ gh: async () => "nope", repo: "o/r", since: "2026-10-01" }), /unreadable/);
49
+ });
50
+ it("parseArgs and buildReport wire --origin with stubbed gh", async () => {
51
+ const o = parseArgs(["--origin", "--repo", "o/r", "--since", "2026-10-01"]);
52
+ assert.equal(o.origin, true);
53
+ const gh = async (args) => (args[0] === "issue" ? JSON.stringify(ISSUES) : "[]");
54
+ const rep = await buildReport({ ...o, cache: false, local: false }, { gh, env: {}, now: () => Date.parse("2026-11-10T00:00:00Z") });
55
+ assert.equal(rep.query.origin.total, 5);
56
+ assert.equal(rep.query.origin.since, "2026-10-01");
57
+ });
58
+ });
@@ -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