forgedock 1.54.1 → 1.55.1

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 (115) hide show
  1. package/bin/config-schema.mjs +12 -0
  2. package/bin/engine/events.mjs +1 -0
  3. package/bin/engine/events.test.mjs +5 -1
  4. package/bin/engine/outcome-codes.mjs +3 -0
  5. package/bin/engine-cli.mjs +126 -34
  6. package/bin/forge-utils.mjs +37 -5
  7. package/bin/forgedock.mjs +54 -2
  8. package/bin/gc-schedule.mjs +83 -0
  9. package/bin/gc.mjs +66 -10
  10. package/bin/help-text.mjs +1 -1
  11. package/bin/hooks/pre-tool-use.mjs +1 -0
  12. package/bin/init-detect.mjs +73 -2
  13. package/bin/labels.json +5 -0
  14. package/bin/lean/admission.mjs +21 -1
  15. package/bin/lean/baselines.mjs +43 -0
  16. package/bin/lean/baselines.test.mjs +33 -0
  17. package/bin/lean/batch-health.mjs +43 -6
  18. package/bin/lean/batch-health.test.mjs +41 -1
  19. package/bin/lean/batch.mjs +41 -4
  20. package/bin/lean/batch.test.mjs +106 -3
  21. package/bin/lean/conformance.mjs +131 -12
  22. package/bin/lean/conformance.test.mjs +172 -3
  23. package/bin/lean/depcache.mjs +23 -2
  24. package/bin/lean/depcache.test.mjs +22 -0
  25. package/bin/lean/docsgate.mjs +137 -0
  26. package/bin/lean/docsgate.test.mjs +78 -0
  27. package/bin/lean/effects.mjs +31 -2
  28. package/bin/lean/enumerating.mjs +39 -13
  29. package/bin/lean/enumerating.test.mjs +20 -0
  30. package/bin/lean/execution.test.mjs +3 -3
  31. package/bin/lean/fastforward.mjs +93 -0
  32. package/bin/lean/fastforward.test.mjs +73 -0
  33. package/bin/lean/guardgate.mjs +38 -7
  34. package/bin/lean/guardgate.test.mjs +39 -0
  35. package/bin/lean/issuewatch-install.mjs +92 -0
  36. package/bin/lean/issuewatch-install.test.mjs +31 -0
  37. package/bin/lean/issuewatch-parity.mjs +33 -3
  38. package/bin/lean/issuewatch-parity.test.mjs +30 -5
  39. package/bin/lean/issuewatch-reconcile.mjs +123 -0
  40. package/bin/lean/issuewatch-reconcile.test.mjs +30 -0
  41. package/bin/lean/issuewatch-verify.mjs +51 -9
  42. package/bin/lean/issuewatch.mjs +153 -33
  43. package/bin/lean/issuewatch.test.mjs +243 -22
  44. package/bin/lean/lean.mjs +381 -75
  45. package/bin/lean/lean.test.mjs +437 -20
  46. package/bin/lean/light.mjs +11 -3
  47. package/bin/lean/light.test.mjs +27 -0
  48. package/bin/lean/lightlane.mjs +8 -3
  49. package/bin/lean/lightlane.test.mjs +20 -0
  50. package/bin/lean/mechfix.mjs +21 -2
  51. package/bin/lean/mechfix.test.mjs +28 -1
  52. package/bin/lean/orchestrate-children.test.mjs +10 -0
  53. package/bin/lean/orchestrate-owned.test.mjs +73 -0
  54. package/bin/lean/orchestrate.mjs +28 -4
  55. package/bin/lean/overlap.mjs +20 -0
  56. package/bin/lean/overlap.test.mjs +49 -0
  57. package/bin/lean/pagegate.mjs +152 -0
  58. package/bin/lean/pagegate.test.mjs +77 -0
  59. package/bin/lean/parked-relabel.mjs +32 -0
  60. package/bin/lean/parked-relabel.test.mjs +45 -0
  61. package/bin/lean/phaseledger.mjs +17 -2
  62. package/bin/lean/postdeploy-check.mjs +27 -0
  63. package/bin/lean/postdeploy-check.test.mjs +13 -1
  64. package/bin/lean/postrun.mjs +32 -0
  65. package/bin/lean/postrun.test.mjs +41 -0
  66. package/bin/lean/preflight.mjs +46 -0
  67. package/bin/lean/preflight.test.mjs +30 -1
  68. package/bin/lean/prompts.mjs +36 -6
  69. package/bin/lean/recovery.test.mjs +16 -0
  70. package/bin/lean/release-review.mjs +12 -1
  71. package/bin/lean/release-review.test.mjs +14 -0
  72. package/bin/lean/release.mjs +23 -2
  73. package/bin/lean/release.test.mjs +28 -1
  74. package/bin/lean/render.mjs +17 -6
  75. package/bin/lean/reproquality.mjs +116 -0
  76. package/bin/lean/reproquality.test.mjs +85 -0
  77. package/bin/lean/review-trigger.mjs +8 -3
  78. package/bin/lean/sandbox-budget.test.mjs +27 -0
  79. package/bin/lean/schedd.mjs +40 -11
  80. package/bin/lean/schedd.test.mjs +12 -1
  81. package/bin/lean/testadequacy.mjs +97 -0
  82. package/bin/lean/testadequacy.test.mjs +92 -0
  83. package/bin/lean/testsandbox.mjs +202 -0
  84. package/bin/lean/testsandbox.test.mjs +157 -0
  85. package/bin/lean/toolplace.mjs +5 -2
  86. package/bin/lean/toolplace.test.mjs +6 -0
  87. package/bin/lean/verify.mjs +6 -1
  88. package/bin/lean/verify.test.mjs +18 -2
  89. package/bin/lean/warmtree.mjs +77 -0
  90. package/bin/lean/warmtree.test.mjs +81 -0
  91. package/bin/review-staging.mjs +51 -9
  92. package/bin/stats/conformance-outcomes.mjs +12 -2
  93. package/bin/stats/depth.mjs +24 -1
  94. package/bin/stats/depth.test.mjs +21 -1
  95. package/bin/stats/index.mjs +5 -2
  96. package/bin/stats/query.mjs +2 -1
  97. package/commands/cleanup.md +18 -0
  98. package/commands/fd-introspect.md +19 -0
  99. package/commands/milestone.md +5 -1
  100. package/commands/pipeline-health/phase-2-metrics.md +4 -0
  101. package/commands/recover-orphans.md +31 -1
  102. package/commands/review-pr-staging.md +9 -0
  103. package/commands/review-pr.md +2 -0
  104. package/docs/CONFIG.md +26 -1
  105. package/docs/EVENTS.md +1 -0
  106. package/docs/ISSUE-WATCH.md +12 -3
  107. package/docs/eval/adversarial-bench.md +1 -1
  108. package/docs/eval/published/adversarial-2026-11-11.md +58 -0
  109. package/package.json +1 -1
  110. package/scripts/bench-lightlane.mjs +3 -2
  111. package/scripts/hotspots.sh +7 -4
  112. package/scripts/hotspots.test.sh +12 -0
  113. package/scripts/recover-orphans-stateless.test.sh +79 -0
  114. package/scripts/transition-label.sh +2 -0
  115. package/templates/workflows/forgedock-reopen-clean.yml +33 -0
@@ -21,6 +21,8 @@ import { postDeployOnly } from "./prefilter.mjs";
21
21
 
22
22
  export const LIGHT_MODES = Object.freeze(["off", "shadow", "on"]);
23
23
  export const LIGHT_DEFAULTS = Object.freeze({ mode: "shadow", maxLines: 40, maxFiles: 2 });
24
+ /** #5426: where eligibility is computed from: the issue text (default) or the investigation's predicted files and size (bin/lean/fastforward.mjs). */
25
+ export const LIGHT_SOURCES = Object.freeze(["text", "investigation"]);
24
26
  /** #5209: commits in 90 days (scripts/hotspots.sh commits_90d) at or above which a named file records a `churn_high` signal. */
25
27
  export const CHURN_HIGH = 20;
26
28
 
@@ -34,10 +36,12 @@ const posInt = (v) => { const s = String(v ?? "").trim(); return /^\d+$/.test(s)
34
36
  export function parseLightConfig(lean = {}) {
35
37
  const l = lean && typeof lean === "object" ? lean : {};
36
38
  const m = String(l.light_mode ?? l.mode ?? "").trim().toLowerCase();
39
+ const src = String(l.light_source ?? l.source ?? "").trim().toLowerCase();
37
40
  return {
38
41
  mode: LIGHT_MODES.includes(m) ? m : LIGHT_DEFAULTS.mode,
39
42
  maxLines: posInt(l.light_max_lines) ?? posInt(l.max_lines) ?? LIGHT_DEFAULTS.maxLines,
40
43
  maxFiles: posInt(l.light_max_files) ?? posInt(l.max_files) ?? LIGHT_DEFAULTS.maxFiles,
44
+ ...(LIGHT_SOURCES.includes(src) ? { source: src } : {}), // #5426: unset = investigation (see fastforward.mjs); `text` is the kill-switch
41
45
  };
42
46
  }
43
47
 
@@ -92,13 +96,14 @@ function riskDetails(files, riskPaths) {
92
96
  * reason. `signals` lists every evaluated signal (codes: repro|no_repro, files_named, churn_high, hotspot, risk_path,
93
97
  * label_docs|label_config|label_chore, size_S|size_M|size_L|size_none) and never changes the verdict.
94
98
  */
95
- export function lightEligibility({ title = "", body = "", labels = [], predictedFiles = [], riskPaths = [], hotspots = [], cfg = {} } = {}) {
99
+ export function lightEligibility({ title = "", body = "", labels = [], predictedFiles = [], riskPaths = [], hotspots = [], cfg = {}, source = "text", size: sizeOverride = null, extraHard = [], preText = null } = {}) {
96
100
  const c = cfgOf(cfg);
97
101
  if (c.mode === "off") return { mode: "off", verdict: "off", eligible: false, light: false, reasons: [], signals: [] };
98
102
  const hard = [], soft = [], signals = [];
99
103
  const text = String(body ?? "").replace(/<!--[\s\S]*?-->/g, " ");
104
+ const fromInvestigation = source === "investigation"; // #5426: the investigator's confirmation replaces the text repro requirement
100
105
  if (!FENCE_RE.test(text) && !REPRO_RE.test(text)) {
101
- soft.push({ code: "no_repro", detail: "no repro, expected behaviour or code block in the body" });
106
+ if (!fromInvestigation) soft.push({ code: "no_repro", detail: "no repro, expected behaviour or code block in the body" });
102
107
  signals.push({ code: "no_repro", detail: "no repro, expected behaviour or code block in the body" });
103
108
  } else signals.push({ code: "repro", detail: "repro, expected behaviour or code block in the body" });
104
109
 
@@ -122,9 +127,11 @@ export function lightEligibility({ title = "", body = "", labels = [], predicted
122
127
  }
123
128
 
124
129
  const names = labelNames(labels);
125
- const size = laneSize({ labels: names });
130
+ const size = ["S", "M", "L"].includes(sizeOverride) ? sizeOverride : laneSize({ labels: names });
126
131
  if (size && size !== "S") hard.push({ code: "size", detail: `size:${size}` });
127
132
  signals.push({ code: size ? `size_${size}` : "size_none", detail: size ? `size:${size}` : "no size label" });
133
+ if (fromInvestigation) signals.push({ code: "source_investigation", detail: "predicted files, size and risk come from the investigation" });
134
+ if (preText) signals.push({ code: `pre_text_${preText}`, detail: `the pre-investigation text heuristic said ${preText}` }); // shadow only
128
135
  for (const [code, re] of KIND_LABELS) {
129
136
  const n = names.find((x) => re.test(x));
130
137
  if (n) signals.push({ code, detail: `label ${n}` });
@@ -132,6 +139,7 @@ export function lightEligibility({ title = "", body = "", labels = [], predicted
132
139
 
133
140
  for (const d of riskDetails(files, riskPaths)) { hard.push({ code: "risk_path", detail: d }); signals.push({ code: "risk_path", detail: d }); }
134
141
 
142
+ for (const x of Array.isArray(extraHard) ? extraHard : []) if (x?.code) { hard.push({ code: String(x.code), detail: String(x.detail ?? "") }); signals.push({ code: String(x.code), detail: String(x.detail ?? "") }); }
135
143
  if (isInvestigation(title)) hard.push({ code: "investigate", detail: "investigate( issue" });
136
144
  const pdLabel = names.find((n) => POST_DEPLOY_LABELS.has(n.toLowerCase()));
137
145
  if (pdLabel) hard.push({ code: "post_deploy", detail: `label ${pdLabel}` });
@@ -205,3 +205,30 @@ describe("light.mjs purity (#4448)", () => {
205
205
  for (const m of ["node:fs", "node:child_process", "node:net", "node:http", "node:https"]) assert.equal(src.includes(`"${m}"`), false, m);
206
206
  });
207
207
  });
208
+
209
+ describe("lightEligibility source/size/pre_text (#5426)", () => {
210
+ const base = { title: "fix", body: "tidy the helper", predictedFiles: ["src/a.py"], cfg: ON };
211
+ it("source text is unchanged: no repro is a soft reason, no source signal", () => {
212
+ const r = lightEligibility(base);
213
+ assert.equal(r.signals.some((s) => s.code === "source_investigation"), false);
214
+ assert.equal(r.reasons.some((x) => x.code === "no_repro"), true);
215
+ });
216
+ it("source investigation records the source and drops the text repro requirement", () => {
217
+ const r = lightEligibility({ ...base, source: "investigation", size: "S" });
218
+ assert.equal(r.light, true);
219
+ assert.equal(r.signals.some((s) => s.code === "source_investigation"), true);
220
+ });
221
+ it("size override M is a hard size reason; pre_text is a signal only", () => {
222
+ const m = lightEligibility({ ...base, source: "investigation", size: "M" });
223
+ assert.equal(m.light, false);
224
+ assert.equal(m.reasons.some((x) => x.code === "size"), true);
225
+ const p = lightEligibility({ ...base, source: "investigation", size: "S", preText: "ineligible" });
226
+ assert.equal(p.light, true);
227
+ assert.equal(p.signals.some((s) => s.code === "pre_text_ineligible"), true);
228
+ });
229
+ it("parseLightConfig accepts source text|investigation only", () => {
230
+ assert.equal(parseLightConfig({ source: "investigation" }).source, "investigation");
231
+ assert.equal(parseLightConfig({ source: "text" }).source, "text");
232
+ assert.equal("source" in parseLightConfig({ source: "bogus" }), false);
233
+ });
234
+ });
@@ -37,7 +37,7 @@ When done and committed, write ${IMPLEMENTATION_FILE} (markdown, no HTML comment
37
37
  ### Changes (file: what)
38
38
  ### Verification (each test command, its result, and whether the new test fails without the fix)
39
39
 
40
- Finally write ${RESULT_FILE}: {"status":"fixed","summary":"one line","requirement":"<one sentence of the issue, verbatim, that this fix delivers>","repro_test":{"path":"<test file>","id":"<test name>","command":"<exact command that runs only that test>"},"tests":[{"command":"<targeted test command>","result":"pass|fail: ...","fails_without_fix":true|false|"unknown"}]}
40
+ Finally write ${RESULT_FILE}: {"status":"fixed","summary":"one line","requirement":"<one sentence of the issue, verbatim, that this fix delivers>","repro_test":{"path":"<test file>","id":"<test name>","command":"<exact command that runs only that test>"},"test_plan":[{"requirement":"R1","proof":"<the root-cause observable that was wrong and must now hold, never 'the fix is present'>","level":"unit|integration|e2e|live","level_reason":"<why the cheapest level that observes the cause; never mock the component the bug lives in>","repro":"<test id> or no-repro","reason":"<no-repro only>","regression":[],"env":[],"command":"<exact command>"}],"tests":[{"command":"<targeted test command>","result":"pass|fail: ...","fails_without_fix":true|false|"unknown"}]}
41
41
  If the issue is invalid, already fixed, blocked, or bigger than a small fix (more than a couple of files, a design decision), do not grind: write {"status":"upgrade","summary":"<why>"} and stop. The engine then runs the full lane, keeping what you committed.`;
42
42
  }
43
43
 
@@ -92,10 +92,12 @@ export function deriveLightContract({ title = "", issueText = "", result = null,
92
92
  const repro = t && typeof t === "object" && !Array.isArray(t) && String(t.path ?? "").trim() && String(t.command ?? "").trim()
93
93
  ? { path: String(t.path).trim(), id: String(t.id ?? "").trim(), command: String(t.command).trim() } : null;
94
94
  const commands = [...new Set([repro?.command, ...(Array.isArray(r.tests) ? r.tests : []).map((x) => (x && typeof x === "object" ? String(x.command ?? "").trim() : ""))].filter(Boolean))];
95
+ const plan = Array.isArray(r.test_plan) ? r.test_plan.filter((x) => x && typeof x === "object").map((x) => ({ ...x, requirement: "R1" })).slice(0, 1) : []; // #5445: the single light requirement carries one plan row
95
96
  return {
96
97
  requirements: [{ id: "R1", quote, disposition: "deliver" }],
97
98
  deliverables: code.map((path, i) => ({ id: `D${i + 1}`, path, change: "light-lane fix (issue-named file)", requirements: ["R1"] })),
98
99
  validate: commands.map((command, i) => ({ id: `V${i + 1}`, command })),
100
+ ...(plan.length ? { test_plan: plan } : {}),
99
101
  ...(repro ? { repro_test: repro } : { repro_test: "none", repro_test_reason: "the light-lane builder named no repro test" }),
100
102
  };
101
103
  }
@@ -200,9 +202,10 @@ const bullets = (xs) => {
200
202
  * The FORGE:LITE receipt of a light lane (#4452, parent #4442), without the marker (pure): outcome, diff stat, red/green
201
203
  * repro, gates (targeted tests, API shape, derived contract), cost and eligibility, plus the upgrade reasons when the lane
202
204
  * moved to the full pipeline. `costUsd` is the lane's true cost so far: the sum of #4407 per-session deltas, never a
203
- * running session total. `lr` is runLightStep's return; `eligibility` is lightEligibility's.
205
+ * running session total. `lr` is runLightStep's return; `eligibility` is lightEligibility's. `skipped` (#5426) is
206
+ * fastforward.mjs skippedStages: listed only on a fast-forwarded lane that did not upgrade.
204
207
  */
205
- export function renderLiteReceipt({ lr = {}, eligibility = null, costUsd = null, contractHash = null } = {}) {
208
+ export function renderLiteReceipt({ lr = {}, eligibility = null, costUsd = null, contractHash = null, skipped = [] } = {}) {
206
209
  const r = lr && typeof lr === "object" ? lr : {};
207
210
  const upgraded = !!r.upgrade;
208
211
  const rows = Array.isArray(r.diff?.files) ? r.diff.files : null;
@@ -236,6 +239,8 @@ export function renderLiteReceipt({ lr = {}, eligibility = null, costUsd = null,
236
239
  `**Eligibility:** ${one(e.verdict ?? "unknown", 20)} (mode ${one(e.mode ?? "?", 10)})${e.verdict === "eligible" && !eReasons.length ? ": repro or expected behaviour, predicted files within limits, size S, no risk path" : ""}`,
237
240
  ...bullets(eReasons),
238
241
  ];
242
+ const skips = (Array.isArray(skipped) ? skipped : []).filter((x) => x && x.stage); // #5426: a fast-forwarded lane names what it skipped
243
+ if (skips.length && !upgraded) lines.push("**Fast-forward (investigation decided the depth):** skipped stages", ...bullets(skips.map((x) => `${one(x.stage, 40)}: ${one(x.why)}`)));
239
244
  if (upgraded) {
240
245
  const ups = (Array.isArray(r.reasons) ? r.reasons : []).filter((x) => x && x.code).map((x) => `${one(x.code, 40)}: ${one(x.detail)}`);
241
246
  lines.push("**Upgrade reasons:**", ...bullets(ups.length ? ups : ["unknown"]));
@@ -197,6 +197,14 @@ describe("renderLiteReceipt (#4452)", () => {
197
197
  assert.ok(!/<!--|undefined|NaN/.test(body), body);
198
198
  });
199
199
 
200
+ it("#5426 a fast-forwarded lane lists the skipped stages and why; an upgraded one does not", async () => {
201
+ const skipped = [{ stage: "plan", why: "small change" }, { stage: "contract freeze", why: "small change" }];
202
+ const ok = renderLiteReceipt({ lr: await runLightStep(step().ctx), eligibility: ELIG, skipped });
203
+ assert.match(ok, /\*\*Fast-forward \(investigation decided the depth\):\*\* skipped stages\n - plan: small change\n - contract freeze: small change/);
204
+ assert.ok(!/Fast-forward/.test(renderLiteReceipt({ lr: await runLightStep(step().ctx), eligibility: ELIG })));
205
+ assert.ok(!/Fast-forward/.test(renderLiteReceipt({ lr: { upgrade: true, reasons: [{ code: "diff_lines", detail: "x" }] }, eligibility: ELIG, skipped })));
206
+ });
207
+
200
208
  it("an upgraded lane lists the gates that fired and the upgrade reasons; free text is sanitised", async () => {
201
209
  const api = { status: "changed", changes: [{ file: "src/foo.js", symbol: "foo", change: "sync-async" }], unknown: [] };
202
210
  const r = await runLightStep(step({ api, testRcs: [1, 1], repro: { base: "PASSED", head: "RAN" } }).ctx);
@@ -269,3 +277,15 @@ describe("#4502 light lane fixes", () => {
269
277
  assert.deepEqual(seen, [900000, 900000]);
270
278
  });
271
279
  });
280
+
281
+ describe("light lane freezes a test plan (#5445)", () => {
282
+ const PLAN = { requirement: "R9", proof: "foo returns null for a null argument instead of throwing a TypeError", level: "unit", level_reason: "a direct call observes the cause", repro: "foo handles null", regression: [], env: [], command: "node --test test/foo.test.js" };
283
+ const strict = (c) => validateContract(c, ISSUE, { repro: true, testPlan: true });
284
+ it("a derived bug contract without a test_plan row is rejected; with one it is frozen as R1", () => {
285
+ const bare = deriveLightContract({ title: TITLE, issueText: ISSUE, result: RESULT, files: FILES });
286
+ assert.match(strict(bare).problems.join("\n"), /R1: test_plan needs a row/);
287
+ const c = deriveLightContract({ title: TITLE, issueText: ISSUE, result: { ...RESULT, test_plan: [PLAN] }, files: FILES });
288
+ assert.equal(c.test_plan[0].requirement, "R1");
289
+ assert.deepEqual(strict(c), { ok: true, problems: [] });
290
+ });
291
+ });
@@ -60,12 +60,13 @@ export function insertIntoList(text, line, symbols) {
60
60
  * @returns {{applied: object[], remaining: object[]}}
61
61
  */
62
62
  export function applyEnumerating({ missing = [], cwd, fsx = fs } = {}) {
63
- const applied = [], remaining = [];
63
+ const applied = [], remaining = [], originals = new Map();
64
64
  const byTest = new Map();
65
65
  for (const m of missing) { if (!byTest.has(m.test)) byTest.set(m.test, []); byTest.get(m.test).push(m); }
66
66
  for (const [test, rows] of byTest) {
67
67
  let text;
68
68
  try { text = fsx.readFileSync(join(cwd, test), "utf8"); } catch { remaining.push(...rows); continue; }
69
+ const text0 = text;
69
70
  const groups = new Map();
70
71
  for (const m of rows) { const k = `${m.line}\0${m.module}`; if (!groups.has(k)) groups.set(k, []); groups.get(k).push(m); }
71
72
  let changed = false;
@@ -77,9 +78,27 @@ export function applyEnumerating({ missing = [], cwd, fsx = fs } = {}) {
77
78
  for (const m of g) (done.has(m.symbol) ? mine : remaining).push(m);
78
79
  if (r.inserted.length) { text = r.text; changed = true; }
79
80
  }
80
- if (changed) { try { fsx.writeFileSync(join(cwd, test), text); } catch { remaining.push(...mine); continue; } }
81
+ if (changed) { const before = text0; try { fsx.writeFileSync(join(cwd, test), text); } catch { remaining.push(...mine); continue; } originals.set(test, before); }
81
82
  applied.push(...mine);
82
83
  }
84
+ return { applied, remaining, originals };
85
+ }
86
+
87
+ /**
88
+ * #5480: run each test file applyEnumerating edited (`runTest(path)` -> true when green); a red one gets its original text
89
+ * back and its rows move to `remaining`, so the engine never commits an edit that fails a test.
90
+ * @returns {Promise<{applied: object[], remaining: object[]}>}
91
+ */
92
+ export async function verifyApplied({ result, cwd, runTest, fsx = fs } = {}) {
93
+ const applied = [], remaining = [...(result?.remaining ?? [])];
94
+ for (const [test, before] of result?.originals ?? []) {
95
+ const rows = (result.applied ?? []).filter((m) => m.test === test);
96
+ let green = false;
97
+ try { green = (await runTest(test)) === true; } catch { green = false; }
98
+ if (green) { applied.push(...rows); continue; }
99
+ try { fsx.writeFileSync(join(cwd, test), before); } catch { /* the detector re-run still sees the file */ }
100
+ remaining.push(...rows);
101
+ }
83
102
  return { applied, remaining };
84
103
  }
85
104
 
@@ -4,7 +4,7 @@ import { describe, it } from "node:test";
4
4
  import assert from "node:assert/strict";
5
5
  import fs from "node:fs";
6
6
  import { join } from "node:path";
7
- import { insertIntoList, applyEnumerating, renamedExport, renameDuplicates } from "./mechfix.mjs";
7
+ import { insertIntoList, applyEnumerating, verifyApplied, renamedExport, renameDuplicates } from "./mechfix.mjs";
8
8
  import { tmpDir } from "../tests/_tmp.mjs";
9
9
 
10
10
  const tmp = () => tmpDir("mechfix-");
@@ -93,3 +93,30 @@ describe("#5348 duplicate export rename", () => {
93
93
  assert.match(fs.readFileSync(join(w.cwd, "app/ui.ts"), "utf8"), /export const Button = 1/);
94
94
  });
95
95
  });
96
+
97
+ describe("#5480 verify-after-edit", () => {
98
+ const setup = () => {
99
+ const cwd = tmp(), orig = `const names = [\n "alpha",\n "beta",\n "gamma",\n];\n`;
100
+ fs.writeFileSync(join(cwd, "t.test.mjs"), orig);
101
+ const missing = [{ symbol: "delta", module: "m", test: "t.test.mjs", line: 3 }];
102
+ return { cwd, orig, result: applyEnumerating({ missing, cwd }) };
103
+ };
104
+ it("a red test gets its original text back and its rows move to remaining", async () => {
105
+ const { cwd, orig, result } = setup();
106
+ const r = await verifyApplied({ result, cwd, runTest: async () => false });
107
+ assert.equal(r.applied.length, 0); assert.equal(r.remaining.length, 1);
108
+ assert.equal(fs.readFileSync(join(cwd, "t.test.mjs"), "utf8"), orig);
109
+ });
110
+ it("a green test keeps the edit", async () => {
111
+ const { cwd, result } = setup();
112
+ const r = await verifyApplied({ result, cwd, runTest: async () => true });
113
+ assert.equal(r.applied.length, 1); assert.equal(r.remaining.length, 0);
114
+ assert.match(fs.readFileSync(join(cwd, "t.test.mjs"), "utf8"), /"delta"/);
115
+ });
116
+ it("a runner that throws counts as red", async () => {
117
+ const { cwd, orig, result } = setup();
118
+ const r = await verifyApplied({ result, cwd, runTest: async () => { throw new Error("x"); } });
119
+ assert.equal(r.remaining.length, 1);
120
+ assert.equal(fs.readFileSync(join(cwd, "t.test.mjs"), "utf8"), orig);
121
+ });
122
+ });
@@ -93,3 +93,13 @@ describe("#4965 auto_add_children", () => {
93
93
  }
94
94
  });
95
95
  });
96
+
97
+ describe("#5437 post-run after the slot frees", () => {
98
+ it("result.postRun runs once the lane's slot is free (the next lane starts) and the batch waits for it", async () => {
99
+ const order = [];
100
+ await orchestrate({ issues: [1, 2], parallel: 1, pollMs: 5, trusted: () => true, readBody: async () => "",
101
+ runOne: async (n) => { order.push(`start:${n}`); return n === 1 ? { terminalReason: "merged", postRun: async () => { order.push("post:1"); await new Promise((r) => setTimeout(r, 60)); order.push("post-done:1"); } } : merged; } });
102
+ assert.ok(order.indexOf("start:2") < order.indexOf("post-done:1"), `lane 2 starts while the post-run job is still running: ${order}`);
103
+ assert.ok(order.includes("post-done:1"), "the batch did not end before the job finished");
104
+ });
105
+ });
@@ -0,0 +1,73 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // #5471: --add/--requeue/dispatch skip an issue another live batch of the repo holds; --force overrides; status warns.
4
+ import { describe, it } from "node:test";
5
+ import assert from "node:assert/strict";
6
+ import { tmpDir } from "../tests/_tmp.mjs";
7
+ import { sharedPendingLines } from "./schedd.mjs";
8
+ import { openBatch, ownerOf, dispatchOwner } from "./batch.mjs";
9
+ import { orchestrateFromCli, makeDispatchCheck } from "../engine-cli.mjs";
10
+
11
+ process.env.FORGEDOCK_SCHED_DIR = tmpDir("owned-sched-");
12
+ const quiet = async (fn) => { const l = console.log; console.log = () => {}; try { return await fn(); } finally { console.log = l; } };
13
+ const queued = (p) => p.catch((e) => { if (e?.code === "batch.not-hosted") return e.result; throw e; });
14
+ const seed = (root, id, { order = [5], running = {}, pending = [], results = {}, held = [], repo = "o/r" } = {}) => {
15
+ const b = openBatch(root, id);
16
+ b.writePlan({ v: 1, id, repo });
17
+ b.store.save({ order, running, pending, results, notBefore: {} });
18
+ if (held.length) b.holdIssues(held);
19
+ return b;
20
+ };
21
+ const io = { gh: async (a) => { if (a[0] === "api") return "OWNER\n"; return JSON.stringify({ state: "OPEN", labels: [] }); } };
22
+
23
+ describe("cross-batch ownership (#5471)", () => {
24
+ it("add skips an issue pending in another live batch of the repo, naming the owner; after the owner finishes it, B may add it", async () => {
25
+ const root = tmpDir("owned-add-");
26
+ seed(root, "bA", { pending: [5] });
27
+ const b = seed(root, "bB", { order: [1], pending: [1] });
28
+ const res = await queued(quiet(() => orchestrateFromCli(["--add", "bB", "5"], { batchRoot: root, io })));
29
+ assert.deepEqual(res.added, []);
30
+ assert.deepEqual(res.skipped.map((x) => [x.issue, x.reason]), [[5, "owned by bA"]]);
31
+ assert.deepEqual(b.readAdded(), []);
32
+ openBatch(root, "bA").store.save({ order: [5], running: {}, pending: [], results: { 5: { outcome: "merged" } }, notBefore: {} });
33
+ const again = await queued(quiet(() => orchestrateFromCli(["--add", "bB", "5"], { batchRoot: root, io })));
34
+ assert.deepEqual(again.added, [5]);
35
+ });
36
+ it("--force overrides the add skip; another repo's batch does not own", async () => {
37
+ const root = tmpDir("owned-force-");
38
+ seed(root, "bA", { pending: [5] });
39
+ seed(root, "bC", { pending: [6], order: [6], repo: "o/other" });
40
+ const b = seed(root, "bB", { order: [1], pending: [1] });
41
+ const res = await queued(quiet(() => orchestrateFromCli(["--add", "bB", "5", "6", "--force", "dup ok"], { batchRoot: root, io })));
42
+ assert.deepEqual(res.added, [5, 6]);
43
+ assert.equal(ownerOf(root, "o/r", 6, "bB"), null);
44
+ assert.deepEqual(b.readAdded(), [5, 6]);
45
+ });
46
+ it("requeue refuses an issue another live batch runs, held counts as owned", async () => {
47
+ const root = tmpDir("owned-requeue-");
48
+ seed(root, "bA", { order: [5, 7], pending: [7], running: { 5: {} }, held: [7] });
49
+ const b = seed(root, "bB", { order: [5, 7], results: { 5: { outcome: "needs-human" }, 7: { outcome: "needs-human" } } });
50
+ assert.equal(ownerOf(root, "o/r", 7, "bB"), "bA");
51
+ const res = await queued(quiet(() => orchestrateFromCli(["--requeue", "bB", "5", "7", "--reason", "r"], { batchRoot: root, io })));
52
+ assert.deepEqual(res.requeued, []);
53
+ assert.deepEqual(res.refused.map((x) => [x.issue, x.reason]), [[5, "owned by bA"], [7, "owned by bA"]]);
54
+ assert.deepEqual(b.readRequeued(), []);
55
+ });
56
+ it("dispatch defers an issue another batch runs (or holds pending with a lower id) and admits it once the owner is done", async () => {
57
+ const root = tmpDir("owned-dispatch-");
58
+ seed(root, "bA", { pending: [5] });
59
+ openBatch(root, "bA");
60
+ const check = (id) => makeDispatchCheck({ gh: async () => JSON.stringify({ state: "OPEN", labels: [] }), repo: "o/r", owner: (n) => dispatchOwner(root, "o/r", n, id) });
61
+ const r = await check("bB")(5);
62
+ assert.deepEqual([r?.outcome, r?.code, r?.detail], ["deferred", "batch.owned", "owned by bA"]);
63
+ assert.equal(await check("bA")(5), null, "the lower id keeps it: no mutual deferral");
64
+ openBatch(root, "bA").store.save({ order: [5], running: {}, pending: [], results: { 5: { outcome: "merged" } }, notBefore: {} });
65
+ assert.equal(await check("bB")(5), null);
66
+ });
67
+ it("schedd status warns when two hosted batches share a pending issue", async () => {
68
+ const statuses = { type: "status", pid: 1, batches: [{ id: "bA", running: true, pending: [5, 6] }, { id: "bB", running: true, pending: [5] }], unhosted: [] };
69
+ const lines = sharedPendingLines(statuses.batches);
70
+ assert.ok(lines.some((t) => /#5 is pending in 2 batches \(bA, bB\)/.test(t)), lines.join("\n"));
71
+ assert.ok(!lines.some((t) => /#6 is pending/.test(t)));
72
+ });
73
+ });
@@ -311,7 +311,7 @@ const toMap = (o) => new Map(Object.entries(o ?? {}).map(([k, v]) => [Number(k),
311
311
  export async function orchestrate({ issues, parallel = 3, runOne, readBody, prefilter = null, resolveLane = null, now = () => Date.now(), onUpdate = () => {}, onCrossLane = () => {},
312
312
  store = null, adopt = null, getParallel = null, getAdded = null, getRequeued = null, breaker = null, maxDeferrals = DEFAULT_MAX_DEFERRALS, sleep = cancellableSleep, pollMs = 5000,
313
313
  classify = null, maintenance = null, limits = null, identity = () => "default", batchId = null, drift = null, integration = null, sched = null, priorityOf = null, remote = null, beforeAdmit = null, preflight = null,
314
- recovery = null, decide = () => {}, conflicting = null, relabelNeedsHuman = null, onExit = null, issueLabels = null, issueState = null, getCancelled = null, getHeld = null, getBlocked = null, trusted = null, getGates = null, stopLane = null, releaseLease = null, stopRetryMs = STOP_RETRY_MS, stopTimeoutMs = STOP_TIMEOUT_MS,
314
+ recovery = null, decide = () => {}, conflicting = null, relabelNeedsHuman = null, onExit = null, issueLabels = null, issueState = null, getCancelled = null, getHeld = null, expireHolds = null, getHoldInfo = null, getBlocked = null, trusted = null, getGates = null, stopLane = null, releaseLease = null, stopRetryMs = STOP_RETRY_MS, stopTimeoutMs = STOP_TIMEOUT_MS,
315
315
  estimate = null, starveMs = DEFAULT_STARVE_MS, setupConcurrency = DEFAULT_SETUP_CONCURRENCY, signal = null, dispatchCheck = null, syncParked = null, syncEveryMs = DEFAULT_SYNC_EVERY_MS, lifecycle = null,
316
316
  getChildren = null, autoChildren = null, baseWait = null, rotator = null, transientRetries = DEFAULT_TRANSIENT_RETRIES, overload = null, version = null, onInterrupted = null }) {
317
317
  const saved = store?.load?.() ?? null;
@@ -386,6 +386,9 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
386
386
  if (!remote) return null;
387
387
  // #4542: a lane recovering from a remote capability block runs on the host, which has the capability.
388
388
  // #4785: a tool-missing recovery too: the sandbox that lacked the tool is not chosen again.
389
+ // #5423: the lane now provisions the sandbox before ending tool_missing, so the first tool-missing recovery of a remote run retries remotely (not parked behind host load); a repeat goes to the host
390
+ const rec = recovering.get(n);
391
+ if (rec?.code === OUTCOME_CODES.ENV_TOOL_MISSING && rec.where === "remote" && (rec.attempt ?? 1) <= 1 && !budgetLocal) return { where: "remote", reason: "retry remotely after sandbox provisioning" };
389
392
  if ([OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.ENV_TOOL_MISSING].includes(recovering.get(n)?.code)) return { where: "local", reason: `host capability: recovering ${recovering.get(n).code}` };
390
393
  // #5371: a mechanical recovery never repeats the placement of the run that failed (a remote sandbox env defect recurs there), and a remote validate failure is rerun on the host
391
394
  if (recovering.get(n)?.code === ENV_VALIDATE_PLACEMENT || (MECHANICAL_CODES.includes(recovering.get(n)?.code) && recovering.get(n)?.where === "remote")) return { where: "local", reason: `different placement: recovering ${recovering.get(n).code} off the remote run` };
@@ -734,7 +737,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
734
737
  };
735
738
 
736
739
  // Apply one lane's result: requeue it (deferred, dependency-open, engine-error) or record its final row.
737
- const settle = async (n, r, rec, pf) => {
740
+ const settleLane = async (n, r, rec, pf) => {
738
741
  if (halted) return; // #4454: a resume adopts the lane and settles it
739
742
  if (cancelled && releaseLease) { try { await releaseLease(n, rec); } catch { /* best effort: the lease expires */ } } // #5241: the lane ended: its lease goes with it
740
743
  // #4304: the pre-filter runs once per issue; a recovery pass's row adds the earlier attempt's cost, which already holds it.
@@ -949,7 +952,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
949
952
  }
950
953
  // #4656: a mechanical terminal park (recovery spent or none applies) moves to the remediation queue, not the human queue.
951
954
  if (row.outcome === "needs-human" && !row.parkedQueued && !everRelabelled.has(n) && typeof relabelNeedsHuman === "function" && (cls => cls === "parked" || (cls === "recoverable" && prior))(classifyNeedsHuman({ ...row, issueEdited: r?.issueEdited === true }, { parked: true }))) { // a recoverable row with a finished recovery has used its attempts
952
- try { const res = await relabelNeedsHuman({ issue: n, parked: { code: row.code, pr: Number.isInteger(row.pr) ? row.pr : null }, evidence: `Mechanical park \`${row.code}\`${Number.isInteger(row.pr) ? ` (PR #${row.pr})` : ""}:\n${String(row.detail ?? "")}` }); if (res !== false && res !== "failed" && res !== "skipped") row.parkedQueued = true; } catch { /* best effort */ }
955
+ try { const res = await relabelNeedsHuman({ issue: n, parked: { code: row.code, pr: Number.isInteger(row.pr) ? row.pr : null }, evidence: `Mechanical park \`${row.code}\`${Number.isInteger(row.pr) ? ` (PR #${row.pr})` : ""}:\n${String(row.detail ?? "")}` }); if (res !== false && res !== "failed" && res !== "skipped") row.parkedQueued = true; else if (res === false || res === "failed") { const ev = { event: "relabel.failed", issue: n, batch: batchId ?? null, detail: `parked relabel failed (${row.code}): needs-human kept` }; try { store?.log?.(ev); } catch { /* best effort */ } onUpdate(ev); } } catch { /* best effort */ }
953
956
  }
954
957
  results.set(n, row);
955
958
  if (row.outcome === "merged" && lifecycle && r?.milestone) lifecycleTitles.add(String(r.milestone)); // #4657
@@ -967,6 +970,14 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
967
970
  done(); save(); update(row);
968
971
  };
969
972
 
973
+ // #5437: a lane's post-run bookkeeping (r.postRun) starts once its slot is free; the batch waits for it before it ends.
974
+ const postRuns = new Set();
975
+ const settle = async (n, r, rec, pf) => {
976
+ await settleLane(n, r, rec, pf);
977
+ if (typeof r?.postRun !== "function") return;
978
+ const p = Promise.resolve().then(() => r.postRun()).catch(() => {}).finally(() => postRuns.delete(p));
979
+ postRuns.add(p);
980
+ };
970
981
  const track = (n, p) => { running.set(n, p.catch((e) => settle(n, { terminalReason: "engine-error", detail: e?.message ?? String(e) }, runRecs.get(n), null))); };
971
982
  const laneRetries = new Map(); // #4791: transient lane-resolution failures per issue; never counted in `deferrals`
972
983
  // A transient refusal (gh/git failed) re-resolves; the settled `deferred` frees the slot and requeues with backoff.
@@ -1081,7 +1092,9 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1081
1092
  }
1082
1093
  save();
1083
1094
 
1084
- const heldDetail = (n) => cancelled ? "cancelled by operator" : opHeld.has(n) ? "held by operator" : baseHeld.has(n) ? baseHeld.get(n) : tripped?.detail ?? (integHeld.has(n) ? `integration: ${integHeld.get(n)}` : (driftHeld.has(n) ? `drift: ${driftHeld.get(n)} flagged` : budgetStop ? `execution budget: ${budgetStop}` : budgetHeld ? "maintenance share" : "not run"));
1095
+ // #5469: a final held row names the owner and since when the hold recorded them (`forgedock orchestrate --hold ... --for`)
1096
+ const heldByOperator = (n) => { let e = null; try { e = getHoldInfo?.()?.[n] ?? null; } catch { e = null; } return e ? `held by operator (${e.owner}, since ${e.since})` : "held by operator"; };
1097
+ const heldDetail = (n) => cancelled ? "cancelled by operator" : opHeld.has(n) ? heldByOperator(n) : baseHeld.has(n) ? baseHeld.get(n) : tripped?.detail ?? (integHeld.has(n) ? `integration: ${integHeld.get(n)}` : (driftHeld.has(n) ? `drift: ${driftHeld.get(n)} flagged` : budgetStop ? `execution budget: ${budgetStop}` : budgetHeld ? "maintenance share" : "not run"));
1085
1098
  // #4315: a recovery queued but never launched (the batch stopped: breaker, budget, hold; or a resume that did not relaunch a
1086
1099
  // lost run) left the issue without needs-human, since a non-final attempt does not relabel. Relabel it once, with the full reason.
1087
1100
  // #4318: also on a throw out of the loop and on a signal (`onExit`); `cause` overrides the held reason. Runs once per process.
@@ -1234,8 +1247,17 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1234
1247
  try { Promise.resolve(stopLane(n, rec)).then((ok) => { if (ok !== false) s.accepted = true; }, () => {}); } catch { /* best effort */ }
1235
1248
  }
1236
1249
  // #4592: re-read the hold set; one decision and one row when it changes.
1250
+ const holdExpiring = (list) => { let info = null; try { info = getHoldInfo?.() ?? null; } catch { info = null; } return !!expireHolds && list.some((n) => Number.isFinite(Date.parse(info?.[n]?.expiresAt))); }; // #5469
1237
1251
  const refreshHeld = () => {
1238
1252
  if (!getHeld) return;
1253
+ if (expireHolds) { // #5469: a hold past its expiry is released here; the diff below then admits it. A dead owner session is an alert.
1254
+ let due = []; try { due = expireHolds() ?? []; } catch { due = []; }
1255
+ for (const e of due) {
1256
+ decided({ issue: null, what: `hold on #${e.issue} expired (held by ${e.owner} since ${e.since}${e.reason ? `: ${e.reason}` : ""}); re-admitted`, why: "hold expiry (--hold --for)", alternative: "hold it again" });
1257
+ update({ issue: null, outcome: "hold-expired", detail: `#${e.issue} (${e.owner}, since ${e.since})` });
1258
+ if (e.ownerGone) update({ issue: null, outcome: "hold-alert", detail: `#${e.issue}: the hold owner session (${e.owner}) is gone; the hold expired and the issue was re-admitted` });
1259
+ }
1260
+ }
1239
1261
  let got = [];
1240
1262
  try { got = getHeld() ?? []; } catch { got = opHeld.size ? [...opHeld] : []; }
1241
1263
  const next = new Set((Array.isArray(got) ? got : []).filter((n) => Number.isSafeInteger(n) && n > 0));
@@ -1568,6 +1590,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1568
1590
  else if (pending.length && baseHit.size) await nap(wake ?? pollMs); // #5031: only issues waiting for a base commit: poll for it
1569
1591
  else if (pending.length && waits.length) await nap(Math.min(wake, getCancelled ? pollMs : Infinity)); // wake is poll-capped by a hold or a live K; #4454: nap wakes on a stop
1570
1592
  else if (pending.length && budgetHeld) { if (await drainAdds()) continue; break; } // maintenance the budget does not admit now: held for a later batch
1593
+ else if (pending.length && opHeldHit.size && !pending.some((n) => !opHeldHit.has(n) && isReady(n)) && holdExpiring([...opHeldHit]) && !cancelled) await nap(wake ?? pollMs); // #5469: a hold with an expiry keeps the batch open until it expires (re-admit or alert), not finalised silently
1571
1594
  else if (pending.length && opHeldHit.size && !pending.some((n) => !opHeldHit.has(n) && isReady(n))) { if (await drainAdds()) continue; break; } // #4592: held by the operator: pending for a --resume
1572
1595
  else if (pending.length && (driftHeld.size || integHeld.size)) { if (await drainAdds()) continue; break; } // held by a drift flag (block_dispatch) or a red integration streak (#4667): pending for a later batch
1573
1596
  else if (pending.some((n) => remoteCapped.has(n))) await nap(wake ?? pollMs); // #5138: live max_remote 0: wait for a raise or another placement
@@ -1593,6 +1616,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1593
1616
  if (!halted) try { await relabelQueued(`batch failed: ${firstLine(e?.message ?? e)}`); } catch { /* best effort */ }
1594
1617
  throw e;
1595
1618
  }
1619
+ await Promise.allSettled([...postRuns]); // #5437
1596
1620
  if (reg) withdrawExcept(new Set());
1597
1621
  await relabelQueued();
1598
1622
  // #4657: a milestone whose `close_on` state is reached closes here; a failure is a row, never an outcome change.
@@ -0,0 +1,20 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Speculative start (#5436): the review session reads the same committed diff as the guard and precheck run, so it starts
5
+ * beside them. `fn` must have no effect on lane state (only the model call); the caller applies the reply when it adopts
6
+ * the job, and `discard()` drops it when precheck fails, so a red precheck costs nothing but the unused call.
7
+ */
8
+ export function startSpeculative(fn) {
9
+ const p = Promise.resolve().then(fn);
10
+ let state = "running";
11
+ p.then(() => { if (state === "running") state = "settled"; }, () => { if (state === "running") state = "failed"; });
12
+ p.catch(() => {}); // a discarded job's rejection is never unhandled
13
+ return {
14
+ /** The job's promise; rejects as `fn` did. */
15
+ adopt() { state = "adopted"; return p; },
16
+ /** Drop the job; its result is never read. Returns true when it had not finished. */
17
+ discard() { const was = state === "running"; if (state !== "adopted") state = "discarded"; return was; },
18
+ state: () => state,
19
+ };
20
+ }
@@ -0,0 +1,49 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import test from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import { startSpeculative } from "./overlap.mjs";
6
+
7
+ const deferred = () => { let resolve, reject; const promise = new Promise((a, b) => { resolve = a; reject = b; }); return { promise, resolve, reject }; };
8
+
9
+ // The gate's shape: guard+precheck and the review run together; the review is adopted only when precheck passes.
10
+ async function gate({ precheck, review, order }) {
11
+ const spec = startSpeculative(() => review.promise);
12
+ const applied = [];
13
+ try {
14
+ const finish = order === "review-first" ? [review.resolve, precheck.resolve] : [precheck.resolve, review.resolve];
15
+ const failed = await Promise.all([precheck.promise, Promise.resolve().then(() => finish.forEach((f) => f("x")))]).then(([p]) => p);
16
+ if (failed) return { state: "nonconforming", applied };
17
+ applied.push(await spec.adopt());
18
+ return { state: "conforms", applied };
19
+ } finally { spec.discard(); }
20
+ }
21
+
22
+ for (const order of ["review-first", "precheck-first"]) {
23
+ test(`a green precheck adopts the review whichever finishes first (${order})`, async () => {
24
+ const p = deferred(), r = deferred();
25
+ p.promise.then(() => {});
26
+ const out = await gate({ precheck: { promise: p.promise.then(() => false), resolve: p.resolve }, review: r, order });
27
+ assert.deepEqual(out, { state: "conforms", applied: ["x"] });
28
+ });
29
+ test(`a red precheck discards the review and applies nothing (${order})`, async () => {
30
+ const p = deferred(), r = deferred();
31
+ const out = await gate({ precheck: { promise: p.promise.then(() => true), resolve: p.resolve }, review: r, order });
32
+ assert.deepEqual(out, { state: "nonconforming", applied: [] });
33
+ });
34
+ }
35
+
36
+ test("a discarded job that rejects is never an unhandled rejection, and an adopted one rejects as the job did", async () => {
37
+ const a = startSpeculative(async () => { throw new Error("boom"); });
38
+ assert.equal(a.discard() === true || a.discard() === false, true);
39
+ const b = startSpeculative(async () => { throw new Error("boom"); });
40
+ await assert.rejects(b.adopt(), /boom/);
41
+ await new Promise((r) => setImmediate(r));
42
+ });
43
+
44
+ test("discard reports whether the job was still running", async () => {
45
+ const d = deferred();
46
+ const s = startSpeculative(() => d.promise);
47
+ assert.equal(s.discard(), true);
48
+ assert.equal(s.state(), "discarded");
49
+ });