forgedock 1.67.0 → 1.68.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 (140) hide show
  1. package/bin/config-schema.mjs +1 -0
  2. package/bin/engine/outcome-codes.mjs +1 -0
  3. package/bin/engine-cli.mjs +99 -12
  4. package/bin/engine.mjs +10 -0
  5. package/bin/forgedock.mjs +17 -1
  6. package/bin/help-text.mjs +1 -0
  7. package/bin/lean/admission.mjs +21 -0
  8. package/bin/lean/admission.test.mjs +30 -0
  9. package/bin/lean/advisory.test.mjs +25 -10
  10. package/bin/lean/amendment-schema.mjs +3 -4
  11. package/bin/lean/attempts.mjs +34 -31
  12. package/bin/lean/attempts.test.mjs +33 -19
  13. package/bin/lean/basered.mjs +26 -0
  14. package/bin/lean/batch-health.mjs +17 -12
  15. package/bin/lean/batch-health.test.mjs +39 -11
  16. package/bin/lean/batch.test.mjs +51 -2
  17. package/bin/lean/ci-gate.mjs +2 -90
  18. package/bin/lean/ci-gate.test.mjs +1 -127
  19. package/bin/lean/ci-precheck.mjs +25 -8
  20. package/bin/lean/ci-precheck.test.mjs +24 -0
  21. package/bin/lean/clear-breaker.test.mjs +4 -3
  22. package/bin/lean/commentstate.mjs +10 -5
  23. package/bin/lean/commentstate.test.mjs +12 -1
  24. package/bin/lean/conformance.e2e.test.mjs +9 -6
  25. package/bin/lean/conformance.mjs +56 -196
  26. package/bin/lean/conformance.test.mjs +40 -376
  27. package/bin/lean/depcache.mjs +100 -10
  28. package/bin/lean/depcache.test.mjs +105 -0
  29. package/bin/lean/docsgate.mjs +0 -32
  30. package/bin/lean/docsgate.test.mjs +2 -23
  31. package/bin/lean/effects-cap.test.mjs +9 -1
  32. package/bin/lean/effects-killtree.test.mjs +35 -0
  33. package/bin/lean/effects.mjs +42 -24
  34. package/bin/lean/engine-readmit.test.mjs +35 -0
  35. package/bin/lean/envgap.mjs +93 -0
  36. package/bin/lean/envgap.test.mjs +53 -0
  37. package/bin/lean/execution.mjs +10 -4
  38. package/bin/lean/execution.test.mjs +12 -0
  39. package/bin/lean/failure-census.mjs +170 -0
  40. package/bin/lean/failure-census.test.mjs +59 -0
  41. package/bin/lean/guardgate.test.mjs +2 -3
  42. package/bin/lean/heavy.mjs +33 -4
  43. package/bin/lean/heavy.test.mjs +38 -6
  44. package/bin/lean/hotarea.mjs +0 -36
  45. package/bin/lean/hotarea.test.mjs +1 -22
  46. package/bin/lean/issuewatch-verify.mjs +19 -4
  47. package/bin/lean/issuewatch.mjs +21 -4
  48. package/bin/lean/issuewatch.test.mjs +48 -1
  49. package/bin/lean/lane-audit-gap.mjs +66 -0
  50. package/bin/lean/lane-audit-gap.test.mjs +59 -0
  51. package/bin/lean/lane-audit-llm.mjs +5 -0
  52. package/bin/lean/lane-audit-query.mjs +47 -0
  53. package/bin/lean/lane-audit-query.test.mjs +44 -0
  54. package/bin/lean/lane-audit-signatures.mjs +33 -0
  55. package/bin/lean/lane-audit.mjs +110 -0
  56. package/bin/lean/lane-audit.test.mjs +97 -0
  57. package/bin/lean/lane-recovery.test.mjs +33 -0
  58. package/bin/lean/lanecheck.mjs +5 -3
  59. package/bin/lean/lanecheck.test.mjs +6 -0
  60. package/bin/lean/lean.mjs +206 -148
  61. package/bin/lean/lean.test.mjs +406 -190
  62. package/bin/lean/limits.mjs +17 -0
  63. package/bin/lean/limits.test.mjs +15 -1
  64. package/bin/lean/live-execution.mjs +21 -2
  65. package/bin/lean/live-execution.test.mjs +39 -0
  66. package/bin/lean/orchestrate-attempts.test.mjs +17 -9
  67. package/bin/lean/orchestrate-envhold.test.mjs +47 -0
  68. package/bin/lean/orchestrate-heldroot.test.mjs +72 -0
  69. package/bin/lean/orchestrate-hostfallback.test.mjs +59 -1
  70. package/bin/lean/orchestrate-overload-recovery.test.mjs +37 -0
  71. package/bin/lean/orchestrate-pause.test.mjs +53 -1
  72. package/bin/lean/orchestrate-reconcile.test.mjs +17 -0
  73. package/bin/lean/orchestrate-relaunch-gates.test.mjs +57 -0
  74. package/bin/lean/orchestrate-stacking.test.mjs +10 -0
  75. package/bin/lean/orchestrate.mjs +188 -33
  76. package/bin/lean/postdeploy-check.test.mjs +1 -3
  77. package/bin/lean/precheck.mjs +20 -0
  78. package/bin/lean/preflight.mjs +100 -11
  79. package/bin/lean/preflight.test.mjs +44 -4
  80. package/bin/lean/prompts.mjs +10 -21
  81. package/bin/lean/recurrence.mjs +6 -148
  82. package/bin/lean/recurrence.test.mjs +11 -147
  83. package/bin/lean/release-flakes.mjs +14 -2
  84. package/bin/lean/release-flakes.test.mjs +17 -1
  85. package/bin/lean/release-ledger.mjs +19 -1
  86. package/bin/lean/release-ledger.test.mjs +23 -0
  87. package/bin/lean/release-preflight.mjs +28 -0
  88. package/bin/lean/release-preflight.test.mjs +42 -1
  89. package/bin/lean/release-review.mjs +40 -5
  90. package/bin/lean/release-review.test.mjs +43 -2
  91. package/bin/lean/release.mjs +43 -14
  92. package/bin/lean/release.test.mjs +32 -0
  93. package/bin/lean/retry.mjs +1 -1
  94. package/bin/lean/retry.test.mjs +6 -1
  95. package/bin/lean/rotator.mjs +9 -0
  96. package/bin/lean/rotator.test.mjs +11 -1
  97. package/bin/lean/sandbox-remote.mjs +16 -9
  98. package/bin/lean/schedd.mjs +11 -6
  99. package/bin/lean/schedd.test.mjs +65 -5
  100. package/bin/lean/selfreview.mjs +1 -1
  101. package/bin/lean/statuscomment.mjs +4 -1
  102. package/bin/lean/validate-catalog.mjs +108 -0
  103. package/bin/lean/validate-catalog.test.mjs +46 -1
  104. package/bin/lean/verify.mjs +1 -1
  105. package/bin/pool/affinity.test.mjs +91 -0
  106. package/bin/pool/agent.mjs +143 -9
  107. package/bin/pool/cache-sweep.mjs +31 -10
  108. package/bin/pool/ci-autoscale.mjs +160 -0
  109. package/bin/pool/cli.mjs +37 -8
  110. package/bin/pool/docker.mjs +3 -0
  111. package/bin/pool/engine-placement.test.mjs +94 -0
  112. package/bin/pool/lane-target.mjs +41 -0
  113. package/bin/pool/lane-tools.mjs +7 -2
  114. package/bin/pool/lane-tools.test.mjs +9 -0
  115. package/bin/pool/mirror-seed.mjs +15 -11
  116. package/bin/pool/router.mjs +88 -32
  117. package/bin/pool/version.mjs +29 -2
  118. package/bin/review-staging.mjs +11 -3
  119. package/bin/runner.mjs +59 -11
  120. package/bin/stats/release.mjs +7 -0
  121. package/bin/stats/release.test.mjs +20 -0
  122. package/bin/stats/scorecard.mjs +187 -0
  123. package/bin/stats/scorecard.test.mjs +89 -0
  124. package/docs/CONFIG.md +41 -0
  125. package/docs/OUTCOME-CODES.md +1 -0
  126. package/docs/STATS.md +17 -0
  127. package/package.json +1 -1
  128. package/pool/image/Dockerfile +14 -2
  129. package/pool/image/manifest.json +25 -0
  130. package/pool/image/mirror.sh +11 -2
  131. package/pool/install/install-agent.ps1 +11 -4
  132. package/scripts/ci-local/adapters/github-actions.mjs +8 -0
  133. package/scripts/ci-local/cli.mjs +1 -1
  134. package/scripts/ci-local/plan.mjs +3 -2
  135. package/scripts/ci-local.test.sh +11 -0
  136. package/scripts/failure-census.mjs +67 -0
  137. package/scripts/review-finalize.sh +5 -5
  138. package/scripts/review-finalize.test.sh +8 -1
  139. package/scripts/verify-phase-trail.sh +11 -0
  140. package/scripts/verify-phase-trail.test.sh +9 -0
@@ -11,7 +11,7 @@
11
11
  */
12
12
  import { builtinModules } from "node:module";
13
13
  import { existsSync } from "node:fs";
14
- import { join, dirname, delimiter, relative } from "node:path";
14
+ import { join, dirname, delimiter, posix } from "node:path";
15
15
  import { missingTool } from "./conformance.mjs";
16
16
 
17
17
  export const PREFLIGHT_CAP = 20;
@@ -159,12 +159,32 @@ export function testRunnerProblems(contract, runners) {
159
159
  return out;
160
160
  }
161
161
 
162
+ /**
163
+ * #5749: validate/repro commands that cannot run in a lane sandbox whatever is installed: a host-only wrapper or path
164
+ * (`legion-run`, `ssh <host>`, `/home/<user>/...`) or an unbounded CPU busy loop (`while :`/`while true` with no sleep or
165
+ * read, `yes > /dev/null`, `seq $(nproc)` fan-out). One problem per command id. Pure.
166
+ */
167
+ export function hostOnlyProblems(contract) {
168
+ const out = [];
169
+ for (const v of contractCommands(contract)) {
170
+ const cmd = v.command, why = [];
171
+ const exes = shellSegments(cmd).map((seg) => { let i = 0; while (i < seg.length && (/^[A-Za-z_]\w*=/.test(seg[i]) || ["!", "time", "exec", "command", "env"].includes(seg[i]))) i++; return seg[i]; });
172
+ if (cmd.split(/[\s'"`(;&|]+/).includes("legion-run") || exes.includes("legion-run")) why.push("the host-only wrapper `legion-run`");
173
+ if (exes.includes("ssh")) why.push("`ssh <host>`");
174
+ if (/(^|[\s='"`:(])\/home\/[\w.-]+\//.test(cmd)) why.push("an absolute `/home/<user>/` path");
175
+ if (/\bwhile\s+(:|true)\s*;\s*do\s*(:\s*;\s*)?done\b/.test(cmd) || /\byes\b[^|;&]*>\s*\/dev\/null/.test(cmd) || /\bseq\s+\$\(\s*nproc\s*\)/.test(cmd)) why.push("an unbounded CPU busy loop");
176
+ if (why.length) out.push(`${v.id}: uses ${why.join(" and ")}, which no lane sandbox provides or tolerates, so the command cannot run as written; use a bounded check through the repo's own toolchain, not a host wrapper, host path or CPU stress loop`);
177
+ }
178
+ return out;
179
+ }
180
+
162
181
  const FIX_HOW = "run the check through the repo's own toolchain (its virtualenv, lockfile-pinned runner or package scripts) or use a check that does not need it, never a global install";
163
182
  /** One contract problem per miss: names the validate ids and the tool (or path, or env var), and how to fix the plan (never a global install). */
164
183
  export function preflightProblems(misses) {
165
184
  return (misses ?? []).map((m) => {
166
185
  const ids = m.ids.join(", ");
167
186
  if (m.kind === "env-var") return `${ids}: uses $${m.tool}, which is unset or empty in the lane environment, so the validate command cannot run as written; set it inside the command or ${FIX_HOW}`;
187
+ if (m.source === "collect") return `${ids}: importing its test modules on the base worktree (pytest --collect-only) failed: needs Python module '${m.tool}'${m.line ? ` (\`${m.line}\`)` : ""}, so the command does not run in the environment that has the test's dependencies; run it the way the repo's CI runs that test path (its working-directory and poetry run / uv run) or ${FIX_HOW}`; // #5753
168
188
  if (m.source === "run") return `${ids}: running it on the base worktree stopped before any test ran: needs ${KIND_NAME[m.kind] ?? m.kind} '${m.tool}'${m.line ? ` (\`${m.line}\`)` : ""}, so the validate command cannot run here; ${m.kind === "path" ? "point it at a path the repo or a deliverable has, or " : ""}${FIX_HOW}`;
169
189
  return `${ids}: needs ${KIND_NAME[m.kind] ?? m.kind} '${m.tool}'${m.interp ? ` (for ${m.interp})` : ""}, which this host lacks, so the validate command cannot run here; ${FIX_HOW}`;
170
190
  });
@@ -326,12 +346,81 @@ export function testRunSummary({ contract, failures = [], repro = null } = {}) {
326
346
  return { declared: ids.length, ran: ids.length - skipped.length, redGreen, skipped };
327
347
  }
328
348
 
329
- /** #5447: tool names the contract's test plan declares in `env` (per row of the #5445 `test_plan` array, or `test_plan.env`); strings, comma lists or {tool}; [] when absent. Pure. */
330
- export function declaredEnv(contract) {
349
+ /**
350
+ * #5447: tool names the contract's test plan declares in `env` (per row of the #5445 `test_plan` array, or `test_plan.env`);
351
+ * strings, comma lists or {tool}; [] when absent. #5753: a directory the repo tracks (`files`: tracked paths, e.g. `shared`)
352
+ * is never a host tool. Pure.
353
+ */
354
+ export function declaredEnv(contract, files = []) {
331
355
  const plan = contract?.test_plan;
332
356
  const raw = Array.isArray(plan) ? plan.map((r) => r?.env) : [plan?.env];
333
357
  const names = raw.flatMap((e) => (Array.isArray(e) ? e : typeof e === "string" ? e.split(",") : [])).map((e) => String(typeof e === "string" ? e : e?.tool ?? "").trim());
334
- return [...new Set(names.filter((t) => /^[\w.+-]+$/.test(t) && isExecutableName(t)))];
358
+ const dirs = trackedDirs(files);
359
+ return [...new Set(names.filter((t) => /^[\w.+-]+$/.test(t) && isExecutableName(t) && !dirs.has(t)))];
360
+ }
361
+ /** #5753: every directory name a tracked path runs through (`shared/detection/x.py` -> shared, detection). */
362
+ function trackedDirs(files) {
363
+ const out = new Set();
364
+ for (const f of Array.isArray(files) ? files : []) for (const seg of String(f).split("/").slice(0, -1)) if (seg) out.add(seg);
365
+ return out;
366
+ }
367
+
368
+ /** The prefix of one command segment up to its pytest invocation (bare, path/.venv, `python[3[.x]] -m pytest`, after
369
+ * `poetry|uv [flags] run [flags]` and env assignments), or null. A linear token scan: no backtracking (CodeQL js/redos). */
370
+ function pytestPrefix(segment) {
371
+ const toks = [...String(segment).matchAll(/\S+/g)].map((m) => ({ t: m[0], end: m.index + m[0].length }));
372
+ let i = 0;
373
+ while (i < toks.length && /^[A-Za-z_]\w*=/.test(toks[i].t)) i++;
374
+ const base = (t) => t.split("/").pop();
375
+ const isPy = (t) => /^python3?(?:\.\d+)?$/.test(base(t));
376
+ const isPytest = (t) => base(t) === "pytest";
377
+ if (i < toks.length && (toks[i].t === "poetry" || toks[i].t === "uv")) {
378
+ i++;
379
+ while (i < toks.length && toks[i].t.startsWith("-")) i++;
380
+ if (toks[i]?.t !== "run") return null;
381
+ i++;
382
+ while (i < toks.length && toks[i].t.startsWith("-")) {
383
+ const flag = toks[i].t; i++;
384
+ const next = toks[i]?.t;
385
+ if (!flag.includes("=") && next && !next.startsWith("-") && !isPy(next) && !isPytest(next) && toks[i + 1]) i++;
386
+ }
387
+ }
388
+ const t = toks[i]?.t;
389
+ if (!t) return null;
390
+ if (isPytest(t)) return segment.slice(0, toks[i].end);
391
+ if (isPy(t) && toks[i + 1]?.t === "-m" && toks[i + 2]?.t === "pytest") return segment.slice(0, toks[i + 2].end);
392
+ return null;
393
+ }
394
+ /**
395
+ * #5753: the contract command with `--collect-only -q` after its first pytest invocation (bare, `.venv/bin/python -m`,
396
+ * `poetry run`, `uv run`): one cheap run imports the test modules, so an import error shows at freeze, not in the builder.
397
+ * null when the command runs no pytest. Pure.
398
+ */
399
+ export function collectOnlyCommand(command) {
400
+ const parts = String(command ?? "").split(/(&&|\|\||;|\||\n)/);
401
+ for (let i = 0; i < parts.length; i += 2) {
402
+ const pre = pytestPrefix(parts[i]);
403
+ if (pre === null) continue;
404
+ if (/(?:^|\s)--collect-only\b/.test(parts[i])) return null;
405
+ parts[i] = `${pre} --collect-only -q${parts[i].slice(pre.length)}`;
406
+ return parts.slice(0, i + 1).join(""); // later segments (`| tail`, `&& echo`) would hide the collect exit
407
+ }
408
+ return null;
409
+ }
410
+ const COLLECT_IMPORT_RE = /(?:ModuleNotFoundError|ImportError): No module named '?([\w.]+)'?/;
411
+ /**
412
+ * #5753: why a collect-only run (collectOnlyCommand) shows the test module cannot import on this host: a module the repo does
413
+ * not track (`repoHas`) is {tool, kind: "python-module", line}. A passing or empty collection, a timeout, an import of a name
414
+ * the change adds (`cannot import name`) and a repo-owned module are no miss (RED on base is expected). Pure.
415
+ */
416
+ export function collectImportMiss(r, { repoHas = () => false } = {}) {
417
+ const rc = r?.rc, out = String(r?.output ?? "");
418
+ if (!Number.isInteger(rc) || rc === 0 || rc === 5 || rc === TIMEOUT_RC) return null;
419
+ const m = COLLECT_IMPORT_RE.exec(out);
420
+ if (!m) return null;
421
+ const tool = m[1].split(".")[0];
422
+ if (!tool || repoHas(tool) || repoHas(m[1])) return null;
423
+ return { tool, kind: "python-module", line: (out.split("\n").find((l) => l.includes(m[0])) ?? "").trim().slice(0, 160) };
335
424
  }
336
425
 
337
426
  /** #5590: pytest's built-in fixtures, never host executables. */
@@ -390,15 +479,15 @@ export function manifestDepOwner(name, files = [], readFile = () => "") {
390
479
  const parts = String(f).split("/"), base = parts[parts.length - 1];
391
480
  if (parts.includes("node_modules") || !(base === "package.json" || base === "pyproject.toml" || /^requirements[\w.-]*\.txt$/.test(base))) continue;
392
481
  let text = ""; try { text = String(readFile(f) ?? ""); } catch { continue; }
393
- if (manifestDeclares(base.startsWith("requirements") ? "requirements.txt" : base, text, name)) return dirname(f);
482
+ if (manifestDeclares(base.startsWith("requirements") ? "requirements.txt" : base, text, name)) return posix.dirname(f);
394
483
  }
395
484
  return null;
396
485
  }
397
486
 
398
487
  /** nearest ancestor dir (of `dir`, up to the root ".") holding a tracked Python manifest, or null. */
399
488
  function nearestPyProject(dir, files) {
400
- const have = new Set(files.filter((f) => PY_MANIFESTS.has(String(f).split("/").pop()) || /(^|\/)requirements[\w.-]*\.txt$/.test(f)).map((f) => dirname(f)));
401
- for (let d = dir; ; d = dirname(d)) { if (have.has(d)) return d; if (d === "." || d === "/") return null; }
489
+ const have = new Set(files.filter((f) => PY_MANIFESTS.has(String(f).split("/").pop()) || /(^|\/)requirements[\w.-]*\.txt$/.test(f)).map((f) => posix.dirname(f)));
490
+ for (let d = dir; ; d = posix.dirname(d)) { if (have.has(d)) return d; if (d === "." || d === "/") return null; }
402
491
  }
403
492
  const PYTEST_SEG = /^(\s*(?:[A-Za-z_]\w*=\S*\s+)*)(?:python3?(?:\.\d+)?\s+-m\s+pytest|pytest)\b/;
404
493
  /**
@@ -412,17 +501,17 @@ export function venvPythonRewrite(command, files = [], exists = () => false) {
412
501
  const out = parts.map((seg, i) => {
413
502
  if (i % 2) return seg;
414
503
  const cd = /^\s*cd\s+(?:"([^"]+)"|'([^']+)'|(\S+))\s*$/.exec(seg);
415
- if (cd) { const t = (cd[1] ?? cd[2] ?? cd[3]).replace(/^\.\//, "").replace(/\/+$/, ""); cwd = t.startsWith("/") || t.startsWith("$") || t.startsWith("..") ? "?" : join(cwd === "?" ? "." : cwd, t) || "."; return seg; }
504
+ if (cd) { const t = (cd[1] ?? cd[2] ?? cd[3]).replace(/^\.\//, "").replace(/\/+$/, ""); cwd = t.startsWith("/") || t.startsWith("$") || t.startsWith("..") ? "?" : posix.join(cwd === "?" ? "." : cwd, t) || "."; return seg; }
416
505
  const m = PYTEST_SEG.exec(seg);
417
506
  if (!m || cwd === "?") return seg;
418
507
  const rest = seg.slice(m[0].length);
419
508
  const tp = rest.split(/\s+/).map((x) => x.replace(/::.*$/, "").replace(/^\.\//, "")).find((x) => x && !x.startsWith("-") && /[\w-]\/|\.py$/.test(x) && !x.startsWith("/"));
420
- const origin = cwd !== "." ? cwd : tp ? dirname(tp) : ".";
509
+ const origin = cwd !== "." ? cwd : tp ? posix.dirname(tp) : ".";
421
510
  const proj = nearestPyProject(origin, files);
422
511
  if (proj === null) return seg;
423
- const venv = join(proj, ".venv/bin/python");
512
+ const venv = posix.join(proj, ".venv/bin/python");
424
513
  if (!exists(venv)) return seg;
425
- const rel = cwd === "." ? venv : relative(cwd, venv);
514
+ const rel = cwd === "." ? venv : posix.relative(cwd, venv);
426
515
  changed = true;
427
516
  return `${m[1]}${rel} -m pytest${rest}`;
428
517
  });
@@ -3,8 +3,8 @@
3
3
  import { describe, it } from "node:test";
4
4
  import assert from "node:assert/strict";
5
5
  import { mkdirSync, writeFileSync } from "node:fs";
6
- import { join } from "node:path";
7
- import { manifestDepOwner, venvPythonRewrite, testRunnerProblems, shellSegments, pythonImports, nodeImports, preflightProbes, preflightProblems, runProbeMiss, unsetEnvVars, runPreflight, knownToContract, contractCommands, depInstallFailures, toolMissingInstalls, testRunSummary, projectBinDirs, withLocalBins } from "./preflight.mjs";
6
+ import { join, delimiter } from "node:path";
7
+ import { manifestDepOwner, venvPythonRewrite, testRunnerProblems, shellSegments, pythonImports, nodeImports, preflightProbes, preflightProblems, runProbeMiss, unsetEnvVars, runPreflight, knownToContract, contractCommands, depInstallFailures, toolMissingInstalls, testRunSummary, projectBinDirs, withLocalBins, collectOnlyCommand, collectImportMiss, declaredEnv } from "./preflight.mjs";
8
8
  import { runCheckCommand } from "./effects.mjs";
9
9
  import { repoTracks } from "./conformance.mjs";
10
10
  import { tmpDir } from "../tests/_tmp.mjs";
@@ -54,7 +54,7 @@ describe("#4328 validate preflight: what a command needs", () => {
54
54
  assert.equal(rc["command:node"], 0); assert.equal(rc["node-module:here"], 0, "found in an ancestor node_modules");
55
55
  assert.notEqual(rc["node-module:absent-pkg-4328"], 0);
56
56
  const py = preflightProbes(C(`python3 -c "import json, no_such_mod_4328"`)).probes.filter((p) => p.kind === "python-module");
57
- if ((await runCheckCommand({ command: "command -v python3", cwd: dir })).rc === 0) {
57
+ if ((await runCheckCommand({ command: "python3 -c pass", cwd: dir })).rc === 0) { // #5753: a Windows Store python3 stub is on PATH but runs nothing
58
58
  assert.deepEqual(await Promise.all(py.map(async (p) => (await runCheckCommand({ command: p.probe, cwd: dir })).rc !== 0)), [false, true]);
59
59
  }
60
60
  });
@@ -209,7 +209,7 @@ describe("project-local executables (#5592 3d/9)", () => {
209
209
  assert.equal((await runCheckCommand({ command: probes[0].probe, cwd: wt, env: { PATH: withLocalBins(base, local) } })).rc, 0);
210
210
  });
211
211
  it("local bins go after the lane PATH, never ahead, and are not duplicated", () => {
212
- assert.equal(withLocalBins("/a:/b", ["/c", "/a"]), "/a:/b:/c");
212
+ assert.equal(withLocalBins(["/a", "/b"].join(delimiter), ["/c", "/a"]), ["/a", "/b", "/c"].join(delimiter)); // #5753: the host PATH delimiter (; on Windows)
213
213
  });
214
214
  });
215
215
 
@@ -241,3 +241,43 @@ describe("#5683 sub-project manifest deps and venv python", () => {
241
241
  assert.equal(venvPythonRewrite("cd web && pytest", files, exists), "cd web && pytest");
242
242
  });
243
243
  });
244
+
245
+ describe("#5749 host-only and busy-loop validates", () => {
246
+ const V = (...commands) => ({ deliverables: [], validate: commands.map((command, i) => ({ id: `V${i + 1}`, command })) });
247
+ it("#5749 hostOnlyProblems rejects host-only and busy-loop validates", async () => {
248
+ const { hostOnlyProblems } = await import("./preflight.mjs");
249
+ const bad = [`legion-run bash -lc 'for i in $(seq $(nproc)); do (timeout 300 sh -c "while :; do :; done") & done; npx vitest run'`, "ssh build-host make test", "bash /home/u/x/check.sh", "yes > /dev/null & npx vitest run"];
250
+ for (const c of bad) assert.equal(hostOnlyProblems(V(c)).length, 1, c);
251
+ assert.match(hostOnlyProblems(V(bad[0]))[0], /^V1: /);
252
+ assert.deepEqual(hostOnlyProblems(V("npx vitest run", "python -m pytest tests/x.py", "while read l; do echo $l; done < f", "git diff origin/staging...HEAD --stat")), []);
253
+ assert.equal(hostOnlyProblems({ ...V("npx vitest run"), repro_test: { path: "t.py", id: "t", command: "ssh h pytest t.py" } }).length, 1);
254
+ });
255
+ it("#5749 repro_test python -m pytest is probed at freeze", () => {
256
+ const c = { ...V("npx vitest run"), repro_test: { path: "tests/x.py", id: "t", command: "python -m pytest tests/x.py::t" } };
257
+ const got = preflightProbes(c).probes.map((p) => [p.kind, p.tool, p.ids.join(",")]);
258
+ assert.deepEqual(got.filter((x) => x[2] === "repro_test"), [["command", "python", "repro_test"], ["python-module", "pytest", "repro_test"]]);
259
+ });
260
+ });
261
+
262
+ describe("#5753 collect-only import preflight and tracked-dir env names", () => {
263
+ it("collectOnlyCommand adds --collect-only -q after the pytest invocation, dropping later segments", () => {
264
+ assert.equal(collectOnlyCommand("cd services/worker && poetry run pytest ../../shared/t.py -x"), "cd services/worker && poetry run pytest --collect-only -q ../../shared/t.py -x");
265
+ assert.equal(collectOnlyCommand("python3 -m pytest -q tests/t.py | tail -5"), "python3 -m pytest --collect-only -q -q tests/t.py ");
266
+ assert.equal(collectOnlyCommand(".venv/bin/python -m pytest t.py"), ".venv/bin/python -m pytest --collect-only -q t.py");
267
+ assert.equal(collectOnlyCommand("uv run --frozen pytest"), "uv run --frozen pytest --collect-only -q");
268
+ assert.equal(collectOnlyCommand("node --test x.test.mjs"), null);
269
+ });
270
+ it("a collect-only ModuleNotFoundError of a module the repo does not track is a miss; RED-on-base shapes are not", () => {
271
+ const out = "ImportError while importing test module '/w/shared/detection/test_x.py'.\nE ModuleNotFoundError: No module named 'html2text'\n";
272
+ assert.deepEqual(collectImportMiss({ rc: 2, output: out }), { tool: "html2text", kind: "python-module", line: "E ModuleNotFoundError: No module named 'html2text'" });
273
+ assert.equal(collectImportMiss({ rc: 2, output: out }, { repoHas: (n) => n === "html2text" }), null, "a repo-owned module is the change's");
274
+ assert.equal(collectImportMiss({ rc: 2, output: "ImportError: cannot import name 'new_fn' from 'shared.x'" }), null, "a name the change adds");
275
+ assert.equal(collectImportMiss({ rc: 0, output: out }), null);
276
+ assert.equal(collectImportMiss({ rc: 5, output: "no tests ran" }), null);
277
+ });
278
+ it("a tracked repo directory name (shared) in declared env is never a host tool", () => {
279
+ const c = { test_plan: [{ requirement: "R1", env: ["shared", "pytest"] }] };
280
+ assert.deepEqual(declaredEnv(c, ["shared/detection/test_x.py", "services/worker/pyproject.toml"]), ["pytest"]);
281
+ assert.deepEqual(declaredEnv(c), ["shared", "pytest"], "without tracked paths the name is unchanged");
282
+ });
283
+ });
@@ -322,15 +322,7 @@ export function buildOpeningNote({ paths = [], tests = [], packFiles = [] } = {}
322
322
  /** #4857: validate-command rules for the plan prompt (the implement session resumes it), kept out of the shared templates (their token caps are guarded). */
323
323
  export function unrunnableValidateNote(testRunners = null) {
324
324
  const map = testRunners && typeof testRunners === "object" ? Object.entries(testRunners).map(([k, v]) => `${k}/ -> ${v}`).join("; ") : "";
325
- return `\n\nValidate and repro commands must pass bash -n (no prose notes), select tests that exist, and run from the right cwd (never combine \`poetry -C <dir>\` or \`uv run --project <dir>\` with repo-root-relative paths: use \`cd <dir> && poetry run pytest <dir-relative paths>\`)${map ? ` (forge.yaml verification.test_runners: ${map})` : ""}. An unrunnable validate (missing tool, wrong cwd, no tests selected) is never a block or "human" product-decision: run an equivalent through the repo's toolchain and record {"kind":"substitute-validate","validate":"V#","command":"<runnable equivalent>","why":""} in ${RESULT_FILE} amendments. A post-deploy requirement needs a registered check id; one that is a manual or production-credential action with no runnable check is disposition "defer" with bucket "owner:<action>" only when it needs credentials, spend, an account, a third party or a customer; read-only prod data is "host". forge.yaml validate.recipes rewrite matching commands at freeze, and the engine rewrites an unrunnable command from the repo's CI-derived command catalogue: prefer the repo's own CI test commands over free-form paths. A substitute that runs the same test ids with the same result is recorded, not failed. A criterion only time or production can show (a 14-day metric, a corpus re-run, a published scorecard) is post-deploy or defer with a bucket: never narrow it into something the lane can observe.`;
326
- }
327
-
328
- /** #5419: the R-docs rule for the planner; "" when forge.yaml docs.required_for is unset. */
329
- export function docsPlanNote(cfg) {
330
- if (!cfg?.required_for?.length) return "";
331
- const where = cfg.paths?.length ? ` under ${cfg.paths.join(", ")}` : "";
332
- const reg = cfg.registries?.length ? ` and their registration (${cfg.registries.join(", ")})` : "";
333
- return `\n\nThis repo requires user docs for user-facing surfaces (${cfg.required_for.join(", ")}). When the issue adds or changes one (a public API endpoint, MCP tool, dashboard page or feature, CLI command or SDK method), ${CONTRACT_FILE} must carry a requirement R-docs and a deliverable for each docs page${where} to create or update${reg}. A \`/docs/...\` link the change adds must resolve to a page. If no docs apply, say why in the result file as docs: [{"surface":"<kind>","justification":"<why>"}].`;
325
+ return `\n\nValidate and repro commands must pass bash -n (no prose notes), select tests that exist, and run from the right cwd (never combine \`poetry -C <dir>\` or \`uv run --project <dir>\` with repo-root-relative paths: use \`cd <dir> && poetry run pytest <dir-relative paths>\`)${map ? ` (forge.yaml verification.test_runners: ${map})` : ""}. An unrunnable validate (missing tool, wrong cwd, no tests selected) is never a block or "human" product-decision: run an equivalent through the repo's toolchain and report its real result in ${RESULT_FILE}. A post-deploy requirement needs a registered check id; one that is a manual or production-credential action with no runnable check is disposition "defer" with bucket "owner:<action>" only when it needs credentials, spend, an account, a third party or a customer; read-only prod data is "host". forge.yaml validate.recipes rewrite matching commands at freeze, and the engine rewrites an unrunnable command from the repo's CI-derived command catalogue: prefer the repo's own CI test commands over free-form paths. A criterion only time or production can show (a 14-day metric, a corpus re-run, a published scorecard) is post-deploy or defer with a bucket: never narrow it into something the lane can observe.`;
334
326
  }
335
327
 
336
328
  /** #5428: the page_gate rule for the planner; "" when forge.yaml pages is off. */
@@ -426,17 +418,18 @@ export function contractCorrectionPrompt(problems) {
426
418
  return `Your ${CONTRACT_FILE} is not valid:\n${problems.slice(0, 20).map((p) => `- ${p}`).join("\n")}\n\nFix the contract (planning only, no code, no commit) and stop. Do not push or touch GitHub.`;
427
419
  }
428
420
 
429
- /** #5089: the builder's amendments name an unknown kind or miss a field; one correction before the conformance gate. */
430
- export function amendmentCorrectionPrompt(problems) {
431
- return `The amendments in ${RESULT_FILE} are not valid:\n${problems.slice(0, 20).map((p) => `- ${p}`).join("\n")}\n\nRewrite them with a valid kind (${AMEND_KINDS.join(", ")}). A validate-row id (G2) is never a supersedes guard: use {"kind":"substitute-validate","validate":"G2","command":"<runnable equivalent>","why":""}. A deliverable that is impossible on this platform is {"kind":"defer","requirement":"R#","why":""}, not a changed deliverable. Edit only ${RESULT_FILE} (commit nothing else) and stop. Do not push or touch GitHub.`;
432
- }
433
-
434
421
  /** The one bounded correction round, in the builder's own session. */
435
422
  export function conformanceResumePrompt(failures, mode = "local", lane = "") {
436
423
  const baseMoved = lane && failures.some((f) => f?.kind === "validate_failed")
437
424
  ? `\n\nIf a validate command fails only because origin/${lane} moved on after this branch started (the change itself is fine), bring the branch up to date with \`git merge --no-edit origin/${lane}\` (already fetched; never rebase or force), resolve any conflicts, then re-run every validate command and record the results.`
438
425
  : "";
439
- return `The change does not conform to the frozen contract and the issue:\n${failures.slice(0, 30).map((f) => `- ${f.code}: ${String(f.detail).slice(0, 900)}`).join("\n")}${baseMoved}\n\nFix each item in the code, or record a typed amendment with a why in ${RESULT_FILE}. ${rerun(mode)}, commit, and update ${IMPLEMENTATION_FILE} and ${RESULT_FILE}. Do not push or touch GitHub.`;
426
+ // #6058: a requirement with no status row was skipped, not failed: name each id with its quote and ask for the work and a row
427
+ const skipped = failures.filter((f) => f?.kind === "requirement_no_status" && f.reqId);
428
+ const rest = skipped.length ? failures.filter((f) => !skipped.includes(f)) : failures;
429
+ const targeted = skipped.length
430
+ ? `You skipped ${skipped.length === 1 ? "a requirement" : `${skipped.length} requirements`}: ${RESULT_FILE} has no status row for ${skipped.map((f) => f.reqId).join(", ")}, so ${skipped.length === 1 ? "it was" : "they were"} not addressed at all:\n${skipped.map((f) => `- ${f.reqId}: "${String(f.quote ?? "").slice(0, 400)}"`).join("\n")}\n\nFor each one, implement it now (a file it needs that no deliverable names is an \`add-deliverable\` amendment), then add its row {"id","status","evidence"} to the requirements array of ${RESULT_FILE}, keeping the rows already there.${rest.length ? "\n\nAlso:\n" : ""}`
431
+ : "The change does not conform to the frozen contract and the issue:\n";
432
+ return `${targeted}${rest.slice(0, 30).map((f) => `- ${f.code}: ${String(f.detail).slice(0, 900)}`).join("\n")}${baseMoved}\n\nFix each item in the code, or record a typed amendment with a why in ${RESULT_FILE}. ${rerun(mode)}, commit, and update ${IMPLEMENTATION_FILE} and ${RESULT_FILE}. Do not push or touch GitHub.`;
440
433
  }
441
434
 
442
435
  /** forge#4159: the one resume for package.json edges between workspace packages the contract does not name. */
@@ -444,11 +437,6 @@ export function structurePrompt(edges, mode = "local") {
444
437
  return `This change adds dependencies between workspace packages that the frozen contract does not name:\n${edges.slice(0, 30).map((e) => `- ${e.from} -> ${e.to} (${e.kind}, ${e.manifest})`).join("\n")}\n\nFor each one, add it to the contract with a reason, or remove it: either record {"kind":"add-deliverable","path":"<that package.json>","why":"<names the package and why this dependency is right>"} in ${RESULT_FILE}, or drop the dependency from the package.json and the code that needs it. ${rerun(mode)}, commit, and update ${IMPLEMENTATION_FILE} and ${RESULT_FILE}. Do not push or touch GitHub.`;
445
438
  }
446
439
 
447
- /** The repo's devdocs freshness rule failed on the committed change: add a decision record (conflict-free) and commit. */
448
- export function docsPrompt(output, mode = "local") {
449
- return `The repository's docs freshness check (scripts/check-devdocs-freshness.sh) fails on this change:\n${String(output ?? "").slice(0, 4000)}\n\nAdd a new devdocs/decisions/<issue>-<slug>.md describing the behaviour you changed in a few lines (a new file never conflicts with parallel lanes; edit a shared dossier only when the check accepts nothing else). ${rerun(mode)}, commit, and update ${IMPLEMENTATION_FILE} and ${RESULT_FILE}. Do not push or touch GitHub.`;
450
- }
451
-
452
440
  /**
453
441
  * #4363: a fix round in a fresh session (no transcript). It carries the site's task prompt (which holds the capped
454
442
  * failure output), the lane diff, the frozen contract and the issue title and summary, each capped; under FIX_PROMPT_MAX.
@@ -520,6 +508,7 @@ You receive the GitHub issue with its comments, the frozen contract (requirement
520
508
  - issue_coverage: one row per requirement or acceptance criterion in the issue, quoted verbatim, saying whether the contract covers it, narrows it, or misses it. The skeleton lists the contract's quotes; add a row for any issue requirement the contract does not quote.
521
509
  - guidance: a guidance requirement (pre-filled covered / not-applicable) is a proposed change, non-binding: judge whether the outcome rows are met, never whether the proposal was followed. Set misclassified: true on its issue_coverage row only when the quote is really a symptom or success criterion. A deliver row with derived_outcome is judged against derived_outcome, like amendment.text.
522
510
  - amendment: a requirement with an \`amendment\` is judged against amendment.text and its why, not the quote; its issue_coverage row is covered when the amendment follows from its why. A requirement with \`amended_from\` was contracted defer or post-deploy and flipped to deliver: compare amended_from.quote and amended_from.why with amendment.text side by side, and mark the row partial when the rewording drops the original work or only trivially restates it. If it does not hold, mark the row partial with note "amendment: <what to change>".
511
+ - frozen defer/post-deploy rows: a requirement the contract froze as defer or post-deploy is a tracked follow-up, never an omission; do not mark its issue_coverage row narrowed or missing for that. An amendment that cites a frozen decision id (D#/K#) is judged against that decision's choice and justification.
523
512
  - requirements: one row per contract requirement id: implemented|partial|missing|deferred|post-deploy|not-applicable, with evidence as a backtick-quoted repo-relative path:line copied verbatim from the changed files, including (group), [slug] and [...slug] folders (e.g. \`apps/web/app/(console)/layout.tsx:12\`, not route.ts:12) and the validate id or test that proves it (validated_by). For a defer or post-deploy requirement add deferral_ok: true only if it is genuinely separate work or only checkable after a deploy, false if it belongs in this change, including an outcome criterion (a metric, rate or log expectation) this change could ship as a test, metric or alert, or a read-only production check possible now (bucket verify-now). For a verify out_of_band row (measured by the named job, not in this lane) set instrumented: true only when its budget test or bench is committed and that job is configured, with that path:line as evidence; false otherwise. Do not judge the measured result.
524
513
  - post-deploy requirements: deferral_ok is false when the requirement has no \`check\` id, or its check is neither in .forge/post-deploy-checks.json on the default branch nor added by this change (the commands run from that file only).
525
514
  - scope: one row per changed file, pre-filled with the engine's authorization: the deliverable id that authorizes it (deliverables may be directories or globs), "test", "incidental" (changelog, lockfile), or "none" with what it changes. Change it only if the diff shows the file does something its deliverable does not cover.
@@ -602,7 +591,7 @@ export function reproFlagNote(flag) {
602
591
 
603
592
  export function reviewerPrompt({ issue, comments = [], contract, result, files = [], diff, stat = "", base = "", structure = "", ignore = [`${LEAN_DIR}/`], skeleton = null, investigationVerdict = null, domains = [], relaxations = [], reproFlag = null }) {
604
593
  const notes = comments.map((c) => String(c?.body ?? "")).filter((b) => !/^<!-- FORGE:/.test(b.trim()));
605
- const decisions = comments.filter((c) => isDecision(c?.body) && isTrustedIssueComment(c)).map((c) => String(c.body)); // #4901: operator decisions bind the review; other FORGE: records stay out
594
+ const decisions = comments.filter((c) => isDecision(c?.body) && isTrustedIssueComment(c)).map((c) => `Binding operator decision (trusted; judge the rows against it, as the builder was told):\n${String(c.body)}`); // #4901/#6051: operator decisions bind the review and the builder alike; other FORGE: records stay out
606
595
  notes.push(...decisions);
607
596
  const sk = JSON.stringify(skeleton ?? reviewSkeleton(contract ?? {}, files, ignore), null, 1);
608
597
  return `Issue #${issue.number}: ${issue.title}\n\n<issue_body>\n${cap(issue.body ?? "", 20000)}\n</issue_body>\n\n<issue_comments>\n${cap(notes.join("\n---\n"), 8000)}\n</issue_comments>\n\n<contract>\n${cap(JSON.stringify(contract ?? {}, null, 1), 12000)}\n</contract>\n\n<builder_result>\n${cap(JSON.stringify(result ?? {}, null, 1), 6000)}\n</builder_result>\n\n${investigationVerdict ? `<investigation_verdict>${investigationVerdict}</investigation_verdict>\n${VERDICT_RULE}\n\n` : ""}<changed_files>\n${files.join("\n")}\n</changed_files>\n\n<rubric>\n${REVIEW_RUBRIC}\n</rubric>\n\n<row_skeleton>\n${cap(sk, 30000)}\n</row_skeleton>\n\n<diff>\n${boundDiff(diff, { stat, base })}\n</diff>${structure ? `\n<structure>${String(structure).replace(/[\r\n]+/g, " ")}</structure>` : ""}${domainChecksBlock(domains)}${relaxationBlock(relaxations)}${reproFlagNote(reproFlag)}`;
@@ -1,51 +1,23 @@
1
1
  // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  /**
4
- * #5751: recurrence routing. A new issue that matches at least `threshold` earlier merged fixes by symptom (subject recall
5
- * or an explicit `Recurs #n` link) AND by area (the fix touched a path the issue names) is a recurrence: the lane runs as a
6
- * design lane (no light lane, a stricter plan prompt, a contract `design` block) instead of adding a further fix.
7
- * Deterministic: zero LLM calls. The engine's inputs are subjectHistory rows (context.mjs) and the merged PRs' file lists.
4
+ * forge.yaml `recurrence.hot_areas` (#5751): areas where one lane at a time may work (branch lock), and `pathsOverlap`.
5
+ * The recurrence design routing (symptom/area detection, design lane, design block requirement) was cut in #6083: it had no
6
+ * measured catch and 15 parks on 11 issues in 25 days.
8
7
  */
9
- import { OUTCOME_CODES as C } from "../engine/outcome-codes.mjs";
10
- import { subjectHistory } from "./context.mjs";
11
-
12
- export const RECURRENCE_DEFAULTS = Object.freeze({ mode: "on", threshold: 2 });
13
- /** At most this many merged rows have their file lists read (one GitHub call each). */
14
- export const MAX_RECURRENCE_ROWS = 6;
15
-
16
8
  const clean = (p) => String(p ?? "").trim().replace(/^\.?\/+/, "").replace(/\/+$/, "");
17
9
  const list = (v) => (Array.isArray(v) ? v : typeof v === "string" ? v.split(",") : []).map((x) => String(x).trim()).filter(Boolean);
18
- const COUNTER_SEP = " -- "; // `pattern -- glob, glob`: the git grep pathspec separator
19
10
 
20
11
  /**
21
- * forge.yaml `recurrence:` (absent: the defaults, mode on). `hot_areas` is a list of {name, paths} or a block map
22
- * {name: "glob, glob"}; `counters` a list of {name, pattern, paths} or a block map {name: "pattern -- glob, glob"}.
23
- * @returns {{mode:"on"|"off", threshold:number, hotAreas:{name:string, paths:string[]}[], counters:{name:string, pattern:string, paths:string[]}[]}}
12
+ * forge.yaml `recurrence:`: `hot_areas` is a list of {name, paths} or a block map {name: "glob, glob"}.
13
+ * @returns {{hotAreas:{name:string, paths:string[]}[]}}
24
14
  */
25
15
  export function parseRecurrenceConfig(raw) {
26
16
  const r = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
27
- const m = String(r.mode ?? "").trim().toLowerCase();
28
- const mode = r.mode === false || m === "off" || m === "false" ? "off" : RECURRENCE_DEFAULTS.mode;
29
- const t = Number(r.threshold);
30
- const threshold = Number.isInteger(t) && t >= 1 ? t : RECURRENCE_DEFAULTS.threshold;
31
17
  const rows = (v) => (Array.isArray(v) ? v : v && typeof v === "object" ? Object.entries(v).map(([name, val]) => ({ name, val })) : []);
32
18
  const hotAreas = rows(r.hot_areas).map((x) => ({ name: String(x?.name ?? "").trim(), paths: list(x?.paths ?? x?.val).map(clean) }))
33
19
  .filter((a) => a.name && a.paths.length);
34
- const counters = rows(r.counters).map((x) => {
35
- if (x?.val !== undefined) {
36
- const s = String(x.val), i = s.lastIndexOf(COUNTER_SEP);
37
- return { name: String(x.name).trim(), pattern: (i >= 0 ? s.slice(0, i) : s).trim(), paths: i >= 0 ? list(s.slice(i + COUNTER_SEP.length)).map(clean) : [] };
38
- }
39
- return { name: String(x?.name ?? "").trim(), pattern: String(x?.pattern ?? "").trim(), paths: list(x?.paths).map(clean) };
40
- }).filter((c) => c.name && c.pattern);
41
- return { mode, threshold, hotAreas, counters };
42
- }
43
-
44
- /** Issue numbers named by `Recurs #n` (also `Recurs: #n`, `Recurs of #n`, `Recurs #n, #m`). */
45
- export function recursLinks(body = "") {
46
- const out = new Set();
47
- for (const m of String(body ?? "").matchAll(/\brecurs(?:\s+of)?\s*:?\s*((?:#\d+[\s,]*(?:and\s+)?)+)/gi)) for (const n of m[1].matchAll(/#(\d+)/g)) out.add(Number(n[1]));
48
- return [...out].filter((n) => Number.isSafeInteger(n) && n > 0);
20
+ return { hotAreas };
49
21
  }
50
22
 
51
23
  /** Two paths overlap when they are equal or one is a directory prefix of the other. */
@@ -53,117 +25,3 @@ export function pathsOverlap(a, b) {
53
25
  const x = clean(a), y = clean(b);
54
26
  return Boolean(x && y) && (x === y || x.startsWith(`${y}/`) || y.startsWith(`${x}/`));
55
27
  }
56
-
57
- /** #5979: backticked error/outcome-code/test signatures of the issue body (identifier-shaped, not a path). */
58
- function symptomTerms(body) {
59
- return [...new Set([...String(body ?? "").matchAll(/`([A-Za-z][\w.:-]{3,79})`/g)].map((m) => m[1].toLowerCase()).filter((t) => !/\.(?:m?[jt]sx?|md|json|ya?ml|py|sh)$/.test(t)))];
60
- }
61
-
62
- /** #5979: a subjectHistory row shares the issue's symptom: it matched on a code-shaped term (outcome code, error name, symbol), on two or more terms, or its title carries a backticked signature of the issue. */
63
- function symptomMatch(row, terms) {
64
- const m = (row?.matched ?? []).map(String);
65
- return m.some((t) => /[._:-]|\d|[a-z][A-Z]|^[A-Z0-9_]{3,}$/.test(t)) || m.length >= 2 || terms.some((t) => String(row?.title ?? "").toLowerCase().includes(t));
66
- }
67
-
68
- /**
69
- * Count earlier merged fixes on the same symptom and the same area. A subjectHistory row counts when it is a merged PR
70
- * whose files (`mergedPrFiles[number]`) overlap a path the issue names AND that shares the symptom (#5979: path-only overlap never counts). A `Recurs #n` link is an explicit symptom match:
71
- * it counts when its files overlap or are unknown (the author declared the same area). Rows without overlap never count.
72
- * @returns {{recurs:boolean, count:number, threshold:number, evidence:{number:number, title:string, via:string, paths:string[]}[], reason:string}}
73
- */
74
- export function detectRecurrence({ rows = [], mergedPrFiles = {}, body = "", namedPaths = [], threshold = RECURRENCE_DEFAULTS.threshold } = {}) {
75
- const named = [...new Set((namedPaths ?? []).map(clean).filter(Boolean))];
76
- const filesOf = (n) => (mergedPrFiles instanceof Map ? mergedPrFiles.get(n) : mergedPrFiles?.[n]);
77
- const evidence = [], seen = new Set();
78
- const sym = symptomTerms(body);
79
- for (const r of rows ?? []) {
80
- const n = Number(r?.number);
81
- if (!Number.isSafeInteger(n) || seen.has(n) || r?.kind !== "PR" || r?.status !== "merged") continue;
82
- if (!symptomMatch(r, sym)) continue; // #5979: path overlap alone is the same area, not the same symptom
83
- const paths = (filesOf(n) ?? []).map(clean).filter((f) => named.some((p) => pathsOverlap(f, p)));
84
- if (!paths.length) continue;
85
- seen.add(n);
86
- evidence.push({ number: n, title: String(r.title ?? ""), via: `subject (${(r.matched ?? []).join(", ")})`, paths: [...new Set(paths)] });
87
- }
88
- for (const n of recursLinks(body)) {
89
- if (seen.has(n)) continue;
90
- const files = filesOf(n);
91
- const paths = Array.isArray(files) ? files.map(clean).filter((f) => named.some((p) => pathsOverlap(f, p))) : null;
92
- if (paths && !paths.length) continue;
93
- seen.add(n);
94
- evidence.push({ number: n, title: "", via: "Recurs link", paths: paths ?? [] });
95
- }
96
- const t = Number.isInteger(threshold) && threshold >= 1 ? threshold : RECURRENCE_DEFAULTS.threshold;
97
- const count = evidence.length, recurs = count >= t;
98
- const reason = recurs
99
- ? `recurrence: ${count} earlier merged fix(es) on the same symptom and area (threshold ${t}): ${evidence.map((e) => `#${e.number}${e.paths.length ? ` (${e.paths.slice(0, 3).join(", ")})` : ""}`).join(", ")}`
100
- : "";
101
- return { recurs, count, threshold: t, evidence, reason };
102
- }
103
-
104
- /** #6016: a staging->default release PR head (`release/...`). */
105
- export const isReleaseHead = (ref) => /^release\//.test(String(ref ?? ""));
106
-
107
- /**
108
- * The engine-side gather: subjectHistory rows plus one file-list read per merged row (capped). `io`: {gh, git}. Never
109
- * throws: a failed source contributes nothing and lands in `errors`.
110
- */
111
- export async function recurrenceFacts({ io, repo, issue, title = "", body = "", base = null, namedPaths = [], threshold, exclude = [], createdAt = null }) {
112
- const errors = [];
113
- let rows = [];
114
- try { const h = await subjectHistory({ io, repo, issue, title, body, base, exclude }); rows = h.rows ?? []; errors.push(...(h.errors ?? [])); } catch (e) { errors.push(`recurrence: ${String(e?.message ?? e).slice(0, 80)}`); }
115
- // #6016: a release PR (head release/*) touches every shipped file, and a PR merged after the issue was filed cannot be an
116
- // earlier fix that did not hold: neither is evidence. A row whose metadata cannot be read stays (explicit Recurs links too).
117
- const created = Date.parse(createdAt ?? "");
118
- const notEvidence = new Set();
119
- for (const r of rows.filter((x) => x?.kind === "PR" && x?.status === "merged").slice(0, MAX_RECURRENCE_ROWS)) {
120
- try {
121
- const m = JSON.parse(String(await io.gh(["api", `repos/${repo}/pulls/${Number(r.number)}`, "--jq", "{head: .head.ref, merged: .merged_at}"])));
122
- if (isReleaseHead(m?.head) || (Number.isFinite(created) && Date.parse(m?.merged ?? "") > created)) notEvidence.add(Number(r.number));
123
- } catch { /* unreadable: keep the row */ }
124
- }
125
- rows = rows.filter((r) => !notEvidence.has(Number(r?.number)));
126
- const wanted = [...new Set([...rows.filter((r) => r?.kind === "PR" && r?.status === "merged").map((r) => Number(r.number)), ...recursLinks(body)])].slice(0, MAX_RECURRENCE_ROWS);
127
- const mergedPrFiles = {};
128
- if (namedPaths.length) {
129
- for (const n of wanted) {
130
- try {
131
- const out = String(await io.gh(["api", `repos/${repo}/pulls/${n}/files`, "--paginate", "--jq", ".[].filename"]));
132
- mergedPrFiles[n] = out.split("\n").map((x) => x.trim()).filter(Boolean);
133
- } catch { /* not a PR (an issue link) or unreadable: unknown files */ }
134
- }
135
- }
136
- return { ...detectRecurrence({ rows, mergedPrFiles, body, namedPaths, threshold }), errors };
137
- }
138
-
139
- /** The design lane's plan instruction (#5751): why the earlier fixes failed, delete or replace, a measurable outcome. */
140
- export function designLaneNote(detection) {
141
- if (!detection?.recurs) return "";
142
- const ev = detection.evidence.map((e) => `- #${e.number}${e.title ? ` ${e.title}` : ""} [${e.via}]${e.paths.length ? `: ${e.paths.join(", ")}` : ""}`).join("\n");
143
- return `\n\nDESIGN LANE (#5751): this issue recurs. ${detection.count} earlier merged fix(es) hit the same symptom in the same area:\n${ev}\nDo not add another patch on top of them. Read each earlier fix (gh pr view N, git show) as an active input, then put a "design" object in .forge-lean/contract.json:
144
- {"design":{"why_failed":"<why the earlier fixes did not hold, naming them>","disposition":"delete|replace|extend","outcome":{"metric":"<what is measured>","target":"<the value that shows it held>"}}}
145
- Prefer "delete" or "replace" of the earlier fixes; "extend" needs its reason in why_failed. The outcome needs a validate (test, counter or check) that measures it. When the redesign is too big for one lane, decompose it into ordinary lanes with the split-required block.`;
146
- }
147
-
148
- /** #5751: a design lane's contract must carry design {why_failed, disposition delete|replace|extend, outcome {metric, target}}. */
149
- export function designContractFailures(contract, detection) {
150
- if (!detection?.recurs) return [];
151
- // #5918/#5979: a design block is demanded once. Asked for on an earlier run and still absent, it is not demanded again: the repeat parks (failure.repeated) for a decision.
152
- if (detection.demanded) {
153
- const d0 = contract?.design;
154
- if (d0 && typeof d0 === "object" && !Array.isArray(d0)) return designContractFailures(contract, { ...detection, demanded: false });
155
- return [{ code: C.FAILURE_REPEATED, kind: "design_missing_repeated", detail: `recurring issue (${detection.count} earlier fixes): the design block was already demanded on an earlier run and is still missing; parked for a decision instead of demanding it again` }];
156
- }
157
- const d = contract?.design, problems = [];
158
- const s = (v) => typeof v === "string" && v.trim();
159
- if (!d || typeof d !== "object" || Array.isArray(d)) problems.push("no design block");
160
- else {
161
- if (!s(d.why_failed)) problems.push("design.why_failed is empty");
162
- if (!["delete", "replace", "extend"].includes(String(d.disposition ?? "").trim())) problems.push("design.disposition is not delete, replace or extend");
163
- if (!s(d.outcome?.metric) || !(s(d.outcome?.target) || Number.isFinite(d.outcome?.target))) problems.push("design.outcome needs a metric and a target");
164
- }
165
- return problems.length ? [{ code: C.RECURRENCE_DESIGN_MISSING, kind: "design_missing", detail: `recurring issue (${detection.count} earlier fixes) routed to a design lane: ${problems.join("; ")}` }] : [];
166
- }
167
-
168
- /** #5979: true when an earlier NEEDS_HUMAN/PARKED comment of the issue already reported the missing design block. */
169
- export const designDemanded = (comments) => (Array.isArray(comments) ? comments : []).some((c) => /<!--\s*FORGE:(?:NEEDS_HUMAN|PARKED)/.test(String(c?.body ?? "")) && /routed to a design lane:/.test(String(c?.body ?? "")));