forgedock 1.52.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.
- package/.claude-plugin/marketplace.json +51 -0
- package/README.md +8 -2
- package/bin/auth/app-manifest.mjs +89 -0
- package/bin/auth/app-manifest.test.mjs +75 -0
- package/bin/auth/app-token.mjs +256 -0
- package/bin/auth/app-token.test.mjs +232 -0
- package/bin/brand.mjs +7 -0
- package/bin/config-history.mjs +151 -0
- package/bin/config-schema.mjs +115 -0
- package/bin/demo.mjs +65 -11
- package/bin/engine/outcome-codes.mjs +9 -3
- package/bin/engine/telemetry-seam.mjs +11 -3
- package/bin/engine/telemetry-seam.test.mjs +17 -0
- package/bin/engine-cli.mjs +110 -36
- package/bin/experiment.mjs +58 -6
- package/bin/first-run.mjs +122 -0
- package/bin/forge-utils.mjs +6 -2
- package/bin/forgedock.mjs +138 -142
- package/bin/help-text.mjs +144 -0
- package/bin/hooks/pre-tool-use.mjs +7 -0
- package/bin/journey.mjs +82 -83
- package/bin/lean/acceptance.mjs +313 -0
- package/bin/lean/acceptance.test.mjs +215 -0
- package/bin/lean/account-watch.mjs +28 -0
- package/bin/lean/account-watch.test.mjs +30 -0
- package/bin/lean/activation.mjs +38 -0
- package/bin/lean/activation.test.mjs +36 -1
- package/bin/lean/basered.mjs +115 -0
- package/bin/lean/basered.test.mjs +66 -0
- package/bin/lean/batch-health.mjs +114 -7
- package/bin/lean/batch-health.test.mjs +87 -1
- package/bin/lean/batch.mjs +41 -2
- package/bin/lean/batch.test.mjs +115 -11
- package/bin/lean/branchlock.mjs +54 -0
- package/bin/lean/branchlock.test.mjs +49 -0
- package/bin/lean/ceiling.mjs +72 -0
- package/bin/lean/ceiling.test.mjs +54 -0
- package/bin/lean/checkpoint-reconcile.mjs +43 -0
- package/bin/lean/checkpoint-reconcile.test.mjs +95 -0
- package/bin/lean/ci-budget.mjs +366 -0
- package/bin/lean/ci-budget.test.mjs +167 -0
- package/bin/lean/conformance.e2e.test.mjs +8 -1
- package/bin/lean/conformance.mjs +269 -38
- package/bin/lean/conformance.test.mjs +280 -7
- package/bin/lean/context.mjs +35 -6
- package/bin/lean/context.test.mjs +27 -1
- package/bin/lean/depcache.mjs +25 -1
- package/bin/lean/depcache.test.mjs +26 -0
- package/bin/lean/e2e.mjs +18 -2
- package/bin/lean/e2e.test.mjs +26 -1
- package/bin/lean/effects.mjs +47 -14
- package/bin/lean/execution.mjs +19 -3
- package/bin/lean/execution.test.mjs +63 -0
- package/bin/lean/facts.mjs +3 -3
- package/bin/lean/facts.test.mjs +5 -0
- package/bin/lean/findinglabel.mjs +16 -0
- package/bin/lean/findinglabel.test.mjs +39 -0
- package/bin/lean/fixround.mjs +14 -0
- package/bin/lean/fixround.test.mjs +25 -2
- package/bin/lean/gh-assoc.test.mjs +2 -1
- package/bin/lean/integration.mjs +100 -9
- package/bin/lean/integration.test.mjs +98 -0
- package/bin/lean/issuewatch-parity.mjs +64 -0
- package/bin/lean/issuewatch-parity.test.mjs +127 -0
- package/bin/lean/issuewatch-release.mjs +6 -2
- package/bin/lean/issuewatch-release.test.mjs +17 -1
- package/bin/lean/issuewatch.mjs +45 -6
- package/bin/lean/issuewatch.test.mjs +3 -2
- package/bin/lean/lanelock.mjs +14 -0
- package/bin/lean/lean.mjs +473 -100
- package/bin/lean/lean.test.mjs +686 -33
- package/bin/lean/light.mjs +48 -7
- package/bin/lean/light.test.mjs +37 -3
- package/bin/lean/limits.test.mjs +142 -9
- package/bin/lean/mechfix.mjs +124 -0
- package/bin/lean/mechfix.test.mjs +75 -0
- package/bin/lean/orchestrate-cancel.test.mjs +143 -0
- package/bin/lean/orchestrate.mjs +116 -28
- package/bin/lean/phaseledger.mjs +47 -5
- package/bin/lean/phaseledger.test.mjs +30 -1
- package/bin/lean/postdeploy-check.test.mjs +39 -0
- package/bin/lean/precheck.mjs +23 -4
- package/bin/lean/precheck.test.mjs +14 -1
- package/bin/lean/prereq.mjs +28 -0
- package/bin/lean/prereq.test.mjs +20 -0
- package/bin/lean/probe.mjs +4 -2
- package/bin/lean/prodparity.mjs +52 -0
- package/bin/lean/prodparity.test.mjs +67 -0
- package/bin/lean/prompts.mjs +77 -19
- package/bin/lean/quota.mjs +39 -0
- package/bin/lean/recovery.test.mjs +11 -1
- package/bin/lean/relaxation.mjs +73 -0
- package/bin/lean/relaxation.test.mjs +54 -0
- package/bin/lean/release-io.test.mjs +42 -0
- package/bin/lean/release-postmerge.mjs +125 -0
- package/bin/lean/release-preflight.mjs +58 -0
- package/bin/lean/release-preflight.test.mjs +114 -0
- package/bin/lean/release-rehearsal.mjs +64 -0
- package/bin/lean/release-rehearsal.test.mjs +93 -0
- package/bin/lean/release-review.e2e.test.mjs +77 -0
- package/bin/lean/release-review.mjs +254 -0
- package/bin/lean/release-review.test.mjs +307 -0
- package/bin/lean/release-snapshot.mjs +188 -0
- package/bin/lean/release-snapshot.test.mjs +190 -0
- package/bin/lean/release.mjs +296 -0
- package/bin/lean/release.test.mjs +387 -0
- package/bin/lean/render.mjs +1 -1
- package/bin/lean/replan.mjs +184 -0
- package/bin/lean/replan.test.mjs +110 -0
- package/bin/lean/resume.mjs +9 -7
- package/bin/lean/resume.test.mjs +16 -0
- package/bin/lean/rotator.mjs +150 -31
- package/bin/lean/rotator.test.mjs +105 -2
- package/bin/lean/sandbox-remote.mjs +9 -2
- package/bin/lean/schedd.mjs +83 -5
- package/bin/lean/schedd.test.mjs +108 -7
- package/bin/lean/selfreview.mjs +94 -0
- package/bin/lean/selfreview.test.mjs +58 -1
- package/bin/lean/selftest-gate.mjs +22 -0
- package/bin/lean/selftest-gate.test.mjs +18 -1
- package/bin/lean/selftest-journey.mjs +234 -0
- package/bin/lean/selftest-journey.test.mjs +130 -0
- package/bin/lean/selftest-live.mjs +2 -1
- package/bin/lean/seqlease.mjs +35 -1
- package/bin/lean/seqlease.test.mjs +15 -0
- package/bin/lean/seqreserve.e2e.test.mjs +135 -0
- package/bin/lean/seqreserve.mjs +73 -0
- package/bin/lean/seqreserve.test.mjs +134 -0
- package/bin/lean/sequence.mjs +35 -6
- package/bin/lean/seqversioned.mjs +147 -0
- package/bin/lean/stagestamp.mjs +28 -0
- package/bin/lean/stagestamp.test.mjs +32 -0
- package/bin/lean/surfaces.mjs +75 -0
- package/bin/lean/surfaces.test.mjs +59 -0
- package/bin/lean/toolplace.mjs +28 -0
- package/bin/lean/toolplace.test.mjs +24 -0
- package/bin/lean/toolstats.mjs +3 -1
- package/bin/lean/toolstats.test.mjs +11 -0
- package/bin/lean/validatebest.mjs +28 -0
- package/bin/lean/validatebest.test.mjs +27 -0
- package/bin/lean/verifier.mjs +3 -2
- package/bin/lean/verify.mjs +2 -1
- package/bin/lean/verify.test.mjs +6 -0
- package/bin/pool/agent.mjs +27 -4
- package/bin/pool/docker.mjs +5 -0
- package/bin/pool/router.mjs +74 -28
- package/bin/prereqs.mjs +111 -0
- package/bin/replay-timelapse.mjs +149 -0
- package/bin/review-staging.mjs +123 -16
- package/bin/review-staging.test.mjs +18 -0
- package/bin/runner.mjs +43 -6
- package/bin/splash-install.mjs +157 -0
- package/bin/stats/aggregate.mjs +8 -1
- package/bin/stats/conformance-outcomes.mjs +289 -0
- package/bin/stats/conformance-outcomes.test.mjs +274 -0
- package/bin/stats/depth.mjs +275 -0
- package/bin/stats/depth.test.mjs +158 -0
- package/bin/stats/efficiency.mjs +26 -5
- package/bin/stats/efficiency.test.mjs +45 -1
- package/bin/stats/experiment.mjs +7 -5
- package/bin/stats/first-review.mjs +77 -0
- package/bin/stats/first-review.test.mjs +36 -0
- package/bin/stats/firstmerge.mjs +40 -0
- package/bin/stats/firstmerge.test.mjs +41 -0
- package/bin/stats/github-source.mjs +53 -15
- package/bin/stats/index.mjs +147 -9
- package/bin/stats/local-source.mjs +12 -0
- package/bin/stats/origin.mjs +80 -0
- package/bin/stats/origin.test.mjs +58 -0
- package/bin/stats/query.mjs +69 -0
- package/bin/stats/render.mjs +3 -1
- package/bin/stats/scoreboard.mjs +137 -0
- package/bin/stats/scoreboard.test.mjs +87 -0
- package/bin/stats/selffiled.mjs +52 -0
- package/bin/stats/selffiled.test.mjs +71 -0
- package/bin/stats/stats.test.mjs +80 -0
- package/bin/tui.mjs +3 -2
- package/commands/bootstrap.md +15 -14
- package/commands/deploy-pr.md +18 -3
- package/commands/forge-stats.md +1 -1
- package/commands/forgedock-ci-setup.md +28 -0
- package/commands/forgedock-init.md +4 -5
- package/commands/issue.md +2 -0
- package/commands/milestone.md +9 -1
- package/commands/orchestrate.md +1 -1
- package/commands/replay.md +2 -0
- package/commands/review-pr-agents/security.md +4 -0
- package/commands/review-pr-staging.md +6 -1
- package/commands/work-on/build.md +4 -6
- package/commands/work-on/close.md +8 -0
- package/docs/CONFIG.md +170 -18
- package/docs/ISSUE-WATCH.md +25 -0
- package/docs/OUTCOME-CODES.md +4 -0
- package/docs/REPLAY.md +9 -0
- package/docs/SELFTEST.md +11 -0
- package/docs/STATS.md +61 -0
- package/docs/TELEMETRY.md +1 -1
- package/docs/eval/README.md +6 -0
- package/docs/eval/adversarial-bench.md +68 -0
- package/docs/eval/corpus/adversarial-v1.json +285 -0
- package/docs/eval/feature-bench.md +42 -0
- package/docs/eval/feature-specs/crud-auth/journeys/notes-crud-isolated.mjs +21 -0
- package/docs/eval/feature-specs/crud-auth/journeys/register-login.mjs +12 -0
- package/docs/eval/feature-specs/crud-auth/spec.md +15 -0
- package/docs/site/start-a-new-project.md +2 -1
- package/package.json +5 -2
- package/plugins/forgedock-splash/.claude-plugin/plugin.json +10 -0
- package/plugins/forgedock-splash/README.md +27 -0
- package/plugins/forgedock-splash/hooks/hooks.json +1 -0
- package/plugins/forgedock-splash/hooks/register.tsx +74 -0
- package/plugins/forgedock-splash/hooks/scene.ts +222 -0
- package/plugins/forgedock-splash/types/index.d.ts +10 -0
- package/pool/README.md +1 -1
- package/pool/image/cs-cred +14 -1
- package/scripts/backfill-finding-labels.mjs +50 -0
- package/scripts/backfill-finding-labels.test.mjs +36 -0
- package/scripts/bench-adversarial.mjs +216 -0
- package/scripts/bench-feature.mjs +170 -0
- package/scripts/bench-lightlane.mjs +2 -2
- package/scripts/bootstrap-create.mjs +2 -2
- package/scripts/bootstrap-validate.mjs +35 -2
- package/scripts/check-spec-size.sh +4 -3
- package/scripts/check-spec-size.test.sh +3 -0
- package/scripts/doctor-pipeline-state.sh +21 -6
- package/scripts/file-deferred-followups.sh +59 -251
- package/scripts/file-deferred-followups.test.sh +85 -206
- package/scripts/followup-route.mjs +12 -0
- package/scripts/owner-route-parity.test.sh +17 -1
- package/scripts/plan-validate-live.mjs +40 -6
- package/scripts/review-pr-side-effects.test.sh +40 -0
- package/scripts/review-pr-staging-scope.test.sh +1 -1
- package/scripts/review-staging-post.sh +23 -0
- package/scripts/review-staging-post.test.sh +8 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
import { test } from "node:test";
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { writeFileSync, readFileSync } from "node:fs";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { tmpDir } from "../tests/_tmp.mjs";
|
|
8
|
+
import { parseForgeYaml } from "../forge-utils.mjs";
|
|
9
|
+
import { parseIntegration } from "./integration.mjs";
|
|
10
|
+
import {
|
|
11
|
+
parseCiPolicy, sumUsage, project, detectBudget, resolveCiMode, formatBudgetLine, coerceVerify, writeEffective, hitRates, remoteSuites,
|
|
12
|
+
attestPayload, recordHostCheck, budgetAlerts, formatDigest, writeCiBlock, ciFromCli, budgetReportLine, effectiveModeSync, readParity,
|
|
13
|
+
} from "./ci-budget.mjs";
|
|
14
|
+
|
|
15
|
+
const tmp = () => tmpDir("cib-");
|
|
16
|
+
const NOW = Date.parse("2026-11-10T12:00:00Z"); // day 10 of 30
|
|
17
|
+
const item = (q, o = {}) => ({ product: "actions", unitType: "Minutes", sku: "actions_linux", quantity: q, repositoryName: "AlterLab", ...o });
|
|
18
|
+
/** gh stub: repo meta, billing usage, org plan. */
|
|
19
|
+
const ghFor = ({ priv = true, org = true, items = [item(15000)], plan = "enterprise", usageFails = false } = {}) => async (a) => {
|
|
20
|
+
const u = a.join(" ");
|
|
21
|
+
if (/^api repos\/[^/]+\/[^/]+$/.test(u)) return JSON.stringify({ private: priv, owner: { login: "Acme", type: org ? "Organization" : "User" } });
|
|
22
|
+
if (/settings\/billing\/usage/.test(u)) { if (usageFails) throw new Error("HTTP 403"); return JSON.stringify({ usageItems: items }); }
|
|
23
|
+
if (/^api (orgs\/|user$)/.test(u)) return JSON.stringify({ plan: { name: plan } });
|
|
24
|
+
throw new Error(`unexpected ${u}`);
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
test("parseCiPolicy: defaults, flat keys, junk ignored", () => {
|
|
28
|
+
assert.deepEqual(parseCiPolicy(null), { mode: "auto", monthlyMinutes: null, reservePct: 10, includedMinutes: null, plan: null });
|
|
29
|
+
const p = parseCiPolicy({ mode: "local-first", monthly_minutes: "2000", reserve_pct: "20", plan: "Free" });
|
|
30
|
+
assert.equal(p.mode, "local-first"); assert.equal(p.monthlyMinutes, 2000); assert.equal(p.reservePct, 20); assert.equal(p.plan, "free");
|
|
31
|
+
assert.equal(parseCiPolicy({ mode: "bogus", monthly_minutes: "-3", reserve_pct: "99" }).mode, "auto");
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
test("usage sums actions minutes with OS rates; projection is linear", () => {
|
|
35
|
+
const u = sumUsage({ usageItems: [item(100), item(10, { sku: "actions_macos", repositoryName: "B" }), { product: "copilot", quantity: 999 }] });
|
|
36
|
+
assert.equal(u.total, 200); assert.equal(u.byRepo.B, 100);
|
|
37
|
+
assert.equal(project(15000, NOW).projected, 45000);
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
test("private Enterprise repo: over budget in auto switches to local-first and the report says so", async () => {
|
|
41
|
+
const policy = parseCiPolicy({ monthly_minutes: "40000" });
|
|
42
|
+
const facts = await detectBudget({ gh: ghFor(), repo: "Acme/AlterLab", policy, now: NOW });
|
|
43
|
+
assert.equal(facts.mtd, 15000); assert.equal(facts.projected, 45000); assert.equal(facts.plan, "enterprise");
|
|
44
|
+
const res = resolveCiMode({ policy, facts });
|
|
45
|
+
assert.equal(res.effective, "local-first"); assert.equal(res.switched, true);
|
|
46
|
+
const line = formatBudgetLine({ res, facts, release: { runs: 1, minutes: 78 } });
|
|
47
|
+
assert.match(line, /this release: 1 CI run, 78 min/); assert.match(line, /auto -> local-first/); assert.match(line, /month: 15k\/40k, projected 45k/); assert.match(line, /SWITCHED/);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
test("under budget stays remote; plan table supplies the included minutes", async () => {
|
|
51
|
+
const policy = parseCiPolicy(null);
|
|
52
|
+
const facts = await detectBudget({ gh: ghFor({ items: [item(5000)] }), repo: "Acme/x", policy, now: NOW });
|
|
53
|
+
assert.equal(facts.budget, 50000);
|
|
54
|
+
assert.equal(resolveCiMode({ policy, facts }).effective, "remote");
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
test("public repo: free hosted minutes, never auto-switched even over any budget", async () => {
|
|
58
|
+
const policy = parseCiPolicy({ monthly_minutes: "10" });
|
|
59
|
+
const facts = await detectBudget({ gh: ghFor({ priv: false }), repo: "Acme/pub", policy, now: NOW });
|
|
60
|
+
const res = resolveCiMode({ policy, facts });
|
|
61
|
+
assert.equal(res.effective, "remote"); assert.equal(res.switched, false); assert.equal(res.free, true);
|
|
62
|
+
assert.match(formatBudgetLine({ res, facts }), /free hosted minutes/);
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
test("billing API failure is fail-soft: remote, usage unknown", async () => {
|
|
66
|
+
const policy = parseCiPolicy(null);
|
|
67
|
+
const facts = await detectBudget({ gh: ghFor({ usageFails: true }), repo: "Acme/x", policy, now: NOW });
|
|
68
|
+
const res = resolveCiMode({ policy, facts });
|
|
69
|
+
assert.equal(facts.usage, null); assert.equal(res.effective, "remote"); assert.match(res.reason, /unknown/);
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
test("configured local-attested is honoured as is", () => {
|
|
73
|
+
const res = resolveCiMode({ policy: parseCiPolicy({ mode: "local-attested" }), facts: null });
|
|
74
|
+
assert.equal(res.effective, "local-attested");
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
test("local-first coerces verify.mode ci|hybrid to local; remote leaves it", () => {
|
|
78
|
+
const cwd = tmp(), dir = tmp();
|
|
79
|
+
writeFileSync(join(cwd, "forge.yaml"), "ci:\n mode: local-first\n");
|
|
80
|
+
assert.equal(coerceVerify({ mode: "ci" }, { cwd, dir }).mode, "local");
|
|
81
|
+
assert.equal(coerceVerify({ mode: "hybrid" }, { cwd, dir }).mode, "local");
|
|
82
|
+
assert.equal(coerceVerify({ mode: "local" }, { cwd, dir }).mode, "local");
|
|
83
|
+
writeFileSync(join(cwd, "forge.yaml"), "ci:\n mode: remote\n");
|
|
84
|
+
assert.equal(coerceVerify({ mode: "ci" }, { cwd, dir }).mode, "ci");
|
|
85
|
+
writeFileSync(join(cwd, "forge.yaml"), "verify:\n mode: ci\n"); // no ci block: auto with no cache = remote (unchanged default)
|
|
86
|
+
assert.equal(coerceVerify({ mode: "ci" }, { cwd, dir }).mode, "ci");
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
test("auto uses the cached resolution of the budget check", () => {
|
|
90
|
+
const cwd = tmp(), dir = tmp();
|
|
91
|
+
writeFileSync(join(cwd, "forge.yaml"), "ci:\n mode: auto\n");
|
|
92
|
+
assert.equal(effectiveModeSync({ cwd, dir, now: NOW }), "remote");
|
|
93
|
+
writeEffective({ cwd, dir, now: NOW, res: { effective: "local-first", configured: "auto", switched: true, reason: "x" } });
|
|
94
|
+
assert.equal(coerceVerify({ mode: "ci" }, { cwd, dir, now: NOW }).mode, "local");
|
|
95
|
+
assert.equal(effectiveModeSync({ cwd, dir, now: NOW + 3 * 86400000 }), "remote"); // stale cache ignored
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
test("parity: hit rate counts local green -> remote red per suite", () => {
|
|
99
|
+
const rows = [
|
|
100
|
+
{ local: { unit: "pass", lint: "pass" }, remote: { unit: "fail", lint: "pass" } },
|
|
101
|
+
{ local: { unit: "pass" }, remote: { unit: "pass" } },
|
|
102
|
+
{ local: { unit: "fail" }, remote: { unit: "fail" } },
|
|
103
|
+
];
|
|
104
|
+
const r = hitRates(rows);
|
|
105
|
+
assert.deepEqual([r.unit.greenLocal, r.unit.redRemote, r.lint.redRemote], [2, 1, 0]);
|
|
106
|
+
assert.deepEqual(remoteSuites({ check_runs: [{ name: "a", conclusion: "success" }, { name: "b", conclusion: "failure" }, { name: "c", conclusion: null }] }), { a: "pass", b: "fail" });
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
test("recordHostCheck appends a parity row and posts the attested status only in local-attested", async () => {
|
|
110
|
+
const dir = tmp(), calls = [];
|
|
111
|
+
const gh = async (a) => { calls.push(a.join(" ")); return JSON.stringify({ nameWithOwner: "Acme/x" }); };
|
|
112
|
+
await recordHostCheck({ cwd: dir, head: "abc123", ok: true, suites: [{ name: "unit", ok: true }], gh, dir, mode: "local-first" });
|
|
113
|
+
assert.equal(calls.length, 0); assert.deepEqual(readParity(dir)[0].local, { unit: "pass" });
|
|
114
|
+
await recordHostCheck({ cwd: dir, head: "abc123", ok: false, suites: [{ name: "unit", ok: false }], gh, dir, mode: "local-attested" });
|
|
115
|
+
assert.ok(calls.some((c) => /api repos\/Acme\/x\/statuses\/abc123 .*state=failure .*context=forgedock\/ci-local/.test(c)));
|
|
116
|
+
assert.equal(attestPayload({ ok: true, suites: [] }).state, "success");
|
|
117
|
+
await recordHostCheck({ cwd: dir, head: "h", ok: true, suites: [], gh: async () => { throw new Error("boom"); }, dir, mode: "local-attested" }); // fail-soft
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
test("alerts: projected overage and a new burn source; digest lists repos", () => {
|
|
121
|
+
const usage = sumUsage({ usageItems: [item(9000), item(4000, { repositoryName: "Flipped" })] });
|
|
122
|
+
const facts = { budget: 20000, projected: 39000, usage, mtd: 13000, owner: "Acme" };
|
|
123
|
+
const alerts = budgetAlerts({ facts, seen: ["AlterLab"] });
|
|
124
|
+
assert.ok(alerts.some((a) => /projected overage/.test(a))); assert.ok(alerts.some((a) => /new burn source: Flipped/.test(a)));
|
|
125
|
+
assert.equal(budgetAlerts({ facts, seen: null }).some((a) => /new burn/.test(a)), false);
|
|
126
|
+
assert.match(formatDigest(facts), /AlterLab: 9\.0k min/);
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
test("writeCiBlock: plain-language setup writes a valid ci block, keeping milestone_integration keys", () => {
|
|
130
|
+
const raw = "project:\n name: x\nci:\n milestone_integration:\n workflow: e2e.yml\n interval_hours: 12\nverify:\n mode: local\n";
|
|
131
|
+
const out = writeCiBlock(raw, { mode: "local-first", monthly_minutes: 2000, reserve_pct: 15 });
|
|
132
|
+
const p = parseForgeYaml(out);
|
|
133
|
+
assert.equal(parseCiPolicy(p.ci).mode, "local-first"); assert.equal(parseCiPolicy(p.ci).monthlyMinutes, 2000); assert.equal(parseCiPolicy(p.ci).reservePct, 15);
|
|
134
|
+
assert.equal(parseIntegration(p.ci).workflow, "e2e.yml"); assert.equal(parseIntegration(p.ci).intervalHours, 12);
|
|
135
|
+
assert.equal(p.verify.mode, "local");
|
|
136
|
+
assert.equal(parseCiPolicy(parseForgeYaml(writeCiBlock("a: b\n", { mode: "auto" })).ci).mode, "auto"); // creates the block
|
|
137
|
+
const again = parseForgeYaml(writeCiBlock(out, { mode: "remote" }));
|
|
138
|
+
assert.equal(again.ci.mode, "remote"); assert.equal(again.ci.monthly_minutes, "2000");
|
|
139
|
+
assert.throws(() => writeCiBlock(raw, { mode: "fast" }), /ci.mode/);
|
|
140
|
+
assert.throws(() => writeCiBlock(raw, { monthly_minutes: "abc" }), /positive integer/);
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
test("forgedock ci budget prints plan, included, month-to-date, projection and the active mode; flags write forge.yaml", async () => {
|
|
144
|
+
const cwd = tmp(), dir = tmp(), lines = [];
|
|
145
|
+
writeFileSync(join(cwd, "forge.yaml"), "project:\n name: x\n");
|
|
146
|
+
const gh = async (a) => (a[0] === "repo" ? JSON.stringify({ nameWithOwner: "Acme/AlterLab" }) : ghFor({ items: [item(40000)] })(a));
|
|
147
|
+
const code = await ciFromCli(["budget", "--set-mode", "auto", "--budget", "40000"], { cwd, dir, gh, now: NOW, out: (l) => lines.push(l) });
|
|
148
|
+
const text = lines.join("\n");
|
|
149
|
+
assert.equal(code, 0);
|
|
150
|
+
assert.match(text, /plan: enterprise; included minutes: 50000; budget: 40000/);
|
|
151
|
+
assert.match(text, /month-to-date \(all repos of Acme\): 40000 min; burn 4000\/day; projected 120000/);
|
|
152
|
+
assert.match(text, /mode: auto -> local-first/);
|
|
153
|
+
assert.match(readFileSync(join(cwd, "forge.yaml"), "utf8"), /ci:\n {2}mode: auto\n {2}monthly_minutes: 40000/);
|
|
154
|
+
const j = []; await ciFromCli(["budget", "--json"], { cwd, dir, gh, now: NOW, out: (l) => j.push(l) });
|
|
155
|
+
assert.equal(JSON.parse(j.join("")).mode, "local-first");
|
|
156
|
+
await assert.rejects(() => ciFromCli(["budget", "--nope"], { cwd, dir, gh }), /unknown option/);
|
|
157
|
+
await assert.rejects(() => ciFromCli(["other"], { cwd, dir, gh }), /usage/);
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
test("budgetReportLine never throws and caches the effective mode for the next lane", async () => {
|
|
161
|
+
const cwd = tmp(), dir = tmp();
|
|
162
|
+
writeFileSync(join(cwd, "forge.yaml"), "ci:\n monthly_minutes: 1000\n");
|
|
163
|
+
const line = await budgetReportLine({ cwd, dir, repo: "Acme/x", gh: ghFor(), now: NOW });
|
|
164
|
+
assert.match(line, /auto -> local-first/);
|
|
165
|
+
assert.equal(effectiveModeSync({ cwd, dir, now: NOW }), "local-first");
|
|
166
|
+
assert.match(await budgetReportLine({ cwd, dir, repo: "Acme/x", gh: async () => { throw new Error("no gh"); }, now: NOW }), /^ci: auto \(remote\) \(usage unknown/);
|
|
167
|
+
});
|
|
@@ -56,7 +56,7 @@ const contract = (reqs) => ({ requirements: reqs, deliverables: reqs.filter((r)
|
|
|
56
56
|
preserve: [{ id: "P1", what: `${Q.AC3} (src/billing.js price())` }, { id: "P2", what: `${Q.AC2} (test/routes.test.js)` }], validate: [{ id: "V1", command: V1 }] });
|
|
57
57
|
const FULL = () => contract([req("R1"), req("R2"), req("R3"), req("R4"), req("R5")]);
|
|
58
58
|
const OMIT = () => contract([req("R1"), req("R2"), req("R4"), req("R5")]);
|
|
59
|
-
const DEFER = () => contract([req("R1"), req("R2"), req("R3", "defer", { bucket: "
|
|
59
|
+
const DEFER = () => contract([req("R1"), req("R2"), req("R3", "defer", { bucket: "owner:the data-export team ships export.js", why: "export.js ships on the data-export module's own release train" }), req("R4"), req("R5")]);
|
|
60
60
|
|
|
61
61
|
// ---- world ----
|
|
62
62
|
function makeWorld(dir, script) {
|
|
@@ -267,6 +267,13 @@ describe("conformance gate end-to-end (real git, disposable repo)", { skip: !HAV
|
|
|
267
267
|
assert.ok(o.log.some((e) => e.event === "PRECHECK" && e.failures.includes("conformance.unimplemented")));
|
|
268
268
|
assert.match(o.ret.detail, /topology\.route_reachability[\s\S]*\/api\/v1\/agent\/signup\/pending[\s\S]*unreachable: \/api\/v1\/agent\/signup\/pending -> api/);
|
|
269
269
|
});
|
|
270
|
+
it("#5284 a declared topology.prod_parity surface touched without a check result or justification blocks before merge", async () => {
|
|
271
|
+
const o = await runCase({ contract: ROUTED, impl: addRoute }, "enforce", { runCommand: runCheckCommand, opts: { prodParity: { "web/src/app/**": "note: exercise the page under the production runtime" }, verify: { maxRounds: 0 } } });
|
|
272
|
+
assert.equal(o.staging.search, false, "staging untouched");
|
|
273
|
+
assert.equal(o.ret.terminalReason, "needs-human"); assert.equal(o.pr, undefined, "no PR");
|
|
274
|
+
assert.ok(o.log.some((e) => e.event === "PRECHECK" && e.failures.includes("conformance.unimplemented")));
|
|
275
|
+
assert.match(o.ret.detail, /topology\.prod_parity/);
|
|
276
|
+
});
|
|
270
277
|
it("6 a generic PASS over an incomplete implementation never merges (review.incomplete)", async () => {
|
|
271
278
|
const o = await runCase({ contract: FULL, impl: (t) => fix(t, ["scrape", "export"]), generic: true });
|
|
272
279
|
blocked(o, "review.incomplete"); assert.deepEqual([o.counts.builder, o.counts.reviewer], [2, 2]);
|