forgedock 1.54.0 → 1.55.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 (114) hide show
  1. package/bin/auth/app-token.mjs +2 -0
  2. package/bin/auth/app-token.test.mjs +9 -1
  3. package/bin/engine/events.mjs +1 -0
  4. package/bin/engine/events.test.mjs +5 -1
  5. package/bin/engine/outcome-codes.mjs +3 -0
  6. package/bin/engine-cli.mjs +126 -34
  7. package/bin/forgedock.mjs +56 -4
  8. package/bin/gc-schedule.mjs +83 -0
  9. package/bin/gc.mjs +56 -8
  10. package/bin/help-text.mjs +1 -1
  11. package/bin/hooks/pre-tool-use.mjs +1 -0
  12. package/bin/init-detect.mjs +73 -2
  13. package/bin/labels.json +5 -0
  14. package/bin/lean/admission.mjs +21 -1
  15. package/bin/lean/baselines.mjs +43 -0
  16. package/bin/lean/baselines.test.mjs +33 -0
  17. package/bin/lean/batch-health.mjs +43 -6
  18. package/bin/lean/batch-health.test.mjs +41 -1
  19. package/bin/lean/batch.mjs +41 -4
  20. package/bin/lean/batch.test.mjs +106 -3
  21. package/bin/lean/conformance.mjs +131 -12
  22. package/bin/lean/conformance.test.mjs +172 -3
  23. package/bin/lean/depcache.mjs +23 -2
  24. package/bin/lean/depcache.test.mjs +22 -0
  25. package/bin/lean/docsgate.mjs +137 -0
  26. package/bin/lean/docsgate.test.mjs +78 -0
  27. package/bin/lean/effects.mjs +31 -2
  28. package/bin/lean/enumerating.mjs +39 -13
  29. package/bin/lean/enumerating.test.mjs +20 -0
  30. package/bin/lean/execution.test.mjs +3 -3
  31. package/bin/lean/fastforward.mjs +93 -0
  32. package/bin/lean/fastforward.test.mjs +73 -0
  33. package/bin/lean/guardgate.mjs +38 -7
  34. package/bin/lean/guardgate.test.mjs +39 -0
  35. package/bin/lean/issuewatch-install.mjs +92 -0
  36. package/bin/lean/issuewatch-install.test.mjs +31 -0
  37. package/bin/lean/issuewatch-parity.mjs +33 -3
  38. package/bin/lean/issuewatch-parity.test.mjs +30 -5
  39. package/bin/lean/issuewatch-reconcile.mjs +123 -0
  40. package/bin/lean/issuewatch-reconcile.test.mjs +30 -0
  41. package/bin/lean/issuewatch-verify.mjs +51 -9
  42. package/bin/lean/issuewatch.mjs +153 -33
  43. package/bin/lean/issuewatch.test.mjs +243 -22
  44. package/bin/lean/lean.mjs +381 -75
  45. package/bin/lean/lean.test.mjs +437 -20
  46. package/bin/lean/light.mjs +11 -3
  47. package/bin/lean/light.test.mjs +27 -0
  48. package/bin/lean/lightlane.mjs +8 -3
  49. package/bin/lean/lightlane.test.mjs +20 -0
  50. package/bin/lean/mechfix.mjs +35 -4
  51. package/bin/lean/mechfix.test.mjs +48 -1
  52. package/bin/lean/orchestrate-children.test.mjs +10 -0
  53. package/bin/lean/orchestrate-owned.test.mjs +73 -0
  54. package/bin/lean/orchestrate.mjs +28 -4
  55. package/bin/lean/overlap.mjs +20 -0
  56. package/bin/lean/overlap.test.mjs +49 -0
  57. package/bin/lean/pagegate.mjs +152 -0
  58. package/bin/lean/pagegate.test.mjs +77 -0
  59. package/bin/lean/parked-relabel.mjs +32 -0
  60. package/bin/lean/parked-relabel.test.mjs +45 -0
  61. package/bin/lean/phaseledger.mjs +17 -2
  62. package/bin/lean/postdeploy-check.mjs +27 -0
  63. package/bin/lean/postdeploy-check.test.mjs +13 -1
  64. package/bin/lean/postrun.mjs +32 -0
  65. package/bin/lean/postrun.test.mjs +41 -0
  66. package/bin/lean/preflight.mjs +46 -0
  67. package/bin/lean/preflight.test.mjs +30 -1
  68. package/bin/lean/prompts.mjs +36 -6
  69. package/bin/lean/recovery.test.mjs +16 -0
  70. package/bin/lean/release.mjs +30 -3
  71. package/bin/lean/release.test.mjs +36 -0
  72. package/bin/lean/render.mjs +17 -6
  73. package/bin/lean/reproquality.mjs +116 -0
  74. package/bin/lean/reproquality.test.mjs +85 -0
  75. package/bin/lean/review-trigger.mjs +8 -3
  76. package/bin/lean/sandbox-budget.test.mjs +27 -0
  77. package/bin/lean/schedd.mjs +40 -11
  78. package/bin/lean/schedd.test.mjs +12 -1
  79. package/bin/lean/testadequacy.mjs +97 -0
  80. package/bin/lean/testadequacy.test.mjs +92 -0
  81. package/bin/lean/testsandbox.mjs +202 -0
  82. package/bin/lean/testsandbox.test.mjs +157 -0
  83. package/bin/lean/toolplace.mjs +5 -2
  84. package/bin/lean/toolplace.test.mjs +6 -0
  85. package/bin/lean/verify.mjs +6 -1
  86. package/bin/lean/verify.test.mjs +18 -2
  87. package/bin/lean/warmtree.mjs +77 -0
  88. package/bin/lean/warmtree.test.mjs +81 -0
  89. package/bin/runner.mjs +6 -1
  90. package/bin/stats/conformance-outcomes.mjs +12 -2
  91. package/bin/stats/depth.mjs +24 -1
  92. package/bin/stats/depth.test.mjs +21 -1
  93. package/bin/stats/index.mjs +5 -2
  94. package/bin/stats/query.mjs +2 -1
  95. package/commands/cleanup.md +18 -0
  96. package/commands/fd-introspect.md +19 -0
  97. package/commands/milestone.md +5 -1
  98. package/commands/pipeline-health/phase-2-metrics.md +4 -0
  99. package/commands/recover-orphans.md +31 -1
  100. package/commands/review-pr-staging.md +9 -0
  101. package/commands/review-pr.md +2 -0
  102. package/docs/CI.md +1 -1
  103. package/docs/CONFIG.md +26 -1
  104. package/docs/EVENTS.md +1 -0
  105. package/docs/ISSUE-WATCH.md +12 -3
  106. package/docs/eval/adversarial-bench.md +1 -1
  107. package/docs/eval/published/adversarial-2026-11-11.md +58 -0
  108. package/package.json +1 -1
  109. package/scripts/bench-lightlane.mjs +3 -2
  110. package/scripts/hotspots.sh +7 -4
  111. package/scripts/hotspots.test.sh +12 -0
  112. package/scripts/recover-orphans-stateless.test.sh +79 -0
  113. package/scripts/transition-label.sh +2 -0
  114. package/templates/workflows/forgedock-reopen-clean.yml +33 -0
package/bin/forgedock.mjs CHANGED
@@ -93,7 +93,7 @@ import { checkContext, refreshContextFlow } from "./review-context.mjs";
93
93
  import { runConfigCommand } from "./config-history.mjs";
94
94
  import { validateForgeYaml } from "./config-schema.mjs";
95
95
  import { botTokenStatus } from "./bot-token-status.mjs";
96
- import { applyAuthEnv, startAuthRefresh, doctorAppAuth } from "./auth/app-token.mjs";
96
+ import { applyAuthEnv, startAuthRefresh, doctorAppAuth, AUTH_REFRESH_COMMANDS } from "./auth/app-token.mjs";
97
97
  import {
98
98
  parseNameStatusDiff,
99
99
  classifyCommandChanges,
@@ -995,6 +995,17 @@ async function batchHealthSection(c, batchId) {
995
995
  } catch { /* status never fails on batch health */ }
996
996
  }
997
997
 
998
+ /** #5465: issue-watch health; a dead watch is flagged and alerted once (events.webhook_url). */
999
+ async function watchHealthSection(c) {
1000
+ try {
1001
+ const [{ listWatches, alertDeadWatches }, { watchRoot }, { makeEventEmitter }, { readEvents }] = await Promise.all([import("./lean/issuewatch-parity.mjs"), import("./lean/issuewatch.mjs"), import("./engine/events.mjs"), import("./engine-cli.mjs")]);
1002
+ const rows = listWatches(watchRoot());
1003
+ if (!rows.length) return;
1004
+ await alertDeadWatches({ root: watchRoot(), emit: (type, data, ctx) => makeEventEmitter({ repo: ctx.repo, config: readEvents(c.cwd) }).emitEvent(type, data, ctx) });
1005
+ c.stdout.write(` issue-watch\n${rows.map((w) => ` ${w.name} (${w.repo}): ${w.live.state === "dead" ? "DEAD" : w.live.state}${["dead", "exited"].includes(w.live.state) ? ` - ${w.live.reason}` : ""}`).join("\n")}\n\n`);
1006
+ } catch { /* status never fails on watch health */ }
1007
+ }
1008
+
998
1009
  /** Compact status screen for configured/managed directories. */
999
1010
  /** #5174: the status `host` row: the host_overloaded line, else `load X.X/core ...`; null (rendered `unknown`) on any failure. */
1000
1011
  async function hostLoadRow(cwd) {
@@ -1084,6 +1095,18 @@ function ensureToolStateIgnored(c) {
1084
1095
  } catch { /* .gitignore is best effort */ }
1085
1096
  }
1086
1097
 
1098
+ /** #5421: install (or remove) the scheduled `gc --apply` timer from forge.yaml hygiene.schedule; silent when nothing is set. */
1099
+ async function installHygieneSchedule(cwd, write = () => {}) {
1100
+ try {
1101
+ const gc = await import("./gc.mjs");
1102
+ const h = gc.readHygiene(cwd);
1103
+ const { installGcSchedule } = await import("./gc-schedule.mjs");
1104
+ const r = await installGcSchedule({ schedule: h.schedule, enabled: h.auto_gc, cwd });
1105
+ if (r.status !== "off") write(` Hygiene schedule: ${r.status} (${r.kind}) ${r.detail}\n`);
1106
+ return r;
1107
+ } catch { return null; }
1108
+ }
1109
+
1087
1110
  async function initFlow(c) {
1088
1111
  const outputPath = join(c.cwd, "forge.yaml");
1089
1112
  if (flags.includes("--refresh-context")) {
@@ -1142,9 +1165,11 @@ async function initFlow(c) {
1142
1165
  worktreeBase: draft.paths.worktreeBase.value,
1143
1166
  defaultBranch: draft.branches.default.value,
1144
1167
  stagingBranch: draft.branches.staging.value,
1168
+ sandboxes: draft.meta?.sandboxes, // #5450: commented verify.sandboxes proposal
1145
1169
  });
1146
1170
  atomicWriteFile(outputPath, content);
1147
1171
  ensureToolStateIgnored(c);
1172
+ await installHygieneSchedule(c.cwd, (m) => c.stdout.write(m));
1148
1173
  celebrate(c, { written: true, todoCount: 0, isMinimal: true });
1149
1174
  await maybeOfferDemo(c);
1150
1175
  return 0;
@@ -3328,7 +3353,16 @@ async function doctor(fix = false, verbose = false) {
3328
3353
  const plan = await gc.planGc({ probes, ttlMs: gc.hygieneTtls(h), deleteMergedBranches: h.delete_merged_branches });
3329
3354
  const applied = fix ? await gc.applyGc(plan, probes) : null;
3330
3355
  if (applied && applied.reclaimed.length > 0) fixesApplied++;
3331
- const r = gc.hygieneCheck(plan, { applied });
3356
+ // #5421: free disk on the worktree root and ~/.forge against hygiene.min_free_gb; --fix also installs the timer.
3357
+ let disk = null;
3358
+ try {
3359
+ const host = (await import("./lean/effects.mjs")).makeHostProbe();
3360
+ const mbs = [];
3361
+ for (const p of host.hygienePaths(process.cwd())) { try { mbs.push(await host.freeMb(p)); } catch { /* unreadable path */ } }
3362
+ if (mbs.length) disk = { freeGb: Math.min(...mbs) / 1024, minFreeGb: h.min_free_gb };
3363
+ } catch { disk = null; }
3364
+ let r = gc.hygieneCheck(plan, { applied, disk });
3365
+ if (fix && h.schedule) { const sr = await installHygieneSchedule(process.cwd()); if (sr?.status === "installed") fixesApplied++; if (sr?.status === "failed") r = { ...r, detail: `${r.detail}; schedule: ${sr.detail}` }; }
3332
3366
  if (r.status === "pass") pass("Resource hygiene", r.detail);
3333
3367
  else warn("Resource hygiene", r.detail);
3334
3368
  } catch (e) {
@@ -3920,7 +3954,7 @@ async function watch() {
3920
3954
  const SPLASH_COMMANDS = new Set(["run", "bootstrap", "run-issue", "orchestrate", "triage", "probe", "gc", "resume-stalled", "demo", "first-run", "doctor", "watch", "help", "--help", "-h"]);
3921
3955
  const KNOWN_COMMANDS = new Set([
3922
3956
  "install", "init", "enable", "disable", "status", "uninstall", "update",
3923
- "run", "bootstrap", "backend-check", "run-issue", "orchestrate", "milestone", "milestone-sync", "fix-close-reasons", "guards", "triage", "probe", "acceptance", "review-staging", "release", "gc", "resume-stalled", "demo", "first-run", "doctor", "auth", "watch", "issue-watch", "prod-watch", "selftest", "labels", "config", "stats", "limits", "decisions", "sched", "schedd", "pool", "check", "guide", "help", "--help", "-h",
3957
+ "run", "bootstrap", "backend-check", "run-issue", "orchestrate", "milestone", "milestone-sync", "fix-close-reasons", "guards", "triage", "probe", "acceptance", "docs", "review-staging", "release", "gc", "sandbox", "resume-stalled", "demo", "first-run", "doctor", "auth", "watch", "issue-watch", "prod-watch", "selftest", "labels", "config", "stats", "limits", "decisions", "sched", "schedd", "pool", "check", "guide", "help", "--help", "-h",
3924
3958
  "version", "--version", "-v",
3925
3959
  ]);
3926
3960
  if (SPLASH_COMMANDS.has(command) || !KNOWN_COMMANDS.has(command)) splash(command);
@@ -3929,7 +3963,7 @@ let exitCode = 0;
3929
3963
  // #5301: an App login puts a scoped installation token in this process's env (GH_TOKEN) for child gh calls; no login, no change.
3930
3964
  if (command !== "auth") await applyAuthEnv();
3931
3965
  // #5381: installation tokens live 1h; long-running commands re-resolve before expiry so later gh calls and lanes inherit a fresh one.
3932
- if (["orchestrate", "schedd", "watch", "issue-watch", "prod-watch"].includes(command)) startAuthRefresh();
3966
+ if (AUTH_REFRESH_COMMANDS.has(command)) startAuthRefresh();
3933
3967
  switch (command) {
3934
3968
  case "install": {
3935
3969
  const c = ctx();
@@ -4012,6 +4046,7 @@ switch (command) {
4012
4046
  if (statusDir) c.cwd = resolve(statusDir);
4013
4047
  await statusScreen(c);
4014
4048
  await batchHealthSection(c, bi === -1 ? null : statusArgs[bi + 1] ?? null);
4049
+ await watchHealthSection(c);
4015
4050
  break;
4016
4051
  }
4017
4052
  case "uninstall":
@@ -4156,6 +4191,12 @@ switch (command) {
4156
4191
  exitCode = await runGc(restArgs);
4157
4192
  break;
4158
4193
  }
4194
+ case "sandbox": {
4195
+ // #5450: operator control of the lane test sandboxes (verify.sandboxes): up <name>... | down | ls
4196
+ const { sandboxFromCli } = await import("./lean/testsandbox.mjs");
4197
+ exitCode = await sandboxFromCli(restArgs);
4198
+ break;
4199
+ }
4159
4200
  case "orchestrate": {
4160
4201
  const { orchestrateFromCli } = await import("./engine-cli.mjs");
4161
4202
  try {
@@ -4358,6 +4399,17 @@ switch (command) {
4358
4399
  }
4359
4400
  break;
4360
4401
  }
4402
+ case "docs": {
4403
+ // Docs gate (#5419): `forgedock docs gate --milestone T --repo owner/repo`.
4404
+ const { docsFromCli } = await import("./lean/docsgate.mjs");
4405
+ try {
4406
+ exitCode = await docsFromCli(restArgs);
4407
+ } catch (err) {
4408
+ process.stderr.write(`${RED}${err.message}${RESET}\n`);
4409
+ exitCode = 1;
4410
+ }
4411
+ break;
4412
+ }
4361
4413
  case "replan": {
4362
4414
  // Re-plan loop (#5342): `forgedock replan apply --amendment N --repo owner/repo`.
4363
4415
  const { replanFromCli } = await import("./lean/replan.mjs");
@@ -0,0 +1,83 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Scheduled hygiene outside batches (#5421): `forgedock gc --apply` (owned scope only) on a systemd user timer, with a cron
5
+ * entry as the fallback, driven by forge.yaml `hygiene.schedule` ("6h", "30m", "2d"). Installed by `doctor --fix` and
6
+ * `forgedock init`. An empty schedule or `hygiene.auto_gc: false` removes the entry. All I/O is injected (`exec`, `fs`).
7
+ */
8
+ import * as nodeFs from "node:fs";
9
+ import { createHash } from "node:crypto";
10
+ import { execFile } from "node:child_process";
11
+ import { promisify } from "node:util";
12
+ import { homedir } from "node:os";
13
+ import { dirname, join, resolve } from "node:path";
14
+ import { fileURLToPath } from "node:url";
15
+ import { parseDuration } from "./gc.mjs";
16
+
17
+ const pexec = promisify(execFile);
18
+ const CRON_TAG = "# forgedock-gc";
19
+
20
+ /** Unit basename for one repo: `forgedock-gc-<8 hex of the repo path>`. */
21
+ export const unitName = (cwd) => `forgedock-gc-${createHash("sha1").update(resolve(cwd)).digest("hex").slice(0, 8)}`;
22
+
23
+ const q = (s) => `"${String(s).replace(/(["\\$`])/g, "\\$1")}"`;
24
+ const forgedockBin = () => join(dirname(fileURLToPath(import.meta.url)), "forgedock.mjs");
25
+
26
+ /** systemd service + timer text. OnUnitActiveSec is the schedule; Persistent catches up a run missed while the host was off. */
27
+ export function renderSystemd({ schedule, cwd, node = process.execPath, bin = forgedockBin() }) {
28
+ const min = Math.max(1, Math.round(parseDuration(schedule) / 60000));
29
+ return {
30
+ service: `[Unit]\nDescription=ForgeDock owned-resource GC (${resolve(cwd)})\n\n[Service]\nType=oneshot\nWorkingDirectory=${resolve(cwd)}\nExecStart=${q(node)} ${q(bin)} gc --apply\n`,
31
+ timer: `[Unit]\nDescription=ForgeDock owned-resource GC every ${schedule}\n\n[Timer]\nOnBootSec=5min\nOnUnitActiveSec=${min}min\nPersistent=true\n\n[Install]\nWantedBy=timers.target\n`,
32
+ };
33
+ }
34
+
35
+ /** One crontab line (tagged so it can be replaced or removed): minutes < 60, whole hours < 24, else daily. */
36
+ export function renderCron({ schedule, cwd, node = process.execPath, bin = forgedockBin() }) {
37
+ const min = Math.max(1, Math.round(parseDuration(schedule) / 60000));
38
+ const when = min < 60 ? `*/${min} * * * *` : min < 1440 ? `0 */${Math.max(1, Math.round(min / 60))} * * *` : "0 0 * * *";
39
+ return `${when} cd ${q(resolve(cwd))} && ${q(node)} ${q(bin)} gc --apply >/dev/null 2>&1 ${CRON_TAG} ${resolve(cwd)}`;
40
+ }
41
+
42
+ /**
43
+ * Install (or remove) the schedule. `enabled` is hygiene.auto_gc. Returns {status, kind, detail}; status is
44
+ * installed | removed | off | failed. Never throws.
45
+ */
46
+ export async function installGcSchedule({ schedule = "", enabled = true, cwd = process.cwd(), home = homedir(), platform = process.platform, fs = nodeFs, exec = async (cmd, args, input) => { const p = pexec(cmd, args, { timeout: 30000 }); if (input != null) p.child.stdin.end(input); return (await p).stdout; }, node, bin } = {}) {
47
+ const name = unitName(cwd);
48
+ const dir = join(home, ".config", "systemd", "user");
49
+ const want = enabled && !!schedule;
50
+ const opts = { schedule, cwd, ...(node ? { node } : {}), ...(bin ? { bin } : {}) };
51
+ try {
52
+ if (platform === "linux") {
53
+ let hasSystemd = false;
54
+ try { await exec("systemctl", ["--user", "show-environment"]); hasSystemd = true; } catch { hasSystemd = false; }
55
+ if (hasSystemd) {
56
+ if (!want) {
57
+ if (!fs.existsSync(join(dir, `${name}.timer`))) return { status: "off", kind: "systemd", detail: "no schedule set" };
58
+ try { await exec("systemctl", ["--user", "disable", "--now", `${name}.timer`]); } catch { /* already gone */ }
59
+ for (const f of [`${name}.timer`, `${name}.service`]) fs.rmSync(join(dir, f), { force: true });
60
+ return { status: "removed", kind: "systemd", detail: `removed ${name}.timer` };
61
+ }
62
+ const { service, timer } = renderSystemd(opts);
63
+ fs.mkdirSync(dir, { recursive: true });
64
+ fs.writeFileSync(join(dir, `${name}.service`), service);
65
+ fs.writeFileSync(join(dir, `${name}.timer`), timer);
66
+ await exec("systemctl", ["--user", "daemon-reload"]);
67
+ await exec("systemctl", ["--user", "enable", "--now", `${name}.timer`]);
68
+ return { status: "installed", kind: "systemd", detail: `${name}.timer every ${schedule}` };
69
+ }
70
+ }
71
+ // cron fallback: replace our tagged line for this repo, keep every other line.
72
+ let cur = "";
73
+ try { cur = String(await exec("crontab", ["-l"])); } catch { cur = ""; }
74
+ const mine = (l) => l.trimEnd().endsWith(`${CRON_TAG} ${resolve(cwd)}`); // end-anchored: `/work/repo` must not match `/work/repo2`
75
+ const rest = cur.split("\n").filter((l) => l.trim() && !mine(l));
76
+ if (!want && rest.length === cur.split("\n").filter((l) => l.trim()).length) return { status: "off", kind: "cron", detail: "no schedule set" };
77
+ const next = [...rest, ...(want ? [renderCron(opts)] : [])];
78
+ await exec("crontab", ["-"], next.join("\n") + "\n");
79
+ return want ? { status: "installed", kind: "cron", detail: `crontab entry every ${schedule}` } : { status: "removed", kind: "cron", detail: "removed crontab entry" };
80
+ } catch (e) {
81
+ return { status: "failed", kind: "unknown", detail: String(e?.message ?? e).slice(0, 200) };
82
+ }
83
+ }
package/bin/gc.mjs CHANGED
@@ -57,7 +57,9 @@ export function parseGcArgs(argv = []) {
57
57
  }
58
58
 
59
59
  /** forge.yaml `hygiene:` defaults (#4183). TTLs in hours; `max_host_load_ratio` is the near-ceiling trigger for orchestrate GC. */
60
- export const HYGIENE_DEFAULTS = Object.freeze({ container_ttl_hours: 6, worktree_ttl_hours: 24, tmp_ttl_hours: 6, delete_merged_branches: true, max_host_load_ratio: 0.8, auto_gc: true });
60
+ export const HYGIENE_DEFAULTS = Object.freeze({ container_ttl_hours: 6, worktree_ttl_hours: 24, tmp_ttl_hours: 6, delete_merged_branches: true, max_host_load_ratio: 0.8, auto_gc: true, schedule: "", min_free_gb: 5 });
61
+ /** Compose projects a lane starts are named `forgedock-lane-<issue>` (#5421); their containers and volumes are owned by that name. */
62
+ export const LANE_COMPOSE_RE = /^forgedock-lane-\d+/;
61
63
 
62
64
  /** Top-level forge.yaml `hygiene:` block (block form only); each missing or invalid value falls back to its default. */
63
65
  export function readHygiene(cwd = process.cwd(), { fs = nodeFs } = {}) {
@@ -67,7 +69,13 @@ export function readHygiene(cwd = process.cwd(), { fs = nodeFs } = {}) {
67
69
  const hours = (k) => { const v = h[k], n = Number(v); return v !== undefined && v !== "" && Number.isFinite(n) && n >= 0 ? n : HYGIENE_DEFAULTS[k]; };
68
70
  const bool = (k) => { const v = String(h[k] ?? "").trim().toLowerCase(); return v === "true" ? true : v === "false" ? false : HYGIENE_DEFAULTS[k]; };
69
71
  const ratio = Number(h.max_host_load_ratio);
72
+ // #5421: `schedule` ("6h", "30m", "2d"; empty/off/invalid = no timer) and the free-disk threshold in GB (0 = off).
73
+ const sched = String(h.schedule ?? "").trim().toLowerCase();
74
+ let schedule = "";
75
+ if (sched && sched !== "off" && sched !== "false") { try { parseDuration(sched); schedule = sched; } catch { schedule = ""; } }
76
+ const gb = Number(h.min_free_gb);
70
77
  return {
78
+ schedule, min_free_gb: h.min_free_gb !== undefined && h.min_free_gb !== "" && Number.isFinite(gb) && gb >= 0 ? gb : HYGIENE_DEFAULTS.min_free_gb,
71
79
  container_ttl_hours: hours("container_ttl_hours"), worktree_ttl_hours: hours("worktree_ttl_hours"), tmp_ttl_hours: hours("tmp_ttl_hours"),
72
80
  delete_merged_branches: bool("delete_merged_branches"), auto_gc: bool("auto_gc"),
73
81
  max_host_load_ratio: h.max_host_load_ratio !== undefined && h.max_host_load_ratio !== "" && ratio > 0 && ratio <= 1 ? ratio : HYGIENE_DEFAULTS.max_host_load_ratio,
@@ -108,6 +116,7 @@ export function makeGcProbes({ cwd = process.cwd(), home = homedir() } = {}) {
108
116
  ledgerRoot: home === homedir() ? defaultLedgerRoot() : join(home, ".forge", "ledger"),
109
117
  forgeTmpRoot: join(home, ".forge", "tmp"),
110
118
  worktreeRoot: join(cwd, ".claude", "worktrees"),
119
+ legacyWorktreeRoot: join(cwd, ".forge", "worktrees"),
111
120
  protectedBranches: ["main", "master", "staging", b.default, b.staging].filter(Boolean),
112
121
  alive: pidAlive, ppid: (pid) => ppidFromProc(pid), procsInDir: (d) => procsInDir(d),
113
122
  killPid: async (pid, marker) => killLedgerPid(pid, marker),
@@ -272,7 +281,8 @@ export async function planGc({ probes, scopes = new Set(GC_SCOPES), olderThanMs
272
281
  // ---- 2. docker: labelled forgedock.owner=1 is owned; everything else is "not owned" ----
273
282
  if (want("container") || want("volume")) {
274
283
  const ownedBy = (labels, createdMs, type) => {
275
- if (labels["forgedock.owner"] !== "1") return { owned: false, action: "report", reason: "not owned" };
284
+ const lane = LANE_COMPOSE_RE.test(String(labels["com.docker.compose.project"] ?? "")); // #5421: lane compose project by name
285
+ if (labels["forgedock.owner"] !== "1" && !lane) return { owned: false, action: "report", reason: "not owned" };
276
286
  let exp = Number(labels["forgedock.expires"]);
277
287
  if (Number.isFinite(exp) && exp > 0 && exp < 1e12) exp *= 1000;
278
288
  if (Number.isFinite(exp) && exp > 0 && exp < now) return { owned: true, action: "reclaim", reason: "forgedock label, expired" };
@@ -294,7 +304,7 @@ export async function planGc({ probes, scopes = new Set(GC_SCOPES), olderThanMs
294
304
  try {
295
305
  const vols = jsonLines(await P.docker(["volume", "ls", "--format", "{{json .}}"]));
296
306
  const created = new Map();
297
- const labelled = vols.filter((v) => parseLabels(v.Labels)["forgedock.owner"] === "1").map((v) => v.Name);
307
+ const labelled = vols.filter((v) => { const l = parseLabels(v.Labels); return l["forgedock.owner"] === "1" || LANE_COMPOSE_RE.test(String(l["com.docker.compose.project"] ?? "")); }).map((v) => v.Name);
298
308
  if (labelled.length) {
299
309
  try { for (const l of String(await P.docker(["volume", "inspect", "--format", "{{.Name}}\t{{.CreatedAt}}", ...labelled])).split("\n")) { const [n, t] = l.split("\t"); if (n) created.set(n, Date.parse(t)); } }
300
310
  catch { /* age unknown: kept unless expired */ }
@@ -329,6 +339,27 @@ export async function planGc({ probes, scopes = new Set(GC_SCOPES), olderThanMs
329
339
  }
330
340
  }
331
341
 
342
+ // ---- 3b. legacy <repo>/.forge/worktrees/* (#5421): reported; reclaimed only when clean, HEAD on a remote, no live process ----
343
+ if (want("worktree") && worktreeListOk && P.legacyWorktreeRoot) {
344
+ let names = [];
345
+ try { names = fs.readdirSync(P.legacyWorktreeRoot); } catch { /* no legacy root */ }
346
+ for (const n of names) {
347
+ const dir = resolve(join(P.legacyWorktreeRoot, n));
348
+ if (seen.has(`worktree:${dir}`) || liveIds.has(`worktree:${dir}`)) continue;
349
+ try { if (!fs.lstatSync(dir).isDirectory()) continue; } catch { continue; }
350
+ const reg = registered.has(dir);
351
+ const it = { type: "worktree", id: dir, sizeBytes: P.dirSize?.(dir) ?? null, ageMs: age(mtime(dir)), owned: false, action: "report", reason: "", registered: reg, legacy: true };
352
+ const procs = P.procsInDir?.(dir) ?? [];
353
+ const w = await workIn(dir);
354
+ if (procs.length) it.reason = "legacy orchestrator dir, live process inside";
355
+ else if (w) it.reason = `legacy orchestrator dir, ${w}`;
356
+ else if (w === null) it.reason = "legacy orchestrator dir, cannot inspect";
357
+ else if (!(it.ageMs >= ttl("worktree"))) it.reason = "legacy orchestrator dir, younger than TTL";
358
+ else { it.owned = true; it.action = "reclaim"; it.reason = "legacy orchestrator dir, clean and on a remote"; }
359
+ add(it);
360
+ }
361
+ }
362
+
332
363
  // ---- 4. branches: feat/issue-<n>-lean, local and origin, abandoned (closed or invalid issue) and older than TTL ----
333
364
  if (want("branch")) {
334
365
  const scan = async (ref, local) => {
@@ -398,7 +429,20 @@ export async function planGc({ probes, scopes = new Set(GC_SCOPES), olderThanMs
398
429
  if (!st.isDirectory()) { add({ type: "tmp", id: resolve(p), sizeBytes: st.size, ageMs: age(st.mtimeMs), owned: false, action: "report", reason: "unrecognised entry" }); continue; }
399
430
  let kids = []; try { kids = fs.readdirSync(p); } catch { /* unreadable */ }
400
431
  const scratch = kids.length > 0 && kids.every((k) => /^\d+$/.test(k));
401
- if (!scratch) { add({ type: "tmp", id: resolve(p), sizeBytes: P.dirSize?.(p) ?? null, ageMs: age(st.mtimeMs), owned: false, action: "report", reason: "unrecognised entry" }); continue; }
432
+ if (!scratch) {
433
+ // #5421: a top-level scratch dir with a run-owner marker follows the run-dir rule (stale, owner dead on this host).
434
+ let own = null; try { own = JSON.parse(fs.readFileSync(join(p, RUN_OWNER), "utf8")); } catch { /* unmarked */ }
435
+ if (own) {
436
+ const dir = resolve(p), it = { type: "tmp", id: dir, sizeBytes: P.dirSize?.(dir) ?? null, ageMs: age(Number(own.created)), owned: true, action: "report", reason: "", runDir: true };
437
+ if (!(it.ageMs >= ttl("tmp"))) it.reason = "younger than TTL";
438
+ else if (own.host !== P.host) it.reason = "owner on another host";
439
+ else if (Number.isSafeInteger(own.pid) && P.alive(own.pid)) it.reason = "owner alive";
440
+ else { it.action = "reclaim"; it.reason = "stale marked scratch, owner dead"; }
441
+ add(it);
442
+ continue;
443
+ }
444
+ add({ type: "tmp", id: resolve(p), sizeBytes: P.dirSize?.(p) ?? null, ageMs: age(st.mtimeMs), owned: false, action: "report", reason: "unrecognised entry" }); continue;
445
+ }
402
446
  for (const k of kids) {
403
447
  const dir = resolve(join(p, k));
404
448
  if (seen.has(`tmp:${dir}`) || liveIds.has(`tmp:${dir}`)) continue;
@@ -492,7 +536,7 @@ export async function applyGc(plan, probes, { deadline = null, now = () => Date.
492
536
  case "worktree":
493
537
  if (it.registered) await git(["worktree", "remove", "--force", it.id]);
494
538
  else if (fs.existsSync(it.id)) {
495
- if (!isDirectChild(P.worktreeRoot, it.id)) throw new Error("not a direct child of the worktree root");
539
+ if (!isDirectChild(P.worktreeRoot, it.id) && !(it.legacy && P.legacyWorktreeRoot && isDirectChild(P.legacyWorktreeRoot, it.id))) throw new Error("not a direct child of the worktree root");
496
540
  fs.rmSync(it.id, { recursive: true, force: true });
497
541
  }
498
542
  prune = true;
@@ -592,7 +636,7 @@ export async function runOwnedGc({ probes, hygiene = HYGIENE_DEFAULTS, scopes =
592
636
  * doctor's "Resource hygiene" line (#4183): owned counts/sizes per type, reclaimable count, and unowned items older than
593
637
  * their type TTL (reported only, never touched). warn when something is reclaimable (and not applied) or unowned-stale.
594
638
  */
595
- export function hygieneCheck(plan, { applied = null, ttlMs = plan?.ttlMs ?? hygieneTtls() } = {}) {
639
+ export function hygieneCheck(plan, { applied = null, ttlMs = plan?.ttlMs ?? hygieneTtls(), disk = null } = {}) {
596
640
  const items = plan?.items ?? [];
597
641
  const parts = [];
598
642
  for (const t of GC_TYPES) {
@@ -608,8 +652,12 @@ export function hygieneCheck(plan, { applied = null, ttlMs = plan?.ttlMs ?? hygi
608
652
  else bits.push(`${reclaimable} reclaimable`);
609
653
  if (stale) bits.push(`${stale} unowned stale (report only)`);
610
654
  const pending = applied ? applied.failed.length + (applied.deferred?.length ?? 0) : reclaimable;
611
- const status = pending > 0 || stale > 0 ? "warn" : "pass";
655
+ // #5421: free disk below hygiene.min_free_gb warns, with the owned bytes a reclaim would free.
656
+ const ownedBytes = items.filter((i) => i.owned && i.action === "reclaim").reduce((s, i) => s + (i.sizeBytes ?? 0), 0);
657
+ const low = !!disk && Number.isFinite(disk.freeGb) && Number.isFinite(disk.minFreeGb) && disk.minFreeGb > 0 && disk.freeGb < disk.minFreeGb;
658
+ if (low) bits.push(`free disk ${disk.freeGb.toFixed(1)} GB < ${disk.minFreeGb} GB (hygiene.min_free_gb); ${fmtSize(ownedBytes)} owned reclaimable`);
659
+ const status = pending > 0 || stale > 0 || low ? "warn" : "pass";
612
660
  let detail = bits.join("; ");
613
661
  if (!applied && reclaimable > 0) detail += ". Run: npx forgedock doctor --fix (or: npx forgedock gc --apply)";
614
- return { status, detail, reclaimable, stale };
662
+ return { status, detail, reclaimable, stale, lowDisk: low, ownedBytes };
615
663
  }
package/bin/help-text.mjs CHANGED
@@ -67,7 +67,7 @@ export const FULL_COMMAND_GROUPS = [
67
67
  ["npx forgedock run-issue <issue> [--lane <lane>] [--lane-override] [--path core|full] [--retry] [--wait-lease]", "Work one issue from claim to merge (the lane comes from the issue: its milestone, else staging; --lane only asserts it). --retry reopens a failed run, or one needing a human once the label is cleared; --wait-lease waits for another holder of the issue; exit status 75 means deferred, nothing was lost"],
68
68
  ["npx forgedock plan validate --live [--repo owner/repo] [--json]", "Re-run the bootstrap dependency-order rules on live GitHub state: each cross-milestone Depends-on edge is ok, held or invalid (fails on invalid)"],
69
69
  ["npx forgedock orchestrate <issue...> [--parallel K] [--lane L]", "Work on several issues with bounded concurrency and Depends-on ordering; each issue on its own lane, cross-lane dependencies reported"],
70
- ["npx forgedock orchestrate --resume <id> [N...] | --set-parallel <id> K | --set-max-remote <id> N | --set-placement <id> remote|hybrid|local | --add <id> N... | --requeue <id> N... [--reason \"...\"] | --cancel <id> | --hold <id> N... | --release <id> N... | --show-env <id> | --set-env <id> KEY=VAL | --unset-env <id> KEY", "Reattach to a running or finished batch (a finished one replays its report, an interrupted one resumes), change its concurrency or placement live, add, requeue, hold or release single issues, stop one batch without stopping the background scheduler, or print, set or unset the batch environment (secrets redacted; applies to newly started lanes)"],
70
+ ["npx forgedock orchestrate --resume <id> [N...] | --set-parallel <id> K | --set-max-remote <id> N | --set-placement <id> remote|hybrid|local | --add <id> N... | --requeue <id> N... [--reason \"...\"] | --cancel <id> | --hold <id> N... [--for 4h] [--reason \"...\"] | --adopt <issue> | --gc-orphans | --release <id> N... | --show-env <id> | --set-env <id> KEY=VAL | --unset-env <id> KEY", "Reattach to a running or finished batch (a finished one replays its report, an interrupted one resumes), change its concurrency or placement live, add, requeue, hold (with an owner and an optional expiry, --for) or release single issues, adopt an open hand-built PR, cancel orphaned batches (--gc-orphans), stop one batch without stopping the background scheduler, or print, set or unset the batch environment (secrets redacted; applies to newly started lanes)"],
71
71
  ["npx forgedock triage <issue...> [--lane L] [--dry-run]", "Already-fixed pre-filter: close issues a merged PR or green CI already resolved; print the rest"],
72
72
  ["npx forgedock probe [issue...] [--dry-run]", "Run declared acceptance probes for closed issues whose fix is on the default branch; a fail reopens the issue"],
73
73
  ["npx forgedock acceptance check|run|gate", "Feature-level acceptance: validate an epic's journeys, run them on the milestone branch, gate ship/close on a green run"],
@@ -202,6 +202,7 @@ const LABEL_TRANSITIONS = {
202
202
  "workflow:remediating": ["workflow:in-review", "workflow:awaiting-merge", "workflow:merged", "workflow:invalid"], // #3541/#3565: remediation → re-review/merge; evidenced reversal allowed
203
203
  "workflow:awaiting-merge": ["workflow:merged", "workflow:in-review", "workflow:remediating", "workflow:invalid"], // #1810/#3565: merge queue; evidenced reversal allowed
204
204
  "workflow:merged": [], // terminal — no successors
205
+ "workflow:merged-unverified": [], // terminal — a human decides (#5443)
205
206
  "workflow:invalid": [], // terminal
206
207
  "workflow:decomposed": [], // terminal
207
208
  };
@@ -26,7 +26,7 @@
26
26
 
27
27
  import { execFileSync } from "child_process";
28
28
  import { join, resolve } from "path";
29
- import { readdirSync, existsSync } from "fs";
29
+ import { readdirSync, existsSync, readFileSync } from "fs";
30
30
 
31
31
  // ---------------------------------------------------------------------------
32
32
  // Field factory helpers
@@ -474,10 +474,80 @@ export async function detectConfig(cwd = process.cwd()) {
474
474
  remoteDetected,
475
475
  ...repoState,
476
476
  stagingMissing: stagingBranchField.source !== "git branch -r",
477
+ sandboxes: detectSandboxes(gitRoot),
477
478
  },
478
479
  };
479
480
  }
480
481
 
482
+ // ---------------------------------------------------------------------------
483
+ // verify.sandboxes proposal (#5450)
484
+ // ---------------------------------------------------------------------------
485
+
486
+ const COMPOSE_FILES = ["docker-compose.test.yml", "docker-compose.test.yaml", "compose.test.yml", "docker-compose.yml", "docker-compose.yaml", "compose.yml", "compose.yaml"];
487
+ const MIGRATION_DIRS = ["migrations", "db/migrate", "db/migrations", "alembic", "prisma/migrations", "drizzle", "supabase/migrations"];
488
+ const TEST_MARKERS = ["pytest.ini", "conftest.py", "tox.ini", "jest.config.js", "jest.config.ts", "vitest.config.ts", "vitest.config.js"];
489
+
490
+ /** Services (name -> image|null) from a compose file's text; indentation-based, no YAML dependency. */
491
+ function composeServices(text) {
492
+ const out = {};
493
+ let inServices = false, cur = null;
494
+ for (const line of String(text).split("\n")) {
495
+ if (/^\S/.test(line)) { inServices = /^services\s*:/.test(line); cur = null; continue; }
496
+ if (!inServices) continue;
497
+ const svc = /^ {1,4}([A-Za-z0-9_.-]+)\s*:\s*$/.exec(line);
498
+ if (svc) { cur = svc[1]; out[cur] = null; continue; }
499
+ const img = /^\s+image\s*:\s*["']?([^\s"']+)/.exec(line);
500
+ if (img && cur) out[cur] = img[1];
501
+ }
502
+ return out;
503
+ }
504
+
505
+ /**
506
+ * Propose `verify.sandboxes` from compose files, migration directories and test markers. Pure over `fs` ({existsSync, readFileSync});
507
+ * returns `{name: "{ image: ... }"}` one-line entries (the forge.yaml form), `{}` when nothing is detected. Postgres/redis
508
+ * services become image entries; other compose services become compose entries that need them; migrations without a compose
509
+ * postgres propose one with a migrate `init` placeholder. A proposal only: init writes it commented.
510
+ */
511
+ export function detectSandboxes(cwd, fs = { existsSync, readFileSync }) {
512
+ const out = {};
513
+ const compose = COMPOSE_FILES.find((f) => fs.existsSync(join(cwd, f)));
514
+ const hasMigrations = MIGRATION_DIRS.some((d) => fs.existsSync(join(cwd, d)));
515
+ const hasTests = TEST_MARKERS.some((f) => fs.existsSync(join(cwd, f)));
516
+ if (compose) {
517
+ let svcs = {};
518
+ try { svcs = composeServices(fs.readFileSync(join(cwd, compose), "utf8")); } catch { /* unreadable: no proposal from it */ }
519
+ const infra = [];
520
+ for (const [name, image] of Object.entries(svcs)) {
521
+ const base = String(image ?? "").split(":")[0].split("/").pop();
522
+ if (base === "postgres" || base === "redis") { out[base] = `{ image: ${image} }`; infra.push(base); }
523
+ }
524
+ for (const [name, image] of Object.entries(svcs)) {
525
+ const base = String(image ?? "").split(":")[0].split("/").pop();
526
+ if (base === "postgres" || base === "redis" || !/^[a-z][a-z0-9_-]*$/.test(name)) continue;
527
+ out[name] = `{ compose: ${compose}, service: ${name}${infra.length ? `, needs: [${infra.join(", ")}]` : ""} }`;
528
+ }
529
+ }
530
+ if (hasMigrations && !out.postgres && (hasTests || compose)) out.postgres = '{ image: postgres:16, init: "<your migrate command> $SANDBOX_URL" }';
531
+ else if (hasMigrations && out.postgres && !out.postgres.includes("init:")) out.postgres = out.postgres.replace(/ }$/, ', init: "<your migrate command> $SANDBOX_URL" }');
532
+ return out;
533
+ }
534
+
535
+ /** The commented forge.yaml block for a detected proposal; "" when there is none. */
536
+ export function sandboxesProposalYaml(sandboxes) {
537
+ const names = Object.keys(sandboxes ?? {});
538
+ if (!names.length) return "";
539
+ return `
540
+ # =============================================================================
541
+ # TEST SANDBOXES (proposed by init, uncomment to enable; see docs/CONFIG.md verify.sandboxes)
542
+ # =============================================================================
543
+ # A lane creates these only when a contract validate entry names them in env.
544
+ #
545
+ # verify:
546
+ # sandboxes:
547
+ ${names.map((n) => `# ${n}: ${sandboxes[n]}`).join("\n")}
548
+ `;
549
+ }
550
+
481
551
  // ---------------------------------------------------------------------------
482
552
  // Minimal forge.yaml template builder
483
553
  // ---------------------------------------------------------------------------
@@ -531,6 +601,7 @@ export function buildMinimalForgeYaml({
531
601
  worktreeBase,
532
602
  defaultBranch,
533
603
  stagingBranch,
604
+ sandboxes = {},
534
605
  }) {
535
606
  const e = escapeYamlScalar;
536
607
  const descLine = description
@@ -570,5 +641,5 @@ branches:
570
641
  default: "${e(defaultBranch)}"
571
642
  staging: "${e(stagingBranch)}"
572
643
  feature_pattern: "milestone/{slug}"
573
- `;
644
+ ${sandboxesProposalYaml(sandboxes)}`;
574
645
  }
package/bin/labels.json CHANGED
@@ -54,6 +54,11 @@
54
54
  "color": "0E8A16",
55
55
  "description": "Pipeline: PR merged, issue closed. Managed by ForgeDock."
56
56
  },
57
+ {
58
+ "name": "workflow:merged-unverified",
59
+ "color": "FBCA04",
60
+ "description": "Pipeline: PR merged but verification failed, needs a human decision. Managed by ForgeDock."
61
+ },
57
62
  {
58
63
  "name": "workflow:decomposed",
59
64
  "color": "BFD4F2",
@@ -61,7 +61,7 @@ export async function checkAdmission({ cfg = {}, host }) {
61
61
  * mem/tmp <= min / ratio). Orchestrate runs owned-resource GC before an admission when this is true. A failed or
62
62
  * non-finite probe never counts as near.
63
63
  */
64
- export async function nearCeiling({ cfg = {}, host, ratio = 0.8 } = {}) {
64
+ export async function nearCeiling({ cfg = {}, host, ratio = 0.8, minFreeGb = null } = {}) {
65
65
  const c = { ...ADMISSION_DEFAULTS, ...Object.fromEntries(Object.entries(cfg ?? {}).filter(([, v]) => v !== undefined && v !== null)) };
66
66
  if (c.enabled === false || !host) return false;
67
67
  const r = Number.isFinite(ratio) && ratio > 0 && ratio <= 1 ? ratio : 0.8;
@@ -69,6 +69,7 @@ export async function nearCeiling({ cfg = {}, host, ratio = 0.8 } = {}) {
69
69
  const maxLoad = typeof c.max_load_per_core === "number" && Number.isFinite(c.max_load_per_core) ? c.max_load_per_core : null; // off by default (#4169)
70
70
  const load = maxLoad === null ? null : await safe(host.loadAvg1), cores = maxLoad === null ? null : await safe(host.cores);
71
71
  if (load !== null && cores && load / cores >= r * maxLoad) return true;
72
+ if ((await diskLow({ host, minFreeGb: Number.isFinite(minFreeGb) && minFreeGb > 0 ? minFreeGb / r : null })).low) return true; // #5421
72
73
  const mem = await safe(host.memAvailableMb);
73
74
  if (mem !== null && mem <= c.min_free_mem_mb / r) return true;
74
75
  let paths = [];
@@ -76,3 +77,22 @@ export async function nearCeiling({ cfg = {}, host, ratio = 0.8 } = {}) {
76
77
  for (const p of paths) { const free = await safe(host.freeMb, p); if (free !== null && free <= c.min_free_tmp_mb / r) return true; }
77
78
  return false;
78
79
  }
80
+
81
+ /**
82
+ * Free-disk check (#5421): the filesystems holding the worktree root and `~/.forge` (`host.hygienePaths()`, else
83
+ * `host.tmpPaths()`) against `minFreeGb` (hygiene.min_free_gb). A failed probe never counts as low; null/0 is off.
84
+ * @returns {Promise<{low: boolean, reasons: string[]}>}
85
+ */
86
+ export async function diskLow({ host, minFreeGb = null } = {}) {
87
+ const min = Number(minFreeGb);
88
+ if (!host || !Number.isFinite(min) || min <= 0) return { low: false, reasons: [] };
89
+ let paths = [];
90
+ try { paths = (await (host.hygienePaths ?? host.tmpPaths)?.call(host)) ?? []; } catch { paths = []; }
91
+ const reasons = [];
92
+ for (const p of paths) {
93
+ let mb = null;
94
+ try { const v = await host.freeMb?.(p); mb = Number.isFinite(v) ? v : null; } catch { mb = null; }
95
+ if (mb !== null && mb / 1024 < min) reasons.push(`disk ${p} ${(mb / 1024).toFixed(1)} GB < ${min} GB`);
96
+ }
97
+ return { low: reasons.length > 0, reasons };
98
+ }
@@ -0,0 +1,43 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #5448: blast-radius regression checks. `verify.baselines` (forge.yaml) declares suites that validate runs whenever a
5
+ * matching path changes; a contract `regression` set (existing tests of callers, shared modules, sibling configs) is
6
+ * folded into `validate` at freeze so the existing validate machinery runs it.
7
+ */
8
+ import { matchesGlob } from "./verify.mjs";
9
+
10
+ /** `[{when, run}]` or a `{glob: command}` map as `[{when, run}]`; entries missing either half are dropped. */
11
+ export function parseBaselines(v) {
12
+ const rows = Array.isArray(v) ? v : v && typeof v === "object" ? Object.entries(v).map(([when, run]) => ({ when, run })) : [];
13
+ const out = [];
14
+ for (const r of rows) {
15
+ const when = String(r?.when ?? "").trim(), run = String(r?.run ?? "").trim();
16
+ if (when && run) out.push({ when, run });
17
+ }
18
+ return out;
19
+ }
20
+
21
+ /** The baselines whose `when` glob matches at least one changed file, each command once. */
22
+ export function matchBaselines(changedFiles = [], baselines = []) {
23
+ const seen = new Set();
24
+ return baselines.filter((b) => !seen.has(b.run) && (changedFiles ?? []).some((f) => matchesGlob(f, b.when)) && seen.add(b.run));
25
+ }
26
+
27
+ /** Precheck failures (no `code`; precheck adds it) for baseline runs `[{when, run, rc, output}]` that did not exit 0. */
28
+ export function baselineFailures(runs = []) {
29
+ return (runs ?? []).filter((r) => r.rc !== 0).map((r) => ({ kind: "baseline_failed",
30
+ detail: `baseline suite \`${r.run}\` (declared for \`${r.when}\`) failed with exit ${r.rc}: ${String(r.output ?? "").trim().split("\n").slice(-8).join(" | ").slice(0, 400)}` }));
31
+ }
32
+
33
+ /** Fold `contract.regression` ([{id, command, covers}]) into `validate` as G# entries; an id or command already there is skipped. */
34
+ export function foldRegression(contract) {
35
+ const reg = Array.isArray(contract?.regression) ? contract.regression : [];
36
+ if (!reg.length) return contract;
37
+ const validate = Array.isArray(contract.validate) ? [...contract.validate] : [];
38
+ for (const g of reg) {
39
+ if (!g?.id || !g?.command || validate.some((v) => v?.id === g.id || v?.command === g.command)) continue;
40
+ validate.push({ id: g.id, command: g.command, regression: true });
41
+ }
42
+ return { ...contract, validate };
43
+ }
@@ -0,0 +1,33 @@
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 { parseBaselines, matchBaselines, baselineFailures, foldRegression } from "./baselines.mjs";
6
+ import { parseVerify } from "./verify.mjs";
7
+ import { precheck } from "./conformance.mjs";
8
+
9
+ describe("baselines (#5448)", () => {
10
+ it("parses the array and the map forms; parseVerify carries them", () => {
11
+ const want = [{ when: "shared/content/**", run: "make stealth-baseline" }];
12
+ assert.deepEqual(parseBaselines(want), want);
13
+ assert.deepEqual(parseBaselines({ "shared/content/**": "make stealth-baseline" }), want);
14
+ assert.deepEqual(parseVerify({ baselines: { "shared/content/**": "make stealth-baseline" } }).baselines, want);
15
+ assert.equal(parseVerify({}).baselines, undefined);
16
+ });
17
+ it("a shared-module change selects the baseline once; an unrelated change selects none", () => {
18
+ const b = parseBaselines({ "shared/content/**": "make stealth-baseline", "shared/**": "make stealth-baseline" });
19
+ assert.equal(matchBaselines(["shared/content/a.py", "shared/content/b.py"], b).length, 1);
20
+ assert.deepEqual(matchBaselines(["docs/readme.md"], b), []);
21
+ });
22
+ it("a failing baseline fails precheck as a regression; a passing one does not", () => {
23
+ const run = { when: "shared/**", run: "make stealth-baseline" };
24
+ const c = { requirements: [], deliverables: [], validate: [] };
25
+ const fail = precheck({ contract: c, result: {}, changedFiles: [], baselineFailures: baselineFailures([{ ...run, rc: 2, output: "vendor x red" }]) });
26
+ assert.ok(fail.failures.some((f) => f.kind === "baseline_failed" && /vendor x red/.test(f.detail)));
27
+ assert.equal(baselineFailures([{ ...run, rc: 0 }]).length, 0);
28
+ });
29
+ it("folds the regression set into validate once", () => {
30
+ const c = { validate: [{ id: "V1", command: "a" }], regression: [{ id: "G1", command: "b" }, { id: "G2", command: "a" }] };
31
+ assert.deepEqual(foldRegression(c).validate.map((v) => v.id), ["V1", "G1"]);
32
+ });
33
+ });