forgedock 1.53.0 → 1.54.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 (185) hide show
  1. package/.claude-plugin/marketplace.json +51 -0
  2. package/README.md +8 -2
  3. package/bin/auth/app-manifest.mjs +89 -0
  4. package/bin/auth/app-manifest.test.mjs +75 -0
  5. package/bin/auth/app-token.mjs +256 -0
  6. package/bin/auth/app-token.test.mjs +232 -0
  7. package/bin/brand.mjs +7 -0
  8. package/bin/config-history.mjs +151 -0
  9. package/bin/config-schema.mjs +115 -0
  10. package/bin/demo.mjs +65 -11
  11. package/bin/engine/outcome-codes.mjs +6 -3
  12. package/bin/engine/telemetry-seam.mjs +8 -2
  13. package/bin/engine/telemetry-seam.test.mjs +17 -0
  14. package/bin/engine-cli.mjs +57 -20
  15. package/bin/first-run.mjs +122 -0
  16. package/bin/forgedock.mjs +128 -146
  17. package/bin/help-text.mjs +144 -0
  18. package/bin/hooks/pre-tool-use.mjs +7 -0
  19. package/bin/journey.mjs +82 -83
  20. package/bin/lean/acceptance.mjs +313 -0
  21. package/bin/lean/acceptance.test.mjs +215 -0
  22. package/bin/lean/activation.mjs +18 -0
  23. package/bin/lean/activation.test.mjs +23 -1
  24. package/bin/lean/batch-health.mjs +74 -1
  25. package/bin/lean/batch-health.test.mjs +54 -1
  26. package/bin/lean/batch.test.mjs +11 -9
  27. package/bin/lean/branchlock.mjs +54 -0
  28. package/bin/lean/branchlock.test.mjs +49 -0
  29. package/bin/lean/ceiling.mjs +72 -0
  30. package/bin/lean/ceiling.test.mjs +54 -0
  31. package/bin/lean/ci-budget.mjs +366 -0
  32. package/bin/lean/ci-budget.test.mjs +167 -0
  33. package/bin/lean/conformance.e2e.test.mjs +7 -0
  34. package/bin/lean/conformance.mjs +77 -19
  35. package/bin/lean/conformance.test.mjs +129 -3
  36. package/bin/lean/context.mjs +35 -6
  37. package/bin/lean/context.test.mjs +27 -1
  38. package/bin/lean/depcache.mjs +25 -1
  39. package/bin/lean/depcache.test.mjs +26 -0
  40. package/bin/lean/e2e.mjs +18 -2
  41. package/bin/lean/e2e.test.mjs +26 -1
  42. package/bin/lean/effects.mjs +40 -11
  43. package/bin/lean/execution.test.mjs +24 -0
  44. package/bin/lean/facts.mjs +3 -3
  45. package/bin/lean/facts.test.mjs +5 -0
  46. package/bin/lean/fixround.mjs +14 -0
  47. package/bin/lean/fixround.test.mjs +25 -2
  48. package/bin/lean/gh-assoc.test.mjs +2 -1
  49. package/bin/lean/integration.mjs +100 -9
  50. package/bin/lean/integration.test.mjs +98 -0
  51. package/bin/lean/issuewatch-parity.mjs +64 -0
  52. package/bin/lean/issuewatch-parity.test.mjs +127 -0
  53. package/bin/lean/issuewatch-release.test.mjs +1 -1
  54. package/bin/lean/issuewatch.mjs +34 -5
  55. package/bin/lean/issuewatch.test.mjs +3 -2
  56. package/bin/lean/lean.mjs +316 -74
  57. package/bin/lean/lean.test.mjs +397 -24
  58. package/bin/lean/mechfix.mjs +124 -0
  59. package/bin/lean/mechfix.test.mjs +75 -0
  60. package/bin/lean/orchestrate.mjs +20 -2
  61. package/bin/lean/phaseledger.mjs +47 -5
  62. package/bin/lean/phaseledger.test.mjs +30 -1
  63. package/bin/lean/precheck.mjs +23 -4
  64. package/bin/lean/precheck.test.mjs +14 -1
  65. package/bin/lean/prereq.mjs +28 -0
  66. package/bin/lean/prereq.test.mjs +20 -0
  67. package/bin/lean/probe.mjs +4 -2
  68. package/bin/lean/prodparity.mjs +52 -0
  69. package/bin/lean/prodparity.test.mjs +67 -0
  70. package/bin/lean/prompts.mjs +69 -12
  71. package/bin/lean/recovery.test.mjs +1 -1
  72. package/bin/lean/release-io.test.mjs +42 -0
  73. package/bin/lean/release-postmerge.mjs +6 -0
  74. package/bin/lean/release-preflight.mjs +58 -0
  75. package/bin/lean/release-preflight.test.mjs +114 -0
  76. package/bin/lean/release-rehearsal.mjs +8 -7
  77. package/bin/lean/release-review.mjs +67 -11
  78. package/bin/lean/release-review.test.mjs +128 -1
  79. package/bin/lean/release-snapshot.mjs +188 -0
  80. package/bin/lean/release-snapshot.test.mjs +190 -0
  81. package/bin/lean/release.mjs +80 -12
  82. package/bin/lean/release.test.mjs +95 -0
  83. package/bin/lean/render.mjs +1 -1
  84. package/bin/lean/replan.mjs +184 -0
  85. package/bin/lean/replan.test.mjs +110 -0
  86. package/bin/lean/resume.mjs +9 -7
  87. package/bin/lean/resume.test.mjs +16 -0
  88. package/bin/lean/schedd.mjs +34 -1
  89. package/bin/lean/schedd.test.mjs +21 -1
  90. package/bin/lean/selfreview.mjs +94 -0
  91. package/bin/lean/selfreview.test.mjs +58 -1
  92. package/bin/lean/selftest-gate.mjs +22 -0
  93. package/bin/lean/selftest-gate.test.mjs +18 -1
  94. package/bin/lean/selftest-journey.mjs +234 -0
  95. package/bin/lean/selftest-journey.test.mjs +130 -0
  96. package/bin/lean/selftest-live.mjs +2 -1
  97. package/bin/lean/seqlease.mjs +35 -1
  98. package/bin/lean/seqlease.test.mjs +15 -0
  99. package/bin/lean/seqreserve.e2e.test.mjs +135 -0
  100. package/bin/lean/seqreserve.mjs +73 -0
  101. package/bin/lean/seqreserve.test.mjs +134 -0
  102. package/bin/lean/sequence.mjs +35 -6
  103. package/bin/lean/seqversioned.mjs +147 -0
  104. package/bin/lean/stagestamp.mjs +28 -0
  105. package/bin/lean/stagestamp.test.mjs +32 -0
  106. package/bin/lean/surfaces.mjs +75 -0
  107. package/bin/lean/surfaces.test.mjs +59 -0
  108. package/bin/lean/toolplace.mjs +28 -0
  109. package/bin/lean/toolplace.test.mjs +24 -0
  110. package/bin/lean/toolstats.mjs +3 -1
  111. package/bin/lean/toolstats.test.mjs +11 -0
  112. package/bin/lean/validatebest.mjs +28 -0
  113. package/bin/lean/validatebest.test.mjs +27 -0
  114. package/bin/pool/agent.mjs +9 -0
  115. package/bin/pool/docker.mjs +5 -0
  116. package/bin/pool/router.mjs +8 -4
  117. package/bin/prereqs.mjs +111 -0
  118. package/bin/replay-timelapse.mjs +149 -0
  119. package/bin/review-staging.mjs +100 -16
  120. package/bin/review-staging.test.mjs +18 -0
  121. package/bin/runner.mjs +43 -6
  122. package/bin/splash-install.mjs +157 -0
  123. package/bin/stats/aggregate.mjs +8 -1
  124. package/bin/stats/conformance-outcomes.mjs +100 -19
  125. package/bin/stats/conformance-outcomes.test.mjs +87 -1
  126. package/bin/stats/depth.mjs +88 -31
  127. package/bin/stats/depth.test.mjs +63 -38
  128. package/bin/stats/efficiency.mjs +26 -5
  129. package/bin/stats/efficiency.test.mjs +45 -1
  130. package/bin/stats/first-review.mjs +77 -0
  131. package/bin/stats/first-review.test.mjs +36 -0
  132. package/bin/stats/firstmerge.mjs +40 -0
  133. package/bin/stats/firstmerge.test.mjs +41 -0
  134. package/bin/stats/github-source.mjs +51 -13
  135. package/bin/stats/index.mjs +91 -15
  136. package/bin/stats/local-source.mjs +1 -0
  137. package/bin/stats/origin.mjs +80 -0
  138. package/bin/stats/origin.test.mjs +58 -0
  139. package/bin/stats/render.mjs +3 -1
  140. package/bin/stats/scoreboard.mjs +137 -0
  141. package/bin/stats/scoreboard.test.mjs +87 -0
  142. package/bin/stats/stats.test.mjs +80 -0
  143. package/bin/tui.mjs +3 -2
  144. package/commands/bootstrap.md +15 -14
  145. package/commands/deploy-pr.md +18 -3
  146. package/commands/forge-stats.md +1 -1
  147. package/commands/forgedock-ci-setup.md +28 -0
  148. package/commands/forgedock-init.md +4 -5
  149. package/commands/issue.md +2 -0
  150. package/commands/milestone.md +9 -1
  151. package/commands/replay.md +2 -0
  152. package/commands/review-pr-staging.md +4 -1
  153. package/commands/work-on/close.md +8 -0
  154. package/docs/CONFIG.md +105 -10
  155. package/docs/ISSUE-WATCH.md +23 -0
  156. package/docs/OUTCOME-CODES.md +1 -0
  157. package/docs/REPLAY.md +9 -0
  158. package/docs/SELFTEST.md +11 -0
  159. package/docs/STATS.md +19 -2
  160. package/docs/eval/README.md +6 -0
  161. package/docs/eval/adversarial-bench.md +68 -0
  162. package/docs/eval/corpus/adversarial-v1.json +285 -0
  163. package/docs/eval/feature-bench.md +42 -0
  164. package/docs/eval/feature-specs/crud-auth/journeys/notes-crud-isolated.mjs +21 -0
  165. package/docs/eval/feature-specs/crud-auth/journeys/register-login.mjs +12 -0
  166. package/docs/eval/feature-specs/crud-auth/spec.md +15 -0
  167. package/docs/site/start-a-new-project.md +2 -1
  168. package/package.json +5 -2
  169. package/plugins/forgedock-splash/.claude-plugin/plugin.json +10 -0
  170. package/plugins/forgedock-splash/README.md +27 -0
  171. package/plugins/forgedock-splash/hooks/hooks.json +1 -0
  172. package/plugins/forgedock-splash/hooks/register.tsx +74 -0
  173. package/plugins/forgedock-splash/hooks/scene.ts +222 -0
  174. package/plugins/forgedock-splash/types/index.d.ts +10 -0
  175. package/scripts/bench-adversarial.mjs +216 -0
  176. package/scripts/bench-feature.mjs +170 -0
  177. package/scripts/bench-lightlane.mjs +2 -2
  178. package/scripts/bootstrap-create.mjs +2 -2
  179. package/scripts/bootstrap-validate.mjs +35 -2
  180. package/scripts/check-spec-size.sh +4 -3
  181. package/scripts/check-spec-size.test.sh +3 -0
  182. package/scripts/plan-validate-live.mjs +40 -6
  183. package/scripts/review-pr-staging-scope.test.sh +1 -1
  184. package/scripts/review-staging-post.sh +23 -0
  185. package/scripts/review-staging-post.test.sh +8 -0
@@ -0,0 +1,72 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Context-ceiling helpers (#5346): the per-size ceiling, the pre-build restart prediction and the restart hand-off facts.
5
+ * Pure: no I/O. The ceiling itself (#4390) is applied in lean.mjs `builder()`; the mid-edit deferral lives in runner.mjs.
6
+ */
7
+
8
+ import { SIZES } from "./budget.mjs";
9
+
10
+ /** A session that starts above this share of the ceiling restarts whatever the builder does. */
11
+ export const PREDICT_SHARE = 0.6;
12
+ /** Rough bytes per token for source and prose. */
13
+ export const BYTES_PER_TOKEN = 4;
14
+ export const HANDOFF_FILES_MAX = 30;
15
+ const EDIT_TOOLS = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit"]);
16
+
17
+ /** `engine.context_ceiling_by_size`: "S=80000,M=120000,L=160000" or `{S, M, L}`; a null when absent or without a valid entry. 0 = no ceiling for that size. */
18
+ export function parseCeilingBySize(engine) {
19
+ const raw = engine?.context_ceiling_by_size ?? engine?.contextCeilingBySize;
20
+ if (raw == null || raw === "") return null;
21
+ const out = {};
22
+ const put = (k, v) => { const key = String(k).trim().toUpperCase(); if (SIZES.includes(key) && /^\d+$/.test(String(v).trim())) out[key] = Number(String(v).trim()); };
23
+ if (typeof raw === "object" && !Array.isArray(raw)) for (const [k, v] of Object.entries(raw)) put(k, v);
24
+ else for (const part of String(raw).split(/[,;]/)) { const [k, v] = part.split(/[=:]/); if (v !== undefined) put(k, v); }
25
+ return Object.keys(out).length ? out : null;
26
+ }
27
+
28
+ /** The ceiling for a lane of `size`: its per-size entry, else the global one. */
29
+ export function ceilingFor(size, { tokens = 0, bySize = null } = {}) {
30
+ const v = bySize && SIZES.includes(size) ? bySize[size] : undefined;
31
+ return Number.isFinite(v) && v >= 0 ? v : tokens;
32
+ }
33
+
34
+ /**
35
+ * Whether a build session is predicted to restart. `promptBytes` is the build prompt, `fileBytes` the named files' size.
36
+ * `certain`: the named files alone exceed the ceiling, so any session that reads them restarts.
37
+ * `predicted`: the start (prompt + files) is at or above PREDICT_SHARE of the ceiling.
38
+ */
39
+ export function predictRestart({ ceiling = 0, promptBytes = 0, fileBytes = 0 } = {}) {
40
+ const files = Math.ceil(Math.max(0, fileBytes) / BYTES_PER_TOKEN);
41
+ const estimate = Math.ceil(Math.max(0, promptBytes) / BYTES_PER_TOKEN) + files;
42
+ if (!(ceiling > 0)) return { predicted: false, certain: false, estimate, ceiling };
43
+ const certain = files > ceiling;
44
+ return { predicted: certain || estimate >= ceiling * PREDICT_SHARE, certain, estimate, ceiling };
45
+ }
46
+
47
+ /** The tool uses' first edit: the 1-based turn (distinct assistant message) of the first Edit/Write, null when none. */
48
+ export function firstEditTurn(toolUses) {
49
+ const msgs = new Map();
50
+ for (const u of Array.isArray(toolUses) ? toolUses : []) {
51
+ if (!u || typeof u !== "object") continue;
52
+ const k = u.msg ?? `#${msgs.size}`;
53
+ if (!msgs.has(k)) msgs.set(k, msgs.size + 1);
54
+ if (EDIT_TOOLS.has(u.name)) return msgs.get(k);
55
+ }
56
+ return null;
57
+ }
58
+
59
+ /** What the stopped session had established: files read, files edited (deduped, capped) and the last tool call. */
60
+ export function handoffFacts(toolUses, lastTool = null) {
61
+ const read = new Set(), edited = new Set();
62
+ for (const u of Array.isArray(toolUses) ? toolUses : []) {
63
+ if (!u || typeof u.path !== "string" || !u.path) continue;
64
+ if (EDIT_TOOLS.has(u.name)) edited.add(u.path); else if (u.name === "Read") read.add(u.path);
65
+ }
66
+ const readOnly = [...read].filter((p) => !edited.has(p));
67
+ return { read: readOnly.slice(0, HANDOFF_FILES_MAX), edited: [...edited].slice(0, HANDOFF_FILES_MAX), readMore: Math.max(0, readOnly.length - HANDOFF_FILES_MAX),
68
+ last: lastTool && typeof lastTool.name === "string" ? { name: lastTool.name, input: String(lastTool.input ?? "").slice(0, 200) } : null };
69
+ }
70
+
71
+ /** Appended to the build prompt of a lane predicted to restart: read the named files, do not survey. */
72
+ export const NARROW_NOTE = "\n\nContext is tight on this lane (the contract's files and this prompt already fill much of the session window): read only the files the contract names and the code you edit, skip surveys of unrelated code, and make each edit as soon as you know it.";
@@ -0,0 +1,54 @@
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 { parseCeilingBySize, ceilingFor, predictRestart, handoffFacts, firstEditTurn, HANDOFF_FILES_MAX } from "./ceiling.mjs";
6
+ import { contextRestartPrompt } from "./prompts.mjs";
7
+ import { toolStats } from "./toolstats.mjs";
8
+
9
+ describe("context ceiling helpers (#5346)", () => {
10
+ it("parseCeilingBySize reads a string or object, ignores junk, null when empty", () => {
11
+ assert.deepEqual(parseCeilingBySize({ context_ceiling_by_size: "S=80000, m=120000;L:0" }), { S: 80000, M: 120000, L: 0 });
12
+ assert.deepEqual(parseCeilingBySize({ context_ceiling_by_size: { L: "160000", X: "5" } }), { L: 160000 });
13
+ assert.equal(parseCeilingBySize({ context_ceiling_by_size: "big" }), null);
14
+ assert.equal(parseCeilingBySize({}), null);
15
+ });
16
+ it("ceilingFor uses the size entry (0 included), else the global ceiling", () => {
17
+ assert.equal(ceilingFor("L", { tokens: 120000, bySize: { L: 160000 } }), 160000);
18
+ assert.equal(ceilingFor("L", { tokens: 120000, bySize: { L: 0 } }), 0);
19
+ assert.equal(ceilingFor("M", { tokens: 120000, bySize: { L: 160000 } }), 120000);
20
+ assert.equal(ceilingFor(null, { tokens: 120000, bySize: { L: 1 } }), 120000);
21
+ });
22
+ it("predictRestart: 60% of the ceiling predicts, named files over the ceiling are certain, off never predicts", () => {
23
+ assert.equal(predictRestart({ ceiling: 100000, promptBytes: 4000, fileBytes: 0 }).predicted, false);
24
+ const near = predictRestart({ ceiling: 100000, promptBytes: 4000, fileBytes: 4 * 59000 });
25
+ assert.deepEqual([near.predicted, near.certain, near.estimate], [true, false, 60000]);
26
+ assert.deepEqual([predictRestart({ ceiling: 100000, fileBytes: 4 * 100001 }).predicted, predictRestart({ ceiling: 100000, fileBytes: 4 * 100001 }).certain], [true, true]);
27
+ assert.equal(predictRestart({ ceiling: 0, fileBytes: 1e9 }).predicted, false);
28
+ });
29
+ it("handoffFacts dedupes, drops read files that were edited, caps the list and keeps the last tool", () => {
30
+ const uses = [{ name: "Read", path: "a" }, { name: "Read", path: "a" }, { name: "Read", path: "b" }, { name: "Edit", path: "b" }, { name: "Bash", cmd: "ls" },
31
+ ...Array.from({ length: 40 }, (_, i) => ({ name: "Read", path: `f${i}` }))];
32
+ const h = handoffFacts(uses, { name: "Edit", input: "x" });
33
+ assert.deepEqual(h.edited, ["b"]);
34
+ assert.equal(h.read.length, HANDOFF_FILES_MAX);
35
+ assert.equal(h.readMore, 11);
36
+ assert.deepEqual(h.last, { name: "Edit", input: "x" });
37
+ assert.deepEqual(handoffFacts(null, null), { read: [], edited: [], readMore: 0, last: null });
38
+ });
39
+ it("firstEditTurn counts distinct assistant messages; toolStats exposes it", () => {
40
+ const uses = [{ msg: "m1", name: "Read", path: "a" }, { msg: "m1", name: "Read", path: "b" }, { msg: "m2", name: "Bash" }, { msg: "m3", name: "Write", path: "c" }];
41
+ assert.equal(firstEditTurn(uses), 3);
42
+ assert.equal(firstEditTurn([{ msg: "m1", name: "Read" }]), null);
43
+ assert.equal(toolStats(uses).first_edit_turn, 3);
44
+ assert.equal("first_edit_turn" in toolStats([{ msg: "m1", name: "Read", path: "a" }]), false);
45
+ });
46
+ it("the restart prompt carries the established block only when there are facts, and keeps its other sections", () => {
47
+ const base = contextRestartPrompt({ stat: "1 file", diff: "d", base: "origin/x", check: "", ceiling: 5 });
48
+ assert.doesNotMatch(base, /<established>/);
49
+ const p = contextRestartPrompt({ stat: "1 file", diff: "d", base: "origin/x", check: "ok", ceiling: 5, established: handoffFacts([{ name: "Read", path: "src/a.js" }], { name: "Read", input: "i" }) });
50
+ assert.match(p, /<established>\nFiles it read[^\n]*\n- src\/a\.js\nIts last tool call: Read i/);
51
+ assert.match(p, /<diff_stat base="origin\/x">/);
52
+ assert.match(p, /Last validate result/);
53
+ });
54
+ });
@@ -0,0 +1,366 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Actions-minutes budget awareness and CI placement policy (#5278). No LLM anywhere.
5
+ * - Policy: forge.yaml `ci.mode` = remote | local-first | local-attested | auto (default). The one-level parser flattens the
6
+ * `ci` section, so the keys are flat: `mode`, `monthly_minutes`, `reserve_pct`, `included_minutes`, `plan`.
7
+ * - Detect: repo visibility, plan and month-to-date Actions usage across the owner (org or user) through the billing usage
8
+ * API, projected to month end. A public repo is free hosted minutes and is never auto-switched. A billing failure is
9
+ * fail-soft: stay `remote` and say the usage is unknown.
10
+ * - Effective mode is recomputed from GitHub each time (GitHub is the register); the only local files are rebuildable
11
+ * caches under `~/.forge/ci-budget/` (or FORGEDOCK_CI_BUDGET_DIR): the last effective mode, parity rows, seen repos.
12
+ * - `local-first` / `local-attested` coerce verify.mode ci|hybrid to local (no paid CI before review). `local-attested`
13
+ * posts the host check result as a `forgedock/ci-local` commit status: the trust trade-off is the same as a self-hosted runner.
14
+ * Every GitHub effect goes through the injected `gh` (argv -> stdout string).
15
+ */
16
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, appendFileSync } from "node:fs";
17
+ import { execFileSync } from "node:child_process";
18
+ import { createHash } from "node:crypto";
19
+ import { homedir } from "node:os";
20
+ import { join, resolve } from "node:path";
21
+ import { fileURLToPath } from "node:url";
22
+ import { parseForgeYaml } from "../forge-utils.mjs";
23
+
24
+ export const CI_MODES = Object.freeze(["remote", "local-first", "local-attested", "auto"]);
25
+ /** Included Actions minutes per month by plan (overridable: GitHub changes pricing). Public repos are free on standard runners. */
26
+ export const PLAN_MINUTES = Object.freeze({ free: 2000, pro: 3000, team: 3000, enterprise: 50000 });
27
+ /** Minutes consumed from the included pool per runner minute. */
28
+ export const OS_RATE = Object.freeze({ linux: 1, windows: 2, macos: 10 });
29
+ export const DEFAULT_RESERVE_PCT = 10;
30
+ export const ATTEST_CONTEXT = "forgedock/ci-local";
31
+ const CACHE_TTL_MS = 24 * 3600 * 1000;
32
+
33
+ const str = (v) => (v === undefined || v === null ? "" : String(v).trim());
34
+ const posInt = (v) => { const n = Number(v); return str(v) !== "" && Number.isInteger(n) && n > 0 ? n : null; };
35
+ const kmin = (n) => (n >= 10000 ? `${Math.round(n / 1000)}k` : n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(Math.round(n)));
36
+
37
+ /** forge.yaml `ci` section -> {mode, monthlyMinutes, reservePct, includedMinutes, plan}; junk keeps the defaults (auto, 10%). */
38
+ export function parseCiPolicy(sec) {
39
+ const s = sec && typeof sec === "object" ? sec : {};
40
+ const mode = CI_MODES.includes(str(s.mode)) ? str(s.mode) : "auto";
41
+ const r = Number(str(s.reserve_pct));
42
+ const plan = str(s.plan).toLowerCase();
43
+ return {
44
+ mode,
45
+ monthlyMinutes: posInt(s.monthly_minutes),
46
+ reservePct: str(s.reserve_pct) !== "" && Number.isFinite(r) && r >= 0 && r <= 90 ? r : DEFAULT_RESERVE_PCT,
47
+ includedMinutes: posInt(s.included_minutes),
48
+ plan: PLAN_MINUTES[plan] !== undefined ? plan : null,
49
+ };
50
+ }
51
+
52
+ /** The policy of the forge.yaml in `cwd` (defaults when absent or unreadable). */
53
+ export function readCiPolicy(cwd = process.cwd()) {
54
+ try { return parseCiPolicy(parseForgeYaml(readFileSync(join(cwd, "forge.yaml"), "utf8"))?.ci); } catch { return parseCiPolicy(null); }
55
+ }
56
+
57
+ const json = (s) => { try { return JSON.parse(String(s)); } catch { return null; } };
58
+ const ghJson = async (gh, args) => { try { return json(await gh(args)); } catch { return null; } };
59
+
60
+ /** Month-to-date Actions minutes (runner-rate weighted) from a billing usage payload: {total, byRepo, byOs}. */
61
+ export function sumUsage(payload) {
62
+ const items = Array.isArray(payload?.usageItems) ? payload.usageItems : [];
63
+ const out = { total: 0, byRepo: {}, byOs: {} };
64
+ for (const it of items) {
65
+ if (str(it?.product).toLowerCase() !== "actions" || !/minute/i.test(str(it?.unitType) || "minutes")) continue;
66
+ const q = Number(it.quantity);
67
+ if (!Number.isFinite(q) || q <= 0) continue;
68
+ const sku = str(it.sku).toLowerCase();
69
+ const os = /macos|mac_/.test(sku) ? "macos" : /windows/.test(sku) ? "windows" : "linux";
70
+ const pooled = q * OS_RATE[os];
71
+ out.total += pooled;
72
+ out.byOs[os] = (out.byOs[os] ?? 0) + q;
73
+ const repo = str(it.repositoryName) || "(unattributed)";
74
+ out.byRepo[repo] = (out.byRepo[repo] ?? 0) + pooled;
75
+ }
76
+ return out;
77
+ }
78
+
79
+ /** Linear projection of the month: burn per elapsed day x days in the month. */
80
+ export function project(mtd, now) {
81
+ const d = new Date(now), day = d.getUTCDate();
82
+ const days = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 0)).getUTCDate();
83
+ const burn = day > 0 ? mtd / day : 0;
84
+ return { burnPerDay: burn, projected: Math.round(burn * days), day, days };
85
+ }
86
+
87
+ /**
88
+ * Facts for the budget: visibility, plan, included minutes, month-to-date usage across the owner, projection.
89
+ * `usage` is null when the billing API is unreadable (token scope, plan): callers treat it as unknown.
90
+ */
91
+ export async function detectBudget({ gh, repo, policy = parseCiPolicy(null), now = Date.now() }) {
92
+ const meta = await ghJson(gh, ["api", `repos/${repo}`]);
93
+ const owner = str(meta?.owner?.login) || repo.split("/")[0];
94
+ const isOrg = str(meta?.owner?.type) === "Organization";
95
+ const isPublic = meta ? meta.private === false : false;
96
+ const d = new Date(now);
97
+ const usageRaw = await ghJson(gh, ["api", `${isOrg ? "orgs" : "users"}/${owner}/settings/billing/usage?year=${d.getUTCFullYear()}&month=${d.getUTCMonth() + 1}`]);
98
+ let plan = policy.plan;
99
+ if (!plan) {
100
+ const o = await ghJson(gh, ["api", isOrg ? `orgs/${owner}` : "user"]);
101
+ const name = str(o?.plan?.name).toLowerCase();
102
+ plan = PLAN_MINUTES[name] !== undefined ? name : /enterprise/.test(name) ? "enterprise" : null;
103
+ }
104
+ const included = policy.includedMinutes ?? (plan ? PLAN_MINUTES[plan] : null);
105
+ const budget = policy.monthlyMinutes ?? included;
106
+ const usage = usageRaw ? sumUsage(usageRaw) : null;
107
+ const proj = usage ? project(usage.total, now) : null;
108
+ return { repo, owner, isOrg, isPublic, plan, included, budget, usage, mtd: usage ? Math.round(usage.total) : null, projected: proj?.projected ?? null, burnPerDay: proj?.burnPerDay ?? null };
109
+ }
110
+
111
+ /**
112
+ * The effective mode. A public repo is free hosted minutes and never auto-switched. A configured non-auto mode is honoured.
113
+ * `auto`: `remote` while the projection stays under budget x (1 - reserve), else `local-first` (switched, with the reason);
114
+ * an unknown usage or budget stays `remote`.
115
+ * @returns {{configured, effective, switched, free, reason}}
116
+ */
117
+ export function resolveCiMode({ policy, facts }) {
118
+ const configured = policy.mode;
119
+ if (facts?.isPublic && configured === "auto") return { configured, effective: "remote", switched: false, free: true, reason: "public repo: free hosted minutes" };
120
+ if (configured !== "auto") return { configured, effective: configured, switched: false, free: !!facts?.isPublic, reason: "configured" };
121
+ if (!facts || facts.projected === null || facts.budget === null) return { configured, effective: "remote", switched: false, free: false, reason: "usage unknown (billing API unreadable): staying remote" };
122
+ const limit = Math.floor(facts.budget * (1 - policy.reservePct / 100));
123
+ if (facts.projected > limit) return { configured, effective: "local-first", switched: true, free: false, reason: `projected ${kmin(facts.projected)} > budget ${kmin(limit)} (${kmin(facts.budget)} less ${policy.reservePct}% reserve)` };
124
+ return { configured, effective: "remote", switched: false, free: false, reason: `projected ${kmin(facts.projected)} within budget ${kmin(limit)}` };
125
+ }
126
+
127
+ /** One budget line for the batch and release reports: `ci: auto -> local-first (...); month: 22k/50k, projected 41k`. */
128
+ export function formatBudgetLine({ res, facts, release = null }) {
129
+ const mode = res.switched ? `${res.configured} -> ${res.effective}` : res.configured === "auto" ? `auto (${res.effective})` : res.effective;
130
+ const parts = [];
131
+ if (release) parts.push(`this release: ${release.runs} CI run${release.runs === 1 ? "" : "s"}, ${Math.round(release.minutes)} min`);
132
+ parts.push(`ci: ${mode} (${res.reason})`);
133
+ if (res.free) parts.push("free hosted minutes");
134
+ else if (facts?.mtd !== null && facts?.mtd !== undefined) parts.push(`month: ${kmin(facts.mtd)}/${facts.budget === null ? "?" : kmin(facts.budget)}, projected ${kmin(facts.projected)}`);
135
+ if (res.switched) parts.push("SWITCHED to local-first: host checks run before paid CI");
136
+ return parts.join("; ");
137
+ }
138
+
139
+ /** A workflow run's duration in minutes (0 when its timestamps are missing or inverted). */
140
+ const runMinutes = (r) => { const ms = Date.parse(r.updated_at) - Date.parse(r.run_started_at ?? r.created_at); return ms > 0 ? ms / 60000 : 0; };
141
+
142
+ /** Actions runs since `sinceMs` on the repo: {runs, minutes} from run durations (best effort, null on failure). */
143
+ export async function releaseRuns({ gh, repo, sinceMs, branch = null }) {
144
+ const since = new Date(sinceMs).toISOString();
145
+ const q = `repos/${repo}/actions/runs?per_page=100&created=>=${since}${branch ? `&branch=${encodeURIComponent(branch)}` : ""}`;
146
+ const j = await ghJson(gh, ["api", q]);
147
+ if (!j || !Array.isArray(j.workflow_runs)) return null;
148
+ let minutes = 0;
149
+ for (const r of j.workflow_runs) minutes += runMinutes(r);
150
+ return { runs: j.workflow_runs.length, minutes };
151
+ }
152
+
153
+ // ---- caches (rebuildable) -------------------------------------------------------------------------------------------
154
+ export const cacheDir = (env = process.env) => env.FORGEDOCK_CI_BUDGET_DIR || join(homedir(), ".forge", "ci-budget");
155
+ const keyOf = (cwd) => createHash("sha1").update(resolve(cwd)).digest("hex").slice(0, 12);
156
+ const ensure = (dir) => { mkdirSync(dir, { recursive: true }); return dir; };
157
+
158
+ export function writeEffective({ cwd = process.cwd(), res, now = Date.now(), dir = cacheDir() }) {
159
+ try { writeFileSync(join(ensure(dir), `effective-${keyOf(cwd)}.json`), JSON.stringify({ at: now, effective: res.effective, configured: res.configured, switched: res.switched, reason: res.reason })); } catch { /* a cache */ }
160
+ }
161
+ /** The last effective mode the budget resolver cached for this checkout, or null when none or older than a day. */
162
+ export function readEffective({ cwd = process.cwd(), now = Date.now(), dir = cacheDir() } = {}) {
163
+ const j = json((() => { try { return readFileSync(join(dir, `effective-${keyOf(cwd)}.json`), "utf8"); } catch { return ""; } })());
164
+ return j && now - j.at < CACHE_TTL_MS ? j : null;
165
+ }
166
+
167
+ /** The mode engine seams act on, synchronously: a configured mode, or for `auto` the cached resolution (remote when none). */
168
+ export function effectiveModeSync({ cwd = process.cwd(), now = Date.now(), dir = cacheDir() } = {}) {
169
+ const policy = readCiPolicy(cwd);
170
+ if (policy.mode !== "auto") return policy.mode;
171
+ return readEffective({ cwd, now, dir })?.effective ?? "remote";
172
+ }
173
+
174
+ /** `local-first` and `local-attested` never push-and-wait for paid CI before review: verify.mode ci|hybrid becomes local. */
175
+ export function coerceVerify(verify, opts = {}) {
176
+ if (!verify || (verify.mode !== "ci" && verify.mode !== "hybrid")) return verify;
177
+ const m = effectiveModeSync(opts);
178
+ return m === "local-first" || m === "local-attested" ? { ...verify, mode: "local", ciModeCoerced: m } : verify;
179
+ }
180
+
181
+ // ---- parity (local green -> remote red) ------------------------------------------------------------------------------
182
+ export const parityFile = (dir = cacheDir()) => join(dir, "parity.jsonl");
183
+
184
+ /** Per-suite hit rate: of the suites that were local green and have a remote result, the share that went red remotely. */
185
+ export function hitRates(rows) {
186
+ const out = {};
187
+ for (const r of rows) for (const [suite, remote] of Object.entries(r.remote ?? {})) {
188
+ if (r.local?.[suite] !== "pass") continue;
189
+ const s = (out[suite] ??= { greenLocal: 0, redRemote: 0 });
190
+ s.greenLocal++; if (remote === "fail") s.redRemote++;
191
+ }
192
+ for (const s of Object.values(out)) s.rate = s.greenLocal ? s.redRemote / s.greenLocal : 0;
193
+ return out;
194
+ }
195
+
196
+ export const formatHitRates = (rates) => {
197
+ const e = Object.entries(rates);
198
+ return e.length ? `parity (local green -> remote red): ${e.map(([k, v]) => `${k} ${v.redRemote}/${v.greenLocal}`).join(", ")}` : "parity: no local/remote pairs yet";
199
+ };
200
+
201
+ /** Maps check-run names to pass/fail for a head sha (check-runs payload); neutral/skipped count as pass. */
202
+ export function remoteSuites(payload) {
203
+ const out = {};
204
+ for (const c of Array.isArray(payload?.check_runs) ? payload.check_runs : []) {
205
+ if (!c.conclusion) continue;
206
+ const bad = ["failure", "timed_out", "cancelled", "action_required"].includes(c.conclusion);
207
+ out[c.name] = bad ? "fail" : out[c.name] === "fail" ? "fail" : "pass";
208
+ }
209
+ return out;
210
+ }
211
+
212
+ /** Fills each local row's `remote` map from the head's check runs (rows whose head has no completed runs stay unpaired). */
213
+ export async function pairParity({ gh, repo, rows }) {
214
+ const out = [];
215
+ for (const r of rows) {
216
+ if (!r.head) continue;
217
+ const remote = remoteSuites(await ghJson(gh, ["api", `repos/${repo}/commits/${r.head}/check-runs?per_page=100`]));
218
+ out.push({ ...r, remote: Object.fromEntries(Object.entries(remote).filter(([k]) => k in (r.local ?? {}))) });
219
+ }
220
+ return out;
221
+ }
222
+
223
+ export function readParity(dir = cacheDir()) {
224
+ try { return readFileSync(parityFile(dir), "utf8").split("\n").filter(Boolean).map(json).filter(Boolean); } catch { return []; }
225
+ }
226
+
227
+ // ---- the host check hook ---------------------------------------------------------------------------------------------
228
+ /** The attested commit status body for a host result. */
229
+ export const attestPayload = ({ ok, suites }) => ({
230
+ state: ok ? "success" : "failure", context: ATTEST_CONTEXT,
231
+ description: `${ok ? "host checks passed" : "host checks failed"} (${suites.length} suite(s), attested by ForgeDock, not run by Actions)`.slice(0, 140),
232
+ });
233
+
234
+ /**
235
+ * Called after the pre-PR host check record is written: appends a parity row (head, per-suite pass/fail) and, in
236
+ * `local-attested`, posts the `forgedock/ci-local` commit status. Fail-soft: never throws.
237
+ */
238
+ export async function recordHostCheck({ cwd, head, ok, suites, gh = defaultGh, repo = null, dir = cacheDir(), mode = null, now = Date.now() }) {
239
+ try {
240
+ if (!head) return;
241
+ ensure(dir);
242
+ appendFileSync(parityFile(dir), `${JSON.stringify({ at: now, head, local: Object.fromEntries(suites.map((s) => [s.name, s.ok ? "pass" : "fail"])) })}\n`);
243
+ if ((mode ?? effectiveModeSync({ cwd, dir, now })) !== "local-attested") return;
244
+ const slug = repo ?? JSON.parse(String(await gh(["repo", "view", "--json", "nameWithOwner"]))).nameWithOwner;
245
+ const p = attestPayload({ ok, suites });
246
+ await gh(["api", `repos/${slug}/statuses/${head}`, "-f", `state=${p.state}`, "-f", `context=${p.context}`, "-f", `description=${p.description}`]);
247
+ } catch { /* a missing status never fails the check */ }
248
+ }
249
+
250
+ const defaultGh = (args) => execFileSync("gh", args, { encoding: "utf8", maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
251
+
252
+ // ---- alerts and digest -----------------------------------------------------------------------------------------------
253
+ /** Alerts: projected overage and repos burning minutes that were not seen in the previous digest (e.g. a repo flipped private). */
254
+ export function budgetAlerts({ facts, seen = null }) {
255
+ const out = [];
256
+ if (facts?.budget && facts.projected !== null && facts.projected > facts.budget) out.push(`ALERT projected overage: ${kmin(facts.projected)} > ${kmin(facts.budget)} included minutes`);
257
+ if (seen && facts?.usage) for (const [r, m] of Object.entries(facts.usage.byRepo)) if (!seen.includes(r) && m > 0) out.push(`ALERT new burn source: ${r} used ${kmin(m)} min this month (new or flipped private)`);
258
+ return out;
259
+ }
260
+
261
+ /** Monthly digest: per-repo minutes (billing items) and the per-OS split. */
262
+ export function formatDigest(facts) {
263
+ if (!facts?.usage) return "digest: usage unknown (billing API unreadable)";
264
+ const repos = Object.entries(facts.usage.byRepo).sort((a, b) => b[1] - a[1]);
265
+ const lines = [`digest ${facts.owner}: ${kmin(facts.mtd)} min month-to-date, projected ${kmin(facts.projected)}`];
266
+ for (const [r, m] of repos) lines.push(` ${r}: ${kmin(m)} min`);
267
+ const os = Object.entries(facts.usage.byOs).map(([k, v]) => `${k} ${kmin(v)} (x${OS_RATE[k]})`).join(", ");
268
+ if (os) lines.push(` by runner OS: ${os}`);
269
+ return lines.join("\n");
270
+ }
271
+
272
+ /** Per-workflow minutes of the month from run durations (best effort), `[ [name, minutes], ... ]` descending. */
273
+ export async function workflowDigest({ gh, repo, now = Date.now() }) {
274
+ const d = new Date(now), since = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), 1)).toISOString();
275
+ const j = await ghJson(gh, ["api", `repos/${repo}/actions/runs?per_page=100&created=>=${since}`]);
276
+ const by = {};
277
+ for (const r of Array.isArray(j?.workflow_runs) ? j.workflow_runs : []) by[r.name] = (by[r.name] ?? 0) + runMinutes(r);
278
+ return Object.entries(by).sort((a, b) => b[1] - a[1]);
279
+ }
280
+
281
+ const seenFile = (owner, dir) => join(dir, `seen-${owner.replace(/[^A-Za-z0-9_.-]/g, "_")}.json`);
282
+ export const readSeen = (owner, dir = cacheDir()) => { try { return json(readFileSync(seenFile(owner, dir), "utf8"))?.repos ?? null; } catch { return null; } };
283
+ export function writeSeen(owner, repos, dir = cacheDir()) { try { writeFileSync(seenFile(owner, ensure(dir)), JSON.stringify({ repos })); } catch { /* a cache */ } }
284
+
285
+ // ---- forge.yaml writer -----------------------------------------------------------------------------------------------
286
+ const CI_KEYS = ["mode", "monthly_minutes", "reserve_pct", "included_minutes", "plan"];
287
+
288
+ /**
289
+ * Returns forge.yaml text with the ci policy keys set, keeping every other line of the `ci:` block (milestone integration
290
+ * keys) as is. Creates the block when absent. `set` is {mode?, monthly_minutes?, reserve_pct?, included_minutes?, plan?}.
291
+ * Validates through parseCiPolicy semantics and throws on an invalid value.
292
+ */
293
+ export function writeCiBlock(raw, set) {
294
+ if (set.mode !== undefined && !CI_MODES.includes(set.mode)) throw new Error(`ci.mode must be one of ${CI_MODES.join(", ")}`);
295
+ for (const k of ["monthly_minutes", "included_minutes"]) if (set[k] !== undefined && !posInt(set[k])) throw new Error(`ci.${k} must be a positive integer`);
296
+ if (set.reserve_pct !== undefined && !(Number(set.reserve_pct) >= 0 && Number(set.reserve_pct) <= 90)) throw new Error("ci.reserve_pct must be 0-90");
297
+ if (set.plan !== undefined && PLAN_MINUTES[String(set.plan).toLowerCase()] === undefined) throw new Error(`ci.plan must be one of ${Object.keys(PLAN_MINUTES).join(", ")}`);
298
+ const lines = raw.split("\n");
299
+ const start = lines.findIndex((l) => /^ci:\s*(#.*)?$/.test(l));
300
+ const want = CI_KEYS.filter((k) => set[k] !== undefined).map((k) => ` ${k}: ${k === "plan" ? String(set[k]).toLowerCase() : set[k]}`);
301
+ if (start < 0) return `${raw.replace(/\n*$/, "\n")}\nci:\n${want.join("\n")}\n`;
302
+ let end = start + 1;
303
+ while (end < lines.length && (/^\s+\S/.test(lines[end]) || /^\s*(#.*)?$/.test(lines[end]))) end++;
304
+ const body = lines.slice(start + 1, end).filter((l) => !CI_KEYS.some((k) => new RegExp(`^\\s+${k}:`).test(l) && set[k] !== undefined));
305
+ return [...lines.slice(0, start + 1), ...want, ...body, ...lines.slice(end)].join("\n");
306
+ }
307
+
308
+ // ---- CLI -------------------------------------------------------------------------------------------------------------
309
+ export const CI_USAGE = "usage: forgedock ci budget [--repo owner/repo] [--json] [--digest] [--propose [--base REF]] [--set-mode MODE] [--budget MINUTES] [--reserve PCT] [--plan PLAN]";
310
+ const flagVal = (argv, f) => { const i = argv.indexOf(f); return i >= 0 ? argv[i + 1] : undefined; };
311
+
312
+ /** `forgedock ci budget ...`; @returns the exit code. `deps`: {gh, cwd, now, out, dir}. */
313
+ export async function ciFromCli(argv, deps = {}) {
314
+ const out = deps.out ?? ((l) => console.log(l)), cwd = deps.cwd ?? process.cwd(), gh = deps.gh ?? defaultGh, now = deps.now ?? Date.now(), dir = deps.dir ?? cacheDir();
315
+ if (argv[0] !== "budget") throw new Error(CI_USAGE);
316
+ const rest = argv.slice(1);
317
+ const valued = ["--repo", "--set-mode", "--budget", "--reserve", "--plan", "--base"];
318
+ const unknown = rest.find((a, i) => a.startsWith("--") && ![...valued, "--json", "--digest", "--propose"].includes(a) && !valued.includes(rest[i - 1] ?? ""));
319
+ if (unknown) throw new Error(`unknown option ${unknown}; ${CI_USAGE}`);
320
+ const set = {};
321
+ if (flagVal(rest, "--set-mode") !== undefined) set.mode = flagVal(rest, "--set-mode");
322
+ if (flagVal(rest, "--budget") !== undefined) set.monthly_minutes = flagVal(rest, "--budget");
323
+ if (flagVal(rest, "--reserve") !== undefined) set.reserve_pct = flagVal(rest, "--reserve");
324
+ if (flagVal(rest, "--plan") !== undefined) set.plan = flagVal(rest, "--plan");
325
+ if (Object.keys(set).length) {
326
+ const file = join(cwd, "forge.yaml");
327
+ if (!existsSync(file)) throw new Error(`no forge.yaml in ${cwd}`);
328
+ writeFileSync(file, writeCiBlock(readFileSync(file, "utf8"), set));
329
+ out(`forge.yaml: ci ${Object.entries(set).map(([k, v]) => `${k}=${v}`).join(" ")}`);
330
+ }
331
+ const repo = flagVal(rest, "--repo") ?? JSON.parse(String(await gh(["repo", "view", "--json", "nameWithOwner"]))).nameWithOwner;
332
+ const policy = readCiPolicy(cwd);
333
+ const facts = await detectBudget({ gh, repo, policy, now });
334
+ const res = resolveCiMode({ policy, facts });
335
+ writeEffective({ cwd, res, now, dir });
336
+ const seen = readSeen(facts.owner, dir);
337
+ const alerts = budgetAlerts({ facts, seen });
338
+ if (facts.usage) writeSeen(facts.owner, Object.keys(facts.usage.byRepo), dir);
339
+ const rates = hitRates(await pairParity({ gh, repo, rows: readParity(dir).slice(-50) }));
340
+ if (rest.includes("--json")) { out(JSON.stringify({ repo, plan: facts.plan, includedMinutes: facts.included, budget: facts.budget, public: facts.isPublic, monthToDate: facts.mtd, projected: facts.projected, mode: res.effective, configured: res.configured, switched: res.switched, reason: res.reason, alerts, parity: rates }, null, 2)); return 0; }
341
+ out(`repo: ${repo} (${facts.isPublic ? "public: free hosted minutes" : "private"})`);
342
+ out(`plan: ${facts.plan ?? "unknown"}; included minutes: ${facts.included ?? "unknown"}; budget: ${facts.budget ?? "unknown"}`);
343
+ out(facts.usage ? `month-to-date (all repos of ${facts.owner}): ${facts.mtd} min; burn ${Math.round(facts.burnPerDay)}/day; projected ${facts.projected}` : `month-to-date: unknown (billing API unreadable; needs a token that can read ${facts.isOrg ? "org" : "user"} billing)`);
344
+ out(`mode: ${res.configured}${res.configured !== res.effective ? ` -> ${res.effective}` : ""} (${res.reason})`);
345
+ for (const a of alerts) out(a);
346
+ out(formatHitRates(rates));
347
+ if (rest.includes("--digest")) { out(formatDigest(facts)); for (const [n, m] of await workflowDigest({ gh, repo, now })) out(` workflow ${n}: ${kmin(m)} min`); }
348
+ if (rest.includes("--propose")) {
349
+ const { buildPlan, summarizePlan } = await import(fileURLToPath(new URL("../../scripts/ci-local/plan.mjs", import.meta.url)));
350
+ const base = flagVal(rest, "--base") ?? "origin/main";
351
+ for (const l of summarizePlan(buildPlan({ repo: cwd, base })).filter((x) => /CI_LOCAL_JOB: runnable/.test(x))) out(l);
352
+ out(`run locally: bash scripts/ci-local.sh --base ${base}`);
353
+ }
354
+ return 0;
355
+ }
356
+
357
+ /** The report line for the cwd repo (batch and release reports); resolves, caches the effective mode, and never throws. */
358
+ export async function budgetReportLine({ cwd = process.cwd(), repo, gh = defaultGh, now = Date.now(), dir = cacheDir(), release = null } = {}) {
359
+ try {
360
+ const policy = readCiPolicy(cwd);
361
+ const facts = await detectBudget({ gh, repo, policy, now });
362
+ const res = resolveCiMode({ policy, facts });
363
+ writeEffective({ cwd, res, now, dir });
364
+ return formatBudgetLine({ res, facts, release });
365
+ } catch (e) { return `ci: budget n/a (${String(e?.message ?? e).split("\n")[0].slice(0, 120)})`; }
366
+ }