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
@@ -4,6 +4,9 @@ import { createHash } from "node:crypto";
4
4
  import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
5
5
  import { tmpdir } from "node:os";
6
6
  import { join } from "node:path";
7
+ import { loadImageManifest, manifestProvides } from "./image-manifest.mjs";
8
+
9
+ const IMAGE = loadImageManifest();
7
10
 
8
11
  /**
9
12
  * Per-repo lane images (#5650): forge.yaml `execution.lane_tools` lists the tools a repo's lanes need (`name` or
@@ -12,11 +15,13 @@ import { join } from "node:path";
12
15
  * Dockerfile instructions (Debian/Ubuntu base, building as root) that install it.
13
16
  */
14
17
  const apt = (...pkgs) => `RUN apt-get update && apt-get install -y --no-install-recommends ${pkgs.join(" ")} && rm -rf /var/lib/apt/lists/*`;
18
+ /** @deprecated Fallback only (#6017, #6037): pool/image/manifest.json is the source of truth for tools the image ships. */
15
19
  export const RECIPES = {
16
20
  "postgresql-client": { versioned: true, steps: (v) => [apt(v ? `postgresql-client-${v}` : "postgresql-client")] },
17
21
  python: { versioned: true, steps: (v) => [apt(v ? `python${v} python${v}-venv` : "python3 python3-venv")] },
18
22
  xvfb: { versioned: false, steps: () => [apt("xvfb xauth")] }, // headless X for browser/GUI tests that call xvfb-run
19
23
  shellcheck: { versioned: false, steps: () => [apt("shellcheck")] }, // shell-script linter for validate commands
24
+ yaml: { versioned: false, steps: () => [apt("python3-yaml")] }, // PyYAML for validate commands that `import yaml` (#5749)
20
25
  playwright: { versioned: true, steps: (v) => [`RUN npx --yes playwright${v ? `@${v}` : ""} install --with-deps chromium`] },
21
26
  // Example of a release-tarball tool; the version is required.
22
27
  promtool: { versioned: true, steps: (v) => [`RUN curl -fsSL https://github.com/prometheus/prometheus/releases/download/v${v ?? "2.54.1"}/prometheus-${v ?? "2.54.1"}.linux-amd64.tar.gz | tar -xz --strip-components=1 -C /usr/local/bin --wildcards '*/promtool'`] },
@@ -55,14 +60,20 @@ export function recipeFor(tool) {
55
60
  }
56
61
 
57
62
  /** True when `name` has a lane_tools recipe, directly or as a binary one provides (#5652, #5764). */
63
+ /** @deprecated Fallback only; see pool/image/manifest.json (#6017). */
58
64
  export function hasRecipe(name) { return recipeFor(name) !== null; }
59
65
 
60
66
  /**
61
67
  * In-sandbox install commands (#5652) for one tool: the recipe's Dockerfile `RUN` steps as shell commands, `sudo` prefixed
62
- * when the sandbox user is not root. Empty for a tool with no recipe. Pure; the image build keeps using `steps`.
68
+ * when the sandbox user is not root. Empty for a tool with no recipe or one the image manifest provides (#6037).
69
+ * @deprecated Fallback only; pool/image/manifest.json replaces it (#6017).
70
+ * Pure; the image build keeps using `steps`.
63
71
  */
64
72
  export function installCommands(entry, { root = true } = {}) {
65
73
  const { name, version } = parseLaneTool(entry);
74
+ // the image covers the tool only when no version is pinned, or the manifest entry carries that same version (#6147)
75
+ const baked = (IMAGE?.tools ?? []).find((e) => e.name === name || e.binary === name);
76
+ if (manifestProvides(IMAGE, name) && (!version || String(baked?.version ?? "") === String(version))) return [];
66
77
  const recipe = recipeFor(name);
67
78
  if (!recipe) return [];
68
79
  const sh = (s) => s.replace(/^RUN\s+/, "");
@@ -74,17 +85,29 @@ export function installCommands(entry, { root = true } = {}) {
74
85
  * Generic install for a tool no recipe covers (2026-11-26 unclog): a missing Python module is pip-installed, a missing
75
86
  * Node package npm-installed into the worktree, a missing command apt-installed. Replaces adding one recipe per tool
76
87
  * (77 of 215 needs-human parks on open issues were "Remote sandbox lacks X"). `miss`: {kind, tool} from the validate
77
- * preflight. Returns [] for an unsafe name or a kind nothing can install (environment, forgedock-path).
88
+ * preflight. Returns [] for an image-manifest tool, an unsafe name or a kind nothing can install (environment, forgedock-path).
89
+ * @deprecated Fallback only; pool/image/manifest.json replaces it (#6017, #6037).
78
90
  */
79
91
  const PYPI = { yaml: "PyYAML", PIL: "Pillow", cv2: "opencv-python-headless", bs4: "beautifulsoup4", sklearn: "scikit-learn", dateutil: "python-dateutil", jwt: "PyJWT", dotenv: "python-dotenv", google: "protobuf", attr: "attrs", magic: "python-magic", Crypto: "pycryptodome", OpenSSL: "pyOpenSSL", serial: "pyserial", usb: "pyusb", zmq: "pyzmq", git: "GitPython", jose: "python-jose", multipart: "python-multipart" };
80
92
  const SAFE = /^@?[A-Za-z0-9][A-Za-z0-9._/+-]*$/;
93
+ /** Debian/Ubuntu package stems where the import name differs (python3-<stem>). */
94
+ const APT_PY = { PIL: "pil", cv2: "opencv", bs4: "bs4", sklearn: "sklearn", dateutil: "dateutil", jwt: "jwt", dotenv: "dotenv", serial: "serial", git: "git", magic: "magic" };
95
+ /** Python modules a failed run's output reports missing (`No module named 'yaml'`, top-level name only). */
96
+ export function missingPythonModules(output) {
97
+ return [...new Set([...String(output ?? "").matchAll(/No module named ['"]?([A-Za-z0-9_]+)/gi)].map((m) => m[1]))];
98
+ }
81
99
  export function genericInstallCommands(miss, { root = true } = {}) {
82
100
  const tool = String(miss?.tool ?? "").trim();
83
- if (!tool || !SAFE.test(tool) || tool.includes("..")) return [];
101
+ if (!tool || !SAFE.test(tool) || tool.includes("..") || (miss.kind === "command" && manifestProvides(IMAGE, tool))) return [];
84
102
  const su = (c) => (root ? c : `sudo sh -c ${JSON.stringify(c)}`);
85
103
  if (miss.kind === "python-module") {
86
- const pkg = PYPI[tool.split(".")[0]] ?? tool.split(".")[0];
87
- return [`python3 -m pip install --user --quiet ${pkg} || python3 -m pip install --user --quiet --break-system-packages ${pkg}`];
104
+ const mod = tool.split(".")[0], pkg = PYPI[mod] ?? mod;
105
+ // 2026-11-26: lane images may ship python3 without pip; the distro package (python3-<module>) is the fallback
106
+ const deb = `python3-${(APT_PY[mod] ?? mod).toLowerCase().replace(/_/g, "-")}`;
107
+ // #6138: install into the interpreter the validate runs, system-wide (no --user: `python3 -I` ignores user site-packages), then the distro package
108
+ const pip = `python3 -m pip install --quiet --break-system-packages ${pkg} || python3 -m pip install --quiet ${pkg}`;
109
+ const apt = `apt-get update -qq && apt-get install -y --no-install-recommends ${deb} && rm -rf /var/lib/apt/lists/*`;
110
+ return [root ? `${pip} || (${apt})` : `${su(pip)} || (${su(apt)})`];
88
111
  }
89
112
  if (miss.kind === "node-module") return [`npm install --no-save --no-audit --no-fund ${tool}`];
90
113
  if (miss.kind === "command" && !tool.includes("/")) return [su(`apt-get update -qq && apt-get install -y --no-install-recommends ${tool} && rm -rf /var/lib/apt/lists/*`)];
@@ -92,6 +115,7 @@ export function genericInstallCommands(miss, { root = true } = {}) {
92
115
  }
93
116
 
94
117
  /**
118
+ * @deprecated Fallback only; see pool/image/manifest.json (#6017).
95
119
  * Installs `tools` in the running sandbox through the injected `run({command, timeoutMs})` -> {rc, stdout, stderr}.
96
120
  * Never throws: {ok:true} or {ok:false, tool, stderrTail}.
97
121
  */
@@ -2,18 +2,22 @@
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 { hasRecipe, recipeFor, installCommands, installLaneTools, laneToolsDockerfile } from "./lane-tools.mjs";
5
+ import { RECIPES, hasRecipe, recipeFor, installCommands, installLaneTools, laneToolsDockerfile } from "./lane-tools.mjs";
6
6
 
7
7
  describe("#5652 in-sandbox lane tool install", () => {
8
8
  it("installCommands strips RUN, prefixes sudo when not root, and is empty without a recipe", () => {
9
9
  assert.ok(hasRecipe("promtool") && !hasRecipe("nope"));
10
- assert.match(installCommands("postgresql-client")[0], /^apt-get update/);
11
- assert.match(installCommands("postgresql-client", { root: false })[0], /^sudo sh -c /);
10
+ assert.match(installCommands("yaml")[0], /^apt-get update/);
11
+ assert.match(installCommands("yaml", { root: false })[0], /^sudo sh -c /);
12
12
  assert.deepEqual(installCommands("nope"), []);
13
13
  });
14
+ it("a manifest-provided tool is skipped unpinned, but a pinned version still installs (#6147)", () => {
15
+ assert.deepEqual(installCommands("postgresql-client"), []);
16
+ assert.match(installCommands("postgresql-client@16").join("\n"), /postgresql-client-16/);
17
+ });
14
18
  it("installLaneTools runs every step, and returns the stderr tail of the first failure", async () => {
15
19
  const seen = [];
16
- assert.deepEqual(await installLaneTools(["postgresql-client"], { run: async (a) => { seen.push(a.command); return { rc: 0 }; } }), { ok: true });
20
+ assert.deepEqual(await installLaneTools(["yaml"], { run: async (a) => { seen.push(a.command); return { rc: 0 }; } }), { ok: true });
17
21
  assert.equal(seen.length, 1);
18
22
  const bad = await installLaneTools(["promtool@2.54.1"], { run: async () => ({ rc: 3, stderr: "a\nb\n404" }) });
19
23
  assert.equal(bad.ok, false);
@@ -25,13 +29,38 @@ describe("#5652 in-sandbox lane tool install", () => {
25
29
  });
26
30
  it("#5763 shellcheck is an unversioned apt recipe in the derived image", () => {
27
31
  assert.ok(hasRecipe("shellcheck"));
28
- assert.match(installCommands("shellcheck")[0], /^apt-get update && apt-get install -y --no-install-recommends shellcheck /);
32
+ assert.match(RECIPES.shellcheck.steps()[0], /^RUN apt-get update && apt-get install -y --no-install-recommends shellcheck /);
29
33
  assert.match(laneToolsDockerfile("base:1", ["shellcheck"]), /\nRUN apt-get update && apt-get install -y --no-install-recommends shellcheck /);
30
34
  });
31
35
  it("#5764 a binary a recipe provides resolves to it; python3 installs the unversioned python recipe", () => {
32
36
  for (const [b, r] of [["python3", "python"], ["python3.12", "python"], ["pip3", "python"], ["psql", "postgresql-client"], ["xvfb-run", "xvfb"], ["python", "python"]]) assert.equal(recipeFor(b), r, b);
33
37
  assert.ok(hasRecipe("python3") && !hasRecipe("zzcheck") && recipeFor("zzcheck") === null);
34
- assert.match(installCommands("python3")[0], /install -y --no-install-recommends python3 python3-venv /);
35
- assert.match(installCommands("python@3.12")[0], /python3\.12 python3\.12-venv/);
38
+ assert.match(RECIPES.python.steps()[0], /install -y --no-install-recommends python3 python3-venv /);
39
+ assert.match(RECIPES.python.steps("3.12")[0], /python3\.12 python3\.12-venv/);
40
+ });
41
+ });
42
+
43
+ describe("#5749 yaml recipe", () => {
44
+ it("#5749 yaml has a lane_tools recipe", () => {
45
+ assert.ok(hasRecipe("yaml"));
46
+ assert.match(installCommands("yaml")[0], /apt-get install .*python3-yaml/);
47
+ assert.ok(hasRecipe("shellcheck"));
48
+ assert.ok(!hasRecipe("vite") && !hasRecipe("forgedock"), "#5749: manifest/owned deps get no recipe");
49
+ });
50
+ });
51
+
52
+ describe("#6037 image manifest tools skip the fallback installers", () => {
53
+ it("returns [] for manifest tools and keeps commands for others", async () => {
54
+ const { genericInstallCommands } = await import("./lane-tools.mjs");
55
+ for (const t of ["shellcheck", "xvfb", "yq"]) assert.deepEqual(installCommands(t), [], t);
56
+ for (const t of ["shellcheck", "yq"]) assert.deepEqual(genericInstallCommands({ kind: "command", tool: t }), [], t);
57
+ assert.ok(installCommands("promtool").length);
58
+ assert.match(genericInstallCommands({ kind: "command", tool: "ripgrep" })[0], /apt-get install/);
59
+ });
60
+ it("marks the fallbacks deprecated", async () => {
61
+ const { readFileSync } = await import("node:fs");
62
+ const src = readFileSync(new URL("./lane-tools.mjs", import.meta.url), "utf8");
63
+ assert.match(src, /@deprecated[^\n]*\n(export const RECIPES|export function hasRecipe)/);
64
+ assert.ok((src.match(/@deprecated/g) ?? []).length >= 4);
36
65
  });
37
66
  });
@@ -66,8 +66,12 @@ export function localRunner({ root, seedDir }) {
66
66
  /** `runnerFor({slug, cache_key})` -> runner. Returns the agent's mirror seed handlers. */
67
67
  export function makeMirrorSeed({ seedDir, runnerFor, partTtlMs = SEED_PART_TTL_MS, uploadMax = SEED_UPLOAD_MAX, totalMax = SEED_TOTAL_MAX }) {
68
68
  mkdirSync(seedDir, { recursive: true });
69
- const part = (up) => join(seedDir, `${up}.part`);
70
- const size = (up) => { try { return statSync(part(up)).size; } catch { return 0; } };
69
+ // Concurrent lanes seeding the same repo build byte-identical bundles (same sha256). One shared `<sha>.part` let them
70
+ // append into each other's upload: 409 offset mismatch, then 422 when one finish deleted the file under the others
71
+ // (2026-11-26 lane-lifecycle audit: bursts of 5–12 lanes within seconds). Each uploader now has its own part file.
72
+ const who = (u) => (typeof u === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(u) ? `.${u}` : "");
73
+ const part = (up, uploader) => join(seedDir, `${up}${who(uploader)}.part`);
74
+ const size = (up, uploader) => { try { return statSync(part(up, uploader)).size; } catch { return 0; } };
71
75
  /** Removes `.part` files idle past the TTL; returns the bytes the remaining ones hold. */
72
76
  const sweep = () => {
73
77
  let total = 0;
@@ -87,11 +91,11 @@ export function makeMirrorSeed({ seedDir, runnerFor, partTtlMs = SEED_PART_TTL_M
87
91
  };
88
92
  return {
89
93
  /** `GET /mirrors`: {mirrors: {slug: {ref: sha} | "absent"}, upload_offset?}. */
90
- async tips({ slug, cache_key = null, upload = null }) {
94
+ async tips({ slug, cache_key = null, upload = null, uploader = null }) {
91
95
  if (typeof slug !== "string" || !SLUG_RE.test(slug)) throw fail(400, "slug required");
92
96
  const out = String(await runnerFor({ slug, cache_key })(TIPS_SCRIPT, { NAME: mirrorName(slug) })).trim();
93
97
  const mirror = out === "ABSENT" ? "absent" : Object.fromEntries(out.split("\n").filter(Boolean).map((l) => { const i = l.indexOf(" "); return [l.slice(i + 1), l.slice(0, i)]; }));
94
- return { mirrors: { [slug]: mirror }, ...(upload && SHA_RE.test(upload) ? { upload_offset: size(upload) } : {}) };
98
+ return { mirrors: { [slug]: mirror }, ...(upload && SHA_RE.test(upload) ? { upload_offset: size(upload, uploader) } : {}) };
95
99
  },
96
100
  /** One chunk: {slug, cache_key, upload, offset, data_b64, sha256}. A wrong offset is a 409 carrying the offset to resume from. */
97
101
  chunk(b) {
@@ -99,23 +103,23 @@ export function makeMirrorSeed({ seedDir, runnerFor, partTtlMs = SEED_PART_TTL_M
99
103
  const buf = Buffer.from(String(b.data_b64 ?? ""), "base64");
100
104
  if (!buf.length || buf.length > SEED_CHUNK_MAX) throw fail(413, `chunk must be 1..${SEED_CHUNK_MAX} bytes`);
101
105
  if (sha256(buf) !== b.sha256) throw fail(422, "chunk checksum mismatch");
102
- const have = size(b.upload);
106
+ const have = size(b.upload, b.uploader);
103
107
  if (b.offset !== have) throw fail(409, "offset mismatch", { offset: have });
104
108
  if (have + buf.length > uploadMax) throw fail(413, `upload exceeds ${uploadMax} bytes`);
105
109
  if (sweep() + buf.length > totalMax) throw fail(413, `seed dir exceeds ${totalMax} bytes`);
106
- appendFileSync(part(b.upload), buf);
110
+ appendFileSync(part(b.upload, b.uploader), buf);
107
111
  return { offset: have + buf.length };
108
112
  },
109
113
  /** Verifies the whole bundle against {size, sha256 = upload} and applies it. A corrupt upload is dropped; the mirror is never touched on failure. */
110
114
  async finish(b) {
111
115
  check(b);
112
116
  const f = b.finish ?? {};
113
- const have = size(b.upload);
117
+ const p = part(b.upload, b.uploader), have = size(b.upload, b.uploader);
114
118
  if (!Number.isInteger(f.size) || have !== f.size) throw fail(409, "incomplete upload", { offset: have });
115
- if (!existsSync(part(b.upload)) || sha256(readFileSync(part(b.upload))) !== b.upload) { rmSync(part(b.upload), { force: true }); throw fail(422, "bundle checksum mismatch"); }
116
- try { await runnerFor(b)(APPLY_SCRIPT, { NAME: mirrorName(b.slug), BUNDLE: `${b.upload}.part` }); }
117
- catch (e) { rmSync(part(b.upload), { force: true }); throw fail(422, `bundle apply failed: ${String(e.stderr || e.message).slice(-300)}`); }
118
- rmSync(part(b.upload), { force: true });
119
+ if (!existsSync(p) || sha256(readFileSync(p)) !== b.upload) { rmSync(p, { force: true }); throw fail(422, "bundle checksum mismatch"); }
120
+ try { await runnerFor(b)(APPLY_SCRIPT, { NAME: mirrorName(b.slug), BUNDLE: `${b.upload}${who(b.uploader)}.part` }); }
121
+ catch (e) { rmSync(p, { force: true }); throw fail(422, `bundle apply failed: ${String(e.stderr || e.message).slice(-300)}`); }
122
+ rmSync(p, { force: true });
119
123
  return { ok: true, ...(await this.tips({ slug: b.slug, cache_key: b.cache_key })) };
120
124
  },
121
125
  };
@@ -0,0 +1,142 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #6038: a repo's project deps as a cached image layer. deriveProjectDeps reads a worktree (lockfiles via depcache's detect,
5
+ * runtime pins from .tool-versions / .nvmrc / .python-version / CI setup-node|setup-python); projectLayerImageNow builds a
6
+ * layer FROM the lane image tagged `<base>-p<12hex>` (hash of lockfile contents + runtimes), in the background, and falls
7
+ * back to the base image while building or after a failure. Docker and fs are injected; nothing here blocks a launch.
8
+ */
9
+ import * as nodeFs from "node:fs";
10
+ import { createHash } from "node:crypto";
11
+ import { join, posix } from "node:path";
12
+ import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
13
+ import { tmpdir } from "node:os";
14
+ import { detect, pyHint, depCommands } from "../lean/depcache.mjs";
15
+ import { isLaneToolsTagOf } from "./lane-tools.mjs";
16
+
17
+ const JS = new Set(["pnpm", "npm", "yarn"]);
18
+ const MANIFESTS = ["package.json", "pnpm-workspace.yaml", ".npmrc", ".yarnrc.yml", "pyproject.toml", ".python-version"];
19
+ const MAX_FILE = 4 * 1024 * 1024;
20
+ export const PROJECT_BUILD_RETRY_MS = 10 * 60000;
21
+ export const PROJECT_LAYER_ROOT = "/opt/project-deps";
22
+
23
+ const read = (fs, p) => { try { return String(fs.readFileSync(p)); } catch { return null; } };
24
+
25
+ /** Node version the repo pins: .nvmrc, .tool-versions `nodejs`, else the first CI setup-node `node-version`. */
26
+ function nodeHint(fs, wt) {
27
+ const norm = (t) => { const m = /^\s*(?:v|node\/|lts\/)?(\d+(?:\.\d+){0,2})/.exec(t ?? ""); return m ? m[1] : null; };
28
+ const nvmrc = norm(read(fs, join(wt, ".nvmrc")));
29
+ if (nvmrc) return nvmrc;
30
+ const tv = /^\s*node(?:js)?\s+(\S+)/m.exec(read(fs, join(wt, ".tool-versions")) ?? "");
31
+ if (tv && norm(tv[1])) return norm(tv[1]);
32
+ try {
33
+ const dir = join(wt, ".github", "workflows");
34
+ for (const f of fs.readdirSync(dir).sort()) {
35
+ if (!/\.ya?ml$/.test(f)) continue;
36
+ const m = /node-version:\s*\[?\s*["']?v?(\d+(?:\.\d+){0,2})/.exec(read(fs, join(dir, f)) ?? "");
37
+ if (m) return m[1];
38
+ }
39
+ } catch { /* no workflows */ }
40
+ return null;
41
+ }
42
+
43
+ /** Python minor the repo pins: depcache's .python-version / setup-python hint, else .tool-versions `python`. */
44
+ function pythonHint(fs, wt) {
45
+ const h = pyHint(fs, wt);
46
+ if (h) return `${h[0]}.${h[1]}`;
47
+ const m = /^\s*python\s+(\d+\.\d+)/m.exec(read(fs, join(wt, ".tool-versions")) ?? "");
48
+ return m ? m[1] : null;
49
+ }
50
+
51
+ /** {ecosystems, lockfiles, node, python, files, hash} for a worktree; hash is null when there is nothing to install. */
52
+ export function deriveProjectDeps(worktree, fs = nodeFs) {
53
+ const found = detect(fs, worktree).filter((d) => !d.skip);
54
+ const lockfiles = found.map((d) => ({ eco: d.eco, dir: d.dir ?? ".", path: d.dir ? `${d.dir}/${d.lock}` : d.lock, ...(d.berry ? { berry: true } : {}) }));
55
+ const files = {};
56
+ for (const d of lockfiles) {
57
+ for (const name of [posix.basename(d.path), ...MANIFESTS]) {
58
+ const rel = d.dir === "." ? name : `${d.dir}/${name}`;
59
+ if (rel in files) continue;
60
+ const t = read(fs, join(worktree, rel));
61
+ if (t !== null && t.length <= MAX_FILE) files[rel] = t;
62
+ }
63
+ }
64
+ const ecosystems = [...new Set(lockfiles.map((d) => d.eco))].sort();
65
+ const node = lockfiles.some((d) => JS.has(d.eco)) ? nodeHint(fs, worktree) : null;
66
+ const python = lockfiles.some((d) => !JS.has(d.eco)) ? pythonHint(fs, worktree) : null;
67
+ if (!lockfiles.length) return { ecosystems, lockfiles, node, python, files, hash: null };
68
+ const h = createHash("sha256").update(`v1\0${node ?? ""}\0${python ?? ""}\0${process.arch}\0`);
69
+ for (const d of lockfiles) h.update(`${d.eco}\0${d.path}\0${d.berry ? 1 : 0}\0`);
70
+ for (const k of Object.keys(files).sort()) h.update(`${k}\0${files[k]}\0`);
71
+ return { ecosystems, lockfiles, node, python, files, hash: h.digest("hex") };
72
+ }
73
+
74
+ /** Per-project image tag: base plus 12 hex of the deps hash; separate from the lane_tools `-t` tag. */
75
+ export function projectLayerTag(baseImage, hash) {
76
+ return `${baseImage}-p${String(hash).slice(0, 12)}`;
77
+ }
78
+
79
+ /** True for `<base>-p<12 hex>` where `<base>` is the base image or a lane_tools variant of it. */
80
+ export function isProjectLayerTagOf(tag, base) {
81
+ if (typeof tag !== "string") return false;
82
+ const m = /^(.*)-p[0-9a-f]{12}$/.exec(tag);
83
+ return Boolean(m) && isLaneToolsTagOf(m[1], base);
84
+ }
85
+
86
+ const q = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
87
+
88
+ /** The layer Dockerfile: FROM base, runtimes, then per lockfile dir copy manifests and run the frozen install. */
89
+ export function projectLayerDockerfile(baseImage, deps) {
90
+ const out = [`FROM ${baseImage}`, "USER root"];
91
+ if (deps.node) out.push(`RUN npm install -g n && n ${q(deps.node)}`);
92
+ if (deps.python) out.push(`RUN uv python install ${q(deps.python)}`);
93
+ for (const d of deps.lockfiles) {
94
+ const target = d.dir === "." ? PROJECT_LAYER_ROOT : `${PROJECT_LAYER_ROOT}/${d.dir}`;
95
+ const cmds = depCommands(d)?.install ?? [];
96
+ out.push(`COPY ctx/${d.dir === "." ? "" : d.dir} ${target}/`, `WORKDIR ${target}`);
97
+ for (const [cmd, args] of cmds) out.push(`RUN ${[cmd, ...args].map(q).join(" ")}`);
98
+ }
99
+ return [...out, "WORKDIR /", ""].join("\n");
100
+ }
101
+
102
+ const BUILDS = new Map();
103
+ const FAILED = new Map();
104
+
105
+ async function buildLayer({ tag, baseImage, deps, docker, buildTimeoutMs }) {
106
+ const dir = mkdtempSync(join(tmpdir(), "project-layer-"));
107
+ let timer;
108
+ try {
109
+ for (const [rel, text] of Object.entries(deps.files ?? {})) {
110
+ const p = join(dir, "ctx", rel);
111
+ mkdirSync(join(p, ".."), { recursive: true });
112
+ writeFileSync(p, text);
113
+ }
114
+ for (const d of deps.lockfiles) mkdirSync(join(dir, "ctx", d.dir === "." ? "" : d.dir), { recursive: true });
115
+ writeFileSync(join(dir, "Dockerfile"), projectLayerDockerfile(baseImage, deps));
116
+ const timeout = new Promise((_, rej) => { timer = setTimeout(() => rej(new Error(`build timed out after ${buildTimeoutMs}ms`)), buildTimeoutMs); });
117
+ await Promise.race([docker.build(dir, tag, {}), timeout]);
118
+ } catch (e) {
119
+ throw new Error(`project layer ${tag} build failed: ${String(e.stderr || e.message).slice(0, 300)}`);
120
+ } finally { clearTimeout(timer); rmSync(dir, { recursive: true, force: true }); }
121
+ return tag;
122
+ }
123
+
124
+ /**
125
+ * Never blocks: {image: tag} when the layer exists, else starts (or joins) one background build and returns
126
+ * {image: baseImage, building: true}; a build that failed in the last PROJECT_BUILD_RETRY_MS returns {image: baseImage, failed}.
127
+ */
128
+ export async function projectLayerImageNow({ deps, baseImage, docker, buildTimeoutMs = 45 * 60000, now = Date.now }) {
129
+ if (!deps?.hash || !deps.lockfiles?.length) return { image: baseImage };
130
+ const tag = projectLayerTag(baseImage, deps.hash);
131
+ try { if (await docker.hasImage?.(tag)) return { image: tag }; } catch { return { image: baseImage }; }
132
+ const f = FAILED.get(tag);
133
+ if (f && now() - f.at < PROJECT_BUILD_RETRY_MS) return { image: baseImage, failed: f.message };
134
+ if (!BUILDS.has(tag)) {
135
+ FAILED.delete(tag);
136
+ BUILDS.set(tag, buildLayer({ tag, baseImage, deps, docker, buildTimeoutMs }).catch((e) => { FAILED.set(tag, { at: now(), message: e.message }); }).finally(() => BUILDS.delete(tag)));
137
+ }
138
+ return { image: baseImage, building: true, tag };
139
+ }
140
+
141
+ /** Test hook: the in-flight build of a tag. */
142
+ export const pendingBuild = (tag) => BUILDS.get(tag);
@@ -0,0 +1,73 @@
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 { deriveProjectDeps, projectLayerTag, isProjectLayerTagOf, projectLayerDockerfile, projectLayerImageNow, pendingBuild } from "./project-layer.mjs";
6
+ import { laneToolsTag } from "./lane-tools.mjs";
7
+
8
+ const fakeFs = (files) => ({
9
+ existsSync: (p) => p in files || Object.keys(files).some((k) => k.startsWith(`${p}/`)),
10
+ readFileSync: (p) => { if (!(p in files)) throw new Error("ENOENT"); return files[p]; },
11
+ readdirSync: (p) => { const s = new Set(Object.keys(files).filter((k) => k.startsWith(`${p}/`)).map((k) => k.slice(p.length + 1).split("/")[0])); if (!s.size) throw new Error("ENOENT"); return [...s]; },
12
+ });
13
+ const W = "/w";
14
+ const repo = (extra = {}) => fakeFs({ [`${W}/package-lock.json`]: "lock1", [`${W}/package.json`]: "{}", ...extra });
15
+
16
+ describe("#6038 project layer", () => {
17
+ it("same lockfile gives the same tag; a changed lockfile a new one", () => {
18
+ const a = deriveProjectDeps(W, repo()), b = deriveProjectDeps(W, repo()), c = deriveProjectDeps(W, repo({ [`${W}/package-lock.json`]: "lock2" }));
19
+ assert.equal(a.hash, b.hash);
20
+ assert.notEqual(a.hash, c.hash);
21
+ assert.match(projectLayerTag("img:1", a.hash), /^img:1-p[0-9a-f]{12}$/);
22
+ assert.deepEqual(a.ecosystems, ["npm"]);
23
+ });
24
+ it("derives runtime versions from .nvmrc, .tool-versions, .python-version and setup-python/setup-node", () => {
25
+ assert.equal(deriveProjectDeps(W, repo({ [`${W}/.nvmrc`]: "v20.11.1\n" })).node, "20.11.1");
26
+ assert.equal(deriveProjectDeps(W, repo({ [`${W}/.tool-versions`]: "nodejs 22.3.0\n" })).node, "22.3.0");
27
+ assert.equal(deriveProjectDeps(W, repo({ [`${W}/.github/workflows/ci.yml`]: "with:\n node-version: '18'\n" })).node, "18");
28
+ const py = (extra) => deriveProjectDeps(W, fakeFs({ [`${W}/uv.lock`]: "x", ...extra }));
29
+ assert.equal(py({ [`${W}/.python-version`]: "3.12.2\n" }).python, "3.12");
30
+ assert.equal(py({ [`${W}/.github/workflows/ci.yml`]: "python-version: \"3.11\"\n" }).python, "3.11");
31
+ assert.equal(py({ [`${W}/.tool-versions`]: "python 3.10.4\n" }).python, "3.10");
32
+ assert.notEqual(deriveProjectDeps(W, repo()).hash, deriveProjectDeps(W, repo({ [`${W}/.nvmrc`]: "20" })).hash);
33
+ });
34
+ it("no lockfile means no hash; tag ownership does not collide with lane_tools tags", () => {
35
+ assert.equal(deriveProjectDeps(W, fakeFs({})).hash, null);
36
+ const t = laneToolsTag("img:1", ["shellcheck"]);
37
+ assert.ok(isProjectLayerTagOf(projectLayerTag("img:1", "ab".repeat(8)), "img:1"));
38
+ assert.ok(isProjectLayerTagOf(projectLayerTag(t, "ab".repeat(8)), "img:1"));
39
+ assert.ok(!isProjectLayerTagOf(t, "img:1") && !isProjectLayerTagOf("img:1", "img:1") && !isProjectLayerTagOf("img:1-pzz", "img:1"));
40
+ });
41
+ it("Dockerfile is FROM base with the frozen install", () => {
42
+ const df = projectLayerDockerfile("img:1", deriveProjectDeps(W, repo({ [`${W}/.nvmrc`]: "20" })));
43
+ assert.match(df, /^FROM img:1\n/);
44
+ assert.match(df, /RUN 'npm' 'ci'/);
45
+ assert.match(df, /n '20'/);
46
+ });
47
+ it("an existing tag is reused without a build", async () => {
48
+ const deps = deriveProjectDeps(W, repo()), tag = projectLayerTag("img:2", deps.hash);
49
+ let built = 0;
50
+ const docker = { hasImage: async (t) => t === tag, build: async () => { built++; } };
51
+ assert.deepEqual(await projectLayerImageNow({ deps, baseImage: "img:2", docker }), { image: tag });
52
+ assert.equal(built, 0);
53
+ });
54
+ it("concurrent launches share one background build and run the base meanwhile", async () => {
55
+ const deps = deriveProjectDeps(W, repo({ [`${W}/package-lock.json`]: "conc" })), tag = projectLayerTag("img:3", deps.hash);
56
+ let built = 0, release; const gate = new Promise((r) => { release = r; });
57
+ const docker = { hasImage: async () => false, build: async () => { built++; await gate; } };
58
+ const [a, b] = await Promise.all([1, 2].map(() => projectLayerImageNow({ deps, baseImage: "img:3", docker })));
59
+ assert.equal(a.image, "img:3"); assert.ok(a.building && b.building);
60
+ release(); await pendingBuild(tag);
61
+ assert.equal(built, 1);
62
+ });
63
+ it("a failed build falls back to base and is not retried within the window", async () => {
64
+ const deps = deriveProjectDeps(W, repo({ [`${W}/package-lock.json`]: "fail" })), tag = projectLayerTag("img:4", deps.hash);
65
+ let built = 0; let t = 1000;
66
+ const docker = { hasImage: async () => false, build: async () => { built++; throw new Error("boom"); } };
67
+ await projectLayerImageNow({ deps, baseImage: "img:4", docker, now: () => t });
68
+ await pendingBuild(tag);
69
+ const r = await projectLayerImageNow({ deps, baseImage: "img:4", docker, now: () => t });
70
+ assert.equal(r.image, "img:4"); assert.match(r.failed, /boom/);
71
+ assert.equal(built, 1);
72
+ });
73
+ });