forgedock 1.67.0 → 1.69.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 (156) hide show
  1. package/bin/config-schema.mjs +1 -0
  2. package/bin/engine/outcome-codes.mjs +1 -0
  3. package/bin/engine-cli.mjs +103 -21
  4. package/bin/engine.mjs +10 -0
  5. package/bin/forgedock.mjs +17 -1
  6. package/bin/help-text.mjs +1 -0
  7. package/bin/lean/admission.mjs +21 -0
  8. package/bin/lean/admission.test.mjs +30 -0
  9. package/bin/lean/advisory.test.mjs +39 -15
  10. package/bin/lean/amendment-schema.mjs +3 -4
  11. package/bin/lean/attempts.mjs +34 -31
  12. package/bin/lean/attempts.test.mjs +33 -19
  13. package/bin/lean/basered.mjs +26 -0
  14. package/bin/lean/batch-health.mjs +17 -12
  15. package/bin/lean/batch-health.test.mjs +39 -11
  16. package/bin/lean/batch.mjs +11 -1
  17. package/bin/lean/batch.test.mjs +51 -2
  18. package/bin/lean/capsample.mjs +25 -0
  19. package/bin/lean/ci-gate.mjs +2 -90
  20. package/bin/lean/ci-gate.test.mjs +1 -127
  21. package/bin/lean/ci-precheck.mjs +25 -8
  22. package/bin/lean/ci-precheck.test.mjs +24 -0
  23. package/bin/lean/clear-breaker.test.mjs +4 -3
  24. package/bin/lean/commentstate.mjs +10 -5
  25. package/bin/lean/commentstate.test.mjs +12 -1
  26. package/bin/lean/conformance.e2e.test.mjs +9 -6
  27. package/bin/lean/conformance.mjs +62 -197
  28. package/bin/lean/conformance.test.mjs +46 -376
  29. package/bin/lean/depcache.mjs +102 -10
  30. package/bin/lean/depcache.test.mjs +105 -0
  31. package/bin/lean/docsgate.mjs +0 -32
  32. package/bin/lean/docsgate.test.mjs +2 -23
  33. package/bin/lean/effects-cap.test.mjs +9 -1
  34. package/bin/lean/effects-killtree.test.mjs +35 -0
  35. package/bin/lean/effects.mjs +57 -25
  36. package/bin/lean/engine-readmit.test.mjs +35 -0
  37. package/bin/lean/envgap.mjs +111 -0
  38. package/bin/lean/envgap.test.mjs +64 -0
  39. package/bin/lean/execution.mjs +13 -4
  40. package/bin/lean/execution.test.mjs +33 -0
  41. package/bin/lean/failure-census.mjs +170 -0
  42. package/bin/lean/failure-census.test.mjs +59 -0
  43. package/bin/lean/failure-stop.mjs +12 -1
  44. package/bin/lean/failure-stop.test.mjs +14 -1
  45. package/bin/lean/guardgate.test.mjs +2 -3
  46. package/bin/lean/heavy.mjs +33 -4
  47. package/bin/lean/heavy.test.mjs +38 -6
  48. package/bin/lean/hostconfig.mjs +54 -0
  49. package/bin/lean/hostconfig.test.mjs +67 -0
  50. package/bin/lean/hotarea.mjs +0 -36
  51. package/bin/lean/hotarea.test.mjs +1 -22
  52. package/bin/lean/issuewatch-verify.mjs +19 -4
  53. package/bin/lean/issuewatch.mjs +21 -4
  54. package/bin/lean/issuewatch.test.mjs +48 -1
  55. package/bin/lean/lane-audit-gap.mjs +66 -0
  56. package/bin/lean/lane-audit-gap.test.mjs +59 -0
  57. package/bin/lean/lane-audit-llm.mjs +52 -0
  58. package/bin/lean/lane-audit-llm.test.mjs +57 -0
  59. package/bin/lean/lane-audit-query.mjs +47 -0
  60. package/bin/lean/lane-audit-query.test.mjs +44 -0
  61. package/bin/lean/lane-audit-signatures.mjs +33 -0
  62. package/bin/lean/lane-audit.mjs +110 -0
  63. package/bin/lean/lane-audit.test.mjs +97 -0
  64. package/bin/lean/lane-recovery.test.mjs +33 -0
  65. package/bin/lean/lanecheck.mjs +5 -3
  66. package/bin/lean/lanecheck.test.mjs +6 -0
  67. package/bin/lean/lean.mjs +247 -152
  68. package/bin/lean/lean.test.mjs +502 -206
  69. package/bin/lean/limits.mjs +17 -0
  70. package/bin/lean/limits.test.mjs +15 -1
  71. package/bin/lean/live-execution.mjs +24 -2
  72. package/bin/lean/live-execution.test.mjs +62 -0
  73. package/bin/lean/orchestrate-attempts.test.mjs +17 -9
  74. package/bin/lean/orchestrate-dispatch-placement.test.mjs +81 -0
  75. package/bin/lean/orchestrate-envhold.test.mjs +62 -1
  76. package/bin/lean/orchestrate-heldroot.test.mjs +72 -0
  77. package/bin/lean/orchestrate-hostfallback.test.mjs +59 -1
  78. package/bin/lean/orchestrate-overload-recovery.test.mjs +37 -0
  79. package/bin/lean/orchestrate-pause.test.mjs +53 -1
  80. package/bin/lean/orchestrate-reconcile.test.mjs +17 -0
  81. package/bin/lean/orchestrate-relaunch-gates.test.mjs +57 -0
  82. package/bin/lean/orchestrate-stacking.test.mjs +10 -0
  83. package/bin/lean/orchestrate.mjs +215 -42
  84. package/bin/lean/postdeploy-check.test.mjs +1 -3
  85. package/bin/lean/precheck.mjs +20 -0
  86. package/bin/lean/preflight.mjs +110 -14
  87. package/bin/lean/preflight.test.mjs +64 -4
  88. package/bin/lean/prompts.mjs +11 -21
  89. package/bin/lean/recurrence.mjs +6 -148
  90. package/bin/lean/recurrence.test.mjs +11 -147
  91. package/bin/lean/release-deploy.mjs +35 -5
  92. package/bin/lean/release-deploy.test.mjs +50 -3
  93. package/bin/lean/release-flakes.mjs +48 -2
  94. package/bin/lean/release-flakes.test.mjs +45 -1
  95. package/bin/lean/release-ledger.mjs +19 -1
  96. package/bin/lean/release-ledger.test.mjs +23 -0
  97. package/bin/lean/release-preflight.mjs +28 -0
  98. package/bin/lean/release-preflight.test.mjs +42 -1
  99. package/bin/lean/release-review.mjs +40 -5
  100. package/bin/lean/release-review.test.mjs +43 -2
  101. package/bin/lean/release.mjs +45 -15
  102. package/bin/lean/release.test.mjs +32 -0
  103. package/bin/lean/retry.mjs +1 -1
  104. package/bin/lean/retry.test.mjs +6 -1
  105. package/bin/lean/rotator.mjs +9 -0
  106. package/bin/lean/rotator.test.mjs +11 -1
  107. package/bin/lean/sandbox-remote.mjs +51 -13
  108. package/bin/lean/schedd.mjs +13 -8
  109. package/bin/lean/schedd.test.mjs +65 -5
  110. package/bin/lean/selfreview.mjs +1 -1
  111. package/bin/lean/statuscomment.mjs +4 -1
  112. package/bin/lean/validate-catalog.mjs +108 -0
  113. package/bin/lean/validate-catalog.test.mjs +46 -1
  114. package/bin/lean/verify.mjs +1 -1
  115. package/bin/pool/affinity.test.mjs +91 -0
  116. package/bin/pool/agent.mjs +247 -23
  117. package/bin/pool/cache-sweep.mjs +31 -10
  118. package/bin/pool/ci-autoscale.mjs +160 -0
  119. package/bin/pool/cli.mjs +56 -9
  120. package/bin/pool/docker.mjs +5 -0
  121. package/bin/pool/engine-placement.test.mjs +94 -0
  122. package/bin/pool/image-manifest.mjs +24 -0
  123. package/bin/pool/image-manifest.test.mjs +20 -0
  124. package/bin/pool/lane-target.mjs +41 -0
  125. package/bin/pool/lane-tools.mjs +29 -5
  126. package/bin/pool/lane-tools.test.mjs +36 -7
  127. package/bin/pool/mirror-seed.mjs +15 -11
  128. package/bin/pool/project-layer.mjs +142 -0
  129. package/bin/pool/project-layer.test.mjs +73 -0
  130. package/bin/pool/router.mjs +106 -36
  131. package/bin/pool/version.mjs +72 -2
  132. package/bin/review-staging.mjs +11 -3
  133. package/bin/runner.mjs +59 -11
  134. package/bin/stats/release.mjs +7 -0
  135. package/bin/stats/release.test.mjs +20 -0
  136. package/bin/stats/scorecard.mjs +187 -0
  137. package/bin/stats/scorecard.test.mjs +89 -0
  138. package/bin/stats/tool-parks.mjs +29 -0
  139. package/bin/stats/tool-parks.test.mjs +21 -0
  140. package/docs/CONFIG.md +41 -0
  141. package/docs/OUTCOME-CODES.md +1 -0
  142. package/docs/STATS.md +17 -0
  143. package/package.json +1 -1
  144. package/pool/image/Dockerfile +15 -3
  145. package/pool/image/manifest.json +25 -0
  146. package/pool/image/mirror.sh +11 -2
  147. package/pool/install/install-agent.ps1 +11 -4
  148. package/scripts/ci-local/adapters/github-actions.mjs +8 -0
  149. package/scripts/ci-local/cli.mjs +1 -1
  150. package/scripts/ci-local/plan.mjs +3 -2
  151. package/scripts/ci-local.test.sh +14 -2
  152. package/scripts/failure-census.mjs +67 -0
  153. package/scripts/review-finalize.sh +5 -5
  154. package/scripts/review-finalize.test.sh +8 -1
  155. package/scripts/verify-phase-trail.sh +11 -0
  156. package/scripts/verify-phase-trail.test.sh +9 -0
@@ -43,6 +43,7 @@ export const TYPES = {
43
43
  "verification.ci_local.extra_commands": "list",
44
44
  "verification.ci_local.budget_minutes": "number",
45
45
  "verification.ci_local.max_parallel": "number",
46
+ "review.max_parallel": "posint", // #6098: release-review reviewers in flight at once (default max(2, cores/2))
46
47
  "orchestration.merge_train": { enum: ["off", "on"] }, // #5836: lanes end pr-ready and the batch merge train merges (default off)
47
48
  "orchestration.merge_train_batch": "posint", // #5837: up to N green PRs of one base validated together on a candidate ref (default 4)
48
49
  "orchestration.max_attempts_per_issue": "posint", // #5986: lifetime lanes per issue before one FORGE:ESCALATION (default 4)
@@ -61,6 +61,7 @@ export const OUTCOME_CODES = Object.freeze({
61
61
  ENV_REPRO_UNRUNNABLE: "env.repro_unrunnable", // forge#4334: the repro harness could not run the repro test on head; an environment error, not a conformance failure
62
62
  ENV_LANE_LIMIT: "env.lane_limit", // forge#4690: the lane hit its own scope limit (TasksMax or MemoryMax) and was stopped; an environment error, never an engine-error, so the breaker ignores it
63
63
  ENV_CAPABILITY_REMOTE: "env.capability_remote", // forge#4542: a remote sandbox lane blocked only on a host-only capability (SOPS key, ops credentials, prod monitor SSH) the dispatching host has; recovered locally
64
+ ENV_ENGINE_SKEW: "env.engine_skew", // forge#5931: the sandbox ran a different engine version than the host; an environment error (gates fixed in the host version still fire), never conformance
64
65
  SANDBOX_START_FAILED: "sandbox.start_failed", // forge#4254: a lane sandbox could not start (a non-auth 4xx/config error or a non-HTTP start failure); needs-human, not relaunched
65
66
  BASE_RED: "base.red", // forge#5239: a verify.invariants guard fails on the base too; the lane is deferred behind the introducing issue, never needs-human
66
67
  SANDBOX_CAPACITY: "sandbox.capacity", // forge#4254: the sandbox provider had no capacity; deferred with backoff
@@ -23,7 +23,7 @@ import { localLaneCap, ADMISSION_DEFAULTS } from "./lean/admission.mjs";
23
23
  import { memAvailableMb } from "./lean/heavy.mjs";
24
24
  import { liveOverload, formatOverload, formatHostLoad } from "./lean/hostload.mjs";
25
25
  import { join, resolve as resolvePath } from "node:path";
26
- import { runIssue, DEFAULT_MAX_ATTEMPTS, sanitizeLeaseHost, ENGINE_VERSION } from "./engine.mjs";
26
+ import { holdResumePlan, holdTtlRefusal, runIssue, DEFAULT_MAX_ATTEMPTS, sanitizeLeaseHost, ENGINE_VERSION } from "./engine.mjs";
27
27
  import { sandboxBudgetKey } from "./lean/liveness.mjs";
28
28
  import { makeProjector } from "./engine/projector.mjs";
29
29
  import { decomposedSubissues, isDecomposedRecord, isTrustedActor, parseDependsOn } from "./engine/phases.mjs";
@@ -54,6 +54,7 @@ import { OUTCOME_CODES } from "./engine/outcome-codes.mjs";
54
54
  import { USER_ERRORS } from "./help-text.mjs";
55
55
  import * as batchHealth from "./lean/batch-health.mjs";
56
56
  import { makeAttemptsSeam } from "./lean/attempts.mjs";
57
+ import { cmpVersion } from "./pool/version.mjs";
57
58
  import * as _autoChildren from "./lean/autochildren.mjs";
58
59
 
59
60
  /**
@@ -521,7 +522,8 @@ export function readRelayCaps(env = process.env) {
521
522
  export function readHostFallback(cwd = process.cwd()) {
522
523
  let hostRole = null;
523
524
  try { hostRole = parseForgeYaml(readFileSync(join(cwd, "forge.yaml"), "utf8"))?.host?.role ?? null; } catch { /* unreadable: role unset */ }
524
- return hostFallbackAllowed({ hostFallback: readExecution(cwd)?.hostFallback ?? null, hostRole });
525
+ const exec = readExecution(cwd);
526
+ return hostFallbackAllowed({ hostFallback: exec?.hostFallback ?? null, hostRole, mode: exec?.mode ?? null });
525
527
  }
526
528
  export function readExecution(cwd = process.cwd()) {
527
529
  try {
@@ -529,6 +531,10 @@ export function readExecution(cwd = process.cwd()) {
529
531
  return sec && typeof sec === "object" ? parseExecution(sec) : undefined;
530
532
  } catch { return undefined; }
531
533
  }
534
+ /** R2: forge.yaml `execution.min_lane_engine` (a version string such as 1.67); undefined when unset or unreadable. */
535
+ export function readMinLaneEngine(cwd = process.cwd()) {
536
+ try { const v = String(parseForgeYaml(readFileSync(join(cwd, "forge.yaml"), "utf8"))?.execution?.min_lane_engine ?? "").trim(); return /^v?\d+(\.\d+)*$/.test(v) ? v.replace(/^v/, "") : undefined; } catch { return undefined; }
537
+ }
532
538
  /** #5748: forge.yaml sets a valid `execution.mode` (even `local`): the explicit opt-out from the public-repo default. */
533
539
  export function executionModeExplicit(cwd = process.cwd()) {
534
540
  try { return ["local", "remote", "hybrid"].includes(String(parseForgeYaml(readFileSync(join(cwd, "forge.yaml"), "utf8"))?.execution?.mode ?? "").trim()); } catch { return false; }
@@ -655,7 +661,7 @@ export function readEnvConfig(cwd = process.cwd()) {
655
661
  let appPages = false; // #5428: default-on trigger: the repo tracks Next app/**/page.* files
656
662
  try { appPages = String(execFileSync("git", ["ls-files", "--", "*page.*"], { cwd, encoding: "utf8", timeout: 10000, stdio: ["ignore", "pipe", "ignore"] })).split("\n").some((f) => PAGE_RE.test(f)); } catch { /* not a git checkout: off */ }
657
663
  const pg = parsePagesConfig(y?.pages, { hasAppPages: appPages }); // #5428: forge.yaml pages: (off for repos without pages)
658
- const rc = y?.recurrence && typeof y.recurrence === "object" ? parseRecurrenceConfig({ ...y.recurrence, hot_areas: readYamlMap(cwd, "recurrence", "hot_areas"), counters: readYamlMap(cwd, "recurrence", "counters") }) : null; // #5751: forge.yaml recurrence: (absent: the engine defaults)
664
+ const rc = y?.recurrence && typeof y.recurrence === "object" ? parseRecurrenceConfig({ ...y.recurrence, hot_areas: readYamlMap(cwd, "recurrence", "hot_areas") }) : null; // #5751: forge.yaml recurrence: (absent: the engine defaults)
659
665
  const dg = parseDesignConfig(y?.design); // #5330: forge.yaml design: (system always read; routes/gate opt in the design gate)
660
666
  const kb = typeof e.sparse_max_kb === "string" && /^\d+$/.test(e.sparse_max_kb.trim()) ? Number(e.sparse_max_kb) : e.sparse_max_kb;
661
667
  return { ...(s(e.toolchain) ? { toolchainOverride: s(e.toolchain) } : {}), ...(s(e.setup) ? { envSetup: s(e.setup) } : {}),
@@ -1127,7 +1133,12 @@ export async function runFromCli(argv, deps = {}) {
1127
1133
  if (interrupted) return;
1128
1134
  interrupted = true;
1129
1135
  let r = null;
1130
- try { r = teardown ? await teardown(sig) : null; } catch { r = null; }
1136
+ // #6081: a teardown that hangs (a builder child that ignores SIGTERM, a blocked git call) must not leave the lane alive after the operator stop:
1137
+ // bounded, then the lane reports and exits anyway.
1138
+ const bound = Number(deps.teardownMs ?? process.env.FORGEDOCK_TEARDOWN_MS) > 0 ? Number(deps.teardownMs ?? process.env.FORGEDOCK_TEARDOWN_MS) : 30000;
1139
+ let timer;
1140
+ try { r = teardown ? await Promise.race([teardown(sig), new Promise((res) => { timer = setTimeout(() => res(null), bound); })]) : null; } catch { r = null; }
1141
+ clearTimeout(timer);
1131
1142
  try { report({ ...(r ?? {}), terminalReason: "deferred", code: OUTCOME_CODES.RUN_INTERRUPTED, detail: r?.detail ?? `interrupted by ${sig}` }); } catch { /* exit anyway */ }
1132
1143
  console.log(`issue #${issue} → deferred (interrupted by ${sig})`);
1133
1144
  exit(128 + SIGNO[sig]);
@@ -1402,7 +1413,7 @@ async function envBatch({ argv, root, print = (l) => console.log(l) }) {
1402
1413
  }
1403
1414
 
1404
1415
  const ORCH_USAGE = "usage: forgedock orchestrate <issue...> | --select <query> [--parallel K] [--lane L] [--lane-override] [--force <reason>] [--repo owner/repo] [--auto-children off|decomposed|epic|all] [--epic N] | --resume <id> [issue...] | --set-parallel <id> <K> | --set-max-remote <id> <N> | --set-placement <id> remote|hybrid|local | --clear-breaker <id> | --status <id> | --add <id> <issue...> | --requeue <id> <issue...> [--reason <text>] | --cancel <id> [--stop-remote] | --hold <id> --all [--for 2h] [--reason T] (sugar for --pause) | --hold <id> <issue...> [--for <4h|30m|1d>] [--reason <text>] | --pause <id> [--for <4h|30m|1d>] --reason <text> | --unpause <id> | --gc-orphans | --adopt <issue> [--repo owner/repo] [--lane L] | --release <id> <issue...> | --show-env <id> | --set-env <id> KEY=VAL | --unset-env <id> KEY";
1405
- const ORCH_VALUED = ["--parallel", "--lane", "--repo", "--model", "--prefilter-model", "--reason", "--force", "--auto-children", "--epic", "--for", "--select"];
1416
+ const ORCH_VALUED = ["--parallel", "--lane", "--repo", "--model", "--prefilter-model", "--reason", "--force", "--auto-children", "--epic", "--for", "--ttl", "--select"];
1406
1417
  const issuesOf = (argv) => {
1407
1418
  const issues = [];
1408
1419
  for (let i = 0; i < argv.length; i++) {
@@ -1579,7 +1590,7 @@ function parseHoldFor(v) {
1579
1590
  }
1580
1591
  /** #5469: the hold's owner (the operator session: the CLI's parent pid on this host), expiry (`--for`) and `--reason`. */
1581
1592
  function holdMeta(argv) {
1582
- const forLabel = flag(argv, "--for"), reason = flag(argv, "--reason");
1593
+ const forLabel = flag(argv, "--for") ?? flag(argv, "--ttl"), reason = flag(argv, "--reason");
1583
1594
  return { owner: process.env.FORGE_HOLD_OWNER || `${process.env.USER || process.env.USERNAME || "operator"}@${hostname()}`, ownerPid: process.ppid, ownerHost: hostname(), forMs: parseHoldFor(forLabel), forLabel, reason: reason && !reason.startsWith("--") ? reason : null };
1584
1595
  }
1585
1596
 
@@ -1632,6 +1643,8 @@ async function holdBatch({ op, id, tokens, root, viaDaemon = null, takeover = nu
1632
1643
  try { const st = (await import("./lean/batch.mjs")).openBatch(root, id).store.load(); for (const n of st?.pending ?? []) if (!issues.includes(n)) issues.push(n); for (const n of Object.keys(st?.notBefore ?? {})) if (!issues.includes(Number(n))) issues.push(Number(n)); } catch { /* unreadable: the explicit list stands */ }
1633
1644
  }
1634
1645
  if (!id || String(id).startsWith("--") || !issues.length) throw new Error(ORCH_USAGE);
1646
+ const refusal = op === "hold" ? holdTtlRefusal(issues, meta?.forMs) : null; // #5988
1647
+ if (refusal) throw new Error(refusal);
1635
1648
  let res = viaDaemon ? await viaDaemon(op, issues, meta) : null;
1636
1649
  if (!res) {
1637
1650
  const b = (await import("./lean/batch.mjs")).openBatch(root, id);
@@ -1652,6 +1665,7 @@ async function holdBatch({ op, id, tokens, root, viaDaemon = null, takeover = nu
1652
1665
  const list = (res.changed ?? []).map((n) => `#${n}`).join(" ") || "(none)";
1653
1666
  print(op === "hold" ? `batch ${id}: held ${list}${meta?.forMs ? ` for ${meta.forLabel}` : ""}; forgedock orchestrate --release ${id} <issue...> (or --resume ${id} <issue...>) re-admits them`
1654
1667
  : `batch ${id}: released ${list}`);
1668
+ if (op === "hold" && issues.length > 1) print(holdResumePlan(res.changed?.length ? res.changed : issues, meta?.forLabel)); // #5988
1655
1669
  return { ok: true, batch: id, changed: res.changed ?? [] };
1656
1670
  }
1657
1671
 
@@ -2100,6 +2114,7 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
2100
2114
  const prefetchOf = new Map(); // issue -> the frozen contract's relayable read-only commands (#4778), filled by readBody
2101
2115
  let execForNeeds = null;
2102
2116
  let poolUsage = []; // #5985: pool usage-history rows (cpu_avg per repo), refreshed in the background; classify lanes light/heavy
2117
+ let agentEngine = null;
2103
2118
  let lanes, remote = null, execBudget = null, execConf = null, hybrid = false;
2104
2119
  const execMode = () => (deps.execution !== undefined ? deps.execution : readExecution(cwd))?.mode ?? "local";
2105
2120
  if (deps.leanModule) {
@@ -2138,7 +2153,9 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
2138
2153
  return l.runOne(n, ln, ctx);
2139
2154
  }, adopt: l.adopt });
2140
2155
  const execMod = await import("./lean/execution.mjs");
2141
- const exec = deps.execution !== undefined ? deps.execution : await withPublicDefault(readExecution(cwd), { cwd, repo, gh: (a) => leanIo.gh(a, { cwd }), deps }); // #5748
2156
+ const exec0 = deps.execution !== undefined ? deps.execution : await withPublicDefault(readExecution(cwd), { cwd, repo, gh: (a) => leanIo.gh(a, { cwd }), deps }); // #5748
2157
+ const minLane = readMinLaneEngine(cwd); // R2: execution.min_lane_engine, unset = lower-engine agents are a fallback
2158
+ const exec = exec0 && minLane && exec0.minLaneEngine === undefined ? { ...exec0, minLaneEngine: minLane } : exec0;
2142
2159
  execForNeeds = exec ?? null;
2143
2160
  hybrid = exec?.mode === "hybrid" && Number.isInteger(exec.maxRemote) && exec.maxRemote >= 1;
2144
2161
  let remoteStop = null; // #4612: the sandbox provider's checkpoint stop, used only when the cancel asks for it
@@ -2156,6 +2173,10 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
2156
2173
  ...(deps.now ? { now: deps.now } : {}), ...(deps.pollMs ? { pollMs: deps.pollMs } : {}),
2157
2174
  logTail: (h) => { try { return readFileSync(batch.logFile(h.issue), "utf8").slice(-4000); } catch { return ""; } } }); // #4866: a clone failure in the lane log types sandbox.clone
2158
2175
  remoteStop = remoteLanes.stopLane;
2176
+ agentEngine = async () => { // R6: the lane engine of the agent that would run a lane (the best placeable one)
2177
+ const best = ((await provider.capacity?.())?.agents ?? []).filter((a) => a.ok && !a.paused).map((a) => a.engine_version).sort((a, b) => cmpVersion(b, a) ?? 0)[0];
2178
+ return best ?? null;
2179
+ };
2159
2180
  lanes = withPlacement(remoteLanes);
2160
2181
  {
2161
2182
  // #4255: once the budget refuses a remote lane, the rest run as detached host lanes. #4256: hybrid mixes both.
@@ -2182,17 +2203,12 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
2182
2203
  : execMod.placeLane({ exec: e, verifyMode, labels: labelsOf.get(n) ?? [], weight: weight.get(), headroom: hostHeadroom(), needs: needsOf.get(n) ?? [], relays }));
2183
2204
  if (batch.readExecution()?.provider !== true) batch.setExecution({ provider: true });
2184
2205
  // #4540: provider free slots, refreshed in the background (admission is sync); unknown (null) never blocks.
2185
- let capSample = null, onlineSample = null, capAt = 0, capLast = -Infinity, capFailed = false; // #5048: capFailed = last probe rejected // #4547: online = agents alive, null unknown
2186
- let liveSample = {}, usageLast = -Infinity; // #5985: the pool's live load/memory ride the capacity sample
2206
+ let usageLast = -Infinity; // #5985: the pool's live load/memory ride the capacity sample
2207
+ const { makeCapacitySampler } = await import("./lean/capsample.mjs");
2208
+ const sampleCapacity = makeCapacitySampler({ provider, ...(deps.now ? { now: deps.now } : {}), pollMs: deps.pollMs ?? 5000 }); // #4547: online = agents alive, null unknown
2187
2209
  const capacity = () => {
2188
2210
  if (typeof provider.usageHistory === "function" && (deps.now ? deps.now() : Date.now()) - usageLast >= 600000) { usageLast = deps.now ? deps.now() : Date.now(); Promise.resolve().then(() => provider.usageHistory()).then((rows) => { if (Array.isArray(rows)) poolUsage = rows; }, () => {}); }
2189
- if (capFailed) throw new Error("capacity probe failed"); // #5048: until the next successful sample, so every caller sees it (release review CONC-1)
2190
- const t = deps.now ? deps.now() : Date.now();
2191
- if (typeof provider.capacity === "function" && t - capLast >= (deps.pollMs ?? 5000)) {
2192
- capLast = t;
2193
- Promise.resolve().then(() => provider.capacity()).then((c) => { capFailed = false; capSample = c && Number.isInteger(c.free) ? c.free : null; onlineSample = c && Number.isInteger(c.online) ? c.online : null; liveSample = { ...(Number.isFinite(c?.load_per_core) ? { load_per_core: c.load_per_core } : {}), ...(Number.isFinite(c?.mem_available_gb) ? { mem_available_gb: c.mem_available_gb } : {}) }; capAt++; }, () => { capSample = null; onlineSample = null; capFailed = true; capAt++; });
2194
- }
2195
- return capSample === null && onlineSample === null ? null : { free: capSample, online: onlineSample, ...liveSample, at: capAt };
2211
+ return sampleCapacity();
2196
2212
  };
2197
2213
  remote = liveExec.liveRemote({
2198
2214
  hostFallback: readHostFallback(), capacity, isRemote: () => true, identity: () => holdId, ...(exec.fallbackLocal ? { offlineFallback: true, headroom: hostHeadroom, ...(exec.capacityFallbackAfter ? { capacityFallbackAfter: exec.capacityFallbackAfter } : {}) } : {}), onBudget: bud.onBudget ?? "stop", costPerMinute: bud.costPerMinute ?? 0,
@@ -2201,7 +2217,10 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
2201
2217
  try { execBudget.record(sandboxBudgetKey(batch.id, sb.id ?? n, rec?.handle?.startedAt ?? rec?.startedAt ?? null), sb); } catch { /* the batch total still counts it */ }
2202
2218
  Promise.resolve(emitSbx({ event: "SANDBOX_USAGE", issue: n, provider: sb.provider, sandbox_id: sb.id, minutes: sb.minutes, cost_usd: sb.cost_usd, batch: batch.id })).catch(() => {});
2203
2219
  },
2204
- }, { exec, readOverride: batch.readExecution, place, onChange: (e) => sink.line(`execution: live placement ${e.mode}, max_remote ${e.maxRemote}`) });
2220
+ }, { exec, readOverride: batch.readExecution, place, onChange: (e) => sink.line(`execution: live placement ${e.mode}, max_remote ${e.maxRemote}`),
2221
+ // #5746: a live max_remote left below the pinned value is announced once after FORGEDOCK_MAX_REMOTE_WARN_HOURS (default 6)
2222
+ belowPinnedHours: Number(process.env.FORGEDOCK_MAX_REMOTE_WARN_HOURS) || undefined,
2223
+ onBelowPinned: (w) => sink.line(`WARNING: execution: live max_remote ${w.maxRemote} has been below the pinned ${w.pinned} for over ${w.hours}h (forgedock orchestrate --set-max-remote ${batch.id} ${w.pinned} restores it)`) });
2205
2224
  sink.line(`execution: ${hybrid ? "hybrid" : "remote"} via ${provider.name}, max_remote ${exec.maxRemote}`);
2206
2225
  } else {
2207
2226
  lanes = withPlacement(batchMod.detachedLanes({ batch, cwd, env: laneEnv, script: laneScript, bin: deps.laneBin, pollMs: deps.pollMs, laneArgs, spawnFn: laneSpawn }));
@@ -2239,8 +2258,8 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
2239
2258
  const schedMod = await import("./lean/sched.mjs");
2240
2259
  const registry = deps.sched !== undefined ? deps.sched : schedMod.openSched(schedMod.schedDir());
2241
2260
  const overload = deps.overload !== undefined ? deps.overload : registry ? liveOverload(readAdmission(cwd)) : null; // #5174
2242
- const labelNames = async (n) => {
2243
- if (!labelsOf.has(n)) labelsOf.set(n, (JSON.parse(await leanIo.gh(["issue", "view", String(n), "-R", repo, "--json", "labels"])).labels ?? []).map((x) => x.name));
2261
+ const labelNames = async (n, { fresh = false } = {}) => { // #5893: `fresh` re-reads (the readmit decision); the cache serves placement
2262
+ if (fresh || !labelsOf.has(n)) labelsOf.set(n, (JSON.parse(await leanIo.gh(["issue", "view", String(n), "-R", repo, "--json", "labels"])).labels ?? []).map((x) => x.name));
2244
2263
  return labelsOf.get(n);
2245
2264
  };
2246
2265
  let budget = {};
@@ -2365,6 +2384,8 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
2365
2384
  const envHold = deps.envHold !== undefined ? deps.envHold : testDeps ? null : {
2366
2385
  version: () => scheddMod.readInstalledVersion() ?? ENGINE_VERSION,
2367
2386
  envFingerprint: () => batchMod.envFingerprint(batch.readPlan()?.env),
2387
+ envValues: () => batch.readPlan()?.env ?? null, // #5931
2388
+ agentVersion: async () => (agentEngine ? agentEngine() : null), // R6: re-admission of a remote lane checks the agent that will run it
2368
2389
  missingTools: async (tools) => { const p = batch.readPlan()?.env, e = p ? scheddMod.mergeEnv(process.env, p) : env; return hostMissingTools(tools, { path: e.PATH ?? e.Path ?? "" }); },
2369
2390
  };
2370
2391
  // #4785: decisions and the frozen contract's validate commands too. #5824: one view per issue; the plan pass's view is
@@ -2394,6 +2415,12 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
2394
2415
  batch.writePlan({ ...batch.readPlan(), dag: { edges: dag.edges, overlaps: dag.overlaps } });
2395
2416
  } catch (e) { sink.line(`plan: n/a (${String(e?.message ?? e).split("\n")[0].slice(0, 160)})`); }
2396
2417
  }
2418
+ // #5988: the cheap login probe (`claude auth status`, no model call) on the account the rotator names; ok on exit 0.
2419
+ const authProbeOf = () => async ({ configDir = null } = {}) => {
2420
+ const { spawnSync } = await import("node:child_process");
2421
+ const r = spawnSync("claude", ["auth", "status"], { timeout: 15000, stdio: "ignore", env: { ...process.env, ...(configDir ? { CLAUDE_CONFIG_DIR: configDir } : {}) } });
2422
+ return { ok: !r.error && r.status === 0 };
2423
+ };
2397
2424
  let rows, childFields = null; // #4965: the host gh's accepted `issue list --json` fields, read once from its help
2398
2425
  const healthCheck = (checkpoint) => batchHealth.runCheck({ batch, checkpoint, config: healthConf, repo, now: healthNow,
2399
2426
  resolve: (cands) => batchHealth.resolvedOnGithub(cands, (a) => leanIo.gh(a), repo),
@@ -2421,7 +2448,13 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
2421
2448
  autoChildren,
2422
2449
  ...(autoMod.addsEpicChildren(autoChildren.mode) ? { getChildren: async () => ({ list: await autoMod.readChildList({ gh: (a) => leanIo.gh(a), repo, fields: childFields ??= await autoMod.hostListFields((a) => leanIo.gh(a)) }), elsewhere: autoMod.liveElsewhere({ batchMod, root, self: batch.id, repo }) }) } : {}),
2423
2450
  ...(select ? { select, reconcile: await makeReconcile({ select, repo, leanIo, orch, lane, argv }) } : {}),
2424
- issues, parallel, prefilter, resolveLane: laneOf, store: batch.store, getParallel: batch.readParallel, getClearBreaker: batch.peekClearBreaker, consumeClearBreaker: batch.readClearBreaker, ackClearBreaker: batch.ackClearBreaker, getAdded: batch.readAdded, getRequeued: batch.readRequeued, getCancelled: batch.readCancel, getHeld: batch.readHeld, expireHolds: batch.expireHolds, getPause: batch.readPause, expirePause: batch.expirePause, getHoldInfo: batch.readHoldInfo, getGates: batch.readGates, baseWait: baseWaits.size ? baseWaitOf(baseWaits, { io, leanIo, cwd }) : null, ...lanes,
2451
+ issues, parallel, prefilter, resolveLane: laneOf, store: batch.store, getParallel: batch.readParallel, getClearBreaker: batch.peekClearBreaker, consumeClearBreaker: batch.readClearBreaker, ackClearBreaker: batch.ackClearBreaker, getAdded: batch.readAdded, getRequeued: batch.readRequeued, getCancelled: batch.readCancel, getHeld: batch.readHeld, expireHolds: batch.expireHolds, getPause: batch.readPause, expirePause: batch.expirePause, getHoldInfo: batch.readHoldInfo, authProbe: authProbeOf(), onEscalate: async ({ detail, issues: affected }) => { // #5988: the 30 min backend.auth escalation: notify + one issue comment
2452
+ const text = `BATCH AUTH OUTAGE ${batch.id}\n ${detail}\n recovery: forgedock orchestrate --resume ${batch.id}`;
2453
+ await batchHealth.deliverAlert({ text, batchId: batch.id, health: null, sink, gh: (a) => leanIo.gh(a), repo, config: { ...healthConf, issue: null }, epics: [], ...(deps.notify ? { notify: deps.notify } : {}) });
2454
+ const n = [...affected].sort((x, y) => x - y)[0];
2455
+ if (Number.isInteger(n) && repo) { try { await leanIo.gh(["issue", "comment", String(n), "-R", repo, "--body", `<!-- FORGE:AUTH-OUTAGE batch=${batch.id} -->\n${text}`]); } catch { /* best effort */ } }
2456
+ },
2457
+ ...(typeof remote?.quarantineAgent === "function" ? { quarantineAgent: (q) => remote.quarantineAgent(q) } : {}), ...(typeof remote?.reseedCache === "function" ? { reseedCache: (q) => remote.reseedCache(q) } : {}), getGates: batch.readGates, baseWait: baseWaits.size ? baseWaitOf(baseWaits, { io, leanIo, cwd }) : null, ...lanes,
2425
2458
  breaker: orch.breaker, maxDeferrals: orch.maxDeferrals, ...(Number.isInteger(orch.transientRetries) ? { transientRetries: orch.transientRetries } : {}), ...(deps.pollMs ? { pollMs: deps.pollMs } : {}), ...budget, limits, identity, rotator, batchId: batch.id, drift, lifecycle, integration,
2426
2459
  ...(registry ? { sched: { registry, batch: batch.id, repo, cap: liveLaneCap(orch.globalParallel ?? null, { cfg: readAdmission(cwd), host: { cores: () => cpus().length, memAvailableMb, rampingMb: rampProbe.rampingMb } }), exclusive: true }, priorityOf: async (n) => schedMod.priorityFromLabels(await labelNames(n)) } : {}),
2427
2460
  // #5174: hold new local admissions while loadavg/cores is above engine.overload_load_per_core (host-wide batches only)
@@ -2452,8 +2485,19 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
2452
2485
  onInterrupted: deps.onInterrupted ?? (async (n) => leanIo.gh(["issue", "edit", String(n), "-R", repo, "--remove-label", "workflow:building"]).catch(() => {})),
2453
2486
  // #4387: an out-of-set dependency labelled needs-human is not pulled into the batch
2454
2487
  issueLabels: labelNames,
2488
+ // #5893: a held needs-human root is released only when the label's removal event post-dates the newest FORGE:NEEDS_HUMAN comment
2489
+ heldFacts: deps.heldFacts ?? (async (n) => {
2490
+ // #6102: one timestamp per line, so empty pages add nothing (joined per-page arrays broke on an empty page)
2491
+ const ev = String(await leanIo.gh(["api", `repos/${repo}/issues/${n}/events`, "--paginate", "--jq", ".[] | select(.event==\"unlabeled\" and .label.name==\"needs-human\") | .created_at"])).split("\n").map((l) => l.trim()).filter(Boolean);
2492
+ const cs = JSON.parse(await leanIo.gh(["issue", "view", String(n), "-R", repo, "--json", "comments"])).comments ?? [];
2493
+ const blk = cs.filter((c) => String(c.body ?? "").includes("<!-- FORGE:NEEDS_HUMAN"));
2494
+ const last = blk[blk.length - 1];
2495
+ const ask = cs.filter((c) => /FORGE:ASK key=/.test(String(c.body ?? ""))).pop();
2496
+ const t = (x) => Date.parse(x);
2497
+ return { removedAt: Math.max(...ev.map(t), -Infinity), blockedAt: last ? t(last.createdAt) : NaN, askKey: ask ? (/FORGE:ASK key=([^\s>]+)/.exec(String(ask.body))?.[1] ?? "") : "" };
2498
+ }),
2455
2499
  // #5986: per-issue attempts ledger and input-hash admission (off under the test seams)
2456
- ...((deps.attempts !== undefined ? deps.attempts : testDeps ? null : true) ? { attempts: deps.attempts !== undefined ? deps.attempts : makeAttemptsSeam({ gh: (a) => leanIo.gh(a), repo, engineVersion: ENGINE_VERSION, sandboxVersion: scheddMod.readInstalledVersion?.() ?? null, cfg: { maxAttempts: orch.maxAttemptsPerIssue, maxIdentical: orch.maxIdenticalSignature } }) } : {}),
2500
+ ...((deps.attempts !== undefined ? deps.attempts : testDeps ? null : true) ? { attempts: deps.attempts !== undefined ? deps.attempts : makeAttemptsSeam({ gh: (a) => leanIo.gh(a), repo, engineVersion: ENGINE_VERSION, hostVersion: scheddMod.readInstalledVersion?.() ?? null, sandboxVersion: deps.sandboxVersion ?? null, cfg: { maxAttempts: orch.maxAttemptsPerIssue, maxIdentical: orch.maxIdenticalSignature } }) } : {}),
2457
2501
  // #4725: a closed (completed) dependency is satisfied even when it still carries a stale needs-human label
2458
2502
  // #5152: a NOT_PLANNED close labelled workflow:merged, or a decomposition whose sub-issues all closed, is delivered: CLOSED
2459
2503
  issueState: async (n) => {
@@ -2919,6 +2963,44 @@ export async function decisionsFromCli(argv, deps = {}) {
2919
2963
  return { rows };
2920
2964
  }
2921
2965
 
2966
+ /**
2967
+ * `forgedock audits [--repo OWNER/NAME] [--version X | --since-version X] [--signature S] [--class C] [--active] [--json]` (#6077):
2968
+ * queries the repo's FORGE:LANE_AUDIT comments (trusted authors only). `--active` = active, not fixed_in_later, current version
2969
+ * (highest engine_version seen, or --version), grouped per signature with count and lanes. Read-only.
2970
+ */
2971
+ export async function auditsFromCli(argv, deps = {}) {
2972
+ const q = await import("./lean/lane-audit-query.mjs");
2973
+ const { parseAudit, LANE_AUDIT_MARKER } = await import("./lean/lane-audit.mjs");
2974
+ const usage = "usage: forgedock audits [--repo OWNER/NAME] [--version X | --since-version X] [--signature S] [--class C] [--active] [--json]";
2975
+ const valued = new Set(["--repo", "--version", "--since-version", "--signature", "--class"]);
2976
+ const opts = {};
2977
+ for (let i = 0; i < argv.length; i++) {
2978
+ const a = argv[i];
2979
+ if (valued.has(a)) { if (argv[i + 1] == null || argv[i + 1].startsWith("--")) throw new Error(usage); opts[a] = argv[++i]; }
2980
+ else if (a === "--active" || a === "--json") opts[a] = true;
2981
+ else throw new Error(usage);
2982
+ }
2983
+ const run = deps.exec ?? (async (cmd, args) => String((await pexec(cmd, args, { maxBuffer: 64 * 1024 * 1024, timeout: 60000 })).stdout));
2984
+ const repo = opts["--repo"] ?? String(await run("gh", ["repo", "view", "--json", "nameWithOwner", "--jq", ".nameWithOwner"])).trim();
2985
+ const jq = `.[] | select(.body | contains("<!-- ${LANE_AUDIT_MARKER}")) | {body, user, author_association, issue_url} | tojson`;
2986
+ const lines = String(await run("gh", ["api", "--paginate", `repos/${repo}/issues/comments?per_page=100`, "--jq", jq])).split("\n").filter(Boolean);
2987
+ const { isTrustedIssueComment } = await import("./lean/prefilter.mjs");
2988
+ const audits = [];
2989
+ for (const l of lines) {
2990
+ try {
2991
+ const c = JSON.parse(l);
2992
+ if (!isTrustedIssueComment(c)) continue;
2993
+ const a = parseAudit(c.body);
2994
+ if (!a) continue;
2995
+ audits.push({ ...a, issue: Number(/(\d+)$/.exec(c.issue_url ?? "")?.[1]) || a.issue || null });
2996
+ } catch { /* skip a malformed comment */ }
2997
+ }
2998
+ const rows = q.filterAudits(audits, { version: opts["--version"], sinceVersion: opts["--since-version"], signature: opts["--signature"], class: opts["--class"] });
2999
+ const out = opts["--active"] ? q.summarizeActive(rows, { currentVersion: opts["--version"] ?? q.highestVersion(audits) }) : rows;
3000
+ console.log(opts["--json"] ? JSON.stringify(out, null, 2) : q.formatAudits(out, { active: Boolean(opts["--active"]) }));
3001
+ return { rows: out };
3002
+ }
3003
+
2922
3004
  /**
2923
3005
  * `forgedock check [--repo DIR] [--base REF] [--json]` (#4364): runs in the lane worktree what the engine runs after the
2924
3006
  * builder: the frozen validate commands (.forge-lean/contract.json) and the change-scoped pre-PR checks, with the plan
package/bin/engine.mjs CHANGED
@@ -26,6 +26,16 @@ import { OUTCOME_CODES, UNCLASSIFIED, normalizeCode, codeForRunnerError, codeFor
26
26
  // Exported (forge#2175) so bin/engine-cli.mjs can render "failed N/M attempts"
27
27
  // diagnostics without duplicating the retry budget constant.
28
28
  export const DEFAULT_MAX_ATTEMPTS = 3;
29
+ /** #5988: an operator hold on more issues than this needs an explicit `--for`/`--ttl`: an open-ended hold idles them for as long as it is forgotten. */
30
+ export const HOLD_TTL_REQUIRED_ABOVE = 10;
31
+ /** #5988: `--hold` on many issues without a TTL is refused; the message names the flag. @returns {string|null} the refusal, or null when allowed */
32
+ export function holdTtlRefusal(issues, forMs) {
33
+ return issues.length > HOLD_TTL_REQUIRED_ABOVE && !(Number(forMs) > 0) ? `holding ${issues.length} issues (more than ${HOLD_TTL_REQUIRED_ABOVE}) requires an explicit --ttl <4h|30m|1d> (or --for)` : null;
34
+ }
35
+ /** #5988: the plan printed with a hold: when it expires, an alert at T-30 min, and that expiry re-admits at the concurrency controller's pace. */
36
+ export function holdResumePlan(issues, forLabel) {
37
+ return `resume plan: ${issues.length} issue${issues.length === 1 ? "" : "s"} held${forLabel ? ` for ${forLabel}` : " until released"}; an alert posts 30 min before expiry; on expiry they re-admit through the concurrency controller, not all at once`;
38
+ }
29
39
 
30
40
  // forge#2239: lease TTL and renewal-interval defaults. Exported/overridable
31
41
  // (mirrors DEFAULT_MAX_ATTEMPTS) so tests can exercise "phase outlives the
package/bin/forgedock.mjs CHANGED
@@ -4021,7 +4021,7 @@ async function watch() {
4021
4021
  const SPLASH_COMMANDS = new Set(["run", "bootstrap", "run-issue", "orchestrate", "triage", "probe", "gc", "resume-stalled", "demo", "first-run", "doctor", "watch", "help", "--help", "-h"]);
4022
4022
  const KNOWN_COMMANDS = new Set([
4023
4023
  "install", "init", "enable", "disable", "status", "uninstall", "update",
4024
- "run", "bootstrap", "backend-check", "run-issue", "orchestrate", "milestone", "milestone-sync", "fix-close-reasons", "guards", "triage", "probe", "close", "acceptance", "interfaces", "docs", "review-staging", "release", "intake", "gc", "env", "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",
4024
+ "run", "bootstrap", "backend-check", "run-issue", "orchestrate", "milestone", "milestone-sync", "fix-close-reasons", "guards", "triage", "probe", "close", "acceptance", "interfaces", "docs", "review-staging", "release", "intake", "gc", "env", "sandbox", "resume-stalled", "demo", "first-run", "doctor", "auth", "watch", "issue-watch", "prod-watch", "selftest", "labels", "config", "stats", "scorecard", "limits", "decisions", "audits", "sched", "schedd", "pool", "check", "guide", "help", "--help", "-h",
4025
4025
  "ci-step", "ci-hook", "tests",
4026
4026
  "version", "--version", "-v",
4027
4027
  ]);
@@ -4282,6 +4282,17 @@ switch (command) {
4282
4282
  }
4283
4283
  break;
4284
4284
  }
4285
+ case "audits": {
4286
+ // #6077: query FORGE:LANE_AUDIT comments
4287
+ const { auditsFromCli } = await import("./engine-cli.mjs");
4288
+ try {
4289
+ await auditsFromCli(restArgs);
4290
+ } catch (err) {
4291
+ process.stderr.write(`${RED}${err.message}${RESET}\n`);
4292
+ exitCode = 1;
4293
+ }
4294
+ break;
4295
+ }
4285
4296
  case "decisions": {
4286
4297
  // #4695: anchored decisions of the local index
4287
4298
  const { decisionsFromCli } = await import("./engine-cli.mjs");
@@ -4624,6 +4635,11 @@ switch (command) {
4624
4635
  exitCode = await runStats(restArgs);
4625
4636
  break;
4626
4637
  }
4638
+ case "scorecard": {
4639
+ const { runScorecard } = await import("./stats/scorecard.mjs");
4640
+ exitCode = await runScorecard(restArgs);
4641
+ break;
4642
+ }
4627
4643
  case "watch":
4628
4644
  await watch();
4629
4645
  break;
package/bin/help-text.mjs CHANGED
@@ -86,6 +86,7 @@ export const FULL_COMMAND_GROUPS = [
86
86
  ["npx forgedock guards list [--path p] [--json] | backfill --since <date> [--dry-run]", "Fix guards: list the records (test files + protected hunks of merged fixes) covering a path, or build them for already-merged runs"],
87
87
  ["npx forgedock limits show | clear <id>|--all", "Show or clear per-account usage-limit holds shared by orchestrate batches"],
88
88
  ["npx forgedock decisions list [--stale] [--refresh]", "List anchored decisions (FORGE:DECISION); --stale shows those with an anchor missing on the base"],
89
+ ["npx forgedock audits [--repo R] [--version X | --since-version X] [--signature S] [--class C] [--active] [--json]", "Query lane audits (FORGE:LANE_AUDIT) by engine version, signature and class; --active lists current-version findings per signature with counts and lanes"],
89
90
  ["npx forgedock watch [--repo owner/repo]", "Live per-agent orchestration view (Ctrl+C to exit)"],
90
91
  ["npx forgedock report [--days 30] [--md] [--json]", "30-day pipeline impact receipts for your repo"],
91
92
  ["npx forgedock stats [--since <ver|date>] [--repo owner/repo] [--json] [--refresh]", "Version-over-version cost/time/flow/review/gate report from GitHub telemetry (no model)"],
@@ -10,6 +10,27 @@ export const ADMISSION_DEFAULTS = Object.freeze({ enabled: true, min_free_mem_mb
10
10
  // #5845: lanes admitted within `ramp_s` have not grown yet; `host.rampingMb/rampingLanes/laneFootprintMb` (effects.mjs) expose them. null `max_new_per_ramp` = no rate limit.
11
11
  export const ADMISSION_RETRY_SECONDS = 60;
12
12
 
13
+ /**
14
+ * #6047: usable cores = min(VM cores, the container's cgroup CPU quota). `read(path)` returns file text or throws; v2 `cpu.max`
15
+ * ("<quota> <period>" or "max <period>"), v1 `cpu.cfs_quota_us` (-1 = unlimited) / `cpu.cfs_period_us`. `CS_CPU_QUOTA` (set by
16
+ * the pool when the cgroup files are hidden from the lane) is the fallback. Unlimited or unreadable gives the VM cores.
17
+ */
18
+ export function quotaCores({ cores, read, env = {} } = {}) {
19
+ const vm = Number.isFinite(cores) && cores > 0 ? cores : 1;
20
+ const num = (f) => { try { const v = Number(String(read?.(f) ?? "").trim()); return Number.isFinite(v) ? v : null; } catch { return null; } };
21
+ let q = null;
22
+ try {
23
+ const [quota, period] = String(read?.("/sys/fs/cgroup/cpu.max") ?? "").trim().split(/\s+/);
24
+ if (quota && quota !== "max" && Number(quota) > 0 && Number(period) > 0) q = Number(quota) / Number(period);
25
+ } catch { /* not cgroup v2 */ }
26
+ if (q === null) {
27
+ const quota = num("/sys/fs/cgroup/cpu/cpu.cfs_quota_us"), period = num("/sys/fs/cgroup/cpu/cpu.cfs_period_us");
28
+ if (quota > 0 && period > 0) q = quota / period;
29
+ }
30
+ if (q === null) { const e = Number(env?.CS_CPU_QUOTA); if (Number.isFinite(e) && e > 0) q = e; }
31
+ return q === null ? vm : Math.max(1, Math.min(vm, Math.floor(q)));
32
+ }
33
+
13
34
  /** Workers one verification step may use (#4182): max(1, floor(cores / lanes)); bad inputs count as 1. Heavy shims pass live heavy holders (#4169). */
14
35
  export function hostParallelism({ cores, lanes } = {}) {
15
36
  const c = Number.isFinite(cores) && cores > 0 ? cores : 1, l = Number.isFinite(lanes) && lanes > 0 ? lanes : 1;
@@ -0,0 +1,30 @@
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 { quotaCores, hostParallelism } from "./admission.mjs";
6
+
7
+ const files = (m) => (f) => { if (!(f in m)) throw new Error("ENOENT"); return m[f]; };
8
+
9
+ describe("quotaCores (#6047)", () => {
10
+ it("cgroup v2 cpu.max `400000 100000` on 20 VM cores gives 4; `max 100000` gives 20", () => {
11
+ assert.equal(quotaCores({ cores: 20, read: files({ "/sys/fs/cgroup/cpu.max": "400000 100000\n" }) }), 4);
12
+ assert.equal(quotaCores({ cores: 20, read: files({ "/sys/fs/cgroup/cpu.max": "max 100000\n" }) }), 20);
13
+ });
14
+ it("cgroup v1 quota/period; -1 is unlimited", () => {
15
+ const v1 = (q) => files({ "/sys/fs/cgroup/cpu/cpu.cfs_quota_us": q, "/sys/fs/cgroup/cpu/cpu.cfs_period_us": "100000" });
16
+ assert.equal(quotaCores({ cores: 20, read: v1("200000") }), 2);
17
+ assert.equal(quotaCores({ cores: 20, read: v1("-1") }), 20);
18
+ });
19
+ it("unreadable files give the VM cores; CS_CPU_QUOTA is the fallback; a quota above the VM is capped", () => {
20
+ assert.equal(quotaCores({ cores: 20, read: files({}) }), 20);
21
+ assert.equal(quotaCores({ cores: 20, read: files({}), env: { CS_CPU_QUOTA: "4" } }), 4);
22
+ assert.equal(quotaCores({ cores: 2, read: files({ "/sys/fs/cgroup/cpu.max": "800000 100000" }) }), 2);
23
+ assert.equal(quotaCores({ cores: 20, read: files({}), env: { CS_CPU_QUOTA: "junk" } }), 20);
24
+ });
25
+ it("hostParallelism with the quota divides the container's cores, not the VM's", () => {
26
+ const cores = quotaCores({ cores: 20, read: files({ "/sys/fs/cgroup/cpu.max": "400000 100000" }) });
27
+ assert.equal(hostParallelism({ cores, lanes: 2 }), 2);
28
+ assert.equal(hostParallelism({ cores: 20, lanes: 2 }), 10);
29
+ });
30
+ });
@@ -2,28 +2,41 @@
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  import { describe, it } from "node:test";
4
4
  import assert from "node:assert/strict";
5
- import { splitAdvisory, ADVISORY_KINDS } from "./conformance.mjs";
5
+ import { splitAdvisory, ADVISORY_KINDS, ADVISORY_CODES } from "./conformance.mjs";
6
6
  import { OUTCOME_CODES as C } from "../engine/outcome-codes.mjs";
7
- import { genericInstallCommands } from "../pool/lane-tools.mjs";
7
+ import { genericInstallCommands, missingPythonModules } from "../pool/lane-tools.mjs";
8
8
 
9
9
  describe("advisory gates (unclog)", () => {
10
- it("shape rules are advisory; failing checks, regressions and unimplemented requirements block", () => {
10
+ it("shape, environment and opinion rules are advisory; failing checks, regressions and omissions block (#6083)", () => {
11
11
  const rows = [
12
12
  { code: C.CONFORMANCE_SCOPE_CREEP, kind: "scope_creep", detail: "x" },
13
13
  { code: C.CONFORMANCE_SCOPE_CREEP, detail: "review-side creep has no kind" },
14
- { code: C.CONFORMANCE_UNIMPLEMENTED, kind: "check_unknown", detail: "post-deploy check id" },
15
- { code: C.RECURRENCE_DESIGN_MISSING, kind: "design_missing", detail: "no design block" },
16
- { code: C.CONFORMANCE_UNIMPLEMENTED, kind: "amendment_invalid", detail: "unknown or incomplete amendment" },
14
+ { code: C.CONFORMANCE_E2E_UNVERIFIED, kind: "e2e_row", detail: "e2e" },
15
+ { code: C.CONFORMANCE_UNTRACKED_DEFERRAL, kind: "untracked_deferral", detail: "deferral" },
16
+ { code: C.CONFORMANCE_UNIMPLEMENTED, kind: "review_unimplemented", detail: "reviewer opinion" },
17
+ { code: C.CONFORMANCE_UNIMPLEMENTED, kind: "validate_missing", detail: "V1 no result" },
18
+ { code: C.ENV_TOOL_MISSING, kind: "validate_env", detail: "tool" },
19
+ { code: C.CONFORMANCE_GUARD_BROKEN, kind: "guard_broken", detail: "G1" },
20
+ { code: C.CONFORMANCE_UNIMPLEMENTED, kind: "page_metadata_missing", detail: "page" },
21
+ { code: C.CONFORMANCE_UNIMPLEMENTED, kind: "prod_parity_unjustified", detail: "parity" },
17
22
  { code: C.CONFORMANCE_UNIMPLEMENTED, kind: "validate_failed", detail: "V1 failed" },
18
- { code: C.CONFORMANCE_UNIMPLEMENTED, kind: "requirement_unimplemented", detail: "R1" },
19
- { code: C.CONFORMANCE_REGRESSION, kind: "guard_broken", detail: "G1" },
23
+ { code: C.CONFORMANCE_UNIMPLEMENTED, kind: "requirement_unimplemented", detail: "R1 reported not done" },
24
+ { code: C.CONFORMANCE_UNIMPLEMENTED, kind: "repro_red_green", detail: "repro" },
25
+ { code: C.CONFORMANCE_UNIMPLEMENTED, kind: "source_deliverable_untouched", detail: "tests only" },
26
+ { code: C.CONFORMANCE_REGRESSION, detail: "a.test.mjs: fails" },
27
+ { code: C.CONFORMANCE_OMISSION, detail: "narrowed" },
20
28
  ];
21
29
  const { block, advisory } = splitAdvisory(rows);
22
- assert.deepEqual(block.map((f) => f.kind), ["validate_failed", "requirement_unimplemented", "guard_broken"]);
23
- assert.equal(advisory.length, 5);
30
+ assert.deepEqual(block.map((f) => f.kind ?? f.code), ["validate_failed", "requirement_unimplemented", "repro_red_green", "source_deliverable_untouched", C.CONFORMANCE_REGRESSION, C.CONFORMANCE_OMISSION]);
31
+ assert.equal(advisory.length, 10);
24
32
  });
25
33
  it("never lists a kind that proves the change wrong", () => {
26
- for (const k of ["validate_failed", "validate_missing", "guard_broken", "requirement_unimplemented", "repro_red_green", "substitute_unverified", "untracked_deferral", "prod_parity_unjustified", "outcome_evidence_missing"]) assert.ok(!ADVISORY_KINDS.includes(k), k);
34
+ for (const k of ["validate_failed", "requirement_unimplemented", "repro_red_green", "source_deliverable_untouched", "test_missing", "test_weak"]) assert.ok(!ADVISORY_KINDS.includes(k), k);
35
+ assert.ok(!ADVISORY_CODES.includes(C.CONFORMANCE_REGRESSION) && !ADVISORY_CODES.includes(C.CONFORMANCE_OMISSION));
36
+ });
37
+ it("a kind the repo enforces by code stays blocking", () => {
38
+ const { block } = splitAdvisory([{ code: C.CONFORMANCE_GUARD_BROKEN, kind: "guard_broken", detail: "G1" }], { enforce: [C.CONFORMANCE_GUARD_BROKEN] });
39
+ assert.equal(block.length, 1);
27
40
  });
28
41
  it("a code the repo explicitly enforces stays blocking", () => {
29
42
  const { block, advisory } = splitAdvisory([{ code: C.CONFORMANCE_SCOPE_CREEP, kind: "scope_creep", detail: "x" }], { enforce: [C.CONFORMANCE_SCOPE_CREEP] });
@@ -36,11 +49,22 @@ describe("advisory gates (unclog)", () => {
36
49
 
37
50
  describe("generic sandbox install (unclog)", () => {
38
51
  it("installs by miss kind, mapping import names to packages", () => {
39
- assert.match(genericInstallCommands({ kind: "python-module", tool: "yaml" })[0], /pip install --user --quiet PyYAML/);
40
- assert.match(genericInstallCommands({ kind: "python-module", tool: "requests" })[0], /pip install --user --quiet requests/);
52
+ assert.match(genericInstallCommands({ kind: "python-module", tool: "yaml" })[0], /pip install --quiet --break-system-packages PyYAML/);
53
+ assert.match(genericInstallCommands({ kind: "python-module", tool: "requests" })[0], /pip install --quiet --break-system-packages requests/);
54
+ const y = genericInstallCommands({ kind: "python-module", tool: "yaml" })[0];
55
+ assert.match(y, /\|\| \(apt-get update -qq && apt-get install -y --no-install-recommends python3-yaml && rm -rf \/var\/lib\/apt\/lists\/\*\)$/, "apt fallback grouped so it runs only when pip fails");
41
56
  assert.match(genericInstallCommands({ kind: "node-module", tool: "@adobe/css-tools" })[0], /^npm install --no-save .* @adobe\/css-tools$/);
42
- assert.match(genericInstallCommands({ kind: "command", tool: "shellcheck" })[0], /apt-get install -y --no-install-recommends shellcheck/);
43
- assert.match(genericInstallCommands({ kind: "command", tool: "shellcheck" }, { root: false })[0], /^sudo sh -c /);
57
+ assert.match(genericInstallCommands({ kind: "command", tool: "ripgrep" })[0], /apt-get install -y --no-install-recommends ripgrep/);
58
+ assert.match(genericInstallCommands({ kind: "command", tool: "ripgrep" }, { root: false })[0], /^sudo sh -c /);
59
+ });
60
+ it("#6138 python modules install system-wide, never --user, with the apt fallback kept; non-root goes through sudo", () => {
61
+ const root = genericInstallCommands({ kind: "python-module", tool: "yaml" })[0];
62
+ assert.doesNotMatch(root, /--user/);
63
+ assert.match(root, /^python3 -m pip install --quiet --break-system-packages PyYAML \|\| python3 -m pip install --quiet PyYAML \|\| \(apt-get/);
64
+ const nr = genericInstallCommands({ kind: "python-module", tool: "PIL" }, { root: false })[0];
65
+ assert.doesNotMatch(nr, /--user/);
66
+ assert.match(nr, /^sudo sh -c .*Pillow.*\|\| \(sudo sh -c .*python3-pil/);
67
+ assert.deepEqual(missingPythonModules("ModuleNotFoundError: No module named 'yaml.nodes'\nNo module named foo"), ["yaml", "foo"]);
44
68
  });
45
69
  it("refuses unsafe names and kinds nothing can install", () => {
46
70
  for (const m of [{ kind: "command", tool: "a;rm -rf /" }, { kind: "command", tool: "$(x)" }, { kind: "command", tool: "../x" }, { kind: "command", tool: "bin/x" }, { kind: "environment", tool: "db" }, { kind: "forgedock-path", tool: "forgedock" }, {}])
@@ -6,7 +6,7 @@
6
6
  * Pure: no imports.
7
7
  */
8
8
 
9
- /** kind -> {shape, doc, example}. `supersedes` takes only a "#N" guard issue or a mechanism, never a validate-row id (G2): that is substitute-validate. */
9
+ /** kind -> {shape, doc, example}. `supersedes` takes only a "#N" guard issue or a mechanism, never a validate-row id (G2). */
10
10
  export const AMENDMENT_SHAPES = Object.freeze({
11
11
  "add-deliverable": { shape: `{"kind":"add-deliverable","path":"<file>"}`, doc: "a file not listed.", example: { kind: "add-deliverable", path: "bin/x.mjs", why: "needed" } },
12
12
  "add-requirement": { shape: `{"kind":"add-requirement","requirement":{"id":"R9","quote":"<verbatim from the issue>","disposition":"deliver|defer|post-deploy"}}`, doc: "a missed requirement.", example: { kind: "add-requirement", requirement: { id: "R9", quote: "q", disposition: "deliver" }, why: "missed" } },
@@ -14,18 +14,17 @@ export const AMENDMENT_SHAPES = Object.freeze({
14
14
  "post-deploy": { example: { kind: "post-deploy", requirement: "R1", why: "measured after release", check: "c1" } },
15
15
  "amend-requirement": { shape: `{"kind":"amend-requirement","requirement":"R#","text":"<revised wording>"}`, doc: "reworded.", example: { kind: "amend-requirement", requirement: "R1", text: "revised", why: "reworded" } },
16
16
  supersedes: { shape: `{"kind":"supersedes","guard":"#N"}`, doc: `overrides a guard_broken failure; {"kind":"supersedes","mechanism":"<name>"} retires every guard whose test this lane deletes. A validate-row id is never a supersedes guard.`, example: { kind: "supersedes", guard: "#123", why: "obsolete" } },
17
- "substitute-validate": { shape: `{"kind":"substitute-validate","validate":"G2","command":"<runnable equivalent>"}`, doc: "a validate row whose command is unrunnable.", example: { kind: "substitute-validate", validate: "G2", command: "node --test a.test.mjs", why: "frozen command is unrunnable" } },
18
17
  "out-of-band": { shape: `{"kind":"out-of-band","requirement":"R#","evidence":"<job that measures it>"}`, doc: "measured by a job.", example: { kind: "out-of-band", requirement: "R1", evidence: ".github/workflows/bench.yml", why: "measured by the bench job" } },
19
18
  decision: { shape: `{"kind":"decision","decision":{"choice":"","anchors":["<base path>"],"supersedes":"<id>"}}`, doc: "supersedes changes an H-row.", example: { kind: "decision", decision: { choice: "c", anchors: ["bin/x.mjs"] }, why: "w" } },
20
19
  });
21
20
 
22
- export const AMEND_KINDS = Object.freeze(["add-deliverable", "add-requirement", "defer", "post-deploy", "amend-requirement", "supersedes", "decision", "substitute-validate", "out-of-band"]);
21
+ export const AMEND_KINDS = Object.freeze(["add-deliverable", "add-requirement", "defer", "post-deploy", "amend-requirement", "supersedes", "decision", "out-of-band"]);
23
22
 
24
23
  /** One valid example per kind (supersedes only with #N). */
25
24
  export const AMENDMENT_EXAMPLES = Object.freeze(AMEND_KINDS.map((k) => AMENDMENT_SHAPES[k].example));
26
25
 
27
26
  /** The builder-prompt bullet list, in the order the prompt documents them. */
28
27
  export function amendmentPromptLines() {
29
- return ["add-deliverable", "add-requirement", "defer", "amend-requirement", "supersedes", "substitute-validate", "out-of-band", "decision"]
28
+ return ["add-deliverable", "add-requirement", "defer", "amend-requirement", "supersedes", "out-of-band", "decision"]
30
29
  .map((k) => `- ${AMENDMENT_SHAPES[k].shape}: ${AMENDMENT_SHAPES[k].doc}`).join("\n");
31
30
  }