forgedock 1.63.0 → 1.65.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 (89) hide show
  1. package/bin/config-schema.mjs +3 -0
  2. package/bin/engine/outcome-codes.mjs +5 -0
  3. package/bin/engine-cli.mjs +88 -12
  4. package/bin/env/cli.mjs +18 -1
  5. package/bin/lean/basered.mjs +56 -11
  6. package/bin/lean/basered.test.mjs +58 -5
  7. package/bin/lean/batch-health.mjs +46 -4
  8. package/bin/lean/batch-health.test.mjs +55 -1
  9. package/bin/lean/batch.mjs +8 -1
  10. package/bin/lean/batch.test.mjs +71 -6
  11. package/bin/lean/ceiling.mjs +47 -3
  12. package/bin/lean/ceiling.test.mjs +32 -1
  13. package/bin/lean/clear-breaker.mjs +15 -0
  14. package/bin/lean/clear-breaker.test.mjs +100 -0
  15. package/bin/lean/conformance.e2e.test.mjs +32 -6
  16. package/bin/lean/conformance.mjs +57 -13
  17. package/bin/lean/conformance.test.mjs +93 -1
  18. package/bin/lean/execution.mjs +18 -8
  19. package/bin/lean/execution.test.mjs +44 -3
  20. package/bin/lean/issuewatch-reconcile.mjs +2 -0
  21. package/bin/lean/issuewatch-reconcile.test.mjs +25 -0
  22. package/bin/lean/issuewatch.mjs +3 -0
  23. package/bin/lean/lanecheck.test.mjs +13 -1
  24. package/bin/lean/lean.mjs +157 -28
  25. package/bin/lean/lean.test.mjs +289 -21
  26. package/bin/lean/live-execution.mjs +25 -0
  27. package/bin/lean/live-execution.test.mjs +35 -1
  28. package/bin/lean/merged-park.mjs +76 -0
  29. package/bin/lean/merged-park.test.mjs +64 -0
  30. package/bin/lean/mergetrain.mjs +357 -0
  31. package/bin/lean/mergetrain.test.mjs +348 -0
  32. package/bin/lean/mirror-bundle.mjs +84 -0
  33. package/bin/lean/orchestrate-envhold.test.mjs +62 -0
  34. package/bin/lean/orchestrate-stacking.test.mjs +23 -1
  35. package/bin/lean/orchestrate-train.test.mjs +130 -0
  36. package/bin/lean/orchestrate-transient-git.test.mjs +53 -0
  37. package/bin/lean/orchestrate.mjs +170 -13
  38. package/bin/lean/prompts.mjs +4 -3
  39. package/bin/lean/release-review.mjs +8 -1
  40. package/bin/lean/release-review.test.mjs +42 -2
  41. package/bin/lean/release-status.test.mjs +53 -1
  42. package/bin/lean/release.mjs +6 -3
  43. package/bin/lean/render.mjs +6 -1
  44. package/bin/lean/sandbox-provider.contract.test.mjs +6 -0
  45. package/bin/lean/sandbox-remote.mjs +43 -3
  46. package/bin/lean/sched.mjs +19 -2
  47. package/bin/lean/sched.test.mjs +33 -1
  48. package/bin/lean/schedd-health.mjs +2 -1
  49. package/bin/lean/schedd-health.test.mjs +7 -0
  50. package/bin/lean/schedd.mjs +58 -7
  51. package/bin/lean/schedd.test.mjs +78 -1
  52. package/bin/lean/stacking.mjs +45 -0
  53. package/bin/lean/stacking.test.mjs +25 -1
  54. package/bin/lean/statuscomment.mjs +14 -8
  55. package/bin/lean/statuscomment.test.mjs +18 -1
  56. package/bin/lean/validate-catalog.mjs +1 -1
  57. package/bin/lean/validate-catalog.test.mjs +3 -0
  58. package/bin/lean/worktree.mjs +8 -3
  59. package/bin/lean/worktree.test.mjs +18 -0
  60. package/bin/pool/agent.mjs +309 -33
  61. package/bin/pool/cache-sweep.mjs +4 -2
  62. package/bin/pool/cli.mjs +125 -6
  63. package/bin/pool/disk.mjs +43 -0
  64. package/bin/pool/docker.mjs +11 -0
  65. package/bin/pool/health.mjs +95 -0
  66. package/bin/pool/mirror-seed.mjs +103 -0
  67. package/bin/pool/router.mjs +301 -27
  68. package/bin/runner.mjs +3 -1
  69. package/bin/stats/chains.mjs +101 -0
  70. package/bin/stats/chains.test.mjs +53 -0
  71. package/bin/stats/efficiency.mjs +7 -6
  72. package/bin/stats/efficiency.test.mjs +48 -7
  73. package/bin/stats/index.mjs +11 -3
  74. package/bin/stats/stats.test.mjs +9 -0
  75. package/docs/CONFIG.md +8 -1
  76. package/docs/OUTCOME-CODES.md +4 -0
  77. package/package.json +1 -1
  78. package/pool/README.md +10 -0
  79. package/pool/image/Dockerfile +2 -1
  80. package/pool/image/entrypoint.sh +25 -6
  81. package/pool/image/mirror.sh +71 -0
  82. package/pool/install/install-agent-linux.sh +57 -5
  83. package/pool/install/install-agent-macos.sh +148 -0
  84. package/pool/install/install-agent.ps1 +11 -0
  85. package/pool/install/install-agent.sh +59 -7
  86. package/pool/install/uninstall-agent-linux.sh +75 -0
  87. package/pool/install/uninstall-agent-macos.sh +60 -0
  88. package/pool/install/uninstall-agent.ps1 +1 -0
  89. package/scripts/transition-label.sh +11 -0
@@ -67,7 +67,7 @@ function makeWorld(dir, script) {
67
67
  git(["add", "-A"], repo); git(["commit", "-q", "-m", "base"], repo);
68
68
  git(["push", "-q", "origin", "main"], repo); git(["push", "-q", "origin", "main:staging"], repo); git(["fetch", "-q", "origin"], repo);
69
69
  git(["clone", "-q", origin, merger], dir);
70
- const gh = { issues: { 101: { ...ISSUE, state: "OPEN", reason: null, labels: new Set(), comments: [] } }, next: 200, prs: [] };
70
+ const gh = { issues: { 101: { ...(script.issue ?? ISSUE), state: "OPEN", reason: null, labels: new Set(), comments: [] } }, next: 200, prs: [] };
71
71
  const counts = { builder: 0, reviewer: 0 };
72
72
  const tools = (wt) => ({
73
73
  write: (files) => writeAll(wt, files),
@@ -144,7 +144,7 @@ function builderScript(cs) {
144
144
  };
145
145
  }
146
146
  /** A diligent reviewer made deterministic: every row comes from the worktree the engine handed it. */
147
- function oracle(c) {
147
+ function oracle(c, quotes = Q) {
148
148
  const between = (tag) => c.prompt.split(`<${tag}>\n`)[1].split(`\n</${tag}>`)[0];
149
149
  const k = JSON.parse(between("contract")), files = between("changed_files").split("\n").filter(Boolean);
150
150
  const read = (p) => { try { return fs.readFileSync(path.join(c.cwd, p), "utf8"); } catch { return ""; } };
@@ -158,9 +158,11 @@ function oracle(c) {
158
158
  });
159
159
  const covered = (q) => k.requirements.some((r) => r.quote === q) || k.preserve.some((p) => p.what.includes(q));
160
160
  const billing = git(["diff", "--name-only", "origin/staging...HEAD", "--", "src/billing.js"], c.cwd).trim() !== "";
161
- const rv = { issue_coverage: Object.values(Q).map((q) => ({ quote: q, status: covered(q) ? "covered" : "missing" })), requirements: rows,
161
+ const rv = { issue_coverage: Object.values(quotes).map((q) => ({ quote: q, status: covered(q) ? "covered" : "missing" })), requirements: rows,
162
162
  scope: files.map((f) => ({ file: f, authorized_by: k.deliverables.find((d) => d.path === f)?.id ?? (f.startsWith("test/") ? "test" : "none") })),
163
- preserve: [{ id: "P1", status: billing ? "violated" : "intact", evidence: "src/billing.js:1" }, { id: "P2", status: "intact", evidence: "test/routes.test.js:1" }], regressions: [] };
163
+ preserve: [{ id: "P1", status: billing ? "violated" : "intact", evidence: "src/billing.js:1" }, { id: "P2", status: "intact", evidence: "test/routes.test.js:1" },
164
+ // history rows (H#) come from the host-wide ~/.forge/guards cache other test files write to; this repo has no such history
165
+ ...k.preserve.filter((p) => /^H\d+$/.test(p.id)).map((p) => ({ id: p.id, status: "intact", evidence: "src/billing.js:1" }))], regressions: [] };
164
166
  const bad = rv.issue_coverage.some((x) => x.status !== "covered") || rows.some((r) => ["missing", "partial"].includes(r.status)) || rv.scope.some((s) => s.authorized_by === "none") || billing;
165
167
  return "```json\n" + JSON.stringify({ ...rv, verdict: bad ? "NONCONFORMING" : "CONFORMS", summary: "oracle" }) + "\n```";
166
168
  }
@@ -168,7 +170,7 @@ const generic = () => "```json\n" + JSON.stringify({ verdict: "PASS", fixes_issu
168
170
 
169
171
  async function runCase(cs, conformance = "enforce", extra = {}) {
170
172
  const dir = tmpDir("conf-e2e-");
171
- const w = makeWorld(dir, { builder: builderScript(cs), reviewer: (n, c) => (cs.generic ? generic() : oracle(c)) });
173
+ const w = makeWorld(dir, { builder: builderScript(cs), reviewer: (n, c) => (cs.generic ? generic() : oracle(c, cs.quotes)), issue: cs.issue });
172
174
  if (extra.runCommand) w.io.runCommand = extra.runCommand;
173
175
  const ret = await runCore({ issue: 101, repo: "o/r", lane: "staging", cwd: w.repo, worktreeRoot: path.join(dir, "wt"), dir: path.join(dir, "runs"), io: w.io, random: () => 0.5, stableMs: 0, livePollMs: 20, conformance, ...(extra.opts ?? {}) });
174
176
  return { ...w.observe(ret), log: readLog(path.join(dir, "runs"), 101, { repo: "o/r" }) }; // #4432: keyed by repo
@@ -262,7 +264,7 @@ describe("conformance gate end-to-end (real git, disposable repo)", { skip: !HAV
262
264
  it("#5087 a declared topology.route_reachability that rejects the new route blocks before merge (#38241 fixture)", async () => {
263
265
  const ingress = path.join(tmpDir("ingress-"), "check-ingress.sh");
264
266
  fs.writeFileSync(ingress, "for p in \"$@\"; do case \"$p\" in /api/v1/batch*) ;; /api/v1/*) echo \"unreachable: $p -> api\" >&2; exit 1 ;; esac; done\n");
265
- const o = await runCase({ contract: ROUTED, impl: addRoute }, "enforce", { runCommand: runCheckCommand, opts: { routeReachability: `bash ${ingress}`, verify: { maxRounds: 0 } } });
267
+ const o = await runCase({ contract: ROUTED, impl: addRoute }, "enforce", { runCommand: runCheckCommand, opts: { routeReachability: `bash ${ingress.replace(/\\/g, "/")}`, verify: { maxRounds: 0 } } });
266
268
  assert.equal(o.staging.search, false, "staging untouched");
267
269
  assert.equal(o.ret.terminalReason, "needs-human"); assert.equal(o.pr, undefined, "no PR");
268
270
  assert.ok(o.log.some((e) => e.event === "PRECHECK" && e.failures.includes("conformance.unimplemented")));
@@ -275,6 +277,30 @@ describe("conformance gate end-to-end (real git, disposable repo)", { skip: !HAV
275
277
  assert.ok(o.log.some((e) => e.event === "PRECHECK" && e.failures.includes("conformance.unimplemented")));
276
278
  assert.match(o.ret.detail, /topology\.prod_parity/);
277
279
  });
280
+ // #5750: a symptom plus a prescribed fix: the outcome rows bind, the prescription is guidance
281
+ const GQ = { R1: "Outstanding reservations return to 0 after a 429 on the scrape route.", R2: "Catch the rate limiter error in the scrape route and return an empty result.", AC3: Q.AC3 };
282
+ const GISSUE = { ...ISSUE, title: "429 leaks the scrape spend reservation", body: `## Problem\nWhen the rate limiter rejects a request with 429, the scrape route never releases the spend reservation.\n\n## Proposed fix\n${GQ.R2}\n\n## Acceptance\n- ${GQ.R1}\n- ${GQ.AC3}` };
283
+ const GUIDED = () => ({ requirements: [{ id: "R1", quote: GQ.R1, disposition: "deliver" }, { id: "R2", quote: GQ.R2, disposition: "guidance", why: "adapt: release the reservation and re-throw the 429 instead; an empty result hides the limit from the caller" }],
284
+ deliverables: [D.R1, D.R5], preserve: [{ id: "P1", what: `${Q.AC3} (src/billing.js price())` }, { id: "P2", what: `${Q.AC2} (test/routes.test.js)` }], validate: [{ id: "V1", command: V1 }] });
285
+ const prescribed = route("scrape", false).replace(" check(req.user, limits);", " try {\n check(req.user, limits);\n } catch (e) {\n if (e.status === 429) return { ok: false, scrape: [] };\n throw e;\n }");
286
+ it("#5750 the frozen contract binds the outcome and records the prescription as guidance", async () => {
287
+ const o = await runCase({ issue: GISSUE, quotes: GQ, contract: GUIDED, impl: (t) => fix(t, ["scrape"]) });
288
+ const posted = o.issue.comments.find((x) => x.includes("FORGE:CONTRACT")) ?? "";
289
+ assert.match(posted, /guidance/);
290
+ merged(o); assert.equal(o.ret.terminalReason, "merged");
291
+ });
292
+ it("#5750 a lane meeting the outcome with a different fix passes", async () => {
293
+ const o = await runCase({ issue: GISSUE, quotes: GQ, contract: GUIDED, impl: (t) => fix(t, ["scrape"]) });
294
+ merged(o);
295
+ const review = o.issue.comments.find((x) => x.includes("FORGE:REVIEW")) ?? "";
296
+ assert.ok(review.includes("| R2 | guidance (non-binding): adapt: release the reservation"), "the guidance row shows its stance and reason");
297
+ assert.ok(review.includes("**Issue coverage:** 2/2 "), "the guidance row is not counted as an issue requirement");
298
+ });
299
+ it("#5750 a lane following the prescription but missing the outcome fails", async () => {
300
+ const o = await runCase({ issue: GISSUE, quotes: GQ, contract: GUIDED, impl: (t) => t.write({ "src/routes/scrape.js": prescribed, "test/leak.test.js": leakTest([]) }) });
301
+ assert.equal(o.ret.terminalReason, "needs-human"); assert.equal(o.pr, undefined, "no PR"); assert.equal(o.issue.state, "OPEN");
302
+ assert.equal(o.ret.code, "conformance.unimplemented");
303
+ });
278
304
  it("6 a generic PASS over an incomplete implementation never merges (review.incomplete)", async () => {
279
305
  const o = await runCase({ contract: FULL, impl: (t) => fix(t, ["scrape", "export"]), generic: true });
280
306
  blocked(o, "review.incomplete"); assert.deepEqual([o.counts.builder, o.counts.reviewer], [2, 2]);
@@ -16,7 +16,18 @@ import { activationFailures } from "./activation.mjs";
16
16
  import * as nodeFs from "node:fs";
17
17
  import { tmpdir } from "node:os";
18
18
 
19
- export const DISPOSITIONS = Object.freeze(["deliver", "defer", "not-applicable", "post-deploy"]);
19
+ export const DISPOSITIONS = Object.freeze(["deliver", "defer", "not-applicable", "post-deploy", "guidance"]);
20
+ /** #5750: a proposed change the issue prescribes: non-binding; the builder follows, adapts or rejects it with a reason. Conformance judges the outcome rows only. */
21
+ export const GUIDANCE = Object.freeze(["guidance"]);
22
+ /** #5750: the outcome rows a contract binds the lane to; a contract with guidance rows keeps at least one. */
23
+ export const BINDING = Object.freeze(["deliver", "defer", "post-deploy"]);
24
+ const STANCE_RE = /\b(follow|adapt|reject)(?:s|ed|ing)?\b/i;
25
+ /** #5750: the planned stance (follow|adapt|reject) of a guidance row's why, or null when the why names none or gives no reason. */
26
+ export const guidanceStance = (why) => {
27
+ const m = STANCE_RE.exec(String(why ?? ""));
28
+ return m && /\w{2,}/.test(String(why).replace(m[0], "")) ? m[1].toLowerCase() : null;
29
+ };
30
+ const isGuidance = (r) => GUIDANCE.includes(r?.disposition);
20
31
  /** Dispositions the engine files as a tracked follow-up issue before anything merges. */
21
32
  export const TRACKED = Object.freeze(["defer", "post-deploy"]);
22
33
  /** forge#4165: where a plan decision's justification comes from; audits filter on lint|precedent. */
@@ -585,6 +596,8 @@ export function validateContract(c, issueText, { repro = false, pages = null, te
585
596
  if (r?.disposition === "post-deploy" && blank(r?.local_infeasible_why)) problems.push(`${id}: post-deploy needs local_infeasible_why: why a fixture or recorded response cannot check this locally (#5448)`);
586
597
  if (r?.disposition === "post-deploy" && (inLaneDeferral(r) || (bucketKind(r?.bucket) !== "owner" && bucketKind(r?.bucket) !== "host" && DEV_WORK_RE.test(String(r?.quote ?? ""))))) problems.push(`${id}: development work (finding or fixing the signal) is delivered in-lane, never deferred as prod-only; deliver it and keep only the measurement post-deploy (#5448)`);
587
598
  if (r?.disposition === "not-applicable" && blank(r?.evidence)) problems.push(`${id}: not-applicable needs file:line evidence`);
599
+ if (isGuidance(r) && !guidanceStance(r?.why)) problems.push(`${id}: guidance needs a why stating the planned stance (follow|adapt|reject) and a reason, e.g. "adapt: the cache lives in the loader, not the route"`);
600
+ if (r?.derived_outcome != null && (r?.disposition !== "deliver" || blank(r.derived_outcome))) problems.push(`${id}: derived_outcome must be a non-empty observable success statement on a deliver row`);
588
601
  for (const m of bucketProblems(r)) problems.push(`${id}: ${m}`);
589
602
  if (r?.class != null && !FOLLOWUP_CLASSES.includes(r.class)) problems.push(`${id}: class must be one of ${FOLLOWUP_CLASSES.join("|")}`);
590
603
  if (r?.verify != null && !VERIFY_MODES.includes(r.verify)) problems.push(`${id}: verify must be one of ${VERIFY_MODES.join("|")}`);
@@ -592,6 +605,7 @@ export function validateContract(c, issueText, { repro = false, pages = null, te
592
605
  else if (isOutOfBand(r) && blank(r?.evidence)) problems.push(`${id}: verify out_of_band needs evidence naming the job or workflow that measures it (or set verify "in_lane" if this change can check it)`);
593
606
  if (r?.disposition === "deliver" && !isOutOfBand(r) && r?.verify !== "in_lane" && TIME_PROD_ONLY_RE.test(String(r?.quote ?? ""))) problems.push(`${id}: the quote needs time or production to observe (${String(r.quote).match(TIME_PROD_ONLY_RE)[0]}); classify it post-deploy (with a check id), defer with a bucket, or verify out_of_band with evidence, never narrow it into a deliver the lane can observe (#5653)`);
594
607
  }
608
+ if (reqs.some(isGuidance) && !reqs.some((r) => BINDING.includes(r?.disposition))) problems.push(`the contract has guidance rows but no binding outcome row (${BINDING.join("|")}); write the symptom or success statement as a deliver row (with derived_outcome when the issue states none), or end needs-human asking for one (#5750)`);
595
609
  if (c.regression != null && !Array.isArray(c.regression)) problems.push("regression must be an array of {id, command, covers}");
596
610
  for (const g of Array.isArray(c.regression) ? c.regression : []) {
597
611
  if (!g?.id || blank(g?.command)) { problems.push(`regression entry without id or command: ${JSON.stringify(g ?? null).slice(0, 80)}`); continue; }
@@ -797,7 +811,8 @@ export function applyAmendments(frozen, amendments, issueText = null, { generate
797
811
  }
798
812
  const r = { disposition: "deliver", ...a.requirement, ...(snapTo ? { quote: snapTo, requoted: a.requirement.quote } : {}), amended: true };
799
813
  if (!DISPOSITIONS.includes(r.disposition)) { problems.push(`add-requirement ${r.id}: bad disposition ${r.disposition}`); continue; }
800
- if (TRACKED.includes(r.disposition) && blank(r.why)) r.why = a.why;
814
+ if ((TRACKED.includes(r.disposition) || isGuidance(r)) && blank(r.why)) r.why = a.why;
815
+ if (isGuidance(r) && !guidanceStance(r.why)) { problems.push(`add-requirement ${r.id}: guidance needs a why stating follow|adapt|reject and a reason`); continue; }
801
816
  if (tagsOutOfBand(r)) r.verify = "out_of_band"; // #4404: same freeze-time tag as the planned requirements
802
817
  c.requirements.push(r);
803
818
  if (TRACKED.includes(r.disposition)) toTrack.push(r);
@@ -943,6 +958,16 @@ export function envProvisioningCommand(command) {
943
958
  }
944
959
  /** #5732: true when a failed run's output carries test-failure text (an assertion, a runner's failed-test mark), not only an environment error. */
945
960
  const ASSERTION_RE = /AssertionError|\bassert(?:ion)?\b[^\n]*(?:==|!=|failed|error)|^FAILED\s+\S+::|^\s*E\s+(?:assert|Expected)|\bExpected\b[^\n]*\b(?:Received|got|to (?:be|equal))|expect\(|^not ok \d+|^\s*[✗×✖]\s|^\s*● |\bTests?:\s+\d+ failed/m;
961
+ // #5730: sandbox-only failures a validate rerun can show beyond ENV_SIGNATURES: a missing command, a refused connection, an unresolved host, an absent venv path, no display
962
+ const VALIDATE_ENV_RE = /: command not found|: not found\b|ECONNREFUSED|connection refused|no such host|\.venv\/bin\/[\w.-]+: No such file or directory|cannot open display|Missing X server|\$DISPLAY/i;
963
+ /** #5730: a validate output that is the executor's environment (not a red test, not a stale artifact): only these defer to a host replay. */
964
+ export function isEnvValidateFailure(output) {
965
+ const out = String(output ?? "");
966
+ if (!out || isDriftFailure(out) || ASSERTION_RE.test(out)) return false;
967
+ return Boolean(envSignature(out)) || VALIDATE_ENV_RE.test(out);
968
+ }
969
+ /** #5730: the redacted last 4000 characters of a rerun's output, kept on a validate_failed failure so the lane can classify it. */
970
+ const rawTail = (output) => String(output ?? "").replace(/\x1b\[[0-9;]*[A-Za-z]/g, "").slice(-4000).replace(SECRET_PAIR_RE, "$1[redacted]").replace(SECRET_SHAPE_RE, "[redacted]");
946
971
  export function assertionFailure(output) {
947
972
  return ASSERTION_RE.test(String(output ?? ""));
948
973
  }
@@ -1140,6 +1165,8 @@ export function interfaceDecisionFailures(contract, result, changedFiles) {
1140
1165
  return out;
1141
1166
  }
1142
1167
 
1168
+ const tagText = (q) => String(q ?? "").replace(/`[^`\n]*`/g, (span, at, all) => (/[^\s.,;:)]/.test(all.slice(at + span.length).replace(/`[^`\n]*\[type:[^`\n]*`/g, "")) ? "" : span));
1169
+ const wantsE2e = (r) => /\[type:(?:e2e|manual)\]/i.test(tagText(r?.quote));
1143
1170
  /**
1144
1171
  * Deterministic checks before any reviewer tokens are spent: unauthorized files, failed or missing validation,
1145
1172
  * requirements not implemented, deferrals without a tracking issue, and unexempted hotspot growth. Returns {ok, failures[], superseded[]}; each failure carries a
@@ -1161,6 +1188,10 @@ export function precheck({ contract, result, changedFiles, ignore = [], ciVerifi
1161
1188
  if (checkIds) for (const r of contract.requirements ?? []) {
1162
1189
  if (r.disposition === "post-deploy" && !(r.check && checkIds.has(r.check))) failures.push({ code: C.CONFORMANCE_UNIMPLEMENTED, kind: "check_unknown", detail: `${r.id} post-deploy check ${r.check ? `'${r.check}'` : "id"} is neither on the default branch nor added by this PR (.forge/post-deploy-checks.json)` });
1163
1190
  }
1191
+ // #5754: a deliver [type:e2e]/[type:manual] row whose observable exists only in production (live stack, deploy, prod window) cannot be produced by the placement: fail fast with a typed code instead of spending builder resumes
1192
+ for (const r of contract.requirements ?? []) {
1193
+ if (r.disposition === "deliver" && wantsE2e(r) && !isOutOfBand(r) && r.verify !== "in_lane" && prodOnlyE2e(r.quote)) failures.push({ code: C.CONFORMANCE_E2E_UNVERIFIED, kind: "e2e_placement", detail: `${r.id} is a [type:e2e]/[type:manual] criterion observable only in production or on the live stack, which this lane cannot produce; mark ${r.id} post-deploy so it is transferred to the epic's acceptance instead of spending builder resumes (#5754)` });
1194
+ }
1164
1195
  // #4769: a default-off rollout entry added by the diff needs an activation row
1165
1196
  if (newOffKeys?.length) for (const f of activationFailures(contract, newOffKeys)) failures.push({ code: C.CONFORMANCE_UNIMPLEMENTED, ...f });
1166
1197
  // #5285: interactive UI changed on a high-risk surface with no real-browser check configured: a recorded skip that blocks
@@ -1183,7 +1214,7 @@ export function precheck({ contract, result, changedFiles, ignore = [], ciVerifi
1183
1214
  if (verdict === "unverified") { failures.push({ code: C.CONFORMANCE_UNIMPLEMENTED, kind: "substitute_unverified", detail: `${from}, but the engine has no rerun of the frozen command to show it cannot run` }); continue; }
1184
1215
  // #5653: the frozen command runs, and the substitute ran the same test ids with the same exit: recorded, not failed
1185
1216
  if (verdict === "runs" && equivalentRuns(substitutedRuns[v.id], substitutedRuns[v.id].sub)) equivalent.push({ id: v.id, from: v.substituted.from, to: v.command });
1186
- else if (verdict === "runs") { failures.push({ code: C.CONFORMANCE_UNIMPLEMENTED, kind: "validate_failed", detail: `${from}, but the frozen command runs and fails (exit ${substitutedRuns[v.id].rc}): a substitute-validate replaces only a command that cannot run, never a failing check${outputTail(substitutedRuns[v.id].output)}` }); continue; }
1217
+ else if (verdict === "runs") { failures.push({ code: C.CONFORMANCE_UNIMPLEMENTED, kind: "validate_failed", output: rawTail(substitutedRuns[v.id].output), detail: `${from}, but the frozen command runs and fails (exit ${substitutedRuns[v.id].rc}): a substitute-validate replaces only a command that cannot run, never a failing check${outputTail(substitutedRuns[v.id].output)}` }); continue; }
1187
1218
  if (verdict === "timeout" && !ciVerified) { failures.push({ code: ENV_VALIDATE_TIMEOUT, kind: "validate_timeout", detail: `${from}, and the frozen command timed out (exit 124) on the engine's rerun, so its substitution cannot be judged: infrastructure (host load)` }); continue; }
1188
1219
  }
1189
1220
  const r = runs.find((x) => x?.id === v.id);
@@ -1209,13 +1240,13 @@ export function precheck({ contract, result, changedFiles, ignore = [], ciVerifi
1209
1240
  if (miss) failures.push({ code: C.ENV_TOOL_MISSING, kind: "validate_env", tool: miss.tool, detail: `validate ${v.id} (\`${v.command}\`) could not run: the host is missing ${KIND_NAME[miss.kind]} '${miss.tool}' (environment, not the change)${outputTail(rerun.output)}` });
1210
1241
  else if (amendedOnly && isScopeCheck(v.command)) superseded.push({ id: v.id, files: amendedOnly });
1211
1242
  else if (rerun && isDriftFailure(rerun.output)) failures.push({ code: C.BASE_CONFLICT, kind: "validate_drift", detail: `validate ${v.id} (\`${v.command}\`) failed on a stale generated artifact (base drift, not the change): base-sync, regenerate the artifact (forge.yaml validate.regenerate) and rerun${outputTail(rerun.output)}` }); // #5653: a mechanical base-sync recovery, not unimplemented work
1212
- else failures.push({ code: C.CONFORMANCE_UNIMPLEMENTED, kind: "validate_failed", detail: `validate ${v.id} (\`${v.command}\`) failed (exit ${engineRun ? rerun.rc : r.exit}${engineRun ? ", run by the engine: no recorded result" : ""})${outputTail(rerun?.output)}` });
1243
+ else failures.push({ code: C.CONFORMANCE_UNIMPLEMENTED, kind: "validate_failed", output: rawTail(rerun?.output), detail: `validate ${v.id} (\`${v.command}\`) failed (exit ${engineRun ? rerun.rc : r.exit}${engineRun ? ", run by the engine: no recorded result" : ""})${outputTail(rerun?.output)}` });
1213
1244
  }
1214
1245
  }
1215
1246
  const st = Array.isArray(result?.requirements) ? result.requirements : [];
1216
1247
  for (const r of contract.requirements ?? []) {
1217
1248
  const s = st.find((x) => x?.id === r.id)?.status;
1218
- if (TRACKED.includes(r.disposition)) continue; // typed deferrals are judged by the reviewer, then filed before the PR
1249
+ if (TRACKED.includes(r.disposition) || isGuidance(r)) continue; // typed deferrals are judged by the reviewer, then filed before the PR; #5750: guidance is non-binding
1219
1250
  if (r.disposition === "deliver" && isOutOfBand(r)) {
1220
1251
  // #4404: measured outside the lane; the builder delivers its instrumentation (budget test or bench committed, job configured)
1221
1252
  const row = st.find((x) => x?.id === r.id);
@@ -1457,7 +1488,10 @@ export function fillEngineRows(rv, { contract, changedFiles = [], repoFiles = []
1457
1488
  });
1458
1489
  }
1459
1490
  if (Array.isArray(rv.requirements)) {
1460
- out.requirements = rv.requirements.map((r) => {
1491
+ // #5750: a guidance row is non-binding; the engine fills it when the reviewer leaves it out
1492
+ const given = [...rv.requirements];
1493
+ for (const g of (contract.requirements ?? []).filter(isGuidance)) if (!given.some((x) => x?.id === g.id)) given.push({ id: g.id, status: "not-applicable", evidence: "", note: "guidance row filled by the engine", filled: true });
1494
+ out.requirements = given.map((r) => {
1461
1495
  if (r?.status !== "implemented" && r?.instrumented !== true) return r;
1462
1496
  const e = evidenceOf(r.evidence, { changedFiles, repoFiles });
1463
1497
  return e ? { ...r, evidence: `${e.path}:${e.line}` } : r;
@@ -1487,6 +1521,7 @@ export function checkCompleteness(rv, { contract, changedFiles, issueText, pathE
1487
1521
  const rows = (reqs ?? []).filter((x) => x?.id === r.id);
1488
1522
  if (rows.length !== 1) { miss(r.id, `requirement ${r.id} needs exactly one row (has ${rows.length})`); continue; }
1489
1523
  const row = rows[0];
1524
+ if (isGuidance(r)) continue; // #5750: non-binding; any status is accepted
1490
1525
  if (!REQ_STATUS.includes(row.status)) { miss(r.id, `${r.id}: status invalid: ${row.status}`); continue; }
1491
1526
  if (TRACKED.includes(r.disposition) && typeof row.deferral_ok !== "boolean") miss(r.id, `${r.id}: a ${r.disposition} requirement needs deferral_ok true|false (is deferring it justified?)`);
1492
1527
  if (isOutOfBand(r) && typeof row.instrumented !== "boolean") miss(r.id, `${r.id}: a requirement verified out of band needs instrumented true|false (is its budget test or bench committed and its job configured?)`);
@@ -1515,8 +1550,6 @@ export function checkCompleteness(rv, { contract, changedFiles, issueText, pathE
1515
1550
 
1516
1551
  /** #4726, #5339: a requirement quote that carries a `[type:e2e]` or `[type:manual]` criterion. */
1517
1552
  /** #5547: a tag inside a mid-sentence code span (`` `[type:e2e]` row whose ... ``) is a mention of the tag, not the tag; a trailing backticked tag still counts. */
1518
- const tagText = (q) => String(q ?? "").replace(/`[^`\n]*`/g, (span, at, all) => (/[^\s.,;:)]/.test(all.slice(at + span.length).replace(/`[^`\n]*\[type:[^`\n]*`/g, "")) ? "" : span));
1519
- const wantsE2e = (r) => /\[type:(?:e2e|manual)\]/i.test(tagText(r?.quote));
1520
1553
  /** #5339: failure kinds enforced without an `engine.conformance_kinds` entry (the entry still overrides). */
1521
1554
  // #5449: test_missing/test_weak are only generated for bug lanes (testadequacy.mjs), so enforcing the kinds is bug-only.
1522
1555
  const DEFAULT_ENFORCED_KINDS = ["e2e_row", "test_missing", "test_weak"];
@@ -1532,12 +1565,14 @@ export function isE2eCommand(command, e2e = null) {
1532
1565
  if (typeof e2e?.isSpec === "function" && cmd.split(/\s+/).some((t) => t && e2e.isSpec(t.replace(/^["']+|["']+$/g, "")))) return true;
1533
1566
  return E2E_CMD_RE.test(cmd);
1534
1567
  }
1568
+ /** #5754: a criterion verified against the running live stack/service/environment/cluster: observable only in production, so post-deploy at freeze instead of builder resumes. Checked after the local-runnable exclusion. */
1569
+ const LIVE_STACK_RE = /\b(?:against|on|in)\s+(?:the\s+)?live\s+(?:stack|service|environment|cluster)\b|\breal traffic\s+(?:against|on)\s+(?:the\s+)?live\b/i;
1535
1570
  /** #5468: a `[type:e2e]`/`[type:manual]` quote whose observable only exists in production (live URL, deploy, prod probe); local stack, browser and sandbox wording is runnable pre-merge. */
1536
1571
  export function prodOnlyE2e(quote) {
1537
1572
  const q = String(quote ?? "");
1538
1573
  if (LIVE_INFRA_RE.test(q)) return true; // #5547
1539
1574
  if (/\b(?:localhost|127\.0\.0\.1|local stack|playwright|browser|sandbox|staging)\b/i.test(q)) return false;
1540
- return /https?:\/\//i.test(q) || /\b(?:after (?:the )?deploy|production|prod probe|live (?:domain|site)|prod)\b/i.test(q) || PROD_WINDOW_RE.test(q);
1575
+ return /https?:\/\//i.test(q) || /\b(?:after (?:the )?deploy|production|prod probe|live (?:domain|site)|prod)\b/i.test(q) || PROD_WINDOW_RE.test(q) || LIVE_STACK_RE.test(q);
1541
1576
  }
1542
1577
  /** #5547: criteria whose run needs a live benchmark, a paid run, remote infra or host-level load: observable only outside the lane, by shape not by repo name. */
1543
1578
  const LIVE_INFRA_RE = /\b(?:live|paid|remote)\s+(?:benchmarks?|runs?|infra(?:structure)?|hosts?)\b|\bbench(?:mark)?[\w.-]*\.(?:mjs|js|py|sh)\b|\bre-?run\b[^.]{0,60}\bbench(?:mark)?\b|\b(?:sandbox pool|(?:remote|rented|cloud|gpu) (?:infra|hosts?|runners?|clusters?|boxe?s?|machines?|gpus?|pool)|on (?:a|the) (?:remote|rented|cloud|gpu) \w+)\b|\bsynthetic load\b|\b\d+\s*[×x]\s*(?:nproc|cores?|cpus?)\b|\bCPU hogs?\b|\bhost[- ]level (?:load|run)\b|\b[≤<]=?\s*[\d.]+\s*[×x]\s*(?:the\s+)?(?:control\s+)?cost\b/i;
@@ -1642,6 +1677,13 @@ export function e2eVerified(row, contract, e2e = null) {
1642
1677
  * | review.inconsistent. failures[] are {code, detail}; `inconsistent` marks a CONFORMS verdict whose rows fail;
1643
1678
  * `missing` lists the ids (or sections) a targeted re-ask must fill; `review` is the reply with the engine-filled rows.
1644
1679
  */
1680
+ /** #5750: an issue_coverage row for a guidance quote only (by contract_ids, else by quote); judged only when flagged misclassified. */
1681
+ function guidanceCoverage(c, contract) {
1682
+ const reqs = contract?.requirements ?? [];
1683
+ const ids = Array.isArray(c?.contract_ids) ? c.contract_ids : [];
1684
+ const named = ids.length ? reqs.filter((r) => ids.includes(r.id)) : reqs.filter((r) => r.quote === c?.quote);
1685
+ return named.length > 0 && named.every(isGuidance);
1686
+ }
1645
1687
  export function decide(raw, ctx) {
1646
1688
  if (!raw) return { state: "review.unparseable", failures: [{ code: C.REVIEW_NO_VERDICT, detail: "no JSON object in the reviewer reply" }] };
1647
1689
  const rv = fillEngineRows(raw, ctx);
@@ -1650,14 +1692,16 @@ export function decide(raw, ctx) {
1650
1692
  const f = [], converted = [];
1651
1693
  const amendedOf = (ids) => (ctx.contract.requirements ?? []).find((r) => r.amendment?.text && (ids ?? []).includes(r.id));
1652
1694
  const notAccepted = (r) => (r ? `amendment not accepted (${r.id} amended to "${String(r.amendment.text).slice(0, 200)}"): ` : "");
1653
- for (const c of rv.issue_coverage) if (c.status !== "covered") f.push({ code: C.CONFORMANCE_OMISSION, detail: `${notAccepted(amendedOf(c.contract_ids))}issue requirement ${c.status}: "${c.quote}"${c.note ? ` (${c.note})` : ""}` });
1695
+ for (const c of rv.issue_coverage) if (c.misclassified === true) f.push({ code: C.CONFORMANCE_OMISSION, detail: `guidance row misclassified: "${c.quote}" is a symptom or success criterion, judge it as binding${c.note ? ` (${c.note})` : ""}` });
1696
+ else if (c.status !== "covered" && !guidanceCoverage(c, ctx.contract)) f.push({ code: C.CONFORMANCE_OMISSION, detail: `${notAccepted(amendedOf(c.contract_ids))}issue requirement ${c.status}: "${c.quote}"${c.note ? ` (${c.note})` : ""}` });
1654
1697
  for (const r of ctx.contract.requirements) {
1698
+ if (isGuidance(r)) continue; // #5750: the outcome rows are judged, never whether the proposal was followed
1655
1699
  const row = rv.requirements.find((x) => x.id === r.id);
1656
1700
  if (r.disposition === "deliver" && isOutOfBand(r)) {
1657
1701
  // #4404: the measured result lives in the named job; only the instrumentation is judged here
1658
1702
  if (row.instrumented !== true) f.push({ code: C.CONFORMANCE_UNIMPLEMENTED, detail: `${r.id} verified out of band${r.evidence ? ` by ${r.evidence}` : ""}: instrumentation missing${row.note ? `: ${row.note}` : ""}${row.evidence ? ` (${row.evidence})` : ""}` });
1659
1703
  } else if (r.disposition === "deliver" && row.status !== "implemented") {
1660
- f.push({ code: ["deferred", "post-deploy"].includes(row.status) ? C.CONFORMANCE_UNTRACKED_DEFERRAL : C.CONFORMANCE_UNIMPLEMENTED, detail: `${r.amendment?.text ? `${r.id} amendment not accepted (amended to "${String(r.amendment.text).slice(0, 200)}"): ` : `${r.id} `}${row.status}${row.note ? `: ${row.note}` : ""}${row.evidence ? ` (${row.evidence})` : ""}` });
1704
+ f.push({ code: ["deferred", "post-deploy"].includes(row.status) ? C.CONFORMANCE_UNTRACKED_DEFERRAL : C.CONFORMANCE_UNIMPLEMENTED, detail: `${r.amendment?.text ? `${r.id} amendment not accepted (amended to "${String(r.amendment.text).slice(0, 200)}"): ` : r.derived_outcome ? `${r.id} derived outcome not met ("${String(r.derived_outcome).slice(0, 200)}"): ` : `${r.id} `}${row.status}${row.note ? `: ${row.note}` : ""}${row.evidence ? ` (${row.evidence})` : ""}` });
1661
1705
  } else if (r.disposition === "deliver" && wantsE2e(r) && !e2eVerified(row, ctx.contract, ctx.e2e)) {
1662
1706
  const faked = (ctx.e2e?.faked ?? []).length ? `; faked or mocked components in ${ctx.e2e.faked.slice(0, 3).join(", ")}` : "";
1663
1707
  f.push({ code: C.CONFORMANCE_E2E_UNVERIFIED, kind: "e2e_row", detail: `${r.id} is a [type:e2e]/[type:manual] criterion but ${row.validated_by || "its validated_by"} is not a real end-to-end check (the repo's e2e set, Playwright/browser/live stack${faked}); run one, or mark ${r.id} post-deploy so it is transferred to the epic's acceptance${ctx.e2e?.sandboxes?.length ? `; it can run pre-merge: declare env: [${ctx.e2e.sandboxes.slice(0, 3).join(", ")}] on its validate to use the test sandbox (#5450), do not defer it` : ""}` });
@@ -1720,8 +1764,8 @@ export function reviewSkeleton(contract, changedFiles = [], ignore = []) {
1720
1764
  if (contract && !Array.isArray(contract.requirements) && "contract" in contract) ({ contract, changedFiles = [], ignore = [] } = contract);
1721
1765
  const reqs = contract?.requirements ?? [];
1722
1766
  return {
1723
- issue_coverage: reqs.map((r) => ({ quote: r.quote, contract_ids: [r.id], status: "" })),
1724
- requirements: reqs.map((r) => ({ id: r.id, status: "", evidence: "", validated_by: "", ...(TRACKED.includes(r.disposition) ? { deferral_ok: null } : {}), ...(isOutOfBand(r) ? { verify: "out_of_band", job: r.evidence ?? "", instrumented: null } : {}), note: "" })),
1767
+ issue_coverage: reqs.map((r) => (isGuidance(r) ? { quote: r.quote, contract_ids: [r.id], status: "covered", guidance: true, misclassified: false } : { quote: r.quote, contract_ids: [r.id], status: "" })),
1768
+ requirements: reqs.map((r) => isGuidance(r) ? { id: r.id, status: "not-applicable", guidance: true, stance: guidanceStance(r.why), note: "" } : ({ id: r.id, status: "", evidence: "", validated_by: "", ...(TRACKED.includes(r.disposition) ? { deferral_ok: null } : {}), ...(isOutOfBand(r) ? { verify: "out_of_band", job: r.evidence ?? "", instrumented: null } : {}), ...(r.derived_outcome ? { derived_outcome: r.derived_outcome } : {}), note: "" })),
1725
1769
  scope: reviewedFiles(changedFiles, ignore).map((f) => ({ file: f, authorized_by: authorizationOf(contract ?? {}, f) ?? "none", note: "" })),
1726
1770
  preserve: (contract?.preserve ?? []).map((x) => ({ id: x.id, status: "unverified", evidence: "" })),
1727
1771
  regressions: [], verdict: "", summary: "",
@@ -4,7 +4,7 @@ import { readFileSync } from "node:fs";
4
4
  import { describe, it } from "node:test";
5
5
  import assert from "node:assert/strict";
6
6
  import { toolMisses } from "./toolplace.mjs";
7
- import { FORGEDOCK_CHECKS_VAR, FORGEDOCK_ENTRY_VAR, portableForgedockPaths, resolvingIo, testPlanProblems, proofEchoesDeliverable, outputTail, removedNamedPaths, removedPathsOf, shellSyntaxError, unrunnableValidate, noopCommand, substituteVerdict, describesUnrunnableCommand, vitestQuietFlag, normalizeRunnerCommand, cliUsageError, validateContract, applyAmendments, amendmentKindProblems, precheck, hotspotGrowth, reproFailures, reproQualityFailures, isBugIssue, parseReview, checkCompleteness, decide, closePlan, isInvestigation, formatShadowSummary, followupItems, inIssue, snapQuote, snapQuotes, isTestPath, normalizeEvidencePath, mergeReviewRows, reviewSkeleton, missingIds, resolveEvidencePath, movingBaseDiff, scopeText, evidencePathLine, evidencePathOnly, reaskable, matchCriterion, criterionLines, fillEngineRows, explainFailures, resolveForgedockPaths, missingTool, repoTracks, tmpdirInputs, isScopeCheck, isPureScopeCheck, dropScopeValidates, tagOutOfBand, outOfBandRequirements, isOutOfBand, followupMap, renderPendingFollowups, VERIFY_MODES, OUT_OF_BAND_RE, FOLLOWUP_CLASSES, followupClass, inLaneDeferral, pendingTracking, BUCKETS, bucketKind, bucketProblems, bucketTally, isE2eCommand, e2eVerified, impliedDocDeliverables, applyValidateRecipes, deferChecklessPostDeploy, substituteShellProblem, reproEnvMiss, ORCHESTRATOR_BUCKET, ownerRoute, weakenedE2eDecisions, guessedUvEnv, envProvisioningCommand, assertionFailure, projectDirPathMiss, rewriteProjectDirCommand, convertDelivered, mockedDeliverable, proofEchoDetail, contractRuleCounts, onlyTestPlanProblems } from "./conformance.mjs";
7
+ import { BINDING, GUIDANCE, guidanceStance, FORGEDOCK_CHECKS_VAR, FORGEDOCK_ENTRY_VAR, portableForgedockPaths, resolvingIo, testPlanProblems, proofEchoesDeliverable, outputTail, isEnvValidateFailure, removedNamedPaths, removedPathsOf, shellSyntaxError, unrunnableValidate, noopCommand, substituteVerdict, describesUnrunnableCommand, vitestQuietFlag, normalizeRunnerCommand, cliUsageError, validateContract, applyAmendments, amendmentKindProblems, precheck, hotspotGrowth, reproFailures, reproQualityFailures, isBugIssue, parseReview, checkCompleteness, decide, closePlan, isInvestigation, formatShadowSummary, followupItems, inIssue, snapQuote, snapQuotes, isTestPath, normalizeEvidencePath, mergeReviewRows, reviewSkeleton, missingIds, resolveEvidencePath, movingBaseDiff, scopeText, evidencePathLine, evidencePathOnly, reaskable, matchCriterion, criterionLines, fillEngineRows, explainFailures, resolveForgedockPaths, missingTool, repoTracks, tmpdirInputs, isScopeCheck, isPureScopeCheck, dropScopeValidates, tagOutOfBand, outOfBandRequirements, isOutOfBand, followupMap, renderPendingFollowups, VERIFY_MODES, OUT_OF_BAND_RE, FOLLOWUP_CLASSES, followupClass, inLaneDeferral, pendingTracking, BUCKETS, bucketKind, bucketProblems, bucketTally, isE2eCommand, e2eVerified, impliedDocDeliverables, applyValidateRecipes, deferChecklessPostDeploy, substituteShellProblem, reproEnvMiss, ORCHESTRATOR_BUCKET, ownerRoute, weakenedE2eDecisions, guessedUvEnv, envProvisioningCommand, assertionFailure, projectDirPathMiss, rewriteProjectDirCommand, convertDelivered, mockedDeliverable, proofEchoDetail, contractRuleCounts, onlyTestPlanProblems } from "./conformance.mjs";
8
8
 
9
9
  const ISSUE = "## Requirements\n1. The scrape route must release the spend reservation on 429.\n2. The search route must release the spend reservation on 429.\n\n- [ ] Billing pricing is unchanged.";
10
10
  const Q1 = "The scrape route must release the spend reservation on 429.";
@@ -324,6 +324,16 @@ describe("precheck (deterministic, no reviewer)", () => {
324
324
  const local = precheck({ contract: C, result: failed, changedFiles: files, repoHas: repoTracks(["src/leak/__init__.py"]), validateRuns: { V1: { rc: 1, output: "ModuleNotFoundError: No module named 'leak.core'" } } });
325
325
  assert.deepEqual(codes(local), ["conformance.unimplemented"], "a repo module the change did not create is a code defect");
326
326
  });
327
+ it("5730: isEnvValidateFailure matches sandbox-only signatures, never assertion or stale-artifact output", () => {
328
+ for (const o of ["sh: 1: foo: command not found", "connect ECONNREFUSED 127.0.0.1:5432", "dial tcp: lookup db: no such host", "Connection refused", "services/api/.venv/bin/python: No such file or directory", "cannot open display :0", "Cannot connect to the Docker daemon"]) assert.equal(isEnvValidateFailure(o), true, o);
329
+ for (const o of ["AssertionError: 1 != 2", "x.md: missing or out of date (run --render-agent-md)", "ECONNREFUSED\nAssertionError: expected 1 to equal 2", "", undefined]) assert.equal(isEnvValidateFailure(o), false, String(o));
330
+ });
331
+ it("5730: validate_failed carries the redacted rerun output", () => {
332
+ const CV = { ...C, validate: [{ id: "V1", command: "node --test a.test.mjs" }] };
333
+ const rs = { requirements: [{ id: "R1", status: "implemented" }, { id: "R2", status: "implemented" }], validation: [{ id: "V1", exit: 1 }] };
334
+ const bad = precheck({ contract: CV, result: rs, changedFiles: files, validateRuns: { V1: { rc: 1, output: "boom\nTOKEN=abcd1234secretvalue" } } }).failures.filter((x) => x.kind === "validate_failed");
335
+ assert.equal(bad.length, 1); assert.match(bad[0].output, /boom/); assert.doesNotMatch(bad[0].output, /abcd1234secretvalue/);
336
+ });
327
337
  it("#5728 a folded G1 with no recorded result is judged by the engine's rerun", () => {
328
338
  const CG = { ...C, validate: [{ id: "V1", command: "node --test a.test.mjs" }, { id: "G1", command: "node --test b.test.mjs", regression: true }] };
329
339
  const rs = { requirements: [{ id: "R1", status: "implemented" }, { id: "R2", status: "implemented" }], validation: [{ id: "V1", exit: 0 }] };
@@ -350,6 +360,10 @@ describe("precheck (deterministic, no reviewer)", () => {
350
360
  assert.deepEqual(codes(carried), []);
351
361
  assert.deepEqual(precheck({ contract: C, result: { ...res, validation: [] }, changedFiles: files }).failures.map((f) => f.kind), ["validate_missing"]);
352
362
  });
363
+ it("#5750 GUIDANCE and BINDING partition the freezable dispositions; guidanceStance reads the planned stance from a why", () => {
364
+ assert.deepEqual([...GUIDANCE], ["guidance"]); assert.deepEqual([...BINDING], ["deliver", "defer", "post-deploy"]);
365
+ assert.equal(guidanceStance("adapt: the helper already exists"), "adapt"); assert.equal(guidanceStance("follow"), null); assert.equal(guidanceStance(""), null);
366
+ });
353
367
  it("#5446 reproQualityFailures: a mutation survivor fails only when enforced; patch_echo and behavioural never do", () => {
354
368
  assert.equal(reproQualityFailures({ quality: "mutation_survivor", enforce: true })[0].kind, "repro_mutation_survivor");
355
369
  assert.deepEqual(reproQualityFailures({ quality: "mutation_survivor", enforce: false }), []);
@@ -2284,6 +2298,50 @@ describe("#5773 operator decisions survive requeue and amendment replay", () =>
2284
2298
  });
2285
2299
  });
2286
2300
 
2301
+ describe("#5750 outcome rows bind, proposed-change rows are guidance", () => {
2302
+ const GI = `${ISSUE}\n\n## Proposed fix\nWrap the limiter call in try/catch and return an empty result.`;
2303
+ const GQ = "Wrap the limiter call in try/catch and return an empty result.";
2304
+ const G = { ...C, requirements: [...C.requirements, { id: "R3", quote: GQ, disposition: "guidance", why: "adapt: release the reservation and re-throw; an empty result hides the 429" }] };
2305
+ const gctx = { ...ctx, contract: G, issueText: GI };
2306
+ it("guidance freezes with a stance and a reason, needs no deliverable, and is rejected without one", () => {
2307
+ assert.deepEqual(validateContract(G, GI), { ok: true, problems: [] });
2308
+ for (const why of [undefined, "", "because", "adapt"]) assert.ok(validateContract({ ...G, requirements: [...C.requirements, { ...G.requirements[2], why }] }, GI).problems.some((p) => /R3: guidance needs a why/.test(p)), String(why));
2309
+ assert.ok(!validateContract({ ...G, requirements: [...C.requirements, { ...G.requirements[2], quote: "return an empty list from the limiter forever" }] }, GI).ok, "the verbatim quote check applies to guidance");
2310
+ });
2311
+ it("a contract of guidance rows only is rejected; derived_outcome rides only on a deliver row", () => {
2312
+ assert.ok(validateContract({ ...G, requirements: [G.requirements[2]] }, GI).problems.some((p) => /no binding outcome row/.test(p)));
2313
+ const derived = { ...G, requirements: [{ ...C.requirements[0], derived_outcome: "Outstanding reservations return to 0 after a 429." }, G.requirements[2]] };
2314
+ assert.equal(validateContract(derived, GI).ok, true);
2315
+ assert.ok(validateContract({ ...derived, requirements: [{ ...C.requirements[0], disposition: "defer", why: "w", bucket: "host", derived_outcome: "x" }, G.requirements[2]] }, GI).problems.some((p) => /derived_outcome must be/.test(p)));
2316
+ });
2317
+ it("decide passes when the outcome is implemented and the guidance row was not followed", () => {
2318
+ for (const status of ["missing", "partial", "not-applicable", undefined]) {
2319
+ const rv = { ...good, issue_coverage: [...good.issue_coverage, { quote: GQ, status: "missing" }], requirements: [...good.requirements, ...(status ? [{ id: "R3", status }] : [])] };
2320
+ assert.equal(decide(rv, gctx).state, "conforms", String(status));
2321
+ }
2322
+ });
2323
+ it("decide fails when the prescription was followed but the outcome row is missing", () => {
2324
+ const rv = { ...row("R1", { status: "missing", evidence: "" }), requirements: [{ id: "R1", status: "missing" }, good.requirements[1], { id: "R3", status: "implemented", evidence: "src/scrape.js:7" }] };
2325
+ assert.ok(codes(decide(rv, gctx)).includes("conformance.unimplemented"));
2326
+ assert.ok(codes(precheck({ contract: G, result: { requirements: [{ id: "R1", status: "missing" }, { id: "R2", status: "implemented" }, { id: "R3", status: "implemented" }], validation: [{ id: "V1", exit: 0 }] }, changedFiles: files })).includes("conformance.unimplemented"));
2327
+ });
2328
+ it("a guidance quote the reviewer flags misclassified is judged as a binding omission", () => {
2329
+ const d = decide({ ...good, issue_coverage: [...good.issue_coverage, { quote: GQ, contract_ids: ["R3"], status: "covered", misclassified: true }] }, gctx);
2330
+ assert.ok(codes(d).includes("conformance.omission")); assert.match(d.failures.map((f) => f.detail).join(), /misclassified/);
2331
+ });
2332
+ it("reviewSkeleton pre-fills guidance rows and precheck skips them", () => {
2333
+ const sk = reviewSkeleton(G, files);
2334
+ assert.deepEqual([sk.issue_coverage[2].status, sk.requirements[2].status, sk.requirements[2].stance], ["covered", "not-applicable", "adapt"]);
2335
+ assert.equal(sk.issue_coverage[0].status, "");
2336
+ assert.equal(precheck({ contract: G, result: { requirements: [{ id: "R1", status: "implemented" }, { id: "R2", status: "implemented" }], validation: [{ id: "V1", exit: 0 }] }, changedFiles: files }).ok, true);
2337
+ });
2338
+ it("add-requirement accepts guidance with a stance and rejects it without one", () => {
2339
+ const ok = applyAmendments(C, [{ kind: "add-requirement", requirement: { id: "R9", quote: GQ, disposition: "guidance" }, why: "reject: the route must surface the 429" }], GI);
2340
+ assert.equal(ok.contract.requirements.find((r) => r.id === "R9")?.disposition, "guidance");
2341
+ assert.match(applyAmendments(C, [{ kind: "add-requirement", requirement: { id: "R9", quote: GQ, disposition: "guidance" }, why: "seems off" }], GI).problems.join(), /guidance needs a why/);
2342
+ });
2343
+ });
2344
+
2287
2345
  describe("#5752 mechanism supersedes", () => {
2288
2346
  const K = { requirements: [], deliverables: [{ id: "D1", path: "src/triage.mjs" }], validate: [] };
2289
2347
  const broken = (guard, test) => ({ code: "conformance.guard_broken", kind: "guard_broken", guard, test, detail: `guard ${guard} broken` });
@@ -2340,3 +2398,37 @@ describe("recurrence counters and design lane precheck (#5751)", () => {
2340
2398
  assert.equal(run({ recurrence: { ...rec, recurs: false } }).ok, true, "no recurrence: no design check");
2341
2399
  });
2342
2400
  });
2401
+
2402
+ describe("#5754 live-stack e2e rows convert to post-deploy at freeze", () => {
2403
+ const LIVE = "A burst of 100 requests produces zero 429 lines against the live stack [type:e2e]";
2404
+ const mk = (quote) => ({ ...C, requirements: [{ id: "R1", quote, disposition: "deliver" }], validate: [{ id: "V1", command: "pytest tests/test_x.py" }] });
2405
+ it("converts the live-stack quote through autoPostDeployE2e", () => {
2406
+ assert.equal(prodOnlyE2e(LIVE), true);
2407
+ const out = autoPostDeployE2e(mk(LIVE));
2408
+ assert.deepEqual(out.converted.map((x) => x.id), ["R1"]);
2409
+ assert.equal(out.contract.requirements[0].disposition, "post-deploy");
2410
+ for (const q of ["real traffic against the live stack stays under 1% errors [type:manual]", "passes on the live cluster [type:e2e]"]) assert.equal(prodOnlyE2e(q), true, q);
2411
+ });
2412
+ it("keeps localhost, local stack, sandbox, staging and plain wording as deliver", () => {
2413
+ for (const q of ["100 requests give zero 429 lines against localhost [type:e2e]", "zero 429 lines against the local stack, not the live stack [type:e2e]", "sandbox run against the live stack mock [type:e2e]", "zero 429 on staging, not the live stack [type:e2e]", "the live reload works in the dev stack [type:e2e]"]) {
2414
+ assert.equal(prodOnlyE2e(q), false, q);
2415
+ assert.equal(autoPostDeployE2e(mk(q)).converted.length, 0, q);
2416
+ }
2417
+ });
2418
+ });
2419
+
2420
+ describe("#5754 precheck fails fast on a deliver row the placement cannot produce", () => {
2421
+ const LIVE = "A burst of 100 requests produces zero 429 lines against the live stack [type:e2e]";
2422
+ const run = (quote, extra = {}) => precheck({ contract: { ...C, requirements: [{ id: "R1", quote, disposition: "deliver", ...extra }], validate: [] }, result: { requirements: [], validation: [] }, changedFiles: [] });
2423
+ it("a live-stack deliver e2e row fails with a typed code before any builder resume", () => {
2424
+ const f = run(LIVE).failures.filter((x) => x.kind === "e2e_placement");
2425
+ assert.equal(f.length, 1);
2426
+ assert.equal(f[0].code, "conformance.e2e_unverified");
2427
+ });
2428
+ it("local, post-deploy, out-of-band and non-e2e rows do not trip it", () => {
2429
+ assert.equal(run("works against the local stack [type:e2e]").failures.some((x) => x.kind === "e2e_placement"), false);
2430
+ assert.equal(run(LIVE, { disposition: "post-deploy" }).failures.some((x) => x.kind === "e2e_placement"), false);
2431
+ assert.equal(run(LIVE, { verify: "out_of_band", evidence: "job" }).failures.some((x) => x.kind === "e2e_placement"), false);
2432
+ assert.equal(run("zero 429 lines against the live stack").failures.some((x) => x.kind === "e2e_placement"), false);
2433
+ });
2434
+ });
@@ -98,6 +98,12 @@ const CLONE_RETRY_S = 120;
98
98
  export const SANDBOX_CLONE_CODE = "sandbox.clone";
99
99
  /** #4866: a sandbox clone failure is a retryable `deferred` `sandbox.clone`, never an engine-error (so the breaker never sees it). */
100
100
  const cloneDeferred = (id, detail) => ({ terminalReason: "deferred", code: SANDBOX_CLONE_CODE, retryInSeconds: CLONE_RETRY_S, detail: `sandbox ${id} could not clone the repo: ${detail}; retry in ${CLONE_RETRY_S}s` });
101
+ // #5923: a hung github.com connection (ls-remote/fetch, or a connect timeout inside a clone) is egress, not a plain clone failure.
102
+ const EGRESS_RE = /Connection timed out|Failed to connect to|\b(ls-remote|fetch)\b[^\n]*\b(time[ds]?\s?out|timeout|hung|hang)|\b(time[ds]?\s?out|timeout)\b[^\n]*\b(ls-remote|fetch)\b/i;
103
+ export const isEgressTimeout = (text) => EGRESS_RE.test(String(text ?? ""));
104
+ /** Outcome code of a sandbox whose git egress hung to a timeout; local like sandbox.clone. */
105
+ export const SANDBOX_EGRESS_TIMEOUT_CODE = "sandbox.egress_timeout";
106
+ const egressDeferred = (id, detail) => ({ terminalReason: "deferred", code: SANDBOX_EGRESS_TIMEOUT_CODE, retryInSeconds: CLONE_RETRY_S, detail: `sandbox ${id} git egress timed out: ${detail}; retry in ${CLONE_RETRY_S}s` });
101
107
  const errLine = (t) => String(t ?? "").split("\n")[0].slice(0, 300);
102
108
  const errText = (e) => String(e?.stderr || e?.message || e).split("\n")[0].slice(0, 300);
103
109
 
@@ -138,6 +144,7 @@ export function parseExecution(sec = {}) {
138
144
  const patRaw = Array.isArray(s.host_capability_patterns) ? s.host_capability_patterns : str(s.host_capability_patterns) ? str(s.host_capability_patterns).split(",") : [];
139
145
  const hostCapabilityPatterns = patRaw.map((x) => { const t = str(x), i = t.indexOf(":"); return { name: t.slice(0, i).trim().toLowerCase(), pattern: t.slice(i + 1).trim() }; })
140
146
  .filter((x) => CAPABILITY_RE.test(x.name) && x.pattern && safeRegExp(x.pattern));
147
+ const repoSource = ["dispatcher", "github", "auto"].includes(str(s.repo_source).toLowerCase()) ? str(s.repo_source).toLowerCase() : null; // #5949: where a pool sandbox's repo mirror comes from; unset = auto
141
148
  const wsN = Number(str(s.warm_sandboxes));
142
149
  const warmSandboxes = str(s.warm_sandboxes) !== "" && Number.isInteger(wsN) && wsN > 0 ? wsN : 0; // #4912: warm sandboxes the pool agent keeps ready; 0 = off
143
150
  const lt = validateLaneTools(s.lane_tools); // #5650: invalid entries are dropped here and reported in laneToolsErrors; the remote provider refuses to start with them
@@ -154,7 +161,7 @@ export function parseExecution(sec = {}) {
154
161
  const plan = ["free", "pro", "team", "enterprise"].includes(str(s.plan).toLowerCase()) ? str(s.plan).toLowerCase() : null;
155
162
  const publicDefault = str(s.public_default).toLowerCase() === "actions" ? "actions" : null; // #5900: opt-in only
156
163
  const dispatcher = /^[A-Za-z0-9][A-Za-z0-9-]*(\[bot\])?$/.test(str(s.dispatcher)) ? str(s.dispatcher) : null;
157
- return { mode, maxRemote, provider, image, secrets, budget, ...(jobLimit ? { jobLimit } : {}), ...(ciReserve !== null ? { ciReserve } : {}), ...(plan ? { plan } : {}), ...(publicDefault ? { publicDefault } : {}), ...(dispatcher ? { dispatcher } : {}), ...(hostFallback !== null ? { hostFallback } : {}), ...(hostCapabilities.length ? { hostCapabilities } : {}), ...(hostCapabilityPatterns.length ? { hostCapabilityPatterns } : {}), ...(endpoint ? { endpoint } : {}), ...(tokenEnv ? { tokenEnv } : {}), ...(tokenFile ? { tokenFile } : {}), ...(cacheStore ? { cacheStore } : {}), ...(allowActions ? { allowActions } : {}), ...(fallbackLocal ? { fallbackLocal } : {}), ...(capacityFallbackAfter !== null ? { capacityFallbackAfter } : {}), ...(heavy !== null ? { heavy } : {}), ...(unreachableWindowMin !== null ? { unreachableWindowMin } : {}), ...(Object.keys(relay).length ? { relay } : {}), ...(warmSandboxes ? { warmSandboxes } : {}), ...(accountRotator ? { accountRotator } : {}), ...(lt.tools.length ? { laneTools: lt.tools } : {}), ...(lt.errors.length ? { laneToolsErrors: lt.errors } : {}) };
164
+ return { mode, maxRemote, provider, image, secrets, budget, ...(jobLimit ? { jobLimit } : {}), ...(ciReserve !== null ? { ciReserve } : {}), ...(plan ? { plan } : {}), ...(publicDefault ? { publicDefault } : {}), ...(dispatcher ? { dispatcher } : {}), ...(hostFallback !== null ? { hostFallback } : {}), ...(hostCapabilities.length ? { hostCapabilities } : {}), ...(hostCapabilityPatterns.length ? { hostCapabilityPatterns } : {}), ...(endpoint ? { endpoint } : {}), ...(tokenEnv ? { tokenEnv } : {}), ...(tokenFile ? { tokenFile } : {}), ...(cacheStore ? { cacheStore } : {}), ...(allowActions ? { allowActions } : {}), ...(fallbackLocal ? { fallbackLocal } : {}), ...(capacityFallbackAfter !== null ? { capacityFallbackAfter } : {}), ...(heavy !== null ? { heavy } : {}), ...(unreachableWindowMin !== null ? { unreachableWindowMin } : {}), ...(Object.keys(relay).length ? { relay } : {}), ...(warmSandboxes ? { warmSandboxes } : {}), ...(repoSource ? { repoSource } : {}), ...(accountRotator ? { accountRotator } : {}), ...(lt.tools.length ? { laneTools: lt.tools } : {}), ...(lt.errors.length ? { laneToolsErrors: lt.errors } : {}) };
158
165
  }
159
166
 
160
167
  const round1 = (x) => Math.round(x * 10) / 10;
@@ -244,9 +251,9 @@ export async function repoIsPublic({ repo, gh }) {
244
251
  try { return JSON.parse(await gh(["api", `repos/${repo}`]))?.private === false; } catch { return false; }
245
252
  }
246
253
 
247
- /** Where a `mode: remote` lane runs: remote only with `max_remote >= 1`. Hybrid is placed per lane by `placeLane` (#4256). */
254
+ /** Where a `mode: remote` lane runs: always remote (#5933: `max_remote 0` pauses starts, it never falls back to the host). Hybrid is placed per lane by `placeLane` (#4256). */
248
255
  export function placement(exec) {
249
- return exec?.mode === "remote" && Number.isInteger(exec.maxRemote) && exec.maxRemote >= 1 ? "remote" : "local";
256
+ return exec?.mode === "remote" ? "remote" : "local";
250
257
  }
251
258
 
252
259
  /** An explicit need written in prose (#5725): `needs: sops`, `needs sops`, `host capability: sops`. */
@@ -381,7 +388,7 @@ const DOCS_LABELS = new Set(["docs", "documentation", "type:docs"]);
381
388
  /**
382
389
  * Hybrid placement (#4256), pure: facts in, `{where: "local"|"remote", reason}` out. `exec` is parseExecution output,
383
390
  * `verifyMode` forge.yaml `verify.mode`, `labels` the issue's label names (the lane kind), `weight` from
384
- * `validationWeight`, `headroom` from `hostHeadroom`. In order: a non-hybrid mode keeps `placement()`; `max_remote` 0 is
391
+ * `validationWeight`, `headroom` from `hostHeadroom`. In order: a non-hybrid mode keeps `placement()` (remote mode stays remote at `max_remote` 0: orchestrate holds it pending); `max_remote` 0 is
385
392
  * local; `verify.mode: ci` is local (heavy validation already runs, and is billed, on CI); a docs-only lane is local; a
386
393
  * heavy-validation lane is remote; a host without headroom sends the lane remote; anything else stays on the host.
387
394
  * A `needs` entry (host-only capability, #4542) the provider does not `relays` is local first, in `remote` mode too.
@@ -547,7 +554,7 @@ export function containerProvider({ batch, repo, image, gitDir, cacheDir = `${ho
547
554
  async status(h) {
548
555
  let s;
549
556
  try { s = String(await docker(["inspect", "-f", "{{.State.Status}}", h.id])).trim(); } catch { return "gone"; }
550
- return ["running", "created", "restarting"].includes(s) ? "running" : "exited";
557
+ return ["running", "created", "restarting", "paused"].includes(s) ? "running" : "exited";
551
558
  },
552
559
  async fetchResult(h) {
553
560
  const r = readJson(batch.resultFile(h?.issue));
@@ -661,7 +668,7 @@ export function providerByName(name, opts) {
661
668
  // #4685/#5131: an empty env/keychain lookup of `token_env` falls back to `token_file`, then the (matching) router's token file.
662
669
  const credentials = (n) => (n === tokenEnv ? resolve().token : resolveCredential(n, { env, keychain })); // per call, keychain memoised (#5159)
663
670
  const settings = { ...exec, ...(endpoint ? { endpoint } : {}), ...(tokenEnv ? { tokenEnv } : {}), ...(forgeYaml ? { forgeYaml } : {}),
664
- ...(typeof opts?.prefetch === "function" ? { prefetch: opts.prefetch } : {}) }; // #4778: dispatch-time relay pre-fetch
671
+ ...(typeof opts?.prefetch === "function" ? { prefetch: opts.prefetch } : {}), ...(pool && opts?.cwd ? { repoDir: opts.cwd } : {}) }; // #4778; #5949: the dispatcher's clone seeds the pool mirror: dispatch-time relay pre-fetch
665
672
  return remoteProvider({ batch: opts.batch, repo: opts.repo, settings, ...(pool ? { name: "pool" } : {}), env, credentials,
666
673
  transport: remoteTransportFor(settings, { transport: opts?.transport, env, credentials, ...(opts?.fetchFn ? { fetchFn: opts.fetchFn } : {}) }), ...(opts?.now ? { now: opts.now } : {}) });
667
674
  }
@@ -739,7 +746,8 @@ export function providerLanes({ provider, laneArgs, ledgerFor, env = process.env
739
746
  : { terminalReason: "deferred", code: OUTCOME_CODES.SANDBOX_UNREACHABLE, retryInSeconds: 60,
740
747
  detail: `sandbox ${h.id} ${errText(e)}; kept for adopt on resume` });
741
748
  const tailOf = async (h) => { try { return typeof logTail === "function" ? String(await logTail(h) ?? "") : ""; } catch { return ""; } };
742
- const settleClone = (r, id) => (r?.terminalReason === "engine-error" && r.code === undefined && isCloneFailure(r.detail) ? cloneDeferred(id, errLine(r.detail)) : r);
749
+ const settleClone = (r, id) => (r?.terminalReason === "engine-error" && r.code === undefined && isEgressTimeout(r.detail) ? egressDeferred(id, errLine(r.detail))
750
+ : r?.terminalReason === "engine-error" && r.code === undefined && isCloneFailure(r.detail) ? cloneDeferred(id, errLine(r.detail)) : r);
743
751
  // #5669: a halted batch (schedd handover) stops polling; the sandbox is neither torn down nor released, so the next daemon adopts it.
744
752
  const wait = async (h, g = guard({ waited: 0, tries: 0 }), sig = null) => {
745
753
  for (;;) {
@@ -759,7 +767,9 @@ export function providerLanes({ provider, laneArgs, ledgerFor, env = process.env
759
767
  return { terminalReason: "deferred", code: OUTCOME_CODES.RATE_LIMITED, resetAt: lim.resetAt ?? "unknown", resetAtEpochMs: Number.isFinite(at) ? at : null,
760
768
  detail: `${why}: usage limit hit; resets at ${lim.resetAt ?? "unknown"}` };
761
769
  }
762
- return isCloneFailure(tail) ? cloneDeferred(h.id, why) : { terminalReason: "engine-error", detail: why };
770
+ // #5859: tagged with its pool agent so the runner can tell an agent/VM restart (many lost on one agent) from one dead sandbox
771
+ if (isEgressTimeout(tail)) return egressDeferred(h.id, why);
772
+ return isCloneFailure(tail) ? cloneDeferred(h.id, why) : { terminalReason: "engine-error", detail: why, lostWithoutResult: true, ...(typeof h?.agent === "string" && h.agent ? { agent: h.agent } : {}) };
763
773
  }
764
774
  await sleep(pollMs);
765
775
  }