forgedock 1.54.1 → 1.55.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/config-schema.mjs +12 -0
- package/bin/engine/events.mjs +1 -0
- package/bin/engine/events.test.mjs +5 -1
- package/bin/engine/outcome-codes.mjs +3 -0
- package/bin/engine-cli.mjs +126 -34
- package/bin/forge-utils.mjs +37 -5
- package/bin/forgedock.mjs +54 -2
- package/bin/gc-schedule.mjs +83 -0
- package/bin/gc.mjs +66 -10
- package/bin/help-text.mjs +1 -1
- package/bin/hooks/pre-tool-use.mjs +1 -0
- package/bin/init-detect.mjs +73 -2
- package/bin/labels.json +5 -0
- package/bin/lean/admission.mjs +21 -1
- package/bin/lean/baselines.mjs +43 -0
- package/bin/lean/baselines.test.mjs +33 -0
- package/bin/lean/batch-health.mjs +43 -6
- package/bin/lean/batch-health.test.mjs +41 -1
- package/bin/lean/batch.mjs +41 -4
- package/bin/lean/batch.test.mjs +106 -3
- package/bin/lean/conformance.mjs +131 -12
- package/bin/lean/conformance.test.mjs +172 -3
- package/bin/lean/depcache.mjs +23 -2
- package/bin/lean/depcache.test.mjs +22 -0
- package/bin/lean/docsgate.mjs +137 -0
- package/bin/lean/docsgate.test.mjs +78 -0
- package/bin/lean/effects.mjs +31 -2
- package/bin/lean/enumerating.mjs +39 -13
- package/bin/lean/enumerating.test.mjs +20 -0
- package/bin/lean/execution.test.mjs +3 -3
- package/bin/lean/fastforward.mjs +93 -0
- package/bin/lean/fastforward.test.mjs +73 -0
- package/bin/lean/guardgate.mjs +38 -7
- package/bin/lean/guardgate.test.mjs +39 -0
- package/bin/lean/issuewatch-install.mjs +92 -0
- package/bin/lean/issuewatch-install.test.mjs +31 -0
- package/bin/lean/issuewatch-parity.mjs +33 -3
- package/bin/lean/issuewatch-parity.test.mjs +30 -5
- package/bin/lean/issuewatch-reconcile.mjs +123 -0
- package/bin/lean/issuewatch-reconcile.test.mjs +30 -0
- package/bin/lean/issuewatch-verify.mjs +51 -9
- package/bin/lean/issuewatch.mjs +153 -33
- package/bin/lean/issuewatch.test.mjs +243 -22
- package/bin/lean/lean.mjs +381 -75
- package/bin/lean/lean.test.mjs +437 -20
- package/bin/lean/light.mjs +11 -3
- package/bin/lean/light.test.mjs +27 -0
- package/bin/lean/lightlane.mjs +8 -3
- package/bin/lean/lightlane.test.mjs +20 -0
- package/bin/lean/mechfix.mjs +21 -2
- package/bin/lean/mechfix.test.mjs +28 -1
- package/bin/lean/orchestrate-children.test.mjs +10 -0
- package/bin/lean/orchestrate-owned.test.mjs +73 -0
- package/bin/lean/orchestrate.mjs +28 -4
- package/bin/lean/overlap.mjs +20 -0
- package/bin/lean/overlap.test.mjs +49 -0
- package/bin/lean/pagegate.mjs +152 -0
- package/bin/lean/pagegate.test.mjs +77 -0
- package/bin/lean/parked-relabel.mjs +32 -0
- package/bin/lean/parked-relabel.test.mjs +45 -0
- package/bin/lean/phaseledger.mjs +17 -2
- package/bin/lean/postdeploy-check.mjs +27 -0
- package/bin/lean/postdeploy-check.test.mjs +13 -1
- package/bin/lean/postrun.mjs +32 -0
- package/bin/lean/postrun.test.mjs +41 -0
- package/bin/lean/preflight.mjs +46 -0
- package/bin/lean/preflight.test.mjs +30 -1
- package/bin/lean/prompts.mjs +36 -6
- package/bin/lean/recovery.test.mjs +16 -0
- package/bin/lean/release-review.mjs +12 -1
- package/bin/lean/release-review.test.mjs +14 -0
- package/bin/lean/release.mjs +23 -2
- package/bin/lean/release.test.mjs +28 -1
- package/bin/lean/render.mjs +17 -6
- package/bin/lean/reproquality.mjs +116 -0
- package/bin/lean/reproquality.test.mjs +85 -0
- package/bin/lean/review-trigger.mjs +8 -3
- package/bin/lean/sandbox-budget.test.mjs +27 -0
- package/bin/lean/schedd.mjs +40 -11
- package/bin/lean/schedd.test.mjs +12 -1
- package/bin/lean/testadequacy.mjs +97 -0
- package/bin/lean/testadequacy.test.mjs +92 -0
- package/bin/lean/testsandbox.mjs +202 -0
- package/bin/lean/testsandbox.test.mjs +157 -0
- package/bin/lean/toolplace.mjs +5 -2
- package/bin/lean/toolplace.test.mjs +6 -0
- package/bin/lean/verify.mjs +6 -1
- package/bin/lean/verify.test.mjs +18 -2
- package/bin/lean/warmtree.mjs +77 -0
- package/bin/lean/warmtree.test.mjs +81 -0
- package/bin/review-staging.mjs +51 -9
- package/bin/stats/conformance-outcomes.mjs +12 -2
- package/bin/stats/depth.mjs +24 -1
- package/bin/stats/depth.test.mjs +21 -1
- package/bin/stats/index.mjs +5 -2
- package/bin/stats/query.mjs +2 -1
- package/commands/cleanup.md +18 -0
- package/commands/fd-introspect.md +19 -0
- package/commands/milestone.md +5 -1
- package/commands/pipeline-health/phase-2-metrics.md +4 -0
- package/commands/recover-orphans.md +31 -1
- package/commands/review-pr-staging.md +9 -0
- package/commands/review-pr.md +2 -0
- package/docs/CONFIG.md +26 -1
- package/docs/EVENTS.md +1 -0
- package/docs/ISSUE-WATCH.md +12 -3
- package/docs/eval/adversarial-bench.md +1 -1
- package/docs/eval/published/adversarial-2026-11-11.md +58 -0
- package/package.json +1 -1
- package/scripts/bench-lightlane.mjs +3 -2
- package/scripts/hotspots.sh +7 -4
- package/scripts/hotspots.test.sh +12 -0
- package/scripts/recover-orphans-stateless.test.sh +79 -0
- package/scripts/transition-label.sh +2 -0
- package/templates/workflows/forgedock-reopen-clean.yml +33 -0
package/bin/lean/schedd.mjs
CHANGED
|
@@ -55,12 +55,37 @@ import { batchRoot, listBatches, openBatch, SECRET_ENV } from "./batch.mjs";
|
|
|
55
55
|
import { applySetExecution } from "./live-execution.mjs";
|
|
56
56
|
import { liveOverload } from "./hostload.mjs";
|
|
57
57
|
|
|
58
|
+
/** #5471: `schedd status` warning lines for issues pending in two or more hosted batches. */
|
|
59
|
+
export function sharedPendingLines(batches) {
|
|
60
|
+
const shared = new Map();
|
|
61
|
+
for (const b of batches ?? []) if (b.running) for (const n of b.pending ?? []) shared.set(n, [...(shared.get(n) ?? []), b.id]);
|
|
62
|
+
return [...shared].filter(([, ids]) => ids.length > 1).map(([n, ids]) => `schedd: warning: #${n} is pending in ${ids.length} batches (${ids.join(", ")}); only one should run it`);
|
|
63
|
+
}
|
|
64
|
+
|
|
58
65
|
export const IDLE_MS = 10 * 60 * 1000;
|
|
59
66
|
export const STOP_MS = 10 * 1000;
|
|
60
67
|
export const LOCK_CHECK_MS = 5 * 1000;
|
|
61
68
|
export const ADMIT_MS = 120 * 1000; // #4775: how long one add/requeue/attach/resume waits for its batch to start before answering an error
|
|
62
69
|
export const LAG_MS = 5 * 1000; // #4775: an event-loop stall longer than this is logged
|
|
63
70
|
export const REQUEST_MS = 15 * 1000; // #4775: default bound of a control/status request
|
|
71
|
+
/**
|
|
72
|
+
* #5469: the unhosted batches of `root` that still have pending issues and are not cancelled, split by idle time:
|
|
73
|
+
* `orphaned` (no progress for `minAgeMs`) and `unhosted` (recent). @returns {{unhosted: Array<{id, pending}>, orphaned: Array<{id, pending}>}}
|
|
74
|
+
*/
|
|
75
|
+
export function findUnhosted(root, { isHosted = () => false, now = Date.now(), minAgeMs = ORPHAN_AGE_MS } = {}) {
|
|
76
|
+
const unhosted = [], orphaned = [];
|
|
77
|
+
for (const id of listBatches(root)) {
|
|
78
|
+
if (isHosted(id)) continue;
|
|
79
|
+
try {
|
|
80
|
+
const b = openBatch(root, id), pending = b.pendingIssues();
|
|
81
|
+
if (!pending.length || b.readCancel()) continue;
|
|
82
|
+
const last = b.lastProgressMs();
|
|
83
|
+
(last !== null && now - last > minAgeMs ? orphaned : unhosted).push({ id, pending });
|
|
84
|
+
} catch { /* advisory */ }
|
|
85
|
+
}
|
|
86
|
+
return { unhosted, orphaned };
|
|
87
|
+
}
|
|
88
|
+
export const ORPHAN_AGE_MS = 7 * 24 * 3600 * 1000; // #5469: an unhosted batch idle this long with pending issues is orphaned
|
|
64
89
|
export const UNIT = "forgedock-schedd";
|
|
65
90
|
export const DUE_MS = 15 * 60 * 1000; // #4627: how often the due callback (windowed post-deploy monitoring) runs while the daemon is up
|
|
66
91
|
|
|
@@ -264,24 +289,23 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
264
289
|
try { for (const id of listBatches(root)) if (!ids.has(id) && openBatch(root, id).readPlan()?.daemon) ids.add(id); } catch { /* unreadable root */ }
|
|
265
290
|
for (const id of [...ids].sort()) {
|
|
266
291
|
const isHosted = hosted.has(id) || starting.has(id);
|
|
267
|
-
let last = null, pending = [];
|
|
268
|
-
try { const b = openBatch(root, id); last = b.lastProgressMs(); pending = b.unrunAdds(); } catch { /* a half-written batch */ }
|
|
292
|
+
let last = null, pending = [], pend = [];
|
|
293
|
+
try { const b = openBatch(root, id); last = b.lastProgressMs(); pending = b.unrunAdds(); pend = b.pendingIssues(); } catch { /* a half-written batch */ }
|
|
269
294
|
if (!isHosted && !pending.length) continue;
|
|
270
|
-
out.push({ id, running: isHosted, lastProgressAt: last === null ? null : new Date(last).toISOString(), lastProgressAgeSec: last === null ? null : Math.max(0, Math.round((now - last) / 1000)), pendingAdds: pending });
|
|
295
|
+
out.push({ id, running: isHosted, lastProgressAt: last === null ? null : new Date(last).toISOString(), lastProgressAgeSec: last === null ? null : Math.max(0, Math.round((now - last) / 1000)), pendingAdds: pending, pending: pend });
|
|
271
296
|
}
|
|
272
297
|
return out;
|
|
273
298
|
};
|
|
274
299
|
|
|
300
|
+
const unhostedBatches = (now, minAgeMs = ORPHAN_AGE_MS) => findUnhosted(root, { isHosted: (id) => hosted.has(id) || starting.has(id), now, minAgeMs });
|
|
301
|
+
|
|
275
302
|
const handle = async (req, send) => {
|
|
276
303
|
if (req.op === "status") {
|
|
277
304
|
// #4917: a batch dir that still holds pending issues but is not hosted (finalised early, or never resumed)
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
if (hosted.has(id) || starting.has(id)) continue;
|
|
281
|
-
try { const pending = openBatch(root, id).pendingIssues(); if (pending.length) unhosted.push({ id, pending }); } catch { /* advisory */ }
|
|
282
|
-
}
|
|
305
|
+
// #5469: ones idle longer than ORPHAN_AGE_MS collapse into `orphaned` (one line; `orchestrate --gc-orphans` cancels them)
|
|
306
|
+
const { unhosted, orphaned } = unhostedBatches(Date.now());
|
|
283
307
|
let host = null; try { host = hostLoad?.() ?? null; } catch { host = null; } // #5174
|
|
284
|
-
return send({ type: "status", pid, lastTick, batches: statusBatches(), unhosted, host }, true);
|
|
308
|
+
return send({ type: "status", pid, lastTick, batches: statusBatches(), unhosted, orphaned, host }, true);
|
|
285
309
|
}
|
|
286
310
|
if (req.op === "set-parallel") {
|
|
287
311
|
const b = openBatch(root, req.id);
|
|
@@ -318,9 +342,14 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
318
342
|
if (req.op === "hold" || req.op === "release") {
|
|
319
343
|
const b = openBatch(root, req.id);
|
|
320
344
|
if (!b.exists()) throw new Error(`no batch ${req.id} in ${root}`);
|
|
321
|
-
const changed = req.op === "hold" ? b.holdIssues(req.issues ?? []) : b.releaseIssues(req.issues ?? []);
|
|
345
|
+
const changed = req.op === "hold" ? b.holdIssues(req.issues ?? [], req.meta ?? null) : b.releaseIssues(req.issues ?? []);
|
|
322
346
|
return send({ type: "ok", changed, hosted: hosted.has(req.id) }, true);
|
|
323
347
|
}
|
|
348
|
+
if (req.op === "gc-orphans") { // #5469: cancel every orphaned batch (unhosted, pending issues, idle past the threshold)
|
|
349
|
+
const { orphaned } = unhostedBatches(Date.now(), Number.isFinite(req.minAgeMs) ? req.minAgeMs : ORPHAN_AGE_MS);
|
|
350
|
+
for (const o of orphaned) openBatch(root, o.id).requestCancel({ reason: "gc-orphans" });
|
|
351
|
+
return send({ type: "ok", cancelled: orphaned.map((o) => o.id) }, true);
|
|
352
|
+
}
|
|
324
353
|
if (req.op === "cancel") {
|
|
325
354
|
const b = openBatch(root, req.id);
|
|
326
355
|
if (!b.exists()) throw new Error(`no batch ${req.id} in ${root}`);
|
|
@@ -456,7 +485,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
456
485
|
const isHosted = hosted.has(id) || starting.has(id);
|
|
457
486
|
const stall = evaluateDispatchStall(state, { held: b.readHeld(), parallel: b.readParallel(), hosted: isHosted, lastProgressMs: b.lastProgressMs(), now, windowMin: stallMin, cancelled, reported });
|
|
458
487
|
if (Number.isFinite(created) && (reported || now - created >= FIRST_HOUR_MIN * 60_000) && !existsSync(join(b.dir, FIRST_HOUR_FILE)) && now - created < 24 * 3600_000) {
|
|
459
|
-
if (writeFirstHour(b, firstHourReport(state, { batchId: id, now, held: b.readHeld(), stall }))) log(`schedd: first-hour report written for batch ${id}`);
|
|
488
|
+
if (writeFirstHour(b, firstHourReport(state, { batchId: id, now, held: b.readHeld(), holdInfo: b.readHoldInfo?.() ?? null, stall }))) log(`schedd: first-hour report written for batch ${id}`);
|
|
460
489
|
}
|
|
461
490
|
if (!stall) continue;
|
|
462
491
|
const sig = stall.ready.join(",");
|
package/bin/lean/schedd.test.mjs
CHANGED
|
@@ -8,7 +8,7 @@ import { homedir, tmpdir } from "node:os";
|
|
|
8
8
|
import { join } from "node:path";
|
|
9
9
|
import { tmpDir } from "../tests/_tmp.mjs";
|
|
10
10
|
import { openBatch, isLaneAlive, listBatches, SECRET_ENV } from "./batch.mjs";
|
|
11
|
-
import { startDaemon, scheddPaths, connectDaemon, request, unitState, SCHEDD_SCRIPT, mergeEnv, batchEnv, droppedEnv, sanitizePath, redactEnv, exitOnSignals, readInstalledVersion } from "./schedd.mjs";
|
|
11
|
+
import { findUnhosted, startDaemon, scheddPaths, connectDaemon, request, unitState, SCHEDD_SCRIPT, mergeEnv, batchEnv, droppedEnv, sanitizePath, redactEnv, exitOnSignals, readInstalledVersion } from "./schedd.mjs";
|
|
12
12
|
import { schedDir } from "./sched.mjs";
|
|
13
13
|
import { readHeartbeat } from "./schedd-health.mjs";
|
|
14
14
|
import { formatTable, orchestrate } from "./orchestrate.mjs";
|
|
@@ -989,3 +989,14 @@ describe("#4762 win32 socket path", () => {
|
|
|
989
989
|
assert.doesNotMatch(SCHEDD_SCRIPT, /^\/[A-Za-z]:/);
|
|
990
990
|
});
|
|
991
991
|
});
|
|
992
|
+
|
|
993
|
+
describe("#5469: orphaned batches", () => {
|
|
994
|
+
it("#5469: findUnhosted splits unhosted batches with pending issues by idle time and skips cancelled ones", () => {
|
|
995
|
+
const root = tmpDir("schedd-orphan-");
|
|
996
|
+
const mk = (id, ageMs) => { const b = openBatch(root, id); b.writePlan({ argv: [], repo: "o/r" }); b.store.save({ order: [1], pending: [1], results: {} }); const t = new Date(Date.now() - ageMs); utimesSync(join(b.dir, "state.json"), t, t); return b; };
|
|
997
|
+
mk("ancient", 10 * 86400000); mk("recent", 60000); mk("hosted", 10 * 86400000); mk("cancelled", 10 * 86400000).requestCancel({ reason: "t" });
|
|
998
|
+
const r = findUnhosted(root, { isHosted: (id) => id === "hosted" });
|
|
999
|
+
assert.deepEqual(r.orphaned, [{ id: "ancient", pending: [1] }]);
|
|
1000
|
+
assert.deepEqual(r.unhosted, [{ id: "recent", pending: [1] }]);
|
|
1001
|
+
});
|
|
1002
|
+
});
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* #5449: test adequacy per requirement. Pure, deterministic first: the engine derives each row from facts it already has
|
|
5
|
+
* (the executed evidence tests, the mutation result, the repro red/green words, the optional test plan and regression set
|
|
6
|
+
* of the epic's other children); the reviewer only adds an optional `test_adequacy` judgment per requirement.
|
|
7
|
+
* Verdicts: `adequate`, `weak (reason)`, `missing`. Inputs a lane does not have report "n/a", never a guess.
|
|
8
|
+
*/
|
|
9
|
+
import { isTestPath, isOutOfBand, unverifiedRequirements } from "./conformance.mjs";
|
|
10
|
+
|
|
11
|
+
export const TEST_MISSING = "conformance.test_missing";
|
|
12
|
+
export const TEST_WEAK = "conformance.test_weak";
|
|
13
|
+
|
|
14
|
+
const NA = "n/a";
|
|
15
|
+
const planOf = (contract, id) => (Array.isArray(contract?.test_plan) ? contract.test_plan : contract?.test_plan?.requirements ?? []).find?.((p) => p?.requirement === id || p?.id === id) ?? null;
|
|
16
|
+
const testsOf = (contract, r) => (contract?.deliverables ?? []).filter((d) => (d.requirements ?? []).includes(r.id) && isTestPath(d.path)).map((d) => String(d.path));
|
|
17
|
+
const greenId = (id, { runs = [], reruns = null, ciCovered = [] }) => (reruns?.[id] ? reruns[id].rc === 0 : (Array.isArray(runs) ? runs : []).some((x) => x?.id === id && x.exit === 0) || ciCovered.includes(id));
|
|
18
|
+
|
|
19
|
+
/** The red/green words of the lane's repro test as one cell: "BASE=FAILED HEAD=RAN", or n/a. */
|
|
20
|
+
export const reproCell = (repro) => (repro?.base && repro?.head ? `BASE=${repro.base} HEAD=${repro.head}` : NA);
|
|
21
|
+
|
|
22
|
+
/** Whether the contract's planned regression set (`regression_set`: validate ids, from #5448) ran green: true, false, or null without a set. */
|
|
23
|
+
export function regressionRan(contract, evidence = {}) {
|
|
24
|
+
const ids = (Array.isArray(contract?.regression_set) ? contract.regression_set : []).map((x) => String(x?.id ?? x));
|
|
25
|
+
return ids.length ? ids.every((id) => greenId(id, evidence)) : null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* One row per deliver requirement that is not verified out of band.
|
|
30
|
+
* @param {object} contract
|
|
31
|
+
* @param {{runs?: object[], reruns?: object|null, ciCovered?: string[], mutation?: {id: string, status: string}[], repro?: {base?: string, head?: string}|null, review?: object|null}} [o]
|
|
32
|
+
* @returns {{id: string, planned: string, test: string, level: string, redgreen: string, mutation: string, regression: string, verdict: "adequate"|"weak"|"missing", reason: string}[]}
|
|
33
|
+
*/
|
|
34
|
+
export function testAdequacyRows(contract, { runs = [], reruns = null, ciCovered = [], mutation = null, repro = null, review = null } = {}) {
|
|
35
|
+
const ev = { runs, reruns, ciCovered };
|
|
36
|
+
// a repro test proved red on the base and green on head is itself the executed proof for a bug lane
|
|
37
|
+
const redGreen = repro?.base === "FAILED" && repro?.head === "RAN" && contract?.repro_test && typeof contract.repro_test === "object";
|
|
38
|
+
const unverified = new Map(unverifiedRequirements(contract, ev).filter(() => !redGreen).map((u) => [u.id, u.reason]));
|
|
39
|
+
const ran = regressionRan(contract, ev);
|
|
40
|
+
const quality = String(contract?.repro_quality ?? "").toLowerCase();
|
|
41
|
+
return (contract?.requirements ?? []).filter((r) => r.disposition === "deliver" && !isOutOfBand(r)).map((r) => {
|
|
42
|
+
const plan = planOf(contract, r.id);
|
|
43
|
+
const m = (mutation ?? []).filter((x) => x?.id === r.id).map((x) => x.status);
|
|
44
|
+
const mut = !m.length ? NA : m.includes("survived") ? "survived" : m.includes("killed") ? "killed" : "skipped";
|
|
45
|
+
const j = (review?.requirements ?? []).find((x) => x?.id === r.id)?.test_adequacy;
|
|
46
|
+
const reasons = [];
|
|
47
|
+
if (mut === "survived") reasons.push("the test passes with the change reverted");
|
|
48
|
+
if (/patch[-_ ]?echo|weak/.test(quality) && contract?.repro_test && contract.repro_test !== "none") reasons.push(`repro quality ${quality}`);
|
|
49
|
+
if (repro?.base === "RAN" && repro?.head === "RAN") reasons.push("the repro passes on the base");
|
|
50
|
+
if (ran === false) reasons.push("the planned regression set did not run green");
|
|
51
|
+
if (/^weak/i.test(String(j?.verdict ?? ""))) reasons.push(String(j?.reason || "reviewer: the test does not prove the root cause").slice(0, 200));
|
|
52
|
+
const missing = unverified.has(r.id);
|
|
53
|
+
return { id: r.id, planned: plan ? String(plan.proof ?? plan.command ?? "planned") : NA, test: testsOf(contract, r).join(", ") || (redGreen ? String(contract.repro_test.path ?? "repro_test") : "none"), level: String(plan?.level ?? NA), redgreen: reproCell(repro), mutation: mut, regression: ran == null ? NA : ran ? "ran" : "not run",
|
|
54
|
+
verdict: missing ? "missing" : reasons.length ? "weak" : "adequate", reason: missing ? unverified.get(r.id) : reasons.join("; ") };
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Display text of a row verdict: `adequate`, `weak (reason)` or `missing`. */
|
|
59
|
+
export const verdictText = (row) => (row.verdict === "weak" ? `weak (${row.reason})` : row.verdict);
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Gate failures for the rows, bug lanes only. `missing` always blocks; `weak` only in the first gate round (one builder
|
|
63
|
+
* resume to strengthen the test), after which it is recorded in the review table.
|
|
64
|
+
*/
|
|
65
|
+
export function testAdequacyFailures(rows, { bug = false, firstRound = true } = {}) {
|
|
66
|
+
if (!bug) return [];
|
|
67
|
+
return (rows ?? []).flatMap((r) => (r.verdict === "missing" ? [{ code: TEST_MISSING, kind: "test_missing", detail: `${r.id} has no executed test that proves it (${r.reason}); write or run a test that fails without the fix` }]
|
|
68
|
+
: r.verdict === "weak" && firstRound ? [{ code: TEST_WEAK, kind: "test_weak", detail: `${r.id} test is weak: ${r.reason}; strengthen it so it fails when the root cause is present` }] : []));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Per-lane telemetry scalars (FORGE:TELEMETRY); a fact the lane does not have is omitted, never guessed. */
|
|
72
|
+
export function testAdequacyTelemetry(contract, rows, { repro = null, mutation = null, regression = null } = {}) {
|
|
73
|
+
const reqs = (contract?.requirements ?? []).filter((r) => r.disposition === "deliver" && !isOutOfBand(r));
|
|
74
|
+
const ids = [...new Set((contract?.requirements ?? []).filter((r) => r.disposition === "post-deploy" && r.check).map((r) => String(r.check)))];
|
|
75
|
+
const out = { tests_declared: reqs.filter((r) => testsOf(contract, r).length).length, tests_ran: (rows ?? []).filter((r) => r.verdict !== "missing").length };
|
|
76
|
+
if (contract?.repro_test && contract.repro_test !== "none") out.repro_quality = String(contract.repro_quality ?? (repro?.base === "FAILED" && repro?.head === "RAN" ? "red_green" : repro?.base ? "unproven" : "unrun"));
|
|
77
|
+
if (mutation?.length) out.mutation_killed = mutation.filter((x) => x?.status === "killed").length;
|
|
78
|
+
if (regression != null) out.regression_suite_ran = Boolean(regression);
|
|
79
|
+
if (ids.length) out.post_deploy_check_ids = ids.join(",");
|
|
80
|
+
return out;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The class of a lane for outcome splits: the worst row verdict (missing > weak > adequate), or null without rows. */
|
|
84
|
+
export const adequacyClass = (rows) => (!rows?.length ? null : rows.some((r) => r.verdict === "missing") ? "missing" : rows.some((r) => r.verdict === "weak") ? "weak" : "adequate");
|
|
85
|
+
|
|
86
|
+
/** Counts by verdict for a lane's `conformance.test_adequacy` record. */
|
|
87
|
+
export const adequacyCounts = (rows) => (rows?.length ? { adequate: rows.filter((r) => r.verdict === "adequate").length, weak: rows.filter((r) => r.verdict === "weak").length, missing: rows.filter((r) => r.verdict === "missing").length } : null);
|
|
88
|
+
|
|
89
|
+
/** Batch report line from orchestrate rows (`row.conformance.test_adequacy`), or null when no lane has rows. */
|
|
90
|
+
export function formatTestAdequacySummary(rows) {
|
|
91
|
+
const cs = (rows ?? []).map((r) => r?.conformance?.test_adequacy).filter((c) => c && typeof c === "object");
|
|
92
|
+
if (!cs.length) return null;
|
|
93
|
+
const sum = (k) => cs.reduce((n, c) => n + (c[k] || 0), 0);
|
|
94
|
+
const total = sum("adequate") + sum("weak") + sum("missing");
|
|
95
|
+
const pct = (k) => `${total ? Math.round((sum(k) / total) * 100) : 0}%`;
|
|
96
|
+
return `test adequacy: ${cs.length} lane${cs.length === 1 ? "" : "s"}, ${total} requirement(s): adequate ${pct("adequate")}, weak ${pct("weak")}, missing ${pct("missing")}`;
|
|
97
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
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 { testAdequacyRows, testAdequacyFailures, testAdequacyTelemetry, verdictText, adequacyClass, adequacyCounts, formatTestAdequacySummary, regressionRan, TEST_MISSING, TEST_WEAK } from "./testadequacy.mjs";
|
|
6
|
+
import { renderReview, renderShadowReview } from "./render.mjs";
|
|
7
|
+
import { blockingFailures } from "./conformance.mjs";
|
|
8
|
+
import { conformanceOutcomes } from "../stats/conformance-outcomes.mjs";
|
|
9
|
+
|
|
10
|
+
const contract = (extra = {}) => ({
|
|
11
|
+
requirements: [{ id: "R1", quote: "q1", disposition: "deliver" }, { id: "R2", quote: "q2", disposition: "deliver" }, { id: "R3", quote: "q3", disposition: "post-deploy", check: "chk-a" }],
|
|
12
|
+
deliverables: [{ id: "D1", path: "src/a.mjs", requirements: ["R1", "R2"] }, { id: "D2", path: "src/a.test.mjs", requirements: ["R1"] }],
|
|
13
|
+
validate: [{ id: "V1", command: "node --test src/a.test.mjs" }], ...extra,
|
|
14
|
+
});
|
|
15
|
+
const green = { runs: [{ id: "V1", exit: 0 }] };
|
|
16
|
+
|
|
17
|
+
describe("testAdequacyRows verdict rules", () => {
|
|
18
|
+
it("missing when no executed test covers the requirement, adequate when one ran green", () => {
|
|
19
|
+
const rows = testAdequacyRows(contract(), green);
|
|
20
|
+
assert.deepEqual(rows.map((r) => [r.id, r.verdict]), [["R1", "adequate"], ["R2", "missing"]]);
|
|
21
|
+
assert.equal(rows[0].planned, "n/a"); assert.equal(rows[0].mutation, "n/a"); assert.equal(rows[0].regression, "n/a");
|
|
22
|
+
});
|
|
23
|
+
it("a test that was declared but never ran is missing", () => assert.equal(testAdequacyRows(contract(), { runs: [{ id: "V1", exit: 1 }] })[0].verdict, "missing"));
|
|
24
|
+
it("weak when the mutation survived, with the reason", () => {
|
|
25
|
+
const r = testAdequacyRows(contract(), { ...green, mutation: [{ id: "R1", status: "survived" }] })[0];
|
|
26
|
+
assert.equal(r.verdict, "weak"); assert.match(verdictText(r), /^weak \(.*reverted/);
|
|
27
|
+
});
|
|
28
|
+
it("killed mutation keeps adequate; repro BASE=RAN HEAD=RAN is weak", () => {
|
|
29
|
+
assert.equal(testAdequacyRows(contract(), { ...green, mutation: [{ id: "R1", status: "killed" }] })[0].mutation, "killed");
|
|
30
|
+
assert.equal(testAdequacyRows(contract(), { ...green, repro: { base: "RAN", head: "RAN" } })[0].verdict, "weak");
|
|
31
|
+
assert.equal(testAdequacyRows(contract(), { ...green, repro: { base: "FAILED", head: "RAN" } })[0].redgreen, "BASE=FAILED HEAD=RAN");
|
|
32
|
+
});
|
|
33
|
+
it("weak from the reviewer's test_adequacy row and from a regression set that did not run", () => {
|
|
34
|
+
const review = { requirements: [{ id: "R1", test_adequacy: { verdict: "weak", reason: "asserts the URL rewrite only" } }] };
|
|
35
|
+
assert.match(verdictText(testAdequacyRows(contract(), { ...green, review })[0]), /asserts the URL rewrite only/);
|
|
36
|
+
const c = contract({ regression_set: ["V9"] });
|
|
37
|
+
assert.equal(regressionRan(c, green), false);
|
|
38
|
+
assert.equal(testAdequacyRows(c, green)[0].regression, "not run");
|
|
39
|
+
});
|
|
40
|
+
it("a repro test proved red on base and green on head is the executed proof (no evidence validate needed)", () => {
|
|
41
|
+
const c = contract({ repro_test: { path: "src/r.test.mjs", command: "node --test src/r.test.mjs" } });
|
|
42
|
+
const rows = testAdequacyRows(c, { repro: { base: "FAILED", head: "RAN" } });
|
|
43
|
+
assert.deepEqual(rows.map((r) => r.verdict), ["adequate", "adequate"]); assert.equal(rows[1].test, "src/r.test.mjs");
|
|
44
|
+
assert.equal(testAdequacyRows(c, { repro: { base: "RAN", head: "RAN" } })[0].verdict, "missing");
|
|
45
|
+
});
|
|
46
|
+
it("out-of-band requirements get no row", () => {
|
|
47
|
+
const c = contract(); c.requirements[1].verify = "out_of_band";
|
|
48
|
+
assert.deepEqual(testAdequacyRows(c, green).map((r) => r.id), ["R1"]);
|
|
49
|
+
});
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
describe("testAdequacyFailures", () => {
|
|
53
|
+
const rows = testAdequacyRows(contract(), { ...green, mutation: [{ id: "R1", status: "survived" }] });
|
|
54
|
+
it("never fails a non-bug lane", () => assert.deepEqual(testAdequacyFailures(rows, { bug: false }), []));
|
|
55
|
+
it("bug lane: missing always, weak only in the first round", () => {
|
|
56
|
+
assert.deepEqual(testAdequacyFailures(rows, { bug: true, firstRound: true }).map((f) => f.code), [TEST_WEAK, TEST_MISSING]);
|
|
57
|
+
assert.deepEqual(testAdequacyFailures(rows, { bug: true, firstRound: false }).map((f) => f.code), [TEST_MISSING]);
|
|
58
|
+
});
|
|
59
|
+
it("both kinds block in a shadow lane without conformance_kinds", () => {
|
|
60
|
+
const f = testAdequacyFailures(rows, { bug: true });
|
|
61
|
+
assert.equal(blockingFailures(f, { shadow: true }).block.length, 2);
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
describe("telemetry, summary and rendering", () => {
|
|
66
|
+
it("telemetry carries known facts only", () => {
|
|
67
|
+
const rows = testAdequacyRows(contract(), green);
|
|
68
|
+
assert.deepEqual(testAdequacyTelemetry(contract(), rows), { tests_declared: 1, tests_ran: 1, post_deploy_check_ids: "chk-a" });
|
|
69
|
+
const t = testAdequacyTelemetry(contract({ repro_test: { command: "x" } }), rows, { repro: { base: "FAILED", head: "RAN" }, mutation: [{ status: "killed" }, { status: "survived" }], regression: true });
|
|
70
|
+
assert.equal(t.repro_quality, "red_green"); assert.equal(t.mutation_killed, 1); assert.equal(t.regression_suite_ran, true);
|
|
71
|
+
});
|
|
72
|
+
it("class, counts and the batch line", () => {
|
|
73
|
+
const rows = testAdequacyRows(contract(), green);
|
|
74
|
+
assert.equal(adequacyClass(rows), "missing"); assert.deepEqual(adequacyCounts(rows), { adequate: 1, weak: 0, missing: 1 });
|
|
75
|
+
assert.equal(formatTestAdequacySummary([{}]), null);
|
|
76
|
+
assert.equal(formatTestAdequacySummary([{ conformance: { test_adequacy: { adequate: 1, weak: 0, missing: 1 } } }, { conformance: { test_adequacy: { adequate: 2, weak: 0, missing: 0 } } }]), "test adequacy: 2 lanes, 4 requirement(s): adequate 75%, weak 0%, missing 25%");
|
|
77
|
+
});
|
|
78
|
+
it("FORGE:REVIEW (enforced and shadow) renders the Test adequacy table", () => {
|
|
79
|
+
const c = contract(), rows = testAdequacyRows(c, green), rv = { requirements: [], summary: "s" };
|
|
80
|
+
assert.match(renderReview(rv, c, rows), /\*\*Test adequacy\*\*[\s\S]*\| R2 \|.*\| missing \|/);
|
|
81
|
+
assert.match(renderShadowReview({ would: "conforms", review: rv, contract: c, adequacy: rows }), /\*\*Test adequacy\*\*/);
|
|
82
|
+
assert.doesNotMatch(renderReview(rv, c), /Test adequacy/);
|
|
83
|
+
});
|
|
84
|
+
it("outcomes split reopen within 14 days by adequacy class", () => {
|
|
85
|
+
const now = Date.parse("2026-12-01T00:00:00Z"), mk = (n, re) => ({ number: n, repo: "o/r", title: "t", body: "", mergedAt: "2026-11-01T00:00:00Z", closingIssues: [{ number: 100 + n, reopenedAt: re ? ["2026-11-10T00:00:00Z"] : [] }] });
|
|
86
|
+
const prs = [mk(1, true), mk(2, false)];
|
|
87
|
+
const verdicts = new Map([["pr:1", { state: "conforms", kinds: [], test_adequacy: "missing" }], ["pr:2", { state: "conforms", kinds: [], test_adequacy: "adequate" }]]);
|
|
88
|
+
const r = conformanceOutcomes({ prs, verdicts, minN: 1, now });
|
|
89
|
+
assert.equal(r.repos["o/r"].by_adequacy.missing.defects, 1);
|
|
90
|
+
assert.equal(r.repos["o/r"].by_adequacy.adequate.defects, 0);
|
|
91
|
+
});
|
|
92
|
+
});
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* Test sandboxes (#5450): throwaway service containers (database, cache, API) a lane's validate commands need. A frozen
|
|
5
|
+
* validate entry declares `env: [name, ...]`; each name is a forge.yaml `verify.sandboxes` entry. Nothing is created for a
|
|
6
|
+
* lane whose contract names no env. Each lane gets its own containers (`forge-sbx-<lane>-<name>`, ephemeral loopback ports,
|
|
7
|
+
* forgedock.* labels), registered in the lane ledger as kind `container` BEFORE they exist, so teardown and `forgedock gc`
|
|
8
|
+
* reclaim them after a crash. A name no entry defines, or a host without Docker, is a typed `unavailable` result the lane
|
|
9
|
+
* ends on, never a skip. Each sandbox exports `SANDBOX_<NAME>_URL` (a `fixtures:` entry exports `SANDBOX_<NAME>_DIR`).
|
|
10
|
+
* All I/O is injected: `docker(args) -> stdout` (throws on failure), `exec({command, env}) -> {rc}`, `sleep(ms)`.
|
|
11
|
+
*/
|
|
12
|
+
import { resolve } from "node:path";
|
|
13
|
+
import { execFile } from "node:child_process";
|
|
14
|
+
import { promisify } from "node:util";
|
|
15
|
+
import { dockerLabels, makeLedger, safeSegment } from "./ledger.mjs";
|
|
16
|
+
|
|
17
|
+
const NAME_RE = /^[a-z][a-z0-9_-]*$/;
|
|
18
|
+
const KNOWN = { postgres: { port: 5432, env: ["POSTGRES_PASSWORD=sandbox"], url: (p) => `postgresql://postgres:sandbox@127.0.0.1:${p}/postgres`, ready: ["pg_isready", "-U", "postgres"] }, redis: { port: 6379, url: (p) => `redis://127.0.0.1:${p}`, ready: ["redis-cli", "ping"] } };
|
|
19
|
+
const envName = (n) => `SANDBOX_${n.toUpperCase().replace(/[^A-Z0-9]/g, "_")}`;
|
|
20
|
+
const str = (v) => (v === undefined || v === null ? "" : String(v).trim());
|
|
21
|
+
|
|
22
|
+
/** Split on `sep` outside quotes and brackets. */
|
|
23
|
+
function splitTop(s, sep) {
|
|
24
|
+
const out = []; let depth = 0, q = null, cur = "";
|
|
25
|
+
for (const ch of s) {
|
|
26
|
+
if (q) { if (ch === q) q = null; cur += ch; continue; }
|
|
27
|
+
if (ch === '"' || ch === "'") { q = ch; cur += ch; continue; }
|
|
28
|
+
if (ch === "[" || ch === "{") depth++;
|
|
29
|
+
if (ch === "]" || ch === "}") depth--;
|
|
30
|
+
if (ch === sep && depth === 0) { out.push(cur); cur = ""; continue; }
|
|
31
|
+
cur += ch;
|
|
32
|
+
}
|
|
33
|
+
out.push(cur);
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
const unquote = (v) => v.trim().replace(/^(["'])(.*)\1$/s, "$2");
|
|
37
|
+
/** `{ image: postgres:16, needs: [a, b] }` (the one-line form readYamlMap returns) or an object -> plain object. */
|
|
38
|
+
function flowMap(raw) {
|
|
39
|
+
if (raw && typeof raw === "object" && !Array.isArray(raw)) return raw;
|
|
40
|
+
const s = str(raw).replace(/^\{(.*)\}$/s, "$1");
|
|
41
|
+
const o = {};
|
|
42
|
+
for (const part of splitTop(s, ",")) {
|
|
43
|
+
const i = part.indexOf(":");
|
|
44
|
+
if (i < 1) continue;
|
|
45
|
+
const k = part.slice(0, i).trim(), v = part.slice(i + 1).trim();
|
|
46
|
+
o[k] = v.startsWith("[") ? splitTop(v.replace(/^\[(.*)\]$/s, "$1"), ",").map(unquote).filter(Boolean) : unquote(v);
|
|
47
|
+
}
|
|
48
|
+
return o;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** forge.yaml `verify.sandboxes` -> `{name: {image|compose+service|fixtures, needs[], init, ttl, for, port, ready}}`; invalid entries dropped. */
|
|
52
|
+
export function parseSandboxes(raw) {
|
|
53
|
+
const out = {};
|
|
54
|
+
if (!raw || typeof raw !== "object") return out;
|
|
55
|
+
for (const [name, v] of Object.entries(raw)) {
|
|
56
|
+
if (!NAME_RE.test(name)) continue;
|
|
57
|
+
const s = flowMap(v);
|
|
58
|
+
const image = str(s.image), compose = str(s.compose), service = str(s.service), fixtures = str(s.fixtures);
|
|
59
|
+
if (!(image || (compose && service) || fixtures)) continue;
|
|
60
|
+
const needs = (Array.isArray(s.needs) ? s.needs : str(s.needs).split(",")).map((x) => str(x)).filter(Boolean);
|
|
61
|
+
const port = Number(str(s.port));
|
|
62
|
+
out[name] = { ...(image ? { image } : {}), ...(compose && service ? { compose, service } : {}), ...(fixtures ? { fixtures } : {}), needs, ...(str(s.init) ? { init: str(s.init) } : {}),
|
|
63
|
+
...(str(s.ttl) ? { ttl: str(s.ttl) } : {}), ...(str(s.for) ? { for: str(s.for) } : {}), ...(str(s.record) ? { record: str(s.record) } : {}), ...(Number.isInteger(port) && port > 0 && port < 65536 ? { port } : {}), ...(str(s.ready) ? { ready: str(s.ready) } : {}) };
|
|
64
|
+
}
|
|
65
|
+
return out;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The env names a frozen contract's validate entries declare (unique, in order); [] when none. */
|
|
69
|
+
export function envNamesOf(contract) {
|
|
70
|
+
const names = [];
|
|
71
|
+
for (const v of Array.isArray(contract?.validate) ? contract.validate : []) {
|
|
72
|
+
const e = Array.isArray(v?.env) ? v.env : typeof v?.env === "string" ? v.env.split(",") : [];
|
|
73
|
+
for (const n of e) { const x = str(n); if (x && !names.includes(x)) names.push(x); }
|
|
74
|
+
}
|
|
75
|
+
return names;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Names plus their `needs` closure in start order; `missing` lists names no entry defines. */
|
|
79
|
+
export function planNeeds(names, specs) {
|
|
80
|
+
const order = [], missing = [], seen = new Set();
|
|
81
|
+
const visit = (n) => {
|
|
82
|
+
if (seen.has(n)) return;
|
|
83
|
+
seen.add(n);
|
|
84
|
+
if (!specs[n]) { if (!missing.includes(n)) missing.push(n); return; }
|
|
85
|
+
for (const d of specs[n].needs) visit(d);
|
|
86
|
+
order.push(n);
|
|
87
|
+
};
|
|
88
|
+
names.forEach(visit);
|
|
89
|
+
return { order, missing };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Images already pulled/inspected by this process: lanes of one batch share it (pass as `cache`), so an image is checked once per batch. */
|
|
93
|
+
export const batchImageCache = new Set();
|
|
94
|
+
|
|
95
|
+
/** A `fixtures` entry replays recorded upstream responses; `record: true` (or FORGE_SANDBOX_RECORD=1, an operator recording run) makes the test write them instead. */
|
|
96
|
+
const recordMode = (s) => /^(true|1|yes)$/i.test(str(s.record)) || process.env.FORGE_SANDBOX_RECORD === "1";
|
|
97
|
+
|
|
98
|
+
/** One FORGE:SANDBOX trajectory line: what was created, how long it lived, what it cost (local docker: 0). */
|
|
99
|
+
export const sandboxLine = ({ name, kind, ms, cost_usd = 0, id = null }) => `FORGE:SANDBOX ${JSON.stringify({ name, kind, ms, cost_usd, ...(id ? { id } : {}) })}`;
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Provision `names` for one lane. Returns `{ok:true, env, created, lines, down}` or `{ok:false, reason, detail}` (reason `unknown_env`,
|
|
103
|
+
* `no_docker` or `failed`; already-created containers are removed first). No names: returns at once, no provider call.
|
|
104
|
+
* `ledger` ({register, release}) gets each container before it is created. `cache` (a Set) skips repeated image checks in a batch.
|
|
105
|
+
*/
|
|
106
|
+
export async function provisionSandboxes({ names, specs, lane, docker, exec, ledger = null, labels = [], cwd = process.cwd(), sleep = (ms) => new Promise((r) => setTimeout(r, ms)), now = () => Date.now(), cache = new Set() }) {
|
|
107
|
+
const empty = { ok: true, env: {}, created: [], lines: [], down: async () => true };
|
|
108
|
+
if (!names?.length) return empty;
|
|
109
|
+
const { order, missing } = planNeeds(names, specs ?? {});
|
|
110
|
+
if (missing.length) return { ok: false, reason: "unknown_env", detail: `validate env ${missing.join(", ")} has no verify.sandboxes entry in forge.yaml` };
|
|
111
|
+
if (order.some((n) => specs[n].image || specs[n].compose)) {
|
|
112
|
+
try { await docker(["version", "--format", "{{.Server.Version}}"]); } catch (e) { return { ok: false, reason: "no_docker", detail: `docker is unavailable on this host (${str(e?.message).split("\n")[0].slice(0, 160)}); the lane must be placed where it runs` }; }
|
|
113
|
+
}
|
|
114
|
+
const env = {}, created = [], lines = [], lab = labels.flatMap((l) => ["--label", l]);
|
|
115
|
+
const prefix = `forge-sbx-${safeSegment(lane)}`;
|
|
116
|
+
const urls = {};
|
|
117
|
+
let net = null; // the lane's own network (`forge-sbx-<lane>-net`): image sandboxes of one lane join it, no other lane's does
|
|
118
|
+
const down = async () => {
|
|
119
|
+
let ok = true;
|
|
120
|
+
for (const c of [...created].reverse()) {
|
|
121
|
+
try { await docker(c.compose ? ["compose", "-p", c.id, "-f", c.compose, "down", "-v"] : ["rm", "-f", "-v", c.id]); ledger?.release("container", c.id); }
|
|
122
|
+
catch (e) { if (!/No such container/i.test(str(e?.message))) ok = false; else ledger?.release("container", c.id); }
|
|
123
|
+
}
|
|
124
|
+
created.length = 0;
|
|
125
|
+
if (net) { try { await docker(["network", "rm", net]); } catch (e) { if (!/No such network|not found/i.test(str(e?.message))) ok = false; } net = null; }
|
|
126
|
+
return ok;
|
|
127
|
+
};
|
|
128
|
+
try {
|
|
129
|
+
for (const name of order) {
|
|
130
|
+
const s = specs[name], t0 = now(), known = KNOWN[name] ?? KNOWN[str(s.image).split(":")[0].split("/").pop()] ?? {};
|
|
131
|
+
if (s.fixtures && !s.image && !s.compose) { const dir = resolve(cwd, s.fixtures), record = recordMode(s);
|
|
132
|
+
env[`${envName(name)}_DIR`] = dir; env[`${envName(name)}_MODE`] = record ? "record" : "replay";
|
|
133
|
+
if (/^http/i.test(name)) { env.SANDBOX_HTTP_REPLAY_DIR = dir; env.SANDBOX_HTTP_REPLAY_MODE = record ? "record" : "replay"; }
|
|
134
|
+
lines.push(sandboxLine({ name, kind: "fixtures", ms: 0 })); continue; }
|
|
135
|
+
const id = `${prefix}-${name}`;
|
|
136
|
+
let url;
|
|
137
|
+
if (s.image) {
|
|
138
|
+
if (!net) { net = `${prefix}-net`; await docker(["network", "rm", net]).catch(() => {}); await docker(["network", "create", ...lab, net]); }
|
|
139
|
+
const port = s.port ?? known.port;
|
|
140
|
+
if (!cache.has(s.image)) { try { await docker(["image", "inspect", s.image]); } catch { await docker(["pull", s.image]); } cache.add(s.image); }
|
|
141
|
+
ledger?.register("container", id, { sandbox: name });
|
|
142
|
+
await docker(["rm", "-f", "-v", id]).catch(() => {}); // a leftover of a crashed run under the same lane name
|
|
143
|
+
created.push({ id });
|
|
144
|
+
await docker(["run", "-d", "--rm", "--name", id, "--network", net, "--network-alias", name, ...lab, ...(port ? ["-p", `127.0.0.1::${port}`] : []), ...(known.env ?? []).flatMap((e) => ["-e", e]), s.image]);
|
|
145
|
+
let hostPort = null;
|
|
146
|
+
if (port) { const m = /:(\d+)\s*$/m.exec(await docker(["port", id, `${port}/tcp`])); hostPort = m ? Number(m[1]) : null; }
|
|
147
|
+
const probe = s.ready ? s.ready.split(/\s+/) : known.ready;
|
|
148
|
+
for (let i = 0; probe; i++) {
|
|
149
|
+
try { await docker(["exec", id, ...probe]); break; } catch { if (i >= 30) throw new Error(`${name} not ready after 30 tries`); await sleep(1000); }
|
|
150
|
+
}
|
|
151
|
+
url = known.url && hostPort ? known.url(hostPort) : hostPort ? `tcp://127.0.0.1:${hostPort}` : "";
|
|
152
|
+
} else {
|
|
153
|
+
const proj = `${prefix}-${name}`;
|
|
154
|
+
ledger?.register("container", proj, { sandbox: name, compose: s.compose });
|
|
155
|
+
created.push({ id: proj, compose: s.compose });
|
|
156
|
+
await docker(["compose", "-p", proj, "-f", s.compose, "up", "-d", "--wait", s.service]);
|
|
157
|
+
url = "";
|
|
158
|
+
}
|
|
159
|
+
urls[name] = url;
|
|
160
|
+
env[`${envName(name)}_URL`] = url;
|
|
161
|
+
if (s.init) {
|
|
162
|
+
const r = await exec({ command: s.init, env: { ...env, SANDBOX_URL: url } });
|
|
163
|
+
if (r?.rc !== 0) throw new Error(`init of ${name} failed (exit ${r?.rc ?? "?"})`);
|
|
164
|
+
}
|
|
165
|
+
lines.push(sandboxLine({ name, kind: s.image ? "container" : "compose", ms: now() - t0, id }));
|
|
166
|
+
}
|
|
167
|
+
} catch (e) {
|
|
168
|
+
await down();
|
|
169
|
+
return { ok: false, reason: "failed", detail: `sandbox ${names.join(", ")} could not start: ${str(e?.message).split("\n")[0].slice(0, 200)}` };
|
|
170
|
+
}
|
|
171
|
+
return { ok: true, env, created, lines, down };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* `forgedock sandbox up <name>... | down | ls` (operators): the lane flow under batch `sandbox`, lane `operator`. `up` prints the
|
|
176
|
+
* exported env, `down` removes what the ledger lists, `ls` lists it. Returns the exit code.
|
|
177
|
+
*/
|
|
178
|
+
export async function sandboxFromCli(args, { cwd = process.cwd(), specs, out = (t) => process.stdout.write(`${t}\n`), docker = null, exec = null, ledger = null, now = () => Date.now() } = {}) {
|
|
179
|
+
const [verb, ...names] = args;
|
|
180
|
+
const px = promisify(execFile);
|
|
181
|
+
const dk = docker ?? (async (a) => (await px("docker", a, { maxBuffer: 10 * 1024 * 1024, timeout: 300000 })).stdout);
|
|
182
|
+
const run = exec ?? (async ({ command, env }) => { try { await px("bash", ["-c", command], { cwd, env: { ...process.env, ...env }, timeout: 600000 }); return { rc: 0 }; } catch (e) { return { rc: Number(e?.code) || 1 }; } });
|
|
183
|
+
const led = ledger ?? makeLedger({ batch: "sandbox", lane: "operator", owner: "forgedock-cli", issue: 0, ttlMs: 24 * 3600 * 1000 });
|
|
184
|
+
if (verb === "ls") { for (const e of led.entries("container")) out(`${e.value}${e.sandbox ? ` (${e.sandbox})` : ""}`); return 0; }
|
|
185
|
+
if (verb === "down") {
|
|
186
|
+
let rc = 0;
|
|
187
|
+
for (const e of led.entries("container")) {
|
|
188
|
+
try { await dk(e.compose ? ["compose", "-p", String(e.value), "-f", e.compose, "down", "-v"] : ["rm", "-f", "-v", String(e.value)]); led.release("container", e.value); out(`removed ${e.value}`); }
|
|
189
|
+
catch (err) { if (/No such container/i.test(String(err?.message))) led.release("container", e.value); else { rc = 1; out(`could not remove ${e.value}`); } }
|
|
190
|
+
}
|
|
191
|
+
led.remove();
|
|
192
|
+
return rc;
|
|
193
|
+
}
|
|
194
|
+
if (verb !== "up" || !names.length) { out("usage: forgedock sandbox up <name>... | down | ls"); return 2; }
|
|
195
|
+
const { readVerify } = specs ? { readVerify: null } : await import("../engine-cli.mjs");
|
|
196
|
+
const all = specs ?? readVerify(cwd)?.sandboxes ?? {};
|
|
197
|
+
const r = await provisionSandboxes({ names, specs: all, lane: "operator", docker: dk, exec: run, ledger: led, labels: dockerLabels({ batch: "sandbox", lane: "operator", issue: 0, expires: now() + 24 * 3600 * 1000 }), cwd, now });
|
|
198
|
+
if (!r.ok) { out(`sandbox ${r.reason}: ${r.detail}`); return 1; }
|
|
199
|
+
for (const [k, v] of Object.entries(r.env)) out(`${k}=${v}`);
|
|
200
|
+
for (const l of r.lines) out(l);
|
|
201
|
+
return 0;
|
|
202
|
+
}
|