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
@@ -3,8 +3,8 @@
3
3
  /**
4
4
  * forge#5209: adaptive lane depth. `forgedock stats --depth` joins each lane's LIGHT_ELIGIBILITY verdict, reasons and
5
5
  * signals (bin/lean/light.mjs) with its outcome: merged / needs-human, first pass, cost, wall and model time, review
6
- * findings and conformance failures, and post-merge defect signals (a reopen, a revert, or a fix PR touching the same
7
- * non-test files within 7 days). It answers whether, for lanes the light gate would have taken, the plan and review steps
6
+ * findings and conformance failures, and post-merge defect signals within 7 days: the conformance-outcomes set (#5364),
7
+ * reverted, reopened, cited, and same_hunks (a later fix PR's old-side lines blame to the lane's merge commit). It answers whether, for lanes the light gate would have taken, the plan and review steps
8
8
  * caught anything or only added cost, and whether the #5052 light-lane promotion criterion is met:
9
9
  * light-shaped lanes (light or upgraded) cost <= 1.2x eligible full lanes of the same size, wall <= 1.3x model time, and
10
10
  * a defect rate no worse than those full lanes; any cell under min-n is "insufficient data".
@@ -12,11 +12,12 @@
12
12
  *
13
13
  * Sources: the run logs (~/.forge/runs/<issue>.jsonl, every RUN_START..RUN_TERMINAL slice); GitHub only for defect signals.
14
14
  */
15
- import { existsSync, readdirSync, readFileSync } from "node:fs";
15
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
16
16
  import { join } from "node:path";
17
17
  import { firstPassOf } from "../lean/fixround.mjs";
18
- import { classifyPath } from "../lean/routing.mjs";
19
18
  import { DEFAULT_MIN_N } from "./aggregate.mjs";
19
+ import { cacheDir } from "./cache.mjs";
20
+ import { cites, isFix, reverts, sameHunks } from "./conformance-outcomes.mjs";
20
21
  import { sameRepo, WEEK_MS } from "./efficiency.mjs";
21
22
 
22
23
  export const VERDICTS = Object.freeze(["eligible", "ambiguous", "ineligible"]);
@@ -84,42 +85,81 @@ export function depthRows(events, { repo = null, sinceMs = null, issue = null }
84
85
  }
85
86
 
86
87
  const lines = (raw) => String(raw ?? "").split("\n").filter((l) => l.trim()).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
87
- const isFixPr = (p) => /^fix/i.test(String(p.title ?? "")) || (p.labels ?? []).some((l) => String(l).toLowerCase() === "bug");
88
- const isRevertOf = (p, pr) => /^revert/i.test(String(p.title ?? "")) && new RegExp(`#${pr}(?!\\d)`).test(`${p.title ?? ""}\n${p.body ?? ""}`);
89
- const nonTestFiles = (fs) => fs.filter((f) => classifyPath(f) !== "test");
88
+
89
+ const DEFECT_CACHE_V = 2;
90
+ const CONCURRENCY = 4;
91
+ const defectCachePath = (repo, env) => join(cacheDir(repo, env), "depth-defects.json");
92
+ function loadDefectCache(repo, env) {
93
+ try { const c = JSON.parse(readFileSync(defectCachePath(repo, env), "utf8")); if (c?.v === DEFECT_CACHE_V) return { v: DEFECT_CACHE_V, defects: c.defects ?? {}, shas: c.shas ?? {} }; } catch { /* refetch */ }
94
+ return { v: DEFECT_CACHE_V, defects: {}, shas: {} };
95
+ }
96
+ function saveDefectCache(repo, env, c) {
97
+ try { mkdirSync(cacheDir(repo, env), { recursive: true }); writeFileSync(defectCachePath(repo, env), JSON.stringify(c)); } catch { /* a cache never fails the report */ }
98
+ }
99
+ /** Run `fn` over `items` with at most `n` in flight. */
100
+ async function mapLimit(items, n, fn) {
101
+ let next = 0;
102
+ await Promise.all(Array.from({ length: Math.min(n, items.length) }, async () => { while (next < items.length) await fn(items[next++]); }));
103
+ }
90
104
 
91
105
  /**
92
- * Post-merge defect signals of merged rows with a PR, over the injected gh: Map issue -> {reopen, revert, fixPr, defect}.
106
+ * Post-merge defect signals of merged rows with a PR, over the injected gh: Map issue -> {reopen, revert, cited, same_hunks, defect}.
107
+ * The signals are those of conformance-outcomes.mjs (reverts, cites, sameHunks over the injected local `git` probes). same_hunks is
108
+ * null when git cannot resolve (no local clone); defect is then null (n/a) unless another signal is true.
93
109
  * A gh failure gives the rows it could not read null fields (rendered n/a), never false.
110
+ * Bounded crawl (#5318): reopens are read per issue (not repo-wide), the PR search is limited to the rows' merge window,
111
+ * per-PR merge shas are fetched with bounded concurrency, and a row whose window has closed (`now` past its end + window)
112
+ * is cached under cacheDir(repo) with the PR merge shas, so a warm run makes no gh calls for it. `useCache` false skips
113
+ * the cache; `refresh` ignores what is stored. `onProgress({phase, done, total})` is called as rows are resolved.
94
114
  */
95
- export async function gatherDefects({ repo, gh, rows = [], windowMs = WEEK_MS } = {}) {
115
+ export async function gatherDefects({ repo, gh, rows = [], windowMs = WEEK_MS, now = null, env = process.env, useCache = false, refresh = false, onProgress = null, git = null } = {}) {
96
116
  const out = new Map();
97
117
  const merged = rows.filter((x) => x.merged && Number.isSafeInteger(x.pr) && ms(x.endTs) != null);
98
118
  if (!gh || !repo || !merged.length) return out;
119
+ const cache = useCache && !refresh ? loadDefectCache(repo, env) : { v: DEFECT_CACHE_V, defects: {}, shas: {} };
120
+ const settled = (x) => now != null && ms(x.endTs) + windowMs < now;
121
+ const hit = (x) => { const c = cache.defects[`${x.issue}:${x.pr}`]; return c && c.endTs === x.endTs ? c.value : null; };
122
+ const todo = [];
123
+ for (const x of merged) { const v = settled(x) ? hit(x) : null; if (v) out.set(x.issue, v); else todo.push(x); }
124
+ const total = merged.length;
125
+ let done = total - todo.length;
126
+ onProgress?.({ phase: "defect signals (cached)", done, total });
127
+ if (!todo.length) return out;
99
128
  try {
100
- const reopens = lines(await gh(["api", "--paginate", `repos/${repo}/issues/events?per_page=100`, "--jq", '.[] | select(.event == "reopened") | {issue: .issue.number, ts: .created_at}']));
101
- const from = new Date(Math.min(...merged.map((x) => ms(x.endTs)))).toISOString().slice(0, 10);
102
- const prs = lines(await gh(["api", "--paginate", `search/issues?q=${encodeURIComponent(`repo:${repo} is:pr is:merged merged:>=${from}`)}&per_page=100`,
129
+ const from = new Date(Math.min(...todo.map((x) => ms(x.endTs)))).toISOString().slice(0, 10);
130
+ const to = new Date(Math.max(...todo.map((x) => ms(x.endTs))) + windowMs).toISOString().slice(0, 10);
131
+ const prs = lines(await gh(["api", "--paginate", `search/issues?q=${encodeURIComponent(`repo:${repo} is:pr is:merged merged:${from}..${to}`)}&per_page=100`,
103
132
  "--jq", ".items[] | {number, title, body, labels: [.labels[].name], merged_at: .pull_request.merged_at}"]));
104
- const files = new Map();
105
- const filesOf = async (n) => {
106
- if (!files.has(n)) files.set(n, String(await gh(["api", "--paginate", `repos/${repo}/pulls/${n}/files?per_page=100`, "--jq", ".[].filename"])).split("\n").map((l) => l.trim()).filter(Boolean));
107
- return files.get(n);
133
+ const shas = new Map(Object.entries(cache.shas).map(([k, v]) => [Number(k), v]));
134
+ const shaOf = async (n) => {
135
+ if (!shas.has(n)) shas.set(n, String(await gh(["api", `repos/${repo}/pulls/${n}`, "--jq", ".merge_commit_sha"])).trim() || null);
136
+ return shas.get(n);
108
137
  };
109
- for (const x of merged) {
138
+ await mapLimit(todo, CONCURRENCY, async (x) => {
110
139
  const t0 = ms(x.endTs), inWin = (p) => p.number !== x.pr && ms(p.merged_at) != null && ms(p.merged_at) > t0 && ms(p.merged_at) <= t0 + windowMs;
111
- const reopen = reopens.some((e) => e.issue === x.issue && (ms(e.ts) ?? 0) > t0);
112
- const revert = prs.some((p) => inWin(p) && isRevertOf(p, x.pr));
113
- let fixPr = false;
114
- const cands = prs.filter((p) => inWin(p) && isFixPr(p));
115
- if (cands.length) {
116
- const own = new Set(nonTestFiles(await filesOf(x.pr)));
117
- for (const p of cands) if (own.size && nonTestFiles(await filesOf(p.number)).some((f) => own.has(f))) { fixPr = true; break; }
140
+ const reopens = lines(await gh(["api", "--paginate", `repos/${repo}/issues/${x.issue}/events?per_page=100`, "--jq", '.[] | select(.event == "reopened") | {issue: .issue.number, ts: .created_at}']));
141
+ const reopen = reopens.some((e) => (e.issue ?? x.issue) === x.issue && (ms(e.ts) ?? 0) > t0);
142
+ const own = prs.find((p) => p.number === x.pr);
143
+ const lane = { repo, number: x.pr, title: own?.title ?? "", body: own?.body ?? "", closingIssues: [{ number: x.issue }] };
144
+ const later = prs.filter(inWin);
145
+ const revert = later.some((q) => reverts(q, lane, repo));
146
+ const cited = later.some((q) => cites(q, lane));
147
+ const fixes = later.filter(isFix);
148
+ let same_hunks = false;
149
+ if (fixes.length) {
150
+ lane.mergeSha = git ? await shaOf(x.pr) : null;
151
+ const withSha = lane.mergeSha ? await Promise.all(fixes.map(async (q) => ({ ...q, mergeSha: await shaOf(q.number) }))) : fixes;
152
+ same_hunks = sameHunks(lane, withSha, git);
118
153
  }
119
- out.set(x.issue, { reopen, revert, fixPr, defect: reopen || revert || fixPr });
120
- }
154
+ const hit = reopen || revert || cited || same_hunks === true;
155
+ const value = { reopen, revert, cited, same_hunks, defect: hit ? true : same_hunks === null ? null : false };
156
+ out.set(x.issue, value);
157
+ if (settled(x)) cache.defects[`${x.issue}:${x.pr}`] = { endTs: x.endTs, value };
158
+ onProgress?.({ phase: "defect signals", done: ++done, total });
159
+ });
160
+ if (useCache) { cache.shas = Object.fromEntries(shas); saveDefectCache(repo, env, cache); }
121
161
  } catch { // gh unavailable: the unread rows get null defect fields (n/a), never false
122
- for (const x of merged) if (!out.has(x.issue)) out.set(x.issue, { reopen: null, revert: null, fixPr: null, defect: null });
162
+ for (const x of merged) if (!out.has(x.issue)) out.set(x.issue, { reopen: null, revert: null, cited: null, same_hunks: null, defect: null });
123
163
  }
124
164
  return out;
125
165
  }
@@ -166,6 +206,19 @@ export function promotion(rows, defects = new Map(), minN = DEFAULT_MIN_N) {
166
206
  return { met, sizes, n_treatment: t.length, n_control: c.length, min_n: minN, checks, note: "flipping lean.light.mode: on stays a config decision" };
167
207
  }
168
208
 
209
+ /**
210
+ * The promotion recommendation from shadow data (#5318): eligible share of lanes, would-be saving (eligible full lanes x
211
+ * the median cost gap to light-shaped lanes) and the defect rate on eligible lanes. The decision follows promotion().met.
212
+ */
213
+ export function recommendation(rows, defects, prom) {
214
+ const elig = rows.filter((x) => x.verdict === "eligible"), full = elig.filter((x) => x.shape === "full");
215
+ const light = rows.filter((x) => x.shape === "light" || x.shape === "upgraded");
216
+ const fullMed = median(full.map((x) => x.cost)), lightMed = median(light.map((x) => x.cost));
217
+ const saving = fullMed != null && lightMed != null ? r(full.length * (fullMed - lightMed), 100) : null;
218
+ const decision = prom.met === true ? "promote" : prom.met === false ? "do not promote" : INSUFFICIENT;
219
+ return { decision, eligible_share: r(per(elig.length, rows.length)), eligible_n: elig.length, would_be_saving_usd: saving, eligible_defect_rate: depthCell(elig, defects).defect_rate };
220
+ }
221
+
169
222
  /** Pure report: per verdict, per reason/signal code, and the promotion verdict. */
170
223
  export function depthReport({ rows = [], defects = new Map(), minN = DEFAULT_MIN_N, defectsSource = "github" } = {}) {
171
224
  const byVerdict = {};
@@ -175,7 +228,9 @@ export function depthReport({ rows = [], defects = new Map(), minN = DEFAULT_MIN
175
228
  }
176
229
  const byCode = {};
177
230
  for (const code of [...new Set(rows.flatMap((x) => [...x.reasons, ...x.signals]))].sort()) byCode[code] = depthCell(rows.filter((x) => x.reasons.includes(code) || x.signals.includes(code)), defects);
178
- return { lanes: rows.length, min_n: minN, defects_source: defectsSource, by_verdict: byVerdict, by_code: byCode, promotion: promotion(rows, defects, minN) };
231
+ const prom = promotion(rows, defects, minN);
232
+ const unresolved = rows.filter((x) => x.merged && defects.get(x.issue)?.defect === null).length;
233
+ return { lanes: rows.length, min_n: minN, defects_source: defectsSource, defects_unresolved: unresolved, by_verdict: byVerdict, by_code: byCode, promotion: prom, recommendation: recommendation(rows, defects, prom) };
179
234
  }
180
235
 
181
236
  const pct = (x) => (x == null ? "n/a" : `${Math.round(x * 100)}%`);
@@ -186,7 +241,7 @@ const cellLine = (label, c) => ` ${label}: n=${c.n}, merge ${pct(c.merge_rate)}
186
241
 
187
242
  /** Text lines of depthReport. */
188
243
  export function renderDepth(rep, { repo = null, since = null } = {}) {
189
- const out = [`lane depth${repo ? ` ${repo}` : ""}${since ? ` since ${since}` : ""}: ${rep.lanes} lane(s) with a light-eligibility verdict; defect signals: ${rep.defects_source}`];
244
+ const out = [`lane depth${repo ? ` ${repo}` : ""}${since ? ` since ${since}` : ""}: ${rep.lanes} lane(s) with a light-eligibility verdict; defect signals: ${rep.defects_source}${rep.defects_unresolved ? `, ${rep.defects_unresolved} unresolved (n/a: same-hunks needs a local clone of the repo)` : ""}`];
190
245
  out.push("by verdict:");
191
246
  for (const [v, c] of Object.entries(rep.by_verdict)) out.push(cellLine(v, c));
192
247
  out.push("by reason/signal:");
@@ -199,11 +254,13 @@ export function renderDepth(rep, { repo = null, since = null } = {}) {
199
254
  + ` (treatment light|upgraded n=${p.n_treatment}, control eligible full n=${p.n_control}, sizes ${p.sizes.length ? p.sizes.join(",") : "none"})`);
200
255
  out.push(fmt("cost ratio", ck.cost, "x"), fmt("wall/model", ck.wall, "x"), fmt("defect rate", ck.defects, ""));
201
256
  out.push(` ${p.note}`);
257
+ const rc = rep.recommendation;
258
+ if (rc) out.push(`recommendation: ${rc.decision}; eligible share ${pct(rc.eligible_share)} (n=${rc.eligible_n}), would-be saving ${rc.would_be_saving_usd == null ? "n/a" : `$${rc.would_be_saving_usd.toFixed(2)}`} over the window, defect rate on eligible lanes ${pct(rc.eligible_defect_rate)}`);
202
259
  return out.join("\n");
203
260
  }
204
261
 
205
262
  /** Every run log under `runsDir` -> rows -> defects (gh, unless null) -> report. */
206
- export async function buildDepth({ runsDir, repo = null, sinceMs = null, gh = null, minN = DEFAULT_MIN_N } = {}) {
263
+ export async function buildDepth({ runsDir, repo = null, sinceMs = null, gh = null, minN = DEFAULT_MIN_N, now = null, env = process.env, useCache = false, refresh = false, onProgress = null, git = null } = {}) {
207
264
  const rows = [];
208
265
  if (runsDir && existsSync(runsDir)) {
209
266
  for (const f of readdirSync(runsDir).filter((x) => x.endsWith(".jsonl")).sort()) {
@@ -213,6 +270,6 @@ export async function buildDepth({ runsDir, repo = null, sinceMs = null, gh = nu
213
270
  rows.push(...depthRows(parseLog(text), { repo, sinceMs, issue: n ? Number(n[1]) : null }));
214
271
  }
215
272
  }
216
- const defects = gh ? await gatherDefects({ repo, gh, rows }) : new Map();
273
+ const defects = gh ? await gatherDefects({ repo, gh, rows, now, env, useCache, refresh, onProgress, git }) : new Map();
217
274
  return depthReport({ rows, defects, minN, defectsSource: gh ? "github" : "offline" });
218
275
  }
@@ -79,55 +79,80 @@ test("promotion: met, not met and insufficient data below min-n, with n per cell
79
79
  });
80
80
 
81
81
  const fakeGh = (o = {}) => async (args) => {
82
- const path = args[2] ?? "";
82
+ const path = args.find((x) => /^(search|repos)\//.test(x)) ?? "";
83
83
  if (o.fail) throw new Error("gh down");
84
- if (path.includes("issues/events")) return JSON.stringify({ issue: 2, ts: iso(T0 + 2 * DAY) });
84
+ const ev = /issues\/(\d+)\/events/.exec(path);
85
+ if (ev) return ev[1] === "2" ? JSON.stringify({ issue: 2, ts: iso(T0 + 2 * DAY) }) : "";
85
86
  if (path.startsWith("search/issues")) return [
86
87
  { number: 300, title: "Revert \"feat: x (#101)\"", body: "", labels: [], merged_at: iso(T0 + DAY) },
87
88
  { number: 301, title: "fix: y", body: "", labels: [], merged_at: iso(T0 + 2 * DAY) },
88
89
  { number: 302, title: "fix: late", body: "", labels: [], merged_at: iso(T0 + 30 * DAY) },
90
+ { number: 303, title: "fix: rewrite z", body: "", labels: [], merged_at: iso(T0 + 2 * DAY) },
91
+ { number: 304, title: "fix: regression from #105", body: "", labels: [], merged_at: iso(T0 + 3 * DAY) },
89
92
  ].map((x) => JSON.stringify(x)).join("\n");
90
- const files = { 101: "src/a.js", 102: "src/b.js\ntest/b.test.js", 103: "src/c.js\ntest/shared.test.js", 301: "src/b.js\ntest/shared.test.js", 302: "src/c.js" };
91
- const m = /pulls\/(\d+)\/files/.exec(path);
92
- return m ? files[m[1]] ?? "" : "";
93
+ const m = /pulls\/(\d+)$/.exec(path);
94
+ return m ? `sha${m[1]}` : "";
93
95
  };
96
+ // Local git: fix PR 303 rewrites lines of PR 104; every other fix PR (301 touches a shared file) rewrites someone else's lines.
97
+ const fakeGit = { oldRanges: (sha) => [{ file: "src/shared.js", start: 1, end: 5 }], blame: (rev) => (rev === "sha303^" ? ["sha104"] : ["sha999"]) };
94
98
 
95
- test("gatherDefects: reopen, revert and a same-file fix PR within 7 days; gh failure is null, never false", async () => {
96
- const rows = rowsOf({ issue: 1 }, { issue: 2 }, { issue: 3 });
97
- const d = await gatherDefects({ repo: "o/r", gh: fakeGh(), rows });
98
- assert.deepEqual(d.get(1), { reopen: false, revert: true, fixPr: false, defect: true });
99
- assert.deepEqual(d.get(2), { reopen: true, revert: false, fixPr: true, defect: true });
100
- assert.deepEqual(d.get(3), { reopen: false, revert: false, fixPr: false, defect: false }, "test-only overlap and an out-of-window fix do not count");
101
- const bad = await gatherDefects({ repo: "o/r", gh: fakeGh({ fail: true }), rows });
102
- assert.deepEqual(bad.get(1), { reopen: null, revert: null, fixPr: null, defect: null });
99
+ test("depth defect: unrelated fix on a shared file is not a defect, one rewriting the lane's lines is", async () => {
100
+ const rows = rowsOf({ issue: 3 }, { issue: 4 });
101
+ const d = await gatherDefects({ repo: "o/r", gh: fakeGh(), rows, git: fakeGit });
102
+ assert.deepEqual(d.get(3), { reopen: false, revert: false, cited: false, same_hunks: false, defect: false }, "fix 301/303 touch the shared file but not this PR's lines; 302 is out of window");
103
+ assert.deepEqual(d.get(4), { reopen: false, revert: false, cited: false, same_hunks: true, defect: true });
104
+ });
105
+
106
+ test("gatherDefects: reverted, reopened, cited and same_hunks; no git is n/a unless another signal; gh failure is null, never false", async () => {
107
+ const rows = rowsOf({ issue: 1 }, { issue: 2 }, { issue: 3 }, { issue: 5 });
108
+ const d = await gatherDefects({ repo: "o/r", gh: fakeGh(), rows, git: fakeGit });
109
+ assert.deepEqual(d.get(1), { reopen: false, revert: true, cited: false, same_hunks: false, defect: true });
110
+ assert.deepEqual(d.get(2), { reopen: true, revert: false, cited: false, same_hunks: false, defect: true });
111
+ assert.deepEqual(d.get(5), { reopen: false, revert: false, cited: true, same_hunks: false, defect: true });
112
+ const nogit = await gatherDefects({ repo: "o/r", gh: fakeGh(), rows });
113
+ assert.deepEqual(nogit.get(3), { reopen: false, revert: false, cited: false, same_hunks: null, defect: null }, "unresolved same_hunks is n/a, not a defect");
114
+ assert.equal(nogit.get(1).defect, true, "another signal still decides");
115
+ const rep = depthReport({ rows, defects: nogit, minN: 1 });
116
+ assert.equal(rep.defects_unresolved, 1);
117
+ assert.match(renderDepth(rep), /1 unresolved/);
118
+ const bad = await gatherDefects({ repo: "o/r", gh: fakeGh({ fail: true }), rows, git: fakeGit });
119
+ assert.deepEqual(bad.get(1), { reopen: null, revert: null, cited: null, same_hunks: null, defect: null });
103
120
  assert.equal(depthReport({ rows, defects: bad, minN: 1 }).by_verdict.eligible.defect_rate, null);
104
121
  });
105
122
 
106
- test("renderDepth and buildDepth: verdict and promotion lines with n per cell from run logs", async () => {
107
- const dir = tmpDir("depth-");
108
- mkdirSync(join(dir, "runs"), { recursive: true });
109
- writeFileSync(join(dir, "runs", "5.jsonl"), slice({ issue: 5, shape: "light" }).map((e) => JSON.stringify(e)).join("\n") + "\n{torn");
110
- writeFileSync(join(dir, "runs", "6.jsonl"), slice({ issue: 6, verdict: "ambiguous", reasons: ["no_repro"], signals: ["no_repro"] }).map((e) => JSON.stringify(e)).join("\n"));
111
- const rep = await buildDepth({ runsDir: join(dir, "runs"), repo: "o/r", gh: null });
112
- assert.equal(rep.lanes, 2);
113
- assert.equal(rep.defects_source, "offline");
114
- const text = renderDepth(rep, { repo: "o/r" });
115
- assert.match(text, /lane depth o\/r/);
116
- assert.match(text, /^ eligible: n=1, merge 100%/m);
117
- assert.match(text, /^ ambiguous: n=1/m);
118
- assert.match(text, /^ ineligible: n=0/m);
119
- assert.match(text, /^ no_repro: n=1/m);
120
- assert.match(text, /light-lane promotion \(#5052, min n 10 per cell\): insufficient data \(treatment light\|upgraded n=0, control eligible full n=0/);
121
- assert.match(text, /cost ratio: insufficient data/);
122
- assert.match(text, /config decision/);
123
+ test("gatherDefects (#5318): per-issue events, windowed search, a warm cache makes zero gh calls, progress is reported", async () => {
124
+ const dir = tmpDir("depth-cache-");
125
+ const env = { FORGE_STATS_CACHE_DIR: join(dir, "cache") };
126
+ const rows = rowsOf({ issue: 1 }, { issue: 2 }, { issue: 3 });
127
+ const now = T0 + 60 * DAY, git = fakeGit;
128
+ const calls = [];
129
+ const gh = async (args) => { calls.push(args[2]); return fakeGh()(args); };
130
+ const prog = [];
131
+ const cold = await gatherDefects({ repo: "o/r", gh, rows, now, env, useCache: true, git, onProgress: (p) => prog.push(p) });
132
+ assert.equal(cold.get(2).reopen, true);
133
+ assert.ok(!calls.some((c) => c.includes("/issues/events")), "no repo-wide events crawl");
134
+ assert.ok(calls.some((c) => /merged%3A\d{4}-\d{2}-\d{2}\.\./.test(c)), "search bounded to the merge window");
135
+ assert.equal(prog.at(-1).done, 3);
136
+ const n = calls.length;
137
+ const warm = await gatherDefects({ repo: "o/r", gh, rows, now, env, useCache: true, git });
138
+ assert.equal(calls.length, n, "warm run makes no gh calls");
139
+ assert.deepEqual([...warm], [...cold]);
140
+ await gatherDefects({ repo: "o/r", gh, rows, now, env, useCache: true, refresh: true, git });
141
+ assert.ok(calls.length > n, "--refresh re-reads");
142
+ const fresh = calls.length;
143
+ await gatherDefects({ repo: "o/r", gh, rows, now: T0 + DAY, env, useCache: true, git });
144
+ assert.ok(calls.length > fresh, "a row inside its window is never served from the cache");
123
145
  });
124
146
 
125
- test("parseArgs accepts --depth and --depth --offline; --offline alone still needs --efficiency; HELP lists --depth", () => {
126
- assert.equal(parseArgs(["--depth"]).depth, true);
127
- const o = parseArgs(["--depth", "--offline", "--min-n", "3"]);
128
- assert.deepEqual([o.depth, o.offline, o.minN], [true, true, 3]);
129
- assert.equal(parseArgs(["--efficiency", "--offline"]).offline, true);
130
- assert.throws(() => parseArgs(["--offline"]), /--offline need --efficiency/);
131
- assert.throws(() => parseArgs(["--compare", "2026-01-01"]), /--compare and --offline need --efficiency/);
132
- assert.match(HELP, /stats --depth/);
147
+ test("depthReport recommendation: decision, eligible share, would-be saving and defect rate; rendered", () => {
148
+ const rows = rowsOf({ issue: 1, shape: "light", cost: 0.5 }, { issue: 2, cost: 2 }, { issue: 3, cost: 2 }, { issue: 4, verdict: "ineligible" });
149
+ const rep = depthReport({ rows, defects: new Map([[2, { defect: true }], [3, { defect: false }]]), minN: 1 });
150
+ const rc = rep.recommendation;
151
+ assert.equal(rc.eligible_n, 3);
152
+ assert.equal(rc.eligible_share, 0.75);
153
+ assert.equal(rc.would_be_saving_usd, 3, "2 eligible full lanes x (2 - 0.5)");
154
+ assert.equal(rc.eligible_defect_rate, 0.5);
155
+ assert.ok(["promote", "do not promote", INSUFFICIENT].includes(rc.decision));
156
+ assert.match(renderDepth(rep), /^recommendation: .*eligible share 75% \(n=3\), would-be saving \$3\.00/m);
157
+ assert.equal(depthReport({ rows: [], minN: 10 }).recommendation.decision, INSUFFICIENT);
133
158
  });
@@ -17,6 +17,7 @@ import { join } from "node:path";
17
17
  import { citesFileLine } from "../lean/fixround.mjs";
18
18
  import { laneSize, SIZES } from "../lean/budget.mjs";
19
19
  import { probeResultOf } from "../lean/probe.mjs";
20
+ import { summarizeWaits } from "../lean/phaseledger.mjs";
20
21
  import { listBatches } from "../lean/batch.mjs";
21
22
  import { isTrustedComment } from "../engine/phases.mjs";
22
23
  import { noComments } from "../lean/render.mjs";
@@ -76,10 +77,10 @@ export function issueSlices(events) {
76
77
  else if (e.event === "LIGHT_UPGRADE") cur.shape = "upgraded";
77
78
  if (e.event === "PHASE_ATTEMPT_USAGE") {
78
79
  cur.attempts.push({ phase: e.phase ?? "other", trigger: e.trigger ?? null, restart_of: e.restart_of ?? null, model: e.model ?? null,
79
- turns: num(e.turns), cacheRead: num(e.usage?.cache_read_input_tokens), cost: costOf(e), durationMs: num(e.duration_ms), // #4491
80
+ turns: num(e.turns), cacheRead: num(e.usage?.cache_read_input_tokens), cost: costOf(e), durationMs: num(e.duration_ms), baseline: num(e.baseline_tokens), profile: typeof e.lane_profile === "string" ? e.lane_profile : null, // #4491, #5348
80
81
  ...(e.tools && typeof e.tools === "object" ? { calls: num(e.tools.calls), toolTurns: num(e.tools.turns), rereads: num(e.tools.rereads) } : {}) }); // #4410
81
82
  } else if (e.event === "RUN_TERMINAL") {
82
- cur.terminal = { reason: e.reason ?? null, code: e.code ?? null, ts: e.ts ?? null, size: SIZES.includes(e.turns?.size) ? e.turns.size : null };
83
+ cur.terminal = { reason: e.reason ?? null, code: e.code ?? null, ts: e.ts ?? null, size: SIZES.includes(e.turns?.size) ? e.turns.size : null, phases: e.phases && typeof e.phases === "object" ? e.phases : null };
83
84
  }
84
85
  }
85
86
  return out;
@@ -167,6 +168,10 @@ export function efficiencyMetrics({ entries = [], logs = new Map(), issues = nul
167
168
  for (const s of inScope(row, settleAt)) { const g = shapes[s.shape] ?? shapes.full; g.n++; g.cost_usd += sum(s.attempts.map((a) => a.cost)); }
168
169
  }
169
170
  for (const g of Object.values(shapes)) g.cost_usd = r(g.cost_usd, 1e6);
171
+ // #5348: first-turn baseline_tokens per session profile (full, memory-off, lane, narrow) over every attempt of every lane
172
+ const profiles = {};
173
+ for (const { row, settleAt } of entries) for (const s of inScope(row, settleAt)) for (const a of s.attempts) if (a.baseline != null) (profiles[a.profile ?? "unknown"] ??= []).push(a.baseline);
174
+ const baselineByProfile = Object.fromEntries(Object.entries(profiles).map(([k, xs]) => [k, { sessions: xs.length, median: median(xs) }]));
170
175
  const lanes = { ...shapes, upgrade_rate: r(per(shapes.upgraded.n, shapes.light.n + shapes.upgraded.n)) };
171
176
  for (const { row, settleAt } of entries) {
172
177
  if (row?.outcome !== "merged") continue;
@@ -179,7 +184,7 @@ export function efficiencyMetrics({ entries = [], logs = new Map(), issues = nul
179
184
  const term = [...slices].reverse().find((s) => s.terminal?.reason === "merged")?.terminal;
180
185
  merged.push({ issue: row.issue, slices: slices.length, cost: sum(atts.map((a) => a.cost)), implCost: sum(impl.map((a) => a.cost)),
181
186
  reviewCost: sum(atts.filter((a) => a.phase === "review").map((a) => a.cost)), implTurns: sum(impl.map((a) => a.turns)), implCache: sum(impl.map((a) => a.cacheRead)),
182
- size: term?.size ?? laneSize({ labels: info?.labels ?? [] }) ?? "unknown", impl, retries, info, tools: laneTools(impl), shape: slices.at(-1)?.shape ?? null, implWall: laneWall(impl) });
187
+ size: term?.size ?? laneSize({ labels: info?.labels ?? [] }) ?? "unknown", impl, retries, info, tools: laneTools(impl), shape: slices.at(-1)?.shape ?? null, implWall: laneWall(impl), phases: term?.phases ?? null });
183
188
  }
184
189
  const all = group(merged);
185
190
  const bySize = {};
@@ -231,8 +236,8 @@ export function efficiencyMetrics({ entries = [], logs = new Map(), issues = nul
231
236
  retries: { total, per_merge: r(per(total, merged.length), 100), by_cause: retries, lane_reruns: sum(merged.map((m) => Math.max(0, m.slices - 1))) },
232
237
  no_action: { lanes: sum(Object.values(noAction).map((g) => g.n)), cost_usd: r(sum(Object.values(noAction).map((g) => g.cost_usd)), 1e6),
233
238
  by_kind: Object.fromEntries(Object.entries(noAction).map(([k, g]) => [k, { ...g, cost_usd: r(g.cost_usd, 1e6) }])) },
234
- quality, acceptance, lanes,
235
- tool_calls_per_turn_p50: median(withTools.map((m) => m.tools.per_turn)), rereads_per_merge: withTools.length ? r(per(sum(withTools.map((m) => m.tools.rereads)), withTools.length), 100) : null,
239
+ quality, acceptance, lanes, baseline_by_profile: baselineByProfile, wait: summarizeWaits(merged.map((m) => m.phases)), // #5349: non-model time by phase and cause
240
+ tool_calls_per_turn_p50: median(withTools.map((m) => m.tools.per_turn)), tool_calls_per_turn_n: withTools.length, rereads_per_merge: withTools.length ? r(per(sum(withTools.map((m) => m.tools.rereads)), withTools.length), 100) : null,
236
241
  per_issue: merged.map((m) => ({ issue: m.issue, slices: m.slices, cost_usd: r(m.cost, 1e6), implement_usd: r(m.implCost, 1e6), implement_turns: m.implTurns,
237
242
  implement_cache_read: m.implCache, size: m.size, retries: m.retries, ...(m.shape ? { shape: m.shape } : {}), ...(m.info ? { quality: issueQuality(m.info.body).tag } : {}),
238
243
  ...(m.tools ? { implement_tool_calls_per_turn: m.tools.per_turn, implement_rereads: m.tools.rereads } : {}),
@@ -380,6 +385,9 @@ const int = (x) => (num(x) == null ? "n/a" : String(Math.round(x)));
380
385
  const g1 = (g) => `n=${g.n} ${usd(g.usd_per_merge)}/merge turns/merge ${f(g.turns_per_merge, 1)} context/turn ${int(g.context_per_turn)}`;
381
386
 
382
387
  /** The report lines of one scope (the batch report prints them unlabelled). */
388
+ /** #5347: a median of tool calls per turn under this means builders are back to one call per turn. */
389
+ export const CALLS_PER_TURN_ALERT = 1.5;
390
+
383
391
  export function formatEfficiencyLines(m, label = "") {
384
392
  const lines = [`efficiency${label ? ` (${label})` : ""}: merged ${m.merged}, ${usd(m.usd_per_merge)}/merge (implement ${usd(m.implement_usd)}, review ${usd(m.review_usd)}), turns/merge ${f(m.turns_per_merge, 1)}, context/turn ${int(m.context_per_turn)}`];
385
393
  const sizes = Object.entries(m.by_size ?? {});
@@ -397,13 +405,26 @@ export function formatEfficiencyLines(m, label = "") {
397
405
  : "acceptance (7d after promotion): n/a");
398
406
  if (a) lines.push(`unprobed merged issues (no acceptance probe declared): ${a.unprobed_issues?.length ? a.unprobed_issues.map((n) => `#${n}`).join(", ") : "none"}`); // #4908
399
407
  lines.push(`tools: calls/turn p50 ${f(m.tool_calls_per_turn_p50)}, re-reads (>=3x same path)/merge ${f(m.rereads_per_merge)}`); // #4410
408
+ if (num(m.tool_calls_per_turn_p50) != null && m.tool_calls_per_turn_p50 < CALLS_PER_TURN_ALERT && (m.tool_calls_per_turn_n ?? 0) >= 3) lines.push(`ALERT: calls/turn p50 ${f(m.tool_calls_per_turn_p50)} is below ${CALLS_PER_TURN_ALERT}: builders are not batching independent reads (#5347)`);
400
409
  const ln = m.lanes; // #4452
401
410
  lines.push(ln ? `lanes: ${LANE_SHAPES.map((k) => `${k} ${ln[k]?.n ?? 0} (${usd(ln[k]?.cost_usd ?? 0)})`).join(", ")}; upgrade rate ${ln.upgrade_rate == null ? "n/a"
402
411
  : `${Math.round(ln.upgrade_rate * 100)}% (${ln.upgraded?.n ?? 0}/${(ln.light?.n ?? 0) + (ln.upgraded?.n ?? 0)})`}` : "lanes: n/a");
403
412
  lines.push(rates(m)); // #4491
413
+ const bp = Object.entries(m.baseline_by_profile ?? {}); // #5348
414
+ lines.push(`baseline tokens by profile: ${bp.length ? bp.map(([k, g]) => `${k} n=${g.sessions} median ${int(g.median)}`).join("; ") : "n/a"}`);
415
+ lines.push(...waitLines(m.wait)); // #5349
404
416
  return lines;
405
417
  }
406
418
 
419
+ /** #5349: where the non-model time of merged lanes went, by phase and cause; n/a when no merged lane carries a wait breakdown. */
420
+ function waitLines(w) {
421
+ if (!w?.n) return ["wait (non-model time): n/a"];
422
+ const mins = (ms) => `${(ms / 60000).toFixed(1)}m`, causes = (c) => Object.entries(c).map(([k, v]) => `${k} ${mins(v)}`).join(", ") || "none";
423
+ const waiting = Math.max(0, w.total.ms - w.total.model_ms);
424
+ return [`wait (non-model time, ${w.n} merged lane${w.n === 1 ? "" : "s"}): ${mins(waiting)} of ${mins(w.total.ms)} wall (${w.total.ms > 0 ? Math.round((waiting / w.total.ms) * 100) : 0}%); ${causes(w.total.wait)}`,
425
+ ...Object.entries(w.phases).map(([id, g]) => ` wait ${id}: ${mins(Math.max(0, g.ms - g.model_ms))} of ${mins(g.ms)} (${causes(g.wait)}${Object.keys(g.pct ?? {}).length ? `; p50/p90 ${Object.entries(g.pct).map(([k, q]) => `${k} ${mins(q.p50)}/${mins(q.p90)}`).join(", ")}` : ""})`)];
426
+ }
427
+
407
428
  const pct = (x) => (num(x) == null ? "n/a" : `${Math.round(x * 100)}%`);
408
429
  const rates = (m) => `implement wall p50 ${m.implement_wall_p50_min == null ? "n/a" : `${f(m.implement_wall_p50_min, 1)} min`}, merge rate ${pct(m.merge_rate)}, conformance pass ${pct(m.conformance_pass_rate)}`;
409
430
  const sign = (x, d, unit = "") => (num(x) == null ? "n/a" : `${x > 0 ? "+" : ""}${x.toFixed(d)}${unit}`);
@@ -119,8 +119,10 @@ describe("#4402 efficiencyMetrics", () => {
119
119
  });
120
120
  it("renders n/a, never NaN, for an empty cohort", () => {
121
121
  const lines = formatEfficiencyLines(efficiencyMetrics({}));
122
- assert.equal(lines.length, 10);
122
+ assert.equal(lines.length, 12);
123
123
  assert.equal(lines[9], "implement wall p50 n/a, merge rate n/a, conformance pass n/a"); // #4491, appended
124
+ assert.equal(lines[10], "baseline tokens by profile: n/a"); // #5348
125
+ assert.equal(lines[11], "wait (non-model time): n/a"); // #5349
124
126
  assert.ok(!lines.some((l) => /NaN|undefined/.test(l)), lines.join("\n"));
125
127
  assert.match(lines[0], /^efficiency: merged 0, n\/a\/merge/);
126
128
  assert.equal(lines[6], "acceptance (7d after promotion): n/a");
@@ -366,3 +368,45 @@ describe("#4491 before/after compare", () => {
366
368
  assert.match(text, /^issue quality: n\/a \(no gh\/repo\)$/m);
367
369
  });
368
370
  });
371
+
372
+ describe("#5347 calls/turn alert", () => {
373
+ const lines = (p50, n) => formatEfficiencyLines({ ...efficiencyMetrics({}), tool_calls_per_turn_p50: p50, tool_calls_per_turn_n: n });
374
+ it("fires below the threshold with enough samples; silent above it, with few samples or no data", () => {
375
+ assert.ok(lines(1.03, 5).some((l) => /^ALERT: calls\/turn p50 1\.03/.test(l)));
376
+ assert.ok(!lines(2.1, 5).some((l) => l.startsWith("ALERT")));
377
+ assert.ok(!lines(1.03, 1).some((l) => l.startsWith("ALERT")));
378
+ assert.ok(!lines(null, 0).some((l) => l.startsWith("ALERT")));
379
+ });
380
+ });
381
+
382
+ describe("#5348 baseline tokens per session profile", () => {
383
+ const ev = (o) => ({ event: "PHASE_ATTEMPT_USAGE", phase: "implement", ...o });
384
+ const logs = new Map([[1, [{ event: "RUN_START", ts: "2026-10-01T00:00:00Z" },
385
+ ev({ trigger: "build", baseline_tokens: 30000, lane_profile: "lane" }), ev({ trigger: "enumerating", baseline_tokens: 9000, lane_profile: "narrow" }),
386
+ ev({ trigger: "duplicate", baseline_tokens: 11000, lane_profile: "narrow" }), ev({ trigger: "ci_red" }),
387
+ { event: "RUN_TERMINAL", reason: "merged", code: "completed" }]]]);
388
+ const m = efficiencyMetrics({ entries: [{ row: { issue: 1, outcome: "merged" }, settleAt: null }], logs, repo: "o/r", now: Date.parse("2026-10-02T00:00:00Z") });
389
+ it("reports sessions and median baseline per lane_profile; attempts without a baseline are skipped", () => {
390
+ assert.deepEqual(m.baseline_by_profile, { lane: { sessions: 1, median: 30000 }, narrow: { sessions: 2, median: 10000 } });
391
+ assert.equal(formatEfficiencyLines(m).find((l) => l.startsWith("baseline tokens")), "baseline tokens by profile: lane n=1 median 30000; narrow n=2 median 10000");
392
+ });
393
+ });
394
+
395
+ describe("#5349 wait attribution in the efficiency report", () => {
396
+ const phases = { plan: { ms: 600000, model_ms: 200000, wait: { heavy_queue: 100000, command: 300000 } }, implement: { ms: 300000, model_ms: 300000 } };
397
+ const logs = new Map([[1, [start("2026-10-22T10:00:00Z"), term("merged", null, { phases })]], [2, [start("2026-10-22T11:00:00Z"), term("merged", null)]]]);
398
+ const row = (issue) => ({ row: { issue, outcome: "merged" }, settleAt: null });
399
+ it("sums non-model time by phase and cause over merged lanes that carry a breakdown", () => {
400
+ const m = efficiencyMetrics({ entries: [row(1), row(2)], logs });
401
+ assert.equal(m.wait.n, 1);
402
+ assert.deepEqual(m.wait.phases.plan.wait, { heavy_queue: 100000, command: 300000 });
403
+ const out = formatEfficiencyLines(m).filter((l) => /wait/.test(l));
404
+ assert.match(out[0], /wait \(non-model time, 1 merged lane\): 6\.7m of 15\.0m wall \(44%\); heavy_queue 1\.7m, command 5\.0m/);
405
+ assert.match(out[1], /wait plan: 6\.7m of 10\.0m \(heavy_queue 1\.7m, command 5\.0m; p50\/p90 heavy_queue 1\.7m\/1\.7m/);
406
+ });
407
+ it("reports n/a for runs recorded before the breakdown existed", () => {
408
+ const m = efficiencyMetrics({ entries: [row(2)], logs });
409
+ assert.equal(m.wait.n, 0);
410
+ assert.ok(formatEfficiencyLines(m).includes("wait (non-model time): n/a"));
411
+ });
412
+ });
@@ -0,0 +1,77 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * forgedock stats --first-review (#5345): the clean-first-review rate. Each finished lane's `run_terminal` record carries
5
+ * `first_review` ({state, kinds, rounds, clean, incomplete, type, surfaces}, bin/lean/selfreview.mjs firstReviewRecord).
6
+ * Reports the rate and the review.incomplete share overall and per repo, change type and risk surface, the first-round
7
+ * finding kinds with the contract section each traces to, and the cells with a long clean record as light-lane
8
+ * candidates. Candidacy is report-only; a lane touching a risk surface (domain:*, risk:*) is never a candidate (#5283).
9
+ */
10
+ import { sectionOfKind } from "../lean/selfreview.mjs";
11
+
12
+ export const DEFAULT_FIRST_REVIEW_MIN_N = 20;
13
+ export const DEFAULT_CLEAN_STREAK = 20;
14
+ export const TARGET_CLEAN_RATE = 0.85;
15
+ export const TARGET_INCOMPLETE_RATE = 0.02;
16
+
17
+ const rate = (k, n) => (n ? Math.round((k / n) * 1000) / 1000 : null);
18
+ const isRisk = (surfaces) => surfaces.length > 0;
19
+
20
+ /** The first-round record of a run_terminal: the nested object, or the scalar `fr_*` fields the telemetry seam writes. */
21
+ function frOf(r) {
22
+ if (r?.first_review && typeof r.first_review === "object") return r.first_review;
23
+ if (r?.fr_state == null && r?.fr_clean == null) return null;
24
+ const list = (v) => (typeof v === "string" && v !== "none" ? v.split(",").filter(Boolean) : []);
25
+ return { state: r.fr_state, kinds: list(r.fr_kinds), rounds: r.fr_rounds, clean: Number(r.fr_clean) === 1, incomplete: Number(r.fr_incomplete) === 1, type: r.fr_type, surfaces: list(r.fr_surfaces) };
26
+ }
27
+
28
+ /** The latest first_review per issue (later run_terminal wins), oldest first. */
29
+ export function firstReviewLanes(records = [], repo = null) {
30
+ const byIssue = new Map();
31
+ for (const r of records) {
32
+ const f = r?.event === "run_terminal" ? frOf(r) : null;
33
+ if (!f || typeof f !== "object" || r.issue == null) continue;
34
+ const cur = byIssue.get(r.issue);
35
+ if (!cur || String(r.ts ?? "") >= String(cur.ts ?? "")) byIssue.set(r.issue, { issue: r.issue, ts: String(r.ts ?? ""), repo: r.repo ?? repo, merged: r.reason === "merged", state: f.state, kinds: Array.isArray(f.kinds) ? f.kinds : [], rounds: Number(f.rounds) || 1, clean: f.clean === true, incomplete: f.incomplete === true, type: f.type ?? "other", surfaces: Array.isArray(f.surfaces) ? f.surfaces : [] });
36
+ }
37
+ return [...byIssue.values()].sort((a, b) => a.ts.localeCompare(b.ts) || a.issue - b.issue);
38
+ }
39
+
40
+ function cellOf(lanes, { streak, minN }) {
41
+ const n = lanes.length, clean = lanes.filter((l) => l.clean).length, incomplete = lanes.filter((l) => l.incomplete).length;
42
+ const tail = lanes.slice(-streak);
43
+ const safe = lanes.filter((l) => !isRisk(l.surfaces));
44
+ const run = safe.slice(-streak);
45
+ return { n, clean, clean_rate: rate(clean, n), incomplete, incomplete_rate: rate(incomplete, n), enough: n >= minN,
46
+ light_candidate: safe.length === n && n >= minN && tail.length >= streak && tail.every((l) => l.clean) && run.length >= streak };
47
+ }
48
+
49
+ export function firstReviewReport({ records = [], repo = null, minN = DEFAULT_FIRST_REVIEW_MIN_N, streak = DEFAULT_CLEAN_STREAK } = {}) {
50
+ const lanes = firstReviewLanes(records, repo);
51
+ const opt = { streak, minN };
52
+ const group = (keys) => {
53
+ const m = new Map();
54
+ for (const l of lanes) for (const k of keys(l)) { if (!m.has(k)) m.set(k, []); m.get(k).push(l); }
55
+ return Object.fromEntries([...m.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => [k, cellOf(v, opt)]));
56
+ };
57
+ const kinds = {}, sections = {};
58
+ for (const l of lanes) for (const k of l.kinds) { kinds[k] = (kinds[k] ?? 0) + 1; const s = sectionOfKind(k); sections[s] = (sections[s] ?? 0) + 1; }
59
+ const overall = cellOf(lanes, opt);
60
+ const norm = (c) => ({ ...c, light_candidate: false }); // risk surfaces always keep the full independent review
61
+ const bySurface = Object.fromEntries(Object.entries(group((l) => (l.surfaces.length ? l.surfaces : ["none"]))).map(([k, c]) => [k, k === "none" ? c : norm(c)]));
62
+ return { repo, lanes: lanes.length, overall: { ...overall, light_candidate: false }, targets: { clean_rate: TARGET_CLEAN_RATE, incomplete_rate: TARGET_INCOMPLETE_RATE },
63
+ met: overall.n ? overall.clean_rate >= TARGET_CLEAN_RATE && overall.incomplete_rate <= TARGET_INCOMPLETE_RATE : null,
64
+ by_repo: group((l) => [l.repo ?? "unknown"]), by_type: group((l) => [l.type]), by_surface: bySurface,
65
+ first_round_kinds: kinds, finding_sections: sections, rounds: { one: lanes.filter((l) => l.rounds <= 1).length, two: lanes.filter((l) => l.rounds === 2).length, more: lanes.filter((l) => l.rounds > 2).length } };
66
+ }
67
+
68
+ const pct = (x) => (x == null ? "n/a" : `${(x * 100).toFixed(1)}%`);
69
+ export function renderFirstReview(r) {
70
+ if (!r.lanes) return `clean-first-review, ${r.repo ?? "?"}: no lanes with a first_review record yet (recorded by lanes on a release that carries #5345)`;
71
+ const o = r.overall, line = (k, c) => ` ${k.padEnd(28)} n=${String(c.n).padStart(4)} clean ${pct(c.clean_rate).padStart(6)} incomplete ${pct(c.incomplete_rate).padStart(6)}${c.light_candidate ? " light-lane candidate" : ""}`;
72
+ const out = [`clean-first-review, ${r.repo ?? "?"}: ${pct(o.clean_rate)} of ${o.n} lanes (target >= ${pct(r.targets.clean_rate)}), review.incomplete ${pct(o.incomplete_rate)} (target <= ${pct(r.targets.incomplete_rate)}): ${r.met ? "met" : "not met"}`,
73
+ `rounds: one ${r.rounds.one}, two ${r.rounds.two}, three or more ${r.rounds.more}`];
74
+ for (const [title, cells] of [["by repo", r.by_repo], ["by change type", r.by_type], ["by risk surface (always full review)", r.by_surface]]) out.push(title, ...Object.entries(cells).map(([k, c]) => line(k, c)));
75
+ out.push("first-round finding kinds", ...Object.entries(r.first_round_kinds).sort((a, b) => b[1] - a[1]).map(([k, n]) => ` ${k.padEnd(34)} ${n} (contract section: ${sectionOfKind(k)})`));
76
+ return out.join("\n");
77
+ }
@@ -0,0 +1,36 @@
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 { firstReviewReport, firstReviewLanes, renderFirstReview } from "./first-review.mjs";
6
+
7
+ const rec = (issue, o = {}) => ({ event: "run_terminal", issue, ts: `2026-01-${String(issue % 28 + 1).padStart(2, "0")}`, repo: "o/r", reason: "merged", first_review: { state: "conforms", kinds: [], rounds: 1, clean: true, incomplete: false, type: "bug", surfaces: [], ...o } });
8
+
9
+ describe("stats --first-review (#5345)", () => {
10
+ it("reports rate, incomplete share, splits and first-round kinds with their contract section", () => {
11
+ const records = [rec(1), rec(2), rec(3, { clean: false, state: "fails", kinds: ["conformance.omission"], rounds: 2 }), rec(4, { clean: false, incomplete: true, state: "review.incomplete", type: "feature" })];
12
+ const r = firstReviewReport({ records, repo: "o/r", minN: 2 });
13
+ assert.equal(r.lanes, 4);
14
+ assert.equal(r.overall.clean_rate, 0.5);
15
+ assert.equal(r.overall.incomplete_rate, 0.25);
16
+ assert.equal(r.met, false);
17
+ assert.equal(r.by_type.bug.n, 3);
18
+ assert.equal(r.by_repo["o/r"].n, 4);
19
+ assert.equal(r.first_round_kinds["conformance.omission"], 1);
20
+ assert.equal(r.finding_sections.requirements, 1);
21
+ assert.match(renderFirstReview(r), /contract section: requirements/);
22
+ });
23
+ it("keeps the latest record per issue and ignores lanes without first_review", () => {
24
+ assert.equal(firstReviewLanes([rec(1), { event: "run_terminal", issue: 2 }, { ...rec(1, { clean: false }), ts: "2027-01-01" }]).length, 1);
25
+ assert.match(renderFirstReview(firstReviewReport({ records: [] })), /no lanes/);
26
+ });
27
+ it("a long clean streak is a light-lane candidate, but a risk surface never is", () => {
28
+ const safe = Array.from({ length: 5 }, (_, i) => rec(i + 1));
29
+ assert.equal(firstReviewReport({ records: safe, minN: 3, streak: 3 }).by_type.bug.light_candidate, true);
30
+ const risky = Array.from({ length: 5 }, (_, i) => rec(i + 1, { surfaces: ["risk:auth"] }));
31
+ const r = firstReviewReport({ records: risky, minN: 3, streak: 3 });
32
+ assert.equal(r.by_type.bug.light_candidate, false);
33
+ assert.equal(r.by_surface["risk:auth"].light_candidate, false);
34
+ assert.equal(r.overall.light_candidate, false);
35
+ });
36
+ });