@whil/guardrails 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +208 -2
- package/catalog-assets/claude-hooks/guardrails-check.sh +37 -0
- package/catalog-assets/eslint-guardrails/config.mjs +21 -0
- package/catalog-assets/eslint-rules/_rule-tester.mjs +21 -0
- package/catalog-assets/eslint-rules/cache-policy-constant.mjs +35 -0
- package/catalog-assets/eslint-rules/client-imports-server.mjs +26 -0
- package/catalog-assets/eslint-rules/effects-in-hooks.mjs +46 -0
- package/catalog-assets/eslint-rules/env-through-config.mjs +26 -0
- package/catalog-assets/eslint-rules/hook-body-order.mjs +169 -0
- package/catalog-assets/eslint-rules/import-boundaries.mjs +97 -0
- package/catalog-assets/eslint-rules/no-comments.mjs +35 -0
- package/catalog-assets/eslint-rules/no-default-export.mjs +20 -0
- package/catalog-assets/eslint-rules/no-delete.mjs +16 -0
- package/catalog-assets/eslint-rules/no-enum.mjs +14 -0
- package/catalog-assets/eslint-rules/no-heavy-inline-styles.mjs +20 -0
- package/catalog-assets/eslint-rules/no-let.mjs +14 -0
- package/catalog-assets/eslint-rules/no-logic-in-jsx.mjs +23 -0
- package/catalog-assets/eslint-rules/no-manual-memoization.mjs +45 -0
- package/catalog-assets/eslint-rules/no-member-assignment.mjs +28 -0
- package/catalog-assets/eslint-rules/no-module-cache.mjs +40 -0
- package/catalog-assets/eslint-rules/no-mutating-array-methods.mjs +85 -0
- package/catalog-assets/eslint-rules/no-process-exit.mjs +15 -0
- package/catalog-assets/eslint-rules/no-state-mutation.mjs +62 -0
- package/catalog-assets/eslint-rules/no-unnecessary-use-client.mjs +40 -0
- package/catalog-assets/eslint-rules/pure-components.mjs +48 -0
- package/catalog-assets/eslint-rules/query-key-constant.mjs +54 -0
- package/catalog-assets/eslint-rules/require-disable-reason.mjs +29 -0
- package/catalog-assets/eslint-rules/restrict-timers.mjs +35 -0
- package/catalog-assets/eslint-rules/rules-of-hooks.mjs +51 -0
- package/catalog-assets/eslint-rules/thin-api-routes.mjs +18 -0
- package/catalog-assets/eslint-rules/thin-routes.mjs +18 -0
- package/catalog-assets/eslint-rules/virtualized-lists.mjs +32 -0
- package/catalog-assets/githooks/commit-msg +13 -0
- package/catalog-assets/githooks/pre-commit +26 -0
- package/catalog-assets/scripts/check-exact-deps.mjs +26 -0
- package/dist/cli.js +54 -0
- package/dist/core/app/analysis.js +6 -0
- package/dist/core/app/args.js +44 -0
- package/dist/core/app/catalog.js +20 -0
- package/dist/core/app/ci-plan.js +14 -0
- package/dist/core/app/claude.js +37 -0
- package/dist/core/app/commands/add-rule.js +32 -0
- package/dist/core/app/commands/agents-md.js +13 -0
- package/dist/core/app/commands/apply.js +74 -0
- package/dist/core/app/commands/audit.js +38 -0
- package/dist/core/app/commands/check.js +33 -0
- package/dist/core/app/commands/detect.js +16 -0
- package/dist/core/app/commands/init.js +124 -0
- package/dist/core/app/commands/learn.js +48 -0
- package/dist/core/app/commands/plan.js +40 -0
- package/dist/core/app/commands/pr-status.js +66 -0
- package/dist/core/app/commands/self-check.js +17 -0
- package/dist/core/app/git.js +75 -0
- package/dist/core/app/github.js +146 -0
- package/dist/core/app/hooks-script.js +27 -0
- package/dist/core/app/output.js +17 -0
- package/dist/core/app/run.js +32 -0
- package/dist/core/app/session.js +18 -0
- package/dist/core/app/timing.js +11 -0
- package/dist/core/domain/agents-md.js +92 -0
- package/dist/core/domain/audit-report.js +7 -0
- package/dist/core/domain/changes.js +8 -0
- package/dist/core/domain/check-report.js +23 -0
- package/dist/core/domain/claude-settings.js +42 -0
- package/dist/core/domain/constraint.js +7 -0
- package/dist/core/domain/diagnostics.js +3 -0
- package/dist/core/domain/errors.js +20 -0
- package/dist/core/domain/facts.js +18 -0
- package/dist/core/domain/init-report.js +28 -0
- package/dist/core/domain/json.js +43 -0
- package/dist/core/domain/learn.js +78 -0
- package/dist/core/domain/log-parse.js +99 -0
- package/dist/core/domain/pack-defaults.js +17 -0
- package/dist/core/domain/pack.js +1 -0
- package/dist/core/domain/pr-comment.js +45 -0
- package/dist/core/domain/pr-loop.js +85 -0
- package/dist/core/domain/profile.js +25 -0
- package/dist/core/domain/protection.js +43 -0
- package/dist/core/domain/ratchet.js +40 -0
- package/dist/core/domain/registry.js +32 -0
- package/dist/core/domain/remote.js +4 -0
- package/dist/core/domain/result.js +25 -0
- package/dist/core/domain/thresholds.js +9 -0
- package/dist/core/domain/types.js +1 -0
- package/dist/core/domain/workflows.js +252 -0
- package/dist/core/infra/assets.js +7 -0
- package/dist/core/infra/backup.js +31 -0
- package/dist/core/infra/baseline.js +8 -0
- package/dist/core/infra/changes.js +17 -0
- package/dist/core/infra/exec.js +14 -0
- package/dist/core/infra/facts.js +61 -0
- package/dist/core/infra/fs.js +87 -0
- package/dist/core/infra/gh.js +32 -0
- package/dist/core/infra/hooks.js +31 -0
- package/dist/core/infra/learn-sources.js +40 -0
- package/dist/core/infra/pr.js +48 -0
- package/dist/packs/index.js +6 -0
- package/dist/packs/js-ts/app/add-rule.js +116 -0
- package/dist/packs/js-ts/app/analysis.js +104 -0
- package/dist/packs/js-ts/app/bootstrap.js +16 -0
- package/dist/packs/js-ts/app/eslint-constraints.js +155 -0
- package/dist/packs/js-ts/app/eslint-files.js +56 -0
- package/dist/packs/js-ts/app/fixes.js +3 -0
- package/dist/packs/js-ts/app/pr-rules.js +30 -0
- package/dist/packs/js-ts/app/project.js +87 -0
- package/dist/packs/js-ts/app/tests.js +63 -0
- package/dist/packs/js-ts/domain/catalog-specs.js +147 -0
- package/dist/packs/js-ts/domain/ci.js +47 -0
- package/dist/packs/js-ts/domain/data.js +34 -0
- package/dist/packs/js-ts/domain/diagnostics-js.js +17 -0
- package/dist/packs/js-ts/domain/disables.js +11 -0
- package/dist/packs/js-ts/domain/eslint-output.js +46 -0
- package/dist/packs/js-ts/domain/eslint-state.js +80 -0
- package/dist/packs/js-ts/domain/hooks.js +49 -0
- package/dist/packs/js-ts/domain/pr-diagnostics.js +33 -0
- package/dist/packs/js-ts/domain/pr-tests.js +27 -0
- package/dist/packs/js-ts/domain/profile-pure.js +51 -0
- package/dist/packs/js-ts/domain/profile.js +112 -0
- package/dist/packs/js-ts/domain/report.js +74 -0
- package/dist/packs/js-ts/domain/rule-templates.js +44 -0
- package/dist/packs/js-ts/domain/signals.js +14 -0
- package/dist/packs/js-ts/domain/testing.js +33 -0
- package/dist/packs/js-ts/domain/ts-options.js +13 -0
- package/dist/packs/js-ts/index.js +50 -0
- package/dist/packs/js-ts/infra/eslint.js +50 -0
- package/dist/packs/js-ts/infra/scan.js +25 -0
- package/dist/packs/js-ts/infra/tsc.js +21 -0
- package/dist/packs/nextjs/domain/data.js +9 -0
- package/dist/packs/nextjs/domain/profile.js +21 -0
- package/dist/packs/nextjs/domain/specs.js +33 -0
- package/dist/packs/nextjs/index.js +23 -0
- package/dist/packs/node/domain/specs.js +23 -0
- package/dist/packs/node/index.js +26 -0
- package/dist/packs/react/domain/data.js +9 -0
- package/dist/packs/react/domain/specs.js +63 -0
- package/dist/packs/react/index.js +30 -0
- package/dist/packs/react-native/domain/specs.js +29 -0
- package/dist/packs/react-native/domain/testing.js +20 -0
- package/dist/packs/react-native/index.js +30 -0
- package/package.json +60 -4
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { isRecord } from "./json.js";
|
|
2
|
+
import { THRESHOLDS } from "./thresholds.js";
|
|
3
|
+
export const EMPTY_STATE = Object.freeze({ prs: Object.freeze({}) });
|
|
4
|
+
export const MARKER = "<!-- guardrails-pr-diagnostics -->";
|
|
5
|
+
const text = (value) => (typeof value === "string" ? value : "");
|
|
6
|
+
function runState(status, conclusion) {
|
|
7
|
+
if (status !== "COMPLETED")
|
|
8
|
+
return "pending";
|
|
9
|
+
if (conclusion === "SUCCESS" || conclusion === "NEUTRAL")
|
|
10
|
+
return "pass";
|
|
11
|
+
return conclusion === "SKIPPED" ? "skipped" : "fail";
|
|
12
|
+
}
|
|
13
|
+
function contextState(state) {
|
|
14
|
+
if (state === "SUCCESS")
|
|
15
|
+
return "pass";
|
|
16
|
+
return state === "PENDING" || state === "EXPECTED" ? "pending" : "fail";
|
|
17
|
+
}
|
|
18
|
+
function checkOf(entry) {
|
|
19
|
+
const isRun = entry["__typename"] === "CheckRun";
|
|
20
|
+
const url = text(isRun ? entry["detailsUrl"] : entry["targetUrl"]);
|
|
21
|
+
return {
|
|
22
|
+
name: text(isRun ? entry["name"] : entry["context"]),
|
|
23
|
+
state: isRun ? runState(text(entry["status"]), text(entry["conclusion"])) : contextState(text(entry["state"])),
|
|
24
|
+
url,
|
|
25
|
+
jobId: /\/job\/(\d+)/.exec(url)?.[1] ?? null,
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
export function parsePr(value) {
|
|
29
|
+
if (!isRecord(value) || typeof value["number"] !== "number")
|
|
30
|
+
return null;
|
|
31
|
+
const rollup = Array.isArray(value["statusCheckRollup"]) ? value["statusCheckRollup"] : [];
|
|
32
|
+
return {
|
|
33
|
+
number: value["number"],
|
|
34
|
+
url: text(value["url"]),
|
|
35
|
+
head: text(value["headRefOid"]),
|
|
36
|
+
branch: text(value["headRefName"]),
|
|
37
|
+
base: text(value["baseRefName"]),
|
|
38
|
+
checks: rollup.filter(isRecord).map(checkOf),
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
export function verdictOf(checks, ignore, ignorePending) {
|
|
42
|
+
const relevant = checks.filter((check) => !ignore.includes(check.name));
|
|
43
|
+
if (relevant.some((check) => check.state === "fail"))
|
|
44
|
+
return "fix";
|
|
45
|
+
return !ignorePending && relevant.some((check) => check.state === "pending") ? "pending" : "green";
|
|
46
|
+
}
|
|
47
|
+
export function parseState(source) {
|
|
48
|
+
const parsed = source === null ? null : safeParse(source);
|
|
49
|
+
const prs = isRecord(parsed) ? parsed["prs"] : null;
|
|
50
|
+
if (!isRecord(prs))
|
|
51
|
+
return EMPTY_STATE;
|
|
52
|
+
return { prs: Object.fromEntries(Object.entries(prs).map(([key, shas]) => [key, Array.isArray(shas) ? shas.filter((sha) => typeof sha === "string") : []])) };
|
|
53
|
+
}
|
|
54
|
+
function safeParse(source) {
|
|
55
|
+
try {
|
|
56
|
+
return JSON.parse(source);
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
export function failedShas(state, pr) {
|
|
63
|
+
return state.prs[String(pr)] ?? [];
|
|
64
|
+
}
|
|
65
|
+
export function recordFailure(state, pr, sha) {
|
|
66
|
+
const known = failedShas(state, pr);
|
|
67
|
+
return known.includes(sha) ? state : { prs: { ...state.prs, [String(pr)]: [...known, sha] } };
|
|
68
|
+
}
|
|
69
|
+
export function clearPr(state, pr) {
|
|
70
|
+
return { prs: Object.fromEntries(Object.entries(state.prs).filter(([key]) => key !== String(pr))) };
|
|
71
|
+
}
|
|
72
|
+
export function attemptsOf(shas) {
|
|
73
|
+
const used = Math.max(0, shas.length - 1);
|
|
74
|
+
const limit = THRESHOLDS.repairAttempts.value;
|
|
75
|
+
return { used, left: Math.max(0, limit - used), limit };
|
|
76
|
+
}
|
|
77
|
+
export function nextStep(verdict, attempts) {
|
|
78
|
+
if (verdict === "green")
|
|
79
|
+
return "All checks are green: merge with `gh pr merge --auto --squash`.";
|
|
80
|
+
if (verdict === "pending")
|
|
81
|
+
return "Checks are still running: run `guardrails pr-status --wait --json` again.";
|
|
82
|
+
if (verdict === "escalate")
|
|
83
|
+
return `Stop. ${String(attempts.limit)} repair attempts did not turn the PR green. Ask a human for help and hand over failing[] from this output.`;
|
|
84
|
+
return `Fix every entry in failing[].diagnostics (file, line, rule or test, fix), run \`guardrails check --json\` until clean, commit, push to this branch, then run \`guardrails pr-repair --wait --json\` again. ${String(attempts.left)} of ${String(attempts.limit)} attempts left.`;
|
|
85
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { parseRemote } from "./remote.js";
|
|
2
|
+
export function deriveProfile(facts, packs, active) {
|
|
3
|
+
return {
|
|
4
|
+
version: 2,
|
|
5
|
+
name: facts.rootName,
|
|
6
|
+
packs: active,
|
|
7
|
+
stack: Object.fromEntries(packs.map((pack) => [pack.id, pack.profile(facts)])),
|
|
8
|
+
git: {
|
|
9
|
+
isRepo: facts.git.isRepo,
|
|
10
|
+
hooksPath: facts.git.hooksPath,
|
|
11
|
+
baseBranch: facts.git.baseBranch,
|
|
12
|
+
remote: facts.git.originUrl === null ? null : parseRemote(facts.git.originUrl),
|
|
13
|
+
},
|
|
14
|
+
ci: { github: facts.workflows.length > 0, workflows: facts.workflows },
|
|
15
|
+
claude: { dir: facts.present.includes(".claude"), settings: facts.present.includes(".claude/settings.json") },
|
|
16
|
+
agentsMd: facts.present.includes("AGENTS.md"),
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
export function summarizeProfile(profile, packs) {
|
|
20
|
+
return [
|
|
21
|
+
`${profile.name}: packs ${profile.packs.map((pack) => `${pack.id} (${pack.confidence})`).join(", ")}`,
|
|
22
|
+
...packs.flatMap((pack) => pack.describe(profile).map((line) => `${pack.id}: ${line}`)),
|
|
23
|
+
`git hooks path: ${profile.git.hooksPath ?? "none"}, CI workflows: ${profile.ci.workflows.length}`,
|
|
24
|
+
].join("\n");
|
|
25
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { isRecord } from "./json.js";
|
|
2
|
+
const REQUIRED_RULES = ["pull_request", "required_status_checks", "non_fast_forward", "deletion"];
|
|
3
|
+
export const protectionUnknown = (reason) => ({ status: "unknown", source: null, missing: [], reason });
|
|
4
|
+
function fromMissing(source, missing) {
|
|
5
|
+
return { status: missing.length === 0 ? "active" : "missing", source, missing, reason: null };
|
|
6
|
+
}
|
|
7
|
+
function ruleTypes(ruleset) {
|
|
8
|
+
const rules = ruleset["rules"];
|
|
9
|
+
if (!Array.isArray(rules))
|
|
10
|
+
return [];
|
|
11
|
+
return rules.flatMap((rule) => (isRecord(rule) && typeof rule["type"] === "string" ? [rule["type"]] : []));
|
|
12
|
+
}
|
|
13
|
+
function targetsBranch(ruleset, base) {
|
|
14
|
+
const conditions = ruleset["conditions"];
|
|
15
|
+
const refName = isRecord(conditions) ? conditions["ref_name"] : null;
|
|
16
|
+
const include = isRecord(refName) && Array.isArray(refName["include"]) ? refName["include"] : [];
|
|
17
|
+
return include.some((ref) => ref === `refs/heads/${base}` || ref === "~DEFAULT_BRANCH" || ref === "~ALL");
|
|
18
|
+
}
|
|
19
|
+
export function evaluateRuleset(ruleset, base) {
|
|
20
|
+
if (ruleset["enforcement"] !== "active" || !targetsBranch(ruleset, base)) {
|
|
21
|
+
return { status: "missing", source: "ruleset", missing: ["active ruleset targeting the base branch"], reason: null };
|
|
22
|
+
}
|
|
23
|
+
const types = ruleTypes(ruleset);
|
|
24
|
+
const bypass = ruleset["bypass_actors"];
|
|
25
|
+
const bypassing = Array.isArray(bypass) && bypass.length > 0 ? ["no bypass actors"] : [];
|
|
26
|
+
return fromMissing("ruleset", [...REQUIRED_RULES.filter((type) => !types.includes(type)), ...bypassing]);
|
|
27
|
+
}
|
|
28
|
+
function hasChecks(protection) {
|
|
29
|
+
const checks = protection["required_status_checks"];
|
|
30
|
+
return isRecord(checks) && Array.isArray(checks["contexts"]) && checks["contexts"].length > 0;
|
|
31
|
+
}
|
|
32
|
+
function enabled(value) {
|
|
33
|
+
return isRecord(value) && value["enabled"] === true;
|
|
34
|
+
}
|
|
35
|
+
export function evaluateClassic(protection) {
|
|
36
|
+
const missing = [
|
|
37
|
+
...(isRecord(protection["required_pull_request_reviews"]) ? [] : ["pull request required"]),
|
|
38
|
+
...(hasChecks(protection) ? [] : ["required status checks"]),
|
|
39
|
+
...(enabled(protection["allow_force_pushes"]) ? ["no force-push"] : []),
|
|
40
|
+
...(enabled(protection["enforce_admins"]) ? [] : ["no admin bypass"]),
|
|
41
|
+
];
|
|
42
|
+
return fromMissing("branch-protection", missing);
|
|
43
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { isRecord } from "./json.js";
|
|
2
|
+
export const EMPTY_BASELINE = Object.freeze({ version: 1, rules: Object.freeze({}) });
|
|
3
|
+
export const BASELINE_PATH = ".guardrails/baseline.json";
|
|
4
|
+
export function parseBaseline(value) {
|
|
5
|
+
const rules = isRecord(value) ? value["rules"] : null;
|
|
6
|
+
if (!isRecord(rules))
|
|
7
|
+
return EMPTY_BASELINE;
|
|
8
|
+
const coverage = isRecord(value) ? value["coverage"] : undefined;
|
|
9
|
+
return {
|
|
10
|
+
version: 1,
|
|
11
|
+
rules: Object.fromEntries(Object.entries(rules).filter((entry) => typeof entry[1] === "number" && entry[1] > 0)),
|
|
12
|
+
...(typeof coverage === "number" && coverage > 0 ? { coverage } : {}),
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
export function serializeBaseline(baseline) {
|
|
16
|
+
const sorted = Object.fromEntries(Object.entries(baseline.rules).toSorted(([a], [b]) => a.localeCompare(b)));
|
|
17
|
+
return `${JSON.stringify({ version: 1, rules: sorted, ...(baseline.coverage === undefined ? {} : { coverage: baseline.coverage }) }, null, 2)}\n`;
|
|
18
|
+
}
|
|
19
|
+
export function evaluateRatchet(input) {
|
|
20
|
+
const entries = input.warnRules.map((rule) => ({ rule, count: input.counts[rule] ?? 0, baseline: input.baseline.rules[rule] ?? 0 }));
|
|
21
|
+
const regressions = entries.filter((entry) => entry.count > entry.baseline);
|
|
22
|
+
const tolerated = entries.filter((entry) => entry.count > 0 && entry.count <= entry.baseline);
|
|
23
|
+
const promotable = entries.filter((entry) => entry.count === 0).map((entry) => entry.rule);
|
|
24
|
+
const lowered = Object.fromEntries(tolerated.map((entry) => [entry.rule, entry.count]));
|
|
25
|
+
const untouched = Object.fromEntries(Object.entries(input.baseline.rules).filter(([rule]) => !input.warnRules.includes(rule)));
|
|
26
|
+
return { regressions, tolerated, promotable, next: { version: 1, rules: { ...untouched, ...lowered }, ...(input.baseline.coverage === undefined ? {} : { coverage: input.baseline.coverage }) } };
|
|
27
|
+
}
|
|
28
|
+
export function baselineFromCounts(counts) {
|
|
29
|
+
return { version: 1, rules: Object.fromEntries(Object.entries(counts).filter(([, count]) => count > 0)) };
|
|
30
|
+
}
|
|
31
|
+
const roundDown = (value) => Math.floor(value * 100) / 100;
|
|
32
|
+
export function evaluateCoverage(floor, measured) {
|
|
33
|
+
if (measured === null)
|
|
34
|
+
return { regression: null, next: floor };
|
|
35
|
+
if (floor !== undefined && measured < floor)
|
|
36
|
+
return { regression: { floor, measured }, next: floor };
|
|
37
|
+
const raised = roundDown(measured);
|
|
38
|
+
return { regression: null, next: floor === undefined || raised > floor ? (raised > 0 ? raised : floor) : floor };
|
|
39
|
+
}
|
|
40
|
+
export const coverageLowered = (before, after) => before !== undefined && (after === undefined || after < before);
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { appError } from "./errors.js";
|
|
2
|
+
import { err, map, ok } from "./result.js";
|
|
3
|
+
export const ACTIVATION_THRESHOLD = 0.5;
|
|
4
|
+
function byId(registry, id) {
|
|
5
|
+
return registry.find((pack) => pack.id === id);
|
|
6
|
+
}
|
|
7
|
+
function closure(registry, seeds) {
|
|
8
|
+
const missing = seeds.flatMap((id) => byId(registry, id)?.extends ?? []).filter((id) => byId(registry, id) === undefined);
|
|
9
|
+
if (missing.length > 0) {
|
|
10
|
+
return err(appError("unknown-pack", `a pack extends "${missing[0] ?? ""}" which is not registered`, { file: "src/packs/index.ts", fix: "Register the missing pack in src/packs/index.ts or remove it from `extends`." }));
|
|
11
|
+
}
|
|
12
|
+
const next = [...new Set([...seeds, ...seeds.flatMap((id) => byId(registry, id)?.extends ?? [])])];
|
|
13
|
+
return next.length === seeds.length ? ok(next) : closure(registry, next);
|
|
14
|
+
}
|
|
15
|
+
function depth(registry, id, seen) {
|
|
16
|
+
const pack = byId(registry, id);
|
|
17
|
+
if (pack === undefined || seen.includes(id))
|
|
18
|
+
return 0;
|
|
19
|
+
return pack.extends.reduce((max, parent) => Math.max(max, depth(registry, parent, [...seen, id]) + 1), 0);
|
|
20
|
+
}
|
|
21
|
+
export function resolvePacks(registry, facts) {
|
|
22
|
+
const detections = registry.map((pack) => ({ id: pack.id, detection: pack.detect(facts) }));
|
|
23
|
+
const direct = detections.filter((entry) => entry.detection.confidence >= ACTIVATION_THRESHOLD).map((entry) => entry.id);
|
|
24
|
+
return map(closure(registry, direct), (ids) => {
|
|
25
|
+
const packs = registry.filter((pack) => ids.includes(pack.id)).toSorted((a, b) => depth(registry, a.id, []) - depth(registry, b.id, []));
|
|
26
|
+
const active = packs.map((pack) => {
|
|
27
|
+
const found = detections.find((entry) => entry.id === pack.id)?.detection;
|
|
28
|
+
return { id: pack.id, confidence: found?.confidence ?? 1, evidence: found?.evidence ?? [] };
|
|
29
|
+
});
|
|
30
|
+
return { packs, active };
|
|
31
|
+
});
|
|
32
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export const ok = (value) => ({ ok: true, value });
|
|
2
|
+
export const err = (error) => ({ ok: false, error });
|
|
3
|
+
export function map(result, transform) {
|
|
4
|
+
return result.ok ? ok(transform(result.value)) : result;
|
|
5
|
+
}
|
|
6
|
+
export function andThen(result, next) {
|
|
7
|
+
return result.ok ? next(result.value) : result;
|
|
8
|
+
}
|
|
9
|
+
export function collect(results) {
|
|
10
|
+
const [failed] = results.flatMap((result) => (result.ok ? [] : [result]));
|
|
11
|
+
if (failed !== undefined)
|
|
12
|
+
return failed;
|
|
13
|
+
return ok(results.flatMap((result) => (result.ok ? [result.value] : [])));
|
|
14
|
+
}
|
|
15
|
+
export function valueOr(result, fallback) {
|
|
16
|
+
return result.ok ? result.value : fallback;
|
|
17
|
+
}
|
|
18
|
+
export function fromThrowing(attempt, onError) {
|
|
19
|
+
try {
|
|
20
|
+
return ok(attempt());
|
|
21
|
+
}
|
|
22
|
+
catch (cause) {
|
|
23
|
+
return err(onError(cause));
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export const THRESHOLDS = {
|
|
2
|
+
complexity: { value: 10, why: "ESLint's own default for complexity; above it a function has more paths than a reader or a test suite follows." },
|
|
3
|
+
functionLines: { value: 40, why: "Roughly one screen: a function longer than this is doing more than one job." },
|
|
4
|
+
routeLines: { value: 60, why: "A route file only wires data to a view; this leaves room for imports, metadata and one fetch." },
|
|
5
|
+
apiRouteLines: { value: 40, why: "A handler parses the request, calls a service and returns; more is business logic that belongs in a service." },
|
|
6
|
+
inlineStyleProperties: { value: 2, why: "One or two dynamic values (opacity, transform) are legitimate inline; a third means a static style that belongs in StyleSheet.create." },
|
|
7
|
+
repairAttempts: { value: 3, why: "Three fix-push-recheck rounds cover a real mistake and its knock-on failures; a fourth red run means the agent is guessing and a human should look." },
|
|
8
|
+
recurringRuns: { value: 3, why: "A rule violated in three separate checks is a pattern, not a slip." },
|
|
9
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
export const CI_FILE = ".github/workflows/guardrails-ci.yml";
|
|
2
|
+
export const CI_JOB = "check";
|
|
3
|
+
export const STATUS_JOB = "status";
|
|
4
|
+
const CHECKOUT_FULL = [" - uses: actions/checkout@v4", " with:", " fetch-depth: 0"];
|
|
5
|
+
export function statusJob(plan) {
|
|
6
|
+
return [
|
|
7
|
+
"",
|
|
8
|
+
` ${STATUS_JOB}:`,
|
|
9
|
+
` needs: ${CI_JOB}`,
|
|
10
|
+
" if: ${{ always() && github.event_name == 'pull_request' }}",
|
|
11
|
+
" runs-on: ubuntu-latest",
|
|
12
|
+
" timeout-minutes: 10",
|
|
13
|
+
" permissions:",
|
|
14
|
+
" contents: read",
|
|
15
|
+
" actions: read",
|
|
16
|
+
" checks: read",
|
|
17
|
+
" pull-requests: write",
|
|
18
|
+
" steps:",
|
|
19
|
+
" - uses: actions/checkout@v4",
|
|
20
|
+
...plan.setup,
|
|
21
|
+
" - env:",
|
|
22
|
+
" GH_TOKEN: ${{ github.token }}",
|
|
23
|
+
` run: ${plan.cliStatus} --pr \${{ github.event.pull_request.number }} > guardrails-diagnostics.json`,
|
|
24
|
+
" - if: ${{ always() }}",
|
|
25
|
+
" uses: actions/upload-artifact@v4",
|
|
26
|
+
" with:",
|
|
27
|
+
" name: guardrails-diagnostics",
|
|
28
|
+
" path: guardrails-diagnostics.json",
|
|
29
|
+
" if-no-files-found: ignore",
|
|
30
|
+
];
|
|
31
|
+
}
|
|
32
|
+
export function ensureStatusJob(text, plan) {
|
|
33
|
+
const withDepth = text.includes("fetch-depth") ? text : text.replace(" - uses: actions/checkout@v4\n - ", `${CHECKOUT_FULL.join("\n")}\n - `);
|
|
34
|
+
return withDepth.includes(`\n ${STATUS_JOB}:`) ? withDepth : `${withDepth.trimEnd()}\n${statusJob(plan).join("\n")}\n`;
|
|
35
|
+
}
|
|
36
|
+
export function renderCiWorkflow(profile, plan) {
|
|
37
|
+
return [
|
|
38
|
+
"name: Guardrails CI",
|
|
39
|
+
"",
|
|
40
|
+
"on:",
|
|
41
|
+
" pull_request:",
|
|
42
|
+
" push:",
|
|
43
|
+
` branches: [${profile.git.baseBranch}]`,
|
|
44
|
+
"",
|
|
45
|
+
"concurrency:",
|
|
46
|
+
" group: guardrails-ci-${{ github.ref }}",
|
|
47
|
+
" cancel-in-progress: true",
|
|
48
|
+
"",
|
|
49
|
+
"permissions:",
|
|
50
|
+
" contents: read",
|
|
51
|
+
"",
|
|
52
|
+
"jobs:",
|
|
53
|
+
` ${CI_JOB}:`,
|
|
54
|
+
" runs-on: ubuntu-latest",
|
|
55
|
+
" timeout-minutes: 20",
|
|
56
|
+
" steps:",
|
|
57
|
+
...CHECKOUT_FULL,
|
|
58
|
+
...plan.setup,
|
|
59
|
+
...plan.steps,
|
|
60
|
+
` - run: ${plan.cliCheck}`,
|
|
61
|
+
...statusJob(plan),
|
|
62
|
+
"",
|
|
63
|
+
].join("\n");
|
|
64
|
+
}
|
|
65
|
+
export const ROLLBACK_FILE = ".github/workflows/guardrails-rollback.yml";
|
|
66
|
+
export const POST_MERGE_FILE = ".github/workflows/guardrails-post-merge.yml";
|
|
67
|
+
export const AUTO_MERGE_FILE = ".github/workflows/guardrails-auto-merge.yml";
|
|
68
|
+
export function renderPostMergeWorkflow(profile, plan) {
|
|
69
|
+
return [
|
|
70
|
+
"name: Guardrails post-merge smoke",
|
|
71
|
+
"",
|
|
72
|
+
"on:",
|
|
73
|
+
" push:",
|
|
74
|
+
` branches: [${profile.git.baseBranch}]`,
|
|
75
|
+
"",
|
|
76
|
+
"permissions:",
|
|
77
|
+
" contents: read",
|
|
78
|
+
" issues: write",
|
|
79
|
+
"",
|
|
80
|
+
"jobs:",
|
|
81
|
+
" smoke:",
|
|
82
|
+
" runs-on: ubuntu-latest",
|
|
83
|
+
" timeout-minutes: 20",
|
|
84
|
+
" steps:",
|
|
85
|
+
" - uses: actions/checkout@v4",
|
|
86
|
+
...plan.setup,
|
|
87
|
+
...plan.steps,
|
|
88
|
+
" - if: failure()",
|
|
89
|
+
" env:",
|
|
90
|
+
" GH_TOKEN: ${{ github.token }}",
|
|
91
|
+
" run: |",
|
|
92
|
+
' gh issue create --title "Base branch broken at ${GITHUB_SHA::8}" \\',
|
|
93
|
+
' --body "The smoke run failed on ${GITHUB_SHA}. Revert with: gh workflow run guardrails-rollback.yml -f sha=${GITHUB_SHA}"',
|
|
94
|
+
"",
|
|
95
|
+
].join("\n");
|
|
96
|
+
}
|
|
97
|
+
function rollbackScript(base) {
|
|
98
|
+
return [
|
|
99
|
+
' git config user.name "github-actions[bot]"',
|
|
100
|
+
' git config user.email "41898282+github-actions[bot]@users.noreply.github.com"',
|
|
101
|
+
' branch="revert/${SHA::8}"',
|
|
102
|
+
' git switch -c "$branch"',
|
|
103
|
+
' if [ "$(git rev-list --parents -n1 "$SHA" | wc -w)" -gt 2 ]; then',
|
|
104
|
+
' git revert --no-edit -m 1 "$SHA"',
|
|
105
|
+
" else",
|
|
106
|
+
' git revert --no-edit "$SHA"',
|
|
107
|
+
" fi",
|
|
108
|
+
' git push origin "$branch"',
|
|
109
|
+
` gh pr create --base ${base} --head "$branch" --title "revert: $SHA" --body "Reverts $SHA. It merges only when CI is green."`,
|
|
110
|
+
];
|
|
111
|
+
}
|
|
112
|
+
export function renderRollbackWorkflow(profile) {
|
|
113
|
+
const base = profile.git.baseBranch;
|
|
114
|
+
return [
|
|
115
|
+
"name: Guardrails rollback",
|
|
116
|
+
"",
|
|
117
|
+
"on:",
|
|
118
|
+
" workflow_dispatch:",
|
|
119
|
+
" inputs:",
|
|
120
|
+
" sha:",
|
|
121
|
+
` description: Commit on ${base} to revert`,
|
|
122
|
+
" required: true",
|
|
123
|
+
"",
|
|
124
|
+
"permissions:",
|
|
125
|
+
" contents: write",
|
|
126
|
+
" pull-requests: write",
|
|
127
|
+
"",
|
|
128
|
+
"jobs:",
|
|
129
|
+
" revert:",
|
|
130
|
+
" runs-on: ubuntu-latest",
|
|
131
|
+
" steps:",
|
|
132
|
+
" - uses: actions/checkout@v4",
|
|
133
|
+
" with:",
|
|
134
|
+
` ref: ${base}`,
|
|
135
|
+
" fetch-depth: 0",
|
|
136
|
+
" - env:",
|
|
137
|
+
" SHA: ${{ inputs.sha }}",
|
|
138
|
+
" GH_TOKEN: ${{ github.token }}",
|
|
139
|
+
" run: |",
|
|
140
|
+
...rollbackScript(base),
|
|
141
|
+
"",
|
|
142
|
+
].join("\n");
|
|
143
|
+
}
|
|
144
|
+
export function renderAutoMergeWorkflow() {
|
|
145
|
+
return [
|
|
146
|
+
"name: Guardrails auto-merge",
|
|
147
|
+
"",
|
|
148
|
+
"on:",
|
|
149
|
+
" pull_request:",
|
|
150
|
+
" types: [opened, reopened, ready_for_review, labeled]",
|
|
151
|
+
"",
|
|
152
|
+
"permissions:",
|
|
153
|
+
" contents: write",
|
|
154
|
+
" pull-requests: write",
|
|
155
|
+
"",
|
|
156
|
+
"jobs:",
|
|
157
|
+
" auto-merge:",
|
|
158
|
+
" if: ${{ !github.event.pull_request.draft && contains(github.event.pull_request.labels.*.name, 'automerge') }}",
|
|
159
|
+
" runs-on: ubuntu-latest",
|
|
160
|
+
" steps:",
|
|
161
|
+
" - env:",
|
|
162
|
+
" GH_TOKEN: ${{ github.token }}",
|
|
163
|
+
" PR_URL: ${{ github.event.pull_request.html_url }}",
|
|
164
|
+
" run: gh pr merge --auto --squash \"$PR_URL\"",
|
|
165
|
+
"",
|
|
166
|
+
].join("\n");
|
|
167
|
+
}
|
|
168
|
+
export function renderDependabot(profile, plan) {
|
|
169
|
+
const entry = (ecosystem, directory, limit) => [
|
|
170
|
+
` - package-ecosystem: "${ecosystem}"`,
|
|
171
|
+
` directory: "${directory}"`,
|
|
172
|
+
" schedule:",
|
|
173
|
+
' interval: "weekly"',
|
|
174
|
+
...(limit ? [" open-pull-requests-limit: 5"] : []),
|
|
175
|
+
` target-branch: "${profile.git.baseBranch}"`,
|
|
176
|
+
];
|
|
177
|
+
return [
|
|
178
|
+
"version: 2",
|
|
179
|
+
"updates:",
|
|
180
|
+
...plan.dependabot.flatMap((item) => entry(item.ecosystem, item.directory, true)),
|
|
181
|
+
...entry("github-actions", "/", false),
|
|
182
|
+
"",
|
|
183
|
+
].join("\n");
|
|
184
|
+
}
|
|
185
|
+
export function renderPrTemplate() {
|
|
186
|
+
return [
|
|
187
|
+
"## What and why",
|
|
188
|
+
"",
|
|
189
|
+
"## Checklist",
|
|
190
|
+
"",
|
|
191
|
+
"- [ ] `guardrails check --json` returns `verdict: clean`",
|
|
192
|
+
"- [ ] No `eslint-disable`, `@ts-ignore` or `any` was added to silence a rule",
|
|
193
|
+
"- [ ] No rule was moved from `error` to `warn` or removed",
|
|
194
|
+
"- [ ] Tests cover the behaviour that changed",
|
|
195
|
+
"- [ ] The branch is `type/kebab` and this PR targets the base branch",
|
|
196
|
+
"- [ ] Rollback is a plain revert of this PR (no data migration or manual step)",
|
|
197
|
+
"",
|
|
198
|
+
].join("\n");
|
|
199
|
+
}
|
|
200
|
+
export function renderRuleset(profile) {
|
|
201
|
+
return {
|
|
202
|
+
name: "guardrails-base",
|
|
203
|
+
target: "branch",
|
|
204
|
+
enforcement: "active",
|
|
205
|
+
conditions: { ref_name: { include: [`refs/heads/${profile.git.baseBranch}`], exclude: [] } },
|
|
206
|
+
bypass_actors: [],
|
|
207
|
+
rules: [
|
|
208
|
+
{ type: "deletion" },
|
|
209
|
+
{ type: "non_fast_forward" },
|
|
210
|
+
{
|
|
211
|
+
type: "pull_request",
|
|
212
|
+
parameters: {
|
|
213
|
+
required_approving_review_count: 0,
|
|
214
|
+
dismiss_stale_reviews_on_push: true,
|
|
215
|
+
require_code_owner_review: false,
|
|
216
|
+
require_last_push_approval: false,
|
|
217
|
+
required_review_thread_resolution: true,
|
|
218
|
+
},
|
|
219
|
+
},
|
|
220
|
+
{
|
|
221
|
+
type: "required_status_checks",
|
|
222
|
+
parameters: { strict_required_status_checks_policy: true, required_status_checks: [{ context: CI_JOB }, { context: STATUS_JOB }] },
|
|
223
|
+
},
|
|
224
|
+
],
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
export const PROTECTION_DIR = ".guardrails/github";
|
|
228
|
+
export const RULESET_FILE = `${PROTECTION_DIR}/ruleset.json`;
|
|
229
|
+
export const PROTECTION_SCRIPT = `${PROTECTION_DIR}/branch-protection.sh`;
|
|
230
|
+
export function renderProtectionScript() {
|
|
231
|
+
return [
|
|
232
|
+
"#!/bin/sh",
|
|
233
|
+
"set -eu",
|
|
234
|
+
'dir=$(cd "$(dirname "$0")" && pwd)',
|
|
235
|
+
'repo=$(gh repo view --json nameWithOwner --jq .nameWithOwner)',
|
|
236
|
+
'existing=$(gh api "repos/$repo/rulesets" --jq \'.[] | select(.name == "guardrails-base") | .id\')',
|
|
237
|
+
'if [ -n "$existing" ]; then',
|
|
238
|
+
' gh api --method PUT "repos/$repo/rulesets/$existing" --input "$dir/ruleset.json"',
|
|
239
|
+
"else",
|
|
240
|
+
' gh api --method POST "repos/$repo/rulesets" --input "$dir/ruleset.json"',
|
|
241
|
+
"fi",
|
|
242
|
+
'gh api --method PATCH "repos/$repo" -f allow_auto_merge=true -f delete_branch_on_merge=true -f allow_squash_merge=true > /dev/null',
|
|
243
|
+
"",
|
|
244
|
+
].join("\n");
|
|
245
|
+
}
|
|
246
|
+
export function ensureCiStep(text, step, anchor) {
|
|
247
|
+
const lines = text.split("\n");
|
|
248
|
+
if (lines.some((line) => line.trim() === step.trim()))
|
|
249
|
+
return text;
|
|
250
|
+
const at = lines.findIndex((line) => line.includes(anchor));
|
|
251
|
+
return at === -1 ? `${text.trimEnd()}\n${step}\n` : [...lines.slice(0, at), step, ...lines.slice(at)].join("\n");
|
|
252
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
const ASSETS_DIR = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "catalog-assets");
|
|
5
|
+
export function readAsset(rel) {
|
|
6
|
+
return readFileSync(join(ASSETS_DIR, rel), "utf8");
|
|
7
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { copyFileSync, existsSync, mkdirSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { runSync } from "./exec.js";
|
|
4
|
+
import { readText, writeManaged } from "./fs.js";
|
|
5
|
+
export const BACKUP_DIR = ".guardrails/backup";
|
|
6
|
+
export function backupFiles(root, paths) {
|
|
7
|
+
return paths
|
|
8
|
+
.filter((path) => existsSync(join(root, path)) && !existsSync(join(root, BACKUP_DIR, path)))
|
|
9
|
+
.map((path) => {
|
|
10
|
+
const target = join(root, BACKUP_DIR, path);
|
|
11
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
12
|
+
copyFileSync(join(root, path), target);
|
|
13
|
+
return `${BACKUP_DIR}/${path}`;
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
export function ensureLines(root, rel, lines) {
|
|
17
|
+
const current = readText(root, rel) ?? "";
|
|
18
|
+
const present = new Set(current.split("\n").map((line) => line.trim()));
|
|
19
|
+
const missing = lines.filter((line) => !present.has(line));
|
|
20
|
+
if (missing.length === 0)
|
|
21
|
+
return { path: rel, action: "unchanged" };
|
|
22
|
+
const base = current === "" || current.endsWith("\n") ? current : `${current}\n`;
|
|
23
|
+
return writeManaged(root, rel, `${base}${missing.join("\n")}\n`);
|
|
24
|
+
}
|
|
25
|
+
export function runShellSync(root, command) {
|
|
26
|
+
const result = spawnShell(root, command);
|
|
27
|
+
return { status: result.status, output: `${result.stdout}${result.stderr}`.trim().split("\n").slice(-8).join("\n") };
|
|
28
|
+
}
|
|
29
|
+
function spawnShell(root, command) {
|
|
30
|
+
return runSync("sh", ["-c", command], root);
|
|
31
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { BASELINE_PATH, parseBaseline, serializeBaseline } from "../domain/ratchet.js";
|
|
2
|
+
import { readJsonRecord, writeManaged } from "./fs.js";
|
|
3
|
+
export function readBaseline(root) {
|
|
4
|
+
return parseBaseline(readJsonRecord(root, BASELINE_PATH));
|
|
5
|
+
}
|
|
6
|
+
export function writeBaseline(root, baseline) {
|
|
7
|
+
return writeManaged(root, BASELINE_PATH, serializeBaseline(baseline));
|
|
8
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { runSync } from "./exec.js";
|
|
2
|
+
const lines = (text) => text.split("\n").filter((line) => line !== "");
|
|
3
|
+
export function baseRef(root, base) {
|
|
4
|
+
return [`origin/${base}`, base].find((ref) => runSync("git", ["rev-parse", "--verify", "--quiet", ref], root).status === 0) ?? null;
|
|
5
|
+
}
|
|
6
|
+
export function changedFiles(root, ref) {
|
|
7
|
+
const outputs = [
|
|
8
|
+
runSync("git", ["diff", "--name-only", "--diff-filter=AM", `${ref}...HEAD`], root),
|
|
9
|
+
runSync("git", ["diff", "--name-only", "--diff-filter=AM", "HEAD"], root),
|
|
10
|
+
runSync("git", ["ls-files", "--others", "--exclude-standard"], root),
|
|
11
|
+
];
|
|
12
|
+
return [...new Set(outputs.flatMap((output) => (output.status === 0 ? lines(output.stdout) : [])))].toSorted();
|
|
13
|
+
}
|
|
14
|
+
export function readAtRef(root, ref, path) {
|
|
15
|
+
const result = runSync("git", ["show", `${ref}:${path}`], root);
|
|
16
|
+
return result.status === 0 ? result.stdout : null;
|
|
17
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { execFile, spawnSync } from "node:child_process";
|
|
2
|
+
const MAX_BUFFER = 256 * 1024 * 1024;
|
|
3
|
+
export function runSync(command, args, cwd, input) {
|
|
4
|
+
const result = spawnSync(command, [...args], { cwd, encoding: "utf8", maxBuffer: MAX_BUFFER, ...(input === undefined ? {} : { input }) });
|
|
5
|
+
return { status: result.status ?? 1, stdout: result.stdout, stderr: result.stderr };
|
|
6
|
+
}
|
|
7
|
+
export function runAsync(command, args, cwd) {
|
|
8
|
+
return new Promise((resolve) => {
|
|
9
|
+
execFile(command, [...args], { cwd, encoding: "utf8", maxBuffer: MAX_BUFFER }, (error, stdout, stderr) => {
|
|
10
|
+
const code = error === null ? 0 : error.code;
|
|
11
|
+
resolve({ status: typeof code === "number" ? code : error === null ? 0 : 1, stdout, stderr });
|
|
12
|
+
});
|
|
13
|
+
});
|
|
14
|
+
}
|