forgedock 1.61.2 → 1.62.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 (131) hide show
  1. package/bin/config-schema.mjs +10 -1
  2. package/bin/engine/outcome-codes.mjs +4 -0
  3. package/bin/engine-cli.mjs +159 -17
  4. package/bin/env/env.mjs +6 -4
  5. package/bin/forge-home-check.mjs +91 -0
  6. package/bin/forgedock.mjs +50 -7
  7. package/bin/gc.mjs +2 -0
  8. package/bin/hooks/pre-tool-use.mjs +4 -0
  9. package/bin/journey.mjs +55 -5
  10. package/bin/lean/admission.mjs +16 -5
  11. package/bin/lean/batch-health.mjs +55 -16
  12. package/bin/lean/batch-health.test.mjs +67 -1
  13. package/bin/lean/batch.mjs +8 -0
  14. package/bin/lean/batch.test.mjs +5 -0
  15. package/bin/lean/ceiling.mjs +20 -0
  16. package/bin/lean/ceiling.test.mjs +33 -2
  17. package/bin/lean/ci-gate.mjs +240 -0
  18. package/bin/lean/ci-gate.test.mjs +227 -0
  19. package/bin/lean/ci-precheck.mjs +178 -0
  20. package/bin/lean/ci-precheck.test.mjs +149 -0
  21. package/bin/lean/conformance.mjs +85 -9
  22. package/bin/lean/conformance.test.mjs +155 -3
  23. package/bin/lean/context.test.mjs +7 -6
  24. package/bin/lean/dag.mjs +128 -0
  25. package/bin/lean/dag.test.mjs +131 -0
  26. package/bin/lean/decisions.mjs +5 -4
  27. package/bin/lean/decisions.test.mjs +11 -0
  28. package/bin/lean/delguard.mjs +84 -0
  29. package/bin/lean/delguard.test.mjs +104 -0
  30. package/bin/lean/depcache.mjs +125 -17
  31. package/bin/lean/depcache.test.mjs +111 -0
  32. package/bin/lean/design-gate.mjs +5 -5
  33. package/bin/lean/design-gate.test.mjs +14 -0
  34. package/bin/lean/effects.mjs +72 -4
  35. package/bin/lean/execution.mjs +41 -7
  36. package/bin/lean/execution.test.mjs +99 -3
  37. package/bin/lean/forgedock-lane-workflow.test.mjs +35 -0
  38. package/bin/lean/guardgate.mjs +30 -7
  39. package/bin/lean/guardgate.test.mjs +44 -1
  40. package/bin/lean/guards.test.mjs +1 -1
  41. package/bin/lean/heavy.test.mjs +87 -0
  42. package/bin/lean/hotarea.mjs +73 -0
  43. package/bin/lean/hotarea.test.mjs +73 -0
  44. package/bin/lean/issuewatch-reconcile.mjs +20 -1
  45. package/bin/lean/issuewatch-reconcile.test.mjs +30 -0
  46. package/bin/lean/lanecheck.mjs +27 -3
  47. package/bin/lean/lanecheck.test.mjs +47 -5
  48. package/bin/lean/laneconfine.mjs +83 -0
  49. package/bin/lean/laneconfine.test.mjs +113 -0
  50. package/bin/lean/lean.mjs +376 -79
  51. package/bin/lean/lean.test.mjs +710 -22
  52. package/bin/lean/live-reconcile.mjs +169 -0
  53. package/bin/lean/live-reconcile.test.mjs +176 -0
  54. package/bin/lean/orchestrate-envhold.test.mjs +245 -0
  55. package/bin/lean/orchestrate-hostfallback.test.mjs +39 -0
  56. package/bin/lean/orchestrate.mjs +207 -17
  57. package/bin/lean/outcomeevidence.mjs +104 -0
  58. package/bin/lean/outcomeevidence.test.mjs +78 -0
  59. package/bin/lean/page-capture.mjs +68 -0
  60. package/bin/lean/page-capture.test.mjs +44 -0
  61. package/bin/lean/pagegate.mjs +46 -7
  62. package/bin/lean/pagegate.test.mjs +66 -1
  63. package/bin/lean/postdeploy-check.mjs +18 -4
  64. package/bin/lean/postdeploy-check.test.mjs +32 -1
  65. package/bin/lean/prefilter.mjs +36 -4
  66. package/bin/lean/prefilter.test.mjs +31 -1
  67. package/bin/lean/preflight.mjs +22 -0
  68. package/bin/lean/preflight.test.mjs +19 -1
  69. package/bin/lean/probe.mjs +18 -0
  70. package/bin/lean/probe.test.mjs +40 -0
  71. package/bin/lean/prompts.mjs +40 -3
  72. package/bin/lean/recovery.test.mjs +20 -0
  73. package/bin/lean/recurrence.mjs +133 -0
  74. package/bin/lean/recurrence.test.mjs +99 -0
  75. package/bin/lean/release-config.mjs +2 -1
  76. package/bin/lean/release-config.test.mjs +18 -0
  77. package/bin/lean/release-control.mjs +4 -2
  78. package/bin/lean/release-control.test.mjs +15 -0
  79. package/bin/lean/release-merge-hold.mjs +65 -0
  80. package/bin/lean/release-merge-hold.test.mjs +69 -0
  81. package/bin/lean/release-review.mjs +26 -9
  82. package/bin/lean/release-review.test.mjs +53 -0
  83. package/bin/lean/release-status.mjs +3 -1
  84. package/bin/lean/release-status.test.mjs +11 -0
  85. package/bin/lean/release.test.mjs +26 -1
  86. package/bin/lean/render.mjs +8 -7
  87. package/bin/lean/routing.mjs +49 -0
  88. package/bin/lean/routing.test.mjs +54 -1
  89. package/bin/lean/run-issue-placement.test.mjs +30 -1
  90. package/bin/lean/sandbox-actions.mjs +121 -0
  91. package/bin/lean/sandbox-actions.test.mjs +94 -0
  92. package/bin/lean/sandbox-provider.contract.test.mjs +22 -1
  93. package/bin/lean/sandbox-remote.mjs +3 -1
  94. package/bin/lean/schedd-health.mjs +14 -2
  95. package/bin/lean/schedd-health.test.mjs +13 -0
  96. package/bin/lean/schedd.mjs +43 -17
  97. package/bin/lean/schedd.test.mjs +61 -1
  98. package/bin/lean/toolchain.mjs +16 -6
  99. package/bin/lean/toolplace.mjs +12 -0
  100. package/bin/lean/weakguard.mjs +105 -0
  101. package/bin/lean/weakguard.test.mjs +59 -0
  102. package/bin/lean/winspawn.mjs +61 -0
  103. package/bin/lean/winspawn.test.mjs +45 -0
  104. package/bin/lean/worktree.mjs +3 -1
  105. package/bin/lean/worktree.test.mjs +11 -0
  106. package/bin/pool/agent.mjs +210 -14
  107. package/bin/pool/cache-sweep.mjs +74 -0
  108. package/bin/pool/cli.mjs +11 -3
  109. package/bin/pool/docker.mjs +33 -2
  110. package/bin/pool/health.mjs +38 -0
  111. package/bin/pool/lane-tools.mjs +23 -4
  112. package/bin/pool/lane-tools.test.mjs +12 -1
  113. package/bin/pool/router.mjs +21 -3
  114. package/bin/runner.mjs +37 -0
  115. package/bin/splash-scene.mjs +356 -0
  116. package/bin/win-hide-children.mjs +114 -0
  117. package/commands/orchestrate.md +18 -27
  118. package/commands/review-pr-agents/infra.md +1 -0
  119. package/commands/review-pr-staging.md +2 -2
  120. package/docs/CONFIG.md +60 -3
  121. package/docs/OUTCOME-CODES.md +3 -0
  122. package/package.json +1 -1
  123. package/plugins/forgedock-splash/.claude-plugin/plugin.json +1 -1
  124. package/plugins/forgedock-splash/README.md +1 -1
  125. package/plugins/forgedock-splash/hooks/scene.ts +142 -8
  126. package/pool/README.md +6 -0
  127. package/pool/image/entrypoint.sh +1 -0
  128. package/scripts/check-spec-size.sh +3 -1
  129. package/scripts/gen-splash-scene.mjs +24 -0
  130. package/scripts/review-staging-pre.sh +8 -3
  131. package/scripts/review-staging-pre.test.sh +2 -0
@@ -0,0 +1,178 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #5820: the PR's required CI checks, run in the lane before the PR opens. No LLM, no new planner: the check set is
5
+ * `scripts/ci-local` `buildPlan` (workflow parsing, path filters, matrix, secrets/deploy deferral, change scoping) narrowed
6
+ * here to what the PR must pass:
7
+ * - Required: jobs whose name or id is a required status check on the lane base (`io.requiredChecks`: classic protection
8
+ * plus rulesets), plus the jobs a required aggregator job `needs`. No required check maps to a job (none configured,
9
+ * unreadable, or only non-workflow checks): the conservative fallback, the lint, typecheck and unit-test jobs.
10
+ * - Heavy jobs (e2e, visual/storybook, lighthouse, app builds, docker images) stay CI-only unless forge.yaml
11
+ * `lean.ci_precheck_include` names them; `lean.ci_precheck_exclude` always wins; at most `lean.ci_precheck_max_jobs`.
12
+ * - Each selected job is one pre-PR check command: `ci-local.sh run --plan <one-job plan>`, so the job runs with
13
+ * ci-local's env, services, result cache and machine-wide slots, inside the engine's precheck round (heavy slot, budget,
14
+ * per-command timeout). Exit 1 is a failure (the precheck fix round); exit 2, 124 or 127 is unrunnable (recorded with
15
+ * its reason, never a fix round, never blocking the PR).
16
+ * Pure apart from `writeFile`; lean.mjs owns every effect and the events (`CI_PRECHECK_PLAN`, `CI_PRECHECK_RESULT`).
17
+ */
18
+ import { fileURLToPath } from "node:url";
19
+
20
+ /** The ci-local entry the derived commands call (install root, never the lane worktree). */
21
+ export const CI_LOCAL_SH = fileURLToPath(new URL("../../scripts/ci-local.sh", import.meta.url));
22
+ /** Per-job plan files, under the lane's untracked tool state. */
23
+ export const CI_PRECHECK_DIR = ".forge-lean/ci-precheck";
24
+ export const DEFAULT_MAX_JOBS = 8;
25
+ /** ci-local adapters that read CI definitions (task runners, portability and extra_commands are not CI jobs). */
26
+ const CI_SOURCES = new Set(["github-actions", "gitlab-ci", "circleci", "azure-pipelines", "bitbucket", "buildkite"]);
27
+ /** Job kinds that stay CI-only by default (#5820), first match wins; `text` is id + name, `cmds` the job's step commands. */
28
+ const HEAVY = [
29
+ ["e2e", (t, c) => /\be2e\b|end[-_ ]to[-_ ]end|playwright|cypress|webdriver|selenium/i.test(`${t}\n${c}`)],
30
+ ["visual", (t, c) => /storybook|chromatic|\bvisual\b|percy|backstop|\bloki\b/i.test(`${t}\n${c}`)],
31
+ ["lighthouse", (t, c) => /lighthouse|\blhci\b/i.test(`${t}\n${c}`)],
32
+ ["docker", (t, c) => /\bdocker\b|\bimages?\b|\bcontainer\b/i.test(t) || /docker\s+(?:buildx\s+)?build\b|docker\s+compose\s+build\b|\bpodman\s+build\b/.test(c)],
33
+ ["build", (t, c) => /(?:^|[^a-z])(?:build|bundle|dist)(?:[^a-z]|$)/i.test(t) || /\b(?:next|vite|nuxt|astro|remix|webpack)\s+build\b|\bturbo\s+(?:run\s+)?build\b/.test(c)],
34
+ ];
35
+ const CHEAP = [
36
+ ["typecheck", /type-?check|\btsc\b|\bmypy\b|pyright|\btypes\b/i],
37
+ ["lint", /lint|eslint|ruff|prettier|\bformat|clippy|shellcheck|golangci|\bvet\b|stylelint|biome/i],
38
+ ["test", /test|vitest|jest|pytest|\bspec\b|mocha|\bbats\b/i],
39
+ ];
40
+ export const HEAVY_KINDS = HEAVY.map(([k]) => k);
41
+
42
+ const str = (v) => (v === undefined || v === null ? "" : String(v).trim());
43
+ /** A forge.yaml list value: a block list (array), a flow list `[a, b]` or a comma-separated string. */
44
+ const list = (v) => (Array.isArray(v) ? v : str(v).replace(/^\[|\]$/g, "").split(",")).map((x) => str(x).replace(/^(["'])(.*)\1$/, "$2")).filter(Boolean);
45
+ const q = (s) => `'${String(s).replace(/'/g, "'\\''")}'`;
46
+ const globRe = (g) => new RegExp(`^${String(g).replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".")}$`, "i");
47
+
48
+ /**
49
+ * forge.yaml `lean:` (one-level, flat keys) -> {mode, include, exclude, maxJobs}. `ci_precheck: off` turns it off;
50
+ * include/exclude entries are a heavy kind (`e2e`, `visual`, `lighthouse`, `docker`, `build`), a job id (`gha:ci:lint`) or
51
+ * a job name, `*` globs allowed.
52
+ */
53
+ export function parseCiPrecheckConfig(sec) {
54
+ const s = sec && typeof sec === "object" ? sec : {};
55
+ const mode = /^(off|false|no|0)$/i.test(str(s.ci_precheck)) ? "off" : "on";
56
+ const raw = str(s.ci_precheck_max_jobs), n = Number(raw);
57
+ return { mode, include: list(s.ci_precheck_include), exclude: list(s.ci_precheck_exclude), maxJobs: raw !== "" && Number.isInteger(n) && n >= 0 ? n : DEFAULT_MAX_JOBS };
58
+ }
59
+
60
+ /** The job's runnable step commands (install, noop, builtin and scope-skipped steps dropped). */
61
+ const liveSteps = (j) => (Array.isArray(j?.steps) ? j.steps : []).filter((s) => s && !s.noop && !s.skip && !s.builtin && s.kind !== "install" && str(s.command));
62
+
63
+ /** {kind, heavy}: the first heavy class, else lint/typecheck/test, else `other`. */
64
+ export function classifyJob(job) {
65
+ const key = str(job?.id).split(":").pop();
66
+ const text = `${key}\n${str(job?.name)}`, cmds = liveSteps(job).map((s) => s.command).join("\n");
67
+ for (const [kind, hit] of HEAVY) if (hit(text, cmds)) return { kind, heavy: true };
68
+ for (const [kind, re] of CHEAP) if (re.test(text)) return { kind, heavy: false };
69
+ for (const [kind, re] of CHEAP) if (re.test(cmds)) return { kind, heavy: false };
70
+ return { kind: "other", heavy: false };
71
+ }
72
+
73
+ const matchesEntry = (job, kind, entry) => {
74
+ const e = str(entry);
75
+ if (!e) return false;
76
+ if (e.toLowerCase() === kind) return true;
77
+ const re = globRe(e), key = str(job.id).split(":").pop();
78
+ return re.test(str(job.id)) || re.test(str(job.name)) || re.test(key);
79
+ };
80
+
81
+ /** The required check contexts this job reports as: its name or job key, alone, with a matrix suffix `name (a, b)`, or behind a caller `caller / name`. */
82
+ export function requiredFor(job, required) {
83
+ const names = [...new Set([str(job?.name), str(job?.id).split(":").pop()].filter(Boolean))];
84
+ return (required ?? []).filter((ctx) => {
85
+ const c = str(ctx);
86
+ return names.some((n) => c === n || c.startsWith(`${n} (`) || c.endsWith(` / ${n}`) || c.includes(` / ${n} (`));
87
+ });
88
+ }
89
+
90
+ /**
91
+ * Narrow a ci-local plan to the precheck set.
92
+ * @param {{plan:object, required:string[]|null, cfg?:object}} p
93
+ * @returns {{source:"required"|"fallback", run:object[], skipped:{job,name,reason}[], unrunnable:{job,name,reason}[], note:string}}
94
+ * run: [{job, name, workflow, kind, why, steps: string[], plan: object}] (plan: a one-job ci-local plan)
95
+ */
96
+ export function selectCiPrecheck({ plan, required = null, cfg = parseCiPrecheckConfig(null) }) {
97
+ const jobs = (Array.isArray(plan?.jobs) ? plan.jobs : []).filter((j) => j && CI_SOURCES.has(j.source) && !/:variants$/.test(str(j.id)));
98
+ const byId = new Map(jobs.map((j) => [j.id, j]));
99
+ const req = (Array.isArray(required) ? required : []).map(str).filter(Boolean);
100
+ // required jobs, then (transitively) the jobs an aggregator required job needs
101
+ const why = new Map();
102
+ for (const j of jobs) { const hit = requiredFor(j, req); if (hit.length) why.set(j.id, `required check ${hit.map((h) => `"${h}"`).join(", ")}`); }
103
+ const queue = [...why.keys()];
104
+ while (queue.length) {
105
+ const id = queue.shift();
106
+ for (const n of byId.get(id)?.needs ?? []) if (byId.has(n) && !why.has(n)) { why.set(n, `needed by required job ${id}`); queue.push(n); }
107
+ }
108
+ const source = why.size ? "required" : "fallback";
109
+ const note = why.size ? "" : req.length ? "no required check maps to a CI job; conservative lint/typecheck/test set" : "no required checks readable on the base; conservative lint/typecheck/test set";
110
+ const run = [], skipped = [], unrunnable = [];
111
+ for (const j of jobs) {
112
+ const { kind, heavy } = classifyJob(j);
113
+ const base = { job: j.id, name: str(j.name) || j.id };
114
+ if (j.not_applicable) { skipped.push({ ...base, reason: str(j.not_applicable) }); continue; }
115
+ const included = cfg.include.some((e) => matchesEntry(j, kind, e));
116
+ if (cfg.exclude.some((e) => matchesEntry(j, kind, e))) { skipped.push({ ...base, reason: "excluded by lean.ci_precheck_exclude" }); continue; }
117
+ let reason = why.get(j.id) ?? null;
118
+ if (!reason && source === "fallback" && ["lint", "typecheck", "test"].includes(kind)) reason = `${kind} job (fallback set)`;
119
+ if (!reason && included) reason = "named by lean.ci_precheck_include";
120
+ if (heavy && !included && (reason || source === "fallback")) { skipped.push({ ...base, reason: `heavy (${kind}): CI-only unless lean.ci_precheck_include names it` }); continue; }
121
+ if (!reason) { skipped.push({ ...base, reason: source === "required" ? "not a required check" : `${kind} job is not in the fallback set` }); continue; }
122
+ if (j.deferred_reason) { unrunnable.push({ ...base, reason: str(j.deferred_reason) }); continue; }
123
+ const steps = liveSteps(j).map((s) => (s.cwd && s.cwd !== "." ? `cd ${s.cwd} && ${s.command}` : s.command));
124
+ if (!steps.length) { skipped.push({ ...base, reason: "no step runs for this change (scoped out)" }); continue; }
125
+ run.push({ ...base, workflow: str(j.workflow) || null, kind, why: reason, steps, plan: { ...plan, jobs: [j] } });
126
+ }
127
+ const cap = Number.isInteger(cfg.maxJobs) ? cfg.maxJobs : DEFAULT_MAX_JOBS;
128
+ for (const r of run.splice(cap)) skipped.push({ job: r.job, name: r.name, reason: `over lean.ci_precheck_max_jobs (${cap}): left to CI` });
129
+ return { source, run, skipped, unrunnable, note };
130
+ }
131
+
132
+ const slug = (id) => str(id).replace(/[^A-Za-z0-9_.-]+/g, "_").slice(0, 120) || "job";
133
+
134
+ /** The pre-PR check command of one selected job; ci-local's own budget ends a little before the engine's timeout. */
135
+ export function ciPrecheckCommand(sel, { perCommandMs = 300000, script = CI_LOCAL_SH } = {}) {
136
+ const minutes = Math.max(1, Math.floor((Number(perCommandMs) > 0 ? Number(perCommandMs) : 300000) / 60000) - 1);
137
+ return `FORGE_CI_LOCAL_MAX_PARALLEL=1 bash ${q(script)} run --repo . --plan ${q(`${CI_PRECHECK_DIR}/${slug(sel.job)}.json`)} --budget-minutes ${minutes}`;
138
+ }
139
+
140
+ /**
141
+ * One round's plan: build the ci-local plan, select, write the one-job plans, and return the commands.
142
+ * Never throws: a planner failure (no yq, unreadable repo) is one unrunnable entry with its reason.
143
+ * @param {{buildPlan:Function, required:string[]|null, cfg:object, wt:string, base:string, lane:string, files:string[], perCommandMs?:number, writeFile:Function, skipJobs?:Set<string>}} p
144
+ * skipJobs: job ids an earlier round found unrunnable (not rerun)
145
+ * @returns {Promise<{source, note, commands:{job,name,workflow,kind,why,steps,command}[], skipped, unrunnable}>}
146
+ */
147
+ export async function deriveCiPrecheck({ buildPlan, required = null, cfg, wt, base, lane, files = [], perCommandMs, writeFile, skipJobs = new Set() }) {
148
+ let plan;
149
+ try { plan = await buildPlan({ repo: wt, base, baseBranch: lane, files }); } catch (e) {
150
+ return { source: "none", note: "", commands: [], skipped: [], unrunnable: [{ job: "*", name: "ci-local plan", reason: `CI check plan unavailable: ${str(e?.message ?? e).split("\n")[0].slice(0, 200)}` }] };
151
+ }
152
+ const sel = selectCiPrecheck({ plan, required, cfg });
153
+ const commands = [], unrunnable = [...sel.unrunnable], skipped = [...sel.skipped];
154
+ for (const r of sel.run) {
155
+ if (skipJobs.has(r.job)) { skipped.push({ job: r.job, name: r.name, reason: "unrunnable in an earlier round: left to CI" }); continue; }
156
+ try { await writeFile(`${CI_PRECHECK_DIR}/${slug(r.job)}.json`, `${JSON.stringify(r.plan)}\n`); } catch (e) { unrunnable.push({ job: r.job, name: r.name, reason: `plan file not written: ${str(e?.message ?? e).slice(0, 120)}` }); continue; }
157
+ commands.push({ job: r.job, name: r.name, workflow: r.workflow, kind: r.kind, why: r.why, steps: r.steps, command: ciPrecheckCommand(r, { perCommandMs }) });
158
+ }
159
+ return { source: sel.source, note: sel.note, commands, skipped, unrunnable };
160
+ }
161
+
162
+ /** The first line of `output` starting with `prefix`, without it; "" when none. */
163
+ const lineAfter = (output, prefix) => (String(output ?? "").split("\n").find((l) => l.startsWith(prefix)) ?? "").slice(prefix.length).trim();
164
+
165
+ /**
166
+ * One derived command's result -> {status: pass|fail|unrunnable|deferred, reason}. Exit 1 is a real failure; exit 2
167
+ * (ci-local DEGRADED: budget, job timeout, missing yq), 124 (killed by the engine's timeout) and 127 (no bash/node) are
168
+ * unrunnable; exit 0 with a CI_LOCAL_DEFERRED line is a job ci-local could not prove here (left to CI).
169
+ */
170
+ export function ciPrecheckOutcome(r) {
171
+ const rc = Number(r?.rc), out = String(r?.output ?? "");
172
+ if (rc === 1) return { status: "fail", reason: lineAfter(out, "CI_LOCAL_FAIL:") || "exit 1" };
173
+ if (rc === 0) { const d = lineAfter(out, "CI_LOCAL_DEFERRED:"); return d ? { status: "deferred", reason: d.split(" | ").slice(2).join(" | ") || d } : { status: "pass", reason: "" }; }
174
+ if (rc === 124) return { status: "unrunnable", reason: "timed out (host load or a long suite); left to CI" };
175
+ if (rc === 127) return { status: "unrunnable", reason: `could not start: ${out.split("\n").map((l) => l.trim()).find(Boolean)?.slice(0, 160) ?? "command not found"}` };
176
+ const deg = lineAfter(out, "CI_LOCAL_RESULT: DEGRADED");
177
+ return { status: "unrunnable", reason: (deg.replace(/^reason=/, "") || lineAfter(out, "CI_LOCAL_DEGRADED:") || `exit ${Number.isFinite(rc) ? rc : "?"}`).slice(0, 200) };
178
+ }
@@ -0,0 +1,149 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { describe, it } from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import { spawnSync } from "node:child_process";
6
+ import { writeFileSync, mkdirSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import { tmpDir } from "../tests/_tmp.mjs";
9
+ import { parseCiPrecheckConfig, classifyJob, requiredFor, selectCiPrecheck, deriveCiPrecheck, ciPrecheckCommand, ciPrecheckOutcome, CI_PRECHECK_DIR, DEFAULT_MAX_JOBS } from "./ci-precheck.mjs";
10
+
11
+ const step = (command, extra = {}) => ({ name: command, command, cwd: ".", kind: "check", ...extra });
12
+ const job = (key, name, cmds, extra = {}) => ({ id: `gha:ci:${key}`, source: "github-actions", name, workflow: ".github/workflows/ci.yml", steps: [step("pnpm install --frozen-lockfile", { kind: "install" }), ...cmds.map((c) => step(c))], services: [], needs: [], ...extra });
13
+ const PLAN = {
14
+ version: 1, repo: "/wt", jobs: [
15
+ job("lint", "Lint", ["pnpm lint"]),
16
+ job("typecheck", "Typecheck", ["pnpm turbo run typecheck --filter=...[origin/main]"]),
17
+ job("unit", "Unit tests", ["pnpm vitest related src/a.ts"]),
18
+ job("e2e", "E2E", ["pnpm playwright test"]),
19
+ job("storybook", "Storybook", ["pnpm build-storybook"]),
20
+ job("lighthouse", "Lighthouse", ["lhci autorun"]),
21
+ job("build", "Build", ["pnpm next build"]),
22
+ job("image", "Docker image", ["docker build -t app ."]),
23
+ job("dco", "DCO", ["bash scripts/check-dco.sh"]),
24
+ { id: "gha:docs:links", source: "github-actions", name: "Links", not_applicable: "pull_request path filter selects none of the changed files", steps: [], services: [] },
25
+ { id: "explicit:extra", source: "explicit", name: "extra", steps: [step("make extra")], services: [] },
26
+ ],
27
+ };
28
+
29
+ describe("#5820 ci-precheck config", () => {
30
+ it("defaults on, kind/glob lists from block, flow or comma forms; off and max_jobs parse", () => {
31
+ assert.deepEqual(parseCiPrecheckConfig(null), { mode: "on", include: [], exclude: [], maxJobs: DEFAULT_MAX_JOBS });
32
+ const c = parseCiPrecheckConfig({ ci_precheck: "off", ci_precheck_include: ["e2e", "gha:ci:build"], ci_precheck_exclude: "[\"Lint\", 'dco']", ci_precheck_max_jobs: "3" });
33
+ assert.deepEqual(c, { mode: "off", include: ["e2e", "gha:ci:build"], exclude: ["Lint", "dco"], maxJobs: 3 });
34
+ assert.deepEqual(parseCiPrecheckConfig({ ci_precheck_exclude: "a, b" }).exclude, ["a", "b"]);
35
+ assert.equal(parseCiPrecheckConfig({ ci_precheck_max_jobs: "junk" }).maxJobs, DEFAULT_MAX_JOBS);
36
+ });
37
+ });
38
+
39
+ describe("#5820 job classes", () => {
40
+ it("heavy suites are classed by name or command; cheap ones by name, then command", () => {
41
+ const k = (key) => classifyJob(PLAN.jobs.find((j) => j.id === `gha:ci:${key}`));
42
+ assert.deepEqual(["e2e", "storybook", "lighthouse", "build", "image"].map((x) => k(x)), [{ kind: "e2e", heavy: true }, { kind: "visual", heavy: true }, { kind: "lighthouse", heavy: true }, { kind: "build", heavy: true }, { kind: "docker", heavy: true }]);
43
+ assert.deepEqual(["lint", "typecheck", "unit", "dco"].map((x) => k(x).kind), ["lint", "typecheck", "test", "other"]);
44
+ assert.equal(classifyJob(job("checks", "Checks", ["pnpm exec playwright test"])).kind, "e2e", "a heavy runner in the steps of a neutral job name");
45
+ assert.equal(classifyJob(job("checks", "Checks", ["pnpm build && pnpm vitest run"])).kind, "test", "a plain package build before tests is not an app build");
46
+ });
47
+
48
+ it("required contexts match the job name, key, a matrix suffix or a caller prefix", () => {
49
+ const j = job("unit", "Unit tests", ["x"]);
50
+ assert.deepEqual(requiredFor(j, ["Unit tests", "unit (ubuntu-latest, 22)", "CI / Unit tests", "Lint", "Unit tests extra"]), ["Unit tests", "unit (ubuntu-latest, 22)", "CI / Unit tests"]);
51
+ });
52
+ });
53
+
54
+ describe("#5820 selection", () => {
55
+ it("required checks select their jobs (plus what an aggregator needs); heavy required jobs stay CI-only", () => {
56
+ const plan = { ...PLAN, jobs: [...PLAN.jobs, { ...job("all", "All checks", ["true"]), needs: ["gha:ci:typecheck"] }] };
57
+ const s = selectCiPrecheck({ plan, required: ["Lint", "All checks", "E2E", "DCO"] });
58
+ assert.equal(s.source, "required");
59
+ assert.deepEqual(s.run.map((r) => [r.job, r.why]), [["gha:ci:lint", 'required check "Lint"'], ["gha:ci:typecheck", "needed by required job gha:ci:all"], ["gha:ci:dco", 'required check "DCO"'], ["gha:ci:all", 'required check "All checks"']]);
60
+ assert.match(s.skipped.find((x) => x.job === "gha:ci:e2e").reason, /heavy \(e2e\)/);
61
+ assert.equal(s.skipped.find((x) => x.job === "gha:ci:unit").reason, "not a required check");
62
+ assert.ok(!s.run.some((r) => r.job === "explicit:extra"), "ci-local extra commands are not CI jobs");
63
+ assert.deepEqual(s.run[0].steps, ["pnpm lint"], "install steps dropped");
64
+ assert.deepEqual(s.run[0].plan.jobs.map((j) => j.id), ["gha:ci:lint"], "a one-job plan for ci-local run");
65
+ });
66
+
67
+ it("no required checks: the conservative lint/typecheck/test fallback, heavy and other jobs left to CI", () => {
68
+ for (const required of [[], null, ["some-external-app"]]) {
69
+ const s = selectCiPrecheck({ plan: PLAN, required });
70
+ assert.equal(s.source, "fallback");
71
+ assert.deepEqual(s.run.map((r) => r.kind), ["lint", "typecheck", "test"]);
72
+ assert.match(s.note, /conservative/);
73
+ }
74
+ const s = selectCiPrecheck({ plan: PLAN, required: [] });
75
+ for (const id of ["e2e", "storybook", "lighthouse", "build", "image"]) assert.match(s.skipped.find((x) => x.job === `gha:ci:${id}`).reason, /^heavy/);
76
+ assert.match(s.skipped.find((x) => x.job === "gha:ci:dco").reason, /not in the fallback set/);
77
+ assert.match(s.skipped.find((x) => x.job === "gha:docs:links").reason, /path filter/);
78
+ });
79
+
80
+ it("include opts a heavy kind or a job in; exclude always wins; max_jobs caps the rest", () => {
81
+ const cfg = parseCiPrecheckConfig({ ci_precheck_include: ["e2e", "Build"], ci_precheck_exclude: ["gha:ci:lint"], ci_precheck_max_jobs: "3" });
82
+ const s = selectCiPrecheck({ plan: PLAN, required: [], cfg });
83
+ assert.deepEqual(s.run.map((r) => r.job), ["gha:ci:typecheck", "gha:ci:unit", "gha:ci:e2e"]);
84
+ assert.equal(s.skipped.find((x) => x.job === "gha:ci:lint").reason, "excluded by lean.ci_precheck_exclude");
85
+ assert.match(s.skipped.find((x) => x.job === "gha:ci:build").reason, /max_jobs \(3\)/);
86
+ });
87
+
88
+ it("a job ci-local deferred (secrets, missing tool) is unrunnable with its reason; a scoped-out job is skipped", () => {
89
+ const plan = { jobs: [job("unit", "Unit tests", ["x"], { deferred_reason: "tool not installed locally: cargo" }), { ...job("lint", "Lint", []), steps: [step("eslint a.js", { skip: "no changed js file" })] }] };
90
+ const s = selectCiPrecheck({ plan, required: ["Unit tests", "Lint"] });
91
+ assert.deepEqual(s.unrunnable, [{ job: "gha:ci:unit", name: "Unit tests", reason: "tool not installed locally: cargo" }]);
92
+ assert.match(s.skipped.find((x) => x.job === "gha:ci:lint").reason, /scoped out/);
93
+ assert.equal(s.run.length, 0);
94
+ });
95
+ });
96
+
97
+ describe("#5820 derive + outcome", () => {
98
+ it("writes one plan file per job and returns bounded ci-local commands", async () => {
99
+ const written = new Map();
100
+ const d = await deriveCiPrecheck({ buildPlan: async (a) => { assert.deepEqual(a, { repo: "/wt", base: "origin/main", baseBranch: "main", files: ["src/a.ts"] }); return PLAN; },
101
+ required: ["Lint"], cfg: parseCiPrecheckConfig(null), wt: "/wt", base: "origin/main", lane: "main", files: ["src/a.ts"], perCommandMs: 600000, writeFile: async (p, t) => written.set(p, JSON.parse(t)) });
102
+ assert.equal(d.commands.length, 1);
103
+ assert.equal(d.commands[0].command, ciPrecheckCommand({ job: "gha:ci:lint" }, { perCommandMs: 600000 }));
104
+ assert.match(d.commands[0].command, /ci-local\.sh' run --repo \. --plan '\.forge-lean\/ci-precheck\/gha_ci_lint\.json' --budget-minutes 9$/);
105
+ assert.deepEqual([...written.keys()], [`${CI_PRECHECK_DIR}/gha_ci_lint.json`]);
106
+ const again = await deriveCiPrecheck({ buildPlan: async () => PLAN, required: ["Lint"], cfg: parseCiPrecheckConfig(null), wt: "/wt", base: "b", lane: "l", writeFile: async () => {}, skipJobs: new Set(["gha:ci:lint"]) });
107
+ assert.equal(again.commands.length, 0); assert.match(again.skipped.at(-1).reason, /earlier round/);
108
+ });
109
+
110
+ it("a planner failure (no yq) is one unrunnable entry, never a throw", async () => {
111
+ const d = await deriveCiPrecheck({ buildPlan: async () => { throw new Error("yq not found (mikefarah yq v4 is required to read CI definitions)"); }, cfg: parseCiPrecheckConfig(null), wt: "/wt", base: "b", lane: "l", writeFile: async () => {} });
112
+ assert.deepEqual(d.commands, []); assert.equal(d.source, "none");
113
+ assert.match(d.unrunnable[0].reason, /CI check plan unavailable: yq not found/);
114
+ });
115
+
116
+ it("exit 1 fails; exit 2/124/127 are unrunnable with a reason; exit 0 with a deferred line is deferred", () => {
117
+ assert.deepEqual(ciPrecheckOutcome({ rc: 0, output: "CI_LOCAL_RESULT: PASS" }), { status: "pass", reason: "" });
118
+ assert.deepEqual(ciPrecheckOutcome({ rc: 1, output: "x\nCI_LOCAL_FAIL: gha:ci:lint | step: pnpm lint | exit 1\n" }), { status: "fail", reason: "gha:ci:lint | step: pnpm lint | exit 1" });
119
+ assert.deepEqual(ciPrecheckOutcome({ rc: 2, output: "CI_LOCAL_RESULT: DEGRADED reason=budget_exhausted" }), { status: "unrunnable", reason: "budget_exhausted" });
120
+ assert.equal(ciPrecheckOutcome({ rc: 124, output: "" }).status, "unrunnable");
121
+ assert.match(ciPrecheckOutcome({ rc: 127, output: "bash: node: command not found" }).reason, /could not start: bash: node/);
122
+ assert.deepEqual(ciPrecheckOutcome({ rc: 0, output: "CI_LOCAL_DEFERRED: gha:ci:unit | Unit | version drift (node 18 vs 22)\nCI_LOCAL_RESULT: PASS" }), { status: "deferred", reason: "version drift (node 18 vs 22)" });
123
+ });
124
+ });
125
+
126
+ // Plan derivation from a sample workflow through the real ci-local planner; needs mikefarah yq v4 (skipped without it).
127
+ const yq = spawnSync("yq", ["-o=json", ".", "-"], { input: "a: 1\n", encoding: "utf8" });
128
+ describe("#5820 plan derivation from workflow YAML (ci-local planner)", { skip: yq.status === 0 && /"a": 1/.test(yq.stdout) ? false : "yq v4 not installed" }, () => {
129
+ it("required lint and unit jobs run, the e2e job stays CI-only, the docs-only workflow does not apply", async () => {
130
+ const { buildPlan } = await import("../../scripts/ci-local/plan.mjs");
131
+ const repo = tmpDir("ci-precheck-"), g = (...a) => spawnSync("git", ["-C", repo, ...a], { encoding: "utf8" });
132
+ g("init", "-q", "-b", "main"); g("config", "user.email", "t@example.com"); g("config", "user.name", "t");
133
+ mkdirSync(join(repo, ".github", "workflows"), { recursive: true }); mkdirSync(join(repo, "src"));
134
+ writeFileSync(join(repo, ".github", "workflows", "ci.yml"), [
135
+ "name: CI", "on:", " pull_request:", "jobs:",
136
+ " lint:", " name: Lint", " runs-on: ubuntu-latest", " steps:", " - uses: actions/checkout@v4", " - run: echo lint-ok",
137
+ " unit:", " name: Unit tests", " runs-on: ubuntu-latest", " steps:", " - uses: actions/checkout@v4", " - run: echo unit-ok",
138
+ " e2e:", " name: E2E", " runs-on: ubuntu-latest", " steps:", " - uses: actions/checkout@v4", " - run: echo playwright",
139
+ " deploy:", " runs-on: ubuntu-latest", " environment: prod", " steps:", " - run: echo deploy", ""].join("\n"));
140
+ writeFileSync(join(repo, ".github", "workflows", "docs.yml"), ["name: Docs", "on:", " pull_request:", " paths: ['docs/**']", "jobs:", " links:", " runs-on: ubuntu-latest", " steps:", " - run: echo links", ""].join("\n"));
141
+ writeFileSync(join(repo, "src", "a.js"), "1\n"); g("add", "-A"); g("commit", "-qm", "base");
142
+ const plan = buildPlan({ repo, base: "main", files: ["src/a.js"], noCache: true });
143
+ const s = selectCiPrecheck({ plan, required: ["Lint", "Unit tests", "E2E"] });
144
+ assert.equal(s.source, "required");
145
+ assert.deepEqual(s.run.map((r) => [r.job, r.steps]), [["gha:ci:lint", ["echo lint-ok"]], ["gha:ci:unit", ["echo unit-ok"]]]);
146
+ assert.match(s.skipped.find((x) => x.job === "gha:ci:e2e").reason, /^heavy \(e2e\)/);
147
+ assert.match(s.skipped.find((x) => /docs/.test(x.job)).reason, /path filter/);
148
+ });
149
+ });
@@ -37,6 +37,8 @@ import { CHECK_ID_RE, e2eCheckFor } from "./postdeploy-check.mjs";
37
37
  import { normaliseDecision, deadAnchors, anchorMatches, parseRequirementDecision } from "./decisions.mjs";
38
38
  import { globToRegex } from "../../scripts/ci-local/lib.mjs";
39
39
  import { contractBriefProblems } from "./pagegate.mjs"; // #5428
40
+ import { counterGrowth } from "./hotarea.mjs"; // #5751
41
+ import { designContractFailures } from "./recurrence.mjs"; // #5751
40
42
  const C = OUTCOME_CODES;
41
43
 
42
44
  /** #4789: folds what a builder retyping a quote changes: unicode punctuation, markdown links/markup, escapes, invisible chars. */
@@ -693,7 +695,7 @@ function splitRequirementRefs(ref) {
693
695
  function amendmentProblem(a, tag) {
694
696
  const kind = a?.kind;
695
697
  const need = kind === "add-deliverable" ? "needs a path" : kind === "add-requirement" ? "needs requirement {id, quote}"
696
- : kind === "supersedes" ? "needs guard: \"#N\" (the guarded issue)" : TRACKED.includes(kind) ? "needs requirement: \"R#\"" : kind === "amend-requirement" ? "needs requirement: \"R#\" and text (the revised wording)"
698
+ : kind === "supersedes" ? "needs guard: \"#N\" (the guarded issue) or mechanism: \"<name>\" (#5752: retires the guards whose tests the lane deletes)" : TRACKED.includes(kind) ? "needs requirement: \"R#\"" : kind === "amend-requirement" ? "needs requirement: \"R#\" and text (the revised wording)"
697
699
  : kind === "substitute-validate" ? "needs validate: \"V#\" and command" : kind === "out-of-band" ? "needs requirement: \"R#\" and evidence (the job or workflow that measures it)"
698
700
  : kind === "decision" ? "needs decision {choice, anchors: [paths or globs], symbols?, supersedes?: decision id}" : null;
699
701
  const why = need ? `amendment kind '${kind}' ${need}` : `unknown kind '${kind ?? ""}'; valid kinds are ${AMEND_KINDS.join(", ")}`;
@@ -799,6 +801,12 @@ export function applyAmendments(frozen, amendments, issueText = null, { generate
799
801
  if (tagsOutOfBand(r)) r.verify = "out_of_band"; // #4404: same freeze-time tag as the planned requirements
800
802
  c.requirements.push(r);
801
803
  if (TRACKED.includes(r.disposition)) toTrack.push(r);
804
+ } else if (a.kind === "supersedes" && blank(a.guard) && typeof a.mechanism === "string" && !blank(a.mechanism)) {
805
+ // #5752: one decision removes a named mechanism; precheck retires every guard_broken whose test file the lane deleted
806
+ const mechanism = a.mechanism.trim().slice(0, 120);
807
+ c.mechanisms = [...(c.mechanisms ?? []).filter((m) => m.mechanism !== mechanism), { mechanism, why: String(a.why).trim() }];
808
+ applied.push({ kind: a.kind, target: `mechanism ${mechanism}`, why: String(a.why).trim() });
809
+ continue;
802
810
  } else if (a.kind === "supersedes" && GUARD_ID_RE.test(String(a.guard ?? "").trim())) {
803
811
  // #4693: retires one guard's guard_broken for this lane; the reviewer judges it, the engine tells the guarded issue after merge
804
812
  const guard = `#${String(a.guard).trim().replace(/^#/, "")}`;
@@ -1044,6 +1052,9 @@ export function cliUsageError({ rc, output } = {}) {
1044
1052
  }
1045
1053
  const FORGEDOCK_ENTRY_RE = /^\/.*\/forgedock\/bin\/(?:lean\/checks|forgedock)\.mjs$/;
1046
1054
  const FORGEDOCK_TOKEN_RE = /(?<![\w./-])\/[^\s'"`;&|()]*\/forgedock\/bin\/(lean\/checks|forgedock)\.mjs/g;
1055
+ /** #5727: the portable placeholders a frozen command names forgedock's entry points by (the lane env exports both). */
1056
+ export const FORGEDOCK_CHECKS_VAR = "FORGEDOCK_CHECKS_CLI", FORGEDOCK_ENTRY_VAR = "FORGEDOCK_ENTRY_CLI";
1057
+ const FORGEDOCK_PLACEHOLDER_RE = /\$(?:\{FORGEDOCK_(CHECKS|ENTRY)_CLI\}|FORGEDOCK_(CHECKS|ENTRY)_CLI(?!\w))/g;
1047
1058
  /**
1048
1059
  * #5005: a frozen validate command names forgedock's own entry point by the absolute path of the install that wrote it; on
1049
1060
  * the host that runs it that path may not exist. Rewrites each such token whose file is missing to this install's path.
@@ -1052,9 +1063,33 @@ export function resolveForgedockPaths(command, { exists = () => true, checksCli,
1052
1063
  return String(command ?? "").replace(FORGEDOCK_TOKEN_RE, (tok, which) => {
1053
1064
  const here = which === "forgedock" ? forgedockCli : checksCli;
1054
1065
  return here && !exists(tok) ? here : tok;
1066
+ }).replace(FORGEDOCK_PLACEHOLDER_RE, (tok, a, b) => { // #5727: the portable frozen form always names this install
1067
+ const here = (a ?? b) === "ENTRY" ? forgedockCli : checksCli;
1068
+ return here || tok;
1069
+ });
1070
+ }
1071
+ /** #5727: every absolute forgedock entry-point token becomes its portable placeholder, so a frozen contract names no install path. Pure. */
1072
+ export function portableForgedockPaths(command) {
1073
+ return String(command ?? "").replace(FORGEDOCK_TOKEN_RE, (tok, which) => `$${which === "forgedock" ? FORGEDOCK_ENTRY_VAR : FORGEDOCK_CHECKS_VAR}`);
1074
+ }
1075
+ const RESOLVED_RUNNERS = ["runCommand", "probeCommand", "preflightRun", "redGreen"];
1076
+ /**
1077
+ * #5727: `io` with its command runners (runCommand, probeCommand, preflightRun, redGreen) resolving `command` through
1078
+ * resolveForgedockPaths before the call, so no execution site runs a frozen forgedock path of another install. Other members untouched.
1079
+ */
1080
+ export function resolvingIo(io, opts = {}) {
1081
+ if (!io || typeof io !== "object") return io;
1082
+ const wrapped = new Map(); // live view: a member set on io later is seen; a runner is wrapped per function
1083
+ return new Proxy(io, {
1084
+ get(t, k, r) {
1085
+ const fn = Reflect.get(t, k, r);
1086
+ if (!RESOLVED_RUNNERS.includes(k) || typeof fn !== "function") return fn;
1087
+ if (!wrapped.has(fn)) wrapped.set(fn, (a, ...rest) => fn.call(t, a && typeof a === "object" && typeof a.command === "string" ? { ...a, command: resolveForgedockPaths(a.command, opts) } : a, ...rest));
1088
+ return wrapped.get(fn);
1089
+ },
1055
1090
  });
1056
1091
  }
1057
- const KIND_NAME = { command: "command", "python-module": "Python module", "node-module": "Node package", environment: "environment service" };
1092
+ const KIND_NAME = { "forgedock-path": "forgedock install path", command: "command", "python-module": "Python module", "node-module": "Node package", environment: "environment service" };
1058
1093
  /**
1059
1094
  * forge#4323: the host tool or module a failed command could not find, from its {rc, output}: bash/sh "X: command not found"
1060
1095
  * (or rc 127), python "No module named x" (top-level package), node "Cannot find module|package 'x'" (bare specifiers only).
@@ -1067,7 +1102,7 @@ export function missingTool({ rc, output } = {}, { repoHas = () => false, comman
1067
1102
  const py = PY_MISSING_RE.exec(out);
1068
1103
  if (py) { const tool = String(py[1] ?? py[2]).split(".")[0]; return local(tool) ? null : { tool, kind: "python-module" }; }
1069
1104
  const js = NODE_MISSING_RE.exec(out);
1070
- if (js && FORGEDOCK_ENTRY_RE.test(js[1])) return { tool: "forgedock", kind: "command" }; // #5005: the host's forgedock install is not at the frozen path
1105
+ if (js && FORGEDOCK_ENTRY_RE.test(js[1])) return { tool: "forgedock", kind: "forgedock-path" }; // #5005, #5727: an install-path mismatch, never a lane_tools candidate (not a TOOL_KIND)
1071
1106
  if (js) {
1072
1107
  const spec = js[1], scoped = spec.startsWith("@");
1073
1108
  if (!scoped && spec.includes("/")) return null;
@@ -1120,7 +1155,7 @@ export function interfaceDecisionFailures(contract, result, changedFiles) {
1120
1155
  * `ciCovered` (#4527): the validate ids accepted only because the head is CI-verified (no local result, or a missing host
1121
1156
  * tool), for the trajectory; always an array.
1122
1157
  */
1123
- export function precheck({ contract, result, changedFiles, ignore = [], ciVerified = false, hotspots = null, repro = null, validateRuns = null, repoHas = () => false, frozen = null, checkIds = null, baselineFailures = null, guardFailures = null, coupledFailures = null, relaxationFailures = null, routeFailures = null, docsFailures = null, pageFailures = null, docsPaths = null, prodParityFailures = null, seamFailures = null, newOffKeys = null, substitutedRuns = null, removedPaths = [], baseFiles = [], uiBrowser = null }) {
1158
+ export function precheck({ contract, result, changedFiles, ignore = [], ciVerified = false, hotspots = null, repro = null, validateRuns = null, repoHas = () => false, frozen = null, checkIds = null, baselineFailures = null, guardFailures = null, coupledFailures = null, relaxationFailures = null, routeFailures = null, docsFailures = null, pageFailures = null, docsPaths = null, prodParityFailures = null, seamFailures = null, newOffKeys = null, substitutedRuns = null, removedPaths = [], baseFiles = [], uiBrowser = null, ciBudgetFailures = null, counters = null, recurrence = null, outcomeEvidenceFailures = null }) {
1124
1159
  const failures = [], superseded = [], ciCovered = [], equivalent = [];
1125
1160
  // #4626: a post-deploy check id must be on the default branch or added by this PR (`checkIds`: ids of both checks files; null = not resolved)
1126
1161
  if (checkIds) for (const r of contract.requirements ?? []) {
@@ -1192,15 +1227,21 @@ export function precheck({ contract, result, changedFiles, ignore = [], ciVerifi
1192
1227
  }
1193
1228
  for (const f of baselineFailures ?? []) failures.push({ code: C.CONFORMANCE_REGRESSION, ...f }); // #5448
1194
1229
  failures.push(...hotspotGrowth({ contract, result, hotspots, changedFiles }));
1230
+ failures.push(...counterGrowth({ before: counters?.before, after: counters?.after, contract, result })); // #5751: forge.yaml recurrence.counters, measured at base and lane head
1231
+ failures.push(...designContractFailures(contract, recurrence)); // #5751: a recurring issue's design lane contract
1195
1232
  if (repro) failures.push(...reproFailures(contract, repro), ...reproQualityFailures(repro));
1196
1233
  failures.push(...sourceDeliverableFailures(contract, changedFiles, ignore));
1197
1234
  // #4693: a broken guard fails unless the contract carries a supersedes amendment for it
1198
1235
  const retired = new Set((contract.supersedes ?? []).map((s) => s.guard));
1199
- for (const f of guardFailures ?? []) if (!retired.has(f.guard)) failures.push(f);
1236
+ // #5752: a mechanism supersedes retires a guard whose test file the lane deleted; a surviving test still needs its own supersedes
1237
+ const deleted = contract.mechanisms?.length && Array.isArray(removedPaths) ? new Set(removedPaths) : null;
1238
+ for (const f of guardFailures ?? []) if (!retired.has(f.guard) && !(deleted && f.test && deleted.has(f.test))) failures.push(f);
1200
1239
  for (const f of coupledFailures ?? []) failures.push(f); // #5079
1201
1240
  for (const f of relaxationFailures ?? []) failures.push(f); // #5237
1202
1241
  failures.push(...(routeFailures ?? [])); // #5087: topology.route_reachability, blocking when declared
1203
1242
  failures.push(...(docsFailures ?? [])); // #5419: forge.yaml docs
1243
+ failures.push(...(outcomeEvidenceFailures ?? [])); // #5752: forge.yaml outcome_evidence
1244
+ failures.push(...(ciBudgetFailures ?? [])); // #5760: CI additions need a FORGE:CI_BUDGET annotation or the shared job, scoped hygiene, max counts
1204
1245
  failures.push(...(pageFailures ?? [])); // #5428: forge.yaml pages
1205
1246
  failures.push(...(prodParityFailures ?? [])); // #5284: topology.prod_parity
1206
1247
  failures.push(...interfaceDecisionFailures(contract, result, changedFiles)); // #5338
@@ -1524,6 +1565,7 @@ export function autoPostDeployE2e(contract, only = null) {
1524
1565
  });
1525
1566
  return { contract: converted.length ? { ...contract, requirements } : contract, converted };
1526
1567
  }
1568
+ const DECISION_WHY = "operator FORGE:DECISION"; // #5773: the why prefix of a decided row (idempotence marker)
1527
1569
  /**
1528
1570
  * #5547: apply trusted structured operator decisions (`<!-- FORGE:DECISION {"requirement":"R2","disposition":"post-deploy"} -->`) to a
1529
1571
  * frozen contract: a deliver/defer row becomes a checkless post-deploy row (deferChecklessPostDeploy then routes it). Only comments after
@@ -1533,15 +1575,49 @@ export function applyRequirementDecisions(contract, comments = []) {
1533
1575
  const list = Array.isArray(comments) ? comments : [];
1534
1576
  const at = list.map((c) => String(c?.body ?? "").trimStart().startsWith("<!-- FORGE:CONTRACT")).lastIndexOf(true);
1535
1577
  const ds = list.slice(at + 1).map((c) => parseRequirementDecision(c?.body)).filter(Boolean);
1578
+ const rows = Array.isArray(contract?.requirements) ? contract.requirements : [];
1579
+ // #5773: a decision's quote wins over its id (a requeue may have renumbered the row); the id is the fallback
1580
+ const nq = (q) => norm(q).replace(/\s+/g, " ").trim();
1581
+ const target = (d) => {
1582
+ const q = d.quote ? nq(d.quote) : "";
1583
+ const byQuote = q ? rows.find((r) => nq(r?.quote) === q) ?? rows.find((r) => nq(r?.quote).includes(q)) : null; // exact before contains
1584
+ return byQuote ?? rows.find((r) => r?.id === d.requirement) ?? null;
1585
+ };
1586
+ const decided = new Map();
1587
+ for (const d of ds) { const r = target(d); if (r && !decided.has(r.id)) decided.set(r.id, d); }
1536
1588
  const applied = [];
1537
- const requirements = (Array.isArray(contract?.requirements) ? contract.requirements : []).map((r) => {
1538
- const d = ds.find((x) => x.requirement === r?.id);
1539
- if (!d || !["deliver", "defer"].includes(r.disposition)) return r;
1589
+ const requirements = rows.map((r) => {
1590
+ const d = decided.get(r?.id);
1591
+ // #5773: a check-less post-deploy row (added by an amendment) is decided too; one with a check id keeps it, the check-id gate judges it
1592
+ const open = ["deliver", "defer"].includes(r?.disposition) || (r?.disposition === "post-deploy" && !CHECK_ID_RE.test(String(r.check ?? "")));
1593
+ if (!d || !open || String(r.why ?? "").startsWith(DECISION_WHY)) return r;
1540
1594
  applied.push(r.id);
1541
- return { ...r, e2e_tracked: true, disposition: "post-deploy", bucket: "post-deploy", local_infeasible_why: "operator decision: the run needs spend or a third-party host outside the lane", why: `operator FORGE:DECISION: tracked post-deploy by the orchestrator, needs spend or a third-party host${d.why ? ` (${d.why})` : ""} (#5547)` };
1595
+ const { check: _check, engine_check: _engine, ...rest } = r; // #5773: a decided row is checkless; a check id it had is dropped
1596
+ return { ...rest, e2e_tracked: true, disposition: "post-deploy", bucket: "post-deploy", local_infeasible_why: "operator decision: the run needs spend or a third-party host outside the lane", why: `${DECISION_WHY}: tracked post-deploy by the orchestrator, needs spend or a third-party host${d.why ? ` (${d.why})` : ""} (#5547)` };
1542
1597
  });
1543
1598
  return { contract: applied.length ? { ...contract, requirements } : contract, applied };
1544
1599
  }
1600
+ /**
1601
+ * #5773: replayed amendments (priorAmendments plus the builder's re-emitted rows) keep one `add-requirement` per quote, the
1602
+ * last, and drop one whose quote is already a row of `contract` (the frozen contract), so a requeue does not renumber the
1603
+ * same row (#5365 renumbering still applies to distinct quotes). Other kinds pass through in order. Pure.
1604
+ */
1605
+ export function dedupeAddRequirements(contract, amendments = []) {
1606
+ const nq = (q) => norm(q).replace(/\s+/g, " ").trim();
1607
+ const list = Array.isArray(amendments) ? amendments : [];
1608
+ const frozenQuotes = new Set((contract?.requirements ?? []).map((r) => nq(r?.quote)).filter(Boolean));
1609
+ const isAdd = (a) => a?.kind === "add-requirement" && typeof a?.requirement?.quote === "string" && nq(a.requirement.quote);
1610
+ const last = new Map();
1611
+ list.forEach((a, i) => { if (isAdd(a)) last.set(nq(a.requirement.quote), i); });
1612
+ const dropped = [];
1613
+ const kept = list.filter((a, i) => {
1614
+ if (!isAdd(a)) return true;
1615
+ const q = nq(a.requirement.quote);
1616
+ if (frozenQuotes.has(q) || last.get(q) !== i) { dropped.push({ id: a.requirement.id, quote: a.requirement.quote }); return false; }
1617
+ return true;
1618
+ });
1619
+ return { amendments: kept, dropped };
1620
+ }
1545
1621
  /** #5468: the row ids named by `e2e_row` failures when every failure is one; null otherwise (anything else blocks as before). */
1546
1622
  export function loneE2eRows(failures) {
1547
1623
  const fs = failures ?? [];