forgedock 1.56.0 → 1.57.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 (131) hide show
  1. package/bin/config-schema.mjs +1 -1
  2. package/bin/engine/outcome-codes.mjs +1 -0
  3. package/bin/engine/phases.mjs +4 -3
  4. package/bin/engine-cli.mjs +46 -10
  5. package/bin/forgedock.mjs +52 -3
  6. package/bin/gc.mjs +43 -6
  7. package/bin/help-text.mjs +3 -1
  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 +88 -17
  14. package/bin/lean/conformance.test.mjs +98 -3
  15. package/bin/lean/decisions.mjs +86 -1
  16. package/bin/lean/decisions.test.mjs +21 -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 +12 -2
  32. package/bin/lean/issuewatch-parity.test.mjs +26 -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 +72 -21
  39. package/bin/lean/lean.test.mjs +149 -3
  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 +25 -0
  52. package/bin/lean/release-config.mjs +158 -0
  53. package/bin/lean/release-config.test.mjs +109 -0
  54. package/bin/lean/release-control.mjs +148 -0
  55. package/bin/lean/release-control.test.mjs +143 -0
  56. package/bin/lean/release-fence.mjs +50 -0
  57. package/bin/lean/release-fence.test.mjs +105 -0
  58. package/bin/lean/release-flakes.mjs +139 -0
  59. package/bin/lean/release-flakes.test.mjs +116 -0
  60. package/bin/lean/release-ledger.mjs +160 -0
  61. package/bin/lean/release-ledger.test.mjs +226 -0
  62. package/bin/lean/release-minutes.mjs +92 -0
  63. package/bin/lean/release-minutes.test.mjs +99 -0
  64. package/bin/lean/release-nightly.mjs +75 -0
  65. package/bin/lean/release-nightly.test.mjs +48 -0
  66. package/bin/lean/release-postmerge.mjs +8 -2
  67. package/bin/lean/release-review.e2e.test.mjs +1 -0
  68. package/bin/lean/release-review.mjs +54 -7
  69. package/bin/lean/release-review.test.mjs +76 -7
  70. package/bin/lean/release-unitmap.mjs +35 -0
  71. package/bin/lean/release-unitmap.test.mjs +41 -0
  72. package/bin/lean/release.mjs +177 -19
  73. package/bin/lean/release.test.mjs +40 -0
  74. package/bin/lean/render.mjs +3 -1
  75. package/bin/lean/run-issue-placement.test.mjs +82 -0
  76. package/bin/lean/sandbox-remote.mjs +16 -0
  77. package/bin/lean/schedd.mjs +1 -1
  78. package/bin/lean/seam.mjs +115 -0
  79. package/bin/lean/seam.test.mjs +118 -0
  80. package/bin/lean/selftest-journey.mjs +40 -2
  81. package/bin/lean/selftest-journey.test.mjs +43 -3
  82. package/bin/lean/statuscomment.mjs +168 -0
  83. package/bin/lean/statuscomment.test.mjs +133 -0
  84. package/bin/lean/ui-quality.mjs +57 -0
  85. package/bin/lean/ui-quality.test.mjs +55 -0
  86. package/bin/lean/visual-gate.test.mjs +63 -0
  87. package/bin/pool/agent.mjs +16 -2
  88. package/bin/pool/router.mjs +5 -1
  89. package/bin/review-staging.mjs +5 -3
  90. package/bin/stats/card.mjs +117 -0
  91. package/bin/stats/card.test.mjs +109 -0
  92. package/bin/stats/conformance-outcomes.test.mjs +2 -1
  93. package/bin/stats/depth.mjs +1 -1
  94. package/bin/stats/gh-retry.test.mjs +152 -0
  95. package/bin/stats/github-source.mjs +147 -14
  96. package/bin/stats/index.mjs +35 -2
  97. package/bin/stats/stats.test.mjs +31 -3
  98. package/bin/vendor/js-yaml/LICENSE +21 -0
  99. package/bin/vendor/js-yaml/PIN.md +7 -0
  100. package/bin/vendor/js-yaml/js-yaml.mjs +3851 -0
  101. package/commands/design-render-critique-loop.md +2 -0
  102. package/commands/design.md +2 -0
  103. package/commands/issue.md +1 -1
  104. package/commands/milestone.md +1 -1
  105. package/commands/review-pr-agents/frontend.md +1 -0
  106. package/commands/review-pr-staging.md +5 -0
  107. package/docs/CONFIG.md +75 -1
  108. package/docs/ISSUE-WATCH.md +7 -0
  109. package/docs/OUTCOME-CODES.md +1 -0
  110. package/docs/STATS.md +10 -0
  111. package/docs/design/visual-gate.md +25 -0
  112. package/docs/eval/adversarial-bench.md +2 -2
  113. package/docs/eval/corpus/adversarial-v1.json +3 -3
  114. package/docs/site/start-a-new-project.md +7 -0
  115. package/docs/spec/forge-protocol-v1.md +31 -0
  116. package/package.json +1 -1
  117. package/pool/README.md +2 -0
  118. package/scripts/acceptance-red-green.sh +15 -1
  119. package/scripts/acceptance-red-green.test.sh +12 -0
  120. package/scripts/bench-adversarial.mjs +4 -0
  121. package/scripts/bench-lightlane.mjs +4 -1
  122. package/scripts/bootstrap-create.mjs +8 -2
  123. package/scripts/ci-local.test.sh +3 -3
  124. package/scripts/fixtures/ci-local/gha-dorny/.github/workflows/ci.yml +4 -0
  125. package/scripts/plan-validate-live.mjs +9 -6
  126. package/scripts/review-prepare.sh +7 -1
  127. package/scripts/review-roster.sh +5 -2
  128. package/scripts/review-roster.test.sh +9 -0
  129. package/scripts/visual-gate.mjs +64 -0
  130. package/templates/bootstrap/technical-spike.md +17 -0
  131. package/templates/contracts/seam-check.mjs +236 -0
@@ -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
+ });
@@ -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,158 @@
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
+
16
+ export const POLICY_PATH = ".forge/release.yaml";
17
+ export const DEFERRED_KEYS = ["plan.auto_if", "retention_days", "ci.forbid_per_issue_steps", "couplings[].refine", "ci.provider=command", "risk.weights"];
18
+
19
+ export const INIT_PROFILE = `schema: 1
20
+ branches: {default: main}
21
+ plan: {approval: wait}
22
+ lanes: {release: {pipeline: existing}}
23
+ merge: {approval: confirm}
24
+ `;
25
+
26
+ // 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.
27
+ const S = { t: "string" }, N = { t: "number" }, I = { t: "integer" }, B = { t: "boolean" }, ANY = { t: "any" };
28
+ const SN = { t: "string", n: true };
29
+ const list = (i = S) => ({ t: "array", i });
30
+ const obj = (p, extra = {}) => ({ t: "object", p, ...extra });
31
+ const en = (...e) => ({ t: "string", e });
32
+ const PIPELINE = obj({ workflow: S, trigger: en("push", "dispatch"), inputs: { t: "map", v: S }, wait: B });
33
+ export const POLICY_SCHEMA = obj({
34
+ schema: { t: "integer", e: [1] },
35
+ branches: obj({ default: S, integration: SN, train: S, release: S, hotfix: S }),
36
+ trust: obj({ actors: list(), require_verified_commits: B }),
37
+ state: obj({ ledger_prefix: S, lease_ttl_s: N, heartbeat_s: N }),
38
+ 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 }) },
39
+ couplings: list(obj({ paths: list(), affects: list() })),
40
+ contracts: list(obj({ producer: S, consumers: list(), paths: list(), additive_only: B })),
41
+ forces: list(obj({ paths: list(), pipeline: en("full", "service", "hotfix"), reason: S })),
42
+ classify: obj({ min_confidence: N, text_only_cap: N, triage_max_per_hour: N, exists_in_evidence: en("mechanical", "llm") }),
43
+ 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 })) }),
44
+ plan: obj({ approval: en("wait", "auto", "auto-if"), skip_labels: list(), require_design_gate: B, max_issues: N, stale_snapshot_s: N }),
45
+ 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() }) },
46
+ merge: obj({ approval: en("confirm", "with-plan", "auto"), method: en("merge-commit", "squash", "rebase"), trailers: list() }),
47
+ 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 }),
48
+ preflight: obj({ commands: list(), timeout_s: N, blocking: B }),
49
+ deploy: obj({ live_release_command: S, freeze_variable: S, concurrency_group: S, start_timeout_s: N, stage_timeout_s: ANY, recovery: ANY, pipelines: { t: "map", v: PIPELINE } }),
50
+ verify: obj({ slis: list(ANY), post_deploy_checks_file: S, close_requires: en("verified", "deployed") }),
51
+ rollback: obj({ triggers: list(), ladder: list(), refuse_across: list(), open_revert_pr: B }),
52
+ quarantine: obj({ days: N, max: N }),
53
+ controls: obj({ intake: ANY, conductor: ANY, exempt: ANY }),
54
+ });
55
+
56
+ const kind = (v) => (v === null ? "null" : Array.isArray(v) ? "array" : typeof v);
57
+ const typeOk = { string: (v) => typeof v === "string", number: (v) => typeof v === "number" && Number.isFinite(v), integer: Number.isInteger, boolean: (v) => typeof v === "boolean" };
58
+
59
+ function walk(node, v, at, out) {
60
+ if (v === null && node.n) return;
61
+ if (node.t === "any") return;
62
+ if (node.t === "object" || node.t === "map") {
63
+ if (kind(v) !== "object") return void out.push(`${at}: expected a mapping, got ${kind(v)}`);
64
+ for (const [k, x] of Object.entries(v)) {
65
+ const child = node.t === "map" ? node.v : node.p[k];
66
+ if (!child) out.push(`${at ? `${at}.` : ""}${k}: unknown key`);
67
+ else walk(child, x, `${at ? `${at}.` : ""}${k}`, out);
68
+ }
69
+ } else if (node.t === "array") {
70
+ if (!Array.isArray(v)) return void out.push(`${at}: expected a list, got ${kind(v)}`);
71
+ v.forEach((x, i) => walk(node.i, x, `${at}[${i}]`, out));
72
+ } else if (!typeOk[node.t]?.(v)) return void out.push(`${at}: expected ${node.t}, got ${kind(v)}`);
73
+ if (node.e && !node.e.includes(v)) out.push(`${at}: ${JSON.stringify(v)} is not one of ${node.e.join("|")}`);
74
+ }
75
+
76
+ const DEFERRED_AT = [
77
+ [(p) => p?.plan && "auto_if" in p.plan, "plan.auto_if"],
78
+ [(p) => p && "retention_days" in p, "retention_days"],
79
+ [(p) => p?.ci && "forbid_per_issue_steps" in p.ci, "ci.forbid_per_issue_steps"],
80
+ [(p) => Array.isArray(p?.couplings) && p.couplings.some((c) => c && typeof c === "object" && "refine" in c), "couplings[].refine"],
81
+ [(p) => p?.ci?.provider === "command", "ci.provider: command"],
82
+ [(p) => p?.risk && "weights" in p.risk, "risk.weights"],
83
+ ];
84
+
85
+ const DEFERRED_UNKNOWN = new Set(["plan.auto_if", "retention_days", "ci.forbid_per_issue_steps", "risk.weights"].map((k) => `${k}: unknown key`));
86
+
87
+ /** Lanes that can never run: unknown pipeline, `base: integration` without an integration branch, tier not in `ci.tiers`. */
88
+ function unreachable(p, out) {
89
+ const pipes = p.deploy?.pipelines && Object.keys(p.deploy.pipelines);
90
+ const tiers = p.ci?.tiers && Object.keys(p.ci.tiers);
91
+ for (const [name, l] of Object.entries(p.lanes ?? {})) {
92
+ if (!l || typeof l !== "object") continue;
93
+ 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`);
94
+ if (l.base === "integration" && !p.branches?.integration) out.push(`lanes.${name}: unreachable, base integration but branches.integration is not set`);
95
+ 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`);
96
+ }
97
+ const units = Object.keys(p.units ?? {});
98
+ const dangling = (ids, at) => (ids ?? []).filter((u) => !units.includes(u)).forEach((u) => out.push(`${at}: unit ${u} is not in units`));
99
+ (p.couplings ?? []).forEach((c, i) => dangling(c?.affects, `couplings[${i}].affects`));
100
+ (p.contracts ?? []).forEach((c, i) => { dangling(c?.producer ? [c.producer] : [], `contracts[${i}].producer`); dangling(c?.consumers, `contracts[${i}].consumers`); });
101
+ }
102
+
103
+ /** @returns {string[]} findings, empty when `policy` is valid. */
104
+ export function validatePolicy(policy) {
105
+ const out = [];
106
+ if (kind(policy) !== "object") return [`policy: expected a mapping, got ${kind(policy)}`];
107
+ for (const [test, name] of DEFERRED_AT) if (test(policy)) out.push(`${name}: deferred to a later phase, not accepted yet`);
108
+ const rest = [];
109
+ walk(POLICY_SCHEMA, policy, "", rest);
110
+ out.push(...rest.filter((l) => !DEFERRED_UNKNOWN.has(l)));
111
+ if (policy.schema !== 1) out.push("schema: required and must be 1");
112
+ if (!out.length) unreachable(policy, out);
113
+ return out;
114
+ }
115
+
116
+ /** @returns {{policy}|{error}} js-yaml with JSON_SCHEMA; duplicate keys throw. */
117
+ export function parsePolicy(text) {
118
+ try { return { policy: load(String(text), { schema: JSON_SCHEMA }) }; } catch (e) { return { error: String(e?.message ?? e).split("\n")[0] }; }
119
+ }
120
+
121
+ /**
122
+ * 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.
123
+ * Only `io.git(["show", "origin/<default>:.forge/release.yaml"])` is read: a head-modified worktree copy has no effect (I13).
124
+ */
125
+ export function readPolicy({ io, defaultBranch, cwd = process.cwd(), ref }) {
126
+ const spec = `${ref ?? `origin/${defaultBranch}`}:${POLICY_PATH}`;
127
+ let text = null;
128
+ try { text = String(io.git(["show", spec])); } catch { text = null; }
129
+ if (text === null) {
130
+ let raw = ""; try { raw = readFileSync(join(cwd, "forge.yaml"), "utf8"); } catch { /* none */ }
131
+ return { source: "forge.yaml", policy: null, flat: readReleaseConfig(raw), findings: [] };
132
+ }
133
+ const { policy, error } = parsePolicy(text);
134
+ const findings = error ? [`parse: ${error}`] : validatePolicy(policy);
135
+ return { source: "file", policy: findings.length ? null : policy, findings, sha: createHash("sha256").update(text).digest("hex") };
136
+ }
137
+
138
+ const flagOf = (argv, f) => { const i = argv.indexOf(f); return i >= 0 ? argv[i + 1] : null; };
139
+
140
+ /** `forgedock release check-config [--ref <git ref>]`: exit 0 valid (or file absent: flat keys), 1 on any finding. */
141
+ export function checkConfigFromCli(argv, { io, cwd = process.cwd() }) {
142
+ const defaultBranch = readBranches(cwd).default || "main";
143
+ const r = readPolicy({ io, defaultBranch, cwd, ref: flagOf(argv, "--ref") });
144
+ if (r.source === "forge.yaml") { io.print(`release check-config: no ${POLICY_PATH} on origin/${defaultBranch}; using forge.yaml release.* keys`); return 0; }
145
+ r.findings.forEach((f) => io.print(`release check-config: ${f}`));
146
+ io.print(r.findings.length ? `release check-config: FAILED (${r.findings.length})` : `release check-config: ok (sha256 ${r.sha.slice(0, 12)})`);
147
+ return r.findings.length ? 1 : 0;
148
+ }
149
+
150
+ /** `forgedock release init`: writes the zero-config profile (7.4) to `.forge/release.yaml` and nothing else; never overwrites. */
151
+ export function initFromCli(_argv, { io, cwd = process.cwd() }) {
152
+ const file = join(cwd, POLICY_PATH);
153
+ if (existsSync(file)) { io.print(`release init: ${POLICY_PATH} exists; not overwriting`); return 1; }
154
+ mkdirSync(dirname(file), { recursive: true });
155
+ writeFileSync(file, INIT_PROFILE);
156
+ io.print(`release init: wrote ${POLICY_PATH}`);
157
+ return 0;
158
+ }
@@ -0,0 +1,109 @@
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
+ });
@@ -0,0 +1,148 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * One audited control verb set (#5556, epic #5549 Phase 0, invariants I15/I20/I24/I26): `forgedock release control <verb>`
5
+ * (hold, resume, cancel, lane, exempt, freeze, unfreeze); `forgedock release <verb>` is an alias of the same `runControl`.
6
+ * Every mutation needs `--reason`, is one key-scoped `updateActive` commit (state in `_active.json`, one `controls.jsonl`
7
+ * line {at, actor, host, verb, reason, before, after, epoch}) and posts a `FORGE:CONTROL` comment on the tracker (the lease's
8
+ * issue). `holdCheck` is read by `fenced()` before every irreversible action, so every driver obeys a hold (I24).
9
+ * `buildDispatchArgs` is the only workflow-dispatch builder: it never carries a human break-glass input (I26).
10
+ */
11
+ import { hostname } from "node:os";
12
+ import { readActive, readLedger, updateActive } from "./release-ledger.mjs";
13
+ import { UNSKIPPABLE_CLASSES, isUnskippable, parseFlakeConfig, canQuarantine } from "./release-flakes.mjs";
14
+
15
+ export const CONTROL_SCHEMA = "forgedock.release.control/v1";
16
+ export const CONTROL_MARKER = "FORGE:CONTROL";
17
+ export const VERBS = ["hold", "resume", "cancel", "lane", "exempt", "freeze", "unfreeze"];
18
+ export { UNSKIPPABLE_CLASSES as UNSKIPPABLE };
19
+ export const EXEMPT_MAX_H = { skip: 24, quarantine: 14 * 24 };
20
+ export const LANES = ["train", "release", "p0", "exclude"];
21
+ const OWNED = ["holds", "cancelled", "lanes", "exemptions", "freeze"];
22
+ const BREAK_GLASS = /^(override_freeze|acknowledge_hotfix_revert|override_.*|acknowledge_.*)$/;
23
+
24
+ /** Argv of `gh workflow run`; rejects a break-glass input (I26). */
25
+ export function buildDispatchArgs({ workflow, repo, ref, inputs = {} }) {
26
+ for (const k of Object.keys(inputs)) if (BREAK_GLASS.test(k)) throw new Error(`dispatch input ${k} is a human break-glass input; the engine never sets it (I26)`);
27
+ return ["workflow", "run", workflow, "--repo", repo, "--ref", ref, ...Object.entries(inputs).flatMap(([k, v]) => ["-f", `${k}=${v}`])];
28
+ }
29
+
30
+ /** The release-PR-body section listing live exemptions (I20: a demoted check appears in the PR body); "" when none. */
31
+ export function exemptionsSection(exemptions, now = Date.now()) {
32
+ const live = Object.entries(exemptions ?? {}).filter(([, e]) => e?.until && Date.parse(e.until) > now);
33
+ if (!live.length) return "";
34
+ return `\n\n<!-- FORGE:EXEMPT -->\n### Exempted checks\n${live.map(([c, e]) => `- \`${c}\` (${e.mode}) until ${e.until}, issue #${e.issue}, by ${e.actor}: ${e.reason}`).join("\n")}\n`;
35
+ }
36
+
37
+ /** Why release `id` must not act (held or cancelled), else null. Throws when `_active` cannot be read (callers refuse, I5). */
38
+ export async function holdCheck(lctx, id) {
39
+ const a = await readActive(lctx);
40
+ const h = a.holds?.[id] ?? a.holds?.["*"];
41
+ if (h) return `held (${h.reason ?? "no reason"})`;
42
+ if (a.cancelled?.[id]) return `cancelled (${a.cancelled[id].reason ?? "no reason"})`;
43
+ return null;
44
+ }
45
+
46
+ const flagOf = (argv, f) => { const i = argv.indexOf(f); return i >= 0 ? argv[i + 1] : null; };
47
+ const FLAGS = ["--repo", "--reason", "--mode", "--issue", "--until", "--force"];
48
+ const positionals = (argv) => argv.filter((a, i) => !a.startsWith("--") && !FLAGS.includes(argv[i - 1]));
49
+ const ttlHours = (s) => { const m = /^(\d+)([hd])$/.exec(String(s ?? "")); return m ? Number(m[1]) * (m[2] === "d" ? 24 : 1) : null; };
50
+
51
+ /**
52
+ * Run one control verb. `argv` is what follows the verb. `ctx`: {io, repo, policy, actor, host, now}.
53
+ * @returns {{schema, ok: boolean, verb, error?, ...}}; never throws for a refusal.
54
+ */
55
+ export async function runControl(verb, argv, ctx) {
56
+ const { io, repo, policy = null } = ctx;
57
+ const fail = (error) => ({ schema: CONTROL_SCHEMA, ok: false, verb, error });
58
+ if (!VERBS.includes(verb)) return fail(`unknown control verb ${verb}; one of ${VERBS.join("|")}`);
59
+ const reason = flagOf(argv, "--reason");
60
+ if (!reason || !reason.trim() || reason.startsWith("--")) return fail(`${verb}: --reason is required`);
61
+ const actor = ctx.actor ?? process.env.GITHUB_ACTOR ?? process.env.USER ?? "unknown", host = ctx.host ?? hostname();
62
+ const pos = positionals(argv);
63
+ const lctx = { io, repo, credential: "driver" };
64
+ const at = new Date(ctx.now ?? Date.now()).toISOString();
65
+ let apply; // (active) => {patch, before, after} | {refuse}
66
+ let after = null;
67
+ if (verb === "hold" || verb === "resume" || verb === "cancel") {
68
+ const id = pos[0];
69
+ if (!id) return fail(`${verb}: release id required`);
70
+ if (verb === "cancel") {
71
+ const led = await readLedger(lctx, id).catch(() => null);
72
+ const s = led?.state;
73
+ if (!s) return fail(`cancel: no ledger for release ${id}`);
74
+ if (s.steps?.promotion?.result?.merged || s.steps?.["post-merge"]?.done || s.status === "MERGED") return fail(`cancel: release ${id} is already MERGED; the only exits are LIVE or rollback`);
75
+ }
76
+ const key = verb === "cancel" ? "cancelled" : "holds";
77
+ apply = (a) => {
78
+ const before = a[key]?.[id] ?? null, next = { ...(a[key] ?? {}) };
79
+ if (verb === "resume") delete next[id]; else next[id] = { reason, actor, at };
80
+ return { patch: { [key]: next }, before, after: next[id] ?? null };
81
+ };
82
+ } else if (verb === "lane") {
83
+ const force = flagOf(argv, "--force");
84
+ if (!LANES.includes(force)) return fail(`lane: --force must be one of ${LANES.join("|")}`);
85
+ const issues = pos.map((p) => p.replace(/^#/, "")).filter((p) => /^\d+$/.test(p));
86
+ if (!issues.length) return fail("lane: at least one #issue required");
87
+ apply = (a) => {
88
+ const next = { ...(a.lanes ?? {}) }, before = {};
89
+ for (const n of issues) { before[n] = next[n] ?? null; next[n] = { force, reason, actor, at }; }
90
+ return { patch: { lanes: next }, before, after: Object.fromEntries(issues.map((n) => [n, force])) };
91
+ };
92
+ } else if (verb === "exempt") {
93
+ const check = pos[0], mode = flagOf(argv, "--mode"), issue = flagOf(argv, "--issue"), hours = ttlHours(flagOf(argv, "--until"));
94
+ if (!check) return fail("exempt: check or test name required");
95
+ if (!(mode in EXEMPT_MAX_H)) return fail("exempt: --mode must be skip or quarantine");
96
+ if (!/^#?\d+$/.test(issue ?? "")) return fail("exempt: --issue N is required");
97
+ if (hours == null) return fail("exempt: --until <Nh|Nd> is required");
98
+ if (hours > EXEMPT_MAX_H[mode]) return fail(`exempt: ${mode} expires in at most ${EXEMPT_MAX_H[mode]}h (got ${hours}h)`);
99
+ const cfg = parseFlakeConfig(policy);
100
+ if (isUnskippable(check, cfg.unskippable)) return fail(`exempt: ${check} is an unskippable class (${cfg.unskippable.join(", ")}) (I20)`);
101
+ const trusted = policy?.trust?.actors ?? [];
102
+ if (trusted.length && !trusted.includes(actor)) return fail(`exempt: actor ${actor} is not trusted (policy trust.actors)`);
103
+ const num = String(issue).replace("#", "");
104
+ let iv = null;
105
+ try { iv = JSON.parse(String(await io.gh(["issue", "view", num, "--repo", repo, "--json", "number,state,labels"]))); } catch { /* unreadable: refused below */ }
106
+ if (!iv || String(iv.number) !== num) return fail(`exempt: issue #${num} does not exist or is unreadable`);
107
+ const nowMs = ctx.now ?? Date.now(), labels = (iv.labels ?? []).map((l) => l.name ?? l);
108
+ const entry = { mode, issue: num, reason, actor, at, until: new Date(nowMs + hours * 3_600_000).toISOString() };
109
+ apply = (a) => {
110
+ if (mode === "quarantine") {
111
+ const q = canQuarantine({ target: check, exemptions: a.exemptions, issueLabels: labels, issueOpen: String(iv.state).toUpperCase() === "OPEN", cfg, now: nowMs });
112
+ if (!q.ok) return { refuse: `exempt: ${q.why}` };
113
+ }
114
+ return { patch: { exemptions: { ...(a.exemptions ?? {}), [check]: entry } }, before: a.exemptions?.[check] ?? null, after: entry };
115
+ };
116
+ } else { // freeze | unfreeze: the repo's own deploy variable (6.4), not a second mechanism
117
+ const name = policy?.deploy?.freeze_variable;
118
+ if (!name) return fail(`${verb}: policy deploy.freeze_variable is not set`);
119
+ apply = (a) => ({ patch: { freeze: verb === "freeze" ? { variable: name, reason, actor, at } : null }, before: a.freeze ?? null, after: verb === "freeze" ? { variable: name } : null });
120
+ ctx.afterCommit = async () => { await io.gh(verb === "freeze" ? ["variable", "set", name, "--repo", repo, "--body", "1"] : ["variable", "delete", name, "--repo", repo]); };
121
+ }
122
+ let line;
123
+ const r = await updateActive(lctx, OWNED, (a) => {
124
+ const o = apply(a);
125
+ if (o.refuse) return { refuse: o.refuse };
126
+ after = o.after;
127
+ line = { at, actor, host, verb, reason, before: o.before ?? null, after: o.after ?? null, epoch: a.epoch ?? null };
128
+ return { patch: o.patch, control: line };
129
+ });
130
+ if (!r.ok) return fail(r.refused ?? `could not commit the control (lost the race after ${r.attempts} attempts)`);
131
+ if (ctx.afterCommit) await ctx.afterCommit();
132
+ const issue = r.active.lease?.issue;
133
+ let comment = null;
134
+ if (issue) {
135
+ const body = `<!-- ${CONTROL_MARKER} -->\n**${verb}** by ${actor}@${host} at ${at} (epoch ${line.epoch ?? "none"})\nreason: ${reason}\n\n<!-- ${CONTROL_MARKER} ${JSON.stringify(line)} -->`;
136
+ comment = (await io.api("POST", `repos/${repo}/issues/${issue}/comments`, { body }))?.id ?? null;
137
+ }
138
+ return { schema: CONTROL_SCHEMA, ok: true, verb, entry: line, comment };
139
+ }
140
+
141
+ /** CLI: `[--repo R] [--json]` plus the verb's flags; prints one line or the JSON result; @returns the exit code. */
142
+ export async function controlFromCli(verb, argv, { io, policy, actor, host }) {
143
+ const repo = flagOf(argv, "--repo") ?? JSON.parse(String(await io.gh(["repo", "view", "--json", "nameWithOwner"]))).nameWithOwner;
144
+ const r = await runControl(verb, argv.filter((a) => a !== "--json"), { io, repo, policy, actor, host, now: io.now?.() });
145
+ if (argv.includes("--json")) io.print(JSON.stringify(r));
146
+ else io.print(r.ok ? `release ${verb}: recorded (${r.entry.at})` : `release ${verb}: refused: ${r.error}`);
147
+ return r.ok ? 0 : 1;
148
+ }