forgedock 1.66.0 → 1.68.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 (173) hide show
  1. package/bin/config-schema.mjs +3 -0
  2. package/bin/engine/outcome-codes.mjs +2 -0
  3. package/bin/engine-cli.mjs +193 -27
  4. package/bin/engine.mjs +10 -0
  5. package/bin/forgedock.mjs +24 -1
  6. package/bin/help-text.mjs +4 -3
  7. package/bin/introspect-schedule.mjs +98 -0
  8. package/bin/introspect-schedule.test.mjs +67 -0
  9. package/bin/lean/admission.mjs +21 -0
  10. package/bin/lean/admission.test.mjs +30 -0
  11. package/bin/lean/advisory.test.mjs +64 -0
  12. package/bin/lean/amendment-schema.mjs +30 -0
  13. package/bin/lean/attempts.mjs +162 -0
  14. package/bin/lean/attempts.test.mjs +141 -0
  15. package/bin/lean/basered.mjs +81 -0
  16. package/bin/lean/basered.test.mjs +68 -1
  17. package/bin/lean/batch-health.mjs +20 -12
  18. package/bin/lean/batch-health.test.mjs +55 -11
  19. package/bin/lean/batch.mjs +45 -0
  20. package/bin/lean/batch.test.mjs +105 -5
  21. package/bin/lean/capwait.mjs +14 -3
  22. package/bin/lean/capwait.test.mjs +20 -0
  23. package/bin/lean/ci-gate.mjs +2 -90
  24. package/bin/lean/ci-gate.test.mjs +1 -127
  25. package/bin/lean/ci-precheck.mjs +25 -8
  26. package/bin/lean/ci-precheck.test.mjs +24 -0
  27. package/bin/lean/clear-breaker.mjs +14 -0
  28. package/bin/lean/clear-breaker.test.mjs +4 -3
  29. package/bin/lean/commentstate.mjs +46 -0
  30. package/bin/lean/commentstate.test.mjs +43 -0
  31. package/bin/lean/concurrency.mjs +89 -0
  32. package/bin/lean/concurrency.test.mjs +113 -0
  33. package/bin/lean/conformance.e2e.test.mjs +13 -8
  34. package/bin/lean/conformance.mjs +73 -181
  35. package/bin/lean/conformance.test.mjs +61 -345
  36. package/bin/lean/depcache.mjs +100 -10
  37. package/bin/lean/depcache.test.mjs +105 -0
  38. package/bin/lean/docsgate.mjs +0 -32
  39. package/bin/lean/docsgate.test.mjs +2 -23
  40. package/bin/lean/effects-cap.test.mjs +9 -1
  41. package/bin/lean/effects-killtree.test.mjs +35 -0
  42. package/bin/lean/effects.mjs +42 -24
  43. package/bin/lean/efficiency.mjs +162 -0
  44. package/bin/lean/efficiency.test.mjs +79 -0
  45. package/bin/lean/engine-readmit.test.mjs +35 -0
  46. package/bin/lean/envgap.mjs +93 -0
  47. package/bin/lean/envgap.test.mjs +53 -0
  48. package/bin/lean/execution.mjs +41 -17
  49. package/bin/lean/execution.test.mjs +58 -0
  50. package/bin/lean/failure-census.mjs +170 -0
  51. package/bin/lean/failure-census.test.mjs +59 -0
  52. package/bin/lean/failure-stop.mjs +46 -0
  53. package/bin/lean/failure-stop.test.mjs +45 -0
  54. package/bin/lean/fixtures/capacity-storm.json +609 -0
  55. package/bin/lean/guardgate.test.mjs +2 -3
  56. package/bin/lean/heavy.mjs +33 -4
  57. package/bin/lean/heavy.test.mjs +38 -6
  58. package/bin/lean/hotarea.mjs +0 -36
  59. package/bin/lean/hotarea.test.mjs +1 -22
  60. package/bin/lean/issuewatch-verify.mjs +19 -4
  61. package/bin/lean/issuewatch.mjs +21 -4
  62. package/bin/lean/issuewatch.test.mjs +48 -1
  63. package/bin/lean/lane-audit-gap.mjs +66 -0
  64. package/bin/lean/lane-audit-gap.test.mjs +59 -0
  65. package/bin/lean/lane-audit-llm.mjs +5 -0
  66. package/bin/lean/lane-audit-query.mjs +47 -0
  67. package/bin/lean/lane-audit-query.test.mjs +44 -0
  68. package/bin/lean/lane-audit-signatures.mjs +33 -0
  69. package/bin/lean/lane-audit.mjs +110 -0
  70. package/bin/lean/lane-audit.test.mjs +97 -0
  71. package/bin/lean/lane-recovery.test.mjs +33 -0
  72. package/bin/lean/lanecheck.mjs +5 -3
  73. package/bin/lean/lanecheck.test.mjs +6 -0
  74. package/bin/lean/lean.mjs +311 -154
  75. package/bin/lean/lean.test.mjs +530 -223
  76. package/bin/lean/limits.mjs +17 -0
  77. package/bin/lean/limits.test.mjs +15 -1
  78. package/bin/lean/live-execution.mjs +21 -2
  79. package/bin/lean/live-execution.test.mjs +39 -0
  80. package/bin/lean/liveness.mjs +37 -0
  81. package/bin/lean/liveness.test.mjs +33 -0
  82. package/bin/lean/orchestrate-attempts.test.mjs +82 -0
  83. package/bin/lean/orchestrate-envhold.test.mjs +47 -0
  84. package/bin/lean/orchestrate-heldroot.test.mjs +72 -0
  85. package/bin/lean/orchestrate-hostfallback.test.mjs +59 -1
  86. package/bin/lean/orchestrate-overload-recovery.test.mjs +37 -0
  87. package/bin/lean/orchestrate-pause.test.mjs +76 -1
  88. package/bin/lean/orchestrate-reconcile.test.mjs +164 -0
  89. package/bin/lean/orchestrate-relaunch-gates.test.mjs +57 -0
  90. package/bin/lean/orchestrate-stacking.test.mjs +10 -0
  91. package/bin/lean/orchestrate.mjs +344 -45
  92. package/bin/lean/phaseledger.mjs +6 -0
  93. package/bin/lean/phaseledger.test.mjs +13 -1
  94. package/bin/lean/postdeploy-check.test.mjs +1 -3
  95. package/bin/lean/precheck.mjs +20 -0
  96. package/bin/lean/preflight.mjs +100 -11
  97. package/bin/lean/preflight.test.mjs +44 -4
  98. package/bin/lean/prompts.mjs +13 -28
  99. package/bin/lean/reconcile.mjs +90 -0
  100. package/bin/lean/recurrence.mjs +6 -112
  101. package/bin/lean/recurrence.test.mjs +11 -92
  102. package/bin/lean/release-flakes.mjs +14 -2
  103. package/bin/lean/release-flakes.test.mjs +17 -1
  104. package/bin/lean/release-ledger.mjs +19 -1
  105. package/bin/lean/release-ledger.test.mjs +23 -0
  106. package/bin/lean/release-preflight.mjs +28 -0
  107. package/bin/lean/release-preflight.test.mjs +42 -1
  108. package/bin/lean/release-review.mjs +40 -5
  109. package/bin/lean/release-review.test.mjs +43 -2
  110. package/bin/lean/release.mjs +43 -14
  111. package/bin/lean/release.test.mjs +32 -0
  112. package/bin/lean/retry.mjs +1 -1
  113. package/bin/lean/retry.test.mjs +6 -1
  114. package/bin/lean/rotator.mjs +9 -0
  115. package/bin/lean/rotator.test.mjs +11 -1
  116. package/bin/lean/sandbox-remote.mjs +49 -11
  117. package/bin/lean/sched.mjs +19 -0
  118. package/bin/lean/sched.test.mjs +11 -1
  119. package/bin/lean/schedd-health.mjs +4 -4
  120. package/bin/lean/schedd-health.test.mjs +8 -4
  121. package/bin/lean/schedd.mjs +45 -8
  122. package/bin/lean/schedd.test.mjs +120 -7
  123. package/bin/lean/selfreview.mjs +1 -1
  124. package/bin/lean/slo.mjs +126 -0
  125. package/bin/lean/slo.test.mjs +112 -0
  126. package/bin/lean/statuscomment.mjs +40 -0
  127. package/bin/lean/statuscomment.test.mjs +48 -1
  128. package/bin/lean/validate-catalog.mjs +108 -0
  129. package/bin/lean/validate-catalog.test.mjs +46 -1
  130. package/bin/lean/verify.mjs +3 -2
  131. package/bin/pool/affinity.test.mjs +91 -0
  132. package/bin/pool/agent.mjs +144 -10
  133. package/bin/pool/cache-sweep.mjs +31 -10
  134. package/bin/pool/ci-autoscale.mjs +160 -0
  135. package/bin/pool/cli.mjs +53 -9
  136. package/bin/pool/docker.mjs +3 -0
  137. package/bin/pool/engine-placement.test.mjs +94 -0
  138. package/bin/pool/lane-target.mjs +41 -0
  139. package/bin/pool/lane-tools.mjs +26 -0
  140. package/bin/pool/lane-tools.test.mjs +9 -0
  141. package/bin/pool/mirror-seed.mjs +15 -11
  142. package/bin/pool/router.mjs +88 -32
  143. package/bin/pool/version.mjs +29 -2
  144. package/bin/review-staging.mjs +11 -3
  145. package/bin/runner.mjs +59 -11
  146. package/bin/stats/attempts.mjs +54 -0
  147. package/bin/stats/attempts.test.mjs +30 -0
  148. package/bin/stats/churn.mjs +49 -0
  149. package/bin/stats/churn.test.mjs +31 -0
  150. package/bin/stats/index.mjs +11 -3
  151. package/bin/stats/release.mjs +7 -0
  152. package/bin/stats/release.test.mjs +20 -0
  153. package/bin/stats/scorecard.mjs +187 -0
  154. package/bin/stats/scorecard.test.mjs +89 -0
  155. package/commands/orchestrate.md +21 -18
  156. package/docs/CONFIG.md +41 -0
  157. package/docs/OUTCOME-CODES.md +2 -0
  158. package/docs/STATS.md +17 -0
  159. package/package.json +1 -1
  160. package/pool/image/Dockerfile +14 -2
  161. package/pool/image/manifest.json +25 -0
  162. package/pool/image/mirror.sh +11 -2
  163. package/pool/install/install-agent.ps1 +11 -4
  164. package/scripts/check-devdocs-freshness.sh +1 -1
  165. package/scripts/ci-local/adapters/github-actions.mjs +8 -0
  166. package/scripts/ci-local/cli.mjs +1 -1
  167. package/scripts/ci-local/plan.mjs +3 -2
  168. package/scripts/ci-local.test.sh +11 -0
  169. package/scripts/failure-census.mjs +67 -0
  170. package/scripts/review-finalize.sh +5 -5
  171. package/scripts/review-finalize.test.sh +8 -1
  172. package/scripts/verify-phase-trail.sh +11 -0
  173. package/scripts/verify-phase-trail.test.sh +9 -0
@@ -0,0 +1,162 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Batch efficiency ledger (#5987): a pure fold of a batch's `log.jsonl` rows, its state and the schedd's pool samples into a
5
+ * versioned `efficiency.json` (schema in devdocs/modules/lean.md). The failure/stall gates (batch-health.mjs) say a batch is broken;
6
+ * this says it is slow: achieved vs ceiling concurrency, idle slot-minutes by cause, attempts per merge, engine comments per
7
+ * issue, repeated failure signatures, operator interventions, phase p50/p90 vs a baseline, merged/hour, wasted lane-hours, $ per merge.
8
+ *
9
+ * Row fields read are the ones the orchestrator's `update(row)` writes to log.jsonl (all optional): `at`, `issue`, `outcome` (a terminal
10
+ * lane row; `merged` is a good end; `added`, `breaker`, `deferred` are engine/operator notes), `code`, `detail`, `minutes`, `cost_usd`,
11
+ * `phases:{id:{ms}}`. "Engine comments per issue" = the status updates (rows with a `detail`) the engine emitted for the issue.
12
+ * Operator interventions = `--add` rows, `run.interrupted` rows (schedd restart), FORGE:DECISION text in a `detail`, plus `operator`
13
+ * events the caller reads from the batch files (`requeue`, `hold-info`, `parallel`, see `operatorEvents`). Samples `{t, running, ceiling, ready, cause?}` are pushed by the daemon each pass and persisted in the file.
14
+ */
15
+ import { existsSync, readFileSync, statSync } from "node:fs";
16
+ import { join } from "node:path";
17
+ import { writeAtomic } from "./batch.mjs";
18
+
19
+ export const EFFICIENCY_FILE = "efficiency.json";
20
+ export const EFFICIENCY_VERSION = 1;
21
+ export const IDLE_CAUSES = ["capacity", "lease-held", "base.red", "hold", "breaker", "auth-pause", "no-ready"];
22
+ const MIN = 60_000, HOUR = 3_600_000, DAY = 86_400_000;
23
+ /** Rows that are progress notes, not the end of a run; never counted as a failed attempt. */
24
+ const NOTE_OUTCOME = new Set(["recovering", "added", "breaker", "planned", "plan-failed", "pool-offline", "host-overloaded", "sched", "integration", "drift", "budget"]);
25
+ const OPERATOR_ROW = (r) => r.outcome === "added" || r.code === "run.interrupted" || /FORGE:DECISION/.test(String(r.detail ?? ""));
26
+ const num = (v) => (Number.isFinite(Number(v)) && v !== null && v !== "" ? Number(v) : null);
27
+ const round = (v, d = 2) => (v === null || !Number.isFinite(v) ? null : Math.round(v * 10 ** d) / 10 ** d);
28
+ const atMs = (r) => { const t = Date.parse(r?.at ?? ""); return Number.isFinite(t) ? t : null; };
29
+
30
+ export function percentile(sorted, p) {
31
+ if (!sorted.length) return null;
32
+ return sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil(p * sorted.length) - 1))];
33
+ }
34
+
35
+ /** Phase durations (ms) by phase id over `rows`. */
36
+ export function phaseSpans(rows) {
37
+ const by = {};
38
+ for (const r of rows) for (const [id, v] of Object.entries(r?.phases ?? {})) { const ms = num(v?.ms); if (ms !== null && ms >= 0) (by[id] ??= []).push(ms); }
39
+ const out = {};
40
+ for (const [id, xs] of Object.entries(by)) { xs.sort((a, b) => a - b); out[id] = { n: xs.length, p50: percentile(xs, 0.5), p90: percentile(xs, 0.9) }; }
41
+ return out;
42
+ }
43
+
44
+ const runMinutes = (r) => num(r.minutes) ?? (Object.entries(r.phases ?? {}).reduce((s, [id, v]) => (id === "queue_wait" ? s : s + (num(v?.ms) ?? 0)), 0) / MIN);
45
+
46
+ /** Time-weighted `{achieved, ceiling, ratio}` over the samples since `since`; each sample holds until the next one (or `now`). */
47
+ export function concurrencyOver(samples, since, now) {
48
+ let dt = 0, run = 0, cap = 0;
49
+ samples.forEach((s, i) => {
50
+ const from = Math.max(s.t, since), to = Math.min(samples[i + 1]?.t ?? now, now);
51
+ if (to <= from) return;
52
+ dt += to - from; run += (num(s.running) ?? 0) * (to - from); cap += (num(s.ceiling) ?? 0) * (to - from);
53
+ });
54
+ return dt ? { achieved: round(run / dt), ceiling: round(cap / dt), ratio: cap ? round(run / cap, 3) : null } : { achieved: null, ceiling: null, ratio: null };
55
+ }
56
+
57
+ /**
58
+ * Compute the ledger. `prev`: the prior efficiency.json (carries samples and SLO filing state), `sample`: this pass's pool sample,
59
+ * `baseline`: `{phase: {p90}}` over the previous 14 days (default: this log's rows from the 14 days before the last 24 h), `concurrencyMin`: threshold used
60
+ * for `lowSinceMin`. Pure; never throws on malformed rows.
61
+ */
62
+ export function computeEfficiency({ rows = [], state = null, prev = null, sample = null, now = Date.now(), batchId = null, repo = null, operator = [], baseline = null, concurrencyMin = 0.6, windowMin = 15 } = {}) {
63
+ const list = (Array.isArray(rows) ? rows : []).filter((r) => r && typeof r === "object");
64
+ const samples = [...(Array.isArray(prev?.samples) ? prev.samples : []), ...(sample ? [{ ...sample, t: sample.t ?? now }] : [])]
65
+ .filter((s) => Number.isFinite(s?.t) && s.t > now - DAY).slice(-1500);
66
+ const day = list.filter((r) => (atMs(r) ?? now) > now - DAY);
67
+ const terminal = day.filter((r) => r.outcome && r.issue != null && !NOTE_OUTCOME.has(r.outcome));
68
+ const merged = new Set(terminal.filter((r) => r.outcome === "merged").map((r) => r.issue));
69
+ for (const [n, v] of Object.entries(state?.results ?? {})) if (v?.outcome === "merged") merged.add(Number(n));
70
+ const mergedNow = new Set([...merged].filter((n) => terminal.some((r) => r.issue === n && r.outcome === "merged")));
71
+
72
+ // concurrency and idle slot-minutes by cause (24 h)
73
+ const conc = concurrencyOver(samples, now - windowMin * MIN, now);
74
+ const ready = num(samples.at(-1)?.ready) ?? (Array.isArray(state?.pending) ? state.pending.length : 0);
75
+ let lowSince = null;
76
+ for (let i = samples.length - 1; i >= 0; i--) { const s = samples[i]; if (!(num(s.ready) > 0) || !(num(s.ceiling) > 0) || num(s.running) / num(s.ceiling) >= concurrencyMin) break; lowSince = s.t; }
77
+ const idle = {}; let slot = 0;
78
+ samples.forEach((s, i) => {
79
+ const to = Math.min(samples[i + 1]?.t ?? now, now), dt = (to - s.t) / MIN;
80
+ if (dt <= 0) return;
81
+ const cap = num(s.ceiling) ?? 0, run = num(s.running) ?? 0;
82
+ slot += cap * dt;
83
+ if (cap > run) { const c = s.cause ?? (num(s.ready) > 0 ? "capacity" : "no-ready"); idle[c] = (idle[c] ?? 0) + (cap - run) * dt; }
84
+ });
85
+ const idleByCause = Object.fromEntries(Object.entries(idle).map(([c, m]) => [c, round(m, 1)]));
86
+ const idleShare = Object.fromEntries(Object.entries(idle).map(([c, m]) => [c, slot ? round(m / slot, 3) : 0]));
87
+
88
+ // attempts, comments, signatures, interventions
89
+ const attempts = terminal.filter((r) => mergedNow.has(r.issue)).length;
90
+ const comments = {};
91
+ for (const r of day) if (r.issue != null) { if (typeof r.detail === "string" && r.detail) comments[r.issue] = (comments[r.issue] ?? 0) + 1; }
92
+ const sigs = {};
93
+ for (const r of terminal) if (r.outcome !== "merged") { const sig = String(r.signature ?? `${r.outcome}:${r.code ?? r.reason ?? r.error ?? ""}`).slice(0, 160); (sigs[sig] ??= new Set()).add(r.issue); (sigs[sig].n = (sigs[sig].n ?? 0) + 1); }
94
+ const repeats = Object.entries(sigs).map(([signature, s]) => ({ signature, count: s.n, issues: [...s].sort((a, b) => a - b) })).sort((a, b) => b.count - a.count);
95
+ const opAt = (e) => (typeof e?.at === "number" ? e.at : Date.parse(e?.at ?? ""));
96
+ const interventions = day.filter(OPERATOR_ROW).length + (Array.isArray(operator) ? operator : []).filter((e) => opAt(e) > now - DAY && opAt(e) <= now).length;
97
+ const capacityRefusals = list.filter((r) => (atMs(r) ?? 0) > now - HOUR && /capacity/.test(String(r.code ?? ""))).length;
98
+
99
+ // phases vs baseline
100
+ const cur = phaseSpans(day);
101
+ const base = baseline ?? Object.fromEntries(Object.entries(phaseSpans(list.filter((r) => { const t = atMs(r) ?? now; return t <= now - DAY && t > now - 15 * DAY; }))).map(([id, v]) => [id, { p90: v.p90 }]));
102
+ const phases = Object.fromEntries(Object.entries(cur).map(([id, v]) => [id, { ...v, baselineP90: base[id]?.p90 ?? null, ratio: base[id]?.p90 ? round(v.p90 / base[id].p90) : null }]));
103
+
104
+ // merged/hour, wasted lane-hours, $ per merge
105
+ const spanH = Math.max(1, Math.min(24, (now - Math.min(now, ...day.map((r) => atMs(r) ?? now))) / HOUR));
106
+ let wastedLater = 0, wastedNever = 0, usd = 0;
107
+ for (const r of terminal) {
108
+ usd += num(r.cost_usd) ?? 0;
109
+ if (r.outcome === "merged") continue;
110
+ (merged.has(r.issue) ? (wastedLater += runMinutes(r)) : (wastedNever += runMinutes(r)));
111
+ }
112
+ const running = state?.running && typeof state.running === "object" ? Object.keys(state.running).length : null;
113
+ return {
114
+ v: EFFICIENCY_VERSION, at: new Date(now).toISOString(), batch: batchId, repo,
115
+ concurrency: { ...conc, windowMin, running, ready, lowSinceMin: lowSince === null ? 0 : round((now - lowSince) / MIN, 1), min: concurrencyMin },
116
+ idle: { slotMinutes: round(slot, 1), byCause: idleByCause, share: idleShare },
117
+ limiters: Object.entries(idleByCause).sort((a, b) => b[1] - a[1]).slice(0, 3).map(([c]) => c),
118
+ attemptsPerMerged: mergedNow.size ? round(attempts / mergedNow.size) : null, merged: mergedNow.size,
119
+ commentsPerIssue: { max: Math.max(0, ...Object.values(comments)), issues: Object.entries(comments).sort((a, b) => b[1] - a[1]).slice(0, 5).map(([n, c]) => ({ issue: Number(n), comments: c })) },
120
+ repeats: repeats.slice(0, 10), interventionsPerDay: interventions, capacityRefusalsPerHour: capacityRefusals,
121
+ phases, mergedPerHour: round(mergedNow.size / spanH),
122
+ wastedLaneHours: { laterMerged: round(wastedLater / 60), neverMerged: round(wastedNever / 60) },
123
+ usdPerMerge: mergedNow.size ? round(usd / mergedNow.size) : null,
124
+ samples, slo: prev?.slo ?? { sigs: {} }, breaches: prev?.breaches ?? [],
125
+ };
126
+ }
127
+
128
+ /** Idle cause of the pool right now, from the batch's recent log rows (last 10 min); undefined when none applies (capacity/no-ready are inferred from `ready`). */
129
+ export function idleCause(rows, now = Date.now()) {
130
+ const recent = (Array.isArray(rows) ? rows : []).filter((r) => r && (atMs(r) ?? 0) > now - 10 * MIN).reverse();
131
+ const brk = recent.find((r) => r.outcome === "breaker");
132
+ if (brk && !/cleared/.test(String(brk.detail ?? ""))) return "breaker";
133
+ for (const r of recent) {
134
+ const d = String(r.detail ?? "");
135
+ if (/base\.red|base is red/.test(`${r.code ?? ""} ${d}`)) return "base.red";
136
+ if (r.outcome === "deferred" && /live lane in batch/.test(d)) return "lease-held";
137
+ if (/capacity/.test(String(r.code ?? ""))) return "capacity";
138
+ }
139
+ return undefined;
140
+ }
141
+
142
+ /** Operator actions recorded in a batch dir's files: `requeue` entries, `hold-info` (non-engine owners), the `parallel` file (`--set-parallel`). `[{at, kind}]`. */
143
+ export function operatorEvents(dir) {
144
+ const out = [], j = (n) => { try { return JSON.parse(readFileSync(join(dir, n), "utf8")); } catch { return null; } };
145
+ for (const e of Array.isArray(j("requeue")) ? j("requeue") : []) if (typeof e?.at === "string") out.push({ at: Date.parse(e.at), kind: "requeue" });
146
+ for (const e of Object.values(j("hold-info") ?? {})) if (e && e.owner !== "engine" && typeof e.since === "string") out.push({ at: Date.parse(e.since), kind: "hold" });
147
+ try { out.push({ at: statSync(join(dir, "parallel")).mtimeMs, kind: "set" }); } catch { /* none */ }
148
+ return out.filter((e) => Number.isFinite(e.at));
149
+ }
150
+
151
+ export const readEfficiency = (dir) => { try { const v = JSON.parse(readFileSync(join(dir, EFFICIENCY_FILE), "utf8")); return v && v.v === EFFICIENCY_VERSION ? v : null; } catch { return null; } };
152
+ export const writeEfficiency = (dir, eff) => writeAtomic(join(dir, EFFICIENCY_FILE), JSON.stringify(eff) + "\n", { private: true });
153
+ export const hasEfficiency = (dir) => existsSync(join(dir, EFFICIENCY_FILE));
154
+
155
+ /** The `forgedock status` line: `efficiency: 3/12 lanes (25%) - limiter a b; 2 SLO breaches -> FD#NNNN`. null with no ledger. */
156
+ export function efficiencyLine(eff) {
157
+ const c = eff?.concurrency;
158
+ if (!c || c.running == null && c.achieved == null) return null;
159
+ const run = c.running ?? Math.round(c.achieved), cap = Math.round(c.ceiling ?? 0), pct = cap ? Math.round((run / cap) * 100) : 0;
160
+ const n = (eff.breaches ?? []).length, issues = [...new Set((eff.breaches ?? []).map((b) => b.issue).filter(Boolean))];
161
+ return `efficiency: ${run}/${cap} lanes (${pct}%)${eff.limiters?.length ? ` - limiter ${eff.limiters.join(" ")}` : ""}${n ? `; ${n} SLO breach${n === 1 ? "" : "es"}${issues.length ? ` -> ${issues.map((i) => `FD#${i}`).join(" ")}` : ""}` : ""}`;
162
+ }
@@ -0,0 +1,79 @@
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 { computeEfficiency, efficiencyLine, concurrencyOver, idleCause, operatorEvents } from "./efficiency.mjs";
6
+ import { tmpDir } from "../tests/_tmp.mjs";
7
+ import { evaluateSlo, DEFAULT_SLO } from "./slo.mjs";
8
+
9
+ const NOW = Date.parse("2026-11-24T12:00:00Z"), MIN = 60000;
10
+ const iso = (agoMin) => new Date(NOW - agoMin * MIN).toISOString();
11
+ const row = (agoMin, r) => ({ at: iso(agoMin), ...r });
12
+ const samples = (n, running, ceiling, ready) => Array.from({ length: n }, (_, i) => ({ t: NOW - (n - i) * MIN, running, ceiling, ready }));
13
+
14
+ // 11-20..11-24 batches: 3 of 12 lanes busy, one failure signature retried, retries before the merges, operator churn.
15
+ export const slowRows = () => [
16
+ ...[1, 2, 3, 4].map((i) => row(300 - i, { issue: 7, outcome: "engine-error", code: "sandbox.capacity", minutes: 30, phases: { setup: { ms: 600000 } } })),
17
+ row(200, { issue: 7, outcome: "merged", minutes: 20, cost_usd: 4 }),
18
+ row(190, { issue: 8, outcome: "ci-failed", minutes: 10 }), row(180, { issue: 8, outcome: "merged", minutes: 10, cost_usd: 2 }),
19
+ row(110, { issue: null, outcome: "added", detail: "9" }), row(105, { issue: 9, outcome: "deferred", code: "run.interrupted", detail: "interrupted: upgrade; requeued" }),
20
+ ...Array.from({ length: 22 }, (_, i) => row(90 - i, { issue: 9, outcome: "recovering", detail: `recovering (ci), attempt ${i}/30` })),
21
+ ];
22
+ // operator actions the daemon reads from the batch files (requeue entries, hold-info, parallel file)
23
+ export const slowOperator = () => Array.from({ length: 5 }, (_, i) => ({ at: NOW - (100 - i) * MIN, kind: i % 2 ? "requeue" : "hold" }));
24
+ export const healthyRows = () => [row(60, { issue: 1, outcome: "merged", minutes: 20, cost_usd: 2 }), row(30, { issue: 2, outcome: "merged", minutes: 20, cost_usd: 2 })];
25
+
26
+ describe("#5987 efficiency ledger", () => {
27
+ it("time-weights concurrency over the window", () => {
28
+ const s = [{ t: NOW - 10 * MIN, running: 0, ceiling: 4 }, { t: NOW - 5 * MIN, running: 4, ceiling: 4 }];
29
+ assert.equal(concurrencyOver(s, NOW - 15 * MIN, NOW).ratio, 0.5);
30
+ });
31
+
32
+ it("slow batch: low concurrency, repeats, attempts, comments and interventions all breach", () => {
33
+ const eff = computeEfficiency({ rows: slowRows(), operator: slowOperator(), prev: { samples: samples(40, 3, 12, 5) }, now: NOW, batchId: "b1", repo: "o/r" });
34
+ assert.equal(eff.v, 1);
35
+ assert.equal(eff.concurrency.ratio, 0.25);
36
+ assert.ok(eff.concurrency.lowSinceMin >= 30);
37
+ assert.equal(eff.attemptsPerMerged, 3.5);
38
+ assert.equal(eff.interventionsPerDay, 7);
39
+ assert.equal(eff.repeats[0].count, 4);
40
+ assert.ok(eff.wastedLaneHours.laterMerged > 2);
41
+ assert.equal(eff.usdPerMerge, 3);
42
+ assert.equal(eff.limiters[0], "capacity");
43
+ const codes = evaluateSlo(eff, DEFAULT_SLO, { repo: "o/r" }).map((b) => b.code);
44
+ for (const c of ["concurrency", "repeat", "attempts", "interventions", "comments"]) assert.ok(codes.includes(c), `${c} in ${codes}`);
45
+ assert.match(efficiencyLine({ ...eff, concurrency: { ...eff.concurrency, running: 3 }, breaches: [{ issue: 12 }] }), /^efficiency: 3\/12 lanes \(25%\) - limiter capacity.*; 1 SLO breach -> FD#12$/);
46
+ });
47
+
48
+ it("healthy batch: no breaches", () => {
49
+ const eff = computeEfficiency({ rows: healthyRows(), prev: { samples: samples(40, 11, 12, 5) }, now: NOW, batchId: "b2", repo: "o/r" });
50
+ assert.deepEqual(evaluateSlo(eff, DEFAULT_SLO, { repo: "o/r" }), []);
51
+ assert.equal(eff.attemptsPerMerged, 1);
52
+ });
53
+
54
+ it("malformed rows and no samples never throw", () => {
55
+ const eff = computeEfficiency({ rows: [null, "x", { at: "bad" }, { issue: 1, outcome: "merged", phases: { a: { ms: "q" } } }], now: NOW });
56
+ assert.equal(eff.concurrency.ratio, null);
57
+ assert.equal(efficiencyLine(eff), null);
58
+ });
59
+
60
+ it("idleCause reads breaker, lease-held, capacity and base.red from real rows; cleared breaker and old rows give none", () => {
61
+ const r = (o, a = 1) => [row(a, o)];
62
+ assert.equal(idleCause(r({ issue: null, outcome: "breaker", detail: "tripped" }), NOW), "breaker");
63
+ assert.equal(idleCause(r({ issue: null, outcome: "breaker", detail: "circuit breaker cleared" }), NOW), undefined);
64
+ assert.equal(idleCause(r({ issue: 3, outcome: "deferred", detail: "#3 has a live lane in batch b2; retried in 30s" }), NOW), "lease-held");
65
+ assert.equal(idleCause(r({ issue: 3, outcome: "deferred", code: "sandbox.capacity" }), NOW), "capacity");
66
+ assert.equal(idleCause(r({ issue: 3, outcome: "needs-human", code: "base.red" }), NOW), "base.red");
67
+ assert.equal(idleCause(r({ issue: null, outcome: "breaker" }, 60), NOW), undefined);
68
+ });
69
+
70
+ it("operatorEvents reads requeue, hold-info and parallel files", async () => {
71
+ const { writeFileSync } = await import("node:fs"), { join } = await import("node:path");
72
+ const d = tmpDir("opev-");
73
+ writeFileSync(join(d, "requeue"), JSON.stringify([{ issue: 4, at: iso(5) }, { issue: "x" }]));
74
+ writeFileSync(join(d, "hold-info"), JSON.stringify({ 5: { owner: "operator", since: iso(4) }, 6: { owner: "engine", since: iso(3) } }));
75
+ writeFileSync(join(d, "parallel"), "4\n");
76
+ assert.deepEqual(operatorEvents(d).map((e) => e.kind).sort(), ["hold", "requeue", "set"]);
77
+ assert.deepEqual(operatorEvents(join(d, "none")), []);
78
+ });
79
+ });
@@ -0,0 +1,35 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // #6091: a lane held on env.engine_skew is re-admitted by the engine of the agent that will run it, not the orchestrator's.
4
+ import { describe, it } from "node:test";
5
+ import assert from "node:assert/strict";
6
+ import { orchestrate } from "./orchestrate.mjs";
7
+
8
+ const SKEW = { terminalReason: "needs-human", code: "recurrence.design_missing", detail: "gate fired", engineVersion: "1.66.0" };
9
+ const MERGED = { terminalReason: "merged", pr: 9 };
10
+ const run = ({ agentVersion, script }) => {
11
+ let t = 1_000_000, k = 0;
12
+ const calls = [];
13
+ return orchestrate({ issues: [1], parallel: 1, readBody: async () => "", now: () => t, pollMs: 1000, version: "1.67.0",
14
+ sleep: async (ms) => { t += Math.max(1, Number(ms) || 0); },
15
+ envHold: { version: () => "1.67.0", maxMs: 120_000, watchMs: 30_000, agentVersion: () => agentVersion(calls.length) },
16
+ runOne: async (n) => { calls.push(n); t += 1000; return script[Math.min(k++, script.length - 1)]; },
17
+ remote: { max: 2, isRemote: () => true, admit: () => ({ ok: true }), onBudget: "stop", costPerMinute: 0 } })
18
+ .then((rows) => ({ rows, calls }));
19
+ };
20
+
21
+ describe("#6091 engine-held re-admission follows the agent's engine", () => {
22
+ it("stays held while the only agent is still on the old engine", async () => {
23
+ const { rows, calls } = await run({ agentVersion: () => "1.66.0", script: [SKEW, MERGED] });
24
+ assert.equal(calls.length, 1, "not relaunched onto the old agent");
25
+ assert.equal(rows[0].outcome, "held");
26
+ assert.equal(rows[0].code, "env.engine_skew");
27
+ assert.equal(rows[0].engineVersion, "1.66.0", "the engine that ran stays on the row");
28
+ });
29
+
30
+ it("is re-admitted once the agent upgrades to the needed engine", async () => {
31
+ const { rows, calls } = await run({ agentVersion: (n) => (n >= 1 ? "1.67.1" : "1.66.0"), script: [SKEW, MERGED] });
32
+ assert.deepEqual(calls, [1, 1]);
33
+ assert.equal(rows[0].outcome, "merged");
34
+ });
35
+ });
@@ -0,0 +1,93 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: BUSL-1.1
3
+ // #6106: deterministic classification of environment gaps. A missing tool, binary, interpreter, recipe, package or sandbox
4
+ // capability is an `env.*` outcome that recovers on its own, never ci.red or a human block. Genuine human reasons stay human.
5
+ import { OUTCOME_CODES } from "../engine/outcome-codes.mjs";
6
+
7
+ /** A check command's output that says the tool (not the change) is what failed. */
8
+ export const CHECK_TOOL_GAP_RE = /PATH pass-through wrapper with no real binary|command not found|(?:^|\n)\s*(?:\S+:\s*)?(?:sh|bash|zsh): (?:\d+: )?\S+: not found|not found in PATH|: No such file or directory[^\n]*node_modules\/\.bin|\bENOENT\b[^\n]{0,60}spawn|no module named|ModuleNotFoundError|cannot connect to the docker daemon|no docker daemon/i;
9
+
10
+ /** Words that make a block a real human decision, whatever else it says. */
11
+ const HUMAN_SIGNAL_RE = /\bapprov|sign[- ]?off|\bspend\b|\bbudget\b|purchase|\bpayment|\bcustomer|\blegal\b|\bsecrets?\b|password|passphrase|api[- ]?key|\btoken\b|\bcredentials?\b|\bpricing\b|owner (?:decision|call)|which (?:option|approach|product)/i;
12
+
13
+ const SANDBOX_CAP_RE = /\bsandbox\b[^.\n]{0,80}\b(?:lacks?|missing|has no|without|cannot|can't|does not have|doesn't have|no access)\b|\b(?:lacks?|missing|no|without)\b[^.\n]{0,40}\bsandbox (?:capabilit|access|network|docker|gpu)/i;
14
+ const TOOL_GAP_BLOCK_RE = [
15
+ /\b(?:no|missing|lacks?|without|not (?:installed|available|found)|only)\b[^.\n]{0,60}\b(?:interpreter|python\s?3\.\d+|python\s?\d|node(?:\.js)?\s?\d+|binary|binaries|toolchain|runtime|docker|compiler|executable)\b/i,
16
+ /\b(?:interpreter|binary|executable|toolchain)\b[^.\n]{0,60}\b(?:not (?:installed|available|found)|missing|absent|only)\b/i,
17
+ /\blane[-_ ]?tools?\b|\brecipes?\b/i,
18
+ /\b(?:package|module|library|dependency|dependencies)\b[^.\n]{0,60}\b(?:not installed|missing|not found|cannot be installed|unavailable)\b/i,
19
+ /\b(?:not installed|command not found|no module named|ModuleNotFoundError)\b/i,
20
+ ];
21
+
22
+ /**
23
+ * The env code for a builder block whose declared reason is a human one, or null to keep it human.
24
+ * @param {string} why the block's typed reason ("product-decision", "credentials", ...)
25
+ * @param {string} text the builder's summary/reason
26
+ * @returns {string|null} OUTCOME_CODES.ENV_TOOL_MISSING | ENV_CAPABILITY_REMOTE | null
27
+ */
28
+ export function envGapBlockCode(why, text) {
29
+ if (!["product-decision", "credentials"].includes(String(why))) return null;
30
+ const s = String(text ?? "");
31
+ if (!s || HUMAN_SIGNAL_RE.test(s)) return null;
32
+ if (SANDBOX_CAP_RE.test(s)) return OUTCOME_CODES.ENV_CAPABILITY_REMOTE;
33
+ if (TOOL_GAP_BLOCK_RE.some((re) => re.test(s))) return OUTCOME_CODES.ENV_TOOL_MISSING;
34
+ return null;
35
+ }
36
+
37
+ /** The failed check results (`{command, rc, output}`) whose output names a missing tool. */
38
+ export function toolGapFailures(failed = []) {
39
+ return failed.filter((f) => CHECK_TOOL_GAP_RE.test(String(f?.output ?? "")));
40
+ }
41
+
42
+ /**
43
+ * Package directories a check command line works in (`cd web && ...`, `--prefix web`, `-C web`, `--cwd web`, `web/node_modules/.bin/x`)
44
+ * that carry a package.json but no installed node_modules: dependencies to prepare before the checks run.
45
+ * @param {string[]} commands
46
+ * @param {(rel: string) => boolean} exists path relative to the worktree
47
+ */
48
+ export function packageDirsMissingDeps(commands = [], exists = () => false) {
49
+ const dirs = new Set();
50
+ const add = (d) => {
51
+ const dir = String(d ?? "").replace(/^\.\//, "").replace(/\/+$/, "");
52
+ if (!dir || dir.startsWith("/") || dir.split("/").includes("..") || /[$`*]/.test(dir)) return;
53
+ dirs.add(dir);
54
+ };
55
+ for (const c of commands) {
56
+ const s = String(c ?? "");
57
+ for (const m of s.matchAll(/(?:^|[\s;&|(])cd\s+([^\s;&|)]+)/g)) add(m[1]);
58
+ for (const m of s.matchAll(/(?:--prefix|--cwd|-C|--dir)[ =]([^\s;&|)]+)/g)) add(m[1]);
59
+ for (const m of s.matchAll(/(?:^|[\s"'])((?:\.\/)?[\w.-]+(?:\/[\w.-]+)*?)\/node_modules\/\.bin\//g)) add(m[1]);
60
+ }
61
+ return [...dirs].filter((d) => exists(`${d}/package.json`) && !exists(`${d}/node_modules`));
62
+ }
63
+
64
+ // #6094: test-file names in check output. A linear token scan (split on non-path characters, then an anchored test of each
65
+ // basename): the earlier single regex nested quantifiers over overlapping classes and backtracked exponentially on long
66
+ // path-like output, which froze the lane (and the test suite) in a microtask-free spin.
67
+ const TEST_BASENAME_RES = [/^[\w@.-]+\.(?:test|spec)\.[cm]?[jt]sx?$/, /^(?:test_[\w-]+|[\w-]+_test)\.(?:py|go|rb|rs)$/, /^[\w-]+Tests?\.(?:java|kt|cs)$/];
68
+ const MAX_SCAN_CHARS = 512 * 1024, MAX_TOKEN_CHARS = 400;
69
+ function testFilesNamed(output) {
70
+ const text = String(output ?? "");
71
+ const out = new Set();
72
+ for (const raw of (text.length > MAX_SCAN_CHARS ? text.slice(-MAX_SCAN_CHARS) : text).split(/[^\w@./-]+/)) {
73
+ if (!raw || raw.length > MAX_TOKEN_CHARS) continue;
74
+ const tok = raw.replace(/^[./]+(?=[\w@])/, "").replace(/[.]+$/, "");
75
+ const slash = tok.lastIndexOf("/");
76
+ const base = slash < 0 ? tok : tok.slice(slash + 1);
77
+ if (base && TEST_BASENAME_RES.some((re) => re.test(base))) out.add(tok);
78
+ }
79
+ return [...out];
80
+ }
81
+
82
+ /**
83
+ * #6094: a failing check whose output names test files and none of them is in the diff is not caused by the change: the lane
84
+ * reruns it once before treating it as red. Returns false when the output names no test file (cannot tell: not unrelated).
85
+ * @param {string} output
86
+ * @param {string[]} changed files the lane's diff touches
87
+ */
88
+ export function failureOutsideDiff(output, changed = []) {
89
+ const named = testFilesNamed(output);
90
+ if (!named.length) return false;
91
+ const touched = (p) => changed.some((c) => c === p || c.endsWith(`/${p}`) || p.endsWith(`/${c}`) || c.split("/").pop() === p.split("/").pop());
92
+ return !named.some(touched);
93
+ }
@@ -0,0 +1,53 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: BUSL-1.1
3
+ import { describe, it } from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import { envGapBlockCode, toolGapFailures, packageDirsMissingDeps, failureOutsideDiff } from "./envgap.mjs";
6
+
7
+ describe("#6106 env gap classification", () => {
8
+ it("a check that fails on a PATH pass-through wrapper with no real binary is a tool gap", () => {
9
+ const out = "forgedock heavy: eslint at /w/web/node_modules/.bin/eslint is a PATH pass-through wrapper with no real binary behind it";
10
+ assert.equal(toolGapFailures([{ command: "cd web && eslint .", rc: 127, output: out }, { command: "node --test", rc: 1, output: "not ok 1 - assertion" }]).length, 1);
11
+ assert.equal(toolGapFailures([{ command: "x", rc: 1, output: "AssertionError: expected 1 to equal 2" }]).length, 0);
12
+ });
13
+ it("block reasons naming a missing tool/interpreter/recipe/sandbox capability map to env codes", () => {
14
+ assert.equal(envGapBlockCode("product-decision", "the yaml lane-tools recipe lives in the engine"), "env.tool_missing");
15
+ assert.equal(envGapBlockCode("credentials", "no Python 3.11 interpreter (only 3.12.3)"), "env.tool_missing");
16
+ assert.equal(envGapBlockCode("credentials", "the sandbox lacks network access to the registry"), "env.capability_remote");
17
+ });
18
+ it("genuine human reasons stay human", () => {
19
+ assert.equal(envGapBlockCode("product-decision", "needs Stripe approval"), null);
20
+ assert.equal(envGapBlockCode("credentials", "no docker credentials: need the registry token"), null);
21
+ assert.equal(envGapBlockCode("product-decision", "which option should the product take?"), null);
22
+ assert.equal(envGapBlockCode("approval", "no interpreter"), null);
23
+ });
24
+ it("package dirs the checks touch that have a manifest but no node_modules are found", () => {
25
+ const have = new Set(["web/package.json", "api/package.json", "api/node_modules"]);
26
+ const exists = (p) => have.has(p);
27
+ assert.deepEqual(packageDirsMissingDeps(["cd web && npx eslint .", "cd api && npm test", "node --test"], exists), ["web"]);
28
+ assert.deepEqual(packageDirsMissingDeps(["npm --prefix web run lint"], exists), ["web"]);
29
+ assert.deepEqual(packageDirsMissingDeps(["web/node_modules/.bin/eslint src"], exists), ["web"]);
30
+ assert.deepEqual(packageDirsMissingDeps(["cd ../x && ls"], () => true), []);
31
+ });
32
+ });
33
+
34
+ describe("#6094 failures outside the diff", () => {
35
+ it("names a test file the diff does not touch -> outside; touched or unnamed -> not", () => {
36
+ const out = "not ok 5 - ten concurrent\n location: '/w/bin/tests/mirror-script.test.mjs:48:3'";
37
+ assert.equal(failureOutsideDiff(out, ["bin/lean/release.mjs"]), true);
38
+ assert.equal(failureOutsideDiff(out, ["bin/tests/mirror-script.test.mjs"]), false);
39
+ assert.equal(failureOutsideDiff("make: *** [lint] Error 1", ["a.js"]), false);
40
+ assert.equal(failureOutsideDiff("FAILED tests/test_api.py::t - x", ["web/app.ts"]), true);
41
+ });
42
+ it("scans long path-like output in linear time (the old regex backtracked exponentially and froze the lane)", () => {
43
+ const evil = `${"a/".repeat(20000)}b ${"x.".repeat(20000)}y ${"@-".repeat(20000)}`;
44
+ const t0 = Date.now();
45
+ assert.equal(failureOutsideDiff(evil, ["a.js"]), false);
46
+ assert.equal(failureOutsideDiff(`${evil}\n at /w/src/deep/app.spec.ts:3:1`, ["a.js"]), true);
47
+ assert.ok(Date.now() - t0 < 2000, `took ${Date.now() - t0} ms`);
48
+ });
49
+ it("names Go/Java/py test files and strips ./ prefixes", () => {
50
+ assert.equal(failureOutsideDiff("--- FAIL: TestX (0.00s)\n ./pkg/foo_test.go:12: boom", ["pkg/foo_test.go"]), false);
51
+ assert.equal(failureOutsideDiff("at src/com/x/FooTest.java:9", ["src/Bar.java"]), true);
52
+ });
53
+ });
@@ -70,6 +70,7 @@ import { classifyStep, heavyConfig, memAvailableMb } from "./heavy.mjs";
70
70
  import { detectPins } from "./toolchain.mjs";
71
71
  import { parseContractComment, noComments } from "./render.mjs";
72
72
  import { parseRelayCommands } from "./relay.mjs";
73
+ import { classifyTransportLoss, AGENT_UP_WINDOW_MS } from "./liveness.mjs";
73
74
  import { detectUsageLimit, parseSessionLimitResetEpochMs } from "../runner.mjs";
74
75
 
75
76
  export const EXECUTION_MODES = Object.freeze(["local", "remote", "hybrid"]);
@@ -141,6 +142,7 @@ export function parseExecution(sec = {}) {
141
142
  onBudget: str(s.on_budget) === "local" ? "local" : "stop", costPerMinute: cpm ?? 0 };
142
143
  const capList = (v) => (Array.isArray(v) ? v : str(v) ? str(v).split(",") : []).map((x) => str(x).toLowerCase()).filter((x) => CAPABILITY_RE.test(x));
143
144
  const hostCapabilities = [...new Set(capList(s.host_capabilities))];
145
+ const offloadWrappers = [...new Set(capList(s.offload_wrappers))]; // unclog: host commands that only send work elsewhere (e.g. a remote-run wrapper); a sandbox runs their argument directly
144
146
  const patRaw = Array.isArray(s.host_capability_patterns) ? s.host_capability_patterns : str(s.host_capability_patterns) ? str(s.host_capability_patterns).split(",") : [];
145
147
  const hostCapabilityPatterns = patRaw.map((x) => { const t = str(x), i = t.indexOf(":"); return { name: t.slice(0, i).trim().toLowerCase(), pattern: t.slice(i + 1).trim() }; })
146
148
  .filter((x) => CAPABILITY_RE.test(x.name) && x.pattern && safeRegExp(x.pattern));
@@ -161,7 +163,7 @@ export function parseExecution(sec = {}) {
161
163
  const plan = ["free", "pro", "team", "enterprise"].includes(str(s.plan).toLowerCase()) ? str(s.plan).toLowerCase() : null;
162
164
  const publicDefault = str(s.public_default).toLowerCase() === "actions" ? "actions" : null; // #5900: opt-in only
163
165
  const dispatcher = /^[A-Za-z0-9][A-Za-z0-9-]*(\[bot\])?$/.test(str(s.dispatcher)) ? str(s.dispatcher) : null;
164
- return { mode, maxRemote, provider, image, secrets, budget, ...(jobLimit ? { jobLimit } : {}), ...(ciReserve !== null ? { ciReserve } : {}), ...(plan ? { plan } : {}), ...(publicDefault ? { publicDefault } : {}), ...(dispatcher ? { dispatcher } : {}), ...(hostFallback !== null ? { hostFallback } : {}), ...(hostCapabilities.length ? { hostCapabilities } : {}), ...(hostCapabilityPatterns.length ? { hostCapabilityPatterns } : {}), ...(endpoint ? { endpoint } : {}), ...(tokenEnv ? { tokenEnv } : {}), ...(tokenFile ? { tokenFile } : {}), ...(cacheStore ? { cacheStore } : {}), ...(allowActions ? { allowActions } : {}), ...(fallbackLocal ? { fallbackLocal } : {}), ...(capacityFallbackAfter !== null ? { capacityFallbackAfter } : {}), ...(heavy !== null ? { heavy } : {}), ...(unreachableWindowMin !== null ? { unreachableWindowMin } : {}), ...(Object.keys(relay).length ? { relay } : {}), ...(warmSandboxes ? { warmSandboxes } : {}), ...(repoSource ? { repoSource } : {}), ...(accountRotator ? { accountRotator } : {}), ...(lt.tools.length ? { laneTools: lt.tools } : {}), ...(lt.errors.length ? { laneToolsErrors: lt.errors } : {}) };
166
+ return { mode, maxRemote, provider, image, secrets, budget, ...(jobLimit ? { jobLimit } : {}), ...(ciReserve !== null ? { ciReserve } : {}), ...(plan ? { plan } : {}), ...(publicDefault ? { publicDefault } : {}), ...(dispatcher ? { dispatcher } : {}), ...(hostFallback !== null ? { hostFallback } : {}), ...(hostCapabilities.length ? { hostCapabilities } : {}), ...(offloadWrappers.length ? { offloadWrappers } : {}), ...(hostCapabilityPatterns.length ? { hostCapabilityPatterns } : {}), ...(endpoint ? { endpoint } : {}), ...(tokenEnv ? { tokenEnv } : {}), ...(tokenFile ? { tokenFile } : {}), ...(cacheStore ? { cacheStore } : {}), ...(allowActions ? { allowActions } : {}), ...(fallbackLocal ? { fallbackLocal } : {}), ...(capacityFallbackAfter !== null ? { capacityFallbackAfter } : {}), ...(heavy !== null ? { heavy } : {}), ...(unreachableWindowMin !== null ? { unreachableWindowMin } : {}), ...(Object.keys(relay).length ? { relay } : {}), ...(warmSandboxes ? { warmSandboxes } : {}), ...(repoSource ? { repoSource } : {}), ...(accountRotator ? { accountRotator } : {}), ...(lt.tools.length ? { laneTools: lt.tools } : {}), ...(lt.errors.length ? { laneToolsErrors: lt.errors } : {}) };
165
167
  }
166
168
 
167
169
  const round1 = (x) => Math.round(x * 10) / 10;
@@ -178,7 +180,7 @@ const KEEP_DAYS = 7;
178
180
 
179
181
  /**
180
182
  * The execution budget (#4255). `record(key, {minutes, cost_usd})` adds one lane attempt to today's host total; the key
181
- * (`<batch>#<sandbox id>#<startedAt>`) makes a repeated record a no-op. `admit({minutes, cost_usd, running})` gets the
183
+ * (`<batch>#<sandbox id>`) holds one entry per sandbox with its latest cumulative usage (#5987); an identical repeat is a no-op. `admit({minutes, cost_usd, running})` gets the
182
184
  * batch's settled + running usage (`running` the running part alone) and refuses once a batch cap, or a day cap with
183
185
  * today's host total plus this batch's running usage, is reached. A corrupt or unreadable day file refuses while a day
184
186
  * cap is set (a hard cap fails closed) and is ignored otherwise; it is never overwritten.
@@ -207,8 +209,10 @@ export function openExecutionBudget({ budget = {}, file = executionBudgetFile(),
207
209
  const r = read();
208
210
  if (!r.ok) return false;
209
211
  const d = utcDay(now()), today = { ...(r.days[d] ?? {}) };
210
- if (today[key]) return false;
211
- today[key] = { minutes: nonNeg(u?.minutes) ?? 0, cost_usd: nonNeg(u?.cost_usd) ?? 0, at: now() };
212
+ const min = nonNeg(u?.minutes) ?? 0, usd = nonNeg(u?.cost_usd) ?? 0;
213
+ // #5991: one row per key; a replay of the same sandbox keeps the larger usage instead of adding a row
214
+ if (today[key] && !(min > (nonNeg(today[key].minutes) ?? 0) || usd > (nonNeg(today[key].cost_usd) ?? 0))) return false;
215
+ today[key] = { minutes: Math.max(min, nonNeg(today[key]?.minutes) ?? 0), cost_usd: Math.max(usd, nonNeg(today[key]?.cost_usd) ?? 0), at: now() };
212
216
  const days = { [d]: today };
213
217
  for (const [k, v] of Object.entries(r.days)) if (k !== d && Date.parse(k) > now() - KEEP_DAYS * 86400000) days[k] = v;
214
218
  writeAtomic(file, JSON.stringify({ v: 1, days }, null, 2) + "\n");
@@ -293,11 +297,14 @@ export function detectNeeds(text, exec = null, { prose = false } = {}) {
293
297
 
294
298
  /**
295
299
  * #5652: may a remote lane that lacks a tool or host capability be re-placed on the dispatching host? An explicit
296
- * `execution.host_fallback` wins; else off when forge.yaml `host.role` is `orchestrator`; else on (existing repos unchanged).
300
+ * `execution.host_fallback` wins; else off when forge.yaml `host.role` is `orchestrator`; else off in `mode: remote` (#5746);
301
+ * else on (hybrid and local unchanged).
297
302
  */
298
- export function hostFallbackAllowed({ hostFallback = null, hostRole = null } = {}) {
303
+ export function hostFallbackAllowed({ hostFallback = null, hostRole = null, mode = null } = {}) {
299
304
  if (typeof hostFallback === "boolean") return hostFallback;
300
- return String(hostRole ?? "").trim().toLowerCase() !== "orchestrator";
305
+ if (String(hostRole ?? "").trim().toLowerCase() === "orchestrator") return false;
306
+ // #5746: in remote mode the host is not a fallback unless the repo opts in with host_fallback: true
307
+ return mode !== "remote";
301
308
  }
302
309
 
303
310
  /** Declared host capabilities a remote lane's block summary names (#4542); empty when it names none the host has. */
@@ -400,7 +407,10 @@ export function placeLane({ exec = null, verifyMode = "local", labels = [], weig
400
407
  const missing = (Array.isArray(needs) ? needs : []).map(String).filter((n) => n && !(Array.isArray(relays) ? relays : []).includes(n));
401
408
  if (missing.length) return { where: "local", reason: `host capability: ${missing.join(", ")}` };
402
409
  }
403
- if (mode !== "hybrid") { const where = placement(exec); return { where, reason: `mode ${EXECUTION_MODES.includes(mode) ? mode : "local"}` }; }
410
+ if (mode !== "hybrid") {
411
+ const where = placement(exec);
412
+ return { where, reason: `mode ${EXECUTION_MODES.includes(mode) ? mode : "local"}` };
413
+ }
404
414
  if (!(Number.isInteger(exec.maxRemote) && exec.maxRemote >= 1)) return { where: "local", reason: "max_remote 0" };
405
415
  if (verifyMode === "ci") return { where: "local", reason: "verify.mode ci: validation runs on CI, not billed twice" };
406
416
  const names = (Array.isArray(labels) ? labels : []).map((l) => String(l ?? "").trim().toLowerCase());
@@ -699,7 +709,15 @@ const HALTED = { terminalReason: "deferred", detail: "batch halted (schedd hando
699
709
  * (`backendId`; the sandbox's own id kept as `laneBackendId`), so orchestrate can place lanes away from a limited pool.
700
710
  */
701
711
  export function providerLanes({ provider, laneArgs, ledgerFor, env = process.env, secrets = [], pollMs = 5000, sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
702
- costPerMinute = 0, now = () => Date.now(), unreachableWindowMs = 300000, logTail = null, holdId = null }) {
712
+ costPerMinute = 0, now = () => Date.now(), unreachableWindowMs = 300000, logTail = null, holdId = null, agentOnline = null, suspendKept = null, resumeKept = null, phaseOf = null }) {
713
+ // #6008: a sandbox kept for adopt keeps running with no dispatcher: record it (issue, since, phase) and tell it to suspend (the lane refuses push/merge until adopted)
714
+ const keepNote = (r, n, h) => {
715
+ if (!Number.isInteger(n)) return r;
716
+ let phase = null; try { phase = phaseOf?.(n) ?? null; } catch { phase = null; }
717
+ const kept = { issue: n, since: now(), phase, ...(h?.id ? { id: h.id } : {}) };
718
+ try { Promise.resolve(suspendKept?.(n, kept)).catch(() => {}); } catch { /* best effort */ }
719
+ return { ...r, kept };
720
+ };
703
721
  const cpm = nonNeg(Number(costPerMinute)) ?? 0;
704
722
  // #4255: the sandbox's usage: the provider's `usage()`, else the billable minutes it put on the handle (#4254), else wall
705
723
  // clock since the handle's startedAt; cost is the provider's, else minutes x cost_per_minute.
@@ -734,22 +752,27 @@ export function providerLanes({ provider, laneArgs, ledgerFor, env = process.env
734
752
  try { const v = await fn(); st.waited = 0; st.tries = 0; return v; } catch (e) {
735
753
  if (!isTransportError(e)) throw e;
736
754
  // release review BUG-6: a 401 that outlasts the window is an auth failure (capped sandbox.auth), not an uncapped unreachable pool
737
- if (st.waited >= unreachableWindowMs) throw Object.assign(new Error(`unreachable for ${Math.round(st.waited / 1000)}s: ${errText(e)}`), { unreachable: true, ...(e?.status === 401 ? { auth: true, hop: e.hop } : {}) });
738
- const d = Math.min(pollMs * 2 ** Math.min(st.tries++, 10), 30000, Math.max(1, unreachableWindowMs - st.waited));
755
+ // #5991: once the wait reaches the agent-up window, ask the pool agent; an answering agent means this sandbox is gone
756
+ let up = null;
757
+ if (typeof agentOnline === "function" && st.waited >= AGENT_UP_WINDOW_MS && st.waited < unreachableWindowMs) { try { up = (await agentOnline(st.h)) === true; } catch { up = false; } }
758
+ if (classifyTransportLoss({ agentOnline: up, waitedMs: st.waited, windowMs: unreachableWindowMs }) === "unreachable") throw Object.assign(new Error(`unreachable for ${Math.round(st.waited / 1000)}s: ${errText(e)}`), { unreachable: true, ...(e?.status === 401 ? { auth: true, hop: e.hop } : {}) });
759
+ const d = Math.min(pollMs * 2 ** Math.min(st.tries++, 10), 30000, Math.max(1, unreachableWindowMs - st.waited),
760
+ typeof agentOnline === "function" && st.waited < AGENT_UP_WINDOW_MS ? AGENT_UP_WINDOW_MS - st.waited : Infinity); // land on the probe point
739
761
  st.waited += d;
740
762
  await sleep(d);
741
763
  }
742
764
  }
743
765
  };
744
- const unreachable = (h, e) => (e?.auth
766
+ const unreachable0 = (h, e) => (e?.auth
745
767
  ? { terminalReason: "deferred", code: OUTCOME_CODES.SANDBOX_AUTH, retryInSeconds: 300, detail: `sandbox ${h.id} kept answering 401 (${e.hop === "agent" ? "the pool agent refused the router" : "check the pool token"}): ${errText(e)}; kept for adopt on resume` }
746
768
  : { terminalReason: "deferred", code: OUTCOME_CODES.SANDBOX_UNREACHABLE, retryInSeconds: 60,
747
769
  detail: `sandbox ${h.id} ${errText(e)}; kept for adopt on resume` });
770
+ const unreachable = (h, e) => keepNote(unreachable0(h, e), h?.issue, h);
748
771
  const tailOf = async (h) => { try { return typeof logTail === "function" ? String(await logTail(h) ?? "") : ""; } catch { return ""; } };
749
772
  const settleClone = (r, id) => (r?.terminalReason === "engine-error" && r.code === undefined && isEgressTimeout(r.detail) ? egressDeferred(id, errLine(r.detail))
750
773
  : r?.terminalReason === "engine-error" && r.code === undefined && isCloneFailure(r.detail) ? cloneDeferred(id, errLine(r.detail)) : r);
751
774
  // #5669: a halted batch (schedd handover) stops polling; the sandbox is neither torn down nor released, so the next daemon adopts it.
752
- const wait = async (h, g = guard({ waited: 0, tries: 0 }), sig = null) => {
775
+ const wait = async (h, g = guard({ waited: 0, tries: 0, h }), sig = null) => {
753
776
  for (;;) {
754
777
  if (sig?.aborted) return null;
755
778
  const r = await g(() => provider.fetchResult(h));
@@ -779,7 +802,7 @@ export function providerLanes({ provider, laneArgs, ledgerFor, env = process.env
779
802
  const startFailed = (id, e) => ([401, 403].includes(e?.status)
780
803
  ? { terminalReason: "deferred", code: OUTCOME_CODES.SANDBOX_AUTH, retryInSeconds: 300, detail: `sandbox ${id} could not start (auth): ${errText(e)}; ${e?.hop === "agent" ? "the pool agent refused the router (re-enroll or fix the agent token)" : "check the pool token (COMPUTESHARE_TOKEN or ~/.config/computeshare/forgedock.token)"}` }
781
804
  : e?.retryable === true
782
- ? { terminalReason: "deferred", code: OUTCOME_CODES.SANDBOX_CAPACITY, detail: `sandbox ${id} could not start (capacity): ${errText(e)}`, ...(Number(e.retryInSeconds) > 0 ? { retryInSeconds: Number(e.retryInSeconds) } : {}) }
805
+ ? { terminalReason: "deferred", code: OUTCOME_CODES.SANDBOX_CAPACITY, detail: `sandbox ${id} could not start (capacity): ${errText(e)}`, ...(typeof e.poolCode === "string" ? { reason: e.poolCode.replace(/^pool\./, "").replace(/^disk_(low|cap)$/, "disk") } : {}), ...(e.live ? { live: e.live } : {}), ...(Number(e.retryInSeconds) > 0 ? { retryInSeconds: Number(e.retryInSeconds) } : {}) }
783
806
  // #5095: a 5xx from the pool router or agent is infrastructure: deferred with backoff (capped), never needs-human
784
807
  : (Number.isInteger(e?.status) && e.status >= 500 && e.status <= 599) || e?.transient === true || (isTransportError(e) && !isCloneFailure(errText(e))) // #5656: fetch failed, ECONNRESET, ETIMEDOUT; a clone timeout keeps its own code
785
808
  ? { terminalReason: "deferred", code: OUTCOME_CODES.SANDBOX_TRANSIENT, retryInSeconds: Number(e.retryInSeconds) > 0 ? Number(e.retryInSeconds) : TRANSIENT_RETRY_S,
@@ -817,7 +840,7 @@ export function providerLanes({ provider, laneArgs, ledgerFor, env = process.env
817
840
  started = true;
818
841
  ctx.onStart?.({ ...(Number.isInteger(h.pid) ? { pid: h.pid } : {}), handle: h, remote: true });
819
842
  r = settleClone(await wait(h, undefined, ctx.signal), base.id);
820
- if (ctx.signal?.aborted) return HALTED; // #5669: the sandbox stays for adopt, whatever `r` is
843
+ if (ctx.signal?.aborted) return keepNote(HALTED, n, h); // #5669: the sandbox stays for adopt, whatever `r` is
821
844
  } catch (e) {
822
845
  if (started && e?.unreachable) return withUsage(unreachable(h, e), h); // #4672: no tear, the ledger keeps it
823
846
  r = started ? settleClone({ terminalReason: "engine-error", detail: `sandbox ${base.id}: ${errText(e)}` }, base.id) : startFailed(base.id, e);
@@ -836,17 +859,18 @@ export function providerLanes({ provider, laneArgs, ledgerFor, env = process.env
836
859
  saved = (ledgerFor(n)?.entries("sandbox") ?? []).find((e) => e.value === id && (e.provider ?? e.handle?.provider) === provider.name)?.handle;
837
860
  }
838
861
  if (!saved?.id || saved.provider !== provider.name) return null;
862
+ try { Promise.resolve(resumeKept?.(n)).catch(() => {}); } catch { /* best effort */ } // #6008: adopted: the lease is re-established
839
863
  // Usage runs from the sandbox's real start (persisted on the handle), not from this adopt.
840
864
  const h = { ...saved, ...(Number.isFinite(saved.startedAt) ? {} : Number.isFinite(rec?.startedAt) ? { startedAt: rec.startedAt } : {}) };
841
865
  const led = ledgerFor(n);
842
866
  led?.register("sandbox", h.id, { provider: provider.name, handle: { provider: h.provider, id: h.id, issue: h.issue, ...(Number.isFinite(h.startedAt) ? { startedAt: h.startedAt } : {}) } }); // now owned by this dispatcher
843
867
  let r;
844
- const g = guard({ waited: 0, tries: 0 });
868
+ const g = guard({ waited: 0, tries: 0, h });
845
869
  try {
846
870
  const ended = await g(() => provider.fetchResult(h));
847
871
  if (!ended && (await g(() => provider.status(h))) !== "running") r = null; // relaunched
848
872
  else { if (!ended) ctx.onLive?.(); r = await wait(h, g, ctx.signal); } // #4504: a live sandbox is awaited in the background
849
- if (ctx.signal?.aborted) return null; // #5669: halted: left for the next adopt, no tear
873
+ if (ctx.signal?.aborted) { keepNote(HALTED, n, h); return null; } // #5669: halted: left for the next adopt, no tear
850
874
  } catch (e) {
851
875
  if (e?.unreachable) return withUsage(unreachable(h, e), h); // #4672: same tolerance; no tear, left for the next adopt
852
876
  r = { terminalReason: "engine-error", detail: `sandbox ${h.id}: ${errText(e)}` };