forgedock 1.62.0 → 1.64.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 (87) hide show
  1. package/bin/config-schema.mjs +5 -0
  2. package/bin/engine/outcome-codes.mjs +5 -0
  3. package/bin/engine-cli.mjs +109 -21
  4. package/bin/env/cli.mjs +18 -1
  5. package/bin/lean/basered.mjs +56 -11
  6. package/bin/lean/basered.test.mjs +58 -5
  7. package/bin/lean/batch-health.mjs +46 -4
  8. package/bin/lean/batch-health.test.mjs +55 -1
  9. package/bin/lean/batch.mjs +9 -1
  10. package/bin/lean/batch.test.mjs +74 -7
  11. package/bin/lean/ceiling.mjs +47 -3
  12. package/bin/lean/ceiling.test.mjs +32 -1
  13. package/bin/lean/conformance.e2e.test.mjs +32 -6
  14. package/bin/lean/conformance.mjs +57 -13
  15. package/bin/lean/conformance.test.mjs +93 -1
  16. package/bin/lean/execution.mjs +24 -12
  17. package/bin/lean/execution.test.mjs +59 -9
  18. package/bin/lean/forgedock-lane-workflow.test.mjs +62 -2
  19. package/bin/lean/issuewatch-reconcile.mjs +2 -0
  20. package/bin/lean/issuewatch-reconcile.test.mjs +25 -0
  21. package/bin/lean/issuewatch.mjs +3 -0
  22. package/bin/lean/lanecheck.test.mjs +13 -1
  23. package/bin/lean/lean.mjs +214 -32
  24. package/bin/lean/lean.test.mjs +406 -21
  25. package/bin/lean/live-execution.mjs +25 -0
  26. package/bin/lean/live-execution.test.mjs +35 -1
  27. package/bin/lean/merged-park.mjs +76 -0
  28. package/bin/lean/merged-park.test.mjs +64 -0
  29. package/bin/lean/mergetrain.mjs +357 -0
  30. package/bin/lean/mergetrain.test.mjs +348 -0
  31. package/bin/lean/orchestrate-envhold.test.mjs +62 -0
  32. package/bin/lean/orchestrate-stacking.test.mjs +144 -0
  33. package/bin/lean/orchestrate-train.test.mjs +130 -0
  34. package/bin/lean/orchestrate-transient-git.test.mjs +53 -0
  35. package/bin/lean/orchestrate.mjs +234 -17
  36. package/bin/lean/prompts.mjs +4 -3
  37. package/bin/lean/release-review.mjs +8 -1
  38. package/bin/lean/release-review.test.mjs +42 -2
  39. package/bin/lean/release-status.test.mjs +53 -1
  40. package/bin/lean/release.mjs +6 -3
  41. package/bin/lean/render.mjs +6 -1
  42. package/bin/lean/run-issue-placement.test.mjs +27 -3
  43. package/bin/lean/sandbox-provider.contract.test.mjs +6 -0
  44. package/bin/lean/sandbox-remote.mjs +12 -2
  45. package/bin/lean/sched.mjs +19 -2
  46. package/bin/lean/sched.test.mjs +33 -1
  47. package/bin/lean/schedd-health.mjs +2 -1
  48. package/bin/lean/schedd-health.test.mjs +7 -0
  49. package/bin/lean/schedd.mjs +55 -7
  50. package/bin/lean/schedd.test.mjs +42 -1
  51. package/bin/lean/stacking.mjs +140 -0
  52. package/bin/lean/stacking.test.mjs +98 -0
  53. package/bin/lean/statuscomment.mjs +14 -8
  54. package/bin/lean/statuscomment.test.mjs +18 -1
  55. package/bin/lean/validate-catalog.mjs +1 -1
  56. package/bin/lean/validate-catalog.test.mjs +3 -0
  57. package/bin/lean/worktree.mjs +8 -3
  58. package/bin/lean/worktree.test.mjs +18 -0
  59. package/bin/pool/agent.mjs +325 -46
  60. package/bin/pool/cache-sweep.mjs +2 -0
  61. package/bin/pool/cli.mjs +120 -6
  62. package/bin/pool/disk.mjs +43 -0
  63. package/bin/pool/docker.mjs +21 -5
  64. package/bin/pool/health.mjs +95 -0
  65. package/bin/pool/router.mjs +274 -27
  66. package/bin/runner.mjs +3 -1
  67. package/bin/stats/chains.mjs +101 -0
  68. package/bin/stats/chains.test.mjs +53 -0
  69. package/bin/stats/efficiency.mjs +7 -6
  70. package/bin/stats/efficiency.test.mjs +48 -7
  71. package/bin/stats/index.mjs +11 -3
  72. package/bin/stats/stats.test.mjs +9 -0
  73. package/docs/CONFIG.md +23 -1
  74. package/docs/OUTCOME-CODES.md +4 -0
  75. package/package.json +1 -1
  76. package/pool/README.md +10 -0
  77. package/pool/image/Dockerfile +2 -1
  78. package/pool/image/entrypoint.sh +6 -6
  79. package/pool/image/mirror.sh +71 -0
  80. package/pool/install/install-agent-linux.sh +57 -5
  81. package/pool/install/install-agent-macos.sh +148 -0
  82. package/pool/install/install-agent.ps1 +11 -0
  83. package/pool/install/install-agent.sh +59 -7
  84. package/pool/install/uninstall-agent-linux.sh +75 -0
  85. package/pool/install/uninstall-agent-macos.sh +60 -0
  86. package/pool/install/uninstall-agent.ps1 +1 -0
  87. package/scripts/transition-label.sh +11 -0
@@ -0,0 +1,140 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ //
4
+ // bin/lean/stacking.mjs — stacked lanes, phase 1 (#5831, epic #5822). A dependent whose only unmet gates are in-batch
5
+ // dependencies still pending or running is planned (contract frozen, no build) in an idle slot; its build lane later reuses
6
+ // that contract unless the dependency's merged diff made it stale. Pure: facts in, verdicts out; no I/O.
7
+
8
+ export const STACKING_MODES = ["off", "plan", "full"];
9
+
10
+ /** forge.yaml `orchestration.stacking`: off (default) | plan | full (plan lanes plus stacked builds at PR-ready, #5832); anything else is off. */
11
+ export function normalizeStacking(value) {
12
+ const v = String(value ?? "").trim().toLowerCase();
13
+ return v === "plan" || v === "full" ? v : "off";
14
+ }
15
+
16
+ /**
17
+ * Whether `n` may run as a plan lane now: it has in-batch dependencies, at least one still unmet (pending or running, not
18
+ * ended), none ended unsatisfied, it is not running, and it has not been planned or tried before (one plan lane per issue per batch).
19
+ * @param {{n:number, edges:number[], results:Map, pending:number[], running:Map|Set, planTried:Set, satisfied:Set<string>}} a
20
+ */
21
+ export function planAdmissible({ n, edges, results, pending, running, planTried, satisfied }) {
22
+ if (!edges.length || planTried.has(n) || results.has(n) || running.has(n) || !pending.includes(n)) return false;
23
+ let unmet = false;
24
+ for (const d of edges) {
25
+ const r = results.get(d);
26
+ if (!r) { if (!pending.includes(d) && !running.has(d)) return false; unmet = true; continue; }
27
+ if (!satisfied.has(r.outcome)) return false;
28
+ }
29
+ return unmet;
30
+ }
31
+
32
+ /** `--planned <hash>:<sha>` <-> {contractHash, baseSha}; null when malformed. */
33
+ export const formatPlanned = (p) => (p?.contractHash && p?.baseSha ? `${p.contractHash}:${p.baseSha}` : null);
34
+ export function parsePlanned(text) {
35
+ const m = /^([0-9a-f]{6,64}):([0-9a-f]{7,64})$/.exec(String(text ?? "").trim());
36
+ return m ? { contractHash: m[1], baseSha: m[2] } : null;
37
+ }
38
+
39
+ /**
40
+ * Why a plan-lane contract cannot be reused by the build lane, or null. Stale when the frozen contract is not the planned
41
+ * one (the scope changed and it was re-planned), when the plan's base is no longer an ancestor of the lane (lane changed),
42
+ * or when the commits landed on the lane since the plan (the dependency's merge) touch a deliverable path.
43
+ * @param {{planned:{contractHash:string, baseSha:string}, contractHash:string, ancestor:boolean, changedPaths:string[], deliverablePaths:string[]}} a
44
+ */
45
+ export function planStale({ planned, contractHash, ancestor, changedPaths = [], deliverablePaths = [] }) {
46
+ if (!planned) return "no plan";
47
+ if (planned.contractHash !== contractHash) return `contract ${planned.contractHash} -> ${contractHash}`;
48
+ if (!ancestor) return `lane moved: planned base ${planned.baseSha} is not an ancestor of the lane head`;
49
+ const want = new Set(deliverablePaths);
50
+ const hit = changedPaths.filter((p) => want.has(p));
51
+ return hit.length ? `dependency diff touches deliverable path(s): ${hit.slice(0, 5).join(", ")}` : null;
52
+ }
53
+
54
+ /**
55
+ * #5832 (phase 2): whether `n` may build now on its dependency's lane head. Exactly one in-batch dependency is unmerged (running, not
56
+ * ended) and it is PR-ready (`prReady`: issue -> {pr, branch, sha}); every other dependency ended satisfied. Never for a lane that
57
+ * is running, has a result, or was stacked before (one stacked build per issue per batch).
58
+ * @param {{n:number, edges:number[], results:Map, pending:number[], running:Map|Set, prReady:Map, stackedTried:Set, satisfied:Set<string>}} a
59
+ * @returns {{dependency:number, branch:string, sha:string}|null}
60
+ */
61
+ export function stackAdmissible({ n, edges, results, pending, running, prReady, stackedTried, satisfied }) {
62
+ if (!edges.length || stackedTried.has(n) || results.has(n) || running.has(n) || !pending.includes(n)) return null;
63
+ let open = null;
64
+ for (const d of edges) {
65
+ const r = results.get(d);
66
+ if (r) { if (!satisfied.has(r.outcome)) return null; continue; }
67
+ if (open !== null || !running.has(d)) return null;
68
+ open = d;
69
+ }
70
+ const rd = open === null ? null : prReady.get(open);
71
+ return rd?.branch && rd?.sha ? { dependency: open, branch: String(rd.branch), sha: String(rd.sha) } : null;
72
+ }
73
+
74
+ /** `stackedOn` {dependency, branch, sha} <-> `--stacked-on <dep>:<sha>:<branch>`; null when malformed. */
75
+ export const formatStackedOn = (s) => (s?.dependency && s?.branch && s?.sha ? `${s.dependency}:${s.sha}:${s.branch}` : null);
76
+ export function parseStackedOn(text) {
77
+ const m = /^(\d+):([0-9a-f]{7,64}):(.+)$/.exec(String(text ?? "").trim());
78
+ return m ? { dependency: Number(m[1]), sha: m[2], branch: m[3] } : null;
79
+ }
80
+
81
+ /** Valid `stackedOn` object (from ctx/CLI) or null. */
82
+ export const validStackedOn = (s) => (Number.isInteger(s?.dependency) && typeof s?.branch === "string" && s.branch && typeof s?.sha === "string" && /^[0-9a-f]{7,64}$/.test(s.sha) ? { dependency: s.dependency, branch: s.branch, sha: s.sha } : null);
83
+
84
+ /**
85
+ * Engine guard `merge.stacked_base` (#5832): why a PR may not be merged now, or null. A PR whose base is not the lane is a
86
+ * stacked PR; it never merges into the dependency branch (or anything but the lane), and not while a `Depends on` is unmerged.
87
+ * @param {{prBase:string, lane:string, stackedBranch?:string|null, dependencyMerged:boolean}} a
88
+ */
89
+ export function stackedBaseBlock({ prBase, lane, stackedBranch = null, dependencyMerged }) {
90
+ const stacked = Boolean(stackedBranch) || (prBase && lane && prBase !== lane);
91
+ if (!stacked) return null;
92
+ if (!dependencyMerged) return `merge.stacked_base: PR base ${prBase || "?"} is not the lane ${lane} and its dependency is unmerged`;
93
+ if (prBase !== lane) return `merge.stacked_base: PR base ${prBase || "?"} is not the lane ${lane}`;
94
+ return null;
95
+ }
96
+
97
+ /** #5833 (phase 3): cascade kinds recorded on a stacked dependent's row (`cascade`, `cascades`). */
98
+ export const CASCADES = ["rebase", "reverify", "restart", "replan"];
99
+
100
+ /**
101
+ * Which cascade a stacked dependent needs now, or null (nothing moved). `depState`: open | merged | closed (closed = ended without a merge).
102
+ * merged -> rebase onto the lane; closed -> replan on the lane base; open with a moved head -> reverify (clean rebase) or restart (conflict).
103
+ * @param {{depState:string, depHeadSha?:string|null, stackedSha?:string|null, rebaseConflict?:boolean}} a
104
+ */
105
+ export function cascadeDecision({ depState, depHeadSha = null, stackedSha = null, rebaseConflict = false }) {
106
+ if (depState === "merged") return "rebase";
107
+ if (depState === "closed") return "replan";
108
+ if (depState !== "open" || !depHeadSha || !stackedSha || depHeadSha === stackedSha) return null;
109
+ return rebaseConflict ? "restart" : "reverify";
110
+ }
111
+
112
+ /**
113
+ * The checks the dependency's final diff invalidates: a command naming a path (token with `/`) is kept when a changed path equals it or
114
+ * lies under it (or it lies under the changed path); a command naming no path cannot be scoped and is always kept.
115
+ * @param {{changedPaths:string[], checks:string[]}} a
116
+ */
117
+ export function invalidatedChecks({ changedPaths = [], checks = [] }) {
118
+ const norm = (t) => t.replace(/^["']|["']$/g, "").replace(/^\.\//, "").replace(/\/+$/, "");
119
+ return checks.filter((c) => {
120
+ const toks = String(c).split(/\s+/).map(norm).filter((t) => t.includes("/") && !t.startsWith("-") && !/^[a-z]+:\/\//.test(t));
121
+ if (!toks.length) return true;
122
+ return toks.some((t) => changedPaths.some((p) => p === t || p.startsWith(`${t}/`) || t.startsWith(`${p}/`)));
123
+ });
124
+ }
125
+
126
+ /** Batch-report metric: cascades per stacked dependent and the cost of the rework (rows carry `stacked`, `cascades`, `cascade_cost_usd`, `cascade_minutes`). */
127
+ export function cascadeRate(rows = []) {
128
+ const st = rows.filter((r) => r?.stacked);
129
+ const list = st.map((r) => (Array.isArray(r.cascades) ? r.cascades : r.cascade ? [r.cascade] : []));
130
+ const cascades = list.reduce((s, l) => s + l.length, 0);
131
+ const round = (x, k) => Math.round(x * k) / k;
132
+ return { stacked: st.length, cascades, perStacked: st.length ? round(cascades / st.length, 100) : 0,
133
+ reworkCostUsd: round(st.reduce((s, r) => s + (Number(r.cascade_cost_usd) || 0), 0), 1e6), reworkMinutes: round(st.reduce((s, r) => s + (Number(r.cascade_minutes) || 0), 0), 10) };
134
+ }
135
+
136
+ /** One report line, or null when nothing was stacked. */
137
+ export function formatCascadeSummary(rows) {
138
+ const m = cascadeRate(rows);
139
+ return m.stacked ? `stacked lanes: ${m.stacked} dependent(s), ${m.cascades} cascade(s) (${m.perStacked}/dependent), rework $${m.reworkCostUsd.toFixed(2)} / ${m.reworkMinutes} min` : null;
140
+ }
@@ -0,0 +1,98 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // #5831: stacked lanes phase 1 — the pure helpers.
4
+ import { describe, it } from "node:test";
5
+ import assert from "node:assert/strict";
6
+ import { normalizeStacking, planAdmissible, formatPlanned, parsePlanned, planStale, stackAdmissible, formatStackedOn, parseStackedOn, validStackedOn, stackedBaseBlock, cascadeDecision, invalidatedChecks, cascadeRate, formatCascadeSummary, CASCADES } from "./stacking.mjs";
7
+
8
+ const SAT = new Set(["merged", "invalid"]);
9
+ const base = { n: 2, edges: [1], results: new Map(), pending: [1, 2], running: new Map(), planTried: new Set(), satisfied: SAT };
10
+
11
+ describe("stacking helpers (#5831)", () => {
12
+ it("normalizeStacking: off by default, full is its own mode, junk is off", () => {
13
+ assert.equal(normalizeStacking(undefined), "off");
14
+ assert.equal(normalizeStacking("off"), "off");
15
+ assert.equal(normalizeStacking("plan"), "plan");
16
+ assert.equal(normalizeStacking("FULL"), "full");
17
+ assert.equal(normalizeStacking("yes"), "off");
18
+ });
19
+ it("planAdmissible: only a dependent with an unmet in-batch dependency, once", () => {
20
+ assert.equal(planAdmissible(base), true);
21
+ assert.equal(planAdmissible({ ...base, edges: [] }), false, "no dependency");
22
+ assert.equal(planAdmissible({ ...base, planTried: new Set([2]) }), false, "one plan lane per issue");
23
+ assert.equal(planAdmissible({ ...base, running: new Map([[2, 1]]) }), false, "already running");
24
+ assert.equal(planAdmissible({ ...base, results: new Map([[1, { outcome: "merged" }]]) }), false, "nothing unmet: a build lane");
25
+ assert.equal(planAdmissible({ ...base, results: new Map([[1, { outcome: "needs-human" }]]) }), false, "failed dependency");
26
+ assert.equal(planAdmissible({ ...base, pending: [2], running: new Map([[1, 1]]) }), true, "dependency running");
27
+ assert.equal(planAdmissible({ ...base, pending: [2] }), false, "dependency neither pending nor running");
28
+ });
29
+ it("planned <-> --planned round trip", () => {
30
+ const p = { contractHash: "abcdef123456", baseSha: "0123456789abcdef0123456789abcdef01234567" };
31
+ assert.deepEqual(parsePlanned(formatPlanned(p)), p);
32
+ assert.equal(parsePlanned("nonsense"), null);
33
+ assert.equal(parsePlanned(undefined), null);
34
+ assert.equal(formatPlanned(null), null);
35
+ });
36
+ it("planStale: contract, lane and deliverable-path changes make a plan stale", () => {
37
+ const planned = { contractHash: "aaaaaaaaaaaa", baseSha: "b".repeat(40) };
38
+ const ok = { planned, contractHash: "aaaaaaaaaaaa", ancestor: true, changedPaths: ["docs/x.md"], deliverablePaths: ["bin/a.mjs"] };
39
+ assert.equal(planStale(ok), null);
40
+ assert.match(planStale({ ...ok, contractHash: "cccccccccccc" }), /contract/);
41
+ assert.match(planStale({ ...ok, ancestor: false }), /lane moved/);
42
+ assert.match(planStale({ ...ok, changedPaths: ["bin/a.mjs"] }), /deliverable path/);
43
+ assert.match(planStale({ ...ok, planned: null }), /no plan/);
44
+ });
45
+ });
46
+
47
+ describe("stacked builds, phase 2 (#5832)", () => {
48
+ const rd = new Map([[1, { pr: 9, branch: "feat/issue-1", sha: "a".repeat(40) }]]);
49
+ const a = { ...base, pending: [2], running: new Map([[1, 1]]), prReady: rd, stackedTried: new Set() };
50
+ it("stackAdmissible: only when the one unmerged dependency is running and PR-ready", () => {
51
+ assert.deepEqual(stackAdmissible(a), { dependency: 1, branch: "feat/issue-1", sha: "a".repeat(40) });
52
+ assert.equal(stackAdmissible({ ...a, prReady: new Map() }), null, "not PR-ready yet");
53
+ assert.equal(stackAdmissible({ ...a, running: new Map() }), null, "dependency not running");
54
+ assert.equal(stackAdmissible({ ...a, stackedTried: new Set([2]) }), null, "once per issue");
55
+ assert.equal(stackAdmissible({ ...a, edges: [1, 3], pending: [2, 3] }), null, "a second unmerged dependency");
56
+ assert.equal(stackAdmissible({ ...a, edges: [1, 3], results: new Map([[3, { outcome: "merged" }]]) })?.dependency, 1, "others merged");
57
+ assert.equal(stackAdmissible({ ...a, edges: [1, 3], results: new Map([[3, { outcome: "needs-human" }]]) }), null, "another failed");
58
+ });
59
+ it("stackedOn <-> --stacked-on round trip", () => {
60
+ const s = { dependency: 1, branch: "feat/issue-1", sha: "abcdef1234567" };
61
+ assert.deepEqual(parseStackedOn(formatStackedOn(s)), s);
62
+ assert.equal(parseStackedOn("x"), null);
63
+ assert.deepEqual(validStackedOn(s), s);
64
+ assert.equal(validStackedOn({ ...s, sha: "zz" }), null);
65
+ });
66
+ it("stackedBaseBlock (merge.stacked_base): a stacked PR never merges into the dependency branch or before the dependency", () => {
67
+ const g = { prBase: "feat/issue-1", lane: "staging", stackedBranch: "feat/issue-1" };
68
+ assert.match(stackedBaseBlock({ ...g, dependencyMerged: false }), /^merge\.stacked_base/);
69
+ assert.match(stackedBaseBlock({ ...g, dependencyMerged: true }), /not the lane/, "merged dependency but base not yet moved");
70
+ assert.match(stackedBaseBlock({ ...g, prBase: "staging", dependencyMerged: false }), /unmerged/);
71
+ assert.equal(stackedBaseBlock({ ...g, prBase: "staging", dependencyMerged: true }), null);
72
+ assert.equal(stackedBaseBlock({ prBase: "staging", lane: "staging", dependencyMerged: false }), null, "not stacked");
73
+ });
74
+ });
75
+
76
+ describe("cascades (#5833)", () => {
77
+ it("cascadeDecision: merged -> rebase, closed -> replan, moved head -> reverify or restart on a conflict, nothing moved -> null", () => {
78
+ assert.equal(cascadeDecision({ depState: "merged" }), "rebase");
79
+ assert.equal(cascadeDecision({ depState: "closed" }), "replan");
80
+ assert.equal(cascadeDecision({ depState: "open", depHeadSha: "b", stackedSha: "a" }), "reverify");
81
+ assert.equal(cascadeDecision({ depState: "open", depHeadSha: "b", stackedSha: "a", rebaseConflict: true }), "restart");
82
+ assert.equal(cascadeDecision({ depState: "open", depHeadSha: "a", stackedSha: "a" }), null);
83
+ assert.equal(cascadeDecision({ depState: "unknown", depHeadSha: "b", stackedSha: "a" }), null);
84
+ assert.deepEqual(CASCADES, ["rebase", "reverify", "restart", "replan"]);
85
+ });
86
+ it("invalidatedChecks keeps path-scoped checks the diff touches and every unscoped check", () => {
87
+ const checks = ["node --test bin/lean/stacking.test.mjs", "node --test docs/x.test.mjs", "pnpm lint", "eslint src/"];
88
+ assert.deepEqual(invalidatedChecks({ changedPaths: ["bin/lean/stacking.mjs", "src/a.ts"], checks }), ["pnpm lint", "eslint src/"]);
89
+ assert.deepEqual(invalidatedChecks({ changedPaths: ["bin/lean/stacking.test.mjs"], checks }), ["node --test bin/lean/stacking.test.mjs", "pnpm lint", "eslint src/"]);
90
+ assert.deepEqual(invalidatedChecks({ changedPaths: [], checks }), ["pnpm lint", "eslint src/"]);
91
+ });
92
+ it("cascadeRate: cascades per stacked dependent and the rework cost; non-stacked rows are ignored", () => {
93
+ const rows = [{ issue: 1, outcome: "merged" }, { issue: 2, stacked: true, cascades: ["reverify", "rebase"], cascade_cost_usd: 0.5, cascade_minutes: 3 }, { issue: 3, stacked: true }];
94
+ assert.deepEqual(cascadeRate(rows), { stacked: 2, cascades: 2, perStacked: 1, reworkCostUsd: 0.5, reworkMinutes: 3 });
95
+ assert.equal(formatCascadeSummary([{ issue: 1 }]), null);
96
+ assert.match(formatCascadeSummary(rows), /2 dependent\(s\), 2 cascade\(s\)/);
97
+ });
98
+ });
@@ -155,14 +155,20 @@ export const isPipelineLabel = (name) => { const n = String(name ?? ""); return
155
155
  export const pipelineLabels = (labels) => (labels ?? []).map((l) => (typeof l === "string" ? l : l?.name)).filter(isPipelineLabel);
156
156
 
157
157
  /**
158
- * Remove the pipeline labels from an issue. `labels` is what the caller already read (names or `{name}`); null re-reads them.
159
- * Best effort, returns the removed names ([] when none or on failure).
158
+ * Remove the pipeline labels from an issue, one call per label so one failing removal leaves the others removed (#5759).
159
+ * `labels` is what the caller already read (names or `{name}`); null re-reads them. Returns the removed names; `onFail(names, err)`
160
+ * receives the labels whose removal (or the re-read, names []) failed.
160
161
  */
161
- export async function clearPipelineLabels({ gh, repo, issue, labels = null }) {
162
+ export async function clearPipelineLabels({ gh, repo, issue, labels = null, onFail = null }) {
163
+ const removed = [], failed = [];
164
+ let names;
162
165
  try {
163
- const names = pipelineLabels(labels ?? JSON.parse(String(await gh(["issue", "view", String(issue), "-R", repo, "--json", "labels"])))?.labels);
164
- if (!names.length) return [];
165
- await gh(["issue", "edit", String(issue), "-R", repo, "--remove-label", names.join(",")]);
166
- return names;
167
- } catch { return []; }
166
+ names = pipelineLabels(labels ?? JSON.parse(String(await gh(["issue", "view", String(issue), "-R", repo, "--json", "labels"])))?.labels);
167
+ } catch (e) { try { onFail?.([], e); } catch { /* reporting is best effort */ } return []; }
168
+ let last = null;
169
+ for (const name of names) {
170
+ try { await gh(["issue", "edit", String(issue), "-R", repo, "--remove-label", name]); removed.push(name); } catch (e) { failed.push(name); last = e; }
171
+ }
172
+ if (failed.length) { try { onFail?.(failed, last); } catch { /* reporting is best effort */ } }
173
+ return removed;
168
174
  }
@@ -124,10 +124,27 @@ describe("#5592 gh helpers", () => {
124
124
  assert.deepEqual(pipelineLabels([{ name: "bug" }, "needs-human", { name: "parked:x" }]), ["needs-human", "parked:x"]);
125
125
  const log = [];
126
126
  assert.deepEqual(await clearPipelineLabels({ gh: ghWith([], log), repo: "o/r", issue: 7 }), ["parked:ci.red", "needs-human"]);
127
- assert.deepEqual(log.at(-1), ["issue", "edit", "7", "-R", "o/r", "--remove-label", "parked:ci.red,needs-human"]);
127
+ assert.deepEqual(log.slice(-2), [["issue", "edit", "7", "-R", "o/r", "--remove-label", "parked:ci.red"], ["issue", "edit", "7", "-R", "o/r", "--remove-label", "needs-human"]]);
128
128
  const log2 = [];
129
129
  assert.deepEqual(await clearPipelineLabels({ gh: ghWith([], log2), repo: "o/r", issue: 7, labels: [{ name: "bug" }] }), []);
130
130
  assert.equal(log2.length, 0, "nothing to remove: no gh call");
131
131
  assert.deepEqual(await clearPipelineLabels({ gh: async () => { throw new Error("boom"); }, repo: "o/r", issue: 7, labels: ["needs-human"] }), [], "best effort");
132
132
  });
133
+ it("clearPipelineLabels removes the rest when one removal fails and reports it", async () => {
134
+ const edits = [];
135
+ const gh = async (a) => { if (a[1] === "edit") { if (a.at(-1) === "remediation-queue") throw new Error("not found"); edits.push(a.at(-1)); } return ""; };
136
+ const reported = [];
137
+ const out = await clearPipelineLabels({ gh, repo: "o/r", issue: 7, labels: ["needs-human:external", "remediation-queue", "parked:x"], onFail: (n) => reported.push(...n) });
138
+ assert.deepEqual(out, ["needs-human:external", "parked:x"]);
139
+ assert.deepEqual(edits, ["needs-human:external", "parked:x"]);
140
+ assert.deepEqual(reported, ["remediation-queue"]);
141
+ });
142
+ it("clearPipelineLabels reports failed removals to the reporter", async () => {
143
+ const seen = [];
144
+ await clearPipelineLabels({ gh: async () => { throw new Error("boom"); }, repo: "o/r", issue: 7, labels: ["needs-human"], onFail: (n, e) => seen.push([n, e.message]) });
145
+ assert.deepEqual(seen, [[["needs-human"], "boom"]]);
146
+ const read = [];
147
+ await clearPipelineLabels({ gh: async () => { throw new Error("read"); }, repo: "o/r", issue: 7, onFail: (n) => read.push(n) });
148
+ assert.deepEqual(read, [[]]);
149
+ });
133
150
  });
@@ -91,7 +91,7 @@ export function equivalentRuns(frozen, sub) {
91
91
  return a.size > 0 && a.size === b.size && [...a].every(([id, ok]) => ok && b.get(id) === true);
92
92
  }
93
93
 
94
- const DRIFT_RE = /(?:generated|artifact|snapshot)s?\b[^\n]*\b(?:out of date|out-of-date|stale|differ|drift|not up to date)|\b(?:out of date|stale)\b[^\n]*\b(?:generated|regenerate)|run [`'"]?[^\n]*\bgenerate[\w:-]*[`'"]? to (?:update|regenerate)/i;
94
+ const DRIFT_RE = /(?:generated|artifact|snapshot)s?\b[^\n]*\b(?:out of date|out-of-date|stale|differ|drift|not up to date)|\b(?:out of date|stale)\b[^\n]*\b(?:generated|regenerate)|run [`'"]?[^\n]*\bgenerate[\w:-]*[`'"]? to (?:update|regenerate)|\bmissing or out[ -]of[ -]date\b|\brun [`'"]?[^\n)]*--(?:render|write|update)\b/i; // #5730: "missing or out of date (run --render-agent-md)"
95
95
  /** True when a validate failure's output reads as a stale generated artifact (a regenerate case), not a failing test. */
96
96
  export const isDriftFailure = (output) => DRIFT_RE.test(String(output ?? ""));
97
97
 
@@ -38,6 +38,9 @@ describe("#5653 validate catalogue", () => {
38
38
  it("classifies a stale generated artifact, not a test failure", () => {
39
39
  assert.equal(isDriftFailure("error: generated tools file is out of date"), true);
40
40
  assert.equal(isDriftFailure("AssertionError: 1 != 2"), false);
41
+ // 5730: the AlterLab #40841 line
42
+ assert.equal(isDriftFailure("listings/official/maps/agent.md: missing or out of date (run --render-agent-md --render-page)"), true);
43
+ assert.equal(isDriftFailure("AssertionError: expected 3, got 4"), false);
41
44
  });
42
45
  });
43
46
 
@@ -39,6 +39,11 @@ export function sparsePatterns(excludes) {
39
39
  return ["/*", ...excludes.map((p) => `!/${esc(p)}`)];
40
40
  }
41
41
 
42
+ /** forge#5890: a git spawn failure (missing cwd/binary, no exit status), as opposed to a git exit failure. */
43
+ export const isSpawnError = (e) => (e?.code === "ENOENT" || e?.code === "EACCES") && String(e?.syscall ?? "").startsWith("spawn") && typeof e?.status !== "number";
44
+ /** forge#5890: tag a spawn error with the typed deferral (sandbox.repo_missing, requeued); returns the same error. */
45
+ export const repoMissing = (e) => Object.assign(e, { deferCode: "sandbox.repo_missing", deferDetail: `lane repo directory is missing or git cannot run there (${e.code} ${e.syscall}); the lane is requeued`, retryInSeconds: 120 });
46
+
42
47
  /**
43
48
  * Add a lane worktree, sparse when the plan is non-empty. `git(args, {cwd})` is the injected io.git; `write(path, text)`
44
49
  * writes the pattern file (argv-safe for any number of patterns). `addArgs` is the plain `["worktree","add",...]` argv.
@@ -47,13 +52,13 @@ export function sparsePatterns(excludes) {
47
52
  export async function addLaneWorktree(git, write, { cwd, wt, addArgs, ref, maxBlobBytes = DEFAULT_SPARSE_MAX_KB * 1024 }) {
48
53
  let plan = { excludes: [], bytes: 0 };
49
54
  if (maxBlobBytes > 0 && typeof write === "function") {
50
- try { plan = sparsePlan(await git(["ls-tree", "-r", "-l", "-z", ref], { cwd }), { maxBlobBytes }); } catch { /* no plan: full checkout */ }
55
+ try { plan = sparsePlan(await git(["ls-tree", "-r", "-l", "-z", ref], { cwd }), { maxBlobBytes }); } catch (e) { if (isSpawnError(e)) throw repoMissing(e); /* no plan: full checkout */ }
51
56
  }
52
57
  if (!plan.excludes.length) {
53
- await git(addArgs, { cwd });
58
+ try { await git(addArgs, { cwd }); } catch (e) { throw isSpawnError(e) ? repoMissing(e) : e; }
54
59
  return { sparse: false, excluded: 0, bytes: 0 };
55
60
  }
56
- await git([...addArgs.slice(0, 2), "--no-checkout", ...addArgs.slice(2)], { cwd });
61
+ try { await git([...addArgs.slice(0, 2), "--no-checkout", ...addArgs.slice(2)], { cwd }); } catch (e) { throw isSpawnError(e) ? repoMissing(e) : e; }
57
62
  const g = (a) => git(a, { cwd: wt });
58
63
  try {
59
64
  await g(["sparse-checkout", "set", "--no-cone", "/*"]);
@@ -149,4 +149,22 @@ describe("sparse pattern file path on Windows (#5825)", () => {
149
149
  assert.equal(r.sparse, true);
150
150
  assert.deepEqual(wrote, ["C:/r/.git/worktrees/lean-5/info/sparse-checkout"]);
151
151
  });
152
+
153
+ // forge#5890
154
+ it("5890: a spawn ENOENT on ls-tree raises the typed sandbox.repo_missing error and never reaches worktree add", async () => {
155
+ const calls = [];
156
+ const fake = async (a) => { calls.push(a[0]); throw Object.assign(new Error("spawn git ENOENT"), { code: "ENOENT", syscall: "spawn git" }); };
157
+ await assert.rejects(addLaneWorktree(fake, async () => {}, { cwd: "/gone", wt: "/gone/wt", addArgs: ["worktree", "add", "/gone/wt", "main"], ref: "main" }),
158
+ (e) => e.deferCode === "sandbox.repo_missing" && e.retryInSeconds === 120 && !!e.deferDetail);
159
+ assert.deepEqual(calls, ["ls-tree"]);
160
+ });
161
+ it("5890: a non-spawn ls-tree failure still falls back to a full checkout; a spawn error from worktree add is typed", async () => {
162
+ const calls = [];
163
+ const fake = async (a) => { calls.push(a[0]); if (a[0] === "ls-tree") throw Object.assign(new Error("fatal"), { status: 128 }); return ""; };
164
+ const r = await addLaneWorktree(fake, async () => {}, { cwd: "/r", wt: "/r/wt", addArgs: ["worktree", "add", "/r/wt", "main"], ref: "main" });
165
+ assert.equal(r.sparse, false);
166
+ assert.deepEqual(calls, ["ls-tree", "worktree"]);
167
+ const bad = async () => { throw Object.assign(new Error("spawn git EACCES"), { code: "EACCES", syscall: "spawn git" }); };
168
+ await assert.rejects(addLaneWorktree(bad, null, { cwd: "/r", wt: "/r/wt", addArgs: ["worktree", "add", "/r/wt", "main"], ref: "main" }), (e) => e.deferCode === "sandbox.repo_missing");
169
+ });
152
170
  });