forgedock 1.52.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 (93) 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 +53 -16
  4. package/bin/experiment.mjs +58 -6
  5. package/bin/forge-utils.mjs +6 -2
  6. package/bin/forgedock.mjs +15 -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 +195 -22
  21. package/bin/lean/conformance.test.mjs +152 -5
  22. package/bin/lean/effects.mjs +8 -4
  23. package/bin/lean/execution.mjs +19 -3
  24. package/bin/lean/execution.test.mjs +39 -0
  25. package/bin/lean/findinglabel.mjs +16 -0
  26. package/bin/lean/findinglabel.test.mjs +39 -0
  27. package/bin/lean/issuewatch-release.mjs +6 -2
  28. package/bin/lean/issuewatch-release.test.mjs +16 -0
  29. package/bin/lean/issuewatch.mjs +11 -1
  30. package/bin/lean/lanelock.mjs +14 -0
  31. package/bin/lean/lean.mjs +165 -34
  32. package/bin/lean/lean.test.mjs +289 -9
  33. package/bin/lean/light.mjs +48 -7
  34. package/bin/lean/light.test.mjs +37 -3
  35. package/bin/lean/limits.test.mjs +142 -9
  36. package/bin/lean/orchestrate-cancel.test.mjs +143 -0
  37. package/bin/lean/orchestrate.mjs +96 -26
  38. package/bin/lean/postdeploy-check.test.mjs +39 -0
  39. package/bin/lean/prompts.mjs +8 -7
  40. package/bin/lean/quota.mjs +39 -0
  41. package/bin/lean/recovery.test.mjs +10 -0
  42. package/bin/lean/relaxation.mjs +73 -0
  43. package/bin/lean/relaxation.test.mjs +54 -0
  44. package/bin/lean/release-postmerge.mjs +119 -0
  45. package/bin/lean/release-rehearsal.mjs +63 -0
  46. package/bin/lean/release-rehearsal.test.mjs +93 -0
  47. package/bin/lean/release-review.e2e.test.mjs +77 -0
  48. package/bin/lean/release-review.mjs +198 -0
  49. package/bin/lean/release-review.test.mjs +180 -0
  50. package/bin/lean/release.mjs +228 -0
  51. package/bin/lean/release.test.mjs +292 -0
  52. package/bin/lean/rotator.mjs +150 -31
  53. package/bin/lean/rotator.test.mjs +105 -2
  54. package/bin/lean/sandbox-remote.mjs +9 -2
  55. package/bin/lean/schedd.mjs +49 -4
  56. package/bin/lean/schedd.test.mjs +87 -6
  57. package/bin/lean/verifier.mjs +3 -2
  58. package/bin/lean/verify.mjs +2 -1
  59. package/bin/lean/verify.test.mjs +6 -0
  60. package/bin/pool/agent.mjs +18 -4
  61. package/bin/pool/router.mjs +66 -24
  62. package/bin/review-staging.mjs +23 -0
  63. package/bin/stats/conformance-outcomes.mjs +208 -0
  64. package/bin/stats/conformance-outcomes.test.mjs +188 -0
  65. package/bin/stats/depth.mjs +218 -0
  66. package/bin/stats/depth.test.mjs +133 -0
  67. package/bin/stats/experiment.mjs +7 -5
  68. package/bin/stats/github-source.mjs +2 -2
  69. package/bin/stats/index.mjs +64 -2
  70. package/bin/stats/local-source.mjs +11 -0
  71. package/bin/stats/query.mjs +69 -0
  72. package/bin/stats/selffiled.mjs +52 -0
  73. package/bin/stats/selffiled.test.mjs +71 -0
  74. package/commands/orchestrate.md +1 -1
  75. package/commands/review-pr-agents/security.md +4 -0
  76. package/commands/review-pr-staging.md +2 -0
  77. package/commands/work-on/build.md +4 -6
  78. package/docs/CONFIG.md +65 -8
  79. package/docs/ISSUE-WATCH.md +2 -0
  80. package/docs/OUTCOME-CODES.md +3 -0
  81. package/docs/STATS.md +44 -0
  82. package/docs/TELEMETRY.md +1 -1
  83. package/package.json +1 -1
  84. package/pool/README.md +1 -1
  85. package/pool/image/cs-cred +14 -1
  86. package/scripts/backfill-finding-labels.mjs +50 -0
  87. package/scripts/backfill-finding-labels.test.mjs +36 -0
  88. package/scripts/doctor-pipeline-state.sh +21 -6
  89. package/scripts/file-deferred-followups.sh +59 -251
  90. package/scripts/file-deferred-followups.test.sh +85 -206
  91. package/scripts/followup-route.mjs +12 -0
  92. package/scripts/owner-route-parity.test.sh +17 -1
  93. 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", "backlog"]);
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(";"));
@@ -1025,8 +1115,8 @@ describe("post-deploy check ids (#4626)", () => {
1025
1115
  assert.equal(followupClass({ disposition: "defer", bucket: "owner:spend" }), "external");
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
- assert.equal(followupClass({ disposition: "defer", bucket: "new-issue", class: "post-deploy" }), "backlog");
1029
- assert.equal(followupClass({ disposition: "defer", bucket: "new-issue" }), "backlog"); assert.equal(followupClass({ disposition: "defer", bucket: "new-issue", class: "ops" }), "ops"); // #5188
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
1030
1120
  for (const bucket of ["post-deploy", "verify-now", "date:2026-12-01"]) assert.equal(followupClass({ disposition: "defer", bucket }), "post-deploy");
1031
1121
  assert.equal(one({ bucket: "owner:rotate the key" }).why, "owner: rotate the key. [bucket:owner] w");
1032
1122
  assert.equal(one({ bucket: "verify-now" }).why, "post-deploy: [bucket:verify-now] w");
@@ -1486,3 +1576,60 @@ describe("release review #5103", () => {
1486
1576
  }
1487
1577
  });
1488
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
+ });
@@ -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.
@@ -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
+ });
@@ -176,7 +176,7 @@ export function releasePlanComment({ theme, tag, decision, policy, now }) {
176
176
  `**Included:** ${r.set.map((i) => `#${i.number}`).join(" ")}`,
177
177
  ...(r.pulled.length ? [`**Pulled prerequisites:** ${r.pulled.map((p) => `#${p.number} (${p.theme}, for #${p.for})`).join(", ")}`] : []),
178
178
  `**Excluded (stay pooled):** ${r.excluded.map((e) => `#${e.number} (${e.reason})`).join(", ") || "none"}`,
179
- "Promotion to the default branch stays human-only; the watch opens the deploy PR and never merges it."].join("\n");
179
+ "Promotion to the default branch stays opt-in (`release.auto_merge`); the watch opens the deploy PR, starts `forgedock release` for it and never merges it itself."].join("\n");
180
180
  }
181
181
 
182
182
  // ── the tick ─────────────────────────────────────────────────────────────────────────────────────────────────
@@ -200,7 +200,11 @@ export async function releaseTick({ watch, repo, io, state, defaults = [], listO
200
200
  if (!base) throw new Error("no default branch known; cannot open the deploy PR");
201
201
  const open = JSON.parse(await gh(["pr", "list", "-R", repo, "--head", rel.lane, "--base", base, "--state", "open", "--json", "number"]));
202
202
  rel.deployPr = open[0]?.number ?? (+(/(\d+)\s*$/.exec(await gh(["pr", "create", "-R", repo, "--base", base, "--head", rel.lane, "--title", `release(${rel.theme}): ${rel.tag}`,
203
- "--body", `Themed release **${rel.theme}** (${rel.tag}).\n\nIssues: ${rel.issues.map((n) => `#${n}`).join(" ")}\nMerged: ${state.merged.filter((n) => rel.issues.includes(n)).map((n) => `#${n}`).join(" ") || "none"}\nFailed: ${state.failed.filter((n) => rel.issues.includes(n)).map((n) => `#${n}`).join(" ") || "none"}\n\nPromotion is human-only: the issue watch opened this PR and never merges it.`]))?.[1]) || true);
203
+ "--body", `Themed release **${rel.theme}** (${rel.tag}).\n\nIssues: ${rel.issues.map((n) => `#${n}`).join(" ")}\nMerged: ${state.merged.filter((n) => rel.issues.includes(n)).map((n) => `#${n}`).join(" ") || "none"}\nFailed: ${state.failed.filter((n) => rel.issues.includes(n)).map((n) => `#${n}`).join(" ") || "none"}\n\nThe issue watch opened this PR and starts forgedock release for it; it never merges (promotion is opt-in via release.auto_merge).`]))?.[1]) || true);
204
+ }
205
+ // Hand the deploy PR to the release job (#5214); a failed start is recorded, never thrown (claims must not strand). Promotion stays opt-in.
206
+ if (io.release?.start && !rel.job) {
207
+ try { rel.job = (await io.release.start({ repo, pr: rel.deployPr, tag: rel.tag })) || "started"; } catch (e) { rel.jobError = String(e?.message ?? e); }
204
208
  }
205
209
  (state.releases ??= []).push(rel); state.release = null;
206
210
  }
@@ -244,3 +244,19 @@ test("CLI: --dry-run prints the cut without writing; refuses a non-release watch
244
244
  const w = loadWatches(`issue_watch:\n watches:\n sr:\n mode: release\n threshold: { min_issues: 2 }\n`).sr;
245
245
  assert.match(formatStatus({ name: "sr", repo: "o/r", phase: "running", claimed: [1], inflight: [1], merged: [], verified: [], failed: [], pool: [2, 3], llm: 2, releases: [], release: { theme: "billing", issues: [1], batch: "b1" } }, w), /pool: 2.*active: billing.*llm-classified: 2/);
246
246
  });
247
+
248
+ test("#5214: the deploy PR is handed to the release job once, without merge; a failed start is recorded", async () => {
249
+ for (const [prs, fail] of [[[], false], [[{ number: 9 }], false], [[], true]]) {
250
+ const issues = [1, 2, 3].map((n) => iss(n, { labels: lbl("billing") }));
251
+ const io = world(issues, { prs }), started = [];
252
+ io.release = { start: async (a) => { started.push(a); if (fail) throw new Error("spawn failed"); return "r1"; } };
253
+ const w = W(), st = fresh();
254
+ await step(io, w, st);
255
+ io.reported.add("b1"); io.closed.add(1);
256
+ await step(io, w, st);
257
+ assert.deepEqual(started, [{ repo: "o/r", pr: prs[0]?.number ?? 77, tag: "billing-2026-10-30" }]);
258
+ assert.equal(st.releases[0].job, fail ? undefined : "r1"); assert.equal(st.releases[0].jobError, fail ? "spawn failed" : undefined);
259
+ assert.equal(io.calls.some((a) => a[0] === "pr" && a[1] === "merge"), false);
260
+ await step(io, w, st); assert.equal(started.length, 1);
261
+ }
262
+ });
@@ -9,7 +9,7 @@
9
9
  * batch (batch.mjs `addIssues`, so K, the `Depends on` DAG and the report apply) and starts a new one after it reports.
10
10
  * No LLM calls.
11
11
  */
12
- import { existsSync, mkdirSync, readFileSync, rmdirSync } from "node:fs";
12
+ import { existsSync, mkdirSync, readFileSync, readdirSync, rmdirSync } from "node:fs";
13
13
  import { execFileSync, spawn, spawnSync } from "node:child_process";
14
14
  import { homedir, hostname } from "node:os";
15
15
  import { dirname, join } from "node:path";
@@ -18,6 +18,7 @@ import { writeAtomic, batchRoot, openBatch, listBatches } from "./batch.mjs";
18
18
  import { milestoneSlug, readBranches, isDefaultLane, defaultBranches, DEFAULT_STAGING_BRANCH, DEFAULT_FEATURE_PATTERN } from "./lane.mjs";
19
19
  import { postDeployOnly } from "./prefilter.mjs";
20
20
  import { releaseTick, formatDryRun } from "./issuewatch-release.mjs";
21
+ import { releaseRoot } from "./release.mjs";
21
22
  import { loadPolicy } from "./decision-engine.mjs";
22
23
  import { decisionContext, decisionsActive, decisionStep, decisionCounts, formatDecisionDryRun, claimsUsed } from "./issuewatch-decisions.mjs";
23
24
  import { APP_SLUG } from "../init-repo.mjs";
@@ -483,6 +484,15 @@ function realIo(repo, env = process.env) {
483
484
  p.on("close", (code) => { res = { code: code ?? 1 }; }); p.on("error", () => { res = { code: 1 }; });
484
485
  return { poll: () => res };
485
486
  },
487
+ release: {
488
+ // #5214: start the resumable `forgedock release` job for the deploy PR; no --merge (promotion is release.auto_merge only)
489
+ start: async ({ repo: r }) => {
490
+ const dir = releaseRoot(env), ls = () => { try { return readdirSync(dir); } catch { return []; } }, before = new Set(ls());
491
+ spawn(process.execPath, [CLI, "release", "--repo", r], { detached: true, windowsHide: true, stdio: "ignore", cwd: process.cwd(), env }).unref();
492
+ for (let i = 0; i < 10; i++) { const id = ls().find((x) => !before.has(x)); if (id) return id; await new Promise((res) => setTimeout(res, 500)); }
493
+ return "started";
494
+ },
495
+ },
486
496
  batch: {
487
497
  add: (id, issues) => openBatch(root, id).addIssues(issues),
488
498
  // release #5068 MAT-1: the CLI path checks the label, reopens a finished batch and hosts it on the schedd
@@ -29,3 +29,17 @@ export async function otherLaneOwner({ gh, repo, issue, branch = `feat/issue-${i
29
29
  const other = Array.isArray(prs) ? prs.find((p) => Number.isInteger(p?.number) && p.number !== ownPr) : null;
30
30
  return other ? { kind: "pr", detail: `PR #${other.number} is open on ${branch} from another lane` } : null;
31
31
  }
32
+
33
+ /**
34
+ * #5241: clear the lease on `issue`'s FORGE:STATE when `shouldClear(lease)` agrees (a cancelled lane's, once it ended).
35
+ * @param {{projector: {readState: Function, writeState: Function}, issue: number, shouldClear?: (lease: object) => boolean}} a
36
+ * @returns {Promise<boolean>} true when a lease was cleared; false when none, kept by the guard, or GitHub is unreadable (fail-safe)
37
+ */
38
+ export async function clearLease({ projector, issue, shouldClear = () => true }) {
39
+ try {
40
+ const st = await projector.readState(issue);
41
+ if (!st?.lease || !shouldClear(st.lease)) return false;
42
+ await projector.writeState(issue, { ...st, lease: null });
43
+ return true;
44
+ } catch { return false; }
45
+ }