forgedock 1.56.0 → 1.58.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 (140) hide show
  1. package/bin/config-schema.mjs +1 -1
  2. package/bin/engine/outcome-codes.mjs +2 -1
  3. package/bin/engine/phases.mjs +4 -3
  4. package/bin/engine-cli.mjs +48 -12
  5. package/bin/forgedock.mjs +52 -3
  6. package/bin/gc.mjs +43 -6
  7. package/bin/help-text.mjs +4 -2
  8. package/bin/lean/batch-health.mjs +5 -1
  9. package/bin/lean/batch-health.test.mjs +7 -1
  10. package/bin/lean/batch.mjs +7 -2
  11. package/bin/lean/batch.test.mjs +45 -0
  12. package/bin/lean/conformance.e2e.test.mjs +3 -2
  13. package/bin/lean/conformance.mjs +118 -20
  14. package/bin/lean/conformance.test.mjs +172 -3
  15. package/bin/lean/decisions.mjs +98 -1
  16. package/bin/lean/decisions.test.mjs +30 -1
  17. package/bin/lean/depcache.mjs +124 -13
  18. package/bin/lean/depcache.test.mjs +121 -3
  19. package/bin/lean/design-gate.mjs +144 -0
  20. package/bin/lean/design-gate.test.mjs +169 -0
  21. package/bin/lean/effects-cap.test.mjs +17 -0
  22. package/bin/lean/effects.mjs +58 -13
  23. package/bin/lean/heavy.mjs +25 -8
  24. package/bin/lean/hostload.test.mjs +28 -0
  25. package/bin/lean/intake.mjs +97 -0
  26. package/bin/lean/intake.test.mjs +105 -0
  27. package/bin/lean/interfaces.mjs +181 -0
  28. package/bin/lean/interfaces.test.mjs +192 -0
  29. package/bin/lean/issuewatch-install.mjs +52 -12
  30. package/bin/lean/issuewatch-install.test.mjs +50 -0
  31. package/bin/lean/issuewatch-parity.mjs +16 -3
  32. package/bin/lean/issuewatch-parity.test.mjs +32 -0
  33. package/bin/lean/issuewatch-reconcile.mjs +29 -1
  34. package/bin/lean/issuewatch-reconcile.test.mjs +21 -0
  35. package/bin/lean/issuewatch.mjs +34 -3
  36. package/bin/lean/issuewatch.test.mjs +49 -1
  37. package/bin/lean/lanecheck.test.mjs +15 -4
  38. package/bin/lean/lean.mjs +110 -24
  39. package/bin/lean/lean.test.mjs +183 -4
  40. package/bin/lean/orchestrate-blocked.test.mjs +18 -2
  41. package/bin/lean/orchestrate-owned.test.mjs +14 -5
  42. package/bin/lean/orchestrate.mjs +26 -4
  43. package/bin/lean/orphan-pr.mjs +3 -2
  44. package/bin/lean/orphan-pr.test.mjs +8 -1
  45. package/bin/lean/pagegate.mjs +35 -12
  46. package/bin/lean/pagegate.test.mjs +39 -1
  47. package/bin/lean/preflight.mjs +35 -1
  48. package/bin/lean/preflight.test.mjs +27 -1
  49. package/bin/lean/prompts.mjs +2 -1
  50. package/bin/lean/reap.test.mjs +39 -0
  51. package/bin/lean/recovery.test.mjs +28 -3
  52. package/bin/lean/release-config.mjs +169 -0
  53. package/bin/lean/release-config.test.mjs +132 -0
  54. package/bin/lean/release-control.mjs +171 -0
  55. package/bin/lean/release-control.test.mjs +167 -0
  56. package/bin/lean/release-deploy.mjs +209 -0
  57. package/bin/lean/release-deploy.test.mjs +217 -0
  58. package/bin/lean/release-fence.mjs +50 -0
  59. package/bin/lean/release-fence.test.mjs +105 -0
  60. package/bin/lean/release-flakes.mjs +139 -0
  61. package/bin/lean/release-flakes.test.mjs +116 -0
  62. package/bin/lean/release-gates.mjs +230 -0
  63. package/bin/lean/release-gates.test.mjs +146 -0
  64. package/bin/lean/release-ledger.mjs +176 -0
  65. package/bin/lean/release-ledger.test.mjs +226 -0
  66. package/bin/lean/release-minutes.mjs +102 -0
  67. package/bin/lean/release-minutes.test.mjs +107 -0
  68. package/bin/lean/release-nightly.mjs +75 -0
  69. package/bin/lean/release-nightly.test.mjs +48 -0
  70. package/bin/lean/release-postmerge.mjs +8 -2
  71. package/bin/lean/release-review.e2e.test.mjs +1 -0
  72. package/bin/lean/release-review.mjs +54 -7
  73. package/bin/lean/release-review.test.mjs +76 -7
  74. package/bin/lean/release-status.mjs +300 -0
  75. package/bin/lean/release-status.test.mjs +220 -0
  76. package/bin/lean/release-unitmap.mjs +35 -0
  77. package/bin/lean/release-unitmap.test.mjs +41 -0
  78. package/bin/lean/release-verify.mjs +221 -0
  79. package/bin/lean/release-verify.test.mjs +176 -0
  80. package/bin/lean/release.mjs +244 -22
  81. package/bin/lean/release.test.mjs +44 -0
  82. package/bin/lean/render.mjs +3 -1
  83. package/bin/lean/run-issue-placement.test.mjs +82 -0
  84. package/bin/lean/sandbox-remote.mjs +16 -0
  85. package/bin/lean/schedd.mjs +1 -1
  86. package/bin/lean/seam.mjs +115 -0
  87. package/bin/lean/seam.test.mjs +118 -0
  88. package/bin/lean/selftest-journey.mjs +40 -2
  89. package/bin/lean/selftest-journey.test.mjs +43 -3
  90. package/bin/lean/statuscomment.mjs +168 -0
  91. package/bin/lean/statuscomment.test.mjs +133 -0
  92. package/bin/lean/ui-quality.mjs +57 -0
  93. package/bin/lean/ui-quality.test.mjs +55 -0
  94. package/bin/lean/visual-gate.test.mjs +63 -0
  95. package/bin/pool/agent.mjs +16 -2
  96. package/bin/pool/router.mjs +5 -1
  97. package/bin/review-staging.mjs +5 -3
  98. package/bin/stats/card.mjs +117 -0
  99. package/bin/stats/card.test.mjs +109 -0
  100. package/bin/stats/conformance-outcomes.test.mjs +2 -1
  101. package/bin/stats/depth.mjs +1 -1
  102. package/bin/stats/gh-retry.test.mjs +152 -0
  103. package/bin/stats/github-source.mjs +147 -14
  104. package/bin/stats/index.mjs +35 -2
  105. package/bin/stats/stats.test.mjs +31 -3
  106. package/bin/vendor/js-yaml/LICENSE +21 -0
  107. package/bin/vendor/js-yaml/PIN.md +7 -0
  108. package/bin/vendor/js-yaml/js-yaml.mjs +3851 -0
  109. package/commands/design-render-critique-loop.md +2 -0
  110. package/commands/design.md +2 -0
  111. package/commands/issue.md +1 -1
  112. package/commands/milestone.md +1 -1
  113. package/commands/review-pr-agents/frontend.md +1 -0
  114. package/commands/review-pr-staging.md +5 -0
  115. package/docs/CONFIG.md +95 -2
  116. package/docs/ISSUE-WATCH.md +7 -0
  117. package/docs/OUTCOME-CODES.md +1 -0
  118. package/docs/STATS.md +10 -0
  119. package/docs/design/visual-gate.md +25 -0
  120. package/docs/eval/adversarial-bench.md +2 -2
  121. package/docs/eval/corpus/adversarial-v1.json +3 -3
  122. package/docs/site/start-a-new-project.md +7 -0
  123. package/docs/spec/forge-protocol-v1.md +31 -0
  124. package/package.json +1 -1
  125. package/pool/README.md +2 -0
  126. package/scripts/acceptance-red-green.sh +15 -1
  127. package/scripts/acceptance-red-green.test.sh +12 -0
  128. package/scripts/bench-adversarial.mjs +4 -0
  129. package/scripts/bench-lightlane.mjs +4 -1
  130. package/scripts/bootstrap-create.mjs +8 -2
  131. package/scripts/ci-local/scoping.mjs +19 -0
  132. package/scripts/ci-local.test.sh +16 -3
  133. package/scripts/fixtures/ci-local/gha-dorny/.github/workflows/ci.yml +4 -0
  134. package/scripts/plan-validate-live.mjs +9 -6
  135. package/scripts/review-prepare.sh +7 -1
  136. package/scripts/review-roster.sh +5 -2
  137. package/scripts/review-roster.test.sh +9 -0
  138. package/scripts/visual-gate.mjs +64 -0
  139. package/templates/bootstrap/technical-spike.md +17 -0
  140. package/templates/contracts/seam-check.mjs +236 -0
@@ -2,7 +2,7 @@
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 { parsePagesConfig, pageFiles, contractBriefProblems, pageFailures, designSpecApproved, designHold, designLabelApproved } from "./pagegate.mjs";
5
+ import { parsePagesConfig, pageFiles, designOnlyFiles, contractBriefProblems, pageFailures, designSpecApproved, designHold, designLabelApproved } from "./pagegate.mjs";
6
6
  import { pagePlanNote, domainChecksBlock } from "./prompts.mjs";
7
7
  import { pathDomains } from "./review-trigger.mjs";
8
8
  import { validateContract, precheck } from "./conformance.mjs";
@@ -75,3 +75,41 @@ describe("design hold (#5442)", () => {
75
75
  assert.equal(designLabelApproved([]), false);
76
76
  });
77
77
  });
78
+
79
+ describe("page gate exclusions (#5585)", () => {
80
+ const admin = "web/src/app/(site)/admin/page.tsx", pub = storeFiles[0];
81
+ const ex = parsePagesConfig({ exclude: ["web/src/app/**/admin/**"], design_only: ["web/src/app/**/dash/**"] }, { hasAppPages: true });
82
+ const dash = "web/src/app/dash/page.tsx";
83
+ it("parses exclude and design_only, default empty", () => {
84
+ assert.deepEqual([cfg.exclude, cfg.design_only], [[], []]);
85
+ assert.deepEqual(ex.exclude, ["web/src/app/**/admin/**"]);
86
+ });
87
+ it("an excluded route is not a public page at contract time or in precheck", async () => {
88
+ assert.deepEqual(pageFiles([admin, pub], ex), [pub]);
89
+ assert.deepEqual(pageFiles([admin], cfg), [admin]);
90
+ const c = { deliverables: [{ id: "D1", path: admin, change: "x", requirements: ["R1"] }] };
91
+ assert.deepEqual(contractBriefProblems(c, ex), []);
92
+ assert.equal(contractBriefProblems(c, cfg).length, 1);
93
+ assert.deepEqual(await pageFailures({ cfg: ex, files: [admin], diff: `+++ b/${admin}\n+[[null]]\n`, tracked: [admin], designApproved: false }), []);
94
+ });
95
+ it("auto-excludes a noindex page or layout when the file can be read", async () => {
96
+ const rd = (p) => (p === admin ? "export const metadata = { robots: { index: false } }" : p === "web/app/x/layout.tsx" ? "<meta name=robots content=noindex>" : "");
97
+ assert.deepEqual(pageFiles([admin], cfg, { readFile: rd }), []);
98
+ assert.deepEqual(pageFiles(["web/app/x/page.tsx"], cfg, { readFile: rd }), []);
99
+ assert.deepEqual(pageFiles([admin], cfg), [admin]);
100
+ assert.deepEqual(pageFiles([pub], cfg, { readFile: rd }), [pub]);
101
+ const c = { deliverables: [{ id: "D1", path: admin, change: "x", requirements: ["R1"] }] };
102
+ assert.deepEqual(contractBriefProblems(c, cfg, { readFile: rd }), []);
103
+ assert.deepEqual(await pageFailures({ cfg, files: [admin], diff: "", readFile: rd, tracked: [admin], designApproved: false }), []);
104
+ });
105
+ it("design_only keeps the design requirement but not SEO/GEO", async () => {
106
+ assert.deepEqual(designOnlyFiles([dash, pub], ex), [dash]);
107
+ assert.deepEqual(pageFiles([dash], ex), []);
108
+ const c = { deliverables: [{ id: "D1", path: dash, change: "x", requirements: ["R1"] }] };
109
+ const p = contractBriefProblems(c, ex);
110
+ assert.equal(p.length, 1); assert.match(p[0], /design_spec/);
111
+ assert.deepEqual(contractBriefProblems({ ...c, page_gate: { design_spec: "#1 FORGE:DESIGN_SPEC" } }, ex), []);
112
+ const f = await pageFailures({ cfg: ex, files: [dash], diff: "", tracked: [dash], designApproved: false });
113
+ assert.deepEqual(f.map((x) => x.kind).sort(), ["page_design_missing", "page_visual_missing"]);
114
+ });
115
+ });
@@ -10,6 +10,8 @@
10
10
  * env leaves empty (#4325).
11
11
  */
12
12
  import { builtinModules } from "node:module";
13
+ import { existsSync } from "node:fs";
14
+ import { join, dirname, delimiter } from "node:path";
13
15
  import { missingTool } from "./conformance.mjs";
14
16
 
15
17
  export const PREFLIGHT_CAP = 20;
@@ -306,5 +308,37 @@ export function declaredEnv(contract) {
306
308
  const plan = contract?.test_plan;
307
309
  const raw = Array.isArray(plan) ? plan.map((r) => r?.env) : [plan?.env];
308
310
  const names = raw.flatMap((e) => (Array.isArray(e) ? e : typeof e === "string" ? e.split(",") : [])).map((e) => String(typeof e === "string" ? e : e?.tool ?? "").trim());
309
- return [...new Set(names.filter((t) => /^[\w.+-]+$/.test(t)))];
311
+ return [...new Set(names.filter((t) => /^[\w.+-]+$/.test(t) && isExecutableName(t)))];
310
312
  }
313
+
314
+ /** #5590: pytest's built-in fixtures, never host executables. */
315
+ const PYTEST_FIXTURES = new Set(["caplog", "capsys", "capfd", "capsysbinary", "capfdbinary", "monkeypatch", "tmp_path", "tmp_path_factory", "tmpdir", "tmpdir_factory", "request", "recwarn", "pytestconfig", "mocker", "doctest_namespace", "cache", "testdir"]);
316
+ /** #5590: `env` lists executables only; CamelCase (a class such as FakeRedis), snake_case and pytest-fixture names are libraries/fixtures that come from the lockfile. Pure. */
317
+ export function isExecutableName(t) {
318
+ return !/[A-Z]/.test(t) && !t.includes("_") && !PYTEST_FIXTURES.has(t);
319
+ }
320
+
321
+ /**
322
+ * #5592: the project-local executable dirs a lane can run tools from: `node_modules/.bin` and a Python in-project `.venv/bin`
323
+ * at the worktree root and next to every tracked manifest (`files`: tracked paths; package.json, pyproject.toml, poetry.lock,
324
+ * uv.lock mark a project dir, so `services/<svc>/.venv/bin` in a monorepo counts). Only dirs that exist; nearest-to-root first.
325
+ * The tool probe and the heavy-shim writer resolve through these (appended after PATH), so both agree on what is runnable.
326
+ */
327
+ export function projectBinDirs(wt, files = [], { exists = existsSync, cap = 24 } = {}) {
328
+ const dirs = new Set(["."]);
329
+ for (const f of files) {
330
+ const base = String(f).split("/").pop();
331
+ if (["package.json", "pyproject.toml", "poetry.lock", "uv.lock"].includes(base) && !String(f).split("/").includes("node_modules")) dirs.add(dirname(f));
332
+ }
333
+ const out = [];
334
+ for (const d of [...dirs].sort((a, b) => a.split("/").length - b.split("/").length || a.localeCompare(b))) {
335
+ for (const rel of [".venv/bin", "node_modules/.bin"]) {
336
+ const p = d === "." ? join(wt, rel) : join(wt, d, rel);
337
+ if (exists(p) && out.length < cap) out.push(p);
338
+ }
339
+ }
340
+ return out;
341
+ }
342
+
343
+ /** #5592: `base` PATH with the project-local executable dirs appended (never ahead of what the lane already resolves). */
344
+ export const withLocalBins = (base, dirs) => [...String(base ?? "").split(delimiter).filter(Boolean), ...dirs.filter((d) => !String(base ?? "").split(delimiter).includes(d))].join(delimiter);
@@ -4,7 +4,7 @@ import { describe, it } from "node:test";
4
4
  import assert from "node:assert/strict";
5
5
  import { mkdirSync, writeFileSync } from "node:fs";
6
6
  import { join } from "node:path";
7
- import { testRunnerProblems, shellSegments, pythonImports, nodeImports, preflightProbes, preflightProblems, runProbeMiss, unsetEnvVars, runPreflight, knownToContract, contractCommands, depInstallFailures, testRunSummary } from "./preflight.mjs";
7
+ import { testRunnerProblems, shellSegments, pythonImports, nodeImports, preflightProbes, preflightProblems, runProbeMiss, unsetEnvVars, runPreflight, knownToContract, contractCommands, depInstallFailures, testRunSummary, projectBinDirs, withLocalBins } from "./preflight.mjs";
8
8
  import { runCheckCommand } from "./effects.mjs";
9
9
  import { repoTracks } from "./conformance.mjs";
10
10
  import { tmpDir } from "../tests/_tmp.mjs";
@@ -159,5 +159,31 @@ describe("#5447 declaredEnv", () => {
159
159
  assert.deepEqual(declaredEnv({ test_plan: { env: ["pytest", { tool: "uv" }, "bad name"] } }), ["pytest", "uv"]);
160
160
  assert.deepEqual(declaredEnv({ test_plan: [{ requirement: "R1", env: "pytest, uv" }, { requirement: "R2" }] }), ["pytest", "uv"]);
161
161
  assert.deepEqual(declaredEnv({}), []);
162
+ // #5590: fixtures and libraries are not executables
163
+ assert.deepEqual(declaredEnv({ test_plan: { env: ["pytest", "caplog", "FakeRedis", "tmp_path", "node", "psql"] } }), ["pytest", "node", "psql"]);
164
+ });
165
+ });
166
+
167
+ describe("project-local executables (#5592 3d/9)", () => {
168
+ const mkBin = (wt, rel, name) => { const d = join(wt, rel); mkdirSync(d, { recursive: true }); writeFileSync(join(d, name), "#!/bin/sh\nexit 0\n", { mode: 0o755 }); };
169
+ it("finds root and monorepo-service .venv/bin and node_modules/.bin, existing dirs only", () => {
170
+ const wt = tmpDir("fd-localbin-");
171
+ mkBin(wt, "services/cortex/.venv/bin", "pytest"); mkBin(wt, "web/node_modules/.bin", "vitest"); mkBin(wt, ".venv/bin", "ruff");
172
+ const dirs = projectBinDirs(wt, ["pyproject.toml", "services/cortex/poetry.lock", "services/other/uv.lock", "web/package.json", "web/node_modules/x/package.json"]);
173
+ assert.deepEqual(dirs, [join(wt, ".venv/bin"), join(wt, "web/node_modules/.bin"), join(wt, "services/cortex/.venv/bin")]);
174
+ });
175
+ it("a command probe over PATH + local bins finds a venv-only pytest (the tool check no longer says 'lacks pytest')", async () => {
176
+ const wt = tmpDir("fd-localbin-");
177
+ mkBin(wt, "services/cortex/.venv/bin", "pytest-fd5592");
178
+ const contract = { validate: [{ id: "V1", command: "pytest-fd5592 -q" }] };
179
+ const { probes } = preflightProbes(contract);
180
+ assert.equal(probes[0].kind, "command");
181
+ const base = process.env.PATH;
182
+ assert.notEqual((await runCheckCommand({ command: probes[0].probe, cwd: wt, env: { PATH: base } })).rc, 0, "absent from plain PATH");
183
+ const local = projectBinDirs(wt, ["services/cortex/poetry.lock"]);
184
+ assert.equal((await runCheckCommand({ command: probes[0].probe, cwd: wt, env: { PATH: withLocalBins(base, local) } })).rc, 0);
185
+ });
186
+ it("local bins go after the lane PATH, never ahead, and are not duplicated", () => {
187
+ assert.equal(withLocalBins("/a:/b", ["/c", "/a"]), "/a:/b:/c");
162
188
  });
163
189
  });
@@ -9,6 +9,7 @@ import { sequenceBuildNote } from "./seqreserve.mjs";
9
9
  import { capText, FIX_CAPS, FIX_PROMPT_MAX, NARROW_CAPS, NARROW_PROMPT_MAX } from "./fixround.mjs";
10
10
  import { SPLIT_MIN_FILES, SPLIT_MIN_LINES } from "./decompose.mjs";
11
11
  import { relaxationBlock } from "./relaxation.mjs";
12
+ import { visualReviewCheck } from "./ui-quality.mjs";
12
13
  import { stampRule } from "./stagestamp.mjs";
13
14
  import { FINDING_PITFALLS, PLANNER_TIGHTENING } from "./selfreview.mjs";
14
15
  import { isTrustedIssueComment } from "./prefilter.mjs"; // call-time use only: prefilter.mjs imports this module
@@ -546,7 +547,7 @@ export const DOMAIN_CHECKS = Object.freeze({
546
547
  design: "A public page diff with no approved FORGE:DESIGN_SPEC, or a rendering that ignores it (raw JSON as main content, null samples, dead-end empty states, no 390/1440 check), is a regression.",
547
548
  "seo-geo": "A public page diff with no target intent/ICP, title/H1/meta, canonical, structured data, sitemap entry or internal links, or no GEO surface (llms.txt, markdown mirror, ai-catalog, MCP description) an agent question resolves to, is a regression.",
548
549
  docs: "A user-facing diff (public API endpoint, MCP tool, dashboard page, CLI command, SDK method) with no matching docs change, or docs that contradict the code (endpoint paths, fields, scopes), is a regression.",
549
- frontend: "Dynamic API in a static/ISR tree: a headers(), cookies(), connection() or searchParams read in a layout, a not-found/error boundary or a module they import, when the route tree is static or ISR (revalidate, generateStaticParams, dynamic = 'force-static'), opts the route out of static rendering or throws at render and turns pages into HTTP 500.",
550
+ frontend: `${visualReviewCheck()} Dynamic API in a static/ISR tree: a headers(), cookies(), connection() or searchParams read in a layout, a not-found/error boundary or a module they import, when the route tree is static or ISR (revalidate, generateStaticParams, dynamic = 'force-static'), opts the route out of static rendering or throws at render and turns pages into HTTP 500.`,
550
551
  });
551
552
 
552
553
  /** #5099: the <domain_checks> block for the domains the diff touches; "" when none. */
@@ -0,0 +1,39 @@
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 { writeFileSync, readFileSync, chmodSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { tmpDir } from "../tests/_tmp.mjs";
8
+ import { labelDockerArgs } from "./heavy.mjs";
9
+ import { runCheckCommand, reapContainers } from "./effects.mjs";
10
+
11
+ describe("#5598 reap containers", () => {
12
+ it("labels docker run/create once; other commands untouched", () => {
13
+ const env = { FORGE_REAP_LABEL: "forgedock.reap=x" };
14
+ assert.deepEqual(labelDockerArgs("docker", ["run", "--rm", "img"], env), ["run", "--label", "forgedock.reap=x", "--rm", "img"]);
15
+ assert.deepEqual(labelDockerArgs("docker", ["--debug", "create", "i"], env), ["--debug", "create", "--label", "forgedock.reap=x", "i"]);
16
+ const done = ["run", "--label", "forgedock.reap=x", "i"];
17
+ assert.deepEqual(labelDockerArgs("docker", done, env), done);
18
+ assert.deepEqual(labelDockerArgs("docker", ["ps"], env), ["ps"]);
19
+ assert.deepEqual(labelDockerArgs("docker", ["run", "i"], {}), ["run", "i"]);
20
+ assert.deepEqual(labelDockerArgs("pytest", ["run"], env), ["run"]);
21
+ });
22
+
23
+ it("a timed-out check removes the containers labelled for it", async () => {
24
+ const dir = tmpDir("reap-"), log = join(dir, "calls.log");
25
+ writeFileSync(join(dir, "docker"), `#!/bin/sh\necho "$@" >> ${log}\n[ "$1" = ps ] && echo abc123\nexit 0\n`);
26
+ chmodSync(join(dir, "docker"), 0o755);
27
+ const r = await runCheckCommand({ command: "sleep 30", cwd: dir, timeoutMs: 300, graceMs: 100, env: { PATH: `${dir}:${process.env.PATH}` } });
28
+ assert.equal(r.rc, 124);
29
+ const calls = readFileSync(log, "utf8");
30
+ assert.match(calls, /ps -aq --filter label=forgedock\.reap=/);
31
+ assert.match(calls, /rm -f abc123/);
32
+ });
33
+
34
+ it("a missing docker never throws and keeps rc", async () => {
35
+ assert.deepEqual(await reapContainers("forgedock.reap=none", { env: { PATH: "/nonexistent" } }), []);
36
+ const r = await runCheckCommand({ command: "exit 3", cwd: tmpDir("reap-") });
37
+ assert.equal(r.rc, 3);
38
+ });
39
+ });
@@ -161,10 +161,10 @@ describe("in-batch recovery of mechanical needs-human (#4267)", () => {
161
161
  assert.deepEqual(seen.sort(), [[1, 101], [2, 102]]);
162
162
  });
163
163
 
164
- it("contract.invalid recovers only when the issue was edited mid-run", async () => {
165
- const { rows, calls } = await batch({ 1: [NH("contract.invalid", "contract invalid", { issueEdited: true }), { terminalReason: "merged" }], 2: [NH("contract.invalid")] });
164
+ it("#5623: contract.invalid recovers with a fresh plan whether or not the issue was edited mid-run", async () => {
165
+ const { rows, calls } = await batch({ 1: [NH("contract.invalid", "contract invalid", { issueEdited: true }), { terminalReason: "merged" }], 2: [NH("contract.invalid"), { terminalReason: "merged" }] });
166
166
  assert.equal(byIssue(rows)[1].recovered, "contract.invalid");
167
- assert.equal(byIssue(rows)[2].outcome, "needs-human"); assert.equal(calls.filter((c) => c.n === 2).length, 1);
167
+ assert.equal(byIssue(rows)[2].recovered, "contract.invalid"); assert.equal(byIssue(rows)[2].outcome, "merged"); assert.equal(calls.filter((c) => c.n === 2).length, 2);
168
168
  });
169
169
 
170
170
  it("relabelNeedsHuman (SPEC-7/8): only a recovery that ends final engine-error/deferred relabels; invalid/merged never; a requeued deferred waits", async () => {
@@ -575,3 +575,28 @@ describe("#5423 env.tool_missing recovery placement", () => {
575
575
  assert.deepEqual(await run(2), ["remote", "remote", "local"]);
576
576
  });
577
577
  });
578
+
579
+ describe("#5592 env.tool_missing recovery is not a verbatim replay", () => {
580
+ const go = (script, first = "remote") => {
581
+ const calls = [], decisions = [];
582
+ return orchestrate({ issues: [7], parallel: 2, recovery: { maxAttempts: 2, mechanicalMaxAttempts: 3 }, readBody: async () => "",
583
+ remote: { max: 2, isRemote: () => true, place: () => ({ where: first, reason: "test" }), admit: () => ({ ok: true }), onBudget: "stop", costPerMinute: 0 },
584
+ runOne: async (_n, _l, ctx = {}) => { calls.push(ctx.recover?.attempt ?? 0); return script[Math.min(calls.length - 1, script.length - 1)]; },
585
+ decide: (d) => decisions.push(d) }).then((rows) => ({ rows, calls, decisions }));
586
+ };
587
+ const miss = (tool, extra, more = {}) => ({ terminalReason: "needs-human", code: "env.tool_missing", detail: `Environment error: the host is missing ${tool}, so validate command(s) could not run\n- env.tool_missing: ${extra}`, ...more });
588
+ it("a first tool_missing from a run on the host is not recovered on that same host: literal message, no lane", async () => {
589
+ const r = await go([miss("pytest", "x")], "local");
590
+ assert.deepEqual(r.calls, [0]);
591
+ assert.match(r.rows[0].detail, /recovery would replay the identical frozen contract on that same host, so none is launched/);
592
+ });
593
+ it("a first tool_missing from a remote sandbox still recovers on the host", async () => {
594
+ const r = await go([miss("pytest", "x", { placement: { where: "remote" } }), { terminalReason: "merged", pr: 1 }]);
595
+ assert.deepEqual(r.calls, [0, 1]);
596
+ });
597
+ it("a repeat with the same missing tools stops even when the detail lines differ", async () => {
598
+ const r = await go([miss("pytest", "probe line A", { placement: { where: "remote" } }), miss("pytest", "other line B /tmp/x1", { placement: { where: "local" } })]);
599
+ assert.deepEqual(r.calls, [0, 1]);
600
+ assert.match(r.rows[0].detail, /same `env\.tool_missing` as the run before it/);
601
+ });
602
+ });
@@ -0,0 +1,169 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * `.forge/release.yaml` (#5551): committed, nested release policy (`schema: 1`). Read ONLY from the default branch with
5
+ * `git show origin/<default>:.forge/release.yaml`, never the worktree or PR head, so a PR cannot weaken its own gates (I13).
6
+ * Parsed by the vendored, pinned js-yaml (bin/vendor/js-yaml/PIN.md) and validated closed: unknown keys, wrong types,
7
+ * duplicate keys, unreachable lanes and keys deferred to a later phase (I23) all fail. Absent file: the flat forge.yaml `release.*` keys.
8
+ */
9
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
10
+ import { dirname, join } from "node:path";
11
+ import { createHash } from "node:crypto";
12
+ import { load, JSON_SCHEMA } from "../vendor/js-yaml/js-yaml.mjs";
13
+ import { readReleaseConfig } from "./release.mjs";
14
+ import { readBranches } from "./lane.mjs";
15
+ import { catalogueFindings } from "./release-gates.mjs";
16
+
17
+ export const POLICY_PATH = ".forge/release.yaml";
18
+ export const DEFERRED_KEYS = ["plan.auto_if", "retention_days", "ci.forbid_per_issue_steps", "couplings[].refine", "ci.provider=command", "risk.weights"];
19
+
20
+ export const INIT_PROFILE = `schema: 1
21
+ branches: {default: main}
22
+ plan: {approval: wait}
23
+ lanes: {release: {pipeline: existing}}
24
+ merge: {approval: confirm}
25
+ `;
26
+
27
+ // Schema nodes: {t: "object", p: {key: node}} (closed), {t: "map", v: node}, {t: "array", i: node}, {t: "string"|"number"|"integer"|"boolean"|"any"}, {e: [..]}; `n` allows null.
28
+ const S = { t: "string" }, N = { t: "number" }, I = { t: "integer" }, B = { t: "boolean" }, ANY = { t: "any" };
29
+ const SN = { t: "string", n: true };
30
+ const list = (i = S) => ({ t: "array", i });
31
+ const obj = (p, extra = {}) => ({ t: "object", p, ...extra });
32
+ const en = (...e) => ({ t: "string", e });
33
+ const PIPELINE = obj({ workflow: S, trigger: en("push", "dispatch"), inputs: { t: "map", v: S }, wait: B });
34
+ export const POLICY_SCHEMA = obj({
35
+ schema: { t: "integer", e: [1] },
36
+ branches: obj({ default: S, integration: SN, train: S, release: S, hotfix: S }),
37
+ trust: obj({ actors: list(), require_verified_commits: B }),
38
+ state: obj({ ledger_prefix: S, lease_ttl_s: N, heartbeat_s: N }),
39
+ units: { t: "map", v: obj({ paths: list(), image: SN, criticality: en("low", "medium", "high"), tests: list(), verify: list(), service_pipeline: B, single_host_ok: B }) },
40
+ couplings: list(obj({ paths: list(), affects: list() })),
41
+ contracts: list(obj({ producer: S, consumers: list(), paths: list(), additive_only: B })),
42
+ forces: list(obj({ paths: list(), pipeline: en("full", "service", "hotfix"), reason: S })),
43
+ classify: obj({ min_confidence: N, text_only_cap: N, triage_max_per_hour: N, exists_in_evidence: en("mechanical", "llm") }),
44
+ risk: obj({ rules: list(obj({ when: obj({ migration: B, paths: list(), contract: B, rolled_units_gt: N, diff_lines_gt: N, requires: S }), risk: en("low", "medium", "high"), forces: S })) }),
45
+ plan: obj({ approval: en("wait", "auto", "auto-if"), skip_labels: list(), require_design_gate: B, max_issues: N, stale_snapshot_s: N }),
46
+ lanes: { t: "map", v: obj({ pipeline: S, ci_tier: S, approval: S, budget: S, base: en("live", "integration", "default"), units_max: N, max_risk: en("low", "medium", "high"), train_max_issues: N, train_max_units: N, soak_min: { t: "any" }, flag_policy: en("require", "warn", "off"), requires: list() }) },
47
+ merge: obj({ approval: en("confirm", "with-plan", "auto"), method: en("merge-commit", "squash", "rebase"), trailers: list() }),
48
+ ci: obj({ provider: en("github-actions", "command"), required_checks: ANY, selection: ANY, rerun_budget_min: N, fix: ANY, flake: obj({ quarantine_after: N, window_days: N }), unskippable: list(), tiers: { t: "map", v: obj({ jobs: list() }) }, nightly: ANY, budget: ANY }),
49
+ preflight: obj({ commands: list(), timeout_s: N, blocking: B }),
50
+ deploy: obj({ live_release_command: S, freeze_variable: S, concurrency_group: S, start_timeout_s: N, stage_timeout_s: N, expected_digests_command: S, recovery: obj({ rerun_max: I, max_attempts: I, signatures: list() }), pipelines: { t: "map", v: PIPELINE } }),
51
+ verify: obj({ workflow: S, results: list(obj({ workflow: S, kind: en("smoke", "edge", "convergence") })), flags: list(obj({ flag: S, off_command: S })), slis: list(ANY), post_deploy_checks_file: S, close_requires: en("verified", "deployed") }),
52
+ rollback: obj({ triggers: list(), ladder: list(), refuse_across: list(), open_revert_pr: B }),
53
+ quarantine: obj({ days: N, max: N }),
54
+ gates: obj({ demote_fb_rate: N, demote_window: I, safety: list() }),
55
+ controls: obj({ intake: ANY, conductor: ANY, exempt: ANY }),
56
+ });
57
+
58
+ const kind = (v) => (v === null ? "null" : Array.isArray(v) ? "array" : typeof v);
59
+ const typeOk = { string: (v) => typeof v === "string", number: (v) => typeof v === "number" && Number.isFinite(v), integer: Number.isInteger, boolean: (v) => typeof v === "boolean" };
60
+
61
+ function walk(node, v, at, out) {
62
+ if (v === null && node.n) return;
63
+ if (node.t === "any") return;
64
+ if (node.t === "object" || node.t === "map") {
65
+ if (kind(v) !== "object") return void out.push(`${at}: expected a mapping, got ${kind(v)}`);
66
+ for (const [k, x] of Object.entries(v)) {
67
+ const child = node.t === "map" ? node.v : node.p[k];
68
+ if (!child) out.push(`${at ? `${at}.` : ""}${k}: unknown key`);
69
+ else walk(child, x, `${at ? `${at}.` : ""}${k}`, out);
70
+ }
71
+ } else if (node.t === "array") {
72
+ if (!Array.isArray(v)) return void out.push(`${at}: expected a list, got ${kind(v)}`);
73
+ v.forEach((x, i) => walk(node.i, x, `${at}[${i}]`, out));
74
+ } else if (!typeOk[node.t]?.(v)) return void out.push(`${at}: expected ${node.t}, got ${kind(v)}`);
75
+ if (node.e && !node.e.includes(v)) out.push(`${at}: ${JSON.stringify(v)} is not one of ${node.e.join("|")}`);
76
+ }
77
+
78
+ const DEFERRED_AT = [
79
+ [(p) => p?.plan && "auto_if" in p.plan, "plan.auto_if"],
80
+ [(p) => p && "retention_days" in p, "retention_days"],
81
+ [(p) => p?.ci && "forbid_per_issue_steps" in p.ci, "ci.forbid_per_issue_steps"],
82
+ [(p) => Array.isArray(p?.couplings) && p.couplings.some((c) => c && typeof c === "object" && "refine" in c), "couplings[].refine"],
83
+ [(p) => p?.ci?.provider === "command", "ci.provider: command"],
84
+ [(p) => p?.risk && "weights" in p.risk, "risk.weights"],
85
+ ];
86
+
87
+ const DEFERRED_UNKNOWN = new Set(["plan.auto_if", "retention_days", "ci.forbid_per_issue_steps", "risk.weights"].map((k) => `${k}: unknown key`));
88
+
89
+ /** Lanes that can never run: unknown pipeline, `base: integration` without an integration branch, tier not in `ci.tiers`. */
90
+ function unreachable(p, out) {
91
+ const pipes = p.deploy?.pipelines && Object.keys(p.deploy.pipelines);
92
+ const tiers = p.ci?.tiers && Object.keys(p.ci.tiers);
93
+ for (const [name, l] of Object.entries(p.lanes ?? {})) {
94
+ if (!l || typeof l !== "object") continue;
95
+ if (pipes?.length && l.pipeline && l.pipeline !== "existing" && !pipes.includes(l.pipeline)) out.push(`lanes.${name}: unreachable, pipeline ${l.pipeline} is not in deploy.pipelines`);
96
+ if (l.base === "integration" && !p.branches?.integration) out.push(`lanes.${name}: unreachable, base integration but branches.integration is not set`);
97
+ if (tiers?.length && l.ci_tier && !tiers.includes(l.ci_tier)) out.push(`lanes.${name}: unreachable, ci_tier ${l.ci_tier} is not in ci.tiers`);
98
+ }
99
+ const units = Object.keys(p.units ?? {});
100
+ const dangling = (ids, at) => (ids ?? []).filter((u) => !units.includes(u)).forEach((u) => out.push(`${at}: unit ${u} is not in units`));
101
+ (p.couplings ?? []).forEach((c, i) => dangling(c?.affects, `couplings[${i}].affects`));
102
+ (p.contracts ?? []).forEach((c, i) => { dangling(c?.producer ? [c.producer] : [], `contracts[${i}].producer`); dangling(c?.consumers, `contracts[${i}].consumers`); });
103
+ }
104
+
105
+ /** @returns {string[]} findings, empty when `policy` is valid. */
106
+ export function validatePolicy(policy) {
107
+ const out = [];
108
+ if (kind(policy) !== "object") return [`policy: expected a mapping, got ${kind(policy)}`];
109
+ for (const [test, name] of DEFERRED_AT) if (test(policy)) out.push(`${name}: deferred to a later phase, not accepted yet`);
110
+ const rest = [];
111
+ walk(POLICY_SCHEMA, policy, "", rest);
112
+ out.push(...rest.filter((l) => !DEFERRED_UNKNOWN.has(l)));
113
+ if (policy.schema !== 1) out.push("schema: required and must be 1");
114
+ if (!out.length) unreachable(policy, out);
115
+ return out;
116
+ }
117
+
118
+ /** @returns {{policy}|{error}} js-yaml with JSON_SCHEMA; duplicate keys throw. */
119
+ export function parsePolicy(text) {
120
+ try { return { policy: load(String(text), { schema: JSON_SCHEMA }) }; } catch (e) { return { error: String(e?.message ?? e).split("\n")[0] }; }
121
+ }
122
+
123
+ /**
124
+ * Policy as of the default branch. `source`: "file" (sha = sha256 of the text), or "forge.yaml" (flat `release.*` fallback) when the file is absent there.
125
+ * Only `io.git(["show", "origin/<default>:.forge/release.yaml"])` is read: a head-modified worktree copy has no effect (I13).
126
+ */
127
+ export function readPolicy({ io, defaultBranch, cwd = process.cwd(), ref }) {
128
+ const spec = `${ref ?? `origin/${defaultBranch}`}:${POLICY_PATH}`;
129
+ let text = null;
130
+ try { text = String(io.git(["show", spec])); } catch { text = null; }
131
+ if (text === null) {
132
+ let raw = ""; try { raw = readFileSync(join(cwd, "forge.yaml"), "utf8"); } catch { /* none */ }
133
+ return { source: "forge.yaml", policy: null, flat: readReleaseConfig(raw), findings: [] };
134
+ }
135
+ const { policy, error } = parsePolicy(text);
136
+ const findings = error ? [`parse: ${error}`] : validatePolicy(policy);
137
+ return { source: "file", policy: findings.length ? null : policy, findings, sha: createHash("sha256").update(text).digest("hex") };
138
+ }
139
+
140
+ const GATES_PATH_LABEL = ".forge/gates.yaml";
141
+ const flagOf = (argv, f) => { const i = argv.indexOf(f); return i >= 0 ? argv[i + 1] : null; };
142
+
143
+ /** `forgedock release check-config [--ref <git ref>]`: exit 0 valid (or file absent: flat keys), 1 on any finding. */
144
+ export function checkConfigFromCli(argv, { io, cwd = process.cwd() }) {
145
+ const defaultBranch = readBranches(cwd).default || "main";
146
+ const ref = flagOf(argv, "--ref");
147
+ const gf = catalogueFindings(io, ref ?? `origin/${defaultBranch}`); // #5583: .forge/gates.yaml, validated when present
148
+ const gatesLines = () => (gf ?? []).map((f) => `release check-config: ${GATES_PATH_LABEL}: ${f}`);
149
+ const r = readPolicy({ io, defaultBranch, cwd, ref });
150
+ if (r.source === "forge.yaml") {
151
+ io.print(`release check-config: no ${POLICY_PATH} on origin/${defaultBranch}; using forge.yaml release.* keys`);
152
+ gatesLines().forEach((l) => io.print(l));
153
+ return gf?.length ? 1 : 0;
154
+ }
155
+ const findings = [...r.findings, ...(gf ?? []).map((f) => `${GATES_PATH_LABEL}: ${f}`)];
156
+ findings.forEach((f) => io.print(`release check-config: ${f}`));
157
+ io.print(findings.length ? `release check-config: FAILED (${findings.length})` : `release check-config: ok (sha256 ${r.sha.slice(0, 12)})`);
158
+ return findings.length ? 1 : 0;
159
+ }
160
+
161
+ /** `forgedock release init`: writes the zero-config profile (7.4) to `.forge/release.yaml` and nothing else; never overwrites. */
162
+ export function initFromCli(_argv, { io, cwd = process.cwd() }) {
163
+ const file = join(cwd, POLICY_PATH);
164
+ if (existsSync(file)) { io.print(`release init: ${POLICY_PATH} exists; not overwriting`); return 1; }
165
+ mkdirSync(dirname(file), { recursive: true });
166
+ writeFileSync(file, INIT_PROFILE);
167
+ io.print(`release init: wrote ${POLICY_PATH}`);
168
+ return 0;
169
+ }
@@ -0,0 +1,132 @@
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 { existsSync, readFileSync, readdirSync, writeFileSync, mkdirSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { tmpDir } from "../tests/_tmp.mjs";
8
+ import { parsePolicy, validatePolicy, readPolicy, INIT_PROFILE, checkConfigFromCli, initFromCli, POLICY_PATH } from "./release-config.mjs";
9
+ import { releaseFromCli } from "./release.mjs";
10
+
11
+ const OK = `schema: 1
12
+ branches: {default: main, integration: staging}
13
+ units:
14
+ api: {paths: ["services/api/**"], criticality: high}
15
+ web: {paths: ["web/**"]}
16
+ couplings:
17
+ - {paths: ["shared/**"], affects: [api, web]}
18
+ lanes:
19
+ release: {pipeline: full, ci_tier: T3, base: integration}
20
+ deploy:
21
+ pipelines:
22
+ full: {workflow: deploy.yml, trigger: push, wait: true}
23
+ ci:
24
+ tiers: {T3: {jobs: [e2e]}}
25
+ `;
26
+ const check = (text) => { const r = parsePolicy(text); return r.error ? [`parse: ${r.error}`] : validatePolicy(r.policy); };
27
+ const ioFor = (files, calls = []) => ({ calls, printed: [], print(l) { this.printed.push(l); }, git: (a) => { calls.push(a); const t = files[a[1]]; if (t === undefined) throw new Error("missing"); return t; } });
28
+
29
+ describe("validate", () => {
30
+ it("accepts a full policy and the init profile", () => {
31
+ assert.deepEqual(check(OK), []);
32
+ assert.deepEqual(check(INIT_PROFILE), []);
33
+ });
34
+ it("fails closed: unknown key, wrong type, duplicate key, bad schema", () => {
35
+ assert.match(check(OK + "bogus: 1\n").join(), /bogus: unknown key/);
36
+ assert.match(check(OK.replace("criticality: high", "criticality: extreme")).join(), /criticality/);
37
+ assert.match(check(OK.replace("paths: [\"web/**\"]", "paths: web")).join(), /expected a list/);
38
+ assert.match(check(OK + "plan: {approval: wait}\nplan: {approval: auto}\n").join(), /parse: .*duplicated mapping key/);
39
+ assert.match(check("branches: {default: main}\n").join(), /schema/);
40
+ assert.match(check("schema: 2\n").join(), /not one of 1/);
41
+ });
42
+ it("unreachable lanes fail", () => {
43
+ assert.match(check(OK.replace("pipeline: full, ci_tier", "pipeline: nope, ci_tier")).join(), /pipeline nope is not in deploy.pipelines/);
44
+ assert.match(check(OK.replace("ci_tier: T3", "ci_tier: T9")).join(), /ci_tier T9/);
45
+ assert.match(check(OK.replace(", integration: staging", "")).join(), /branches.integration is not set/);
46
+ assert.match(check(OK.replace("affects: [api, web]", "affects: [api, ghost]")).join(), /unit ghost/);
47
+ });
48
+ });
49
+
50
+ describe("I23 deferred keys are rejected", () => {
51
+ const cases = {
52
+ "plan.auto_if": "plan: {auto_if: x}\n", "retention_days": "retention_days: 30\n", "ci.forbid_per_issue_steps": "ci: {forbid_per_issue_steps: true}\n",
53
+ "couplings[].refine": "couplings:\n - {paths: [a], affects: [api], refine: x}\n", "ci.provider: command": "ci: {provider: command}\n", "risk.weights": "risk: {weights: {a: 1}}\n",
54
+ };
55
+ for (const [name, extra] of Object.entries(cases)) it(name, () => {
56
+ const out = check(`schema: 1\nunits:\n api: {paths: [a]}\n${extra}`);
57
+ assert.ok(out.some((l) => l.startsWith(name) && /deferred/.test(l)), `${name}: ${out.join(" | ")}`);
58
+ });
59
+ });
60
+
61
+ describe("readPolicy (I13)", () => {
62
+ it("reads origin/<default>:.forge/release.yaml via git show only; a head-modified worktree copy has no effect", () => {
63
+ const cwd = tmpDir("relcfg-");
64
+ mkdirSync(join(cwd, ".forge"));
65
+ writeFileSync(join(cwd, POLICY_PATH), "schema: 1\nplan: {approval: auto}\n"); // PR head weakens the gate
66
+ const calls = [];
67
+ const r = readPolicy({ io: ioFor({ "origin/main:.forge/release.yaml": INIT_PROFILE }, calls), defaultBranch: "main", cwd });
68
+ assert.deepEqual(calls, [["show", "origin/main:.forge/release.yaml"]]);
69
+ assert.equal(r.source, "file");
70
+ assert.equal(r.policy.plan.approval, "wait");
71
+ assert.match(r.sha, /^[0-9a-f]{64}$/);
72
+ });
73
+ it("an invalid committed file yields findings and no policy", () => {
74
+ const r = readPolicy({ io: ioFor({ "origin/main:.forge/release.yaml": "schema: 1\nx: 1\n" }), defaultBranch: "main" });
75
+ assert.equal(r.policy, null); assert.match(r.findings.join(), /x: unknown key/);
76
+ });
77
+ it("absent file falls back to the flat forge.yaml release.* keys", () => {
78
+ const cwd = tmpDir("relcfg-");
79
+ writeFileSync(join(cwd, "forge.yaml"), "release:\n auto_merge: true\n publish_workflow: p.yml\n");
80
+ const r = readPolicy({ io: ioFor({}), defaultBranch: "main", cwd });
81
+ assert.equal(r.source, "forge.yaml"); assert.equal(r.flat.autoMerge, true); assert.equal(r.flat.publishWorkflow, "p.yml");
82
+ });
83
+ });
84
+
85
+ describe("CLI", () => {
86
+ it("check-config exits 1 on findings, 0 when valid or absent", async () => {
87
+ const cwd = tmpDir("relcfg-");
88
+ const run = (files) => { const io = ioFor(files); return releaseFromCli(["check-config"], { io, cwd }).then((c) => [c, io.printed.join("\n")]); };
89
+ assert.equal((await run({ "origin/main:.forge/release.yaml": OK }))[0], 0);
90
+ const bad = await run({ "origin/main:.forge/release.yaml": OK + "zzz: 1\n" });
91
+ assert.equal(bad[0], 1); assert.match(bad[1], /zzz: unknown key/);
92
+ assert.equal((await run({}))[0], 0);
93
+ });
94
+ it("init writes the 7.4 profile and nothing else, and never overwrites", async () => {
95
+ const cwd = tmpDir("relcfg-");
96
+ const io = ioFor({});
97
+ assert.equal(await releaseFromCli(["init"], { io, cwd }), 0);
98
+ assert.equal(readFileSync(join(cwd, POLICY_PATH), "utf8"), INIT_PROFILE);
99
+ assert.deepEqual(readdirSync(cwd), [".forge"]); assert.deepEqual(readdirSync(join(cwd, ".forge")), ["release.yaml"]);
100
+ assert.deepEqual(check(INIT_PROFILE), []);
101
+ assert.equal(initFromCli([], { io, cwd }), 1);
102
+ assert.equal(existsSync(join(cwd, "forge.yaml")), false);
103
+ });
104
+
105
+ it("accepts the flake and quarantine policy keys (#5568)", () => {
106
+ assert.deepEqual(check(`${OK} flake: {quarantine_after: 3, window_days: 14}\nquarantine: {days: 14, max: 15}\n`.replace("ci:\n tiers: {T3: {jobs: [e2e]}}\n flake", "ci:\n tiers: {T3: {jobs: [e2e]}}\n flake")), []);
107
+ assert.notDeepEqual(check(`${OK}quarantine: {max: x}\n`), []);
108
+ });
109
+ it("accepts the verification layer keys and rejects a bad result kind (#5562)", () => {
110
+ assert.deepEqual(check(`${OK}verify:\n workflow: verify.yml\n close_requires: verified\n results: [{workflow: smoke.yml, kind: smoke}]\n flags: [{flag: F, off_command: x}]\n`), []);
111
+ assert.notDeepEqual(check(`${OK}verify:\n results: [{workflow: s.yml, kind: nope}]\n`), []);
112
+ });
113
+ });
114
+
115
+ describe("gates catalogue and policy (#5583)", () => {
116
+ const GATE = `schema: 1\ngates:\n - {id: g1, protects_against: "#1", where: deploy, determinism: high, pre_merge_artifact: f.json, version: v1, mode: block, owner: me, review_by: 2027-01-01}\n`;
117
+ const gio = (files) => ({ printed: [], print(l) { this.printed.push(l); }, git(a) { const t = files[a[1].split(":").slice(1).join(":")]; if (t === undefined) throw new Error("missing"); return t; } });
118
+ it("accepts the gates policy keys and rejects a wrong type", () => {
119
+ assert.deepEqual(check(OK + "gates: {demote_fb_rate: 5, demote_window: 20, safety: [a]}\n"), []);
120
+ assert.match(check(OK + "gates: {demote_window: 2.5}\n").join(), /demote_window/);
121
+ });
122
+ it("check-config reports catalogue errors, passes a valid one, ignores an absent one", () => {
123
+ const bad = gio({ ".forge/gates.yaml": GATE.replace("mode: block", "mode: nope"), [POLICY_PATH]: OK });
124
+ assert.equal(checkConfigFromCli([], { io: bad }), 1);
125
+ assert.match(bad.printed.join("\n"), /gates\.yaml: gates\[0\]\.mode/);
126
+ const good = gio({ ".forge/gates.yaml": GATE, [POLICY_PATH]: OK });
127
+ assert.equal(checkConfigFromCli([], { io: good }), 0);
128
+ const none = gio({ [POLICY_PATH]: OK });
129
+ assert.equal(checkConfigFromCli([], { io: none }), 0);
130
+ assert.doesNotMatch(none.printed.join("\n"), /gates/);
131
+ });
132
+ });