forgedock 1.51.0 → 1.53.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 (103) hide show
  1. package/bin/engine/outcome-codes.mjs +3 -0
  2. package/bin/engine/telemetry-seam.mjs +4 -2
  3. package/bin/engine-cli.mjs +61 -17
  4. package/bin/experiment.mjs +58 -6
  5. package/bin/forge-utils.mjs +6 -2
  6. package/bin/forgedock.mjs +25 -1
  7. package/bin/lean/account-watch.mjs +28 -0
  8. package/bin/lean/account-watch.test.mjs +30 -0
  9. package/bin/lean/activation.mjs +20 -0
  10. package/bin/lean/activation.test.mjs +14 -1
  11. package/bin/lean/basered.mjs +115 -0
  12. package/bin/lean/basered.test.mjs +66 -0
  13. package/bin/lean/batch-health.mjs +40 -6
  14. package/bin/lean/batch-health.test.mjs +34 -1
  15. package/bin/lean/batch.mjs +41 -2
  16. package/bin/lean/batch.test.mjs +104 -2
  17. package/bin/lean/checkpoint-reconcile.mjs +43 -0
  18. package/bin/lean/checkpoint-reconcile.test.mjs +95 -0
  19. package/bin/lean/conformance.e2e.test.mjs +1 -1
  20. package/bin/lean/conformance.mjs +205 -23
  21. package/bin/lean/conformance.test.mjs +164 -3
  22. package/bin/lean/context.mjs +27 -17
  23. package/bin/lean/context.test.mjs +15 -0
  24. package/bin/lean/effects.mjs +11 -7
  25. package/bin/lean/execution.mjs +19 -3
  26. package/bin/lean/execution.test.mjs +39 -0
  27. package/bin/lean/findinglabel.mjs +16 -0
  28. package/bin/lean/findinglabel.test.mjs +39 -0
  29. package/bin/lean/heavy.mjs +6 -3
  30. package/bin/lean/hostload.mjs +78 -0
  31. package/bin/lean/hostload.test.mjs +117 -0
  32. package/bin/lean/hotspots-remote.e2e.test.mjs +71 -0
  33. package/bin/lean/issuewatch-release.mjs +6 -2
  34. package/bin/lean/issuewatch-release.test.mjs +16 -0
  35. package/bin/lean/issuewatch.mjs +11 -1
  36. package/bin/lean/lanelock.mjs +14 -0
  37. package/bin/lean/lean.mjs +171 -36
  38. package/bin/lean/lean.test.mjs +302 -10
  39. package/bin/lean/light.mjs +48 -7
  40. package/bin/lean/light.test.mjs +37 -3
  41. package/bin/lean/limits.test.mjs +142 -9
  42. package/bin/lean/orchestrate-cancel.test.mjs +143 -0
  43. package/bin/lean/orchestrate.mjs +110 -26
  44. package/bin/lean/postdeploy-check.test.mjs +39 -0
  45. package/bin/lean/prompts.mjs +8 -7
  46. package/bin/lean/quota.mjs +39 -0
  47. package/bin/lean/recovery.test.mjs +10 -0
  48. package/bin/lean/relaxation.mjs +73 -0
  49. package/bin/lean/relaxation.test.mjs +54 -0
  50. package/bin/lean/release-postmerge.mjs +119 -0
  51. package/bin/lean/release-rehearsal.mjs +63 -0
  52. package/bin/lean/release-rehearsal.test.mjs +93 -0
  53. package/bin/lean/release-review.e2e.test.mjs +77 -0
  54. package/bin/lean/release-review.mjs +198 -0
  55. package/bin/lean/release-review.test.mjs +180 -0
  56. package/bin/lean/release.mjs +228 -0
  57. package/bin/lean/release.test.mjs +292 -0
  58. package/bin/lean/rotator.mjs +150 -31
  59. package/bin/lean/rotator.test.mjs +105 -2
  60. package/bin/lean/sandbox-remote.mjs +9 -2
  61. package/bin/lean/schedd.mjs +56 -6
  62. package/bin/lean/schedd.test.mjs +108 -6
  63. package/bin/lean/verifier.mjs +3 -2
  64. package/bin/lean/verify.mjs +2 -1
  65. package/bin/lean/verify.test.mjs +6 -0
  66. package/bin/pool/agent.mjs +18 -4
  67. package/bin/pool/router.mjs +68 -25
  68. package/bin/review-staging.mjs +23 -0
  69. package/bin/stats/conformance-outcomes.mjs +208 -0
  70. package/bin/stats/conformance-outcomes.test.mjs +188 -0
  71. package/bin/stats/depth.mjs +218 -0
  72. package/bin/stats/depth.test.mjs +133 -0
  73. package/bin/stats/experiment.mjs +7 -5
  74. package/bin/stats/github-source.mjs +2 -2
  75. package/bin/stats/index.mjs +64 -2
  76. package/bin/stats/local-source.mjs +11 -0
  77. package/bin/stats/query.mjs +69 -0
  78. package/bin/stats/selffiled.mjs +52 -0
  79. package/bin/stats/selffiled.test.mjs +71 -0
  80. package/commands/orchestrate.md +1 -1
  81. package/commands/review-pr-agents/security.md +4 -0
  82. package/commands/review-pr-staging.md +2 -0
  83. package/commands/work-on/build.md +4 -6
  84. package/docs/CONFIG.md +66 -8
  85. package/docs/ISSUE-WATCH.md +2 -0
  86. package/docs/OUTCOME-CODES.md +3 -0
  87. package/docs/STATS.md +44 -0
  88. package/docs/TELEMETRY.md +1 -1
  89. package/package.json +1 -1
  90. package/pool/README.md +1 -1
  91. package/pool/image/cs-cred +14 -1
  92. package/pool/install/install-agent.ps1 +6 -2
  93. package/scripts/backfill-finding-labels.mjs +50 -0
  94. package/scripts/backfill-finding-labels.test.mjs +36 -0
  95. package/scripts/doctor-pipeline-state.sh +21 -6
  96. package/scripts/file-deferred-followups.sh +60 -238
  97. package/scripts/file-deferred-followups.test.sh +99 -187
  98. package/scripts/followup-route.mjs +12 -0
  99. package/scripts/hotspots.sh +12 -8
  100. package/scripts/hotspots.test.sh +22 -0
  101. package/scripts/owner-route-parity.test.sh +17 -1
  102. package/scripts/prior-attempts.test.mjs +1 -1
  103. package/scripts/review-pr-side-effects.test.sh +40 -0
@@ -3,7 +3,7 @@
3
3
  import { readFileSync } from "node:fs";
4
4
  import { describe, it } from "node:test";
5
5
  import assert from "node:assert/strict";
6
- import { removedNamedPaths, removedPathsOf, shellSyntaxError, unrunnableValidate, noopCommand, substituteVerdict, describesUnrunnableCommand, vitestQuietFlag, normalizeRunnerCommand, cliUsageError, validateContract, applyAmendments, amendmentKindProblems, precheck, hotspotGrowth, reproFailures, isBugIssue, parseReview, checkCompleteness, decide, closePlan, isInvestigation, formatShadowSummary, followupItems, inIssue, 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, BUCKETS, bucketKind, bucketProblems, bucketTally, isE2eCommand, e2eVerified, impliedDocDeliverables, applyValidateRecipes, deferChecklessPostDeploy, substituteShellProblem, reproEnvMiss, ORCHESTRATOR_BUCKET, ownerRoute, weakenedE2eDecisions } from "./conformance.mjs";
6
+ import { removedNamedPaths, removedPathsOf, shellSyntaxError, unrunnableValidate, noopCommand, substituteVerdict, describesUnrunnableCommand, vitestQuietFlag, normalizeRunnerCommand, cliUsageError, validateContract, applyAmendments, amendmentKindProblems, precheck, hotspotGrowth, reproFailures, 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, projectDirPathMiss, rewriteProjectDirCommand } from "./conformance.mjs";
7
7
 
8
8
  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.";
9
9
  const Q1 = "The scrape route must release the spend reservation on 429.";
@@ -467,6 +467,65 @@ describe("conformance review: the engine computes the verdict from complete rows
467
467
  assert.equal(validateContract({ ...C, validate: [{ id: "V4", command: ok }] }, ISSUE).ok, true, ok);
468
468
  }
469
469
  });
470
+ it("#5234 project-dir paths and pytest exit 4", () => {
471
+ const poetry = "poetry -C services/api run pytest -q services/api/tests/test_x.py services/api/tests/test_y.py";
472
+ assert.deepEqual(projectDirPathMiss(poetry), { dir: "services/api", paths: ["services/api/tests/test_x.py", "services/api/tests/test_y.py"] });
473
+ assert.equal(rewriteProjectDirCommand(poetry), "cd services/api && poetry run pytest -q tests/test_x.py tests/test_y.py");
474
+ const uv = "uv run --project services/api pytest services/api/tests/x.py -k foo";
475
+ assert.equal(rewriteProjectDirCommand(uv), "cd services/api && uv run pytest tests/x.py -k foo");
476
+ assert.equal(rewriteProjectDirCommand("poetry --directory=./services/api run pytest services/api/tests/x.py"), "cd services/api && poetry run pytest tests/x.py");
477
+ const mixed = "poetry -C services/api run pytest services/api/tests/x.py tests/hands_conformance";
478
+ assert.equal(rewriteProjectDirCommand(mixed), mixed);
479
+ const chained = "poetry -C services/api run pytest services/api/tests/x.py && echo ok";
480
+ assert.equal(rewriteProjectDirCommand(chained), chained);
481
+ for (const fine of ["cd services/api && poetry run pytest ../../services/api/tests/x.py", "poetry -C services/api run pytest tests/x.py", "poetry run pytest services/api/tests/x.py"]) {
482
+ assert.equal(projectDirPathMiss(fine), null, fine);
483
+ assert.equal(rewriteProjectDirCommand(fine), fine);
484
+ }
485
+ for (const cmd of [poetry, uv, mixed]) {
486
+ const v = validateContract({ ...C, validate: [{ id: "V1", command: cmd }] }, ISSUE);
487
+ assert.ok(v.problems.some((x) => x.startsWith("V1: the command moves its cwd to `services/api`")), v.problems.join("; "));
488
+ }
489
+ const rt = validateContract({ ...C, repro_test: { path: "t/x.py", command: uv } }, ISSUE, { repro: true });
490
+ assert.ok(rt.problems.some((x) => x.startsWith("repro_test: the command moves its cwd")), rt.problems.join("; "));
491
+ // pytest exit 4 is a defect of the frozen command: contract.invalid_command, and a substitute is judged ok
492
+ const exit4 = { rc: 4, output: "ERROR: file or directory not found: services/api/tests/x.py\n\nno tests ran in 0.01s" };
493
+ assert.ok(unrunnableValidate({ rc: 4, output: "ERROR: file or directory not found: services/api/tests/x.py" }));
494
+ assert.ok(unrunnableValidate({ rc: 4, output: "ERROR: not found: /repo/tests/x.py::t" }));
495
+ assert.ok(!unrunnableValidate({ rc: 1, output: "1 failed, 2 passed" }));
496
+ // exit 4 or 5 of a pytest command is unrunnable whatever the output says; other runners and test failures are not
497
+ for (const rc of [4, 5]) assert.ok(unrunnableValidate({ rc, output: "" }, "poetry run pytest -q tests/x.py"), `rc ${rc}`);
498
+ assert.ok(!unrunnableValidate({ rc: 4, output: "" }, "node --test x.mjs"));
499
+ assert.ok(!unrunnableValidate({ rc: 1, output: "1 failed" }, "pytest tests/x.py"));
500
+ assert.equal(substituteVerdict({ rc: 4, output: "" }, { command: poetry }), "ok");
501
+ assert.equal(substituteVerdict({ rc: 1, output: "1 failed" }, { command: poetry }), "runs");
502
+ assert.equal(substituteVerdict(exit4), "ok");
503
+ const contract = { requirements: [], deliverables: [], validate: [{ id: "V1", command: poetry }] };
504
+ const p = precheck({ contract, result: { validation: [{ id: "V1", exit: 4 }] }, changedFiles: [], validateRuns: { V1: exit4 } });
505
+ assert.deepEqual(p.failures.map((f) => [f.code, f.kind]), [["contract.invalid_command", "validate_command_invalid"]]);
506
+ });
507
+ it("#5232 a guessed offline uv --with environment is rejected for repro_test and validate; a requirements export passes", () => {
508
+ const bad = "cd w && uv run --offline --no-project --with pytest --with structlog python -m pytest -q t.py";
509
+ assert.equal(guessedUvEnv(bad), true);
510
+ assert.equal(guessedUvEnv("uv run --no-project --python 3.12 --with-requirements r.txt pytest -q t.py"), false);
511
+ assert.equal(guessedUvEnv("uv run --offline --no-project --with-requirements r.txt pytest"), false);
512
+ assert.equal(guessedUvEnv("pnpm vitest run x"), false);
513
+ const rt = validateContract({ ...C, repro_test: { path: "t/x.py", command: bad } }, ISSUE, { repro: true });
514
+ assert.ok(rt.problems.some((x) => x.startsWith("repro_test: the command builds its environment from a hand-picked")), rt.problems.join("; "));
515
+ const v = validateContract({ ...C, validate: [{ id: "V1", command: bad }] }, ISSUE);
516
+ assert.ok(v.problems.some((x) => x.startsWith("V1: the command builds its environment")), v.problems.join("; "));
517
+ const ok = validateContract({ ...C, repro_test: { path: "t/x.py", command: "uv run --no-project --with-requirements r.txt pytest t/x.py" } }, ISSUE, { repro: true });
518
+ assert.ok(!ok.problems.some((x) => /hand-picked/.test(x)));
519
+ });
520
+
521
+ it("#5230 tmpdirInputs counts venv, clone and worktree dirs as created", () => {
522
+ assert.deepEqual(tmpdirInputs('uv venv -q "$TMPDIR/pv" && uv pip install --offline -q --python "$TMPDIR/pv/bin/python" pytest && "$TMPDIR/pv/bin/python" -m pytest -q x'), []);
523
+ assert.deepEqual(tmpdirInputs("python3 -m venv $TMPDIR/v && $TMPDIR/v/bin/pip install x"), []);
524
+ assert.deepEqual(tmpdirInputs("virtualenv $TMPDIR/v && $TMPDIR/v/bin/pip install x"), []);
525
+ assert.deepEqual(tmpdirInputs("git clone https://x/y.git $TMPDIR/c && cat $TMPDIR/c/f"), []);
526
+ assert.deepEqual(tmpdirInputs("git worktree add $TMPDIR/w && cat $TMPDIR/w/f"), []);
527
+ assert.deepEqual(tmpdirInputs('uv pip install --python "$TMPDIR/pv/bin/python" pytest'), ["$TMPDIR/pv/bin/python"]);
528
+ });
470
529
  it("#4325 tmpdirInputs lists read-before-create $TMPDIR paths once, in first-use order", () => {
471
530
  assert.deepEqual(tmpdirInputs("cat ${TMPDIR:-/tmp}/a.json | jq . && cp $TMPDIR/b.txt out && cat $TMPDIR/a.json"), ["$TMPDIR/a.json", "$TMPDIR/b.txt"]);
472
531
  assert.deepEqual(tmpdirInputs("cp src.txt $TMPDIR/b.txt && cat $TMPDIR/b.txt"), []);
@@ -548,13 +607,28 @@ describe("conformance review: the engine computes the verdict from complete rows
548
607
  assert.equal(i.state, "review.inconsistent"); assert.deepEqual(codes(i), ["review.inconsistent"]);
549
608
  });
550
609
  it("a deferred requirement needs the reviewer's deferral_ok; false is an unjustified deferral", () => {
551
- const k = { ...C, requirements: [C.requirements[0], { ...C.requirements[1], disposition: "defer", why: "w" }] };
610
+ const k = { ...C, requirements: [C.requirements[0], { ...C.requirements[1], disposition: "defer", why: "w", bucket: "owner:rotate the key" }] };
552
611
  const c2 = { ...ctx, contract: k };
553
612
  const rv = (extra) => ({ ...good, requirements: [good.requirements[0], { id: "R2", status: "deferred", ...extra }] });
554
613
  assert.equal(decide(rv({}), c2).state, "review.incomplete");
555
614
  assert.equal(decide(rv({ deferral_ok: true }), c2).state, "conforms");
556
615
  assert.deepEqual(codes(decide(rv({ deferral_ok: false, note: "two lines in the same file" }), c2)), ["conformance.unjustified_deferral"]);
557
616
  });
617
+ it("#5207 an in-lane engineering deferral (new-issue or unbucketed) is never accepted, whatever deferral_ok says, and is never filed", () => {
618
+ const rv = (extra) => ({ ...good, requirements: [good.requirements[0], { id: "R2", status: "deferred", ...extra }] });
619
+ for (const bucket of ["new-issue", undefined]) {
620
+ const c2 = { ...ctx, contract: { ...C, requirements: [C.requirements[0], { ...C.requirements[1], disposition: "defer", why: "w", ...(bucket ? { bucket } : {}) }] } };
621
+ for (const ok of [true, false]) {
622
+ const d = decide(rv({ deferral_ok: ok }), c2);
623
+ assert.deepEqual(codes(d), ["conformance.unjustified_deferral"], `${bucket} ${ok}`); // one per row, no duplicate
624
+ assert.match(d.failures[0].detail, new RegExp(`^R2 is in-lane engineering work \\(bucket ${bucket ?? "none"}\\): deliver it .*\\(#5207\\)$`));
625
+ }
626
+ assert.deepEqual(pendingTracking(c2.contract).map((r) => r.id), [], "never filed");
627
+ assert.ok(inLaneDeferral(c2.contract.requirements[1]));
628
+ }
629
+ for (const r of [{ disposition: "defer", bucket: "owner:spend" }, { disposition: "defer", bucket: "host" }, { disposition: "post-deploy", bucket: "post-deploy" }, { disposition: "defer", class: "ops" }, { disposition: "deliver" }]) assert.equal(inLaneDeferral(r), false, JSON.stringify(r));
630
+ assert.deepEqual(pendingTracking({ requirements: [{ id: "R1", disposition: "defer", bucket: "owner:spend" }, { id: "R2", disposition: "defer", bucket: "new-issue" }] }).map((r) => r.id), ["R1"]);
631
+ });
558
632
  it("short quotes are accepted only as a whole issue line or list item", () => {
559
633
  const t = "Do this:\n- [ ] add --dry-run\n2. keep -v";
560
634
  assert.ok(inIssue("add --dry-run", t)); assert.ok(inIssue("keep -v", t)); assert.ok(!inIssue("dry-run", t)); assert.ok(!inIssue("do", t));
@@ -590,6 +664,22 @@ describe("close plan and follow-up items", () => {
590
664
  assert.deepEqual(closePlan(d, { title, review: { requirements: [{ id: "R1", status: "implemented" }] } }).open.map((r) => r.id), ["R2"], "a missing row is not an answer");
591
665
  assert.equal(closePlan(d, { title, review: null }).reason, "completed", "a skipped review judges dispositions only");
592
666
  });
667
+ it("#5240 an unticked acceptance box with an undelivered or untracked requirement closes partial for any title", () => {
668
+ const issueText = "## Acceptance\n\n- [ ] Replaying the incident keeps the issue open with a partial outcome\n- [ ] The gate mode is recorded in the trajectory notes\n";
669
+ const reqs = [
670
+ { id: "R1", quote: "- [ ] Replaying the incident keeps the issue open with a partial outcome", disposition: "deliver" },
671
+ { id: "R2", quote: "- [ ] The gate mode is recorded in the trajectory notes", disposition: "defer", tracked: "#9" },
672
+ ];
673
+ const rows = (s1) => ({ requirements: [{ id: "R1", status: s1 }, { id: "R2", status: "deferred" }] });
674
+ const p = closePlan({ requirements: reqs }, { title: "fix: x", review: rows("partial"), issueText });
675
+ assert.equal(p.reason, "partial"); assert.equal(p.checklist, true);
676
+ assert.deepEqual(p.open.map((r) => r.id), ["R1"]); assert.deepEqual(p.unticked, ["Replaying the incident keeps the issue open with a partial outcome"]);
677
+ assert.deepEqual(closePlan({ requirements: reqs }, { title: "fix: x", review: rows("implemented"), issueText }), { reason: "completed", tracked: ["#9"] });
678
+ const untracked = closePlan({ requirements: [reqs[0], { ...reqs[1], tracked: undefined }] }, { title: "fix: x", review: rows("implemented"), issueText });
679
+ assert.deepEqual(untracked.open.map((r) => r.id), ["R2"]);
680
+ assert.equal(closePlan({ requirements: reqs }, { title: "fix: x", review: rows("partial") }).reason, "completed", "no issue text: unchanged");
681
+ assert.equal(closePlan({ requirements: reqs }, { title: "fix: x", review: null, issueText }).reason, "completed", "skipped review judges dispositions only");
682
+ });
593
683
  it("#4398 formatShadowSummary: shadow would-block and false-block shares, risk-enforced lanes; null without conformance rows", () => {
594
684
  assert.equal(formatShadowSummary([{ issue: 1 }]), null); assert.equal(formatShadowSummary(undefined), null);
595
685
  const rows = [{ conformance: { mode: "shadow", would: "conforms", risk: false } }, { conformance: { mode: "shadow", would: "nonconforming", risk: false } },
@@ -998,7 +1088,7 @@ describe("post-deploy check ids (#4626)", () => {
998
1088
  assert.equal(cls({ disposition: "post-deploy", check: "x" }), "post-deploy");
999
1089
  assert.equal(cls({ disposition: "defer", class: "external" }), "external");
1000
1090
  assert.equal(cls({ disposition: "defer", class: "bogus" }), "engineering");
1001
- assert.deepEqual(FOLLOWUP_CLASSES, ["engineering", "post-deploy", "external", "ops", "host"]);
1091
+ assert.deepEqual(FOLLOWUP_CLASSES, ["engineering", "post-deploy", "external", "ops", "host"]); // #5207: backlog removed
1002
1092
  assert.equal(followupClass({ disposition: "post-deploy" }), "post-deploy"); assert.equal(followupClass({ class: "ops" }), "ops");
1003
1093
  const v = validateContract({ requirements: [{ id: "R1", quote: Q1, disposition: "defer", why: "w", class: "bogus" }], deliverables: [], preserve: [], validate: [{ id: "V1", command: "true" }] }, Q1);
1004
1094
  assert.ok(v.problems.some((x) => /R1: class must be one of/.test(x)), v.problems.join(";"));
@@ -1026,6 +1116,7 @@ describe("post-deploy check ids (#4626)", () => {
1026
1116
  assert.equal(followupClass({ disposition: "defer", bucket: "owner:spend", class: "ops" }), "ops");
1027
1117
  assert.equal(followupClass({ disposition: "defer", bucket: "owner:x", class: "post-deploy" }), "external");
1028
1118
  assert.equal(followupClass({ disposition: "defer", bucket: "new-issue", class: "post-deploy" }), "engineering");
1119
+ assert.equal(followupClass({ disposition: "defer", bucket: "new-issue" }), "engineering"); assert.equal(followupClass({ disposition: "defer", bucket: "new-issue", class: "ops" }), "engineering"); // #5207
1029
1120
  for (const bucket of ["post-deploy", "verify-now", "date:2026-12-01"]) assert.equal(followupClass({ disposition: "defer", bucket }), "post-deploy");
1030
1121
  assert.equal(one({ bucket: "owner:rotate the key" }).why, "owner: rotate the key. [bucket:owner] w");
1031
1122
  assert.equal(one({ bucket: "verify-now" }).why, "post-deploy: [bucket:verify-now] w");
@@ -1047,6 +1138,13 @@ describe("post-deploy check ids (#4626)", () => {
1047
1138
  assert.equal(followupClass(d("owner:ops", "needs a customer account to read production data")), "external");
1048
1139
  assert.equal(followupClass({ ...d("owner:obs-psql", "read prod data"), class: "ops" }), "ops");
1049
1140
  assert.equal(followupClass(d("host")), "host");
1141
+ // #5186: host + post-promotion text -> rollup; pre-promotion or external need stays host
1142
+ assert.equal(followupClass(d("host", "≥95% success over 7 days by the canary after promotion")), "post-deploy");
1143
+ assert.equal(followupClass(d("host", "billed margin from billing rows in production after promotion")), "post-deploy");
1144
+ assert.equal(followupClass(d("owner:ops", "read billing rows after promotion")), "post-deploy");
1145
+ assert.equal(followupClass(d("host", "capture the page in a browser on the host before promotion")), "host");
1146
+ assert.equal(followupClass(d("host", "capture the page in a browser on the host")), "host");
1147
+ assert.equal(followupClass(d("host", "update the rows after promotion")), "host");
1050
1148
  assert.deepEqual(bucketProblems(d("host")), []);
1051
1149
  assert.match(bucketProblems({ disposition: "post-deploy", check: "a", bucket: "host" }).join(";"), /never post-deploy/);
1052
1150
  assert.match(bucketProblems(d("owner:obs-psql", "capture production query counts")).join(";"), /use bucket host/);
@@ -1405,6 +1503,12 @@ describe("#5087 a plan decision may not weaken an e2e/integration criterion to m
1405
1503
  }
1406
1504
  assert.deepEqual(weakenedE2eDecisions({ ...C, decisions: [{ id: "K1", choice: "Keep playwright e2e coverage; add unit tests (no new fixtures needed for e2e)", source: "doc" }] }), []);
1407
1505
  });
1506
+ it("#5184 a negated omission verb keeps e2e and is not flagged", () => {
1507
+ for (const choice of ["Mocked the gateway with stubs; will not forget to add the e2e test", "Mocked the gateway with stubs; not going to forget to add the e2e test", "Mocked the gateway with stubs; never intending to skip the e2e test", "Stubs for the API; will not fail to run e2e", "Mocks used; never omit the e2e test"]) {
1508
+ assert.deepEqual(weakenedE2eDecisions({ ...C, decisions: [{ id: "K1", choice, source: "doc" }] }), [], choice);
1509
+ }
1510
+ assert.deepEqual(weakenedE2eDecisions({ ...C, decisions: [{ id: "K1", choice: "We do not need to run e2e; mocked route tests cover it", source: "doc" }] }), ["K1"]);
1511
+ });
1408
1512
  it("leaves unrelated decisions and contracts without decisions alone", () => {
1409
1513
  assert.deepEqual(weakenedE2eDecisions(C), []);
1410
1514
  assert.deepEqual(weakenedE2eDecisions({ ...C, decisions: [{ id: "K1", choice: "Run the Playwright e2e suite against the live stack", source: "doc" }, { id: "K3", choice: "Use unit tests with mocks for the parser", source: "spec" }] }), []);
@@ -1472,3 +1576,60 @@ describe("release review #5103", () => {
1472
1576
  }
1473
1577
  });
1474
1578
  });
1579
+
1580
+ import { hostRoute as hostRoute5197 } from "./conformance.mjs";
1581
+ describe("#5197 hostRoute is exported as the single host-route source", () => {
1582
+ it("post-promotion text joins the rollup; pre-promotion and external needs stay host", () => {
1583
+ assert.equal(hostRoute5197({ bucket: "host", why: "verify the dashboard after release" }), "post-deploy");
1584
+ assert.equal(hostRoute5197({ bucket: "host", why: "capture logs before promotion" }), "host");
1585
+ assert.equal(hostRoute5197({ bucket: "host", why: "provide the API key after release" }), "host");
1586
+ });
1587
+ });
1588
+
1589
+ import { intakeHostWork } from "./conformance.mjs";
1590
+ describe("#5250 intakeHostWork", () => {
1591
+ const body = (...items) => `## Problem\nx\n\n## Acceptance Criteria\n\n${items.map((t) => `- [ ] ${t}`).join("\n")}\n`;
1592
+ it("matches when every criterion needs live production measurement or a real-browser capture", () => {
1593
+ const r = intakeHostWork(body("Measured clear rate on live production traffic is above 50%", "Root-cause capture from a real browser is attached"));
1594
+ assert.equal(r.host, true); assert.equal(r.items.length, 2);
1595
+ });
1596
+ it("one code-shaped criterion keeps a code lane", () => {
1597
+ assert.equal(intakeHostWork(body("Measured clear rate on live production traffic is above 50%", "The retry guard stops after a rejection")).host, false);
1598
+ });
1599
+ it("code-only, credential-needing, checklist-less and empty bodies do not match", () => {
1600
+ assert.equal(intakeHostWork(body("The retry guard stops after a rejection")).host, false);
1601
+ assert.equal(intakeHostWork(body("Measure live production latency using the API key")).host, false);
1602
+ assert.equal(intakeHostWork("## Acceptance\nmeasured on live production").host, false);
1603
+ assert.equal(intakeHostWork("").host, false); assert.equal(intakeHostWork(null).host, false);
1604
+ });
1605
+ it("a backlog aggregate that merely quotes such text is not host work", () => {
1606
+ assert.equal(intakeHostWork("## Acceptance Criteria\n\n### #5240\n<!-- FORGE:DEFERRED_FROM: #5240 -->\n\n- [ ] classify issues whose acceptance requires live production measurement or real-browser captures as host work\n").host, false);
1607
+ });
1608
+ });
1609
+
1610
+ describe("contract quote snapping (#5244)", () => {
1611
+ const LINE = "- Add `SLI_CONCENTRATION_MIN_REST_EVENTS` (default 30 per window, documented in `config.env.example`). Below it, publish no signal.";
1612
+ const ISS = `## Problem\n\n${LINE}\n- Remove the legacy **alert** path entirely from the worker.\n- Remove the legacy alert path entirely from the scheduler.\n`;
1613
+ it("markdown inline code spans, elision and spaced identifiers all match", () => {
1614
+ assert.ok(inIssue("Add `SLI_CONCENTRATION_MIN_REST_EVENTS` (default 30 per window, documented in `config.env.example`).", ISS));
1615
+ assert.ok(inIssue("Add SLI_CONCENTRATION_MIN_REST_EVENTS (default 30 per window, documented in config.env.example). Below it, publish...", ISS));
1616
+ assert.ok(inIssue("Add `SLI_CONCENTRATION_MIN_REST_EVENTS` (default 30 per window, documented in `config.env.example`). Below it, publish…", ISS));
1617
+ assert.ok(inIssue("Add SLI CONCENTRATION MIN REST EVENTS (default 30 per window", ISS));
1618
+ assert.ok(!inIssue("Add SLI_CONCENTRATION_MIN_REST_EVENTS (default 99 per window", ISS));
1619
+ });
1620
+ it("a near-verbatim quote snaps to the one issue line and records the original", () => {
1621
+ const q = "Add the SLI_CONCENTRATION_MIN_REST_EVENTS (default 30 per window, documented in config.env.example)";
1622
+ assert.ok(!inIssue(q, ISS));
1623
+ const c = { requirements: [{ id: "R2b", quote: q, disposition: "deliver" }] };
1624
+ const { contract, snapped } = snapQuotes(c, ISS);
1625
+ assert.equal(snapped.length, 1);
1626
+ assert.ok(contract.requirements[0].quote.includes("`SLI_CONCENTRATION_MIN_REST_EVENTS`"));
1627
+ assert.equal(contract.requirements[0].requoted, q);
1628
+ assert.ok(inIssue(contract.requirements[0].quote, ISS));
1629
+ });
1630
+ it("an ambiguous or dissimilar quote does not snap", () => {
1631
+ assert.equal(snapQuote("Remove the legacy alert path entirely from the service", ISS), null);
1632
+ assert.equal(snapQuote("Publish a completely different dashboard widget for billing", ISS), null);
1633
+ assert.equal(snapQuotes({ requirements: [{ id: "R1", quote: "totally unrelated words about something else here" }] }, ISS).snapped.length, 0);
1634
+ });
1635
+ });
@@ -119,6 +119,9 @@ const namesSymbol = (text, symbols) => symbols.some((s) => new RegExp(`(?:^|[^\\
119
119
 
120
120
  const STOPWORDS = new Set(("about after again also always another because before being between both cannot could does doing during each every from have having into issue issues just make makes more most must never only other over same should some such than that their them then there these they this those through under until very what when where which while will with within without would your " +
121
121
  "fix fixes fixed bug bugs feat chore docs test tests file files when wrong error errors fail fails failed failing add adds remove update use uses").split(" "));
122
+ /** #5110: status/label-like tokens that match a large share of any repo's history; a code or word made only of them is not a subject. */
123
+ const GENERIC_TERMS = new Set("blocked generic broad base status state failure failures result results page pages response default common general detection handling".split(" "));
124
+ const isGeneric = (t) => String(t).toLowerCase().split(/[._-]+/).filter(Boolean).every((x) => GENERIC_TERMS.has(x) || STOPWORDS.has(x));
122
125
  const FILE_EXT = /\.(?:m?[jt]sx?|cjs|md|sh|json|ya?ml|py|go|rs|rb|css|html|txt|toml|lock|sql)$/i;
123
126
  /** #5085: subject terms split by kind: codes and symbols (exact, quoted searches) and distinctive title words. */
124
127
  function subjectParts({ title = "", body = "" } = {}) {
@@ -131,8 +134,9 @@ function subjectParts({ title = "", body = "" } = {}) {
131
134
  for (const s of issueSymbols(body)) if (!codes.some((c) => c.toLowerCase().endsWith(`.${s.toLowerCase()}`))) add(s);
132
135
  const head = stripComments(title).replace(/^\s*\w+(?:\([^)]*\))?!?:\s*/, "");
133
136
  const words = [];
134
- for (const w of head.toLowerCase().match(/[a-z][a-z0-9-]{3,}/g) ?? []) if (!STOPWORDS.has(w) && !words.includes(w) && !codes.some((c) => c.toLowerCase() === w)) words.push(w);
135
- return { codes: codes.slice(0, 3), words: words.slice(0, 3) };
137
+ const tokens = [...(head.match(/\b[A-Z][A-Z0-9]{2}\b/g) ?? []), ...(head.toLowerCase().match(/[a-z][a-z0-9-]{3,}/g) ?? [])];
138
+ for (const raw of tokens) { const w = raw.toLowerCase(); if (!isGeneric(w) && !words.includes(w) && !codes.some((c) => c.toLowerCase() === w)) words.push(w); }
139
+ return { codes: codes.filter((c) => !isGeneric(c)).slice(0, 3), words: words.slice(0, 3) };
136
140
  }
137
141
  /** #5085: the issue's subject terms, codes and symbols first, then title words; deterministic, deduped, at most 6. */
138
142
  export function subjectTerms({ title = "", body = "" } = {}) {
@@ -228,7 +232,7 @@ async function readComments(gh, repo, n) {
228
232
 
229
233
  /**
230
234
  * #5085: closed issues and merged PRs on the same subject, found by term rather than by issue number or file: up to
231
- * MAX_SUBJECT_QUERIES GitHub searches (each code/symbol quoted, then the title words together) and one `git log --grep`
235
+ * MAX_SUBJECT_QUERIES GitHub searches (each non-generic code/symbol quoted, then the title words, #5110: generic codes are never searched) and one `git log --grep`
232
236
  * over the whole history of `base`. `exclude` (self, linked issues) is dropped; rows are ranked by the number of
233
237
  * matched terms, then newest first, and capped. A failed query lands in `errors`; the rest still count.
234
238
  * @returns {Promise<{terms:string[], rows:{number:number, kind:string, status:string, title:string, matched:string[]}[], errors:string[]}>}
@@ -245,7 +249,9 @@ export async function subjectHistory({ io, repo, issue = null, title = "", body
245
249
  hits.set(n, row);
246
250
  };
247
251
  if (!terms.length) return { terms, rows: [], errors };
248
- const queries = [...codes.slice(0, words.length ? MAX_SUBJECT_QUERIES - 1 : MAX_SUBJECT_QUERIES).map((c) => [c]), ...(words.length ? [words] : [])].slice(0, MAX_SUBJECT_QUERIES);
252
+ // #5110: words are searched whatever the codes are; three words run as overlapping pairs so an earlier attempt that names only two of them still matches (full matches rank first)
253
+ const groups = words.length > 2 ? [words.slice(0, 2), words.slice(1)] : words.length ? [words] : [];
254
+ const queries = [...codes.slice(0, MAX_SUBJECT_QUERIES - groups.length).map((c) => [c]), ...groups].slice(0, MAX_SUBJECT_QUERIES);
249
255
  for (const q of queries) {
250
256
  const text = q.length === 1 && codes.includes(q[0]) ? `"${q[0]}"` : q.join(" ");
251
257
  try {
@@ -258,19 +264,23 @@ export async function subjectHistory({ io, repo, issue = null, title = "", body
258
264
  } catch (e) { errors.push(`attempts: subject search ${oneLine(e?.message ?? e, 80)}`); }
259
265
  }
260
266
  if (base && io.git) {
261
- try {
262
- const greps = codes.length ? ["-E", `--grep=${codes.map(reEscape).join("|")}`] : ["--all-match", ...words.map((w) => `--grep=${reEscape(w)}`)];
263
- const out = String(await io.git(["log", "-i", ...greps, "-n", "20", "--format=%x1e%H%x1f%s%x1f%b", base]));
264
- for (const rec of out.split("\x1e").filter((x) => x.trim())) {
265
- const [, subject = "", msg = ""] = rec.split("\x1f");
266
- const pr = Number(/Merge pull request #(\d+)/.exec(subject)?.[1] ?? /\(#(\d+)\)\s*$/.exec(subject.trim())?.[1]) || null;
267
- const hay = `${subject}\n${msg}`.toLowerCase();
268
- const matched = (codes.length ? codes : words).filter((t) => hay.includes(t.toLowerCase()));
269
- if (!pr || !matched.length || (!codes.length && matched.length < words.length)) continue;
270
- const named = /^Merge pull request/.test(subject) ? msg.split("\n").map((l) => l.trim()).find(Boolean) ?? subject : subject;
271
- hit(pr, { src: "git", kind: "PR", status: "merged", title: oneLine(named, 120) }, matched);
272
- }
273
- } catch (e) { errors.push(`attempts: subject git log ${oneLine(e?.message ?? e, 80)}`); }
267
+ // one repo-wide log per kind: codes (any), words (all of a group)
268
+ const runs = [...(codes.length ? [{ greps: ["-E", `--grep=${codes.map(reEscape).join("|")}`], groups: codes.map((c) => [c]) }] : []),
269
+ ...(words.length ? [{ greps: ["--all-match", ...words.map((w) => `--grep=${reEscape(w)}`)], groups: [words] }] : [])];
270
+ for (const run of runs) {
271
+ try {
272
+ const out = String(await io.git(["log", "-i", ...run.greps, "-n", "20", "--format=%x1e%H%x1f%s%x1f%b", base]));
273
+ for (const rec of out.split("\x1e").filter((x) => x.trim())) {
274
+ const [, subject = "", msg = ""] = rec.split("\x1f");
275
+ const pr = Number(/Merge pull request #(\d+)/.exec(subject)?.[1] ?? /\(#(\d+)\)\s*$/.exec(subject.trim())?.[1]) || null;
276
+ const hay = `${subject}\n${msg}`.toLowerCase();
277
+ const matched = run.groups.filter((g) => g.every((t) => hay.includes(t.toLowerCase()))).flat();
278
+ if (!pr || !matched.length) continue;
279
+ const named = /^Merge pull request/.test(subject) ? msg.split("\n").map((l) => l.trim()).find(Boolean) ?? subject : subject;
280
+ hit(pr, { src: "git", kind: "PR", status: "merged", title: oneLine(named, 120) }, matched);
281
+ }
282
+ } catch (e) { errors.push(`attempts: subject git log ${oneLine(e?.message ?? e, 80)}`); }
283
+ }
274
284
  }
275
285
  const rows = [...hits.values()].sort((a, b) => b.matched.length - a.matched.length || b.number - a.number)
276
286
  .slice(0, max);
@@ -530,6 +530,21 @@ describe("#5085: subject history and recall status", () => {
530
530
  assert.ok(kinds.indexOf("subject") > kinds.lastIndexOf("salvage"), kinds.join(","));
531
531
  });
532
532
 
533
+ it("#5110: generic quoted codes do not replace the subject words", async () => {
534
+ const corpus = [item(34683, "Classify dead origins: TLS cert verify failures"), item(35204, "classify dead origins failures"), item(39485, "deploy reverts hotfixes blocked.generic broad-base"), item(32764, "release safety blocked.generic generic broad-base")].map((j) => JSON.parse(j));
535
+ const search = (q) => { const terms = q.replace(/^q=repo:\S+ is:closed /, "").replace(/"/g, "").toLowerCase().split(" "); return corpus.filter((c) => terms.every((t) => c.title.toLowerCase().includes(t))).map((c) => JSON.stringify(c)).join("\n"); };
536
+ const title = "fix(detection): ~85% of broad-base 'blocked.generic' are dead origins (cert-invalid, parked, TLS-refused) that run the full ladder";
537
+ const body = "Most `blocked.generic` rows on the `broad-base` crawl are dead origins.";
538
+ assert.ok(!subjectTerms({ title, body }).some((t) => /generic|broad/.test(t)), subjectTerms({ title, body }).join(","));
539
+ const f = fakes({ search });
540
+ const r = await subjectHistory({ io: f.io, repo: REPO, issue: 50, title, body, base: "origin/staging" });
541
+ assert.deepEqual(r.rows.map((x) => x.number).sort(), [34683, 35204]);
542
+ assert.ok(!f.calls.some((c) => c.some((x) => /generic|broad-base/.test(String(x)) && String(x).startsWith("q="))), "no search on a generic code");
543
+ assert.ok(r.rows[0].number === 34683 || r.rows[0].matched.length >= r.rows[1].matched.length);
544
+ const only = await subjectHistory({ io: fakes({ search }).io, repo: REPO, issue: 50, title: "fix(x): 'blocked.generic' on broad-base", body: "`blocked.generic`" });
545
+ assert.deepEqual(only, { terms: [], rows: [], errors: [] });
546
+ });
547
+
533
548
  it("ranks rows by matched-term count, then newest number", async () => {
534
549
  const search = (q) => (q.includes('"a.code"') ? [item(901, "x"), item(950, "y")] : q.includes('"b.code"') ? [item(901, "x")] : []).join("\n");
535
550
  const r = await subjectHistory({ io: fakes({ search }).io, repo: REPO, issue: 50, title: "", body: "`a.code` and `b.code`" });
@@ -110,8 +110,9 @@ export const leanSettingsFlags = ({ subagentModel = null, reread = false, guard
110
110
  };
111
111
 
112
112
  export function makeLeanRunner({ runCli = runCliBackendAsync, probe = systemdRunAvailable, subagentModel = null, sandboxed = inSandbox() } = {}) {
113
- return async ({ role, issue, cwd, model, resume, system, prompt, readOnly = false, noTools = false, rereadNudge = false, maxTurns = null, agents = null, env = null, idleMs = 0, maxMs = 0, laneLimits = null, control = null, onSpawn = null, contextMax = 0, turnMax = 0, busy = null, busyMs = 0, onIdleExtend = null }) => {
114
- const bin = resolveClaudeCliBinary(cwd) || "claude";
113
+ return async ({ role, issue, cwd, model, resume, system, prompt, readOnly = false, noTools = false, rereadNudge = false, maxTurns = null, agents = null, env = null, idleMs = 0, maxMs = 0, laneLimits = null, control = null, onSpawn = null, contextMax = 0, turnMax = 0, busy = null, busyMs = 0, onIdleExtend = null, bin: pinnedBin = null }) => {
114
+ // #5205: a rotation relaunch pins the real claude past the tokenbaton shim; absent, the usual resolution
115
+ const bin = pinnedBin || resolveClaudeCliBinary(cwd) || "claude";
115
116
  const caps = getClaudeCliCapabilities(cwd);
116
117
  // #4391: custom subagents (the explorer) for the builder session; null leaves argv unchanged
117
118
  const flags = [...buildLeanSessionFlags(caps), ...(noTools ? noToolFlags(caps) : readOnly ? buildReadOnlyToolFlags(caps) : []), ...(agents ? ["--agents", JSON.stringify(agents)] : [])];
@@ -366,9 +367,12 @@ export function makeLeanIo({ repo, subagentModel = readSubagentModel() }) {
366
367
  try { const out = String(await run("gh")(["run", "view", String(runId), "-R", repo, "--log-failed"])); return out.length > 64000 ? out.slice(-64000) : out; } catch { return ""; }
367
368
  },
368
369
  async transitionLabel(issue, state) { await pexec("bash", [script("transition-label.sh"), String(issue), "-R", repo, state], { timeout: 60000 }); },
370
+ /** Finding lifecycle (#5254): needs-validation to validated / false-positive. */
371
+ async validateLabel(issue, verdict) { await pexec("bash", [script("transition-label.sh"), "--validate", verdict, String(issue), "-R", repo], { timeout: 60000 }); },
369
372
  /**
370
- * File (or append to) the parent's ONE batched follow-up issue (scripts/file-deferred-followups.sh: trusted lookup,
371
- * append, create, claim marker, duplicate re-check; one issue per class, #4664). items: [{key, why, class?}]; the key is the
373
+ * Append the parent's deferred items to the aggregates only (scripts/file-deferred-followups.sh: trusted lookup, append,
374
+ * create, duplicate re-check): the release rollup, the batch external aggregate and the batch host aggregate; never a
375
+ * per-parent issue, and an engineering item is rejected (exit 2, #5207). items: [{key, why, class?}]; the key is the
372
376
  * item's identity (column 5, column 1 is `-`). milestone / defaultMilestone: the parent's and forge.yaml followups.default_milestone; lane: the release lane of the post-deploy rollup (#4724).
373
377
  * batchId: the external aggregate's batch (FORGE_BATCH_ID); rollupLabel: forge.yaml followups.rollup_issue_label (FORGE_ROLLUP_LABEL) (#5078).
374
378
  * Returns {key: issueNumber}; throws on exit 2/3/4.
@@ -406,9 +410,9 @@ export function makeLeanIo({ repo, subagentModel = readSubagentModel() }) {
406
410
  pitfalls: makePitfallStore(),
407
411
  /** forge#4275: the context pack's facts for one issue (bin/lean/context.mjs), from gh and git only; sources fail independently. */
408
412
  contextFacts: (args) => gatherContextFacts({ ...args, io: { gh: run("gh"), git: run("git"), exists: async (p) => existsSync(p) } }),
409
- /** forge#4195: scripts/hotspots.sh facts for `paths` in cwd (growth since base when given); null on any failure. */
410
- async hotspots({ cwd, base = null, paths = [] }) {
411
- const args = [script("hotspots.sh"), ...(base ? ["--base", base] : []), "--", ...paths];
413
+ /** forge#4195: scripts/hotspots.sh facts for `paths` in cwd (growth since base when given; config = the host forge.yaml, #5163); null on any failure. */
414
+ async hotspots({ cwd, base = null, paths = [], config = null }) {
415
+ const args = [script("hotspots.sh"), ...(config ? ["--config", config] : []), ...(base ? ["--base", base] : []), "--", ...paths];
412
416
  try { return JSON.parse((await pexec("bash", args, { cwd, timeout: 30000, maxBuffer: 16 * 1024 * 1024 })).stdout); } catch { return null; }
413
417
  },
414
418
  /** #4322: tests enumerating the members of the given paths, and new members those tests miss (bin/lean/enumerating.mjs); [] on failure. */
@@ -137,7 +137,8 @@ export function parseExecution(sec = {}) {
137
137
  const warmSandboxes = str(s.warm_sandboxes) !== "" && Number.isInteger(wsN) && wsN > 0 ? wsN : 0; // #4912: warm sandboxes the pool agent keeps ready; 0 = off
138
138
  const relay = Object.fromEntries(Object.entries(parseRelayCommands(s.relay_commands)).filter(([c]) => CAPABILITY_RE.test(c))); // #4778
139
139
  const uw = Number(str(s.unreachable_window_min));
140
- const accountRotator = str(s.account_rotator) === "tokenbaton" ? "tokenbaton" : null; // #5094: rotator.mjs reads its per-account quota state
140
+ // #5094: rotator.mjs reads its per-account quota state; #5205: off/none/false disables auto-detection, anything else is unset (auto)
141
+ const rot = str(s.account_rotator).toLowerCase(), accountRotator = rot === "tokenbaton" ? "tokenbaton" : ["off", "none", "false"].includes(rot) ? "off" : null;
141
142
  const unreachableWindowMin = str(s.unreachable_window_min) !== "" && Number.isFinite(uw) && uw >= 0 ? uw : null; // unset: providerLanes defaults to 5
142
143
  return { mode, maxRemote, provider, image, secrets, budget, ...(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 } : {}) };
143
144
  }
@@ -684,7 +685,16 @@ export function providerLanes({ provider, laneArgs, ledgerFor, env = process.env
684
685
  : { terminalReason: "needs-human", code: OUTCOME_CODES.SANDBOX_START_FAILED, detail: `sandbox ${id} failed to start: ${errText(e)}` });
685
686
  return {
686
687
  // #4612: a graceful stop of a live sandbox (the provider's checkpoint stop); false when it has none.
687
- stopLane: async (n, rec) => (typeof provider.stop === "function" && rec?.handle ? (await provider.stop(rec.handle)) === true : false),
688
+ // #5241: false leaves its reason on `rec.stopNote`, so the cancel reports a lane it could not stop.
689
+ stopLane: async (n, rec) => {
690
+ const note = (why) => { if (rec && typeof rec === "object") rec.stopNote = why; };
691
+ if (typeof provider.stop !== "function") { note("the provider cannot stop a lane"); return false; }
692
+ if (!rec?.handle) { note("no sandbox handle yet"); return false; }
693
+ let ok = false;
694
+ try { ok = (await provider.stop(rec.handle)) === true; } catch (e) { note(`stop failed: ${e?.message ?? e}`); return false; }
695
+ if (!ok) note((typeof provider.stopReason === "function" ? provider.stopReason(rec.handle) : null) ?? "stop not accepted");
696
+ return ok;
697
+ },
688
698
  runOne: async (n, lane, ctx = {}) => {
689
699
  const led = ledgerFor(n);
690
700
  const base = { provider: provider.name, id: provider.idFor(n), issue: n, startedAt: now() };
@@ -714,7 +724,13 @@ export function providerLanes({ provider, laneArgs, ledgerFor, env = process.env
714
724
  adopt: (n, rec, ctx = {}) => adoptSaved(n, rec, ctx),
715
725
  };
716
726
  async function adoptSaved(n, rec, ctx = {}) {
717
- const saved = rec?.handle;
727
+ let saved = rec?.handle;
728
+ // #5204: a record saved before its handle (the old dispatcher halted first) finds the sandbox through the lane's ledger,
729
+ // which registers it before it exists: a live one is reattached, a gone one reaped below, never orphaned.
730
+ if (!saved?.id) {
731
+ const id = provider.idFor(n);
732
+ saved = (ledgerFor(n)?.entries("sandbox") ?? []).find((e) => e.value === id && (e.provider ?? e.handle?.provider) === provider.name)?.handle;
733
+ }
718
734
  if (!saved?.id || saved.provider !== provider.name) return null;
719
735
  // Usage runs from the sandbox's real start (persisted on the handle), not from this adopt.
720
736
  const h = { ...saved, ...(Number.isFinite(saved.startedAt) ? {} : Number.isFinite(rec?.startedAt) ? { startedAt: rec.startedAt } : {}) };
@@ -242,6 +242,45 @@ describe("providerLanes: sandbox ledger and teardown on every exit path (#4253)"
242
242
  });
243
243
  });
244
244
 
245
+ describe("#5204: a remote lane saved without its handle is reattached or reaped through the sandbox ledger", () => {
246
+ const leftBy = (root, n, provider = "fake") => makeLedger({ root, batch: "bt", lane: `sandbox-${n}`, owner: "orch_old", issue: n, host: HOST, pid: 999999 })
247
+ .register("sandbox", `fake-${n}`, { provider, handle: { provider, id: `fake-${n}`, issue: n, startedAt: 500 } });
248
+ it("a live sandbox is reattached (onLive, then its result) and torn down after", async () => {
249
+ const root = tmpDir("exec-5204-live-");
250
+ leftBy(root, 7);
251
+ const ledgerFor = ledgerIn(root);
252
+ const prov = fakeProvider();
253
+ prov.live.add(7);
254
+ let live = 0;
255
+ const lanes = providerLanes({ provider: prov, laneArgs: () => [], ledgerFor, pollMs: 1, now: () => 500, sleep: async () => { prov.results[7] = { terminalReason: "merged", pr: 4 }; prov.live.delete(7); } });
256
+ const r = await lanes.adopt(7, { startedAt: 1, remote: true }, { onLive: () => { live++; } });
257
+ assert.equal(live, 1, "reattached as a live lane");
258
+ assert.equal(r.terminalReason, "merged");
259
+ assert.equal(r.pr, 4);
260
+ assert.ok(prov.calls.some((c) => c[0] === "teardown" && c[1] === "fake-7"));
261
+ assert.equal(ledgerFor(7).read(), null, "the ledger entry is released");
262
+ });
263
+ it("a gone sandbox is reaped (torn down, ledger released) and the adopt returns null so the lane is requeued", async () => {
264
+ const root = tmpDir("exec-5204-gone-");
265
+ leftBy(root, 8);
266
+ const ledgerFor = ledgerIn(root);
267
+ const prov = fakeProvider();
268
+ const r = await providerLanes({ provider: prov, laneArgs: () => [], ledgerFor, pollMs: 1 }).adopt(8, { startedAt: 1, remote: true });
269
+ assert.equal(r, null);
270
+ assert.ok(prov.calls.some((c) => c[0] === "teardown" && c[1] === "fake-8"), "reaped, never orphaned");
271
+ assert.equal(ledgerFor(8).read(), null);
272
+ });
273
+ it("another provider's ledger entry, or no entry, is not adopted", async () => {
274
+ const root = tmpDir("exec-5204-other-");
275
+ leftBy(root, 9, "other");
276
+ const prov = fakeProvider();
277
+ const lanes = providerLanes({ provider: prov, laneArgs: () => [], ledgerFor: ledgerIn(root), pollMs: 1 });
278
+ assert.equal(await lanes.adopt(9, { remote: true }), null);
279
+ assert.equal(await lanes.adopt(10, { remote: true }), null);
280
+ assert.ok(!prov.calls.some((c) => c[0] === "teardown"));
281
+ });
282
+ });
283
+
245
284
  describe("runner kill: a sandbox left by a dead dispatcher is reaped by gc --apply (#4253)", () => {
246
285
  it("lists the stale sandbox, removes the container, releases the ledger; a live one is only reported", async () => {
247
286
  const home = tmpDir("exec-gc-");
@@ -0,0 +1,16 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /** Finding lifecycle at close: a `review-finding` issue leaves `needs-validation` as `validated` (merged fix) or `false-positive` (INVALID). */
4
+ export const FINDING_LABEL = "review-finding";
5
+ const VERDICTS = { merged: "CONFIRMED", invalid: "INVALID" };
6
+
7
+ const names = (labels) => (labels ?? []).map((l) => l?.name ?? l);
8
+ export const isFinding = (labels) => names(labels).includes(FINDING_LABEL);
9
+ export const findingVerdict = (reason) => VERDICTS[reason] ?? null;
10
+
11
+ /** Best effort: `{ applied, error? }`; non-findings and unmapped reasons are untouched. transition-label.sh --validate is idempotent. */
12
+ export async function resolveFindingLabel({ io, issue, labels, reason }) {
13
+ const verdict = findingVerdict(reason);
14
+ if (!verdict || !isFinding(labels)) return { applied: false };
15
+ try { await io.validateLabel(issue, verdict); return { applied: true, verdict }; } catch (e) { return { applied: false, error: String(e?.message ?? e).slice(0, 160) }; }
16
+ }
@@ -0,0 +1,39 @@
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 { readFileSync } from "node:fs";
6
+ import { resolveFindingLabel, isFinding, findingVerdict } from "./findinglabel.mjs";
7
+
8
+ const fake = (fail) => { const calls = []; return { calls, validateLabel: async (n, v) => { calls.push([n, v]); if (fail) throw new Error("gh down"); } }; };
9
+ const F = [{ name: "review-finding" }, { name: "needs-validation" }];
10
+
11
+ describe("finding close resolves needs-validation (#5254)", () => {
12
+ it("finding close resolves needs-validation: merged finding gets CONFIRMED (validated)", async () => {
13
+ const io = fake();
14
+ assert.equal((await resolveFindingLabel({ io, issue: 7, labels: F, reason: "merged" })).applied, true);
15
+ assert.deepEqual(io.calls, [[7, "CONFIRMED"]]);
16
+ });
17
+ it("finding close resolves needs-validation: invalid finding gets INVALID (false-positive)", async () => {
18
+ const io = fake();
19
+ await resolveFindingLabel({ io, issue: 7, labels: ["review-finding"], reason: "invalid" });
20
+ assert.deepEqual(io.calls, [[7, "INVALID"]]);
21
+ });
22
+ it("non-findings and other reasons are untouched", async () => {
23
+ const io = fake();
24
+ await resolveFindingLabel({ io, issue: 7, labels: [{ name: "bug" }], reason: "merged" });
25
+ await resolveFindingLabel({ io, issue: 7, labels: F, reason: "needs-human" });
26
+ assert.deepEqual(io.calls, []);
27
+ assert.equal(isFinding(undefined), false);
28
+ assert.equal(findingVerdict("merged"), "CONFIRMED");
29
+ });
30
+ it("a failing label call is reported, never thrown", async () => {
31
+ const r = await resolveFindingLabel({ io: fake(true), issue: 7, labels: F, reason: "merged" });
32
+ assert.equal(r.applied, false); assert.match(r.error, /gh down/);
33
+ });
34
+ it("lean.mjs wires both close paths; effects runs transition-label.sh --validate", () => {
35
+ const lean = readFileSync(new URL("./lean.mjs", import.meta.url), "utf8");
36
+ assert.match(lean, /reason: "merged" \}\)/); assert.match(lean, /reason: "invalid" \}\)/);
37
+ assert.match(readFileSync(new URL("./effects.mjs", import.meta.url), "utf8"), /"--validate", verdict/);
38
+ });
39
+ });
@@ -26,6 +26,7 @@ import { writeAtomic } from "./batch.mjs";
26
26
  import { schedDir, pidAlive, DEFAULT_PRIORITY } from "./sched.mjs";
27
27
  import { which } from "./toolchain.mjs";
28
28
  import { hostParallelism } from "./admission.mjs";
29
+ import { lowerPriority } from "./hostload.mjs";
29
30
 
30
31
  export const HEAVY_DEFAULTS = Object.freeze({ enabled: true, max: null, step_mem_mb: 2048, reserve_mb: 1024, ramp_s: 60, max_wait_s: 1800 });
31
32
  export const HEAVY_POLL_MS = 2000;
@@ -388,13 +389,15 @@ export async function runWrapped(argv, { env: env0 = process.env, open = openHea
388
389
  let cores = 1; try { cores = hostP.cores() || 1; } catch { /* 1 */ }
389
390
  const childEnv = { ...env, FORGE_HEAVY_HELD: "1",
390
391
  ...(env.FORGE_HEAVY_PARALLELISM_PINNED === "1" ? {} : { FORGE_HOST_PARALLELISM: String(hostParallelism({ cores, lanes: g.holders })) }) };
391
- try { return await run(cmd, args, childEnv); } finally { g.release(); }
392
+ // #5174: a gated step runs at nice 10 / ionice idle so local test runners and installs do not starve the schedd event loop.
393
+ try { return await run(cmd, args, childEnv, (child) => lowerPriority(child?.pid)); } finally { g.release(); }
392
394
  }
393
395
 
394
- /** Spawn with inherited stdio; resolves {code, signal}; forwards termination signals to the child. */
395
- export function spawnInherit(cmd, args, env) {
396
+ /** Spawn with inherited stdio; resolves {code, signal}; forwards termination signals to the child. `onSpawn(child)` runs once it has a pid. */
397
+ export function spawnInherit(cmd, args, env, onSpawn = null) {
396
398
  return new Promise((done) => {
397
399
  const child = spawn(cmd, args, { stdio: "inherit", env });
400
+ if (onSpawn && child.pid) { try { onSpawn(child); } catch { /* best effort */ } }
398
401
  const fwd = (sig) => { try { child.kill(sig); } catch { /* gone */ } };
399
402
  const sigs = ["SIGTERM", "SIGINT", "SIGHUP"];
400
403
  for (const s of sigs) process.on(s, fwd);