forgedock 1.67.0 → 1.69.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 (156) 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 +103 -21
  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 +39 -15
  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.mjs +11 -1
  17. package/bin/lean/batch.test.mjs +51 -2
  18. package/bin/lean/capsample.mjs +25 -0
  19. package/bin/lean/ci-gate.mjs +2 -90
  20. package/bin/lean/ci-gate.test.mjs +1 -127
  21. package/bin/lean/ci-precheck.mjs +25 -8
  22. package/bin/lean/ci-precheck.test.mjs +24 -0
  23. package/bin/lean/clear-breaker.test.mjs +4 -3
  24. package/bin/lean/commentstate.mjs +10 -5
  25. package/bin/lean/commentstate.test.mjs +12 -1
  26. package/bin/lean/conformance.e2e.test.mjs +9 -6
  27. package/bin/lean/conformance.mjs +62 -197
  28. package/bin/lean/conformance.test.mjs +46 -376
  29. package/bin/lean/depcache.mjs +102 -10
  30. package/bin/lean/depcache.test.mjs +105 -0
  31. package/bin/lean/docsgate.mjs +0 -32
  32. package/bin/lean/docsgate.test.mjs +2 -23
  33. package/bin/lean/effects-cap.test.mjs +9 -1
  34. package/bin/lean/effects-killtree.test.mjs +35 -0
  35. package/bin/lean/effects.mjs +57 -25
  36. package/bin/lean/engine-readmit.test.mjs +35 -0
  37. package/bin/lean/envgap.mjs +111 -0
  38. package/bin/lean/envgap.test.mjs +64 -0
  39. package/bin/lean/execution.mjs +13 -4
  40. package/bin/lean/execution.test.mjs +33 -0
  41. package/bin/lean/failure-census.mjs +170 -0
  42. package/bin/lean/failure-census.test.mjs +59 -0
  43. package/bin/lean/failure-stop.mjs +12 -1
  44. package/bin/lean/failure-stop.test.mjs +14 -1
  45. package/bin/lean/guardgate.test.mjs +2 -3
  46. package/bin/lean/heavy.mjs +33 -4
  47. package/bin/lean/heavy.test.mjs +38 -6
  48. package/bin/lean/hostconfig.mjs +54 -0
  49. package/bin/lean/hostconfig.test.mjs +67 -0
  50. package/bin/lean/hotarea.mjs +0 -36
  51. package/bin/lean/hotarea.test.mjs +1 -22
  52. package/bin/lean/issuewatch-verify.mjs +19 -4
  53. package/bin/lean/issuewatch.mjs +21 -4
  54. package/bin/lean/issuewatch.test.mjs +48 -1
  55. package/bin/lean/lane-audit-gap.mjs +66 -0
  56. package/bin/lean/lane-audit-gap.test.mjs +59 -0
  57. package/bin/lean/lane-audit-llm.mjs +52 -0
  58. package/bin/lean/lane-audit-llm.test.mjs +57 -0
  59. package/bin/lean/lane-audit-query.mjs +47 -0
  60. package/bin/lean/lane-audit-query.test.mjs +44 -0
  61. package/bin/lean/lane-audit-signatures.mjs +33 -0
  62. package/bin/lean/lane-audit.mjs +110 -0
  63. package/bin/lean/lane-audit.test.mjs +97 -0
  64. package/bin/lean/lane-recovery.test.mjs +33 -0
  65. package/bin/lean/lanecheck.mjs +5 -3
  66. package/bin/lean/lanecheck.test.mjs +6 -0
  67. package/bin/lean/lean.mjs +247 -152
  68. package/bin/lean/lean.test.mjs +502 -206
  69. package/bin/lean/limits.mjs +17 -0
  70. package/bin/lean/limits.test.mjs +15 -1
  71. package/bin/lean/live-execution.mjs +24 -2
  72. package/bin/lean/live-execution.test.mjs +62 -0
  73. package/bin/lean/orchestrate-attempts.test.mjs +17 -9
  74. package/bin/lean/orchestrate-dispatch-placement.test.mjs +81 -0
  75. package/bin/lean/orchestrate-envhold.test.mjs +62 -1
  76. package/bin/lean/orchestrate-heldroot.test.mjs +72 -0
  77. package/bin/lean/orchestrate-hostfallback.test.mjs +59 -1
  78. package/bin/lean/orchestrate-overload-recovery.test.mjs +37 -0
  79. package/bin/lean/orchestrate-pause.test.mjs +53 -1
  80. package/bin/lean/orchestrate-reconcile.test.mjs +17 -0
  81. package/bin/lean/orchestrate-relaunch-gates.test.mjs +57 -0
  82. package/bin/lean/orchestrate-stacking.test.mjs +10 -0
  83. package/bin/lean/orchestrate.mjs +215 -42
  84. package/bin/lean/postdeploy-check.test.mjs +1 -3
  85. package/bin/lean/precheck.mjs +20 -0
  86. package/bin/lean/preflight.mjs +110 -14
  87. package/bin/lean/preflight.test.mjs +64 -4
  88. package/bin/lean/prompts.mjs +11 -21
  89. package/bin/lean/recurrence.mjs +6 -148
  90. package/bin/lean/recurrence.test.mjs +11 -147
  91. package/bin/lean/release-deploy.mjs +35 -5
  92. package/bin/lean/release-deploy.test.mjs +50 -3
  93. package/bin/lean/release-flakes.mjs +48 -2
  94. package/bin/lean/release-flakes.test.mjs +45 -1
  95. package/bin/lean/release-ledger.mjs +19 -1
  96. package/bin/lean/release-ledger.test.mjs +23 -0
  97. package/bin/lean/release-preflight.mjs +28 -0
  98. package/bin/lean/release-preflight.test.mjs +42 -1
  99. package/bin/lean/release-review.mjs +40 -5
  100. package/bin/lean/release-review.test.mjs +43 -2
  101. package/bin/lean/release.mjs +45 -15
  102. package/bin/lean/release.test.mjs +32 -0
  103. package/bin/lean/retry.mjs +1 -1
  104. package/bin/lean/retry.test.mjs +6 -1
  105. package/bin/lean/rotator.mjs +9 -0
  106. package/bin/lean/rotator.test.mjs +11 -1
  107. package/bin/lean/sandbox-remote.mjs +51 -13
  108. package/bin/lean/schedd.mjs +13 -8
  109. package/bin/lean/schedd.test.mjs +65 -5
  110. package/bin/lean/selfreview.mjs +1 -1
  111. package/bin/lean/statuscomment.mjs +4 -1
  112. package/bin/lean/validate-catalog.mjs +108 -0
  113. package/bin/lean/validate-catalog.test.mjs +46 -1
  114. package/bin/lean/verify.mjs +1 -1
  115. package/bin/pool/affinity.test.mjs +91 -0
  116. package/bin/pool/agent.mjs +247 -23
  117. package/bin/pool/cache-sweep.mjs +31 -10
  118. package/bin/pool/ci-autoscale.mjs +160 -0
  119. package/bin/pool/cli.mjs +56 -9
  120. package/bin/pool/docker.mjs +5 -0
  121. package/bin/pool/engine-placement.test.mjs +94 -0
  122. package/bin/pool/image-manifest.mjs +24 -0
  123. package/bin/pool/image-manifest.test.mjs +20 -0
  124. package/bin/pool/lane-target.mjs +41 -0
  125. package/bin/pool/lane-tools.mjs +29 -5
  126. package/bin/pool/lane-tools.test.mjs +36 -7
  127. package/bin/pool/mirror-seed.mjs +15 -11
  128. package/bin/pool/project-layer.mjs +142 -0
  129. package/bin/pool/project-layer.test.mjs +73 -0
  130. package/bin/pool/router.mjs +106 -36
  131. package/bin/pool/version.mjs +72 -2
  132. package/bin/review-staging.mjs +11 -3
  133. package/bin/runner.mjs +59 -11
  134. package/bin/stats/release.mjs +7 -0
  135. package/bin/stats/release.test.mjs +20 -0
  136. package/bin/stats/scorecard.mjs +187 -0
  137. package/bin/stats/scorecard.test.mjs +89 -0
  138. package/bin/stats/tool-parks.mjs +29 -0
  139. package/bin/stats/tool-parks.test.mjs +21 -0
  140. package/docs/CONFIG.md +41 -0
  141. package/docs/OUTCOME-CODES.md +1 -0
  142. package/docs/STATS.md +17 -0
  143. package/package.json +1 -1
  144. package/pool/image/Dockerfile +15 -3
  145. package/pool/image/manifest.json +25 -0
  146. package/pool/image/mirror.sh +11 -2
  147. package/pool/install/install-agent.ps1 +11 -4
  148. package/scripts/ci-local/adapters/github-actions.mjs +8 -0
  149. package/scripts/ci-local/cli.mjs +1 -1
  150. package/scripts/ci-local/plan.mjs +3 -2
  151. package/scripts/ci-local.test.sh +14 -2
  152. package/scripts/failure-census.mjs +67 -0
  153. package/scripts/review-finalize.sh +5 -5
  154. package/scripts/review-finalize.test.sh +8 -1
  155. package/scripts/verify-phase-trail.sh +11 -0
  156. package/scripts/verify-phase-trail.test.sh +9 -0
@@ -0,0 +1,35 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // #6091: a lane held on env.engine_skew is re-admitted by the engine of the agent that will run it, not the orchestrator's.
4
+ import { describe, it } from "node:test";
5
+ import assert from "node:assert/strict";
6
+ import { orchestrate } from "./orchestrate.mjs";
7
+
8
+ const SKEW = { terminalReason: "needs-human", code: "recurrence.design_missing", detail: "gate fired", engineVersion: "1.66.0" };
9
+ const MERGED = { terminalReason: "merged", pr: 9 };
10
+ const run = ({ agentVersion, script }) => {
11
+ let t = 1_000_000, k = 0;
12
+ const calls = [];
13
+ return orchestrate({ issues: [1], parallel: 1, readBody: async () => "", now: () => t, pollMs: 1000, version: "1.67.0",
14
+ sleep: async (ms) => { t += Math.max(1, Number(ms) || 0); },
15
+ envHold: { version: () => "1.67.0", maxMs: 120_000, watchMs: 30_000, agentVersion: () => agentVersion(calls.length) },
16
+ runOne: async (n) => { calls.push(n); t += 1000; return script[Math.min(k++, script.length - 1)]; },
17
+ remote: { max: 2, isRemote: () => true, admit: () => ({ ok: true }), onBudget: "stop", costPerMinute: 0 } })
18
+ .then((rows) => ({ rows, calls }));
19
+ };
20
+
21
+ describe("#6091 engine-held re-admission follows the agent's engine", () => {
22
+ it("stays held while the only agent is still on the old engine", async () => {
23
+ const { rows, calls } = await run({ agentVersion: () => "1.66.0", script: [SKEW, MERGED] });
24
+ assert.equal(calls.length, 1, "not relaunched onto the old agent");
25
+ assert.equal(rows[0].outcome, "held");
26
+ assert.equal(rows[0].code, "env.engine_skew");
27
+ assert.equal(rows[0].engineVersion, "1.66.0", "the engine that ran stays on the row");
28
+ });
29
+
30
+ it("is re-admitted once the agent upgrades to the needed engine", async () => {
31
+ const { rows, calls } = await run({ agentVersion: (n) => (n >= 1 ? "1.67.1" : "1.66.0"), script: [SKEW, MERGED] });
32
+ assert.deepEqual(calls, [1, 1]);
33
+ assert.equal(rows[0].outcome, "merged");
34
+ });
35
+ });
@@ -0,0 +1,111 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: BUSL-1.1
3
+ // #6106: deterministic classification of environment gaps. A missing tool, binary, interpreter, recipe, package or sandbox
4
+ // capability is an `env.*` outcome that recovers on its own, never ci.red or a human block. Genuine human reasons stay human.
5
+ import { OUTCOME_CODES } from "../engine/outcome-codes.mjs";
6
+
7
+ /** A check command's output that says the tool (not the change) is what failed. */
8
+ export const CHECK_TOOL_GAP_RE = /PATH pass-through wrapper with no real binary|command not found|(?:^|\n)\s*(?:\S+:\s*)?(?:sh|bash|zsh): (?:\d+: )?\S+: not found|not found in PATH|: No such file or directory[^\n]*node_modules\/\.bin|\bENOENT\b[^\n]{0,60}spawn|no module named|ModuleNotFoundError|cannot connect to the docker daemon|no docker daemon/i;
9
+
10
+ /** Words that make a block a real human decision, whatever else it says. */
11
+ const HUMAN_SIGNAL_RE = /\bapprov|sign[- ]?off|\bspend\b|\bbudget\b|purchase|\bpayment|\bcustomer|\blegal\b|\bsecrets?\b|password|passphrase|api[- ]?key|\btoken\b|\bcredentials?\b|\bpricing\b|owner (?:decision|call)|which (?:option|approach|product)/i;
12
+
13
+ const SANDBOX_CAP_RE = /\bsandbox\b[^.\n]{0,80}\b(?:lacks?|missing|has no|without|cannot|can't|does not have|doesn't have|no access)\b|\b(?:lacks?|missing|no|without)\b[^.\n]{0,40}\bsandbox (?:capabilit|access|network|docker|gpu)/i;
14
+ const TOOL_GAP_BLOCK_RE = [
15
+ /\b(?:no|missing|lacks?|without|not (?:installed|available|found)|only)\b[^.\n]{0,60}\b(?:interpreter|python\s?3\.\d+|python\s?\d|node(?:\.js)?\s?\d+|binary|binaries|toolchain|runtime|docker|compiler|executable)\b/i,
16
+ /\b(?:interpreter|binary|executable|toolchain)\b[^.\n]{0,60}\b(?:not (?:installed|available|found)|missing|absent|only)\b/i,
17
+ /\blane[-_ ]?tools?\b|\brecipes?\b/i,
18
+ /\b(?:package|module|library|dependency|dependencies)\b[^.\n]{0,60}\b(?:not installed|missing|not found|cannot be installed|unavailable)\b/i,
19
+ /\b(?:not installed|command not found|no module named|ModuleNotFoundError)\b/i,
20
+ ];
21
+
22
+ /**
23
+ * The env code for a builder block whose declared reason is a human one, or null to keep it human.
24
+ * @param {string} why the block's typed reason ("product-decision", "credentials", ...)
25
+ * @param {string} text the builder's summary/reason
26
+ * @returns {string|null} OUTCOME_CODES.ENV_TOOL_MISSING | ENV_CAPABILITY_REMOTE | null
27
+ */
28
+ export function envGapBlockCode(why, text) {
29
+ if (!["product-decision", "credentials"].includes(String(why))) return null;
30
+ const s = String(text ?? "");
31
+ if (!s || HUMAN_SIGNAL_RE.test(s)) return null;
32
+ if (SANDBOX_CAP_RE.test(s)) return OUTCOME_CODES.ENV_CAPABILITY_REMOTE;
33
+ if (TOOL_GAP_BLOCK_RE.some((re) => re.test(s))) return OUTCOME_CODES.ENV_TOOL_MISSING;
34
+ return null;
35
+ }
36
+
37
+ const BASE_MERGE_RE = /\b(?:merge|merging|merged|sync|syncing|rebase|rebasing|update|updating|bring(?:ing)?)\b[^.\n]{0,50}\b(?:staging|main|master|develop|trunk|the base(?: branch)?|base branch|upstream|origin\/\w+)\b|\b(?:staging|main|master|the base(?: branch)?|base branch)\b[^.\n]{0,40}\b(?:merge|merged|into (?:the |this |my |our )?(?:lane|branch|worktree))\b/i;
38
+ const APPROVAL_NOISE_RE = /\b(?:user|owner|human|operator)[- ]?(?:approved|approval)\b|\bapprov(?:al|ed|e)\b|CLAUDE\.md[^.\n]{0,60}\b(?:forbids?|prohibits?|disallows?|says|rule)\b[^.\n]{0,40}/gi;
39
+
40
+ /**
41
+ * #6137: merging the base into the lane's own branch is the engine's base-sync, never a human gate. A human block whose only
42
+ * reason is such a merge (a repo rule against agents merging is meant for PRs and protected branches) is a mechanical base-sync.
43
+ * Other human signals (spend, credentials, a PR merge, promotion to main) keep the block human.
44
+ * @param {string} why
45
+ * @param {string} text
46
+ */
47
+ export function baseMergeOnlyBlock(why, text) {
48
+ if (String(why) !== "product-decision") return false;
49
+ const s = String(text ?? "");
50
+ if (!BASE_MERGE_RE.test(s)) return false;
51
+ if (/\b(?:pull request|PR)\b[^.\n]{0,20}\bmerge|\bmerge\b[^.\n]{0,20}\b(?:PR|pull request)\b|\bpromot|\brelease\b|\b(?:to|into) (?:main|production|prod)\b/i.test(s)) return false;
52
+ return !HUMAN_SIGNAL_RE.test(s.replace(APPROVAL_NOISE_RE, " "));
53
+ }
54
+
55
+ /** The failed check results (`{command, rc, output}`) whose output names a missing tool. */
56
+ export function toolGapFailures(failed = []) {
57
+ return failed.filter((f) => CHECK_TOOL_GAP_RE.test(String(f?.output ?? "")));
58
+ }
59
+
60
+ /**
61
+ * Package directories a check command line works in (`cd web && ...`, `--prefix web`, `-C web`, `--cwd web`, `web/node_modules/.bin/x`)
62
+ * that carry a package.json but no installed node_modules: dependencies to prepare before the checks run.
63
+ * @param {string[]} commands
64
+ * @param {(rel: string) => boolean} exists path relative to the worktree
65
+ */
66
+ export function packageDirsMissingDeps(commands = [], exists = () => false) {
67
+ const dirs = new Set();
68
+ const add = (d) => {
69
+ const dir = String(d ?? "").replace(/^\.\//, "").replace(/\/+$/, "");
70
+ if (!dir || dir.startsWith("/") || dir.split("/").includes("..") || /[$`*]/.test(dir)) return;
71
+ dirs.add(dir);
72
+ };
73
+ for (const c of commands) {
74
+ const s = String(c ?? "");
75
+ for (const m of s.matchAll(/(?:^|[\s;&|(])cd\s+([^\s;&|)]+)/g)) add(m[1]);
76
+ for (const m of s.matchAll(/(?:--prefix|--cwd|-C|--dir)[ =]([^\s;&|)]+)/g)) add(m[1]);
77
+ for (const m of s.matchAll(/(?:^|[\s"'])((?:\.\/)?[\w.-]+(?:\/[\w.-]+)*?)\/node_modules\/\.bin\//g)) add(m[1]);
78
+ }
79
+ return [...dirs].filter((d) => exists(`${d}/package.json`) && !exists(`${d}/node_modules`));
80
+ }
81
+
82
+ // #6094: test-file names in check output. A linear token scan (split on non-path characters, then an anchored test of each
83
+ // basename): the earlier single regex nested quantifiers over overlapping classes and backtracked exponentially on long
84
+ // path-like output, which froze the lane (and the test suite) in a microtask-free spin.
85
+ const TEST_BASENAME_RES = [/^[\w@.-]+\.(?:test|spec)\.[cm]?[jt]sx?$/, /^(?:test_[\w-]+|[\w-]+_test)\.(?:py|go|rb|rs)$/, /^[\w-]+Tests?\.(?:java|kt|cs)$/];
86
+ const MAX_SCAN_CHARS = 512 * 1024, MAX_TOKEN_CHARS = 400;
87
+ function testFilesNamed(output) {
88
+ const text = String(output ?? "");
89
+ const out = new Set();
90
+ for (const raw of (text.length > MAX_SCAN_CHARS ? text.slice(-MAX_SCAN_CHARS) : text).split(/[^\w@./-]+/)) {
91
+ if (!raw || raw.length > MAX_TOKEN_CHARS) continue;
92
+ const tok = raw.replace(/^[./]+(?=[\w@])/, "").replace(/[.]+$/, "");
93
+ const slash = tok.lastIndexOf("/");
94
+ const base = slash < 0 ? tok : tok.slice(slash + 1);
95
+ if (base && TEST_BASENAME_RES.some((re) => re.test(base))) out.add(tok);
96
+ }
97
+ return [...out];
98
+ }
99
+
100
+ /**
101
+ * #6094: a failing check whose output names test files and none of them is in the diff is not caused by the change: the lane
102
+ * reruns it once before treating it as red. Returns false when the output names no test file (cannot tell: not unrelated).
103
+ * @param {string} output
104
+ * @param {string[]} changed files the lane's diff touches
105
+ */
106
+ export function failureOutsideDiff(output, changed = []) {
107
+ const named = testFilesNamed(output);
108
+ if (!named.length) return false;
109
+ const touched = (p) => changed.some((c) => c === p || c.endsWith(`/${p}`) || p.endsWith(`/${c}`) || c.split("/").pop() === p.split("/").pop());
110
+ return !named.some(touched);
111
+ }
@@ -0,0 +1,64 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: BUSL-1.1
3
+ import { describe, it } from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import { baseMergeOnlyBlock, envGapBlockCode, toolGapFailures, packageDirsMissingDeps, failureOutsideDiff } from "./envgap.mjs";
6
+
7
+ describe("#6106 env gap classification", () => {
8
+ it("a check that fails on a PATH pass-through wrapper with no real binary is a tool gap", () => {
9
+ const out = "forgedock heavy: eslint at /w/web/node_modules/.bin/eslint is a PATH pass-through wrapper with no real binary behind it";
10
+ assert.equal(toolGapFailures([{ command: "cd web && eslint .", rc: 127, output: out }, { command: "node --test", rc: 1, output: "not ok 1 - assertion" }]).length, 1);
11
+ assert.equal(toolGapFailures([{ command: "x", rc: 1, output: "AssertionError: expected 1 to equal 2" }]).length, 0);
12
+ });
13
+ it("block reasons naming a missing tool/interpreter/recipe/sandbox capability map to env codes", () => {
14
+ assert.equal(envGapBlockCode("product-decision", "the yaml lane-tools recipe lives in the engine"), "env.tool_missing");
15
+ assert.equal(envGapBlockCode("credentials", "no Python 3.11 interpreter (only 3.12.3)"), "env.tool_missing");
16
+ assert.equal(envGapBlockCode("credentials", "the sandbox lacks network access to the registry"), "env.capability_remote");
17
+ });
18
+ it("genuine human reasons stay human", () => {
19
+ assert.equal(envGapBlockCode("product-decision", "needs Stripe approval"), null);
20
+ assert.equal(envGapBlockCode("credentials", "no docker credentials: need the registry token"), null);
21
+ assert.equal(envGapBlockCode("product-decision", "which option should the product take?"), null);
22
+ assert.equal(envGapBlockCode("approval", "no interpreter"), null);
23
+ });
24
+ it("package dirs the checks touch that have a manifest but no node_modules are found", () => {
25
+ const have = new Set(["web/package.json", "api/package.json", "api/node_modules"]);
26
+ const exists = (p) => have.has(p);
27
+ assert.deepEqual(packageDirsMissingDeps(["cd web && npx eslint .", "cd api && npm test", "node --test"], exists), ["web"]);
28
+ assert.deepEqual(packageDirsMissingDeps(["npm --prefix web run lint"], exists), ["web"]);
29
+ assert.deepEqual(packageDirsMissingDeps(["web/node_modules/.bin/eslint src"], exists), ["web"]);
30
+ assert.deepEqual(packageDirsMissingDeps(["cd ../x && ls"], () => true), []);
31
+ });
32
+ });
33
+
34
+ describe("#6094 failures outside the diff", () => {
35
+ it("names a test file the diff does not touch -> outside; touched or unnamed -> not", () => {
36
+ const out = "not ok 5 - ten concurrent\n location: '/w/bin/tests/mirror-script.test.mjs:48:3'";
37
+ assert.equal(failureOutsideDiff(out, ["bin/lean/release.mjs"]), true);
38
+ assert.equal(failureOutsideDiff(out, ["bin/tests/mirror-script.test.mjs"]), false);
39
+ assert.equal(failureOutsideDiff("make: *** [lint] Error 1", ["a.js"]), false);
40
+ assert.equal(failureOutsideDiff("FAILED tests/test_api.py::t - x", ["web/app.ts"]), true);
41
+ });
42
+ it("scans long path-like output in linear time (the old regex backtracked exponentially and froze the lane)", () => {
43
+ const evil = `${"a/".repeat(20000)}b ${"x.".repeat(20000)}y ${"@-".repeat(20000)}`;
44
+ const t0 = Date.now();
45
+ assert.equal(failureOutsideDiff(evil, ["a.js"]), false);
46
+ assert.equal(failureOutsideDiff(`${evil}\n at /w/src/deep/app.spec.ts:3:1`, ["a.js"]), true);
47
+ assert.ok(Date.now() - t0 < 2000, `took ${Date.now() - t0} ms`);
48
+ });
49
+ it("names Go/Java/py test files and strips ./ prefixes", () => {
50
+ assert.equal(failureOutsideDiff("--- FAIL: TestX (0.00s)\n ./pkg/foo_test.go:12: boom", ["pkg/foo_test.go"]), false);
51
+ assert.equal(failureOutsideDiff("at src/com/x/FooTest.java:9", ["src/Bar.java"]), true);
52
+ });
53
+ });
54
+
55
+ describe("#6137 a base merge into the lane branch is never a human gate", () => {
56
+ it("only-a-base-merge blocks are mechanical; real human reasons stay human", () => {
57
+ assert.equal(baseMergeOnlyBlock("product-decision", "needs a user-approved merge of staging (CLAUDE.md forbids agent git merge)"), true);
58
+ assert.equal(baseMergeOnlyBlock("product-decision", "the branch is behind: please merge main into the lane branch first"), true);
59
+ assert.equal(baseMergeOnlyBlock("product-decision", "needs a user-approved merge of staging, and the Stripe pricing decision from the owner"), false);
60
+ assert.equal(baseMergeOnlyBlock("product-decision", "merge the PR into main and promote to production"), false);
61
+ assert.equal(baseMergeOnlyBlock("credentials", "needs a merge of staging"), false);
62
+ assert.equal(baseMergeOnlyBlock("product-decision", "which pagination style?"), false);
63
+ });
64
+ });
@@ -297,11 +297,14 @@ export function detectNeeds(text, exec = null, { prose = false } = {}) {
297
297
 
298
298
  /**
299
299
  * #5652: may a remote lane that lacks a tool or host capability be re-placed on the dispatching host? An explicit
300
- * `execution.host_fallback` wins; else off when forge.yaml `host.role` is `orchestrator`; else on (existing repos unchanged).
300
+ * `execution.host_fallback` wins; else off when forge.yaml `host.role` is `orchestrator`; else off in `mode: remote` (#5746);
301
+ * else on (hybrid and local unchanged).
301
302
  */
302
- export function hostFallbackAllowed({ hostFallback = null, hostRole = null } = {}) {
303
+ export function hostFallbackAllowed({ hostFallback = null, hostRole = null, mode = null } = {}) {
303
304
  if (typeof hostFallback === "boolean") return hostFallback;
304
- return String(hostRole ?? "").trim().toLowerCase() !== "orchestrator";
305
+ if (String(hostRole ?? "").trim().toLowerCase() === "orchestrator") return false;
306
+ // #5746: in remote mode the host is not a fallback unless the repo opts in with host_fallback: true
307
+ return mode !== "remote";
305
308
  }
306
309
 
307
310
  /** Declared host capabilities a remote lane's block summary names (#4542); empty when it names none the host has. */
@@ -404,7 +407,10 @@ export function placeLane({ exec = null, verifyMode = "local", labels = [], weig
404
407
  const missing = (Array.isArray(needs) ? needs : []).map(String).filter((n) => n && !(Array.isArray(relays) ? relays : []).includes(n));
405
408
  if (missing.length) return { where: "local", reason: `host capability: ${missing.join(", ")}` };
406
409
  }
407
- if (mode !== "hybrid") { const where = placement(exec); return { where, reason: `mode ${EXECUTION_MODES.includes(mode) ? mode : "local"}` }; }
410
+ if (mode !== "hybrid") {
411
+ const where = placement(exec);
412
+ return { where, reason: `mode ${EXECUTION_MODES.includes(mode) ? mode : "local"}` };
413
+ }
408
414
  if (!(Number.isInteger(exec.maxRemote) && exec.maxRemote >= 1)) return { where: "local", reason: "max_remote 0" };
409
415
  if (verifyMode === "ci") return { where: "local", reason: "verify.mode ci: validation runs on CI, not billed twice" };
410
416
  const names = (Array.isArray(labels) ? labels : []).map((l) => String(l ?? "").trim().toLowerCase());
@@ -816,6 +822,9 @@ export function providerLanes({ provider, laneArgs, ledgerFor, env = process.env
816
822
  return ok;
817
823
  },
818
824
  runOne: async (n, lane, ctx = {}) => {
825
+ // #6124: this dispatcher owns the lane now: a suspend marker left by an earlier keep-for-adopt would make the fresh lane
826
+ // refuse its own push ("kept for adopt") on every relaunch, so it is cleared before the lane starts.
827
+ try { await resumeKept?.(n); } catch { /* best effort: the lane fails open on an unreadable state */ }
819
828
  const led = ledgerFor(n);
820
829
  const base = { provider: provider.name, id: provider.idFor(n), issue: n, startedAt: now() };
821
830
  // A sandbox an earlier attempt left behind (same id) goes first, or the new one could not start.
@@ -1409,6 +1409,18 @@ describe("providerLanes: a halted batch keeps its sandbox for adopt (#5669)", ()
1409
1409
  });
1410
1410
  });
1411
1411
 
1412
+ describe("#5746 remote-mode host fallback and max_remote 0", () => {
1413
+ it("hostFallbackAllowed: remote unset false, hybrid true, explicit true wins", () => {
1414
+ assert.equal(hostFallbackAllowed({ mode: "remote" }), false);
1415
+ assert.equal(hostFallbackAllowed({ mode: "hybrid" }), true);
1416
+ assert.equal(hostFallbackAllowed({ mode: "remote", hostFallback: true }), true);
1417
+ });
1418
+ it("placeLane: remote mode with max_remote 0 stays remote (#5933 pauses starts, never the host)", () => {
1419
+ assert.equal(placeLane({ exec: { mode: "remote", maxRemote: 0 } }).where, "remote");
1420
+ assert.equal(placeLane({ exec: { mode: "remote", maxRemote: 2 } }).reason, "mode remote");
1421
+ });
1422
+ });
1423
+
1412
1424
  describe("public-repo default placement (#5748)", () => {
1413
1425
  const OPT = parseExecution({ public_default: "actions" }); // #5900: the actions default is opt-in
1414
1426
  it("actions is a known provider; plan, job_limit, ci_reserve and dispatcher parse", () => {
@@ -1453,3 +1465,24 @@ describe("public-repo default placement (#5748)", () => {
1453
1465
  assert.equal(await repoIsPublic({ repo: null, gh: async () => "{}" }), false);
1454
1466
  });
1455
1467
  });
1468
+
1469
+ describe("providerLanes: a fresh dispatch clears a stale suspend marker (#6124)", () => {
1470
+ it("runOne calls resumeKept before launching, so the new lane does not refuse its own push", async () => {
1471
+ const order = [];
1472
+ const prov = fakeProvider({ finish: () => ({ terminalReason: "merged", pr: 9 }) });
1473
+ const origStart = prov.start;
1474
+ prov.start = async (...a) => { order.push("start"); return origStart(...a); };
1475
+ const lanes = providerLanes({ provider: prov, laneArgs: () => [], ledgerFor: ledgerIn(tmpDir("exec-6124-")), pollMs: 1, now: () => 1000, resumeKept: async (n) => { order.push(`resume:${n}`); } });
1476
+ const r = await lanes.runOne(7, "staging");
1477
+ assert.equal(r.terminalReason, "merged");
1478
+ assert.deepEqual(order.slice(0, 2), ["resume:7", "start"]);
1479
+ await r.postRun?.();
1480
+ });
1481
+ it("a failing resumeKept does not stop the lane", async () => {
1482
+ const prov = fakeProvider({ finish: () => ({ terminalReason: "merged", pr: 9 }) });
1483
+ const lanes = providerLanes({ provider: prov, laneArgs: () => [], ledgerFor: ledgerIn(tmpDir("exec-6124b-")), pollMs: 1, now: () => 1000, resumeKept: async () => { throw new Error("gh down"); } });
1484
+ const r = await lanes.runOne(7, "staging");
1485
+ assert.equal(r.terminalReason, "merged");
1486
+ await r.postRun?.();
1487
+ });
1488
+ });
@@ -0,0 +1,170 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Failure census (2026-11-26): classify why lanes did not take the happy path, from the register itself, so an agent
5
+ * working on a pipeline fix reads measured failure classes instead of guessing. Pure functions only (no I/O): the CLI
6
+ * (scripts/failure-census.mjs) feeds issue comments and batch log rows in.
7
+ *
8
+ * Inputs it understands (all ForgeDock annotations on issues):
9
+ * - FORGE:NEEDS_HUMAN / FORGE:PARKED bodies: one park each, classified into a bucket and normalised failure rows;
10
+ * - FORGE:AMENDMENT-STATE JSON: the last state per issue gives the distinct amendments (kind + why class);
11
+ * - FORGE:BASE_SYNC bodies: conflicted files.
12
+ * Batch log rows (`~/.forge/batches/<id>/log.jsonl`): outcome/code counts and per-phase timing.
13
+ */
14
+
15
+ /** Ordered: the first matching bucket wins. Patterns match the park body (rows and prose). */
16
+ export const PARK_BUCKETS = Object.freeze([
17
+ ["sandbox_tool_gap", /Remote sandbox lacks|lane_tools recipe|sandbox is missing/i],
18
+ ["recurrence_design", /recurrence\.design_missing/],
19
+ ["post_deploy_check_id", /post-deploy check (id|'[^']*') is neither/],
20
+ ["amendment_syntax", /unknown or incomplete amendment|amendment kind '|amendment not accepted/],
21
+ ["substitute_validate", /substituted `|substitute-validate|substitute_unverified/],
22
+ ["deferral", /unjustified_deferral|untracked_deferral|reported "deferred"/],
23
+ ["no_status", /reported "no status"/],
24
+ ["omission_narrowed", /conformance\.omission|requirement narrowed/],
25
+ ["scope_creep", /scope_creep|outside the contract's deliverables/],
26
+ ["validate_failed", /validate [A-Z]?\d+ .*failed|frozen command runs and fails|Declared check command\(s\) failing/],
27
+ ["ci_red", /Required check\(s\) failed|ci\.red|CI verification failed/],
28
+ ["env_setup", /Environment error|env\.(setup_failed|tool_missing|validate_timeout|validate_placement|repro_unrunnable|capability_remote)/],
29
+ ["builder_blocked", /Builder is blocked|builder\.(blocked|no_commit)|Builder made no commit/],
30
+ ["review_incomplete", /review\.(incomplete|failed|unparseable)|Review FAIL/],
31
+ ["e2e_unverified", /e2e_unverified|e2e_placement/],
32
+ ["design_spec", /design\.spec_required|FORGE:DESIGN_SPEC|Design gate/],
33
+ ["contract_invalid", /contract is still invalid|contract\.invalid/],
34
+ ]);
35
+
36
+ /** Bucket of one park body; "other" when no pattern matches. */
37
+ export function parkBucket(body) {
38
+ const b = String(body ?? "");
39
+ for (const [name, re] of PARK_BUCKETS) if (re.test(b)) return name;
40
+ return "other";
41
+ }
42
+
43
+ /** The `- code: detail` rows of a NEEDS_HUMAN/PARKED body, normalised so repeats across issues group together. */
44
+ export function parkRows(body) {
45
+ return String(body ?? "").split("\n").filter((l) => /^- [a-z_]+\.[a-z_]+:/.test(l)).map(normalizeRow);
46
+ }
47
+
48
+ /** Collapse ids, numbers, quotes and code spans so identical defects compare equal. */
49
+ export function normalizeRow(row) {
50
+ return String(row).replace(/^- /, "").replace(/\bR\d+\b/g, "R#").replace(/\b[GV]\d+\b/g, "V#").replace(/#\d+/g, "#N")
51
+ .replace(/`[^`]*`/g, "`…`").replace(/\("[^]*$/, "").replace(/"[^"]{40,}"/g, "\"…\"").replace(/\d+/g, "N").trim().slice(0, 140);
52
+ }
53
+
54
+ const AMENDMENT_STATE_RE = /FORGE:AMENDMENT-STATE (\{.*\}) -->/;
55
+ /** The distinct amendments of the LAST amendment state on an issue (earlier states are replayed into it). */
56
+ export function lastAmendments(comments) {
57
+ let last = null;
58
+ for (const c of comments ?? []) {
59
+ const m = AMENDMENT_STATE_RE.exec(String(c?.body ?? ""));
60
+ if (!m) continue;
61
+ try { last = JSON.parse(m[1]); } catch { /* a malformed state is skipped */ }
62
+ }
63
+ return Array.isArray(last?.amendments) ? last.amendments : [];
64
+ }
65
+
66
+ /** Why-class of one amendment: broken frozen command, post-deploy measurement, naming, or other. */
67
+ export function amendmentWhyClass(a) {
68
+ const w = String(a?.why ?? "");
69
+ if (/on the (unchanged )?base|origin\/staging|fails before|not on the .*path|ModuleNotFound|cannot import|not installed|command not found|timed out|sandbox|lacks/i.test(w)) return "frozen_command_broken_or_env";
70
+ if (/requirement|post-deploy|measur|production|after deploy/i.test(w)) return "post_deploy_or_measurement";
71
+ if (/duplicate|rename|name/i.test(w)) return "naming_or_decision";
72
+ if (/docs freshness|dossier|registry|check id/i.test(w)) return "forced_by_another_gate";
73
+ return "other";
74
+ }
75
+
76
+ /** Conflicted files listed by a FORGE:BASE_SYNC body ("conflicts in `a`, `b`"). */
77
+ export function baseSyncConflicts(body) {
78
+ const m = /\*\*Result:\*\* conflicts in ([^\n]+)/.exec(String(body ?? ""));
79
+ return m ? [...m[1].matchAll(/`([^`]+)`/g)].map((x) => x[1]) : [];
80
+ }
81
+
82
+ const inc = (o, k, by = 1) => { o[k] = (o[k] ?? 0) + by; return o; };
83
+ const top = (o, n) => Object.entries(o).sort((a, b) => b[1] - a[1]).slice(0, n);
84
+
85
+ /**
86
+ * Census over issues: `issues` = [{number, title, comments: [{body, createdAt, author}]}]. Returns plain data:
87
+ * parks by bucket (+ issues), by day x bucket, top normalised rows, repeat parks (identical rows back to back),
88
+ * amendments by kind x why class, conflict hotspots, and the most-parked issues.
89
+ */
90
+ export function censusIssues(issues) {
91
+ const out = { issues: 0, withParks: 0, parks: 0, repeats: 0, buckets: {}, bucketIssues: {}, byDay: {}, rows: {}, amendments: {}, amendmentIssues: {}, conflicts: {}, baseSyncs: 0, mostParked: [] };
92
+ const perIssue = [];
93
+ for (const iss of issues ?? []) {
94
+ out.issues++;
95
+ let parks = 0, prev = null;
96
+ for (const c of iss.comments ?? []) {
97
+ const body = String(c?.body ?? "");
98
+ if (/FORGE:BASE_SYNC/.test(body)) { out.baseSyncs++; for (const f of baseSyncConflicts(body)) inc(out.conflicts, f); }
99
+ if (!/FORGE:(NEEDS_HUMAN|PARKED)/.test(body)) continue;
100
+ const rows = parkRows(body), bucket = parkBucket(body), key = rows.slice().sort().join("|");
101
+ parks++; out.parks++;
102
+ inc(out.buckets, bucket);
103
+ (out.bucketIssues[bucket] ??= new Set()).add(iss.number);
104
+ const day = String(c?.createdAt ?? "").slice(0, 10) || "unknown";
105
+ inc((out.byDay[day] ??= {}), bucket);
106
+ if (prev !== null && rows.length && key === prev) out.repeats++;
107
+ prev = key;
108
+ for (const r of new Set(rows)) inc(out.rows, r);
109
+ }
110
+ for (const a of lastAmendments(iss.comments)) {
111
+ const k = `${a?.kind ?? "?"} :: ${amendmentWhyClass(a)}`;
112
+ inc(out.amendments, k);
113
+ (out.amendmentIssues[k] ??= new Set()).add(iss.number);
114
+ }
115
+ if (parks) { out.withParks++; perIssue.push({ number: iss.number, title: String(iss.title ?? "").slice(0, 80), parks }); }
116
+ }
117
+ out.mostParked = perIssue.sort((a, b) => b.parks - a.parks).slice(0, 15);
118
+ for (const k of ["bucketIssues", "amendmentIssues"]) for (const b of Object.keys(out[k])) out[k][b] = out[k][b].size;
119
+ return out;
120
+ }
121
+
122
+ /** Census over batch log rows ({outcome, code, phases:{name:{ms}}}): outcome/code counts and per-phase median/p90 (merged lanes). */
123
+ export function censusBatchRows(rows) {
124
+ const outcomes = {}, deferred = {}, needsHuman = {}, phases = {};
125
+ for (const r of rows ?? []) {
126
+ if (!r || r.outcome == null) continue;
127
+ inc(outcomes, r.outcome);
128
+ if (r.outcome === "deferred") inc(deferred, r.code ?? "null");
129
+ if (r.outcome === "needs-human") inc(needsHuman, r.code ?? "null");
130
+ if (r.outcome === "merged" && r.phases && typeof r.phases === "object") {
131
+ for (const [k, v] of Object.entries(r.phases)) if (Number.isFinite(v?.ms)) (phases[k] ??= []).push(v.ms);
132
+ }
133
+ }
134
+ const q = (xs, p) => { const s = [...xs].sort((a, b) => a - b); return s.length ? s[Math.min(s.length - 1, Math.floor(s.length * p))] : null; };
135
+ const phaseStats = Object.fromEntries(Object.entries(phases).map(([k, xs]) => [k, { n: xs.length, median_min: Math.round(q(xs, 0.5) / 6000) / 10, p90_min: Math.round(q(xs, 0.9) / 6000) / 10 }]));
136
+ return { outcomes, deferred, needsHuman, phases: phaseStats };
137
+ }
138
+
139
+ /** Markdown report of both censuses. */
140
+ export function renderCensus({ repo, since, issues, batches }) {
141
+ const L = [`# Failure census: ${repo}${since ? ` (since ${since})` : ""}`, ""];
142
+ if (issues) {
143
+ L.push(`Issues scanned: ${issues.issues}; with parks: ${issues.withParks}; parks (NEEDS_HUMAN/PARKED): ${issues.parks}; identical back-to-back repeats: ${issues.repeats}`, "", "## Parks by class", "", "| class | parks | issues |", "|---|---|---|");
144
+ for (const [b, n] of top(issues.buckets, 30)) L.push(`| ${b} | ${n} | ${issues.bucketIssues[b] ?? 0} |`);
145
+ const days = Object.keys(issues.byDay).sort(), cls = top(issues.buckets, 6).map(([b]) => b);
146
+ if (days.length) {
147
+ L.push("", "## Parks per day (top classes)", "", `| day | ${cls.join(" | ")} | other |`, `|---|${cls.map(() => "---").join("|")}|---|`);
148
+ for (const d of days) { const row = issues.byDay[d]; const rest = Object.entries(row).filter(([k]) => !cls.includes(k)).reduce((s, [, v]) => s + v, 0); L.push(`| ${d} | ${cls.map((c) => row[c] ?? 0).join(" | ")} | ${rest} |`); }
149
+ }
150
+ L.push("", "## Most frequent failure rows (normalised)", "", "| count | row |", "|---|---|");
151
+ for (const [r, n] of top(issues.rows, 20)) L.push(`| ${n} | ${r.replace(/\\/g, "\\\\").replace(/\|/g, "\\|")} |`);
152
+ L.push("", "## Amendments (last state per issue): kind :: why class", "", "| amendment | count | issues |", "|---|---|---|");
153
+ for (const [k, n] of top(issues.amendments, 20)) L.push(`| ${k} | ${n} | ${issues.amendmentIssues[k] ?? 0} |`);
154
+ L.push("", `## Base-sync conflict hotspots (${issues.baseSyncs} base syncs)`, "", "| file | conflicts |", "|---|---|");
155
+ for (const [f, n] of top(issues.conflicts, 15)) L.push(`| \`${f}\` | ${n} |`);
156
+ L.push("", "## Most-parked issues", "", "| issue | parks | title |", "|---|---|---|");
157
+ for (const i of issues.mostParked) L.push(`| #${i.number} | ${i.parks} | ${i.title.replace(/\\/g, "\\\\").replace(/\|/g, "\\|")} |`);
158
+ }
159
+ if (batches) {
160
+ L.push("", "## Batch logs", "", "| outcome | rows |", "|---|---|");
161
+ for (const [k, n] of top(batches.outcomes, 15)) L.push(`| ${k} | ${n} |`);
162
+ L.push("", "| deferred code | rows |", "|---|---|");
163
+ for (const [k, n] of top(batches.deferred, 10)) L.push(`| ${k} | ${n} |`);
164
+ L.push("", "| needs-human code | rows |", "|---|---|");
165
+ for (const [k, n] of top(batches.needsHuman, 12)) L.push(`| ${k} | ${n} |`);
166
+ L.push("", "| phase (merged lanes) | n | median min | p90 min |", "|---|---|---|---|");
167
+ for (const [k, v] of Object.entries(batches.phases).sort((a, b) => b[1].median_min - a[1].median_min)) L.push(`| ${k} | ${v.n} | ${v.median_min} | ${v.p90_min} |`);
168
+ }
169
+ return L.join("\n") + "\n";
170
+ }
@@ -0,0 +1,59 @@
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 { parkBucket, parkRows, normalizeRow, lastAmendments, amendmentWhyClass, baseSyncConflicts, censusIssues, censusBatchRows, renderCensus } from "./failure-census.mjs";
6
+
7
+ const nh = (rows, prose = "") => `<!-- FORGE:NEEDS_HUMAN -->\n## Needs human\n${prose}\n${rows.map((r) => `- ${r}`).join("\n")}`;
8
+
9
+ describe("failure census", () => {
10
+ it("buckets parks by the first matching class", () => {
11
+ assert.equal(parkBucket("Remote sandbox lacks yaml, and no lane_tools recipe exists for it."), "sandbox_tool_gap");
12
+ assert.equal(parkBucket(nh(["recurrence.design_missing: recurring issue routed to a design lane: no design block"])), "recurrence_design");
13
+ assert.equal(parkBucket(nh(["conformance.unimplemented: R13 post-deploy check id is neither on the default branch nor added by this PR (.forge/post-deploy-checks.json)"])), "post_deploy_check_id");
14
+ assert.equal(parkBucket(nh(["conformance.unimplemented: unknown or incomplete amendment: amendment kind 'supersedes' needs guard"])), "amendment_syntax");
15
+ assert.equal(parkBucket(nh(['conformance.unimplemented: R4 reported "no status" ("x")'])), "no_status");
16
+ assert.equal(parkBucket("Required check(s) failed on PR #6011 (Spec-size budget) and the builder made no new commit for it"), "ci_red");
17
+ assert.equal(parkBucket("something new"), "other");
18
+ });
19
+ it("normalises rows so the same defect on different issues groups together", () => {
20
+ const a = normalizeRow('- conformance.unimplemented: R13 post-deploy check id is neither on the default branch nor added by this PR (.forge/post-deploy-checks.json) ("quote one")');
21
+ const b = normalizeRow('- conformance.unimplemented: R7 post-deploy check id is neither on the default branch nor added by this PR (.forge/post-deploy-checks.json) ("another")');
22
+ assert.equal(a, b);
23
+ assert.deepEqual(parkRows(nh(["a.b: one", "c.d: two"], "prose line")).length, 2);
24
+ });
25
+ it("uses only the last amendment state and classifies why", () => {
26
+ const st = (am) => ({ body: `<!-- FORGE:AMENDMENT-STATE ${JSON.stringify({ contract: "x", amendments: am })} -->` });
27
+ const am = lastAmendments([st([{ kind: "decision", why: "rename" }]), { body: "noise" }, st([{ kind: "substitute-validate", why: "fails on the unchanged base too" }, { kind: "add-deliverable", path: "devdocs/x.md", why: "docs freshness rule" }])]);
28
+ assert.deepEqual(am.map((a) => a.kind), ["substitute-validate", "add-deliverable"]);
29
+ assert.equal(amendmentWhyClass(am[0]), "frozen_command_broken_or_env");
30
+ assert.equal(amendmentWhyClass(am[1]), "forced_by_another_gate");
31
+ assert.deepEqual(lastAmendments([{ body: "<!-- FORGE:AMENDMENT-STATE {broken -->" }]), []);
32
+ });
33
+ it("reads base-sync conflict files", () => {
34
+ assert.deepEqual(baseSyncConflicts("## Base Sync\n**Result:** conflicts in `devdocs/modules/lean.md`, `.forge/post-deploy-checks.json`\n"), ["devdocs/modules/lean.md", ".forge/post-deploy-checks.json"]);
35
+ assert.deepEqual(baseSyncConflicts("**Result:** clean merge"), []);
36
+ });
37
+ it("counts parks, identical back-to-back repeats, amendments and hotspots per issue", () => {
38
+ const row = "conformance.unimplemented: unknown or incomplete amendment: amendment kind 'supersedes' needs guard";
39
+ const c = censusIssues([
40
+ { number: 1, title: "one", comments: [{ body: nh([row]), createdAt: "2026-11-24T01:00:00Z" }, { body: nh([row]), createdAt: "2026-11-24T02:00:00Z" }, { body: "<!-- FORGE:BASE_SYNC -->\n## Base Sync\n**Result:** conflicts in `a.md`" }] },
41
+ { number: 2, title: "two", comments: [{ body: nh([], "Remote sandbox lacks bash, and no lane_tools recipe exists for it."), createdAt: "2026-11-25T01:00:00Z" }] },
42
+ { number: 3, title: "clean", comments: [{ body: "hello" }] },
43
+ ]);
44
+ assert.equal(c.issues, 3); assert.equal(c.withParks, 2); assert.equal(c.parks, 3); assert.equal(c.repeats, 1);
45
+ assert.equal(c.buckets.amendment_syntax, 2); assert.equal(c.bucketIssues.amendment_syntax, 1);
46
+ assert.equal(c.byDay["2026-11-25"].sandbox_tool_gap, 1);
47
+ assert.equal(c.conflicts["a.md"], 1); assert.equal(c.mostParked[0].number, 1);
48
+ assert.match(renderCensus({ repo: "o/r", issues: c }), /\| amendment_syntax \| 2 \| 1 \|/);
49
+ });
50
+ it("summarises batch rows: outcomes, deferral codes and merged-lane phase timing", () => {
51
+ const b = censusBatchRows([
52
+ { outcome: "merged", phases: { implement: { ms: 300000 }, ci_wait: { ms: 600000 } } },
53
+ { outcome: "merged", phases: { implement: { ms: 420000 } } },
54
+ { outcome: "deferred", code: "sandbox.capacity" }, { outcome: "needs-human", code: "ci.red" }, { issue: 1 },
55
+ ]);
56
+ assert.equal(b.outcomes.merged, 2); assert.equal(b.deferred["sandbox.capacity"], 1); assert.equal(b.needsHuman["ci.red"], 1);
57
+ assert.equal(b.phases.implement.n, 2); assert.equal(b.phases.ci_wait.median_min, 10);
58
+ });
59
+ });
@@ -26,11 +26,22 @@ export function repeatSignature(code, detail) {
26
26
  return createHash("sha256").update(`${code ?? ""}\n${normalizeDetail(detail)}`).digest("hex").slice(0, 12);
27
27
  }
28
28
 
29
- /** Earlier trusted NEEDS_HUMAN/PARKED comments carrying `sig=<hash>`. A PARKED summary counts as the failure it parked on. */
29
+ const DECISION_RE = /<!--\s*FORGE:DECISION(?![A-Za-z0-9_])/;
30
+ const PREMISE_DECISION_RE = /^\s*(?:<!--[^>]*-->\s*)?##\s*Decision:\s*no needs-human/i;
31
+
32
+ /** #6122: a trusted operator/builder FORGE:DECISION (not the engine's own "no needs-human" premise note) is new input for the lane. */
33
+ export const isResetDecision = (body) => DECISION_RE.test(String(body ?? "")) && !PREMISE_DECISION_RE.test(String(body ?? "").replace(DECISION_RE, "").replace(/^\s*(?:-->)?/, ""));
34
+
35
+ /**
36
+ * Earlier trusted NEEDS_HUMAN/PARKED comments carrying `sig=<hash>`. A PARKED summary counts as the failure it parked on.
37
+ * #6122: comments are chronological; a trusted FORGE:DECISION newer than a park resets the count (the decision is applied on the
38
+ * next run, so the repeat is no longer "the same input"), only failures after the last decision count.
39
+ */
30
40
  export function countIdentical(comments, sig, trusted = () => true) {
31
41
  let n = 0;
32
42
  for (const c of Array.isArray(comments) ? comments : []) {
33
43
  const body = String(c?.body ?? "");
44
+ if (isResetDecision(body) && trusted(c)) { n = 0; continue; }
34
45
  if (MARKER_RE.test(body) && SIG_RE.exec(body)?.[1] === sig && trusted(c)) n++;
35
46
  }
36
47
  return n;
@@ -2,7 +2,7 @@
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  import { describe, it } from "node:test";
4
4
  import assert from "node:assert/strict";
5
- import { repeatSignature, countIdentical, shouldPark, summaryComment } from "./failure-stop.mjs";
5
+ import { repeatSignature, countIdentical, isResetDecision, shouldPark, summaryComment } from "./failure-stop.mjs";
6
6
  import { OUTCOME_CODES, RECOVERABLE_CODES, classifyNeedsHuman, parkedLabel } from "../engine/outcome-codes.mjs";
7
7
 
8
8
  const D1 = "R3 unimplemented at 1e0c3e45 (cost $1.2345, 12 turns) 2026-11-25T10:00:00Z";
@@ -27,6 +27,19 @@ describe("identical-failure stop (#5979)", () => {
27
27
  assert.equal(countIdentical([{ body: `sig=${sig}` }], sig), 0);
28
28
  assert.equal(countIdentical([{ body: `<!-- FORGE:PARKED -->\nsig=${sig}` }], sig), 1);
29
29
  });
30
+ it("#6122 a FORGE:DECISION newer than the last park resets the repeat count; one before it does not; the engine's own premise note never does", () => {
31
+ const sig = repeatSignature("builder.blocked", "R4 manual");
32
+ const dec = { body: `<!-- FORGE:DECISION {"requirement":"R4","disposition":"post-deploy","quote":"x"} -->` };
33
+ const premise = { body: "<!-- FORGE:DECISION -->\n## Decision: no needs-human\nx" };
34
+ assert.equal(isResetDecision(dec.body), true);
35
+ assert.equal(isResetDecision(premise.body), false);
36
+ assert.equal(shouldPark(countIdentical([nh(sig), dec], sig) + 1), false, "decision after the park: the next failure is a first");
37
+ assert.equal(shouldPark(countIdentical([dec, nh(sig)], sig) + 1), true, "decision before the park does not clear it");
38
+ assert.equal(shouldPark(countIdentical([nh(sig), premise], sig) + 1), true);
39
+ assert.equal(shouldPark(countIdentical([nh(sig), dec, nh(sig)], sig) + 1), true, "an identical failure after the decision still parks");
40
+ assert.equal(countIdentical([nh(sig), dec], sig, () => false), 0);
41
+ assert.equal(shouldPark(countIdentical([nh(sig), dec], sig, (c) => c !== dec) + 1), true, "an untrusted decision does not reset");
42
+ });
30
43
  it("the summary names the attempts, the failure and what would unblock it", () => {
31
44
  const s = summaryComment({ attempts: 2, code: "ci.red", detail: "boom", unblock: "decide X", sig: "abcabcabcabc" });
32
45
  assert.match(s, /2 lane runs/);
@@ -83,10 +83,9 @@ test("an accepted supersedes amendment passes the precheck and names the superse
83
83
  assert.deepEqual(supersededIds(a.contract, []), [], "only selected guards are retired");
84
84
  });
85
85
 
86
- test("a supersedes amendment without a guard id is rejected", () => {
86
+ test("a supersedes amendment without a guard id is not applied (#6083)", () => {
87
87
  const a = applyAmendments({ requirements: [], deliverables: [] }, [{ kind: "supersedes", why: "x" }, { kind: "supersedes", guard: "abc", why: "x" }]);
88
- assert.equal(a.problems.length, 2);
89
- assert.match(a.problems[0], /needs guard/);
88
+ assert.deepEqual(a.contract.supersedes ?? [], []);
90
89
  });
91
90
 
92
91
  test("a lane touching no guarded hunk selects nothing and runs no git or test", async () => {