forgedock 1.52.0 → 1.54.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (233) hide show
  1. package/.claude-plugin/marketplace.json +51 -0
  2. package/README.md +8 -2
  3. package/bin/auth/app-manifest.mjs +89 -0
  4. package/bin/auth/app-manifest.test.mjs +75 -0
  5. package/bin/auth/app-token.mjs +256 -0
  6. package/bin/auth/app-token.test.mjs +232 -0
  7. package/bin/brand.mjs +7 -0
  8. package/bin/config-history.mjs +151 -0
  9. package/bin/config-schema.mjs +115 -0
  10. package/bin/demo.mjs +65 -11
  11. package/bin/engine/outcome-codes.mjs +9 -3
  12. package/bin/engine/telemetry-seam.mjs +11 -3
  13. package/bin/engine/telemetry-seam.test.mjs +17 -0
  14. package/bin/engine-cli.mjs +110 -36
  15. package/bin/experiment.mjs +58 -6
  16. package/bin/first-run.mjs +122 -0
  17. package/bin/forge-utils.mjs +6 -2
  18. package/bin/forgedock.mjs +138 -142
  19. package/bin/help-text.mjs +144 -0
  20. package/bin/hooks/pre-tool-use.mjs +7 -0
  21. package/bin/journey.mjs +82 -83
  22. package/bin/lean/acceptance.mjs +313 -0
  23. package/bin/lean/acceptance.test.mjs +215 -0
  24. package/bin/lean/account-watch.mjs +28 -0
  25. package/bin/lean/account-watch.test.mjs +30 -0
  26. package/bin/lean/activation.mjs +38 -0
  27. package/bin/lean/activation.test.mjs +36 -1
  28. package/bin/lean/basered.mjs +115 -0
  29. package/bin/lean/basered.test.mjs +66 -0
  30. package/bin/lean/batch-health.mjs +114 -7
  31. package/bin/lean/batch-health.test.mjs +87 -1
  32. package/bin/lean/batch.mjs +41 -2
  33. package/bin/lean/batch.test.mjs +115 -11
  34. package/bin/lean/branchlock.mjs +54 -0
  35. package/bin/lean/branchlock.test.mjs +49 -0
  36. package/bin/lean/ceiling.mjs +72 -0
  37. package/bin/lean/ceiling.test.mjs +54 -0
  38. package/bin/lean/checkpoint-reconcile.mjs +43 -0
  39. package/bin/lean/checkpoint-reconcile.test.mjs +95 -0
  40. package/bin/lean/ci-budget.mjs +366 -0
  41. package/bin/lean/ci-budget.test.mjs +167 -0
  42. package/bin/lean/conformance.e2e.test.mjs +8 -1
  43. package/bin/lean/conformance.mjs +269 -38
  44. package/bin/lean/conformance.test.mjs +280 -7
  45. package/bin/lean/context.mjs +35 -6
  46. package/bin/lean/context.test.mjs +27 -1
  47. package/bin/lean/depcache.mjs +25 -1
  48. package/bin/lean/depcache.test.mjs +26 -0
  49. package/bin/lean/e2e.mjs +18 -2
  50. package/bin/lean/e2e.test.mjs +26 -1
  51. package/bin/lean/effects.mjs +47 -14
  52. package/bin/lean/execution.mjs +19 -3
  53. package/bin/lean/execution.test.mjs +63 -0
  54. package/bin/lean/facts.mjs +3 -3
  55. package/bin/lean/facts.test.mjs +5 -0
  56. package/bin/lean/findinglabel.mjs +16 -0
  57. package/bin/lean/findinglabel.test.mjs +39 -0
  58. package/bin/lean/fixround.mjs +14 -0
  59. package/bin/lean/fixround.test.mjs +25 -2
  60. package/bin/lean/gh-assoc.test.mjs +2 -1
  61. package/bin/lean/integration.mjs +100 -9
  62. package/bin/lean/integration.test.mjs +98 -0
  63. package/bin/lean/issuewatch-parity.mjs +64 -0
  64. package/bin/lean/issuewatch-parity.test.mjs +127 -0
  65. package/bin/lean/issuewatch-release.mjs +6 -2
  66. package/bin/lean/issuewatch-release.test.mjs +17 -1
  67. package/bin/lean/issuewatch.mjs +45 -6
  68. package/bin/lean/issuewatch.test.mjs +3 -2
  69. package/bin/lean/lanelock.mjs +14 -0
  70. package/bin/lean/lean.mjs +473 -100
  71. package/bin/lean/lean.test.mjs +686 -33
  72. package/bin/lean/light.mjs +48 -7
  73. package/bin/lean/light.test.mjs +37 -3
  74. package/bin/lean/limits.test.mjs +142 -9
  75. package/bin/lean/mechfix.mjs +124 -0
  76. package/bin/lean/mechfix.test.mjs +75 -0
  77. package/bin/lean/orchestrate-cancel.test.mjs +143 -0
  78. package/bin/lean/orchestrate.mjs +116 -28
  79. package/bin/lean/phaseledger.mjs +47 -5
  80. package/bin/lean/phaseledger.test.mjs +30 -1
  81. package/bin/lean/postdeploy-check.test.mjs +39 -0
  82. package/bin/lean/precheck.mjs +23 -4
  83. package/bin/lean/precheck.test.mjs +14 -1
  84. package/bin/lean/prereq.mjs +28 -0
  85. package/bin/lean/prereq.test.mjs +20 -0
  86. package/bin/lean/probe.mjs +4 -2
  87. package/bin/lean/prodparity.mjs +52 -0
  88. package/bin/lean/prodparity.test.mjs +67 -0
  89. package/bin/lean/prompts.mjs +77 -19
  90. package/bin/lean/quota.mjs +39 -0
  91. package/bin/lean/recovery.test.mjs +11 -1
  92. package/bin/lean/relaxation.mjs +73 -0
  93. package/bin/lean/relaxation.test.mjs +54 -0
  94. package/bin/lean/release-io.test.mjs +42 -0
  95. package/bin/lean/release-postmerge.mjs +125 -0
  96. package/bin/lean/release-preflight.mjs +58 -0
  97. package/bin/lean/release-preflight.test.mjs +114 -0
  98. package/bin/lean/release-rehearsal.mjs +64 -0
  99. package/bin/lean/release-rehearsal.test.mjs +93 -0
  100. package/bin/lean/release-review.e2e.test.mjs +77 -0
  101. package/bin/lean/release-review.mjs +254 -0
  102. package/bin/lean/release-review.test.mjs +307 -0
  103. package/bin/lean/release-snapshot.mjs +188 -0
  104. package/bin/lean/release-snapshot.test.mjs +190 -0
  105. package/bin/lean/release.mjs +296 -0
  106. package/bin/lean/release.test.mjs +387 -0
  107. package/bin/lean/render.mjs +1 -1
  108. package/bin/lean/replan.mjs +184 -0
  109. package/bin/lean/replan.test.mjs +110 -0
  110. package/bin/lean/resume.mjs +9 -7
  111. package/bin/lean/resume.test.mjs +16 -0
  112. package/bin/lean/rotator.mjs +150 -31
  113. package/bin/lean/rotator.test.mjs +105 -2
  114. package/bin/lean/sandbox-remote.mjs +9 -2
  115. package/bin/lean/schedd.mjs +83 -5
  116. package/bin/lean/schedd.test.mjs +108 -7
  117. package/bin/lean/selfreview.mjs +94 -0
  118. package/bin/lean/selfreview.test.mjs +58 -1
  119. package/bin/lean/selftest-gate.mjs +22 -0
  120. package/bin/lean/selftest-gate.test.mjs +18 -1
  121. package/bin/lean/selftest-journey.mjs +234 -0
  122. package/bin/lean/selftest-journey.test.mjs +130 -0
  123. package/bin/lean/selftest-live.mjs +2 -1
  124. package/bin/lean/seqlease.mjs +35 -1
  125. package/bin/lean/seqlease.test.mjs +15 -0
  126. package/bin/lean/seqreserve.e2e.test.mjs +135 -0
  127. package/bin/lean/seqreserve.mjs +73 -0
  128. package/bin/lean/seqreserve.test.mjs +134 -0
  129. package/bin/lean/sequence.mjs +35 -6
  130. package/bin/lean/seqversioned.mjs +147 -0
  131. package/bin/lean/stagestamp.mjs +28 -0
  132. package/bin/lean/stagestamp.test.mjs +32 -0
  133. package/bin/lean/surfaces.mjs +75 -0
  134. package/bin/lean/surfaces.test.mjs +59 -0
  135. package/bin/lean/toolplace.mjs +28 -0
  136. package/bin/lean/toolplace.test.mjs +24 -0
  137. package/bin/lean/toolstats.mjs +3 -1
  138. package/bin/lean/toolstats.test.mjs +11 -0
  139. package/bin/lean/validatebest.mjs +28 -0
  140. package/bin/lean/validatebest.test.mjs +27 -0
  141. package/bin/lean/verifier.mjs +3 -2
  142. package/bin/lean/verify.mjs +2 -1
  143. package/bin/lean/verify.test.mjs +6 -0
  144. package/bin/pool/agent.mjs +27 -4
  145. package/bin/pool/docker.mjs +5 -0
  146. package/bin/pool/router.mjs +74 -28
  147. package/bin/prereqs.mjs +111 -0
  148. package/bin/replay-timelapse.mjs +149 -0
  149. package/bin/review-staging.mjs +123 -16
  150. package/bin/review-staging.test.mjs +18 -0
  151. package/bin/runner.mjs +43 -6
  152. package/bin/splash-install.mjs +157 -0
  153. package/bin/stats/aggregate.mjs +8 -1
  154. package/bin/stats/conformance-outcomes.mjs +289 -0
  155. package/bin/stats/conformance-outcomes.test.mjs +274 -0
  156. package/bin/stats/depth.mjs +275 -0
  157. package/bin/stats/depth.test.mjs +158 -0
  158. package/bin/stats/efficiency.mjs +26 -5
  159. package/bin/stats/efficiency.test.mjs +45 -1
  160. package/bin/stats/experiment.mjs +7 -5
  161. package/bin/stats/first-review.mjs +77 -0
  162. package/bin/stats/first-review.test.mjs +36 -0
  163. package/bin/stats/firstmerge.mjs +40 -0
  164. package/bin/stats/firstmerge.test.mjs +41 -0
  165. package/bin/stats/github-source.mjs +53 -15
  166. package/bin/stats/index.mjs +147 -9
  167. package/bin/stats/local-source.mjs +12 -0
  168. package/bin/stats/origin.mjs +80 -0
  169. package/bin/stats/origin.test.mjs +58 -0
  170. package/bin/stats/query.mjs +69 -0
  171. package/bin/stats/render.mjs +3 -1
  172. package/bin/stats/scoreboard.mjs +137 -0
  173. package/bin/stats/scoreboard.test.mjs +87 -0
  174. package/bin/stats/selffiled.mjs +52 -0
  175. package/bin/stats/selffiled.test.mjs +71 -0
  176. package/bin/stats/stats.test.mjs +80 -0
  177. package/bin/tui.mjs +3 -2
  178. package/commands/bootstrap.md +15 -14
  179. package/commands/deploy-pr.md +18 -3
  180. package/commands/forge-stats.md +1 -1
  181. package/commands/forgedock-ci-setup.md +28 -0
  182. package/commands/forgedock-init.md +4 -5
  183. package/commands/issue.md +2 -0
  184. package/commands/milestone.md +9 -1
  185. package/commands/orchestrate.md +1 -1
  186. package/commands/replay.md +2 -0
  187. package/commands/review-pr-agents/security.md +4 -0
  188. package/commands/review-pr-staging.md +6 -1
  189. package/commands/work-on/build.md +4 -6
  190. package/commands/work-on/close.md +8 -0
  191. package/docs/CONFIG.md +170 -18
  192. package/docs/ISSUE-WATCH.md +25 -0
  193. package/docs/OUTCOME-CODES.md +4 -0
  194. package/docs/REPLAY.md +9 -0
  195. package/docs/SELFTEST.md +11 -0
  196. package/docs/STATS.md +61 -0
  197. package/docs/TELEMETRY.md +1 -1
  198. package/docs/eval/README.md +6 -0
  199. package/docs/eval/adversarial-bench.md +68 -0
  200. package/docs/eval/corpus/adversarial-v1.json +285 -0
  201. package/docs/eval/feature-bench.md +42 -0
  202. package/docs/eval/feature-specs/crud-auth/journeys/notes-crud-isolated.mjs +21 -0
  203. package/docs/eval/feature-specs/crud-auth/journeys/register-login.mjs +12 -0
  204. package/docs/eval/feature-specs/crud-auth/spec.md +15 -0
  205. package/docs/site/start-a-new-project.md +2 -1
  206. package/package.json +5 -2
  207. package/plugins/forgedock-splash/.claude-plugin/plugin.json +10 -0
  208. package/plugins/forgedock-splash/README.md +27 -0
  209. package/plugins/forgedock-splash/hooks/hooks.json +1 -0
  210. package/plugins/forgedock-splash/hooks/register.tsx +74 -0
  211. package/plugins/forgedock-splash/hooks/scene.ts +222 -0
  212. package/plugins/forgedock-splash/types/index.d.ts +10 -0
  213. package/pool/README.md +1 -1
  214. package/pool/image/cs-cred +14 -1
  215. package/scripts/backfill-finding-labels.mjs +50 -0
  216. package/scripts/backfill-finding-labels.test.mjs +36 -0
  217. package/scripts/bench-adversarial.mjs +216 -0
  218. package/scripts/bench-feature.mjs +170 -0
  219. package/scripts/bench-lightlane.mjs +2 -2
  220. package/scripts/bootstrap-create.mjs +2 -2
  221. package/scripts/bootstrap-validate.mjs +35 -2
  222. package/scripts/check-spec-size.sh +4 -3
  223. package/scripts/check-spec-size.test.sh +3 -0
  224. package/scripts/doctor-pipeline-state.sh +21 -6
  225. package/scripts/file-deferred-followups.sh +59 -251
  226. package/scripts/file-deferred-followups.test.sh +85 -206
  227. package/scripts/followup-route.mjs +12 -0
  228. package/scripts/owner-route-parity.test.sh +17 -1
  229. package/scripts/plan-validate-live.mjs +40 -6
  230. package/scripts/review-pr-side-effects.test.sh +40 -0
  231. package/scripts/review-pr-staging-scope.test.sh +1 -1
  232. package/scripts/review-staging-post.sh +23 -0
  233. package/scripts/review-staging-post.test.sh +8 -0
@@ -33,6 +33,12 @@
33
33
  * Exit reasons (#4503): every exit logs a line: `idle, exiting`, `exiting (<signal>|uncaught: …)`, `lost lock|socket …,
34
34
  * exiting` (checked every `lockCheckMs`: the lock no longer holds this pid, or the socket is gone; nothing it does not own
35
35
  * is removed), then `exited (code N)`. Taking over a dead owner's lock is logged, so a SIGKILLed daemon leaves a trace.
36
+ * Upgrade handover (#5204): the same `lockCheckMs` tick compares `installedVersion()` (the `version` of the package.json of
37
+ * this install) with the version loaded at start. When the install moved (`npm i -g`, `forgedock update`) it logs
38
+ * `schedd: install moved v<old> → v<new>; handing over` once, runs `close()` (no admission, lanes keep running, lock and
39
+ * socket released), then `respawn()`: a fresh daemon from the new install when no systemd unit runs it (`Restart=always`
40
+ * restarts an active unit). The new daemon resumes every batch; each lane it cannot adopt is requeued with an
41
+ * `interrupted: upgrade vX→vY` row (orchestrate.mjs).
36
42
  * `runBatch({argv, cwd, env, sink, keepBreaker, signal})` is injected (engine-cli `runBatch`); `sink` gets `batch(b)`, `row(r)`, `line(text)`.
37
43
  */
38
44
  import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, writeSync } from "node:fs";
@@ -43,6 +49,7 @@ import { createHash } from "node:crypto";
43
49
  import { join, resolve } from "node:path";
44
50
  import { fileURLToPath } from "node:url";
45
51
  import { schedDir, pidAlive } from "./sched.mjs";
52
+ import { DEFAULT_STALL_MIN, FIRST_HOUR_FILE, FIRST_HOUR_MIN, evaluateDispatchStall, firstHourReport, recordStallAlert, writeFirstHour } from "./batch-health.mjs";
46
53
  import { HEARTBEAT_MS, writeHeartbeat, clearHeartbeat } from "./schedd-health.mjs";
47
54
  import { batchRoot, listBatches, openBatch, SECRET_ENV } from "./batch.mjs";
48
55
  import { applySetExecution } from "./live-execution.mjs";
@@ -147,9 +154,11 @@ function takeLock(lock, pid, alive) {
147
154
  */
148
155
  export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(process.env.FORGEDOCK_SCHEDD_IDLE_MS) || IDLE_MS,
149
156
  root = batchRoot(), log = (m) => console.log(m), pid = process.pid, alive = pidAlive, resumeOnStart = true, stopMs = STOP_MS,
150
- lockCheckMs = LOCK_CHECK_MS, admitMs = Number(process.env.FORGEDOCK_SCHEDD_ADMIT_MS) || ADMIT_MS, lagMs = LAG_MS, due = null, dueMs = Number(process.env.FORGEDOCK_SCHEDD_DUE_MS) || DUE_MS, preflight = null,
151
- hostLoad = liveOverload() } = {}) {
157
+ lockCheckMs = LOCK_CHECK_MS, admitMs = Number(process.env.FORGEDOCK_SCHEDD_ADMIT_MS) || ADMIT_MS, lagMs = LAG_MS, stallCheckMs = Number(process.env.FORGEDOCK_SCHEDD_STALL_CHECK_MS) || 60_000, stallMin = Number(process.env.FORGEDOCK_SCHEDD_STALL_MIN) || DEFAULT_STALL_MIN, due = null, dueMs = Number(process.env.FORGEDOCK_SCHEDD_DUE_MS) || DUE_MS, preflight = null,
158
+ hostLoad = liveOverload(), installedVersion = readInstalledVersion, respawn = undefined } = {}) {
152
159
  const p = scheddPaths(dir);
160
+ // #5204: default handover target: a new daemon from the (new) install unless systemd restarts the unit itself
161
+ const respawnFn = respawn !== undefined ? respawn : () => { if (!["active", "activating"].includes(unitState())) defaultSpawn({ dir }); };
153
162
  mkdirSync(dir, { recursive: true });
154
163
  const lock = takeLock(p.lock, pid, alive);
155
164
  if (lock?.took) log(`schedd: took over the lock of dead pid ${lock.took} (it exited without a clean shutdown)`);
@@ -176,7 +185,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
176
185
  const ac = new AbortController();
177
186
  const ent = { id: null, dir: null, subs: new Set(first ? [first] : []) };
178
187
  const emit = (m) => { for (const s of ent.subs) s(m); };
179
- let started = false;
188
+ let started = false, endedClean = false;
180
189
  const sink = {
181
190
  batch: (b) => { ent.id = b.id; ent.dir = b.dir; hosted.set(b.id, ent); started = true; resolve(ent); },
182
191
  row: (row) => emit({ type: "row", row }),
@@ -186,12 +195,12 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
186
195
  const run = Promise.resolve().then(() => runBatch({ argv, cwd, env, sink, keepBreaker, signal: ac.signal })).then((result) => {
187
196
  const report = ent.dir ? openBatch(root, ent.id).readReport()?.report ?? null : null;
188
197
  emit({ type: "done", result, report });
189
- if (ent.id) rehostLater(ent.id); // #4917
198
+ if (ent.id) { rehostLater(ent.id); endedClean = true; } // #4917
190
199
  }, (e) => {
191
200
  const message = e?.message ?? String(e);
192
201
  if (e?.code === "batch.stopped") { log(`schedd: batch ${ent.id ?? argv.join(" ")} stopped (lanes keep running; resumed by the next daemon)`); if (!started) reject(new Error(message)); return; }
193
202
  if (!started) reject(new Error(message)); else { log(`schedd: batch ${ent.id} failed: ${message}`); emit({ type: "error", message }); }
194
- }).finally(() => { if (ent.id) hosted.delete(ent.id); ent.subs.clear(); runs.delete(run); touch(); });
203
+ }).finally(() => { if (ent.id) hosted.delete(ent.id); ent.subs.clear(); runs.delete(run); touch(); if (ent.id && endedClean) rehostUnrun(ent.id); });
195
204
  runs.set(run, ac);
196
205
  });
197
206
 
@@ -217,6 +226,29 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
217
226
  rehostTimers.add(t);
218
227
  };
219
228
 
229
+ // #5242: an add/requeue that landed while the runner was past its dispatch loop (still "hosted", no longer draining) is
230
+ // dispatched by re-hosting the batch once the run has ended. Once per distinct set of unrun entries, so an add that cannot
231
+ // drain (a cancel, a tripped breaker) never loops.
232
+ const rehostedUnrun = new Map();
233
+ const rehostUnrun = (id) => {
234
+ if (closing || hosted.has(id) || starting.has(id)) return;
235
+ let sig;
236
+ try {
237
+ const b = openBatch(root, id);
238
+ if (b.readCancel()) return;
239
+ const st = b.store.load();
240
+ if (st?.breaker && !st.breaker.transport) return;
241
+ sig = JSON.stringify([b.unrunAdds(), b.unrunRequeues().map((e) => e.issue ?? e)]);
242
+ if (!b.unrunAdds().length && !b.unrunRequeues().length) { rehostedUnrun.delete(id); return; }
243
+ } catch { return; }
244
+ if (rehostedUnrun.get(id) === sig) return;
245
+ rehostedUnrun.set(id, sig);
246
+ log(`schedd: re-hosting batch ${id} (an add or requeue arrived after its runner stopped draining)`);
247
+ const started = host({ argv: ["--resume", id], cwd: process.cwd(), env: {}, keepBreaker: true });
248
+ starting.set(id, started);
249
+ started.catch((e) => log(`schedd: re-host ${id} failed: ${e?.message ?? e}`)).finally(() => starting.delete(id));
250
+ };
251
+
220
252
  /** #4775: wait for a batch start at most `admitMs`; the start itself goes on (a second host() would duplicate the batch). */
221
253
  const bound = (p, what) => {
222
254
  let t;
@@ -359,6 +391,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
359
391
  clearInterval(idleTimer);
360
392
  clearInterval(lockTimer);
361
393
  clearInterval(lagTimer);
394
+ clearInterval(stallTimer);
362
395
  clearInterval(beatTimer);
363
396
  for (const t of rehostTimers) clearTimeout(t);
364
397
  if (dueTimer) clearInterval(dueTimer);
@@ -383,9 +416,18 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
383
416
  if (!hosted.size && !conns.size && Date.now() - lastActive >= idleMs) { log("schedd: idle, exiting"); close(); }
384
417
  }, Math.min(idleMs, 30_000));
385
418
  idleTimer.unref?.();
419
+ // #5204: the version this daemon runs; an install that moves under it hands over on the next tick.
420
+ const versionOf = () => { try { return installedVersion?.() ?? null; } catch { return null; } };
421
+ const loadedVersion = versionOf();
386
422
  // #4503: a daemon whose lock or socket was taken stops (its batches stay resumable) instead of running unreachable.
387
423
  const lockTimer = setInterval(() => {
388
424
  if (closing) return;
425
+ const now = loadedVersion ? versionOf() : null;
426
+ if (now && now !== loadedVersion) {
427
+ log(`schedd: install moved v${loadedVersion} → v${now}; handing over`);
428
+ close().then(() => { try { respawnFn?.(); } catch (e) { log(`schedd: respawn failed: ${e?.message ?? e}`); } });
429
+ return;
430
+ }
389
431
  let owner = NaN;
390
432
  try { owner = parseInt(readFileSync(p.lock, "utf8"), 10); } catch { /* gone */ }
391
433
  if (owner !== pid) { keepSock = true; log(`schedd: lost lock (owner ${Number.isInteger(owner) ? `pid ${owner}` : "none"}), exiting`); close(); }
@@ -400,6 +442,37 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
400
442
  if (lag >= lagMs && now - lagLogged >= 60_000) { lagLogged = now; log(`schedd: event loop stalled ${Math.round(lag / 1000)}s (host overloaded?)`); }
401
443
  }, 1000);
402
444
  lagTimer.unref?.();
445
+ // #5314: a batch with ready issues, free lanes and no dispatch for `stallMin` is re-hosted once per ready set, else one needs-you
446
+ // alert is recorded (health.json, status, sched show); every batch also gets its first-hour report once, without operator action.
447
+ const rehostedStall = new Map();
448
+ const watchBatches = () => {
449
+ if (closing) return;
450
+ const now = Date.now();
451
+ for (const id of listBatches(root)) {
452
+ try {
453
+ const b = openBatch(root, id), plan = b.readPlan();
454
+ if (!plan?.daemon) continue;
455
+ const reported = !!b.readReport(), cancelled = !!b.readCancel(), state = b.store.load(), created = Date.parse(plan.created ?? "");
456
+ const isHosted = hosted.has(id) || starting.has(id);
457
+ const stall = evaluateDispatchStall(state, { held: b.readHeld(), parallel: b.readParallel(), hosted: isHosted, lastProgressMs: b.lastProgressMs(), now, windowMin: stallMin, cancelled, reported });
458
+ if (Number.isFinite(created) && (reported || now - created >= FIRST_HOUR_MIN * 60_000) && !existsSync(join(b.dir, FIRST_HOUR_FILE)) && now - created < 24 * 3600_000) {
459
+ if (writeFirstHour(b, firstHourReport(state, { batchId: id, now, held: b.readHeld(), stall }))) log(`schedd: first-hour report written for batch ${id}`);
460
+ }
461
+ if (!stall) continue;
462
+ const sig = stall.ready.join(",");
463
+ if (!isHosted && rehostedStall.get(id) !== sig) {
464
+ rehostedStall.set(id, sig);
465
+ log(`schedd: re-hosting batch ${id} (${stall.detail})`);
466
+ const started = host({ argv: ["--resume", id], cwd: process.cwd(), env: {}, keepBreaker: true });
467
+ starting.set(id, started);
468
+ started.catch((e) => { log(`schedd: re-host ${id} failed: ${e?.message ?? e}`); recordStallAlert(b, stall); }).finally(() => starting.delete(id));
469
+ } else if (recordStallAlert(b, stall)) log(`schedd: batch ${id} needs you: ${stall.detail}`);
470
+ } catch { /* advisory: one unreadable batch never stops the watchdog */ }
471
+ }
472
+ };
473
+ const stallTimer = setInterval(watchBatches, stallCheckMs);
474
+ stallTimer.unref?.();
475
+
403
476
  // #4627: windowed post-deploy checks. One run at a time; a failure is logged and never stops the daemon.
404
477
  let dueRunning = false;
405
478
  const dueTimer = due ? setInterval(async () => {
@@ -433,6 +506,11 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
433
506
  return { running: true, pid, sock: p.sock, close, closed };
434
507
  }
435
508
 
509
+ /** #5204: `version` of the package.json of this install (../../package.json), null when it cannot be read. */
510
+ export function readInstalledVersion({ file = fileURLToPath(new URL("../../package.json", import.meta.url)) } = {}) {
511
+ try { return String(JSON.parse(readFileSync(file, "utf8")).version ?? "") || null; } catch { return null; }
512
+ }
513
+
436
514
  /**
437
515
  * #4454: on SIGTERM/SIGINT/SIGHUP stop the daemon (`close()`: batch loops first, then lock and socket), then exit 128+signo,
438
516
  * once; an uncaught exception or unhandled rejection does the same and exits 1. #4503: each logs its reason first, and the
@@ -3,12 +3,12 @@
3
3
  import { describe, it } from "node:test";
4
4
  import assert from "node:assert/strict";
5
5
  import { spawn } from "node:child_process";
6
- import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from "node:fs";
6
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, utimesSync, writeFileSync } from "node:fs";
7
7
  import { homedir, tmpdir } from "node:os";
8
8
  import { join } from "node:path";
9
9
  import { tmpDir } from "../tests/_tmp.mjs";
10
10
  import { openBatch, isLaneAlive, listBatches, SECRET_ENV } from "./batch.mjs";
11
- import { startDaemon, scheddPaths, connectDaemon, request, unitState, SCHEDD_SCRIPT, mergeEnv, batchEnv, droppedEnv, sanitizePath, redactEnv, exitOnSignals } from "./schedd.mjs";
11
+ import { startDaemon, scheddPaths, connectDaemon, request, unitState, SCHEDD_SCRIPT, mergeEnv, batchEnv, droppedEnv, sanitizePath, redactEnv, exitOnSignals, readInstalledVersion } from "./schedd.mjs";
12
12
  import { schedDir } from "./sched.mjs";
13
13
  import { readHeartbeat } from "./schedd-health.mjs";
14
14
  import { formatTable, orchestrate } from "./orchestrate.mjs";
@@ -80,6 +80,8 @@ await d.closed;
80
80
  // (liveLaneCap derives the cap from them). Run the clients from h.work via h.inWork to use it.
81
81
  writeFileSync(join(work, "forge.yaml"), "engine:\n admission_enabled: false\n");
82
82
  h.inWork = async (fn) => { const prev = process.cwd(); process.chdir(work); try { return await fn(); } finally { process.chdir(prev); } };
83
+ // #5204: a whole-test h.inWork for tests that start clients in the background (and a child client); cleanup restores the cwd.
84
+ h.enter = () => { h.prevCwd ??= process.cwd(); process.chdir(work); };
83
85
  h.launched = () => readFileSync(h.launches, "utf8").trim().split("\n").filter(Boolean).map(Number).sort();
84
86
  h.lanePids = () => listBatches(h.root).flatMap((id) => Object.values(openBatch(h.root, id).store.load()?.running ?? {}).map((r) => r.pid).filter(Boolean));
85
87
  h.stubPids = () => (existsSync(h.lanePidFile) ? readFileSync(h.lanePidFile, "utf8").trim().split("\n").filter(Boolean).map(Number) : []);
@@ -88,6 +90,7 @@ await d.closed;
88
90
  for (const pid of h.stubPids()) { try { process.kill(pid, "SIGKILL"); } catch { /* gone */ } }
89
91
  };
90
92
  h.cleanup = async () => {
93
+ if (h.prevCwd) { process.chdir(h.prevCwd); h.prevCwd = undefined; }
91
94
  if (existsSync(h.work)) writeFileSync(h.release, "");
92
95
  h.reap();
93
96
  await until(() => h.stubPids().every((pid) => !isLaneAlive(pid, null)), 5000).catch(() => {});
@@ -145,7 +148,7 @@ describe("schedd host scheduler (#4192)", () => {
145
148
  });
146
149
 
147
150
  it("a client that disconnects does not stop the batch; --resume reattaches, and replays the report once done", async () => {
148
- const h = host();
151
+ const h = host(); h.enter(); // admission off: this test needs >1 concurrent local lane on any host
149
152
  try {
150
153
  await h.daemon();
151
154
  const clientScript = join(h.work, "client.mjs");
@@ -174,7 +177,7 @@ await orchestrateFromCli(["1", "2", "--parallel", "2", "--repo", "o/r", "--no-pr
174
177
  });
175
178
 
176
179
  it("a daemon restart resumes the batch from state and re-adopts its live lanes without duplicate launches", async () => {
177
- const h = host();
180
+ const h = host(); h.enter(); // admission off: this test needs >1 concurrent local lane on any host
178
181
  try {
179
182
  const d1 = await h.daemon();
180
183
  const first = capture(() => orchestrateFromCli(["1", "2", "3", "--parallel", "2", "--repo", "o/r", "--no-prefilter"], h.client)).then(() => null, (e) => e);
@@ -303,7 +306,7 @@ await orchestrateFromCli(["1", "2", "--parallel", "2", "--repo", "o/r", "--no-pr
303
306
  });
304
307
 
305
308
  it("#4376: --cancel stops one batch (its lane torn down, the rest held, report written); the other batch and the daemon run on", async () => {
306
- const h = host();
309
+ const h = host(); h.enter(); // admission off: this test needs >1 concurrent local lane on any host
307
310
  try {
308
311
  const d = await h.daemon();
309
312
  await withRoot(h, () => capture(async () => {
@@ -424,6 +427,63 @@ await orchestrateFromCli(["1", "2", "--parallel", "2", "--repo", "o/r", "--no-pr
424
427
  } finally { await d.close(); }
425
428
  });
426
429
 
430
+ it("#5242: an add that lands while the runner is past its dispatch loop is dispatched by a re-host, not left for a manual --resume", async () => {
431
+ for (const drains of [true, false]) {
432
+ const dir = tmpDir("schedd-tail-add-"), root = join(dir, "batches"), id = "b20261108-000000-5242";
433
+ const calls = [];
434
+ let release;
435
+ const gate = new Promise((r) => { release = r; });
436
+ const runBatch = async ({ argv, sink }) => {
437
+ calls.push(argv);
438
+ const b = openBatch(root, id);
439
+ if (argv[0] !== "--resume") {
440
+ b.writePlan({ daemon: true, repo: "o/r" });
441
+ b.store.save({ v: 1, order: [1], results: { 1: { issue: 1, outcome: "merged" } }, running: {}, pending: [] });
442
+ sink.batch({ id, dir: b.dir });
443
+ await gate; // the run's tail: hosted, no longer draining adds
444
+ } else {
445
+ sink.batch({ id, dir: b.dir });
446
+ if (drains) b.store.save({ ...b.store.load(), order: [1, 6], results: { 1: { issue: 1, outcome: "merged" }, 6: { issue: 6, outcome: "merged" } } });
447
+ }
448
+ return {};
449
+ };
450
+ const d = await startDaemon({ dir, root, runBatch, log: () => {}, resumeOnStart: false });
451
+ try {
452
+ const submitted = request(await connectDaemon({ dir, spawnDaemon: null }), { op: "submit", argv: ["1"], cwd: dir, env: {} }).catch(() => {}); // streams until the run ends
453
+ await until(() => calls.length === 1 && openBatch(root, id).readPlan());
454
+ const res = await request(await connectDaemon({ dir, spawnDaemon: null }), { op: "add", id, issues: [6] });
455
+ assert.deepEqual(res.added, [6]);
456
+ assert.equal(res.reopened, false, "the runner still counts as hosted");
457
+ release();
458
+ await submitted;
459
+ await until(() => calls.length === 2, 8000);
460
+ assert.deepEqual(calls[1], ["--resume", id]);
461
+ await new Promise((r) => setTimeout(r, 300));
462
+ assert.equal(calls.length, 2, drains ? "drained: no further re-host" : "an add that cannot drain does not loop");
463
+ } finally { release(); await d.close(); }
464
+ }
465
+ });
466
+
467
+ it("#5314: a batch whose runner is gone with ready issues pending is re-hosted by the watchdog; a runner that dispatches nothing raises one alert", async () => {
468
+ const dir = tmpDir("schedd-stall-"), root = join(dir, "batches"), id = "b20261104-052317-5314";
469
+ const calls = [];
470
+ const b = openBatch(root, id);
471
+ b.writePlan({ daemon: true, repo: "o/r", created: new Date(Date.now() - 90 * 60000).toISOString() });
472
+ b.store.save({ v: 1, order: [1], results: {}, running: {}, pending: [1], parallel: 2 });
473
+ const old = new Date(Date.now() - 30 * 60000);
474
+ utimesSync(join(b.dir, "state.json"), old, old);
475
+ const runBatch = async ({ argv, sink }) => { calls.push(argv); sink.batch({ id, dir: b.dir }); return await new Promise(() => {}); }; // a wedged runner
476
+ const d = await startDaemon({ dir, root, runBatch, log: () => {}, resumeOnStart: false, stallCheckMs: 50, stallMin: 10 });
477
+ try {
478
+ await until(() => calls.length === 1, 8000);
479
+ assert.deepEqual(calls[0], ["--resume", id], "re-hosted without operator action");
480
+ await until(() => existsSync(join(b.dir, "first-hour.json")), 8000);
481
+ utimesSync(join(b.dir, "state.json"), old, old); // the wedged runner still dispatched nothing
482
+ await until(() => existsSync(join(b.dir, "health.json")) && readFileSync(join(b.dir, "health.json"), "utf8").includes("dispatch-stalled"), 8000);
483
+ assert.equal(calls.length, 1, "a hosted runner is not re-hosted again");
484
+ } finally { await d.close(); }
485
+ });
486
+
427
487
  it("#4917: a resume that leaves the waiting issue unadmitted (breaker tripped, retry-at passed) is not re-hosted again", async () => {
428
488
  const dir = tmpDir("schedd-rehost-loop-"), root = join(dir, "batches"), id = "b20261031-000000-4918";
429
489
  const calls = [];
@@ -514,7 +574,7 @@ await orchestrateFromCli(["1", "2", "--parallel", "2", "--repo", "o/r", "--no-pr
514
574
  });
515
575
 
516
576
  it("#4454: kill -TERM stops both batches and exits 143 within the bound; lanes keep running; the next daemon resumes and adopts them", async () => {
517
- const h = host();
577
+ const h = host(); h.enter(); // admission off: this test needs >1 concurrent local lane on any host
518
578
  try {
519
579
  const d1 = await h.daemon();
520
580
  const { lines } = await withRoot(h, () => capture(async () => {
@@ -593,6 +653,47 @@ await orchestrateFromCli(["1", "2", "--parallel", "2", "--repo", "o/r", "--no-pr
593
653
  assert.equal(existsSync(p.lock), false, "its own lock is released");
594
654
  });
595
655
 
656
+ it("#5204: an install that moves under the daemon hands over once: batches stop resumable, lock and socket released, then respawn starts the next daemon", async () => {
657
+ const dir = tmpDir("schedd-upgrade-"), p = scheddPaths(dir), root = join(dir, "batches"), lines = [];
658
+ let version = "1.51.0", stopped = false, d2 = null, lockAtRespawn = null, respawns = 0;
659
+ const d = await startDaemon({ dir, root, log: (m) => lines.push(m), resumeOnStart: false, lockCheckMs: 30, installedVersion: () => version,
660
+ runBatch: ({ sink, signal }) => { sink.batch({ id: "x", dir }); return new Promise((_, rej) => signal.addEventListener("abort", () => { stopped = true; rej(Object.assign(new Error("stopped"), { code: "batch.stopped" })); })); },
661
+ respawn: async () => { respawns++; lockAtRespawn = existsSync(p.lock); d2 = await startDaemon({ dir, root, runBatch: async () => ({}), log: () => {}, resumeOnStart: false, installedVersion: () => version }); } });
662
+ request(await connectDaemon({ dir, spawnDaemon: null }), { op: "submit", argv: ["x"], cwd: dir, env: {} }).catch(() => {});
663
+ await until(() => lines.some((l) => l.includes("listening")));
664
+ await new Promise((r) => setTimeout(r, 90));
665
+ assert.ok(!lines.some((l) => l.includes("handing over")), "no handover while the install is unchanged");
666
+ version = "1.52.0";
667
+ await d.closed;
668
+ await until(() => d2 !== null);
669
+ try {
670
+ assert.equal(lines.filter((l) => l === "schedd: install moved v1.51.0 → v1.52.0; handing over").length, 1, lines.join("\n"));
671
+ assert.equal(stopped, true, "the hosted batch stopped resumable (no admission, lanes keep running)");
672
+ assert.equal(lockAtRespawn, false, "the lock was released before the respawn");
673
+ assert.equal(respawns, 1);
674
+ assert.equal(d2.running, true, "the next daemon took the lock");
675
+ } finally { await d2?.close?.(); }
676
+ });
677
+
678
+ it("#5204: readInstalledVersion reads this install's package.json version, null when unreadable", () => {
679
+ assert.equal(readInstalledVersion(), JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version);
680
+ const dir = tmpDir("schedd-ver-");
681
+ writeFileSync(join(dir, "package.json"), "{not json");
682
+ assert.equal(readInstalledVersion({ file: join(dir, "package.json") }), null);
683
+ assert.equal(readInstalledVersion({ file: join(dir, "missing.json") }), null);
684
+ });
685
+
686
+ it("#5204: an unreadable install version never hands over", async () => {
687
+ const dir = tmpDir("schedd-upgrade-null-"), lines = [];
688
+ let calls = 0;
689
+ const d = await startDaemon({ dir, root: join(dir, "batches"), runBatch: async () => ({}), log: (m) => lines.push(m), resumeOnStart: false, lockCheckMs: 20,
690
+ installedVersion: () => (++calls === 1 ? "1.51.0" : null), respawn: () => assert.fail("no respawn") });
691
+ await new Promise((r) => setTimeout(r, 100));
692
+ assert.ok(calls > 1, "checked on the tick");
693
+ assert.ok(!lines.some((l) => l.includes("handing over")));
694
+ await d.close();
695
+ });
696
+
596
697
  it("#4503: a client whose daemon is SIGKILLed re-attaches to the next daemon and finishes, without relaunching a lane", async () => {
597
698
  const h = host();
598
699
  try {
@@ -616,7 +717,7 @@ await orchestrateFromCli(["1", "2", "--parallel", "2", "--repo", "o/r", "--no-pr
616
717
  it("#4503: test runs never resolve ~/.forge/sched, and teardown leaves no live stub lane", async () => {
617
718
  assert.notEqual(schedDir(), join(homedir(), ".forge", "sched"));
618
719
  assert.ok(schedDir().startsWith(tmpdir()), schedDir());
619
- const h = host();
720
+ const h = host(); h.enter(); // admission off: this test needs >1 concurrent local lane on any host
620
721
  let pids = [], a;
621
722
  try {
622
723
  await h.daemon();
@@ -7,6 +7,9 @@
7
7
  * SELF_REVIEW_DISAGREED). Never a failure, never a runner call. Pure: no I/O.
8
8
  */
9
9
 
10
+ import { precheck, authorizationOf, applyAmendments } from "./conformance.mjs";
11
+ import { pathDomains, riskClassOf } from "./review-trigger.mjs";
12
+
10
13
  const text = (v) => (v === null || v === undefined ? "" : String(v)).trim();
11
14
 
12
15
  /**
@@ -35,3 +38,94 @@ export function compareSelfReview(self, decision) {
35
38
  const allYes = self.no.length === 0;
36
39
  return { agreed: allYes === (reviewer === "conforms"), reviewer, self_no: self.no };
37
40
  }
41
+
42
+ // ---- #5345 clean-first-review: the reviewer's deterministic checks, run by the builder before it finishes ----
43
+ /** (selfReviewFindings, firstReviewRecord, sectionOfKind, FINDING_PITFALLS: precheck() subset + preserve-touch; the first-round record riding on RUN_TERMINAL) */
44
+ /** The contract section a finding kind traces to (measures which section of the plan first-round findings map to). */
45
+ export const KIND_SECTION = Object.freeze({
46
+ "conformance.omission": "requirements",
47
+ "conformance.unimplemented": "requirements",
48
+ "conformance.untracked_deferral": "requirements",
49
+ "conformance.unjustified_deferral": "requirements",
50
+ "conformance.scope_creep": "deliverables",
51
+ "conformance.preserve_violated": "preserve",
52
+ "conformance.regression": "validate",
53
+ "review.incomplete": "reviewer",
54
+ });
55
+ export const sectionOfKind = (code) => KIND_SECTION[code] ?? "other";
56
+
57
+ /** Builder pitfall per recurring finding kind (the three that are 80% of first-round findings). */
58
+ export const FINDING_PITFALLS = Object.freeze({
59
+ "conformance.omission": "Map every issue requirement to the diff line that delivers it; omission is the top finding.",
60
+ "conformance.scope_creep": "Edit only contract-listed files (tests aside); amend a needed extra file in first.",
61
+ "conformance.preserve_violated": "Re-check each preserve path is unchanged; an edited one needs a covering deliverable.",
62
+ });
63
+
64
+ /** R5: the planner rule per contract section the first-round findings trace to (rendered into the plan prompt). */
65
+ export const PLANNER_TIGHTENING = Object.freeze({
66
+ requirements: "One requirement per sentence or clause, each with a deliverable and a validate (omission is the top finding).",
67
+ deliverables: "List every changed file, tests included (scope_creep flags unnamed ones).",
68
+ preserve: "Give each preserve row a file path; it cannot be checked without one.",
69
+ });
70
+
71
+ const PATH_RE = /[\w@.-]+(?:\/[\w@.*-]+)+\.\w+|[\w@.-]+\/[\w@.*-]+\/?/g;
72
+ const NEEDS_RESULT = new Set(["requirement_unimplemented", "untracked_deferral"]);
73
+
74
+ /**
75
+ * The deterministic conformance findings of the current tree: [{code, kind, detail, section}]. Validate commands are not
76
+ * judged here (`forgedock check` runs them); requirement statuses are judged only when the builder reported any.
77
+ */
78
+ export function selfReviewFindings({ contract: frozen, result = null, changedFiles = [], ignore = [".forge-lean/"], hotspots = null }) {
79
+ if (!frozen || typeof frozen !== "object") return [];
80
+ // the builder's typed amendments (add-deliverable, ...) are part of the contract the gate judges; problems are the engine's to report
81
+ const contract = Array.isArray(result?.amendments) && result.amendments.length ? applyAmendments(frozen, result.amendments).contract : frozen;
82
+ const reported = Array.isArray(result?.requirements);
83
+ const pc = precheck({ contract: { ...contract, validate: [] }, result: reported ? result : null, changedFiles, ignore, hotspots, ciVerified: true });
84
+ // no result.json yet: the builder cannot have amended an extra file in, so scope_creep is not judged until one exists
85
+ const out = pc.failures.filter((f) => (reported || !NEEDS_RESULT.has(f.kind)) && (result || f.code !== "conformance.scope_creep")).map((f) => ({ code: f.code, kind: f.kind ?? null, detail: f.detail, section: sectionOfKind(f.code) }));
86
+ out.push(...preserveTouched(contract, changedFiles, ignore));
87
+ return out;
88
+ }
89
+
90
+ /** A preserve item names a path the diff changed that no deliverable authorizes: the touch can only be a violation. */
91
+ export function preserveTouched(contract, changedFiles = [], ignore = []) {
92
+ const out = [];
93
+ for (const p of contract?.preserve ?? []) {
94
+ const named = [...String(p?.what ?? "").matchAll(PATH_RE)].map((m) => m[0].replace(/[.,;:)]+$/, ""));
95
+ for (const f of changedFiles) {
96
+ if (ignore.some((x) => f.startsWith(x)) || authorizationOf(contract, f)) continue;
97
+ if (named.some((n) => n === f || (n.endsWith("/") && f.startsWith(n)))) out.push({ code: "conformance.preserve_violated", kind: "preserve_touched", detail: `${p.id}: ${f} is preserved and no deliverable authorizes changing it`, section: "preserve" });
98
+ }
99
+ }
100
+ return out;
101
+ }
102
+
103
+ /** The change type of a lane from its issue labels: bug|feature|chore|docs|other. */
104
+ export function changeTypeOf(labels = []) {
105
+ const names = (Array.isArray(labels) ? labels : []).map((l) => String(l?.name ?? l).toLowerCase());
106
+ for (const t of ["bug", "feature", "chore", "docs"]) if (names.some((n) => n === t || n === `type:${t}`)) return t;
107
+ return "other";
108
+ }
109
+
110
+ /** `domain:<d>` / `risk:<class>` surfaces a lane's files touch (the same names `stats --conformance-outcomes` uses). */
111
+ export function surfacesOf(files = []) {
112
+ const domains = pathDomains(files) ?? [];
113
+ return [...new Set([...domains.map((d) => `domain:${d}`), ...files.map(riskClassOf).filter(Boolean).map((c) => `risk:${c}`)])].sort();
114
+ }
115
+
116
+ /**
117
+ * The first-round record riding on RUN_TERMINAL: the first gate judgement (`rounds[0]`: {state, failures: [code]}), its
118
+ * failure kinds, how many gate rounds the lane took, and whether the reviewer's own first reply (`firstReply`, a decide()
119
+ * state) was incomplete. null when no review ran.
120
+ */
121
+ export function firstReviewRecord({ rounds = [], firstReply = null, labels = [], files = [] } = {}) {
122
+ if (!rounds.length) return null;
123
+ const first = rounds[0];
124
+ const kinds = [...new Set((first.failures ?? []).filter(Boolean))].sort();
125
+ return { state: first.state, kinds, rounds: rounds.length, clean: first.state === "conforms", incomplete: firstReply === "review.incomplete" || first.state === "review.incomplete", type: changeTypeOf(labels), surfaces: surfacesOf(files) };
126
+ }
127
+
128
+ /** The failures a builder's own red `forgedock check` record holds (the review section), as resume failures; [] when none. */
129
+ export function selfCheckFailures(record) {
130
+ return (Array.isArray(record?.review) ? record.review : []).filter((f) => f?.code && f?.detail).map((f) => ({ code: f.code, detail: String(f.detail) }));
131
+ }
@@ -2,7 +2,8 @@
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  import { describe, it } from "node:test";
4
4
  import assert from "node:assert/strict";
5
- import { readSelfReview, compareSelfReview } from "./selfreview.mjs";
5
+ import { readSelfReview, compareSelfReview, selfReviewFindings, selfCheckFailures, firstReviewRecord, sectionOfKind, FINDING_PITFALLS } from "./selfreview.mjs";
6
+ import { selfCheck, selfCheckState, formatCheckTable } from "./precheck.mjs";
6
7
 
7
8
  const item = (question, answer = "yes", evidence = "src/a.py:3") => ({ question, answer, evidence });
8
9
 
@@ -49,3 +50,59 @@ describe("compareSelfReview (#4374)", () => {
49
50
  assert.equal(compareSelfReview(yes, null), null);
50
51
  });
51
52
  });
53
+
54
+ describe("selfReviewFindings (#5345)", () => {
55
+ const contract = { requirements: [{ id: "R1", quote: "q", disposition: "deliver" }], deliverables: [{ id: "D1", path: "src/a.js" }], preserve: [{ id: "P1", what: "src/keep.js behaviour unchanged" }], validate: [] };
56
+ it("catches scope creep and a preserved path touched without authorization", () => {
57
+ const f = selfReviewFindings({ contract, result: {}, changedFiles: ["src/a.js", "src/keep.js", "src/b.js"] });
58
+ assert.ok(f.some((x) => x.code === "conformance.scope_creep" && x.section === "deliverables"));
59
+ assert.ok(f.some((x) => x.code === "conformance.preserve_violated" && /P1: src\/keep\.js/.test(x.detail)));
60
+ });
61
+ it("selfReviewFindings applies add-deliverable amendments", () => {
62
+ const files = ["src/a.js", "src/b.js"];
63
+ const amendments = [{ kind: "add-deliverable", path: "src/b.js", why: "needed helper" }];
64
+ assert.ok(selfReviewFindings({ contract, result: { amendments }, changedFiles: files }).length === 0);
65
+ assert.ok(selfReviewFindings({ contract, result: { amendments: [] }, changedFiles: files }).some((x) => x.code === "conformance.scope_creep"));
66
+ assert.ok(!selfReviewFindings({ contract, changedFiles: files }).some((x) => x.code === "conformance.scope_creep"), "no result.json yet: scope_creep not judged");
67
+ const keep = selfReviewFindings({ contract, result: { amendments: [{ kind: "add-deliverable", path: "src/keep.js", why: "w" }] }, changedFiles: ["src/a.js", "src/keep.js"] });
68
+ assert.deepEqual(keep, []);
69
+ });
70
+ it("catches an unimplemented requirement only once the builder reported statuses", () => {
71
+ assert.deepEqual(selfReviewFindings({ contract, changedFiles: ["src/a.js"] }), []);
72
+ const f = selfReviewFindings({ contract, result: { requirements: [{ id: "R1", status: "missing" }] }, changedFiles: ["src/a.js"] });
73
+ assert.ok(f.some((x) => x.code === "conformance.unimplemented" && x.section === "requirements"));
74
+ });
75
+ it("a red review section makes the check fail and the record red, so the lane is fixed before review", async () => {
76
+ const review = selfReviewFindings({ contract, result: {}, changedFiles: ["src/b.js"] });
77
+ const r = await selfCheck({ review, contract, plan: { commands: [], budgetMs: 0, perCommandMs: 1 }, run: async () => ({ rc: 0 }) });
78
+ assert.equal(r.ok, false);
79
+ assert.match(formatCheckTable(r), /FAIL review {2}conformance\.scope_creep/);
80
+ const rec = { fingerprint: "x", ok: r.ok, review: r.review.map((f) => ({ code: f.code, detail: f.detail })) };
81
+ assert.equal(selfCheckState(rec, "x"), "red");
82
+ assert.deepEqual(selfCheckFailures(rec).map((f) => f.code), review.map((f) => f.code));
83
+ assert.equal((await selfCheck({ contract, plan: { commands: [], budgetMs: 0, perCommandMs: 1 }, run: async () => ({ rc: 0 }) })).ok, true);
84
+ });
85
+ it("pitfalls cover the recurring kinds and map to sections", () => {
86
+ assert.deepEqual(Object.keys(FINDING_PITFALLS).sort(), ["conformance.omission", "conformance.preserve_violated", "conformance.scope_creep"]);
87
+ assert.equal(sectionOfKind("conformance.preserve_violated"), "preserve");
88
+ });
89
+ });
90
+
91
+ describe("firstReviewRecord (#5345)", () => {
92
+ it("null without a round; otherwise the first judgement, rounds, type and surfaces", () => {
93
+ assert.equal(firstReviewRecord({}), null);
94
+ const r = firstReviewRecord({ rounds: [{ state: "fails", failures: ["conformance.scope_creep"] }, { state: "conforms", failures: [] }], labels: [{ name: "bug" }], files: ["src/a.js"] });
95
+ assert.deepEqual([r.state, r.kinds, r.rounds, r.clean, r.type], ["fails", ["conformance.scope_creep"], 2, false, "bug"]);
96
+ assert.equal(firstReviewRecord({ rounds: [{ state: "review.incomplete", failures: [] }] }).incomplete, true);
97
+ });
98
+ });
99
+
100
+ describe("planner tightening (#5345 R5)", () => {
101
+ it("every contract section first-round findings map to has a planner rule, rendered in the plan prompt", async () => {
102
+ const { PLANNER_TIGHTENING, KIND_SECTION } = await import("./selfreview.mjs");
103
+ const { builderPlanPrompt } = await import("./prompts.mjs");
104
+ for (const s of new Set(Object.values(KIND_SECTION).filter((x) => ["requirements", "deliverables", "preserve"].includes(x)))) assert.ok(PLANNER_TIGHTENING[s], s);
105
+ const p = builderPlanPrompt(1);
106
+ for (const x of Object.values(PLANNER_TIGHTENING)) assert.ok(p.includes(x));
107
+ });
108
+ });
@@ -44,3 +44,25 @@ export async function readMarkerComments(gh, repo, pr) {
44
44
  export async function postMarker(gh, repo, pr, m) {
45
45
  await gh(["pr", "comment", String(pr), "-R", repo, "--body", `${buildMarker(m)}\nLive selftest: ${m.result}${m.step ? ` (step ${m.step})` : ""}`]);
46
46
  }
47
+
48
+ // FORGE:JOURNEY marker (#5305): the new-user journey result, posted next to GATE_PASS. Informational: the release gate
49
+ // above never reads it, and it is a separate marker so it cannot replace the FORGE:SELFTEST result.
50
+ const JOURNEY_RE = /^\s*<!--\s*FORGE:JOURNEY\s+([^>]*?)\s*-->/;
51
+
52
+ /** @param {{result:"pass"|"fail", sha:string, step?:string|null, ttfm?:number|null}} m ttfm: seconds to the first merged PR */
53
+ export function buildJourneyMarker({ result, sha, step, ttfm }) {
54
+ return `<!-- FORGE:JOURNEY result=${result} sha=${sha} step=${step || "none"} ttfm=${ttfm ?? "na"} -->`;
55
+ }
56
+
57
+ /** @returns {{result:string, sha:string, step:string, ttfm:number|null}|null} */
58
+ export function parseJourneyMarker(body) {
59
+ const m = JOURNEY_RE.exec(String(body ?? ""));
60
+ if (!m) return null;
61
+ const kv = Object.fromEntries(m[1].split(/\s+/).map((p) => p.split("=")).filter((p) => p.length === 2));
62
+ if (!/^(pass|fail)$/.test(kv.result ?? "") || !/^[0-9a-f]{40}$/.test(kv.sha ?? "")) return null;
63
+ return { result: kv.result, sha: kv.sha, step: kv.step ?? "none", ttfm: /^\d+$/.test(kv.ttfm ?? "") ? Number(kv.ttfm) : null };
64
+ }
65
+
66
+ export async function postJourneyMarker(gh, repo, pr, m) {
67
+ await gh(["pr", "comment", String(pr), "-R", repo, "--body", `${buildJourneyMarker(m)}\nNew-user journey: ${m.result}${m.step ? ` (step ${m.step})` : ""}${m.ttfm != null ? `, first merged PR in ${m.ttfm}s` : ""}`]);
68
+ }
@@ -2,7 +2,7 @@
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  import { describe, it } from "node:test";
4
4
  import assert from "node:assert/strict";
5
- import { buildMarker, parseMarker, selftestGate, readMarkerComments, postMarker } from "./selftest-gate.mjs";
5
+ import { buildJourneyMarker, parseJourneyMarker, postJourneyMarker, buildMarker, parseMarker, selftestGate, readMarkerComments, postMarker } from "./selftest-gate.mjs";
6
6
 
7
7
  const H = "a".repeat(40), O = "b".repeat(40);
8
8
  describe("FORGE:SELFTEST gate (#4865)", () => {
@@ -38,3 +38,20 @@ describe("FORGE:SELFTEST gate (#4865)", () => {
38
38
  });
39
39
  });
40
40
 
41
+
42
+ describe("FORGE:JOURNEY marker (#5305)", () => {
43
+ it("round-trips and never counts as a FORGE:SELFTEST result", () => {
44
+ const m = buildJourneyMarker({ result: "pass", sha: H, ttfm: 312 });
45
+ assert.deepEqual(parseJourneyMarker(m), { result: "pass", sha: H, step: "none", ttfm: 312 });
46
+ assert.equal(parseMarker(m), null);
47
+ assert.equal(selftestGate([m], H).ok, false);
48
+ assert.equal(parseJourneyMarker(buildMarker({ result: "pass", sha: H })), null);
49
+ assert.equal(parseJourneyMarker(`quote ${m}`), null);
50
+ assert.equal(parseJourneyMarker(buildJourneyMarker({ result: "fail", sha: H, step: "doctor" })).ttfm, null);
51
+ });
52
+ it("posts through gh", async () => {
53
+ const calls = [];
54
+ await postJourneyMarker(async (a) => { calls.push(a); return ""; }, "o/r", 5, { result: "fail", sha: H, step: "banner" });
55
+ assert.match(calls[0].at(-1), /^<!-- FORGE:JOURNEY result=fail sha=a{40} step=banner ttfm=na -->/);
56
+ });
57
+ });