@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,16 @@
|
|
|
1
|
+
import { EXIT } from "../../domain/errors.js";
|
|
2
|
+
import { stringifyJson } from "../../domain/json.js";
|
|
3
|
+
import { summarizeProfile } from "../../domain/profile.js";
|
|
4
|
+
import { map } from "../../domain/result.js";
|
|
5
|
+
import { writeManaged } from "../../infra/fs.js";
|
|
6
|
+
import { PROFILE_PATH, buildSession } from "../session.js";
|
|
7
|
+
export function detectCommand(root, registry) {
|
|
8
|
+
return map(buildSession(root, registry), ({ profile, packs }) => {
|
|
9
|
+
const change = writeManaged(root, PROFILE_PATH, stringifyJson(profile));
|
|
10
|
+
return {
|
|
11
|
+
exit: EXIT.ok,
|
|
12
|
+
data: { packs: profile.packs, profile, profilePath: PROFILE_PATH, change: change.action, next: "guardrails plan --json" },
|
|
13
|
+
text: `${summarizeProfile(profile, packs)}\nprofile ${change.action}: ${PROFILE_PATH}\nnext: guardrails plan`,
|
|
14
|
+
};
|
|
15
|
+
});
|
|
16
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { EXIT } from "../../domain/errors.js";
|
|
2
|
+
import { debtTotal, nextSteps, renderInitText } from "../../domain/init-report.js";
|
|
3
|
+
import { stringifyJson } from "../../domain/json.js";
|
|
4
|
+
import { baselineFromCounts } from "../../domain/ratchet.js";
|
|
5
|
+
import { ok } from "../../domain/result.js";
|
|
6
|
+
import { writeBaseline } from "../../infra/baseline.js";
|
|
7
|
+
import { backupFiles, ensureLines, runShellSync } from "../../infra/backup.js";
|
|
8
|
+
import { writeManaged } from "../../infra/fs.js";
|
|
9
|
+
import { analyze } from "../analysis.js";
|
|
10
|
+
import { flagBool, flagString } from "../args.js";
|
|
11
|
+
import { catalogOf } from "../catalog.js";
|
|
12
|
+
import { commandsOf } from "../ci-plan.js";
|
|
13
|
+
import { PROFILE_PATH, buildSession } from "../session.js";
|
|
14
|
+
import { agentsMdCommand } from "./agents-md.js";
|
|
15
|
+
import { preflight } from "./apply.js";
|
|
16
|
+
const EDITED_FILES = ["package.json", "tsconfig.json", "eslint.config.mjs", "eslint.config.js", ".claude/settings.json", "AGENTS.md", ".gitignore"];
|
|
17
|
+
const IGNORED = [".guardrails/profile.json", ".guardrails/backup/", ".guardrails/history.jsonl"];
|
|
18
|
+
function ownerOf(args, session) {
|
|
19
|
+
const flag = flagString(args, "owner");
|
|
20
|
+
const remote = session.profile.git.remote;
|
|
21
|
+
return flag ?? (remote === null ? undefined : `@${remote.owner}`);
|
|
22
|
+
}
|
|
23
|
+
function ctxOf(args, session) {
|
|
24
|
+
const owner = ownerOf(args, session);
|
|
25
|
+
return { root: args.cwd, profile: session.profile, packs: session.packs, gradual: true, ...(owner === undefined ? {} : { owner }) };
|
|
26
|
+
}
|
|
27
|
+
function triage(session, ctx) {
|
|
28
|
+
const entries = catalogOf(session.packs);
|
|
29
|
+
const applicable = entries.filter((entry) => entry.constraint.notApplicable(session.profile) === null);
|
|
30
|
+
const pending = applicable.filter((entry) => !entry.constraint.isInstalled(ctx));
|
|
31
|
+
const checked = pending.map((entry) => ({ entry, error: preflight(entry.constraint, session) }));
|
|
32
|
+
return {
|
|
33
|
+
gaps: checked.filter((item) => item.error === null).map((item) => item.entry),
|
|
34
|
+
blocked: checked.flatMap((item) => (item.error === null ? [] : [{ id: item.entry.constraint.id, reason: item.error.message, fix: item.error.fix }])),
|
|
35
|
+
installed: applicable.length - pending.length,
|
|
36
|
+
notApplicable: entries.length - applicable.length,
|
|
37
|
+
missing: [...new Set(pending.flatMap((entry) => entry.constraint.requires(session.profile, session.packs).map((requirement) => requirement.pkg)))],
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
function installGroup(ctx, group) {
|
|
41
|
+
const first = group[0]?.batch;
|
|
42
|
+
if (first === undefined)
|
|
43
|
+
return [];
|
|
44
|
+
const result = first.run(ctx, group.flatMap((constraint) => (constraint.batch === undefined ? [] : [constraint.batch.payload])));
|
|
45
|
+
return group.map((constraint) => ({ id: constraint.id, result }));
|
|
46
|
+
}
|
|
47
|
+
function installAll(ctx, gaps) {
|
|
48
|
+
const constraints = gaps.map((entry) => entry.constraint);
|
|
49
|
+
const batchIds = [...new Set(constraints.flatMap((constraint) => (constraint.batch === undefined ? [] : [constraint.batch.id])))];
|
|
50
|
+
const batched = batchIds.flatMap((id) => installGroup(ctx, constraints.filter((constraint) => constraint.batch?.id === id)));
|
|
51
|
+
const single = constraints.filter((constraint) => constraint.batch === undefined).map((constraint) => ({ id: constraint.id, result: constraint.install(ctx) }));
|
|
52
|
+
return [...batched, ...single];
|
|
53
|
+
}
|
|
54
|
+
function summarizeOutcomes(outcomes) {
|
|
55
|
+
const done = outcomes.flatMap((item) => (item.result.ok ? [{ id: item.id, outcome: item.result.value }] : []));
|
|
56
|
+
const rows = done.map((item) => ({ id: item.id, level: Object.values(item.outcome.levels).includes("deferred") ? "deferred" : "installed", notes: item.outcome.notes }));
|
|
57
|
+
return {
|
|
58
|
+
applied: rows.filter((row) => row.level !== "deferred"),
|
|
59
|
+
deferred: rows.filter((row) => row.level === "deferred"),
|
|
60
|
+
failed: outcomes.flatMap((item) => (item.result.ok ? [] : [{ id: item.id, reason: item.result.error.message, fix: item.result.error.fix }])),
|
|
61
|
+
changes: done.flatMap((item) => item.outcome.changes),
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
function dryRun(args, session, found) {
|
|
65
|
+
const install = found.missing.length === 0 ? null : (commandsOf(session.packs)?.installDev(session.profile, found.missing) ?? null);
|
|
66
|
+
const ids = found.gaps.map((entry) => entry.constraint.id);
|
|
67
|
+
return ok({
|
|
68
|
+
exit: EXIT.ok,
|
|
69
|
+
data: { dryRun: true, packs: session.profile.packs.map((pack) => pack.id), wouldApply: ids, blocked: found.blocked, alreadyInstalled: found.installed, notApplicable: found.notApplicable, install, wouldBackUp: EDITED_FILES },
|
|
70
|
+
text: [`dry run in ${args.cwd}`, `packs: ${session.profile.packs.map((pack) => pack.id).join(", ")}`, `would apply ${String(ids.length)}: ${ids.join(", ")}`, ...found.blocked.map((item) => `blocked: ${item.id}: ${item.reason}`), ...(install === null ? [] : [`install first: ${install}`])].join("\n"),
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
function tryInstall(args, session, found) {
|
|
74
|
+
const command = found.missing.length === 0 ? null : (commandsOf(session.packs)?.installDev(session.profile, found.missing) ?? null);
|
|
75
|
+
if (command !== null && flagBool(args, "install"))
|
|
76
|
+
runShellSync(args.cwd, command);
|
|
77
|
+
return command;
|
|
78
|
+
}
|
|
79
|
+
export async function initCommand(args, registry) {
|
|
80
|
+
const first = buildSession(args.cwd, registry);
|
|
81
|
+
if (!first.ok)
|
|
82
|
+
return first;
|
|
83
|
+
const found = triage(first.value, ctxOf(args, first.value));
|
|
84
|
+
if (flagBool(args, "dry-run"))
|
|
85
|
+
return dryRun(args, first.value, found);
|
|
86
|
+
const command = tryInstall(args, first.value, found);
|
|
87
|
+
const session = flagBool(args, "install") && command !== null ? buildSession(args.cwd, registry) : first;
|
|
88
|
+
if (!session.ok)
|
|
89
|
+
return session;
|
|
90
|
+
return finishInit(args, session.value, registry, command);
|
|
91
|
+
}
|
|
92
|
+
async function finishInit(args, session, registry, command) {
|
|
93
|
+
const ctx = ctxOf(args, session);
|
|
94
|
+
const found = triage(session, ctx);
|
|
95
|
+
const stillMissing = flagBool(args, "install") ? [] : found.missing;
|
|
96
|
+
const backups = backupFiles(args.cwd, EDITED_FILES);
|
|
97
|
+
const gitignore = ensureLines(args.cwd, ".gitignore", IGNORED);
|
|
98
|
+
const done = summarizeOutcomes(installAll(ctx, found.gaps));
|
|
99
|
+
const fresh = buildSession(args.cwd, registry);
|
|
100
|
+
if (!fresh.ok)
|
|
101
|
+
return fresh;
|
|
102
|
+
const analysis = await analyze(args.cwd, fresh.value.profile, fresh.value.packs, []);
|
|
103
|
+
const debt = analysis.results.reduce((all, result) => ({ ...all, ...result.debt }), {});
|
|
104
|
+
const baseline = writeBaseline(args.cwd, baselineFromCounts(debt));
|
|
105
|
+
const agents = agentsMdCommand(args.cwd, registry);
|
|
106
|
+
const profile = writeManaged(args.cwd, PROFILE_PATH, stringifyJson(fresh.value.profile));
|
|
107
|
+
const errors = analysis.results.flatMap((result) => result.diagnostics).filter((item) => item.severity === "error" && item.tool !== "ratchet").length;
|
|
108
|
+
const summary = {
|
|
109
|
+
packs: fresh.value.profile.packs.map((pack) => pack.id),
|
|
110
|
+
applied: done.applied,
|
|
111
|
+
alreadyInstalled: found.installed,
|
|
112
|
+
notApplicable: found.notApplicable,
|
|
113
|
+
blocked: [...found.blocked, ...done.failed],
|
|
114
|
+
deferred: done.deferred,
|
|
115
|
+
debt,
|
|
116
|
+
errors,
|
|
117
|
+
install: stillMissing.length === 0 ? null : command,
|
|
118
|
+
changes: [...done.changes, gitignore, baseline, profile, ...(agents.ok ? [{ path: "AGENTS.md", action: "updated" }] : [])],
|
|
119
|
+
backups,
|
|
120
|
+
};
|
|
121
|
+
const steps = nextSteps(summary);
|
|
122
|
+
const clean = summary.blocked.length === 0 && errors === 0 && summary.install === null;
|
|
123
|
+
return ok({ exit: clean ? EXIT.ok : EXIT.findings, data: { ...summary, debtTotal: debtTotal(debt), phasesMs: analysis.phasesMs, next: steps }, text: renderInitText(summary, steps) });
|
|
124
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { EXIT } from "../../domain/errors.js";
|
|
2
|
+
import { proposeDebt, proposeInstalls, proposeRecurring, tally, total } from "../../domain/learn.js";
|
|
3
|
+
import { map } from "../../domain/result.js";
|
|
4
|
+
import { readBaseline } from "../../infra/baseline.js";
|
|
5
|
+
import { ciFailureLines, fixCommitSubjects, readHistory, reviewComments } from "../../infra/learn-sources.js";
|
|
6
|
+
import { flagBool } from "../args.js";
|
|
7
|
+
import { catalogOf } from "../catalog.js";
|
|
8
|
+
import { buildSession } from "../session.js";
|
|
9
|
+
function pendingIds(session) {
|
|
10
|
+
const ctx = { root: session.root, profile: session.profile, packs: session.packs };
|
|
11
|
+
return new Set(catalogOf(session.packs).filter((entry) => entry.constraint.notApplicable(session.profile) === null && !entry.constraint.isInstalled(ctx)).map((entry) => entry.constraint.id));
|
|
12
|
+
}
|
|
13
|
+
function signalsOf(packs) {
|
|
14
|
+
return packs.flatMap((pack) => pack.signals ?? []);
|
|
15
|
+
}
|
|
16
|
+
function gather(session, offline) {
|
|
17
|
+
const { root, profile, packs } = session;
|
|
18
|
+
const signals = signalsOf(packs);
|
|
19
|
+
const repo = profile.git.remote === null ? null : `${profile.git.remote.owner}/${profile.git.remote.repo}`;
|
|
20
|
+
const history = readHistory(root);
|
|
21
|
+
const commits = fixCommitSubjects(root);
|
|
22
|
+
const reviews = offline || repo === null ? { texts: [], available: false } : reviewComments(root, repo);
|
|
23
|
+
const ci = offline || repo === null ? { texts: [], available: false } : ciFailureLines(root);
|
|
24
|
+
const baseline = readBaseline(root).rules;
|
|
25
|
+
const ruleNames = Object.keys(baseline);
|
|
26
|
+
const installs = proposeInstalls([
|
|
27
|
+
{ source: "fix-commits", tallies: tally(commits, signals) },
|
|
28
|
+
{ source: "reviews", tallies: tally(reviews.texts, signals) },
|
|
29
|
+
{ source: "ci", tallies: tally(ci.texts, signals) },
|
|
30
|
+
], pendingIds(session));
|
|
31
|
+
const debt = proposeDebt(baseline);
|
|
32
|
+
return {
|
|
33
|
+
proposals: [...installs, ...proposeRecurring(history), ...debt],
|
|
34
|
+
sources: { "check-history": `${String(history.length)} runs`, "fix-commits": `${String(commits.length)} lines`, reviews: reviews.available ? `${String(reviews.texts.length)} comments` : "unavailable (offline, no remote or gh)", ci: ci.available ? `${String(ci.texts.length)} log lines` : "unavailable (offline, no remote or gh)", baseline: `${String(ruleNames.length)} rules` },
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
function render(proposals, sources) {
|
|
38
|
+
return [
|
|
39
|
+
`sources: ${Object.entries(sources).map(([name, detail]) => `${name} ${detail}`).join("; ")}`,
|
|
40
|
+
...(proposals.length === 0 ? ["no proposals yet: run `guardrails check` more often so the history fills, or add --offline false with gh access"] : proposals.slice(0, 15).map((item) => `${item.kind} ${item.id} (${String(total(item.evidence))} signals): ${item.command}`)),
|
|
41
|
+
].join("\n");
|
|
42
|
+
}
|
|
43
|
+
export function learnCommand(args, registry) {
|
|
44
|
+
return map(buildSession(args.cwd, registry), (session) => {
|
|
45
|
+
const { proposals, sources } = gather(session, flagBool(args, "offline"));
|
|
46
|
+
return { exit: EXIT.ok, data: { sources, count: proposals.length, proposals }, text: render(proposals, sources) };
|
|
47
|
+
});
|
|
48
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { EXIT } from "../../domain/errors.js";
|
|
2
|
+
import { stringifyJson } from "../../domain/json.js";
|
|
3
|
+
import { map } from "../../domain/result.js";
|
|
4
|
+
import { writeManaged } from "../../infra/fs.js";
|
|
5
|
+
import { flagBool } from "../args.js";
|
|
6
|
+
import { catalogOf } from "../catalog.js";
|
|
7
|
+
import { commandsOf } from "../ci-plan.js";
|
|
8
|
+
import { PROFILE_PATH, buildSession } from "../session.js";
|
|
9
|
+
function itemOf({ constraint, pack }, ctx) {
|
|
10
|
+
const { profile } = ctx;
|
|
11
|
+
const base = { id: constraint.id, pack, title: constraint.title, layer: constraint.layer, why: constraint.why, apply: `guardrails apply ${constraint.id}` };
|
|
12
|
+
const reason = constraint.notApplicable(profile);
|
|
13
|
+
if (reason !== null)
|
|
14
|
+
return { ...base, status: "not-applicable", reason, requires: [] };
|
|
15
|
+
const done = constraint.isInstalled(ctx);
|
|
16
|
+
return { ...base, status: done ? "installed" : "gap", requires: done ? [] : constraint.requires(profile, ctx.packs) };
|
|
17
|
+
}
|
|
18
|
+
const MARK = { gap: "GAP ", installed: "ok ", "not-applicable": "n/a " };
|
|
19
|
+
function render(items, install) {
|
|
20
|
+
const gaps = items.filter((item) => item.status === "gap").length;
|
|
21
|
+
const count = (status) => items.filter((item) => item.status === status).length;
|
|
22
|
+
return [
|
|
23
|
+
...items.map((item) => `${MARK[item.status]} ${item.id} [${item.pack}]${item.reason === undefined ? "" : ` (${item.reason})`}`),
|
|
24
|
+
`${count("installed")} installed, ${gaps} gaps, ${count("not-applicable")} not applicable`,
|
|
25
|
+
...(install === null ? [] : [`first install the packages: ${install}`]),
|
|
26
|
+
...(gaps > 0 ? ["then: guardrails apply <id> for each GAP, in the order above"] : []),
|
|
27
|
+
].join("\n");
|
|
28
|
+
}
|
|
29
|
+
export function planCommand(args, registry) {
|
|
30
|
+
return map(buildSession(args.cwd, registry), ({ profile, packs }) => {
|
|
31
|
+
writeManaged(args.cwd, PROFILE_PATH, stringifyJson(profile));
|
|
32
|
+
const ctx = { root: args.cwd, profile, packs };
|
|
33
|
+
const items = catalogOf(packs).map((entry) => itemOf(entry, ctx));
|
|
34
|
+
const gaps = items.filter((item) => item.status === "gap");
|
|
35
|
+
const packages = [...new Set(gaps.flatMap((item) => item.requires.map((requirement) => requirement.pkg)))];
|
|
36
|
+
const install = packages.length === 0 ? null : (commandsOf(packs)?.installDev(profile, packages) ?? `install: ${packages.join(" ")}`);
|
|
37
|
+
const counts = { installed: items.filter((item) => item.status === "installed").length, gaps: gaps.length, notApplicable: items.filter((item) => item.status === "not-applicable").length };
|
|
38
|
+
return { exit: flagBool(args, "fail-on-gaps") && gaps.length > 0 ? EXIT.findings : EXIT.ok, data: { packs: profile.packs.map((pack) => pack.id), counts, install, items }, text: render(items, install) };
|
|
39
|
+
});
|
|
40
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { EXIT } from "../../domain/errors.js";
|
|
2
|
+
import { parseLog } from "../../domain/log-parse.js";
|
|
3
|
+
import { renderComment } from "../../domain/pr-comment.js";
|
|
4
|
+
import { attemptsOf, clearPr, failedShas, nextStep, recordFailure, verdictOf } from "../../domain/pr-loop.js";
|
|
5
|
+
import { andThen, ok } from "../../domain/result.js";
|
|
6
|
+
import { jobLog, readLoopState, readPr, upsertComment, waitForChecks, writeLoopState } from "../../infra/pr.js";
|
|
7
|
+
import { flagBool, flagString } from "../args.js";
|
|
8
|
+
import { buildSession } from "../session.js";
|
|
9
|
+
const fixesOf = (packs) => packs.reduce((all, pack) => ({ ...all, ...pack.fixes }), {});
|
|
10
|
+
const withFix = (fixes, entry) => {
|
|
11
|
+
const known = entry.rule === null ? undefined : fixes[entry.rule];
|
|
12
|
+
return known === undefined ? entry : { ...entry, fix: known };
|
|
13
|
+
};
|
|
14
|
+
function failingChecks(root, pr, ignore, fixes) {
|
|
15
|
+
return pr.checks
|
|
16
|
+
.filter((check) => check.state === "fail" && !ignore.includes(check.name))
|
|
17
|
+
.map((check) => ({ check: check.name, url: check.url, diagnostics: parseLog(check.name, check.jobId === null ? "" : jobLog(root, check.jobId)).map((entry) => withFix(fixes, entry)) }));
|
|
18
|
+
}
|
|
19
|
+
function settle(root, pr, base, record) {
|
|
20
|
+
const state = readLoopState(root);
|
|
21
|
+
const next = base === "fix" ? recordFailure(state, pr.number, pr.head) : base === "green" ? clearPr(state, pr.number) : state;
|
|
22
|
+
if (record && next !== state)
|
|
23
|
+
writeLoopState(root, next);
|
|
24
|
+
const attempts = attemptsOf(failedShas(next, pr.number));
|
|
25
|
+
return { verdict: base === "fix" && attempts.left === 0 ? "escalate" : base, report: { attempts } };
|
|
26
|
+
}
|
|
27
|
+
function build(root, pr, args, fixes, record) {
|
|
28
|
+
const ignore = (flagString(args, "ignore") ?? "").split(",").filter((name) => name !== "");
|
|
29
|
+
const base = verdictOf(pr.checks, ignore, flagBool(args, "ignore-pending"));
|
|
30
|
+
const settled = settle(root, pr, base, record);
|
|
31
|
+
return {
|
|
32
|
+
verdict: settled.verdict,
|
|
33
|
+
pr: { number: pr.number, url: pr.url, head: pr.head, branch: pr.branch, base: pr.base },
|
|
34
|
+
attempts: settled.report.attempts,
|
|
35
|
+
checks: pr.checks.map(({ name, state, url }) => ({ name, state, url })),
|
|
36
|
+
failing: base === "fix" ? failingChecks(root, pr, ignore, fixes) : [],
|
|
37
|
+
next: nextStep(settled.verdict, settled.report.attempts),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
function textOf(report) {
|
|
41
|
+
const rows = report.failing.flatMap((failing) => [`${failing.check}: ${String(failing.diagnostics.length)} to fix`, ...failing.diagnostics.map((entry) => ` ${entry.file}${entry.line > 0 ? `:${String(entry.line)}` : ""} [${entry.rule ?? entry.test ?? "-"}] ${entry.message}\n fix: ${entry.fix}`)]);
|
|
42
|
+
return [`PR #${String(report.pr.number)}: ${report.verdict}`, ...rows, report.next].join("\n");
|
|
43
|
+
}
|
|
44
|
+
function output(report, commented) {
|
|
45
|
+
const exit = report.verdict === "green" ? EXIT.ok : report.verdict === "escalate" ? EXIT.precondition : EXIT.findings;
|
|
46
|
+
return { exit, data: { ...report, commented }, text: textOf(report) };
|
|
47
|
+
}
|
|
48
|
+
async function load(args) {
|
|
49
|
+
const number = flagString(args, "pr");
|
|
50
|
+
const first = readPr(args.cwd, number);
|
|
51
|
+
if (!first.ok || !flagBool(args, "wait"))
|
|
52
|
+
return first;
|
|
53
|
+
await waitForChecks(args.cwd, first.value.number);
|
|
54
|
+
return readPr(args.cwd, String(first.value.number));
|
|
55
|
+
}
|
|
56
|
+
async function run(args, registry, record) {
|
|
57
|
+
const session = buildSession(args.cwd, registry);
|
|
58
|
+
const fixes = session.ok ? fixesOf(session.value.packs) : {};
|
|
59
|
+
return andThen(await load(args), (pr) => {
|
|
60
|
+
const report = build(args.cwd, pr, args, fixes, record);
|
|
61
|
+
const commented = flagBool(args, "comment") ? upsertComment(args.cwd, pr.number, renderComment(report)) : null;
|
|
62
|
+
return ok(output(report, commented));
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
export const prStatusCommand = (args, registry) => run(args, registry, false);
|
|
66
|
+
export const prRepairCommand = (args, registry) => run(args, registry, true);
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { EXIT } from "../../domain/errors.js";
|
|
2
|
+
import { andThen, ok } from "../../domain/result.js";
|
|
3
|
+
import { analyze } from "../analysis.js";
|
|
4
|
+
import { flagBool } from "../args.js";
|
|
5
|
+
import { buildSession } from "../session.js";
|
|
6
|
+
import { reportAudit } from "./audit.js";
|
|
7
|
+
import { reportCheck } from "./check.js";
|
|
8
|
+
export async function selfCheckCommand(args, registry) {
|
|
9
|
+
const session = buildSession(args.cwd, registry);
|
|
10
|
+
if (!session.ok)
|
|
11
|
+
return session;
|
|
12
|
+
const analysis = await analyze(args.cwd, session.value.profile, session.value.packs, []);
|
|
13
|
+
return andThen(reportCheck(analysis), (check) => andThen(reportAudit(analysis, flagBool(args, "offline")), (audit) => {
|
|
14
|
+
const clean = check.exit === EXIT.ok && audit.exit === EXIT.ok;
|
|
15
|
+
return ok({ exit: clean ? EXIT.ok : EXIT.findings, data: { verdict: clean ? (check.data["verdict"] === "debt" ? "debt" : "clean") : "fix", check: check.data, audit: audit.data, phasesMs: analysis.phasesMs }, text: `${check.text}\n${audit.text}` });
|
|
16
|
+
}));
|
|
17
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { appError } from "../domain/errors.js";
|
|
2
|
+
import { andThen, collect, err, map, ok } from "../domain/result.js";
|
|
3
|
+
import { readAsset } from "../infra/assets.js";
|
|
4
|
+
import { preCommitScript } from "./hooks-script.js";
|
|
5
|
+
import { exists, writeIfAbsent } from "../infra/fs.js";
|
|
6
|
+
import { gitConfigGet, gitConfigSet, runCommitMsgHook, shellSyntax } from "../infra/hooks.js";
|
|
7
|
+
import { installed } from "../domain/constraint.js";
|
|
8
|
+
export const HOOKS_DIR = ".githooks";
|
|
9
|
+
const notApplicable = (profile) => (profile.git.isRepo ? null : "not a git repository");
|
|
10
|
+
function hooksActive(ctx) {
|
|
11
|
+
return ctx.profile.git.hooksPath === HOOKS_DIR || ctx.packs.some((pack) => pack.hooks?.bootstrap?.active(ctx) === true);
|
|
12
|
+
}
|
|
13
|
+
function activateHooks(ctx) {
|
|
14
|
+
const { root, profile } = ctx;
|
|
15
|
+
if (profile.git.hooksPath === HOOKS_DIR)
|
|
16
|
+
return ok([]);
|
|
17
|
+
if (profile.git.hooksPath !== null) {
|
|
18
|
+
return err(appError("conflict", `core.hooksPath already points to ${profile.git.hooksPath}`, {
|
|
19
|
+
file: `${profile.git.hooksPath}/pre-commit`,
|
|
20
|
+
fix: `Copy the guardrails hook into ${profile.git.hooksPath}/ by hand (see catalog-assets/githooks in the guardrails package), or run \`git config core.hooksPath ${HOOKS_DIR}\` yourself if you want to move the hooks.`,
|
|
21
|
+
}));
|
|
22
|
+
}
|
|
23
|
+
const result = gitConfigSet(root, "core.hooksPath", HOOKS_DIR);
|
|
24
|
+
return result.ok ? ok([{ path: ".git/config (core.hooksPath)", action: "updated" }]) : err(appError("verify-failed", `git config core.hooksPath failed: ${result.detail}`, { fix: `Run \`git config core.hooksPath ${HOOKS_DIR}\` in the repo.` }));
|
|
25
|
+
}
|
|
26
|
+
function ensureBootstrap(ctx) {
|
|
27
|
+
const steps = ctx.packs.flatMap((pack) => {
|
|
28
|
+
const bootstrap = pack.hooks?.bootstrap;
|
|
29
|
+
return bootstrap === null || bootstrap === undefined ? [] : [bootstrap.ensure(ctx)];
|
|
30
|
+
});
|
|
31
|
+
return map(collect(steps), (lists) => lists.flat());
|
|
32
|
+
}
|
|
33
|
+
function installHook(ctx, name, content) {
|
|
34
|
+
return andThen(writeIfAbsent(ctx.root, `${HOOKS_DIR}/${name}`, content, `git-${name}`, 0o755), (file) => andThen(activateHooks(ctx), (hooks) => andThen(ensureBootstrap(ctx), (boot) => installed([file, ...hooks, ...boot]))));
|
|
35
|
+
}
|
|
36
|
+
function hookChecks(ctx, name) {
|
|
37
|
+
const syntax = shellSyntax(ctx.root, `${HOOKS_DIR}/${name}`);
|
|
38
|
+
const hooksPath = gitConfigGet(ctx.root, "core.hooksPath");
|
|
39
|
+
return [
|
|
40
|
+
{ name: `${name} exists`, ok: exists(ctx.root, `${HOOKS_DIR}/${name}`), detail: `${HOOKS_DIR}/${name}` },
|
|
41
|
+
{ name: `${name} shell syntax`, ok: syntax.ok, detail: syntax.detail },
|
|
42
|
+
{ name: "core.hooksPath", ok: hooksPath === HOOKS_DIR, detail: hooksPath === "" ? "unset" : hooksPath },
|
|
43
|
+
];
|
|
44
|
+
}
|
|
45
|
+
export const gitPreCommit = {
|
|
46
|
+
id: "git-pre-commit",
|
|
47
|
+
title: "pre-commit runs the linters on staged files and the typechecks",
|
|
48
|
+
layer: "git-hook",
|
|
49
|
+
why: "A commit that fails lint or types never leaves the agent's machine.",
|
|
50
|
+
notApplicable,
|
|
51
|
+
requires: () => [],
|
|
52
|
+
isInstalled: (ctx) => exists(ctx.root, `${HOOKS_DIR}/pre-commit`) && hooksActive(ctx),
|
|
53
|
+
install: (ctx) => installHook(ctx, "pre-commit", preCommitScript(ctx.profile, ctx.packs)),
|
|
54
|
+
verify: (ctx) => hookChecks(ctx, "pre-commit"),
|
|
55
|
+
};
|
|
56
|
+
export const gitCommitMsg = {
|
|
57
|
+
id: "git-commit-msg",
|
|
58
|
+
title: "commit-msg enforces Conventional Commits",
|
|
59
|
+
layer: "git-hook",
|
|
60
|
+
why: "A predictable history makes reverts and releases mechanical.",
|
|
61
|
+
notApplicable,
|
|
62
|
+
requires: () => [],
|
|
63
|
+
isInstalled: (ctx) => exists(ctx.root, `${HOOKS_DIR}/commit-msg`) && hooksActive(ctx),
|
|
64
|
+
install: (ctx) => installHook(ctx, "commit-msg", readAsset("githooks/commit-msg")),
|
|
65
|
+
verify: (ctx) => {
|
|
66
|
+
const hook = `${HOOKS_DIR}/commit-msg`;
|
|
67
|
+
const rejects = runCommitMsgHook(ctx.root, hook, "did some stuff");
|
|
68
|
+
const accepts = runCommitMsgHook(ctx.root, hook, "feat(core): add thing");
|
|
69
|
+
return [
|
|
70
|
+
...hookChecks(ctx, "commit-msg"),
|
|
71
|
+
{ name: "commit-msg rejects a free-form subject", ok: rejects !== 0, detail: `exit ${rejects}` },
|
|
72
|
+
{ name: "commit-msg accepts a Conventional Commit", ok: accepts === 0, detail: `exit ${accepts}` },
|
|
73
|
+
];
|
|
74
|
+
},
|
|
75
|
+
};
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { appError } from "../domain/errors.js";
|
|
2
|
+
import { stringifyJson } from "../domain/json.js";
|
|
3
|
+
import { andThen, err, map } from "../domain/result.js";
|
|
4
|
+
import { AUTO_MERGE_FILE, CI_FILE, POST_MERGE_FILE, PROTECTION_SCRIPT, RULESET_FILE, ROLLBACK_FILE, renderAutoMergeWorkflow, renderCiWorkflow, renderDependabot, STATUS_JOB, ensureStatusJob, renderPostMergeWorkflow, renderPrTemplate, renderProtectionScript, renderRollbackWorkflow, renderRuleset, } from "../domain/workflows.js";
|
|
5
|
+
import { exists, readJsonRecord, readText, writeIfAbsent, writeManaged } from "../infra/fs.js";
|
|
6
|
+
import { runShellScript, shellSyntax } from "../infra/hooks.js";
|
|
7
|
+
import { installed } from "../domain/constraint.js";
|
|
8
|
+
import { ciPlan, commandsOf } from "./ci-plan.js";
|
|
9
|
+
const FORBIDDEN_IN_CI = [/\|\|\s*true/, /continue-on-error/, /--no-verify/];
|
|
10
|
+
const fileChecks = (root, files) => files.map((file) => ({ name: `${file} exists`, ok: exists(root, file), detail: file }));
|
|
11
|
+
function noEscapes(root, file) {
|
|
12
|
+
const text = readText(root, file) ?? "";
|
|
13
|
+
const found = FORBIDDEN_IN_CI.filter((pattern) => pattern.test(text)).map((pattern) => pattern.source);
|
|
14
|
+
return { name: `${file} has no escape hatches`, ok: found.length === 0, detail: found.length === 0 ? "no `|| true`, continue-on-error or --no-verify" : `found: ${found.join(", ")}` };
|
|
15
|
+
}
|
|
16
|
+
function simple(id, title, why, file, render, notes = []) {
|
|
17
|
+
return {
|
|
18
|
+
id,
|
|
19
|
+
title,
|
|
20
|
+
layer: "github",
|
|
21
|
+
why,
|
|
22
|
+
notApplicable: () => null,
|
|
23
|
+
requires: () => [],
|
|
24
|
+
isInstalled: ({ root }) => exists(root, file),
|
|
25
|
+
install: (ctx) => andThen(writeIfAbsent(ctx.root, file, render(ctx), id), (change) => installed([change], notes)),
|
|
26
|
+
verify: ({ root }) => fileChecks(root, [file]),
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
export const ciWorkflow = {
|
|
30
|
+
id: "ci-workflow",
|
|
31
|
+
title: "Blocking CI on every PR: lint, typecheck, tests, build, guardrails check",
|
|
32
|
+
layer: "ci",
|
|
33
|
+
why: "The last automatic gate before the base branch; nothing red can merge.",
|
|
34
|
+
notApplicable: () => null,
|
|
35
|
+
requires: (profile, packs) => commandsOf(packs)?.cliRequirement(profile) ?? [],
|
|
36
|
+
isInstalled: ({ root }) => exists(root, CI_FILE),
|
|
37
|
+
install: (ctx) => {
|
|
38
|
+
const blocked = ctx.packs.flatMap((pack) => {
|
|
39
|
+
const error = pack.ci?.preflight(ctx.profile) ?? null;
|
|
40
|
+
return error === null ? [] : [error];
|
|
41
|
+
})[0];
|
|
42
|
+
return blocked !== undefined
|
|
43
|
+
? err(blocked)
|
|
44
|
+
: andThen(writeIfAbsent(ctx.root, CI_FILE, renderCiWorkflow(ctx.profile, ciPlan(ctx.profile, ctx.packs)), "ci-workflow"), (change) => installed([change], ["Mark the job `check` as a required status check: `guardrails apply branch-protection` does it in the ruleset."]));
|
|
45
|
+
},
|
|
46
|
+
verify: ({ root }) => [
|
|
47
|
+
...fileChecks(root, [CI_FILE]),
|
|
48
|
+
noEscapes(root, CI_FILE),
|
|
49
|
+
{ name: "job check runs guardrails check --json", ok: (readText(root, CI_FILE) ?? "").includes("guardrails check --json"), detail: CI_FILE },
|
|
50
|
+
],
|
|
51
|
+
};
|
|
52
|
+
const statusInstalled = (root) => (readText(root, CI_FILE) ?? "").includes(`\n ${STATUS_JOB}:`);
|
|
53
|
+
export const prFeedback = {
|
|
54
|
+
id: "pr-feedback",
|
|
55
|
+
title: "PR diagnostics: one updating comment, a JSON artifact and a required `status` check",
|
|
56
|
+
layer: "ci",
|
|
57
|
+
why: "The agent reads what failed in the PR as structured JSON (file, line, rule or test, fix) instead of scrolling logs, and the final state is a required check.",
|
|
58
|
+
notApplicable: () => null,
|
|
59
|
+
requires: (profile, packs) => commandsOf(packs)?.cliRequirement(profile) ?? [],
|
|
60
|
+
isInstalled: ({ root }) => statusInstalled(root),
|
|
61
|
+
install: (ctx) => {
|
|
62
|
+
const text = readText(ctx.root, CI_FILE);
|
|
63
|
+
return text === null
|
|
64
|
+
? err(appError("not-applicable", `${CI_FILE} does not exist`, { file: CI_FILE, rule: "pr-feedback", fix: "Run `guardrails apply ci-workflow` first; it already includes the status job." }))
|
|
65
|
+
: installed([writeManaged(ctx.root, CI_FILE, ensureStatusJob(text, ciPlan(ctx.profile, ctx.packs)))], ["Re-run `guardrails apply branch-protection` so `status` becomes a required check."]);
|
|
66
|
+
},
|
|
67
|
+
verify: ({ root }) => {
|
|
68
|
+
const text = readText(root, CI_FILE) ?? "";
|
|
69
|
+
return [
|
|
70
|
+
{ name: "job status runs pr-status with --comment", ok: statusInstalled(root) && text.includes("pr-status") && text.includes("--comment"), detail: CI_FILE },
|
|
71
|
+
{ name: "diagnostics uploaded as artifact", ok: text.includes("upload-artifact"), detail: "guardrails-diagnostics" },
|
|
72
|
+
noEscapes(root, CI_FILE),
|
|
73
|
+
];
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
export const autoMerge = {
|
|
77
|
+
...simple("auto-merge", "Auto-merge only when every required check is green", "`gh pr merge --auto` waits for the required checks, so a green PR merges without a human and a red one never does.", AUTO_MERGE_FILE, () => renderAutoMergeWorkflow(), [
|
|
78
|
+
"Label a PR `automerge` (or run `gh pr merge --auto --squash`) to queue it. Requires `allow_auto_merge` on the repo: branch-protection sets it.",
|
|
79
|
+
]),
|
|
80
|
+
verify: ({ root }) => [...fileChecks(root, [AUTO_MERGE_FILE]), { name: "uses --auto", ok: (readText(root, AUTO_MERGE_FILE) ?? "").includes("gh pr merge --auto"), detail: AUTO_MERGE_FILE }],
|
|
81
|
+
};
|
|
82
|
+
export const rollback = {
|
|
83
|
+
id: "rollback",
|
|
84
|
+
title: "Safe rollback: one-click revert PR and a post-merge smoke that reports a broken base",
|
|
85
|
+
layer: "github",
|
|
86
|
+
why: "A broken base must be noticed within minutes and undone by a revert that goes through the same CI.",
|
|
87
|
+
notApplicable: () => null,
|
|
88
|
+
requires: () => [],
|
|
89
|
+
isInstalled: ({ root }) => exists(root, ROLLBACK_FILE) && exists(root, POST_MERGE_FILE),
|
|
90
|
+
install: ({ root, profile, packs }) => andThen(writeIfAbsent(root, ROLLBACK_FILE, renderRollbackWorkflow(profile), "rollback"), (revert) => andThen(writeIfAbsent(root, POST_MERGE_FILE, renderPostMergeWorkflow(profile, ciPlan(profile, packs)), "rollback"), (smoke) => installed([revert, smoke], ["Enable Settings > Actions > Allow GitHub Actions to create pull requests so the rollback workflow can open the revert PR."]))),
|
|
91
|
+
verify: ({ root }) => [...fileChecks(root, [ROLLBACK_FILE, POST_MERGE_FILE]), noEscapes(root, POST_MERGE_FILE)],
|
|
92
|
+
};
|
|
93
|
+
export const dependabot = simple("dependabot", "Dependabot PRs for each ecosystem and GitHub Actions", "Dependency updates arrive as PRs that go through the same blocking CI.", ".github/dependabot.yml", ({ profile, packs }) => renderDependabot(profile, ciPlan(profile, packs)));
|
|
94
|
+
export const codeowners = {
|
|
95
|
+
id: "codeowners",
|
|
96
|
+
title: "CODEOWNERS",
|
|
97
|
+
layer: "github",
|
|
98
|
+
why: "Every change has a named owner, so reviews and alerts reach a person.",
|
|
99
|
+
notApplicable: () => null,
|
|
100
|
+
requires: () => [],
|
|
101
|
+
isInstalled: ({ root }) => exists(root, ".github/CODEOWNERS"),
|
|
102
|
+
install: ({ root, owner }) => owner === undefined || !/^@[\w.-]+(\/[\w.-]+)?$/.test(owner)
|
|
103
|
+
? err(appError("usage", "codeowners needs the GitHub owner: --owner @user or --owner @org/team", { rule: "codeowners", fix: "Run `guardrails apply codeowners --owner @your-user`." }))
|
|
104
|
+
: andThen(writeIfAbsent(root, ".github/CODEOWNERS", `* ${owner}\n`, "codeowners"), (change) => installed([change])),
|
|
105
|
+
verify: ({ root }) => [{ name: "CODEOWNERS has an owner line", ok: /^\*\s+@/m.test(readText(root, ".github/CODEOWNERS") ?? ""), detail: ".github/CODEOWNERS" }],
|
|
106
|
+
};
|
|
107
|
+
export const prTemplate = {
|
|
108
|
+
...simple("pr-template", "Pull request template with the guardrails checklist", "The checklist makes the agent state what it checked and what it did not touch.", ".github/pull_request_template.md", () => renderPrTemplate()),
|
|
109
|
+
verify: ({ root }) => [...fileChecks(root, [".github/pull_request_template.md"]), { name: "has checklist items", ok: (readText(root, ".github/pull_request_template.md") ?? "").includes("- [ ]"), detail: "checklist" }],
|
|
110
|
+
};
|
|
111
|
+
function protectionCommand(profile) {
|
|
112
|
+
return profile.git.remote === null ? `sh ${PROTECTION_SCRIPT}` : `sh ${PROTECTION_SCRIPT} # targets ${profile.git.remote.owner}/${profile.git.remote.repo}`;
|
|
113
|
+
}
|
|
114
|
+
function executeProtection(ctx) {
|
|
115
|
+
if (ctx.profile.git.remote === null)
|
|
116
|
+
return err(appError("not-applicable", "no GitHub remote named origin", { rule: "branch-protection", fix: "Add the remote (`git remote add origin <url>`) and run again." }));
|
|
117
|
+
const result = runShellScript(ctx.root, PROTECTION_SCRIPT);
|
|
118
|
+
return result.ok ? installed([], ["Ruleset guardrails-base applied on GitHub."]) : err(appError("verify-failed", `gh api failed: ${result.detail}`, { file: PROTECTION_SCRIPT, fix: "Check `gh auth status` and that you have admin rights on the repo." }));
|
|
119
|
+
}
|
|
120
|
+
export const branchProtection = {
|
|
121
|
+
id: "branch-protection",
|
|
122
|
+
title: "Base branch protected: PR required, checks required, branch up to date, no force-push, no bypass",
|
|
123
|
+
layer: "github",
|
|
124
|
+
why: "The agent can only reach the base branch through a PR that passed CI.",
|
|
125
|
+
notApplicable: (profile) => (profile.git.isRepo ? null : "not a git repository"),
|
|
126
|
+
requires: () => [],
|
|
127
|
+
isInstalled: ({ root }) => exists(root, PROTECTION_SCRIPT) && exists(root, RULESET_FILE),
|
|
128
|
+
install: (ctx) => {
|
|
129
|
+
const changes = [writeManaged(ctx.root, RULESET_FILE, stringifyJson(renderRuleset(ctx.profile))), writeManaged(ctx.root, PROTECTION_SCRIPT, renderProtectionScript(), 0o755)];
|
|
130
|
+
if (ctx.execute !== true) {
|
|
131
|
+
return installed(changes, [`Not applied to GitHub. When Ivan asks for it, run: ${protectionCommand(ctx.profile)} (or \`guardrails apply branch-protection --execute\`). Needs gh authenticated with admin rights on the repo.`]);
|
|
132
|
+
}
|
|
133
|
+
return map(executeProtection(ctx), (done) => ({ ...done, changes }));
|
|
134
|
+
},
|
|
135
|
+
verify: ({ root, profile }) => {
|
|
136
|
+
const syntax = shellSyntax(root, PROTECTION_SCRIPT);
|
|
137
|
+
const text = JSON.stringify(readJsonRecord(root, RULESET_FILE) ?? {});
|
|
138
|
+
return [
|
|
139
|
+
{ name: "protection script syntax", ok: syntax.ok, detail: syntax.detail },
|
|
140
|
+
{ name: "ruleset targets the base branch", ok: text.includes(`refs/heads/${profile.git.baseBranch}`), detail: profile.git.baseBranch },
|
|
141
|
+
{ name: "ruleset requires PR, checks, no force-push, no deletion", ok: ["pull_request", "required_status_checks", "non_fast_forward", "deletion"].every((type) => text.includes(`"${type}"`)), detail: RULESET_FILE },
|
|
142
|
+
{ name: "ruleset has no bypass actors", ok: text.includes('"bypass_actors":[]'), detail: "bypass_actors is empty" },
|
|
143
|
+
];
|
|
144
|
+
},
|
|
145
|
+
};
|
|
146
|
+
export const GITHUB_CONSTRAINTS = Object.freeze([ciWorkflow, prFeedback, branchProtection, autoMerge, rollback, dependabot, codeowners, prTemplate]);
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export function preCommitScript(profile, packs) {
|
|
2
|
+
return ["#!/bin/sh", "", ...packs.flatMap((pack) => (pack.hooks === null ? [] : [pack.hooks.preCommit(profile)])), ""].join("\n");
|
|
3
|
+
}
|
|
4
|
+
const CLAUDE_HEADER = `#!/bin/sh
|
|
5
|
+
file=$(node -e 'let s="";process.stdin.on("data",(d)=>{s+=d}).on("end",()=>{try{process.stdout.write(String(JSON.parse(s).tool_input?.file_path??""))}catch{}})')
|
|
6
|
+
[ -n "$file" ] || exit 0
|
|
7
|
+
`;
|
|
8
|
+
const CLAUDE_ROOT = `[ -f "$file" ] || exit 0
|
|
9
|
+
|
|
10
|
+
root=$(git -C "$(dirname "$file")" rev-parse --show-toplevel 2>/dev/null) || exit 0
|
|
11
|
+
case "$file" in
|
|
12
|
+
"$root"/node_modules/* | "$root"/dist/* | "$root"/.next/* | "$root"/build/* | "$root"/.venv/*) exit 0 ;;
|
|
13
|
+
esac
|
|
14
|
+
cd "$root" || exit 0
|
|
15
|
+
`;
|
|
16
|
+
export function claudeEditScript(profile, packs) {
|
|
17
|
+
const hooked = packs.flatMap((pack) => (pack.hooks === null ? [] : [pack.hooks]));
|
|
18
|
+
const patterns = [...new Set(hooked.flatMap((hooks) => hooks.editPatterns))].join(" | ");
|
|
19
|
+
return [
|
|
20
|
+
CLAUDE_HEADER,
|
|
21
|
+
`case "$file" in\n ${patterns}) ;;\n *) exit 0 ;;\nesac`,
|
|
22
|
+
CLAUDE_ROOT,
|
|
23
|
+
...hooked.map((hooks) => hooks.claudeEdit(profile)),
|
|
24
|
+
"exit 0",
|
|
25
|
+
"",
|
|
26
|
+
].join("\n");
|
|
27
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { exitCodeOf } from "../domain/errors.js";
|
|
2
|
+
export function emitResult(command, result, json, timingMs) {
|
|
3
|
+
if (json) {
|
|
4
|
+
return { stdout: `${JSON.stringify({ ok: result.exit === 0, command, exit: result.exit, timingMs, ...result.data }, null, 2)}\n`, stderr: "", exit: result.exit };
|
|
5
|
+
}
|
|
6
|
+
return { stdout: `${result.text}\n`, stderr: "", exit: result.exit };
|
|
7
|
+
}
|
|
8
|
+
export function emitError(command, error, json, timingMs) {
|
|
9
|
+
const exit = exitCodeOf(error.code);
|
|
10
|
+
if (json) {
|
|
11
|
+
const payload = { ok: false, command, exit, timingMs, error };
|
|
12
|
+
return { stdout: `${JSON.stringify(payload, null, 2)}\n`, stderr: "", exit };
|
|
13
|
+
}
|
|
14
|
+
const where = [error.file === undefined ? null : `file: ${error.file}`, error.rule === undefined ? null : `rule: ${error.rule}`].filter((part) => part !== null);
|
|
15
|
+
const lines = [`error[${error.code}]: ${error.message}`, ...where.map((part) => ` ${part}`), ` fix: ${error.fix}`];
|
|
16
|
+
return { stdout: "", stderr: `${lines.join("\n")}\n`, exit };
|
|
17
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { appError } from "../domain/errors.js";
|
|
2
|
+
import { err } from "../domain/result.js";
|
|
3
|
+
import { addRuleCommand } from "./commands/add-rule.js";
|
|
4
|
+
import { agentsMdCommand } from "./commands/agents-md.js";
|
|
5
|
+
import { applyCommand } from "./commands/apply.js";
|
|
6
|
+
import { auditCommand } from "./commands/audit.js";
|
|
7
|
+
import { checkCommand } from "./commands/check.js";
|
|
8
|
+
import { detectCommand } from "./commands/detect.js";
|
|
9
|
+
import { prRepairCommand, prStatusCommand } from "./commands/pr-status.js";
|
|
10
|
+
import { planCommand } from "./commands/plan.js";
|
|
11
|
+
import { initCommand } from "./commands/init.js";
|
|
12
|
+
import { learnCommand } from "./commands/learn.js";
|
|
13
|
+
import { selfCheckCommand } from "./commands/self-check.js";
|
|
14
|
+
const HANDLERS = {
|
|
15
|
+
detect: (args, registry) => detectCommand(args.cwd, registry),
|
|
16
|
+
plan: planCommand,
|
|
17
|
+
apply: applyCommand,
|
|
18
|
+
check: checkCommand,
|
|
19
|
+
"add-rule": addRuleCommand,
|
|
20
|
+
audit: auditCommand,
|
|
21
|
+
"agents-md": (args, registry) => agentsMdCommand(args.cwd, registry),
|
|
22
|
+
"self-check": selfCheckCommand,
|
|
23
|
+
init: initCommand,
|
|
24
|
+
learn: learnCommand,
|
|
25
|
+
"pr-status": prStatusCommand,
|
|
26
|
+
"pr-repair": prRepairCommand,
|
|
27
|
+
};
|
|
28
|
+
export async function runCommand(args, registry) {
|
|
29
|
+
if (args.command === "help")
|
|
30
|
+
return err(appError("usage", "help is handled by the CLI entry point", { fix: "Run `guardrails --help`." }));
|
|
31
|
+
return HANDLERS[args.command](args, registry);
|
|
32
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { appError } from "../domain/errors.js";
|
|
2
|
+
import { deriveProfile } from "../domain/profile.js";
|
|
3
|
+
import { resolvePacks } from "../domain/registry.js";
|
|
4
|
+
import { andThen, err, ok } from "../domain/result.js";
|
|
5
|
+
import { readFacts } from "../infra/facts.js";
|
|
6
|
+
export const PROFILE_PATH = ".guardrails/profile.json";
|
|
7
|
+
export function buildSession(root, registry) {
|
|
8
|
+
const facts = readFacts(root, registry.map((pack) => pack.probe));
|
|
9
|
+
return andThen(resolvePacks(registry, facts), (resolution) => {
|
|
10
|
+
if (resolution.packs.length === 0) {
|
|
11
|
+
return err(appError("no-pack", "no supported ecosystem detected in the target directory", {
|
|
12
|
+
fix: `Run guardrails from the repo root, or pass --cwd <repo-root>. Registered packs: ${registry.map((pack) => `${pack.id} (${pack.title})`).join("; ")}.`,
|
|
13
|
+
}));
|
|
14
|
+
}
|
|
15
|
+
const packs = resolution.packs.filter((pack) => resolution.active.some((active) => active.id === pack.id));
|
|
16
|
+
return ok({ root, packs, profile: deriveProfile(facts, packs, resolution.active) });
|
|
17
|
+
});
|
|
18
|
+
}
|