forgedock 1.61.2 → 1.62.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 (131) hide show
  1. package/bin/config-schema.mjs +10 -1
  2. package/bin/engine/outcome-codes.mjs +4 -0
  3. package/bin/engine-cli.mjs +159 -17
  4. package/bin/env/env.mjs +6 -4
  5. package/bin/forge-home-check.mjs +91 -0
  6. package/bin/forgedock.mjs +50 -7
  7. package/bin/gc.mjs +2 -0
  8. package/bin/hooks/pre-tool-use.mjs +4 -0
  9. package/bin/journey.mjs +55 -5
  10. package/bin/lean/admission.mjs +16 -5
  11. package/bin/lean/batch-health.mjs +55 -16
  12. package/bin/lean/batch-health.test.mjs +67 -1
  13. package/bin/lean/batch.mjs +8 -0
  14. package/bin/lean/batch.test.mjs +5 -0
  15. package/bin/lean/ceiling.mjs +20 -0
  16. package/bin/lean/ceiling.test.mjs +33 -2
  17. package/bin/lean/ci-gate.mjs +240 -0
  18. package/bin/lean/ci-gate.test.mjs +227 -0
  19. package/bin/lean/ci-precheck.mjs +178 -0
  20. package/bin/lean/ci-precheck.test.mjs +149 -0
  21. package/bin/lean/conformance.mjs +85 -9
  22. package/bin/lean/conformance.test.mjs +155 -3
  23. package/bin/lean/context.test.mjs +7 -6
  24. package/bin/lean/dag.mjs +128 -0
  25. package/bin/lean/dag.test.mjs +131 -0
  26. package/bin/lean/decisions.mjs +5 -4
  27. package/bin/lean/decisions.test.mjs +11 -0
  28. package/bin/lean/delguard.mjs +84 -0
  29. package/bin/lean/delguard.test.mjs +104 -0
  30. package/bin/lean/depcache.mjs +125 -17
  31. package/bin/lean/depcache.test.mjs +111 -0
  32. package/bin/lean/design-gate.mjs +5 -5
  33. package/bin/lean/design-gate.test.mjs +14 -0
  34. package/bin/lean/effects.mjs +72 -4
  35. package/bin/lean/execution.mjs +41 -7
  36. package/bin/lean/execution.test.mjs +99 -3
  37. package/bin/lean/forgedock-lane-workflow.test.mjs +35 -0
  38. package/bin/lean/guardgate.mjs +30 -7
  39. package/bin/lean/guardgate.test.mjs +44 -1
  40. package/bin/lean/guards.test.mjs +1 -1
  41. package/bin/lean/heavy.test.mjs +87 -0
  42. package/bin/lean/hotarea.mjs +73 -0
  43. package/bin/lean/hotarea.test.mjs +73 -0
  44. package/bin/lean/issuewatch-reconcile.mjs +20 -1
  45. package/bin/lean/issuewatch-reconcile.test.mjs +30 -0
  46. package/bin/lean/lanecheck.mjs +27 -3
  47. package/bin/lean/lanecheck.test.mjs +47 -5
  48. package/bin/lean/laneconfine.mjs +83 -0
  49. package/bin/lean/laneconfine.test.mjs +113 -0
  50. package/bin/lean/lean.mjs +376 -79
  51. package/bin/lean/lean.test.mjs +710 -22
  52. package/bin/lean/live-reconcile.mjs +169 -0
  53. package/bin/lean/live-reconcile.test.mjs +176 -0
  54. package/bin/lean/orchestrate-envhold.test.mjs +245 -0
  55. package/bin/lean/orchestrate-hostfallback.test.mjs +39 -0
  56. package/bin/lean/orchestrate.mjs +207 -17
  57. package/bin/lean/outcomeevidence.mjs +104 -0
  58. package/bin/lean/outcomeevidence.test.mjs +78 -0
  59. package/bin/lean/page-capture.mjs +68 -0
  60. package/bin/lean/page-capture.test.mjs +44 -0
  61. package/bin/lean/pagegate.mjs +46 -7
  62. package/bin/lean/pagegate.test.mjs +66 -1
  63. package/bin/lean/postdeploy-check.mjs +18 -4
  64. package/bin/lean/postdeploy-check.test.mjs +32 -1
  65. package/bin/lean/prefilter.mjs +36 -4
  66. package/bin/lean/prefilter.test.mjs +31 -1
  67. package/bin/lean/preflight.mjs +22 -0
  68. package/bin/lean/preflight.test.mjs +19 -1
  69. package/bin/lean/probe.mjs +18 -0
  70. package/bin/lean/probe.test.mjs +40 -0
  71. package/bin/lean/prompts.mjs +40 -3
  72. package/bin/lean/recovery.test.mjs +20 -0
  73. package/bin/lean/recurrence.mjs +133 -0
  74. package/bin/lean/recurrence.test.mjs +99 -0
  75. package/bin/lean/release-config.mjs +2 -1
  76. package/bin/lean/release-config.test.mjs +18 -0
  77. package/bin/lean/release-control.mjs +4 -2
  78. package/bin/lean/release-control.test.mjs +15 -0
  79. package/bin/lean/release-merge-hold.mjs +65 -0
  80. package/bin/lean/release-merge-hold.test.mjs +69 -0
  81. package/bin/lean/release-review.mjs +26 -9
  82. package/bin/lean/release-review.test.mjs +53 -0
  83. package/bin/lean/release-status.mjs +3 -1
  84. package/bin/lean/release-status.test.mjs +11 -0
  85. package/bin/lean/release.test.mjs +26 -1
  86. package/bin/lean/render.mjs +8 -7
  87. package/bin/lean/routing.mjs +49 -0
  88. package/bin/lean/routing.test.mjs +54 -1
  89. package/bin/lean/run-issue-placement.test.mjs +30 -1
  90. package/bin/lean/sandbox-actions.mjs +121 -0
  91. package/bin/lean/sandbox-actions.test.mjs +94 -0
  92. package/bin/lean/sandbox-provider.contract.test.mjs +22 -1
  93. package/bin/lean/sandbox-remote.mjs +3 -1
  94. package/bin/lean/schedd-health.mjs +14 -2
  95. package/bin/lean/schedd-health.test.mjs +13 -0
  96. package/bin/lean/schedd.mjs +43 -17
  97. package/bin/lean/schedd.test.mjs +61 -1
  98. package/bin/lean/toolchain.mjs +16 -6
  99. package/bin/lean/toolplace.mjs +12 -0
  100. package/bin/lean/weakguard.mjs +105 -0
  101. package/bin/lean/weakguard.test.mjs +59 -0
  102. package/bin/lean/winspawn.mjs +61 -0
  103. package/bin/lean/winspawn.test.mjs +45 -0
  104. package/bin/lean/worktree.mjs +3 -1
  105. package/bin/lean/worktree.test.mjs +11 -0
  106. package/bin/pool/agent.mjs +210 -14
  107. package/bin/pool/cache-sweep.mjs +74 -0
  108. package/bin/pool/cli.mjs +11 -3
  109. package/bin/pool/docker.mjs +33 -2
  110. package/bin/pool/health.mjs +38 -0
  111. package/bin/pool/lane-tools.mjs +23 -4
  112. package/bin/pool/lane-tools.test.mjs +12 -1
  113. package/bin/pool/router.mjs +21 -3
  114. package/bin/runner.mjs +37 -0
  115. package/bin/splash-scene.mjs +356 -0
  116. package/bin/win-hide-children.mjs +114 -0
  117. package/commands/orchestrate.md +18 -27
  118. package/commands/review-pr-agents/infra.md +1 -0
  119. package/commands/review-pr-staging.md +2 -2
  120. package/docs/CONFIG.md +60 -3
  121. package/docs/OUTCOME-CODES.md +3 -0
  122. package/package.json +1 -1
  123. package/plugins/forgedock-splash/.claude-plugin/plugin.json +1 -1
  124. package/plugins/forgedock-splash/README.md +1 -1
  125. package/plugins/forgedock-splash/hooks/scene.ts +142 -8
  126. package/pool/README.md +6 -0
  127. package/pool/image/entrypoint.sh +1 -0
  128. package/scripts/check-spec-size.sh +3 -1
  129. package/scripts/gen-splash-scene.mjs +24 -0
  130. package/scripts/review-staging-pre.sh +8 -3
  131. package/scripts/review-staging-pre.test.sh +2 -0
@@ -0,0 +1,169 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #5704: the post-deploy reconcile for unmanaged repos (`release.managed` off). "Merged" is not "live": an issue whose lane merged
5
+ * is reconciled against the **live SHA** read from the deploy record (`deploy.live_release_command` in `.forge/release.yaml` on the
6
+ * default branch, else forge.yaml `deploy.engine.live_release_command`), never against the default branch. An unknown live SHA
7
+ * is a no-op (fail closed). Per open `workflow:merged` / `workflow:merged-unverified` issue:
8
+ * - fix commit unresolvable (or not in the clone) -> skipped and reported;
9
+ * - fix not an ancestor of the live SHA -> `awaiting-promotion` ensured, left open;
10
+ * - an ancestor -> `awaiting-promotion` dropped and the issue's `[check:<id>]` entries from `.forge/post-deploy-checks.json` on
11
+ * origin/<default> run (the probe runner, `expect` included); a windowed entry (`for`) leaves it open under the monitoring label;
12
+ * - any fail -> `post-deploy-failed` plus a comment with the output; never closed;
13
+ * - all pass, or no checks and no FORGE:TRACKED hand-off (the orphan path) -> `FORGE:VERIFIED <live sha>`, close, tick the rollup.
14
+ * Helper-level reuse of the #5562 engine (verifiedMarker, hasVerified, readTarget) and of the #4626 check runner, so managed and
15
+ * unmanaged modes share one marker and one check implementation; `closeIssues`/`verifyStep` are not called (they need the managed
16
+ * release ctx and fence). Idempotent: a FORGE:VERIFIED for the live SHA is never re-posted, a `post-deploy-failed` issue is not re-run.
17
+ * Run by `forgedock close reconcile [--dry-run]` and by `probe --due` (the schedd timer). No model call.
18
+ */
19
+ import { readFileSync } from "node:fs";
20
+ import { join } from "node:path";
21
+ import { readTarget } from "./release-deploy.mjs";
22
+ import { verifiedMarker, hasVerified } from "./release-verify.mjs";
23
+ import { parsePolicy, POLICY_PATH } from "./release-config.mjs";
24
+ import { readEngine } from "./deploy-stages.mjs";
25
+ import { checksAt, runNamedChecks, tickItems, addMonitoringLabel, CHECKS_FILE } from "./postdeploy-check.mjs";
26
+ import { fixSha, readProbeConfig, resolveDefaultBranch, spawnProbe, clearAwaitingPromotion, markPostDeployFailed, POST_DEPLOY_FAILED_LABEL, OUTPUT_TAIL } from "./probe.mjs";
27
+ import { REMEDIATION_TRACKED_MARKER } from "./issuewatch-reconcile.mjs";
28
+ import { AWAITING_PROMOTION_LABEL } from "./prefilter.mjs";
29
+
30
+ export const MERGED_LABELS = ["workflow:merged", "workflow:merged-unverified"];
31
+ const CHECK_RE = /\[check:\s*([a-z0-9][a-z0-9._-]{0,63})\s*\]/g;
32
+ const short = (s) => String(s ?? "").slice(0, 12);
33
+ const labelsOf = (iss) => (iss?.labels ?? []).map((l) => String(l?.name ?? l));
34
+ const fenced = (s) => { const f = "`".repeat(Math.max(3, ...[...String(s).matchAll(/`+/g)].map((m) => m[0].length + 1))); return `${f}\n${String(s).trim() || "(no output)"}\n${f}`; };
35
+
36
+ /** A FORGE:TRACKED hand-off that defers the issue (the remediation merge's own note is not one: it waits for this reconcile). */
37
+ export const hasHandOff = (comments) => (comments ?? []).some((c) => { const b = String(c?.body ?? ""); return /FORGE:TRACKED/.test(b) && !b.includes(REMEDIATION_TRACKED_MARKER); });
38
+
39
+ /** The `[check:<id>]` ids an issue body names, in order, distinct. */
40
+ export const checkIdsOf = (body) => [...new Set([...String(body ?? "").matchAll(CHECK_RE)].map((m) => m[1]))];
41
+
42
+ /** `deploy.live_release_command`: `.forge/release.yaml` on origin/<default>, else forge.yaml `deploy.engine` (default branch's copy wins). */
43
+ export async function liveReleaseCommand({ io, cwd, defaultBranch }) {
44
+ let text = null;
45
+ try { text = String(await io.git(["show", `origin/${defaultBranch}:${POLICY_PATH}`], { cwd })); } catch { text = null; }
46
+ if (text != null) {
47
+ const cmd = parsePolicy(text).policy?.deploy?.live_release_command;
48
+ if (typeof cmd === "string" && cmd.trim()) return cmd.trim();
49
+ }
50
+ let raw = null;
51
+ try { raw = String(await io.git(["show", `origin/${defaultBranch}:forge.yaml`], { cwd })); } catch { try { raw = readFileSync(join(cwd, "forge.yaml"), "utf8"); } catch { raw = null; } }
52
+ const cmd = readEngine({ raw, io: null, def: null })?.live_release_command;
53
+ return typeof cmd === "string" && cmd.trim() ? cmd.trim() : null;
54
+ }
55
+
56
+ /** `io.rehearse` when the io has one (release io), else the probe runner with the caller's env. */
57
+ const rehearseOf = (io, cwd, env, spawn) => io.rehearse ? io.rehearse.bind(io) : async (cmd, { timeout = 120_000 } = {}) => {
58
+ const r = await (spawn ?? spawnProbe)({ run: cmd, cwd, env, timeoutMs: timeout });
59
+ return { ok: !r.timedOut && r.code === 0, code: r.code, output: String(r.stdout ?? "") };
60
+ };
61
+
62
+ async function readIssue(n, repo, io) {
63
+ const iss = JSON.parse(String(await io.gh(["api", `repos/${repo}/issues/${n}`])));
64
+ const raw = String(await io.gh(["api", `repos/${repo}/issues/${n}/comments`, "--paginate", "--jq", ".[]"]));
65
+ return { ...iss, number: n, comments: raw.split("\n").filter((l) => l.trim()).map((l) => JSON.parse(l)) };
66
+ }
67
+
68
+ async function openMerged(repo, io, limit) {
69
+ const seen = new Set();
70
+ for (const label of MERGED_LABELS) {
71
+ try {
72
+ for (const i of JSON.parse(String(await io.gh(["issue", "list", "-R", repo, "--state", "open", "--label", label, "--json", "number", "--limit", String(limit)])) || "[]")) seen.add(Number(i.number));
73
+ } catch { /* a repo without the label lists nothing */ }
74
+ }
75
+ return [...seen].filter(Number.isInteger).sort((a, b) => a - b);
76
+ }
77
+
78
+ const hasCommit = async (io, sha, cwd) => { try { await io.git(["rev-parse", "--verify", "--quiet", `${sha}^{commit}`], { cwd }); return true; } catch { return false; } };
79
+ const isAncestor = async (io, sha, live, cwd) => { try { await io.git(["merge-base", "--is-ancestor", sha, live], { cwd }); return true; } catch { return false; } };
80
+
81
+ async function ensureAwaiting({ io, repo, issue }) {
82
+ const add = () => io.gh(["issue", "edit", String(issue), "-R", repo, "--add-label", AWAITING_PROMOTION_LABEL]);
83
+ try { await add(); } catch {
84
+ try { await io.gh(["label", "create", AWAITING_PROMOTION_LABEL, "-R", repo, "--force", "--color", "FBCA04", "--description", "Merged, not yet in the live release. Managed by ForgeDock."]); await add(); } catch { /* the reconcile row still says it */ }
85
+ }
86
+ }
87
+
88
+ /** Tick the passed checks' items in the issue body and in the open post-deploy rollup issues; best effort. */
89
+ async function tickRollup({ io, repo, iss, ids }) {
90
+ if (!ids.length) return;
91
+ const set = new Set(ids);
92
+ const edit = async (n, body) => { const next = tickItems(body, set); if (next !== String(body ?? "")) await io.gh(["issue", "edit", String(n), "-R", repo, "--body", next]); };
93
+ try { await edit(iss.number, iss.body); } catch { /* the FORGE:VERIFIED comment is the record */ }
94
+ try {
95
+ const rolls = JSON.parse(String(await io.gh(["issue", "list", "-R", repo, "--state", "open", "--search", "FORGE:POSTDEPLOY_ROLLUP in:body", "--json", "number,body", "--limit", "20"])) || "[]");
96
+ for (const r of rolls) { try { await edit(r.number, r.body); } catch { /* next pass */ } }
97
+ } catch { /* no rollup */ }
98
+ }
99
+
100
+ /**
101
+ * Reconcile the open merged issues against the live SHA. @returns {Promise<{live: ?string, reason?: string, rows: Array<{issue, outcome, detail}>}>}
102
+ * Outcomes: unresolved | awaiting-promotion | monitoring | failed | failed-earlier | missing-check | tracked | verified | error.
103
+ */
104
+ export async function reconcileLive({ repo, io, cwd = process.cwd(), dryRun = false, config = readProbeConfig(cwd), env = process.env, spawn, defaultBranch, limit = 200 }) {
105
+ const def = defaultBranch ?? await resolveDefaultBranch({ repo, io, cwd });
106
+ if (!def) return { live: null, reason: "default branch unknown", rows: [] };
107
+ const cmd = await liveReleaseCommand({ io, cwd, defaultBranch: def });
108
+ if (!cmd) return { live: null, reason: "deploy.live_release_command is not set: live SHA unknown, nothing reconciled", rows: [] };
109
+ const target = await readTarget({ rehearse: rehearseOf(io, cwd, env, spawn) }, cmd);
110
+ if (!target?.sha) return { live: null, reason: "the live-release command returned no SHA: nothing reconciled", rows: [] };
111
+ const live = target.sha;
112
+ if (!(await hasCommit(io, live, cwd))) return { live, reason: `live SHA ${short(live)} is not in this clone (fetch first): nothing reconciled`, rows: [] };
113
+ const checks = await checksAt((a, o) => io.git(a, o), [`origin/${def}`], cwd);
114
+ const rows = [];
115
+ for (const n of await openMerged(repo, io, limit)) {
116
+ try { rows.push(await reconcileIssue({ n, repo, io, cwd, dryRun, config, env, spawn, live, checks, def })); }
117
+ catch (e) { rows.push({ issue: n, outcome: "error", detail: String(e?.message ?? e).split("\n")[0].slice(0, 200) }); }
118
+ }
119
+ return { live, rows };
120
+ }
121
+
122
+ async function reconcileIssue({ n, repo, io, cwd, dryRun, config, env, spawn, live, checks, def }) {
123
+ const row = (outcome, detail = "") => ({ issue: n, outcome, detail });
124
+ const iss = await readIssue(n, repo, io);
125
+ const labels = labelsOf(iss);
126
+ const fix = await fixSha(iss, io, repo);
127
+ if (!fix || !(await hasCommit(io, fix, cwd))) return row("unresolved", fix ? `fix ${short(fix)} is not in this clone` : "no fix commit found (FORGE:TRAJECTORY or a merged closing PR)");
128
+ if (!(await isAncestor(io, fix, live, cwd))) {
129
+ if (!dryRun && !labels.includes(AWAITING_PROMOTION_LABEL)) await ensureAwaiting({ io, repo, issue: n });
130
+ return row("awaiting-promotion", `fix ${short(fix)} is not in live ${short(live)}`);
131
+ }
132
+ if (labels.includes(POST_DEPLOY_FAILED_LABEL)) return row("failed-earlier", `labelled ${POST_DEPLOY_FAILED_LABEL}: cleared by a person or a new fix`);
133
+ if (!dryRun && labels.includes(AWAITING_PROMOTION_LABEL)) await clearAwaitingPromotion({ io, repo, issue: n });
134
+ const verified = hasVerified(iss.comments, live);
135
+ const ids = verified ? [] : checkIdsOf(iss.body);
136
+ const missing = ids.filter((id) => !checks[id]);
137
+ if (missing.length) return row("missing-check", `names ${missing.map((m) => `[check:${m}]`).join(", ")} but ${CHECKS_FILE} on ${def} has no such entry`);
138
+ const windowed = ids.filter((id) => checks[id].forMs), now = ids.filter((id) => !checks[id].forMs);
139
+ const results = now.length ? await runNamedChecks({ ids: now, checks, cwd, config, env, spawn }) : [];
140
+ const failed = results.filter((r) => r.result !== "pass");
141
+ if (failed.length) {
142
+ if (dryRun) return row("failed", `${failed.map((f) => f.id).join(", ")} failed (dry run: not recorded)`);
143
+ await markPostDeployFailed({ io, repo, issue: n });
144
+ const body = [`## Post-deploy verification failed at live ${short(live)}`, `The fix \`${short(fix)}\` is live, but ${failed.map((f) => `\`${f.id}\``).join(", ")} failed. Not closed; labelled \`${POST_DEPLOY_FAILED_LABEL}\`.`, "",
145
+ ...failed.flatMap((f) => [`**${f.id}** (exit ${f.exit ?? "timeout"})`, fenced(String(f.output ?? "").slice(-OUTPUT_TAIL)), ""])].join("\n");
146
+ try { await io.gh(["issue", "comment", String(n), "-R", repo, "--body", body]); } catch { /* the label still shows it */ }
147
+ return row("failed", `${failed.map((f) => f.id).join(", ")} failed at live ${short(live)}`);
148
+ }
149
+ if (windowed.length) {
150
+ if (!dryRun) await addMonitoringLabel({ io, repo, issue: n });
151
+ return row("monitoring", `windowed ${windowed.join(", ")}: left open under monitoring`);
152
+ }
153
+ if (!verified && !ids.length && hasHandOff(iss.comments)) return row("tracked", "no checks and a FORGE:TRACKED hand-off: left open");
154
+ if (dryRun) return row("verified", `live ${short(live)}${ids.length ? `, ${ids.length} check(s) passed` : ", no checks"} (dry run: not closed)`);
155
+ const note = ids.length ? `${ids.map((i) => `\`${i}\``).join(", ")} passed against the live release.` : "No post-deploy checks and no hand-off: closed once the fix is live.";
156
+ if (!verified) await io.gh(["issue", "comment", String(n), "-R", repo, "--body", `${verifiedMarker(live)}\n## Live and verified\nThe fix \`${short(fix)}\` is in the live release \`${short(live)}\`. ${note}`]);
157
+ await tickRollup({ io, repo, iss, ids });
158
+ await io.gh(["issue", "close", String(n), "-R", repo, "--reason", "completed"]);
159
+ return row("verified", `closed at live ${short(live)}${verified ? " (already verified)" : ""}`);
160
+ }
161
+
162
+ const GROUPS = [["verified", "verified and closed"], ["failed", "failed (post-deploy-failed)"], ["awaiting-promotion", "awaiting promotion"], ["monitoring", "monitoring"], ["tracked", "tracked hand-off"], ["missing-check", "missing check"], ["failed-earlier", "failed earlier"], ["unresolved", "unresolved fix"], ["error", "error"]];
163
+
164
+ /** One line: `live <sha>: verified 2, awaiting promotion 1`, the no-op reason, or "" when nothing was open. */
165
+ export function formatReconcileSummary({ live, reason, rows = [] } = {}) {
166
+ if (!live || reason) return `live reconcile: ${reason ?? "live SHA unknown, nothing reconciled"}`;
167
+ const parts = GROUPS.map(([k, label]) => [label, rows.filter((r) => r.outcome === k).length]).filter(([, c]) => c).map(([l, c]) => `${l} ${c}`);
168
+ return parts.length ? `live reconcile at ${short(live)}: ${parts.join(", ")}` : "";
169
+ }
@@ -0,0 +1,176 @@
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 { reconcileLive, formatReconcileSummary, liveReleaseCommand, checkIdsOf, hasHandOff } from "./live-reconcile.mjs";
6
+ import { REMEDIATION_TRACKED_MARKER } from "./issuewatch-reconcile.mjs";
7
+
8
+ const BOT = { author_association: "NONE", user: { login: "forgedock[bot]", type: "Bot" } };
9
+ const LIVE = "1111111111111111111111111111111111111111";
10
+ const FIX = "abcdef1234567890abcdef1234567890abcdef12";
11
+ const traj = { ...BOT, body: `<!-- FORGE:TRAJECTORY -->\n| Merge | merge commit | merged at ${FIX} |` };
12
+ const RELEASE_YAML = "version: 1\ndeploy:\n live_release_command: ./live.sh\n";
13
+ const config = { env: [], timeoutS: 30, sweepDays: 30, enabled: true };
14
+
15
+ /**
16
+ * A fake gh/git world. `ancestor` says whether the fix is in the live SHA; `liveOut` is the live-release command output (null: it fails);
17
+ * `checks` the checks file on origin/main; `runs` maps a check command to its exit code.
18
+ */
19
+ function world({ body = "Fix.", comments = [traj], labels = ["workflow:merged"], ancestor = true, liveOut = LIVE, checks = null, runs = {}, releaseYaml = RELEASE_YAML } = {}) {
20
+ const w = { calls: [], comments: [], closed: [], edits: [], ran: [], state: "open", labels: [...labels], issueComments: [...comments] };
21
+ w.io = {
22
+ async rehearse(cmd) { w.ran.push(cmd); return liveOut == null ? { ok: false, output: "" } : { ok: true, output: `${liveOut}\n` }; },
23
+ async gh(a) {
24
+ w.calls.push(a);
25
+ if (a[0] === "api" && /\/comments$/.test(a[1])) return w.issueComments.map((c) => JSON.stringify(c)).join("\n");
26
+ if (a[0] === "api") return JSON.stringify({ number: 7, state: w.state, body, labels: w.labels.map((name) => ({ name })) });
27
+ if (a[0] === "issue" && a[1] === "list" && a.includes("--label")) return JSON.stringify(w.state === "open" && w.labels.includes(a[a.indexOf("--label") + 1]) ? [{ number: 7 }] : []);
28
+ if (a[0] === "issue" && a[1] === "list") return JSON.stringify([{ number: 90, body: "<!-- FORGE:POSTDEPLOY_ROLLUP: x -->\n- [ ] `R1` — post-deploy: [check:smoke] #7" }]);
29
+ if (a[0] === "issue" && a[1] === "comment") { const b = a[a.indexOf("--body") + 1]; w.comments.push(b); w.issueComments.push({ ...BOT, body: b }); return ""; }
30
+ if (a[0] === "issue" && a[1] === "close") { w.closed.push(a[2]); w.state = "closed"; return ""; }
31
+ if (a[0] === "issue" && a[1] === "edit") {
32
+ w.edits.push(a.slice(3).filter((x) => x !== "-R" && x !== "o/r"));
33
+ const add = a.indexOf("--add-label"), rm = a.indexOf("--remove-label");
34
+ if (add > 0) w.labels.push(a[add + 1]);
35
+ if (rm > 0) w.labels = w.labels.filter((l) => l !== a[rm + 1]);
36
+ return "";
37
+ }
38
+ if (a[0] === "label") return "";
39
+ if (a[0] === "pr") return "[]";
40
+ throw new Error(`unexpected gh ${a.join(" ")}`);
41
+ },
42
+ async git(a) {
43
+ w.calls.push(["git", ...a]);
44
+ if (a[0] === "show" && a[1] === "origin/main:.forge/release.yaml") { if (releaseYaml == null) throw new Error("no file"); return releaseYaml; }
45
+ if (a[0] === "show" && a[1] === "origin/main:forge.yaml") throw new Error("no file");
46
+ if (a[0] === "show" && a[1] === "origin/main:.forge/post-deploy-checks.json") { if (!checks) throw new Error("no file"); return JSON.stringify(checks); }
47
+ if (a[0] === "rev-parse") return "ok\n";
48
+ if (a[0] === "merge-base") { if (!ancestor) throw new Error("exit 1"); return ""; }
49
+ throw new Error(`unexpected git ${a.join(" ")}`);
50
+ },
51
+ };
52
+ w.spawn = async ({ run }) => { w.ran.push(run); return { code: runs[run] ?? 0, stdout: `out:${run}`, stderr: "", timedOut: false }; };
53
+ return w;
54
+ }
55
+ const reconcile = (w, extra = {}) => reconcileLive({ repo: "o/r", io: w.io, cwd: "/nonexistent-5704", defaultBranch: "main", config, env: { PATH: "/bin" }, spawn: w.spawn, ...extra });
56
+
57
+ describe("live reconcile (#5704)", () => {
58
+ it("main ahead of a failed deploy: the fix is not in the live SHA, so the issue stays open with awaiting-promotion", async () => {
59
+ const w = world({ ancestor: false, checks: { smoke: "./smoke.sh" }, body: "- [ ] `R1` — post-deploy: [check:smoke]" });
60
+ const r = await reconcile(w);
61
+ assert.equal(r.live, LIVE);
62
+ assert.deepEqual(r.rows.map((x) => x.outcome), ["awaiting-promotion"]);
63
+ assert.deepEqual(w.closed, []);
64
+ assert.deepEqual(w.comments, []);
65
+ assert.ok(w.labels.includes("awaiting-promotion"));
66
+ assert.ok(!w.ran.includes("./smoke.sh"), "no check runs before the fix is live");
67
+ assert.ok(w.calls.some((c) => c[0] === "git" && c[1] === "merge-base" && c.includes(LIVE)), "ancestry is against the live SHA, not origin/main");
68
+ });
69
+
70
+ it("unknown live SHA is a no-op (fail closed): command fails, or no command configured", async () => {
71
+ for (const w of [world({ liveOut: null }), world({ releaseYaml: null })]) {
72
+ const r = await reconcile(w);
73
+ assert.equal(r.live, null);
74
+ assert.deepEqual(r.rows, []);
75
+ assert.equal(w.calls.filter((c) => c[0] === "issue").length, 0);
76
+ assert.match(formatReconcileSummary(r), /nothing reconciled/);
77
+ }
78
+ });
79
+
80
+ it("a check that fails after going live is never closed: post-deploy-failed added, awaiting-promotion removed, output commented", async () => {
81
+ const w = world({ labels: ["workflow:merged", "awaiting-promotion"], checks: { smoke: "./smoke.sh" }, runs: { "./smoke.sh": 1 }, body: "- [ ] `R1` — post-deploy: [check:smoke]" });
82
+ const r = await reconcile(w);
83
+ assert.deepEqual(r.rows.map((x) => x.outcome), ["failed"]);
84
+ assert.deepEqual(w.closed, []);
85
+ assert.ok(w.labels.includes("post-deploy-failed") && !w.labels.includes("awaiting-promotion"));
86
+ assert.equal(w.comments.length, 1);
87
+ assert.match(w.comments[0], /verification failed[\s\S]*out:\.\/smoke\.sh/);
88
+ assert.ok(!w.comments[0].includes("FORGE:VERIFIED"));
89
+ // the next pass does not re-run or re-comment
90
+ const again = await reconcile(w);
91
+ assert.deepEqual(again.rows.map((x) => x.outcome), ["failed-earlier"]);
92
+ assert.equal(w.comments.length, 1);
93
+ });
94
+
95
+ it("a passing run with a failing expect (positive evidence) is a fail, never a close", async () => {
96
+ const w = world({ checks: { quiet: { run: "./no-alert.sh", expect: "./rule-loaded.sh" } }, runs: { "./rule-loaded.sh": 1 }, body: "[check:quiet]" });
97
+ const r = await reconcile(w);
98
+ assert.deepEqual(r.rows.map((x) => x.outcome), ["failed"]);
99
+ assert.deepEqual(w.closed, []);
100
+ assert.match(w.comments[0], /expect \(positive evidence\) failed/);
101
+ });
102
+
103
+ it("all checks pass: FORGE:VERIFIED <live sha> posted, the issue closed and the rollup line ticked; a rerun repeats nothing", async () => {
104
+ const w = world({ labels: ["workflow:merged", "awaiting-promotion"], checks: { smoke: "./smoke.sh" }, body: "- [ ] `R1` — post-deploy: [check:smoke]" });
105
+ const r = await reconcile(w);
106
+ assert.deepEqual(r.rows.map((x) => x.outcome), ["verified"]);
107
+ assert.deepEqual(w.closed, ["7"]);
108
+ assert.equal(w.comments.length, 1);
109
+ assert.ok(w.comments[0].startsWith(`<!-- FORGE:VERIFIED ${LIVE} -->`));
110
+ assert.ok(!w.labels.includes("awaiting-promotion"));
111
+ const bodies = w.edits.filter((e) => e[0] === "--body").map((e) => e[1]);
112
+ assert.ok(bodies.some((b) => b.includes("- [x] `R1` — post-deploy: [check:smoke] #7") && b.includes("ROLLUP")), "rollup ticked");
113
+ const again = await reconcile(w);
114
+ assert.deepEqual(again.rows, []);
115
+ assert.equal(w.comments.length, 1);
116
+ assert.deepEqual(w.closed, ["7"]);
117
+ });
118
+
119
+ it("an open issue already carrying FORGE:VERIFIED for the live SHA is closed without a second marker or check run", async () => {
120
+ const w = world({ comments: [traj, { ...BOT, body: `<!-- FORGE:VERIFIED ${LIVE} -->` }], checks: { smoke: "./smoke.sh" }, body: "[check:smoke]" });
121
+ const r = await reconcile(w);
122
+ assert.deepEqual(r.rows.map((x) => x.outcome), ["verified"]);
123
+ assert.equal(w.comments.length, 0);
124
+ assert.ok(!w.ran.includes("./smoke.sh"));
125
+ assert.deepEqual(w.closed, ["7"]);
126
+ });
127
+
128
+ it("orphan: no checks and no hand-off closes once live with a note; a remediation-only TRACKED note is not a hand-off", async () => {
129
+ for (const comments of [[traj], [traj, { ...BOT, body: `${REMEDIATION_TRACKED_MARKER}\n## Merged by remediation` }]]) {
130
+ const w = world({ comments });
131
+ const r = await reconcile(w);
132
+ assert.deepEqual(r.rows.map((x) => x.outcome), ["verified"]);
133
+ assert.match(w.comments[0], /No post-deploy checks and no hand-off/);
134
+ assert.deepEqual(w.closed, ["7"]);
135
+ }
136
+ });
137
+
138
+ it("a FORGE:TRACKED hand-off with no checks stays open", async () => {
139
+ const w = world({ comments: [traj, { ...BOT, body: "<!-- FORGE:TRACKED -->\n## Left open: partial" }] });
140
+ const r = await reconcile(w);
141
+ assert.deepEqual(r.rows.map((x) => x.outcome), ["tracked"]);
142
+ assert.deepEqual(w.closed, []);
143
+ assert.deepEqual(w.comments, []);
144
+ });
145
+
146
+ it("a windowed check leaves the issue open under the monitoring label", async () => {
147
+ const w = world({ checks: { soak: { run: "./soak.sh", for: "7d" } }, body: "[check:soak]" });
148
+ const r = await reconcile(w);
149
+ assert.deepEqual(r.rows.map((x) => x.outcome), ["monitoring"]);
150
+ assert.deepEqual(w.closed, []);
151
+ assert.ok(w.labels.includes("post-deploy-monitoring"));
152
+ });
153
+
154
+ it("an unresolvable fix commit is skipped and reported; a named check missing from the file is not closed", async () => {
155
+ const w = world({ comments: [] });
156
+ assert.deepEqual((await reconcile(w)).rows.map((x) => x.outcome), ["unresolved"]);
157
+ const m = world({ body: "[check:ghost]", checks: { smoke: "./s" } });
158
+ assert.deepEqual((await reconcile(m)).rows.map((x) => x.outcome), ["missing-check"]);
159
+ assert.deepEqual(m.closed, []);
160
+ });
161
+
162
+ it("dry run writes nothing", async () => {
163
+ const w = world({ checks: { smoke: "./smoke.sh" }, body: "[check:smoke]" });
164
+ const r = await reconcile(w, { dryRun: true });
165
+ assert.deepEqual(r.rows.map((x) => x.outcome), ["verified"]);
166
+ assert.equal(w.calls.filter((c) => c[0] === "issue" && ["comment", "close", "edit"].includes(c[1])).length, 0);
167
+ });
168
+
169
+ it("helpers: live command from release.yaml, check ids, hand-off, summary", async () => {
170
+ assert.equal(await liveReleaseCommand({ io: world().io, cwd: "/nonexistent-5704", defaultBranch: "main" }), "./live.sh");
171
+ assert.deepEqual(checkIdsOf("[check:a] x [check:b] [check:a]"), ["a", "b"]);
172
+ assert.equal(hasHandOff([{ body: "<!-- FORGE:TRACKED -->" }]), true);
173
+ assert.equal(hasHandOff([{ body: REMEDIATION_TRACKED_MARKER }]), false);
174
+ assert.equal(formatReconcileSummary({ live: LIVE, rows: [{ outcome: "verified" }, { outcome: "awaiting-promotion" }] }), "live reconcile at 111111111111: verified and closed 1, awaiting promotion 1");
175
+ });
176
+ });
@@ -0,0 +1,245 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // #5805: engine/env-caused failures are held by signature (not relaunched blindly, not ended terminal) and re-admitted on an
4
+ // engine version change, a batch env change (--set-env) or the missing tool appearing; issue-caused failures are unchanged.
5
+ import { describe, it } from "node:test";
6
+ import assert from "node:assert/strict";
7
+ import { mkdirSync, writeFileSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { tmpDir } from "../tests/_tmp.mjs";
10
+ import { orchestrate, failureSignature, formatTable } from "./orchestrate.mjs";
11
+ import { envFingerprint } from "./batch.mjs";
12
+ import { hostMissingTools } from "./toolplace.mjs";
13
+
14
+ // A fake clock: every sleep advances it, so the batch's engine/env watch (30s) and hold window (2 min here) run instantly.
15
+ const harness = ({ script, issues = Object.keys(script).map(Number), parallel = 1, envHold = {}, store = null, onRow = () => {}, extra = {} }) => {
16
+ let t = 1_000_000;
17
+ const calls = [], decisions = [], updates = [];
18
+ const p = orchestrate({ issues, parallel, readBody: async () => "", now: () => t, store, pollMs: 1000,
19
+ sleep: async (ms) => { t += Math.max(1, Number(ms) || 0); },
20
+ recovery: { maxAttempts: 1, mechanicalMaxAttempts: 3 },
21
+ envHold: { maxMs: 120_000, watchMs: 30_000, ...envHold },
22
+ runOne: async (n, _l, ctx = {}) => {
23
+ calls.push({ n, recover: ctx.recover?.attempt ?? 0 });
24
+ t += 1000;
25
+ const list = script[n] ?? [{ terminalReason: "merged", pr: 1 }];
26
+ const k = calls.filter((c) => c.n === n).length - 1;
27
+ return list[Math.min(k, list.length - 1)];
28
+ },
29
+ decide: (d) => decisions.push(d), onUpdate: (r) => { updates.push(r); onRow(r); }, ...extra });
30
+ return p.then((rows) => ({ rows, calls, decisions, updates, byIssue: Object.fromEntries(rows.map((r) => [r.issue, r])) }));
31
+ };
32
+ const EE = (detail, code) => ({ terminalReason: "engine-error", detail, ...(code ? { code } : {}) });
33
+ const MERGED = { terminalReason: "merged", pr: 9 };
34
+ const miss = (tool, more = {}) => ({ terminalReason: "needs-human", code: "env.tool_missing", detail: `Environment error: the host is missing ${tool}, so validate command(s) could not run\n- env.tool_missing: probe ${Math.random()}`, ...more });
35
+ const memStore = () => { let st = null; return { load: () => (st ? JSON.parse(JSON.stringify(st)) : null), save: (s) => { st = JSON.parse(JSON.stringify(s)); }, log: () => {} }; };
36
+
37
+ describe("#5805 engine-error signatures", () => {
38
+ it("failureSignature normalises pids, ids, times and paths' numbers; the code is part of it", () => {
39
+ const a = failureSignature(undefined, "lane pid 4242 exited without a result; see /x/run-1a2b3c4d5e/log 2026-11-21T08:58:42.387Z\nstack");
40
+ const b = failureSignature(undefined, "lane pid 77 exited without a result; see /x/run-9f8e7d6c5b/log 2026-11-21T09:00:00Z\nother");
41
+ assert.equal(a, b);
42
+ assert.notEqual(failureSignature("engine.crash", "x"), failureSignature(undefined, "x"));
43
+ assert.notEqual(failureSignature(undefined, "ENOENT: no such file C:\\a"), failureSignature(undefined, "EACCES: denied"));
44
+ });
45
+
46
+ it("a relaunch that hits the same engine-error is held (not terminal); another issue with that signature is held without a relaunch", async () => {
47
+ const boom = (pid) => EE(`spawn failed: bad path segment (pid ${pid})`);
48
+ let added = [];
49
+ const r = await harness({ script: { 1: [boom(1), boom(2)], 2: [boom(3)] }, issues: [1], envHold: { version: () => "1.0.0" },
50
+ extra: { getAdded: () => added }, onRow: (row) => { if (row.issue === 1 && row.outcome === "held") added = [2]; } });
51
+ assert.deepEqual(r.calls.map((c) => c.n), [1, 1, 2], "issue 1 relaunched once; issue 2 (same signature, added later) never relaunched");
52
+ for (const n of [1, 2]) {
53
+ assert.equal(r.byIssue[n].outcome, "held");
54
+ assert.equal(r.byIssue[n].envHold.kind, "engine");
55
+ assert.equal(r.byIssue[n].envHold.version, "1.0.0");
56
+ assert.match(r.byIssue[n].detail, /^waiting on engine\/env change: .*re-admitted on an engine upgrade/);
57
+ assert.match(r.byIssue[n].detail.split("\n")[0], /no engine\/env change within/, "the hold window ended the batch, the row stays held (resumable)");
58
+ }
59
+ assert.match(formatTable(r.rows).split("\n")[2], /^#1 +held \(waiting on engine\/env change: .*\) +- /, "one report line per row");
60
+ assert.ok(r.decisions.some((d) => d.issue === 1 && /^held: waiting on engine\/env change/.test(d.what)));
61
+ });
62
+
63
+ it("a relaunch that fails with a different message keeps the current behaviour: final engine-error", async () => {
64
+ const r = await harness({ script: { 1: [EE("first failure"), EE("a different failure")] }, envHold: { version: () => "1.0.0" } });
65
+ assert.deepEqual(r.calls.map((c) => c.n), [1, 1]);
66
+ assert.equal(r.byIssue[1].outcome, "engine-error");
67
+ });
68
+
69
+ it("without envHold (module default) a repeated engine-error still ends engine-error after one relaunch", async () => {
70
+ const r = await harness({ script: { 1: [EE("same"), EE("same")] }, envHold: undefined, extra: { envHold: null } });
71
+ assert.equal(r.byIssue[1].outcome, "engine-error");
72
+ assert.equal(r.calls.length, 2);
73
+ });
74
+ });
75
+
76
+ describe("#5805 re-admission of held issues, no --requeue", () => {
77
+ const heldNow = (r, n) => r.issue === n && r.outcome === "held" && r.envHold;
78
+ it("an engine version change (reinstall/upgrade) re-admits the held issue and its dependent", async () => {
79
+ let v = "1.0.0";
80
+ const r = await harness({ script: { 1: [EE("boom"), EE("boom"), MERGED] }, issues: [1, 2], extra: { readBody: async (n) => (n === 2 ? "Depends on #1" : "") },
81
+ envHold: { version: () => v }, onRow: (row) => { if (heldNow(row, 1)) v = "1.0.1"; } });
82
+ assert.deepEqual(r.calls.map((c) => c.n), [1, 1, 1, 2]);
83
+ assert.equal(r.byIssue[1].outcome, "merged");
84
+ assert.equal(r.byIssue[2].outcome, "merged");
85
+ assert.ok(r.updates.some((u) => u.issue === 1 && u.outcome === "readmitted" && /engine version changed v1\.0\.0 → v1\.0\.1/.test(u.detail)));
86
+ });
87
+
88
+ it("a dependent waits held behind the held root and is released with it", async () => {
89
+ let v = "1.0.0", seen = 0;
90
+ const r = await harness({ script: { 1: [EE("boom"), EE("boom"), MERGED] }, issues: [1, 2], extra: { readBody: async (n) => (n === 2 ? "Depends on #1" : "") },
91
+ envHold: { version: () => v }, onRow: (row) => { if (row.issue === 2 && row.outcome === "held" && row.root === 1) { seen++; v = "1.0.1"; } } });
92
+ assert.equal(seen, 1, "issue 2 was held behind #1, not skipped");
93
+ assert.equal(r.byIssue[2].outcome, "merged");
94
+ });
95
+
96
+ it("a batch env change (--set-env) re-admits the held issue", async () => {
97
+ let fp = envFingerprint({ A: "1" });
98
+ const r = await harness({ script: { 1: [EE("boom"), EE("boom"), MERGED] }, envHold: { version: () => "1.0.0", envFingerprint: () => fp },
99
+ onRow: (row) => { if (heldNow(row, 1)) fp = envFingerprint({ A: "2" }); } });
100
+ assert.equal(r.byIssue[1].outcome, "merged");
101
+ assert.equal(r.calls.length, 3);
102
+ assert.ok(r.updates.some((u) => u.outcome === "readmitted" && /batch env changed \(--set-env\)/.test(u.detail)));
103
+ });
104
+
105
+ it("a resumed batch on a new engine version re-admits a hold an earlier run ended with", async () => {
106
+ const store = memStore();
107
+ const a = await harness({ script: { 1: [EE("boom")] }, store, envHold: { version: () => "1.0.0" } });
108
+ assert.equal(a.byIssue[1].outcome, "held");
109
+ const b = await harness({ script: { 1: [MERGED] }, store, envHold: { version: () => "1.1.0" } });
110
+ assert.equal(b.byIssue[1].outcome, "merged");
111
+ assert.ok(b.updates.some((u) => u.outcome === "readmitted" && /v1\.0\.0 → v1\.1\.0/.test(u.detail)));
112
+ });
113
+ });
114
+
115
+ describe("#5805 env.tool_missing is not recovered while the host lacks the tool", () => {
116
+ const remote = (first) => ({ max: 2, isRemote: () => true, place: () => ({ where: first, reason: "test" }), admit: () => ({ ok: true }), onBudget: "stop", costPerMinute: 0 });
117
+ it("a host run that lacked the tool is held, not re-run, until the probe finds it; then re-admitted", async () => {
118
+ let lacks = ["pytest"], probes = 0;
119
+ const r = await harness({ script: { 7: [miss("pytest"), MERGED] }, extra: { remote: remote("local") },
120
+ envHold: { version: () => "1.0.0", missingTools: async (t) => { probes++; if (probes >= 2) lacks = []; return t.filter((x) => lacks.includes(x)); } } });
121
+ assert.deepEqual(r.calls.map((c) => c.n), [7, 7]);
122
+ assert.equal(r.byIssue[7].outcome, "merged");
123
+ assert.ok(r.updates.some((u) => u.issue === 7 && u.outcome === "held" && u.envHold?.kind === "tool" && /the host that ran it lacks pytest/.test(u.detail)));
124
+ assert.ok(r.updates.some((u) => u.outcome === "readmitted" && /pytest now found on the host/.test(u.detail)));
125
+ });
126
+
127
+ it("a host recovery is not launched while the probe still misses the tool (the remote retry already used)", async () => {
128
+ const r = await harness({ script: { 7: [miss("pytest", { placement: { where: "remote" } }), miss("ruff", { placement: { where: "remote" } })] }, extra: { remote: remote("remote") },
129
+ envHold: { version: () => "1.0.0", missingTools: async (t) => t } });
130
+ assert.deepEqual(r.calls.map((c) => c.recover), [0, 1], "no host recovery lane while ruff is missing on the host");
131
+ assert.equal(r.byIssue[7].outcome, "held");
132
+ assert.deepEqual(r.byIssue[7].envHold.tools, ["ruff"]);
133
+ });
134
+
135
+ it("a probe that finds the tool re-admits once: the same miss again waits for an engine or env change (no loop)", async () => {
136
+ const r = await harness({ script: { 7: [miss("pytest")] }, extra: { remote: remote("local") }, envHold: { version: () => "1.0.0", missingTools: async () => [] } });
137
+ assert.equal(r.calls.length, 2);
138
+ assert.equal(r.byIssue[7].outcome, "held");
139
+ });
140
+ });
141
+
142
+ describe("#5805 issue-caused failures keep their behaviour", () => {
143
+ const NH = (code, more = {}) => ({ terminalReason: "needs-human", code, detail: `ended ${code}`, ...more });
144
+ it("ci.red still recovers in the batch; builder.blocked still ends needs-human", async () => {
145
+ const a = await harness({ script: { 1: [NH("ci.red", { pr: 5 }), MERGED] }, envHold: { version: () => "1.0.0", missingTools: async (t) => t } });
146
+ assert.deepEqual(a.calls.map((c) => c.recover), [0, 1]);
147
+ assert.equal(a.byIssue[1].outcome, "merged");
148
+ const b = await harness({ script: { 2: [NH("builder.blocked")] }, envHold: { version: () => "1.0.0" } });
149
+ assert.equal(b.calls.length, 1);
150
+ assert.equal(b.byIssue[2].outcome, "needs-human");
151
+ assert.equal(b.byIssue[2].envHold, undefined);
152
+ });
153
+ });
154
+
155
+ describe("#5805 probes", () => {
156
+ it("hostMissingTools finds executables on the PATH it is given", () => {
157
+ const dir = tmpDir("envhold-");
158
+ mkdirSync(join(dir, "sub"));
159
+ if (process.platform === "win32") writeFileSync(join(dir, "mytool.cmd"), "");
160
+ else writeFileSync(join(dir, "mytool"), "#!/bin/sh\n", { mode: 0o755 });
161
+ assert.deepEqual(hostMissingTools(["mytool", "nope-tool", "sub"], { path: dir }), ["nope-tool", "sub"]);
162
+ });
163
+ it("envFingerprint is order-independent and changes with a value", () => {
164
+ assert.equal(envFingerprint({ A: "1", B: "2" }), envFingerprint({ B: "2", A: "1" }));
165
+ assert.notEqual(envFingerprint({ A: "1" }), envFingerprint({ A: "2" }));
166
+ assert.equal(envFingerprint(undefined), envFingerprint({}));
167
+ });
168
+ });
169
+
170
+ describe("#5755 one env issue per signature", () => {
171
+ const seam = (closed = () => false) => {
172
+ const calls = [];
173
+ return { calls, ensure: async (a) => { calls.push(a); return 900; }, isClosed: async () => closed() };
174
+ };
175
+ const timeout = (extra = {}) => ({ terminalReason: "needs-human", code: "env.validate_timeout", detail: "validate V1 timed out after 900s on host 1234", ...extra });
176
+
177
+ it("two issues with the same env signature share one env issue and are held, never needs-human", async () => {
178
+ const e = seam();
179
+ const { byIssue, calls } = await harness({ script: { 1: [miss("html2text")], 2: [miss("html2text")] }, envHold: null, extra: { envIssue: e } });
180
+ assert.equal(byIssue[1].outcome, "held");
181
+ assert.equal(byIssue[2].outcome, "held");
182
+ assert.equal(byIssue[1].envHold.envIssue, 900);
183
+ assert.deepEqual(e.calls.map((c) => c.sig), ["env.tool_missing|html2text", "env.tool_missing|html2text"]);
184
+ assert.deepEqual(e.calls[1].issues, [1, 2]);
185
+ assert.equal(calls.length, 2, "no recovery lane is launched");
186
+ });
187
+
188
+ it("after 2 issues hit a signature a pending issue whose body names the tool is not admitted", async () => {
189
+ const e = seam();
190
+ const bodies = { 3: "needs html2text to validate", 4: "unrelated" };
191
+ const { byIssue, calls } = await harness({ script: { 1: [miss("html2text")], 2: [miss("html2text")], 3: [MERGED], 4: [MERGED] }, envHold: null, extra: { envIssue: e, readBody: async (n) => bodies[n] ?? "" } });
192
+ assert.equal(byIssue[3].outcome, "held");
193
+ assert.equal(byIssue[3].envHold.envIssue, 900);
194
+ assert.equal(byIssue[4].outcome, "merged");
195
+ assert.equal(calls.some((c) => c.n === 3), false);
196
+ });
197
+
198
+ it("env.validate_timeout and env.capability_remote are held on an env issue, not needs-human", async () => {
199
+ const e = seam();
200
+ const { byIssue } = await harness({ script: { 1: [timeout()], 2: [{ terminalReason: "needs-human", code: "env.capability_remote", detail: "capability sops is host-only" }] }, envHold: null, extra: { envIssue: e } });
201
+ assert.equal(byIssue[1].outcome, "held");
202
+ assert.equal(byIssue[2].outcome, "held");
203
+ });
204
+
205
+ it("held issues are requeued when the env issue closes", async () => {
206
+ let closed = false;
207
+ const e = seam(() => closed);
208
+ const { byIssue } = await harness({ script: { 1: [miss("html2text"), MERGED] }, envHold: null,
209
+ onRow: (r) => { if (r.issue === 1 && r.outcome === "held") closed = true; }, extra: { envIssue: e } });
210
+ assert.equal(byIssue[1].outcome, "merged");
211
+ });
212
+
213
+ it("without the seam the env.validate_timeout flow is unchanged (needs-human)", async () => {
214
+ const { byIssue } = await harness({ script: { 1: [timeout()] }, envHold: null });
215
+ assert.notEqual(byIssue[1].outcome, "held");
216
+ });
217
+
218
+ it("after 2 issues hit a non-tool signature a pending issue whose contract names its path is not admitted", async () => {
219
+ const e = seam();
220
+ const t = (d) => ({ terminalReason: "needs-human", code: "env.validate_timeout", detail: d });
221
+ const bodies = { 3: "validate runs shared/html2text/build.sh", 4: "unrelated" };
222
+ const { byIssue } = await harness({ script: { 1: [t("validate timed out running shared/html2text/build.sh")], 2: [t("validate timed out running shared/html2text/build.sh")], 3: [MERGED], 4: [MERGED] },
223
+ envHold: null, extra: { envIssue: e, readBody: async (n) => bodies[n] ?? "" } });
224
+ assert.equal(byIssue[3].outcome, "held");
225
+ assert.equal(byIssue[4].outcome, "merged");
226
+ });
227
+
228
+ it("an env park on a security issue escalates: not held, not parked into remediation-queue", async () => {
229
+ const e = seam();
230
+ const relabels = [];
231
+ const { byIssue } = await harness({ script: { 1: [miss("html2text")] }, envHold: null,
232
+ extra: { envIssue: e, issueLabels: async () => ["security"], relabelNeedsHuman: async (a) => { relabels.push(a); return true; } } });
233
+ assert.equal(byIssue[1].outcome, "needs-human");
234
+ assert.match(byIssue[1].detail, /Security issue escalated/);
235
+ assert.equal(relabels.some((a) => a.parked), false, "no parked/remediation-queue relabel");
236
+ assert.equal(relabels.some((a) => !a.parked && /Security issue escalated/.test(a.evidence)), true, "needs-human label applied");
237
+ });
238
+
239
+ it("when the env issue cannot be filed the env.* failure is still held, never needs-human", async () => {
240
+ const e = { ensure: async () => { throw new Error("gh down"); }, isClosed: async () => false };
241
+ const { byIssue } = await harness({ script: { 1: [miss("html2text")] }, envHold: null, extra: { envIssue: e } });
242
+ assert.equal(byIssue[1].outcome, "held");
243
+ assert.equal(byIssue[1].envHold.envIssue, undefined);
244
+ });
245
+ });
@@ -39,3 +39,42 @@ describe("#5652 host fallback placement", () => {
39
39
  assert.ok(r.calls.length >= 1);
40
40
  });
41
41
  });
42
+
43
+ // #5808: a lane's slow post-result work (teardown) is its postRun: the dependent starts at once, the batch still waits for it.
44
+ describe("#5808 dispatch on lane exit", () => {
45
+ const run = async (cfg = {}) => {
46
+ const log = [];
47
+ let release;
48
+ const gate = new Promise((res) => { release = res; });
49
+ const p = orchestrate({ issues: [1, 2], parallel: 2, readBody: async (n) => (n === 2 ? "Depends on #1" : ""),
50
+ remote: { max: 1, isRemote: () => true, place: () => ({ where: "remote", reason: "mode remote" }), admit: () => ({ ok: true }), onBudget: "stop", costPerMinute: 0, ...cfg },
51
+ runOne: async (n) => {
52
+ log.push(`start ${n}`);
53
+ if (n === 1) return { terminalReason: "merged", pr: 1, postRun: async () => { await gate; log.push("postRun 1 done"); } };
54
+ return { terminalReason: "merged", pr: 2 };
55
+ } });
56
+ return { p, log, release };
57
+ };
58
+ it("orchestrate: dependent starts before the finished lane's postRun resolves (#5808)", async () => {
59
+ const { p, log, release } = await run({ max: 2 });
60
+ await new Promise((r) => setTimeout(r, 50));
61
+ assert.deepEqual(log, ["start 1", "start 2"]); // before postRun 1 resolved
62
+ release();
63
+ await p;
64
+ assert.deepEqual(log, ["start 1", "start 2", "postRun 1 done"]); // the batch waited for it
65
+ });
66
+ it("orchestrate: a pass runs on lane exit, with no scheduler tick (sleep never fires) (#5808)", async () => {
67
+ const log = [];
68
+ const never = () => new Promise(() => {}); // a tick that never arrives: only the lane exit can wake the loop
69
+ let free;
70
+ const gate = new Promise((res) => { free = res; });
71
+ const p = orchestrate({ issues: [1, 2], parallel: 1, pollMs: 1e9, sleep: never, readBody: async (n) => (n === 2 ? "Depends on #1" : ""),
72
+ runOne: async (n) => { log.push(`start ${n}`); if (n === 1) await gate; return { terminalReason: "merged", pr: n }; } });
73
+ await new Promise((r) => setTimeout(r, 20));
74
+ assert.deepEqual(log, ["start 1"]); // K=1: the dependent is held while the slot is taken
75
+ free();
76
+ const rows = await p; // would hang if the next pass waited for a tick
77
+ assert.deepEqual(log, ["start 1", "start 2"]);
78
+ assert.deepEqual(rows.map((x) => x.outcome), ["merged", "merged"]);
79
+ });
80
+ });