forgedock 1.60.0 → 1.61.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 (78) hide show
  1. package/bin/config-schema.mjs +44 -1
  2. package/bin/engine/runlog.mjs +52 -0
  3. package/bin/engine-cli.mjs +9 -4
  4. package/bin/env/bench.mjs +38 -0
  5. package/bin/env/cli.mjs +134 -0
  6. package/bin/env/env.mjs +339 -0
  7. package/bin/forgedock.mjs +32 -3
  8. package/bin/help-text.mjs +2 -0
  9. package/bin/lean/ci-budget.mjs +3 -1
  10. package/bin/lean/ci-classify.mjs +74 -0
  11. package/bin/lean/ci-classify.test.mjs +147 -0
  12. package/bin/lean/ci-emit.mjs +175 -0
  13. package/bin/lean/ci-emit.test.mjs +177 -0
  14. package/bin/lean/ci-preflight.mjs +183 -0
  15. package/bin/lean/ci-preflight.test.mjs +122 -0
  16. package/bin/lean/ci-runner-health.mjs +213 -0
  17. package/bin/lean/ci-runner-health.test.mjs +113 -0
  18. package/bin/lean/ci-watch.mjs +79 -0
  19. package/bin/lean/ci-watch.test.mjs +80 -0
  20. package/bin/lean/conformance.mjs +7 -1
  21. package/bin/lean/conformance.test.mjs +7 -1
  22. package/bin/lean/depcache.mjs +38 -8
  23. package/bin/lean/deploy-stages.mjs +514 -0
  24. package/bin/lean/deploy-stages.test.mjs +580 -0
  25. package/bin/lean/effects.mjs +50 -0
  26. package/bin/lean/execution.mjs +8 -1
  27. package/bin/lean/lean.mjs +61 -12
  28. package/bin/lean/lean.test.mjs +87 -0
  29. package/bin/lean/preflight.mjs +62 -1
  30. package/bin/lean/preflight.test.mjs +30 -1
  31. package/bin/lean/release-deploy.mjs +12 -6
  32. package/bin/lean/release-flakes.mjs +16 -0
  33. package/bin/lean/release-flakes.test.mjs +15 -0
  34. package/bin/lean/release-gates.mjs +24 -1
  35. package/bin/lean/release-ledger.mjs +21 -0
  36. package/bin/lean/release-minutes-timing.test.mjs +57 -0
  37. package/bin/lean/release-minutes.mjs +98 -0
  38. package/bin/lean/release-promote.mjs +444 -0
  39. package/bin/lean/release-promote.test.mjs +470 -0
  40. package/bin/lean/release-rollback.mjs +14 -6
  41. package/bin/lean/release.mjs +31 -2
  42. package/bin/lean/sandbox-remote.mjs +11 -3
  43. package/bin/lean/testengine-recall.mjs +82 -0
  44. package/bin/lean/testengine-recall.test.mjs +103 -0
  45. package/bin/lean/testengine-shard.mjs +150 -0
  46. package/bin/lean/testengine-shard.test.mjs +111 -0
  47. package/bin/lean/testengine.mjs +486 -0
  48. package/bin/lean/testengine.test.mjs +303 -0
  49. package/bin/lean/validate-catalog.mjs +16 -0
  50. package/bin/lean/validate-catalog.test.mjs +14 -1
  51. package/bin/lean/verify-settle.test.mjs +156 -0
  52. package/bin/lean/verify.mjs +98 -3
  53. package/bin/pool/agent.mjs +65 -6
  54. package/bin/pool/ci-events.mjs +183 -0
  55. package/bin/pool/ci-events.test.mjs +143 -0
  56. package/bin/pool/docker.mjs +7 -0
  57. package/bin/pool/lane-tools.mjs +32 -0
  58. package/bin/pool/router.mjs +21 -1
  59. package/bin/pool/warm.mjs +14 -3
  60. package/bin/stats/ci-awareness.mjs +66 -0
  61. package/bin/stats/index.mjs +44 -3
  62. package/bin/stats/release-ledger.test.mjs +226 -0
  63. package/bin/stats/release.mjs +365 -1
  64. package/bin/stats/stats.test.mjs +36 -0
  65. package/docs/CI.md +31 -0
  66. package/docs/CONFIG.md +235 -2
  67. package/docs/ENV-LIBRARY.md +172 -0
  68. package/docs/STATS.md +43 -0
  69. package/docs/ci-events.md +88 -0
  70. package/docs/test-engine.md +98 -0
  71. package/package.json +1 -1
  72. package/pool/README.md +1 -0
  73. package/pool/image/entrypoint.sh +15 -3
  74. package/pool/services/docker-compose.yml +53 -0
  75. package/pool/services/git-mirror.sh +22 -0
  76. package/scripts/acceptance-red-green.sh +5 -2
  77. package/scripts/acceptance-red-green.test.sh +11 -0
  78. package/templates/github-actions/forge-env/action.yml +65 -0
@@ -19,6 +19,17 @@ export const TOP_LEVEL = [
19
19
  /** Sections whose direct children are a closed set: another child is an unknown key. */
20
20
  export const CLOSED = {
21
21
  "verification.ci_local": ["mode", "exclude_jobs", "include_jobs", "extra_commands", "services", "budget_minutes", "max_parallel"],
22
+ "env.snapshots": ["enabled", "store", "keep", "max_age_days", "ready", "base_image", "image"],
23
+ "env.proxies": ["npm", "pypi", "apt", "git"],
24
+ // #5710 test engine. The one-level parser flattens these under `ci`, so every name is unique within `ci`.
25
+ "ci.tests": ["selection", "suites", "run_all", "ignore", "test_globs", "full_branches", "graduate_after", "graduate_min_failing", "shards", "shard_target_s", "quarantine", "quarantine_after", "quarantine_window_days", "recall_ledger"],
26
+ // #5712: the deploy stage engine (bin/lean/deploy-stages.mjs); the stage entries themselves are checked by validateEngine
27
+ "deploy.engine": ["enabled", "live_release_command", "stage_timeout_s", "colour", "services", "canary", "rollback", "stages"],
28
+ "deploy.engine.colour": ["active_command", "names"],
29
+ "deploy.engine.services": ["mode", "desired_command", "live_command"],
30
+ "deploy.engine.canary": ["health_command", "low", "medium", "high"],
31
+ "deploy.engine.rollback": ["budget_s", "shift_back_command", "abort_command"],
32
+ "deploy.promote": ["enabled", "shadow", "required_checks", "evidence_app", "cache_ref", "cache_mode", "builder", "rebuild_all", "services"], // #5711, read by bin/lean/release-promote.mjs
22
33
  };
23
34
 
24
35
  /** Typed keys: list | number | bool | scalar | {enum:[...]}. */
@@ -30,9 +41,41 @@ export const TYPES = {
30
41
  "verification.ci_local.extra_commands": "list",
31
42
  "verification.ci_local.budget_minutes": "number",
32
43
  "verification.ci_local.max_parallel": "number",
44
+ "env.snapshots.enabled": "bool",
45
+ "env.snapshots.store": { enum: ["local", "oci"] },
46
+ "env.snapshots.keep": "number",
47
+ "env.snapshots.max_age_days": "number",
48
+ "env.snapshots.ready": "number",
49
+ "ci.tests.selection": { enum: ["off", "shadow", "enforce"] },
50
+ "ci.tests.quarantine": { enum: ["off", "report", "non-blocking"] },
51
+ "ci.tests.suites": "list",
52
+ "ci.tests.run_all": "list",
53
+ "ci.tests.ignore": "list",
54
+ "ci.tests.test_globs": "list",
55
+ "ci.tests.full_branches": "list",
56
+ "ci.tests.graduate_after": "number",
57
+ "ci.tests.graduate_min_failing": "number",
58
+ "ci.tests.shards": "number",
59
+ "ci.tests.shard_target_s": "number",
60
+ "ci.tests.quarantine_after": "number",
61
+ "ci.tests.quarantine_window_days": "number",
33
62
  "engine.path": { enum: ["core", "full", "lean", "auto"] },
63
+ "deploy.engine.enabled": "bool",
64
+ "deploy.engine.stage_timeout_s": "number",
65
+ "deploy.engine.stages": "list",
66
+ "deploy.engine.colour.names": "list",
67
+ "deploy.engine.services.mode": { enum: ["off", "shadow", "enforce"] },
68
+ "deploy.engine.rollback.budget_s": "number",
34
69
  "billing.enabled": "bool",
35
70
  "gate.required_checks": "list",
71
+ "verify.settle": { enum: ["fixed", "shadow", "condition"] }, // #5718
72
+ "verify.cancel_superseded": { enum: ["off", "own", "all", "true", "false"] },
73
+ "stats.ledger_ci_workflows": "list",
74
+ "deploy.promote.enabled": "bool",
75
+ "deploy.promote.shadow": "bool",
76
+ "deploy.promote.required_checks": "list",
77
+ "deploy.promote.rebuild_all": "list",
78
+ "deploy.promote.cache_mode": { enum: ["min", "max"] },
36
79
  };
37
80
 
38
81
  /** Keys the legacy `full` path never reads (the core path reads them: bin/engine-cli.mjs readEnvConfig, readConformanceMode). */
@@ -57,7 +100,7 @@ export function scanKeys(text) {
57
100
  if (/^\s*(#.*)?$/.test(line)) continue;
58
101
  const indent = line.match(/^ */)[0].length;
59
102
  if (skipAbove >= 0) { if (indent > skipAbove) continue; skipAbove = -1; }
60
- if (/^\s*-(\s|$)/.test(line)) continue;
103
+ if (/^\s*-(\s|$)/.test(line)) { skipAbove = indent; continue; } // a list item; the keys of a map item (deeper lines) belong to the item, not to the parent
61
104
  const m = line.match(/^( *)([A-Za-z_][\w.-]*)\s*:(?:\s+(.*))?$/);
62
105
  if (!m) continue;
63
106
  while (stack.length && stack[stack.length - 1].indent >= indent) stack.pop();
@@ -254,3 +254,55 @@ export function deriveState(allEvents, { path = "full" } = {}) {
254
254
  }
255
255
  return s;
256
256
  }
257
+
258
+ /** #5697: the most run-log text a lane exports in its result (bytes); a longer log is cut from the middle. */
259
+ export const RUNLOG_EXPORT_MAX = 20 * 1024 * 1024;
260
+
261
+ /** Keep the head and the tail of `text` (whole lines, half of `max` each) with a LOG_TRUNCATED marker event between them. */
262
+ export function capLog(text, max = RUNLOG_EXPORT_MAX) {
263
+ if (Buffer.byteLength(text) <= max) return text;
264
+ const lines = text.split("\n").filter((l) => l.trim());
265
+ const half = Math.floor(max / 2);
266
+ let head = 0, hb = 0, tail = lines.length, tb = 0;
267
+ while (head < tail && hb + Buffer.byteLength(lines[head]) + 1 <= half) hb += Buffer.byteLength(lines[head++]) + 1;
268
+ while (tail > head && tb + Buffer.byteLength(lines[tail - 1]) + 1 <= half) tb += Buffer.byteLength(lines[--tail]) + 1;
269
+ const marker = JSON.stringify({ event: "LOG_TRUNCATED", dropped_lines: tail - head, dropped_bytes: Buffer.byteLength(text) - hb - tb, ts: new Date().toISOString() });
270
+ return [...lines.slice(0, head), marker, ...lines.slice(tail)].join("\n") + "\n";
271
+ }
272
+
273
+ /** #5697: `result` plus the lane's own run log (capped) as `runLog`, so the host can keep it after the sandbox is gone. Never throws. */
274
+ export function attachRunLog(result, { dir, issue, repo = null, max = RUNLOG_EXPORT_MAX }) {
275
+ try {
276
+ const path = runLogPath(dir, issue, repo);
277
+ if (!existsSync(path)) return result;
278
+ return { ...result, runLog: capLog(readFileSync(path, "utf-8"), max) };
279
+ } catch { return result; }
280
+ }
281
+
282
+ /**
283
+ * #5697: append the events of an exported run log (jsonl text) to the host run log, once. Each event is keyed by its
284
+ * lane-side seq + ts + event (`remote_seq` after a merge), so collecting the same log again adds nothing; merged events
285
+ * get the next host seq. Returns the number appended; never throws.
286
+ */
287
+ export function mergeRemoteLog(dir, issue, runLog, { repo = null } = {}) {
288
+ try {
289
+ const incoming = [];
290
+ for (const l of String(runLog ?? "").split("\n")) { if (!l.trim()) continue; try { incoming.push(JSON.parse(l)); } catch { /* a cut line */ } }
291
+ if (!incoming.length) return 0;
292
+ mkdirSync(dir, { recursive: true });
293
+ const path = runLogPath(dir, issue, repo);
294
+ const existing = parseLog(path);
295
+ const key = (e, seq) => `${seq}|${e.ts ?? ""}|${e.event ?? ""}`;
296
+ const seen = new Set(existing.map((e) => key(e, e.remote_seq ?? e.seq)));
297
+ let seq = existing.length;
298
+ const lines = [];
299
+ for (const e of incoming) {
300
+ const k = key(e, e.seq ?? ""); if (seen.has(k)) continue;
301
+ seen.add(k);
302
+ const { seq: remote, ...rest } = e;
303
+ lines.push(JSON.stringify({ seq: ++seq, ...rest, ...(remote !== undefined ? { remote_seq: remote } : {}) }));
304
+ }
305
+ if (lines.length) appendFileSync(path, lines.join("\n") + "\n");
306
+ return lines.length;
307
+ } catch { return 0; }
308
+ }
@@ -23,7 +23,7 @@ import { join, resolve as resolvePath } from "node:path";
23
23
  import { runIssue, DEFAULT_MAX_ATTEMPTS, sanitizeLeaseHost, ENGINE_VERSION } from "./engine.mjs";
24
24
  import { makeProjector } from "./engine/projector.mjs";
25
25
  import { decomposedSubissues, isDecomposedRecord, isTrustedActor, parseDependsOn } from "./engine/phases.mjs";
26
- import { readLog, readLogFile, deriveState, runLogPath, migrateRunLogs } from "./engine/runlog.mjs";
26
+ import { readLog, readLogFile, deriveState, runLogPath, migrateRunLogs, attachRunLog } from "./engine/runlog.mjs";
27
27
  import { assertOpenCodeNativeRuntime } from "./runner.mjs";
28
28
  import { parseForgeYaml } from "./forge-utils.mjs";
29
29
  import { makeEmitTelemetry } from "./engine/telemetry-seam.mjs";
@@ -327,6 +327,10 @@ export function readFollowupsDefaultMilestone(cwd = process.cwd()) {
327
327
  export function readFollowupsRollupLabel(cwd = process.cwd()) {
328
328
  try { return String(parseForgeYaml(readFileSync(join(cwd, "forge.yaml"), "utf8"))?.followups?.rollup_issue_label ?? "").trim() || undefined; } catch { return undefined; }
329
329
  }
330
+ /** #5692: forge.yaml `ci.fail_fast` (`deterministic` cancels a CI run on a downstream-class failure; anything else is off), or undefined. */
331
+ export function readCiFailFast(cwd = process.cwd()) {
332
+ try { const v = String(parseForgeYaml(readFileSync(join(cwd, "forge.yaml"), "utf8"))?.ci?.fail_fast ?? "").trim(); return v === "deterministic" ? v : undefined; } catch { return undefined; }
333
+ }
330
334
  /** #4389: forge.yaml `post_deploy.precondition_cmd` (exit 0 = ready, 1 = parked, other = ignored), or null. */
331
335
  export function readPreconditionCmd(cwd = process.cwd()) {
332
336
  try {
@@ -981,7 +985,8 @@ export async function runFromCli(argv, deps = {}) {
981
985
  const recoverCode = flag(argv, "--recover");
982
986
  const recoverAttempt = Number(flag(argv, "--recover-attempt"));
983
987
  const recover = recoverCode && !recoverCode.startsWith("--") ? { code: recoverCode, attempt: Number.isInteger(recoverAttempt) && recoverAttempt > 0 ? recoverAttempt : 1, final: !argv.includes("--recover-nonfinal") } : null;
984
- const report = (r) => { if (resultFile) (deps.writeAtomic ?? writeResultAtomic)(resultFile, JSON.stringify(r) + "\n"); return r; };
988
+ // #5697: a sandbox lane (result under /result/) ships its run log with the result; the host merges it and strips it.
989
+ const report = (r) => { if (resultFile) (deps.writeAtomic ?? writeResultAtomic)(resultFile, JSON.stringify(resultFile.startsWith("/result/") ? attachRunLog(r, { dir: runDir(), issue, repo }) : r) + "\n"); return r; };
985
990
  try {
986
991
  await assertRepoMatchesCwd(io, repo, { sleep: deps.sleep });
987
992
  } catch (e) {
@@ -1070,7 +1075,7 @@ export async function runFromCli(argv, deps = {}) {
1070
1075
  ...(rotatorKind({ execution: readExecution(process.cwd()), env }) ? { accountRotator: rotatorKind({ execution: readExecution(process.cwd()), env }) } : {}), // #5094, #5205: detected
1071
1076
  onTeardown: (fn) => { teardown = fn; }, ...(env.FORGEDOCK_BATCH_ID ? { batchId: env.FORGEDOCK_BATCH_ID } : {}), ...(placement ? { placement } : {}), ...(recover ? { recover } : {}),
1072
1077
  emitTelemetry: deps.emitTelemetry ?? composeEmit(makeEmitTelemetry({ repo: leanRepo }), makeEventEmitter({ repo: leanRepo, config: readEvents() }).emit),
1073
- admission: readAdmission(), heavy: readHeavy(), ...readCoreLimits(), ...readEnvConfig(), ...(readMergeWait() ? { mergeWait: readMergeWait() } : {}), ...(readConformanceMode() ? { conformance: readConformanceMode() } : {}), ...(readConformanceKinds() ? { conformanceKinds: readConformanceKinds() } : {}), ...(readConformanceMutation() ? { conformanceMutation: "report" } : {}), ...(readContextPack() ? { contextPack: readContextPack() } : {}), ...(readSequenceVersioned() ? { sequenceVersioned: readSequenceVersioned() } : {}), ...(readSharedSurfaces() ? { sharedSurfaces: readSharedSurfaces() } : {}), ...(readReviewIncomplete() ? { reviewIncomplete: readReviewIncomplete() } : {}), ...(readLaneInstructions() ? { laneInstructions: readLaneInstructions() } : {}), ...(readReproTest() ? { reproTest: readReproTest() } : {}), ...(readReproQuality() ? { reproQuality: readReproQuality() } : {}), ...(readExplore() ? { explore: readExplore() } : {}), ...(readExperiment() ? { experiment: readExperiment() } : {}), light: readLight(), ...(readCloseParent() ? { closeParent: true } : {}), ...(readReviewTrigger() ? { reviewTrigger: readReviewTrigger() } : {}), ...(readVerify() ? { verify: readVerify() } : {}), ...readPrecheckOptions(), ...(model ? { builderModel: model } : {}), ...(readLeanSetting("reviewer_model") ? { reviewerModel: readLeanSetting("reviewer_model") } : {}), ...(readFixModel() ? { fixModel: readFixModel() } : {}), ...(readBuilderRouting() ? { builderRouting: readBuilderRouting() } : {}), ...(readVerifier() ? { verifier: readVerifier() } : {}), ...(readHostCaps() ? { hostCaps: readHostCaps() } : {}), hostFallback: readHostFallback(), ...readRelayCaps(), ...(readSequenceRegenerate() ? { sequenceRegenerate: readSequenceRegenerate() } : {}), ...(readBaseMerge() ? { baseMerge: readBaseMerge() } : {}), ...(readFollowupsDefaultMilestone() ? { followupsDefaultMilestone: readFollowupsDefaultMilestone() } : {}), ...(readFollowupsRollupLabel() ? { followupsRollupLabel: readFollowupsRollupLabel() } : {}), ...(Number.isInteger(Number(readLeanSetting("contract_max_corrections"))) && Number(readLeanSetting("contract_max_corrections")) >= 1 ? { contractMaxCorrections: Number(readLeanSetting("contract_max_corrections")) } : {}), ...(Number.isInteger(Number(readLeanSetting("review_max_resumes"))) && Number(readLeanSetting("review_max_resumes")) >= 1 ? { reviewMaxResumes: Number(readLeanSetting("review_max_resumes")) } : {}) });
1078
+ admission: readAdmission(), heavy: readHeavy(), ...readCoreLimits(), ...readEnvConfig(), ...(readMergeWait() ? { mergeWait: readMergeWait() } : {}), ...(readConformanceMode() ? { conformance: readConformanceMode() } : {}), ...(readConformanceKinds() ? { conformanceKinds: readConformanceKinds() } : {}), ...(readConformanceMutation() ? { conformanceMutation: "report" } : {}), ...(readContextPack() ? { contextPack: readContextPack() } : {}), ...(readSequenceVersioned() ? { sequenceVersioned: readSequenceVersioned() } : {}), ...(readSharedSurfaces() ? { sharedSurfaces: readSharedSurfaces() } : {}), ...(readReviewIncomplete() ? { reviewIncomplete: readReviewIncomplete() } : {}), ...(readLaneInstructions() ? { laneInstructions: readLaneInstructions() } : {}), ...(readReproTest() ? { reproTest: readReproTest() } : {}), ...(readReproQuality() ? { reproQuality: readReproQuality() } : {}), ...(readExplore() ? { explore: readExplore() } : {}), ...(readExperiment() ? { experiment: readExperiment() } : {}), light: readLight(), ...(readCloseParent() ? { closeParent: true } : {}), ...(readReviewTrigger() ? { reviewTrigger: readReviewTrigger() } : {}), ...(readVerify() ? { verify: readVerify() } : {}), ...readPrecheckOptions(), ...(model ? { builderModel: model } : {}), ...(readLeanSetting("reviewer_model") ? { reviewerModel: readLeanSetting("reviewer_model") } : {}), ...(readFixModel() ? { fixModel: readFixModel() } : {}), ...(readBuilderRouting() ? { builderRouting: readBuilderRouting() } : {}), ...(readVerifier() ? { verifier: readVerifier() } : {}), ...(readHostCaps() ? { hostCaps: readHostCaps() } : {}), hostFallback: readHostFallback(), ...readRelayCaps(), ...(readSequenceRegenerate() ? { sequenceRegenerate: readSequenceRegenerate() } : {}), ...(readBaseMerge() ? { baseMerge: readBaseMerge() } : {}), ...(readFollowupsDefaultMilestone() ? { followupsDefaultMilestone: readFollowupsDefaultMilestone() } : {}), ...(readFollowupsRollupLabel() ? { followupsRollupLabel: readFollowupsRollupLabel() } : {}), ...(readCiFailFast() ? { ci: { fail_fast: readCiFailFast() } } : {}), ...(Number.isInteger(Number(readLeanSetting("contract_max_corrections"))) && Number(readLeanSetting("contract_max_corrections")) >= 1 ? { contractMaxCorrections: Number(readLeanSetting("contract_max_corrections")) } : {}), ...(Number.isInteger(Number(readLeanSetting("review_max_resumes"))) && Number(readLeanSetting("review_max_resumes")) >= 1 ? { reviewMaxResumes: Number(readLeanSetting("review_max_resumes")) } : {}) });
1074
1079
  } catch (e) { if (!interrupted) report({ terminalReason: "engine-error", detail: String(e?.message ?? e).slice(0, 500) }); throw e; }
1075
1080
  finally { if (!interrupted) for (const [sig, f] of Object.entries(handlers)) off(sig, f); }
1076
1081
  if (interrupted) return lres; // the signal handler reported and exits
@@ -1923,7 +1928,7 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
1923
1928
  lanes = { adopt: null, runOne: (n, ln, ctx = {}) => runCore({ issue: n, repo, lane: ln, deferPostRun: true, // #5437: orchestrate runs result.postRun once the slot is free
1924
1929
  laneOverride, ...(ctx.placement ? { placement: { ...ctx.placement, mode: execMode() } } : {}), ...(ctx.recover ? { recover: ctx.recover } : {}), branches, cwd, dir, io: leanIo, agentId: `orch_${process.pid}_${n}`, emitTelemetry, batchId: batch.id,
1925
1930
  ...(rotatorKind({ execution: readExecution(cwd), env }) ? { accountRotator: rotatorKind({ execution: readExecution(cwd), env }) } : {}), // #5094, #5205: detected
1926
- admission: readAdmission(cwd), heavy: readHeavy(cwd), ...readCoreLimits(cwd), ...readEnvConfig(cwd), ...(readMergeWait(cwd) ? { mergeWait: readMergeWait(cwd) } : {}), ...(readConformanceMode(cwd) ? { conformance: readConformanceMode(cwd) } : {}), ...(readConformanceKinds(cwd) ? { conformanceKinds: readConformanceKinds(cwd) } : {}), ...(readConformanceMutation(cwd) ? { conformanceMutation: "report" } : {}), ...(readContextPack(cwd) ? { contextPack: readContextPack(cwd) } : {}), ...(readSequenceVersioned(cwd) ? { sequenceVersioned: readSequenceVersioned(cwd) } : {}), ...(readSharedSurfaces(cwd) ? { sharedSurfaces: readSharedSurfaces(cwd) } : {}), ...(readReviewIncomplete(cwd) ? { reviewIncomplete: readReviewIncomplete(cwd) } : {}), ...(readLaneInstructions(cwd) ? { laneInstructions: readLaneInstructions(cwd) } : {}), ...(readReproTest(cwd) ? { reproTest: readReproTest(cwd) } : {}), ...(readReproQuality(cwd) ? { reproQuality: readReproQuality(cwd) } : {}), ...(readExplore(cwd) ? { explore: readExplore(cwd) } : {}), ...(readExperiment(cwd) ? { experiment: readExperiment(cwd) } : {}), light: readLight(cwd), ...(readCloseParent(cwd) ? { closeParent: true } : {}), ...(readReviewTrigger(cwd) ? { reviewTrigger: readReviewTrigger(cwd) } : {}), ...(readVerify(cwd) ? { verify: readVerify(cwd) } : {}), ...readPrecheckOptions(cwd), ...(model ? { builderModel: model } : {}), ...(readLeanSetting("reviewer_model", cwd) ? { reviewerModel: readLeanSetting("reviewer_model", cwd) } : {}), ...(readFixModel(cwd) ? { fixModel: readFixModel(cwd) } : {}), ...(readBuilderRouting(cwd) ? { builderRouting: readBuilderRouting(cwd) } : {}), ...(readVerifier(cwd) ? { verifier: readVerifier(cwd) } : {}), ...(readHostCaps(cwd) ? { hostCaps: readHostCaps(cwd) } : {}), hostFallback: readHostFallback(cwd), ...readRelayCaps(), ...(readSequenceRegenerate(cwd) ? { sequenceRegenerate: readSequenceRegenerate(cwd) } : {}), ...(readBaseMerge(cwd) ? { baseMerge: readBaseMerge(cwd) } : {}), ...(readFollowupsDefaultMilestone(cwd) ? { followupsDefaultMilestone: readFollowupsDefaultMilestone(cwd) } : {}), ...(readFollowupsRollupLabel(cwd) ? { followupsRollupLabel: readFollowupsRollupLabel(cwd) } : {}), ...(Number.isInteger(Number(readLeanSetting("contract_max_corrections", cwd))) && Number(readLeanSetting("contract_max_corrections", cwd)) >= 1 ? { contractMaxCorrections: Number(readLeanSetting("contract_max_corrections", cwd)) } : {}), ...(Number.isInteger(Number(readLeanSetting("review_max_resumes", cwd))) && Number(readLeanSetting("review_max_resumes", cwd)) >= 1 ? { reviewMaxResumes: Number(readLeanSetting("review_max_resumes", cwd)) } : {}) }) };
1931
+ admission: readAdmission(cwd), heavy: readHeavy(cwd), ...readCoreLimits(cwd), ...readEnvConfig(cwd), ...(readMergeWait(cwd) ? { mergeWait: readMergeWait(cwd) } : {}), ...(readConformanceMode(cwd) ? { conformance: readConformanceMode(cwd) } : {}), ...(readConformanceKinds(cwd) ? { conformanceKinds: readConformanceKinds(cwd) } : {}), ...(readConformanceMutation(cwd) ? { conformanceMutation: "report" } : {}), ...(readContextPack(cwd) ? { contextPack: readContextPack(cwd) } : {}), ...(readSequenceVersioned(cwd) ? { sequenceVersioned: readSequenceVersioned(cwd) } : {}), ...(readSharedSurfaces(cwd) ? { sharedSurfaces: readSharedSurfaces(cwd) } : {}), ...(readReviewIncomplete(cwd) ? { reviewIncomplete: readReviewIncomplete(cwd) } : {}), ...(readLaneInstructions(cwd) ? { laneInstructions: readLaneInstructions(cwd) } : {}), ...(readReproTest(cwd) ? { reproTest: readReproTest(cwd) } : {}), ...(readReproQuality(cwd) ? { reproQuality: readReproQuality(cwd) } : {}), ...(readExplore(cwd) ? { explore: readExplore(cwd) } : {}), ...(readExperiment(cwd) ? { experiment: readExperiment(cwd) } : {}), light: readLight(cwd), ...(readCloseParent(cwd) ? { closeParent: true } : {}), ...(readReviewTrigger(cwd) ? { reviewTrigger: readReviewTrigger(cwd) } : {}), ...(readVerify(cwd) ? { verify: readVerify(cwd) } : {}), ...readPrecheckOptions(cwd), ...(model ? { builderModel: model } : {}), ...(readLeanSetting("reviewer_model", cwd) ? { reviewerModel: readLeanSetting("reviewer_model", cwd) } : {}), ...(readFixModel(cwd) ? { fixModel: readFixModel(cwd) } : {}), ...(readBuilderRouting(cwd) ? { builderRouting: readBuilderRouting(cwd) } : {}), ...(readVerifier(cwd) ? { verifier: readVerifier(cwd) } : {}), ...(readHostCaps(cwd) ? { hostCaps: readHostCaps(cwd) } : {}), hostFallback: readHostFallback(cwd), ...readRelayCaps(), ...(readSequenceRegenerate(cwd) ? { sequenceRegenerate: readSequenceRegenerate(cwd) } : {}), ...(readBaseMerge(cwd) ? { baseMerge: readBaseMerge(cwd) } : {}), ...(readFollowupsDefaultMilestone(cwd) ? { followupsDefaultMilestone: readFollowupsDefaultMilestone(cwd) } : {}), ...(readFollowupsRollupLabel(cwd) ? { followupsRollupLabel: readFollowupsRollupLabel(cwd) } : {}), ...(readCiFailFast(cwd) ? { ci: { fail_fast: readCiFailFast(cwd) } } : {}), ...(Number.isInteger(Number(readLeanSetting("contract_max_corrections", cwd))) && Number(readLeanSetting("contract_max_corrections", cwd)) >= 1 ? { contractMaxCorrections: Number(readLeanSetting("contract_max_corrections", cwd)) } : {}), ...(Number.isInteger(Number(readLeanSetting("review_max_resumes", cwd))) && Number(readLeanSetting("review_max_resumes", cwd)) >= 1 ? { reviewMaxResumes: Number(readLeanSetting("review_max_resumes", cwd)) } : {}) }) };
1927
1932
  } else {
1928
1933
  const laneScript = deps.laneScript ?? fileURLToPath(new URL("./forgedock.mjs", import.meta.url));
1929
1934
  // #4690: lanes learn K (the default MemoryMax is derived from it); one line says so when no scope caps them.
@@ -0,0 +1,38 @@
1
+ #!/usr/bin/env node
2
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
3
+ // SPDX-License-Identifier: AGPL-3.0-or-later
4
+ /**
5
+ * Measures how a lane gets its dependency trees from the env store, on this machine's filesystem:
6
+ * node bin/env/bench.mjs [--files 19677] [--dir <scratch dir>]
7
+ * Builds a synthetic node_modules of N small files, publishes it, then times stage (pool host, outside jobs), a claim
8
+ * of a staged copy (rename) and a claim with nothing staged (hardlink per file). File size does not matter to either:
9
+ * no file data is read or written after publish. Prints one JSON line.
10
+ */
11
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
12
+ import { tmpdir } from "node:os";
13
+ import { join } from "node:path";
14
+ import { makeDepCache } from "../lean/depcache.mjs";
15
+ import { makeEnvStore } from "./env.mjs";
16
+
17
+ const arg = (n, d) => { const i = process.argv.indexOf(n); return i >= 0 ? process.argv[i + 1] : d; };
18
+ const files = Number(arg("--files", "19677"));
19
+ const base = mkdtempSync(join(arg("--dir", tmpdir()), "fd-env-bench-"));
20
+ try {
21
+ const wt = join(base, "build"), nm = join(wt, "node_modules");
22
+ for (let i = 0; i < files; i++) {
23
+ const d = join(nm, `pkg-${i % 1200}`, `lib-${i % 7}`);
24
+ if (i < 8400) mkdirSync(d, { recursive: true });
25
+ writeFileSync(join(d, `f${i}.js`), "module.exports = 1;\n");
26
+ }
27
+ const deps = makeDepCache({ root: join(base, "depcache"), exec: async () => "", env: {} });
28
+ const store = makeEnvStore({ root: join(base, "store"), linkTree: deps.linkTree, readOnly: deps.readOnly });
29
+ const key = "0123456789abcdef";
30
+ const ms = (fn) => { const t = process.hrtime.bigint(); const r = fn(); return [Number((process.hrtime.bigint() - t) / 1000000n), r]; };
31
+ const [publishMs, man] = ms(() => store.publish({ key, wt, trees: ["node_modules"] }));
32
+ const [stageMs] = ms(() => store.stage({ key, count: 1 }));
33
+ rmSync(nm, { recursive: true });
34
+ const [renameMs, a] = ms(() => store.claim({ key, wt }));
35
+ rmSync(nm, { recursive: true });
36
+ const [linkMs, b] = ms(() => store.claim({ key, wt }));
37
+ process.stdout.write(JSON.stringify({ files: man.files, publish_ms: publishMs, stage_ms: stageMs, claim_staged: { mode: a.mode, ms: renameMs }, claim_unstaged: { mode: b.mode, ms: linkMs } }) + "\n");
38
+ } finally { rmSync(base, { recursive: true, force: true }); }
@@ -0,0 +1,134 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * `forgedock env key|build|status|gc|stage|ensure` — the environment library's CLI (bin/env/env.mjs).
5
+ * key the environment key of a checkout (no tool is run)
6
+ * build writes the recipe and manifest for the key (Dockerfile.env for the oci store, build.sh for the local one);
7
+ * --apply runs the installs in the checkout and publishes to the local store (for a build container on a pool host)
8
+ * status the snapshots in the local store
9
+ * gc plan (default) or --apply removal by keep count and age
10
+ * stage stage ready copies of a snapshot (pool host)
11
+ * ensure pool-host helper: clone a ref from a bare mirror, build if missing, stage, gc
12
+ * Nothing here runs docker.
13
+ */
14
+ import * as nodeFs from "node:fs";
15
+ import { execFile } from "node:child_process";
16
+ import { promisify } from "node:util";
17
+ import { join, resolve } from "node:path";
18
+ import { makeDepCache } from "../lean/depcache.mjs";
19
+ import { validateLaneTools } from "../pool/lane-tools.mjs";
20
+ import { parseForgeYaml } from "../forge-utils.mjs";
21
+ import { ENV_PREFIX, buildLocal, describeEnv, envRoot, makeEnvStore, makeOciStore, manifestOf, readEnvSnapshots } from "./env.mjs";
22
+
23
+ const pexec = promisify(execFile);
24
+ const defaultExec = async (cmd, args, { cwd, env, timeoutMs } = {}) => String((await pexec(cmd, args, { cwd, env: { ...process.env, ...(env ?? {}) }, timeout: timeoutMs ?? 0, maxBuffer: 1 << 28 })).stdout);
25
+ const USAGE = "usage: forgedock env key|build|status|gc|stage|ensure [--wt <dir>] [--store local|oci] [--out <dir>] [--apply] [--json] [--keep <n>] [--max-age-days <n>] [--key <key>] [--count <n>] [--image <ref>] [--lane-tools a,b]";
26
+ const VALUED = ["--wt", "--store", "--out", "--keep", "--max-age-days", "--key", "--count", "--image", "--lane-tools", "--mirror", "--ref", "--repo", "--ready", "--prefix"];
27
+
28
+ function parseArgs(argv) {
29
+ const o = { _: [] };
30
+ for (let i = 0; i < argv.length; i++) {
31
+ const a = argv[i];
32
+ if (VALUED.includes(a)) { if (argv[i + 1] === undefined) throw new Error(`usage: ${a} requires a value`); o[a.slice(2)] = argv[++i]; }
33
+ else if (a === "--apply" || a === "--json") o[a.slice(2)] = true;
34
+ else if (a.startsWith("--")) throw new Error(`usage: unknown flag ${a}\n${USAGE}`);
35
+ else o._.push(a);
36
+ }
37
+ return o;
38
+ }
39
+ const num = (v, def) => (v !== undefined && /^\d+$/.test(String(v)) ? Number(v) : def);
40
+ const gb = (n) => (Number.isFinite(n) ? `${(n / 2 ** 30).toFixed(2)} GB` : "?");
41
+
42
+ /** @returns {Promise<number>} exit code */
43
+ export async function envFromCli(argv, { fs = nodeFs, exec = defaultExec, out = (s) => process.stdout.write(`${s}\n`), env = process.env, cwd = process.cwd(), now = () => Date.now() } = {}) {
44
+ let o;
45
+ try { o = parseArgs(argv); } catch (e) { process.stderr.write(`${e.message}\n`); return 2; }
46
+ const sub = o._[0];
47
+ const wt = resolve(cwd, o.wt ?? ".");
48
+ let yaml = "";
49
+ try { yaml = String(fs.readFileSync(join(wt, "forge.yaml"))); } catch { /* no config: defaults */ }
50
+ const cfg = readEnvSnapshots(yaml);
51
+ let yamlTools = [];
52
+ try { yamlTools = validateLaneTools(parseForgeYaml(yaml)?.execution?.lane_tools).tools; } catch { /* none */ }
53
+ const laneTools = o["lane-tools"] !== undefined ? validateLaneTools(o["lane-tools"]).tools : yamlTools;
54
+ const deps = makeDepCache({ exec, fs, now, env });
55
+ const store = makeEnvStore({ root: envRoot(env), fs, now, linkTree: deps.linkTree, readOnly: deps.readOnly });
56
+ const kind = o.store ?? cfg.store;
57
+ const image = o.image ?? (kind === "oci" ? cfg.baseImage ?? "" : env.FORGE_ENV_IMAGE ?? "");
58
+ const describe = (dir = wt) => describeEnv({ wt: dir, deps, fs, laneTools, image });
59
+ const git = async (dir, args) => { try { return (await exec("git", args, { cwd: dir, timeoutMs: 60000 })).trim(); } catch { return null; } };
60
+ const maxAgeMs = num(o["max-age-days"], cfg.maxAgeDays) * 86400000, keep = num(o.keep, cfg.keep);
61
+
62
+ switch (sub) {
63
+ case "key": {
64
+ const d = await describe();
65
+ out(o.json ? JSON.stringify({ key: d.key, ecosystems: d.components.map((c) => ({ eco: c.eco, dir: c.dir, lock: c.lock })), skipped: d.skipped, pins: d.pins, lane_tools: d.laneTools, image: d.image, platform: d.platform }) : d.key);
66
+ return d.components.length ? 0 : 1;
67
+ }
68
+ case "build": {
69
+ const d = await describe();
70
+ if (!d.components.length) { process.stderr.write("env build: no lockfile the environment library can install\n"); return 1; }
71
+ const commit = await git(wt, ["rev-parse", "HEAD"]);
72
+ if (o.apply) {
73
+ if (kind !== "local") { process.stderr.write("env build --apply: only the local store is built here; the oci image is built on the pool host from Dockerfile.env\n"); return 2; }
74
+ const r = await buildLocal({ wt, deps, store, desc: d, fs, exec, repo: o.repo ?? null, ref: o.ref ?? null, commit });
75
+ out(o.json ? JSON.stringify(r) : `env ${r.key}: ${r.status}${r.reason ? ` (${r.reason})` : ""}${r.manifest ? ` ${r.manifest.files} files, ${gb(r.manifest.size_bytes)}` : ""}`);
76
+ return r.status === "failed" ? 1 : 0;
77
+ }
78
+ const dir = resolve(cwd, o.out ?? join(".forge", "env", d.key));
79
+ fs.mkdirSync(dir, { recursive: true });
80
+ let recipe;
81
+ if (kind === "oci") {
82
+ try { recipe = makeOciStore({ image: cfg.image, baseImage: cfg.baseImage }).recipe({ desc: d, existing: (f) => fs.existsSync(join(wt, f)), repo: o.repo ?? null, commit }); }
83
+ catch (e) { process.stderr.write(`env build: ${e.message}\n`); return 2; }
84
+ fs.writeFileSync(join(dir, "Dockerfile.env"), recipe.dockerfile);
85
+ fs.writeFileSync(join(dir, "manifest.json"), JSON.stringify(recipe.manifest, null, 2) + "\n");
86
+ fs.writeFileSync(join(dir, "build.sh"), `#!/usr/bin/env bash\n# Run on a build host from the repo root (not inside a job).\nset -euo pipefail\ndocker build -f ${JSON.stringify(join(dir, "Dockerfile.env"))} -t ${recipe.ref} .\ndocker push ${recipe.ref}\n`, { mode: 0o755 });
87
+ } else {
88
+ const man = { v: 1, key: d.key, prefix: ENV_PREFIX, trees: d.components.flatMap((c) => c.trees), ...manifestOf(d, { repo: o.repo ?? null, commit }) };
89
+ fs.writeFileSync(join(dir, "manifest.json"), JSON.stringify(man, null, 2) + "\n");
90
+ fs.writeFileSync(join(dir, "build.sh"), `#!/usr/bin/env bash\n# Run in a build container on the pool host (not inside a job), with the checkout at ${ENV_PREFIX} and the env store mounted.\nset -euo pipefail\ncd ${ENV_PREFIX}\nforgedock env build --apply\nforgedock env stage --key ${d.key} --count ${cfg.ready}\n`, { mode: 0o755 });
91
+ }
92
+ out(o.json ? JSON.stringify({ key: d.key, store: kind, out: dir, ...(recipe ? { ref: recipe.ref } : {}) }) : `env ${d.key}: ${kind} recipe written to ${dir}${recipe ? ` (image ${recipe.ref})` : ""}`);
93
+ return 0;
94
+ }
95
+ case "status": {
96
+ const list = store.list();
97
+ if (o.json) { out(JSON.stringify({ root: store.root, enabled: cfg.enabled, store: cfg.store, snapshots: list })); return 0; }
98
+ out(`env store ${store.root} (env.snapshots.enabled: ${cfg.enabled}, store: ${cfg.store})`);
99
+ if (!list.length) out("no snapshots");
100
+ for (const s of list) out(`${s.key} ${s.repo ?? "-"} ${s.ecosystems.join("+") || "-"} ${gb(s.size_bytes)} ${s.files ?? "?"} files ready ${s.ready} created ${new Date(s.created).toISOString()} commit ${String(s.commit ?? "-").slice(0, 12)}`);
101
+ return 0;
102
+ }
103
+ case "gc": {
104
+ const r = store.gc({ keep, maxAgeMs, apply: Boolean(o.apply) });
105
+ if (o.json) out(JSON.stringify(r));
106
+ else { for (const x of r.remove) out(`${o.apply ? (r.removed.includes(x.key) ? "removed" : "kept (busy)") : "would remove"} ${x.key} (${x.reason})`); if (!r.remove.length) out("nothing to remove"); }
107
+ return 0;
108
+ }
109
+ case "stage": {
110
+ const key = o.key ?? (await describe()).key;
111
+ if (!store.has(key)) { process.stderr.write(`env stage: no snapshot ${key} in ${store.root}\n`); return 1; }
112
+ const added = store.stage({ key, count: num(o.count, cfg.ready) });
113
+ out(o.json ? JSON.stringify({ key, added }) : `env ${key}: staged ${added}`);
114
+ return 0;
115
+ }
116
+ case "ensure": {
117
+ // Pool-host helper (bin/pool/agent.mjs envEnsureArgs). A missing mirror or a failed install leaves lanes on today's path.
118
+ const prefix = o.prefix ?? ENV_PREFIX;
119
+ if (!o.mirror || !fs.existsSync(o.mirror)) { out(`env ensure: mirror ${o.mirror ?? "(none)"} not ready`); return 0; }
120
+ if (fs.existsSync(prefix)) { process.stderr.write(`env ensure: ${prefix} already exists (run in a fresh build container)\n`); return 1; }
121
+ try { await exec("git", ["clone", "--quiet", "--shared", ...(o.ref ? ["--branch", o.ref] : []), o.mirror, prefix], { timeoutMs: 10 * 60000 }); }
122
+ catch (e) { process.stderr.write(`env ensure: clone failed: ${String(e.stderr || e.message).slice(0, 300)}\n`); return 1; }
123
+ const d = await describe(prefix);
124
+ const r = await buildLocal({ wt: prefix, deps, store, desc: d, fs, exec, repo: o.repo ?? null, ref: o.ref ?? null, commit: await git(prefix, ["rev-parse", "HEAD"]) });
125
+ const staged = r.status === "failed" ? 0 : store.stage({ key: d.key, count: num(o.ready, cfg.ready) });
126
+ const g = store.gc({ keep, maxAgeMs, apply: true });
127
+ out(JSON.stringify({ key: d.key, status: r.status, ...(r.reason ? { reason: r.reason } : {}), staged, removed: g.removed }));
128
+ return r.status === "failed" ? 1 : 0;
129
+ }
130
+ default:
131
+ process.stderr.write(`${USAGE}\n`);
132
+ return 2;
133
+ }
134
+ }