@whil/guardrails 0.0.0-stage → 0.2.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 +222 -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 +57 -0
- package/dist/config/runtime.js +15 -0
- package/dist/core/app/analysis.js +74 -0
- package/dist/core/app/args.js +46 -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 +127 -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 +20 -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 +104 -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 +21 -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/perf.js +65 -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 +15 -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/hash.js +10 -0
- package/dist/core/infra/hooks.js +31 -0
- package/dist/core/infra/learn-sources.js +40 -0
- package/dist/core/infra/lock.js +102 -0
- package/dist/core/infra/pr.js +48 -0
- package/dist/core/infra/result-cache.js +49 -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 +111 -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 +16 -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 +29 -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,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
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
const round = (ms) => Math.round(ms * 10) / 10;
|
|
2
|
+
export async function timed(task) {
|
|
3
|
+
const start = performance.now();
|
|
4
|
+
const value = await task();
|
|
5
|
+
return { value, ms: round(performance.now() - start) };
|
|
6
|
+
}
|
|
7
|
+
export function timedSync(task) {
|
|
8
|
+
const start = performance.now();
|
|
9
|
+
const value = task();
|
|
10
|
+
return { value, ms: round(performance.now() - start) };
|
|
11
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
export const BLOCK_START = "<!-- guardrails:start -->";
|
|
2
|
+
export const BLOCK_END = "<!-- guardrails:end -->";
|
|
3
|
+
function flowSection(g) {
|
|
4
|
+
return [
|
|
5
|
+
"## Guardrails: the environment validates, you generate",
|
|
6
|
+
"",
|
|
7
|
+
"You write code; this repo's tooling decides if it is correct. Never judge your own output. Run the loop below and fix what it reports. All commands take `--json`, never ask questions, and never delete or overwrite files they do not own.",
|
|
8
|
+
"",
|
|
9
|
+
"### Flow",
|
|
10
|
+
"",
|
|
11
|
+
`0. New repo or first time here: \`${g("init --json")}\` does steps 1 to 3 in one run: it activates the packs, installs the strongest set of constraints, writes the ratchet baseline (\`.guardrails/baseline.json\`) and AGENTS.md, and ends with \`next[]\`, the steps for you. \`--dry-run\` shows what it would do; it never overwrites your files and backs up what it edits in \`.guardrails/backup/\`.`,
|
|
12
|
+
`1. \`${g("detect --json")}\`: read the repo and write \`.guardrails/profile.json\`.`,
|
|
13
|
+
`2. \`${g("plan --json")}\`: list gaps against the constraint catalog (\`items[].status\` is \`gap\`, \`installed\` or \`not-applicable\`). If \`install\` is set, run that command first.`,
|
|
14
|
+
`3. \`${g("apply <id> --json")}\` for each gap, in plan order. It installs the rule, hook or workflow and verifies it. Rules start at \`warn\` if the repo already violates them and move to \`error\` once violations reach 0.`,
|
|
15
|
+
`4. \`${g("check --json")}\`: after every change (inside a task, \`${g("check <paths...> --json")}\` on just your files). Fix every entry in \`diagnostics[]\` (\`file\`, \`line\`, \`rule\`, \`message\`, \`fix\`) and run it again until \`verdict\` is \`clean\` (or \`debt\`: only warnings inside the baseline remain). The ratchet: a rule at warn may have at most the baseline count of violations, it can only go down, and at 0 it moves to error by itself. More than the baseline is an error \`ratchet/<rule>\`.`,
|
|
16
|
+
`5. \`${g("audit --json")}\` (or \`${g("self-check --json")}\` for check + audit with eslint and tsc run once): metrics (violations, \`eslint-disable\` without reason, rules at warn, branch protection).`,
|
|
17
|
+
`6. \`${g('add-rule <name> --message "<how to fix>" --selector "<esquery>" --bad "<code>" --good "<code>" --json')}\`: when you were corrected for a mistake a rule could catch, turn the correction into a rule plus test. Clean existing violations to 0, then \`add-rule <name> --promote\`.`,
|
|
18
|
+
`7. \`${g("learn --json")}\`: proposes new constraints and rules from your check history, fix commits, review comments and CI failures. Run it after a stretch of work and apply what it proposes with \`apply <id>\` or \`add-rule\`.`,
|
|
19
|
+
"",
|
|
20
|
+
"### Exit codes",
|
|
21
|
+
"",
|
|
22
|
+
"| code | meaning |",
|
|
23
|
+
"| --- | --- |",
|
|
24
|
+
"| 0 | ok / clean |",
|
|
25
|
+
"| 1 | findings: fix the diagnostics or violations reported |",
|
|
26
|
+
"| 2 | usage error: fix the command |",
|
|
27
|
+
"| 3 | precondition, conflict or missing dependency: read `error.fix` |",
|
|
28
|
+
"| 4 | verification failed after installing: read `checks[]` and `error.fix` |",
|
|
29
|
+
"",
|
|
30
|
+
"Errors in JSON look like `{ ok: false, error: { code, message, file, rule, fix } }`: change `file` as `fix` says.",
|
|
31
|
+
];
|
|
32
|
+
}
|
|
33
|
+
function performanceSection(g) {
|
|
34
|
+
return [
|
|
35
|
+
"### Performance: one heavy run per machine",
|
|
36
|
+
"",
|
|
37
|
+
"`check`, `audit` and `self-check` run eslint and tsc over the repo. Many agents doing that at once froze a laptop, so the CLI serializes them without you doing anything: a lock per machine and per repo (in the user cache dir, with the pid, so a crashed run frees it), a result cache keyed by the content of the tree, tsc in incremental mode and a memory cap on the child processes.",
|
|
38
|
+
"",
|
|
39
|
+
`- Validate your own folder, not the repo: \`${g("check <paths...> --json")}\` lints only those files and keeps the tsc errors that are in those paths. Use the full \`check\` once, before the PR.`,
|
|
40
|
+
"- If stderr says `otra corrida en curso en <repo>, esperando`, another run holds the lock. Do not start another one, do not kill it, do not run eslint or tsc by hand: wait, the command returns by itself. When it finishes and nothing changed, the answer comes from the cache (`cached: true` in the JSON).",
|
|
41
|
+
"- Never pass `--incremental false` to tsc and never run `tsc` or `eslint` over the whole repo yourself: use the commands above.",
|
|
42
|
+
"- `--no-cache` forces a fresh run. `--lock-timeout <seconds>` (or `GUARDRAILS_LOCK_TIMEOUT_MS`, default 600000) sets how long to wait before failing with `error[busy]` (exit 3: wait and run again, do not loop). `GUARDRAILS_MAX_JOBS` (default 1) is the number of heavy runs per machine and `GUARDRAILS_MAX_OLD_SPACE_MB` (default 2048) caps the memory of the child processes.",
|
|
43
|
+
];
|
|
44
|
+
}
|
|
45
|
+
function prLoopSection(g, base) {
|
|
46
|
+
return [
|
|
47
|
+
"### PR loop: CI answers, you fix",
|
|
48
|
+
"",
|
|
49
|
+
"Tests run in CI (Vitest, or Jest with jest-expo on React Native), not on your machine unless the user asks. A changed logic file needs a `.test` next to it (components and styles are exempt) and line coverage only goes up: the floor lives in `.guardrails/baseline.json`.",
|
|
50
|
+
"",
|
|
51
|
+
`1. Open the PR into \`${base}\` and push. CI runs lint, typecheck, tests and \`check\`, then the \`status\` job posts one PR comment (updated in place) with the diagnostics JSON, uploads it as the \`guardrails-diagnostics\` artifact and sets the required \`status\` check.`,
|
|
52
|
+
`2. \`${g("pr-repair --wait --json")}\`: waits for the checks, then returns \`failing[].diagnostics[]\` (\`check\`, \`file\`, \`line\`, \`rule\` or \`test\`, \`message\`, \`fix\`) and \`attempts\` (\`used\`, \`left\`). \`pr-status\` is the same read-only view.`,
|
|
53
|
+
`3. Fix every entry, run \`${g("check --json")}\` until \`verdict\` is \`clean\`, commit, push, and run \`pr-repair --wait\` again.`,
|
|
54
|
+
"4. Repeat until `verdict` is `green`, then `gh pr merge --auto --squash`.",
|
|
55
|
+
"5. `verdict` `escalate` (exit 3) means 3 repair pushes did not turn the PR green: stop, do not try a fourth, and ask the user for help with `failing[]`.",
|
|
56
|
+
];
|
|
57
|
+
}
|
|
58
|
+
function rulesSection(base) {
|
|
59
|
+
return [
|
|
60
|
+
"### Rules for you",
|
|
61
|
+
"",
|
|
62
|
+
"- Do not silence a failing check: no suppression comments (`eslint-disable`, `@ts-ignore`), no `any`, no `--no-verify`, no lowering a rule from `error` to `warn`. Change the code until the check passes.",
|
|
63
|
+
"- A rule you cannot satisfy is a rule to discuss with the user, not to bypass.",
|
|
64
|
+
`- Always work on a branch \`type/kebab-case\` and open a PR into \`${base}\`. Never push to \`${base}\`; never force-push.`,
|
|
65
|
+
"- Merge only through `gh pr merge --auto --squash`: it waits for every required check to be green.",
|
|
66
|
+
`- If \`${base}\` breaks, revert with the rollback workflow (\`gh workflow run guardrails-rollback.yml -f sha=<sha>\`) instead of patching forward.`,
|
|
67
|
+
"",
|
|
68
|
+
"### Layers, closest to you first",
|
|
69
|
+
"",
|
|
70
|
+
"1. Claude hook (`.claude/hooks/guardrails-check.sh`): linters and typechecks after every edit; its stderr is the fix list.",
|
|
71
|
+
"2. `.githooks/pre-commit`: linters on staged files and typechecks.",
|
|
72
|
+
"3. `.githooks/commit-msg`: Conventional Commits.",
|
|
73
|
+
"4. CI (`.github/workflows/guardrails-ci.yml`): blocking linters, typechecks, tests, build and `guardrails check --json`.",
|
|
74
|
+
];
|
|
75
|
+
}
|
|
76
|
+
function packsSection(profile, packs) {
|
|
77
|
+
return [
|
|
78
|
+
"### Packs",
|
|
79
|
+
"",
|
|
80
|
+
"The core (detect, plan, apply, check, audit, add-rule) knows no language: it asks the active packs for constraints, tools, hooks and CI steps. Active here: " +
|
|
81
|
+
profile.packs.map((active) => `\`${active.id}\` (confidence ${active.confidence})`).join(", ") +
|
|
82
|
+
". Packs stack through `extends`; each declares its own constraint catalog.",
|
|
83
|
+
...packs.map((pack) => `- \`${pack.id}\`: ${pack.title}`),
|
|
84
|
+
];
|
|
85
|
+
}
|
|
86
|
+
const NEW_PACK_SECTION = [
|
|
87
|
+
"### Adding a pack for another language (Python, Go)",
|
|
88
|
+
"",
|
|
89
|
+
"A new ecosystem is one folder, `src/packs/<id>/`, that exports a `Pack` (`src/core/domain/pack.ts`) and one line in `src/packs/index.ts`. `detect(facts)` returns a confidence from the files named in `probe` (`pyproject.toml`, `go.mod`) and `profile(facts)` returns the facts the rest of the pack needs. `constraints` is the pack's own catalog (ruff or golangci-lint rules, mypy strict or `go vet`, an immutability rule, a layer-limit rule), each with `install`, `verify` and a test. `tools` names the linter, typecheck, formatter and test adapters, and `analyze` runs them and returns diagnostics in the shared `{ file, line, rule, message, fix }` shape. `commands` says how to install and run things (`uv add --dev`, `go install`), `hooks` supplies the shell fragments for pre-commit and the Claude edit hook, and `ci` supplies the setup and check steps and the Dependabot ecosystem.",
|
|
90
|
+
"",
|
|
91
|
+
"The core never imports a pack, so adding one cannot break another: `import-boundaries` enforces it. Reuse a base pack with `extends` (a Django pack would extend `python`) so shared constraints are declared once, and keep `domain` pure with I/O in `infra`, as every pack does. Nothing in `src/core` changes: `detect` activates the pack when its confidence is at least 0.5, `plan` and `apply` list its constraints, and `check` and `audit` run its `analyze`. This is documented, not implemented: there is no Python or Go pack in the repo.",
|
|
92
|
+
];
|
|
93
|
+
export function renderAgentsBlock(profile, packs, g) {
|
|
94
|
+
return [BLOCK_START, ...flowSection(g), "", ...performanceSection(g), "", ...prLoopSection(g, profile.git.baseBranch), "", ...packsSection(profile, packs), "", ...NEW_PACK_SECTION, "", ...rulesSection(profile.git.baseBranch), BLOCK_END, ""].join("\n");
|
|
95
|
+
}
|
|
96
|
+
export function mergeAgentsMd(existing, block) {
|
|
97
|
+
if (existing === null || existing.trim() === "")
|
|
98
|
+
return `# AGENTS.md\n\n${block}`;
|
|
99
|
+
const start = existing.indexOf(BLOCK_START);
|
|
100
|
+
const end = existing.indexOf(BLOCK_END);
|
|
101
|
+
if (start !== -1 && end > start)
|
|
102
|
+
return `${existing.slice(0, start)}${block}${existing.slice(end + BLOCK_END.length).replace(/^\n/, "")}`;
|
|
103
|
+
return `${existing.trimEnd()}\n\n${block}`;
|
|
104
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export function failingReasons(input) {
|
|
2
|
+
return [
|
|
3
|
+
...input.packFailing,
|
|
4
|
+
...(input.protection.status === "missing" ? [`base branch protection incomplete: ${input.protection.missing.join(", ")}`] : []),
|
|
5
|
+
...(input.notInstalled > 0 ? [`${input.notInstalled} constraints not installed (guardrails plan)`] : []),
|
|
6
|
+
];
|
|
7
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
const RANK = { created: 2, updated: 1, unchanged: 0 };
|
|
2
|
+
export function mergeChanges(changes) {
|
|
3
|
+
const byPath = changes.reduce((merged, change) => {
|
|
4
|
+
const current = merged[change.path];
|
|
5
|
+
return current !== undefined && RANK[current.action] >= RANK[change.action] ? merged : { ...merged, [change.path]: change };
|
|
6
|
+
}, {});
|
|
7
|
+
return Object.values(byPath);
|
|
8
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export const DIAGNOSTIC_LIMIT = 200;
|
|
2
|
+
export function summarize(diagnostics) {
|
|
3
|
+
const byTool = diagnostics.reduce((acc, item) => ({ ...acc, [item.tool]: (acc[item.tool] ?? 0) + 1 }), {});
|
|
4
|
+
return {
|
|
5
|
+
total: diagnostics.length,
|
|
6
|
+
errors: diagnostics.filter((item) => item.severity === "error").length,
|
|
7
|
+
warnings: diagnostics.filter((item) => item.severity === "warn").length,
|
|
8
|
+
byTool,
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
export function mergeAnalyses(analyses) {
|
|
12
|
+
return { diagnostics: analyses.flatMap((item) => item.diagnostics), skipped: analyses.flatMap((item) => item.skipped), ran: analyses.some((item) => item.ran) };
|
|
13
|
+
}
|
|
14
|
+
export function renderCheckText(shown, summary, truncated, skipped) {
|
|
15
|
+
if (summary.errors === 0 && summary.total > 0)
|
|
16
|
+
return [...shown.map((item) => `${item.file}:${item.line}:${item.column} warn [${item.rule}] ${item.message}`), `deuda dentro del baseline: ${summary.warnings} avisos; no pueden aumentar`].join("\n");
|
|
17
|
+
if (summary.total === 0)
|
|
18
|
+
return `todo bien: sin violaciones${skipped.length > 0 ? ` (omitido: ${skipped.map((item) => item.tool).join(", ")})` : ""}`;
|
|
19
|
+
return [
|
|
20
|
+
...shown.flatMap((item) => [`${item.file}:${item.line}:${item.column} ${item.severity} [${item.rule}] ${item.message}`, ` fix: ${item.fix}`]),
|
|
21
|
+
`arregla esto: ${summary.errors} errores, ${summary.warnings} avisos${truncated ? ` (mostrando ${DIAGNOSTIC_LIMIT})` : ""}`,
|
|
22
|
+
].join("\n");
|
|
23
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { objectAt } from "./json.js";
|
|
2
|
+
export const HOOK_PATH = ".claude/hooks/guardrails-check.sh";
|
|
3
|
+
export const SETTINGS_PATH = ".claude/settings.json";
|
|
4
|
+
const HOOK_COMMAND = `"$CLAUDE_PROJECT_DIR"/${HOOK_PATH}`;
|
|
5
|
+
export const DENY_BYPASS = Object.freeze([
|
|
6
|
+
"Bash(git commit *--no-verify*)",
|
|
7
|
+
"Bash(git push *--no-verify*)",
|
|
8
|
+
"Bash(git push --force*)",
|
|
9
|
+
"Bash(git push -f*)",
|
|
10
|
+
"Bash(git push * --force*)",
|
|
11
|
+
"Bash(git push * -f*)",
|
|
12
|
+
"Bash(git push *--force-with-lease*)",
|
|
13
|
+
"Bash(git push origin main*)",
|
|
14
|
+
"Bash(git push * main*)",
|
|
15
|
+
"Bash(git push origin master*)",
|
|
16
|
+
"Bash(git push * master*)",
|
|
17
|
+
"Bash(git config core.hooksPath*)",
|
|
18
|
+
"Bash(git config * core.hooksPath*)",
|
|
19
|
+
]);
|
|
20
|
+
function postToolUse(settings) {
|
|
21
|
+
const list = objectAt(settings, "hooks")["PostToolUse"];
|
|
22
|
+
return Array.isArray(list) ? list : [];
|
|
23
|
+
}
|
|
24
|
+
export function hasCheckHook(settings) {
|
|
25
|
+
return settings !== null && JSON.stringify(postToolUse(settings)).includes("guardrails-check.sh");
|
|
26
|
+
}
|
|
27
|
+
export function withCheckHook(settings) {
|
|
28
|
+
if (hasCheckHook(settings))
|
|
29
|
+
return settings;
|
|
30
|
+
const entry = { matcher: "Edit|Write|MultiEdit", hooks: [{ type: "command", command: HOOK_COMMAND, timeout: 180, statusMessage: "guardrails: lint + typecheck" }] };
|
|
31
|
+
return { ...settings, hooks: { ...objectAt(settings, "hooks"), PostToolUse: [...postToolUse(settings), entry] } };
|
|
32
|
+
}
|
|
33
|
+
export function denyList(settings) {
|
|
34
|
+
if (settings === null)
|
|
35
|
+
return [];
|
|
36
|
+
const deny = objectAt(settings, "permissions")["deny"];
|
|
37
|
+
return Array.isArray(deny) ? deny.filter((item) => typeof item === "string") : [];
|
|
38
|
+
}
|
|
39
|
+
export function withDeny(settings) {
|
|
40
|
+
const current = denyList(settings);
|
|
41
|
+
return { ...settings, permissions: { ...objectAt(settings, "permissions"), deny: [...current, ...DENY_BYPASS.filter((entry) => !current.includes(entry))] } };
|
|
42
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export const EXIT = Object.freeze({ ok: 0, findings: 1, usage: 2, precondition: 3, verify: 4 });
|
|
2
|
+
const EXIT_BY_CODE = Object.freeze({
|
|
3
|
+
usage: EXIT.usage,
|
|
4
|
+
"unknown-constraint": EXIT.usage,
|
|
5
|
+
"invalid-name": EXIT.usage,
|
|
6
|
+
"no-pack": EXIT.precondition,
|
|
7
|
+
"unknown-pack": EXIT.precondition,
|
|
8
|
+
"not-applicable": EXIT.precondition,
|
|
9
|
+
conflict: EXIT.precondition,
|
|
10
|
+
"missing-dependency": EXIT.precondition,
|
|
11
|
+
"unsupported-config": EXIT.precondition,
|
|
12
|
+
busy: EXIT.precondition,
|
|
13
|
+
"verify-failed": EXIT.verify,
|
|
14
|
+
internal: EXIT.verify,
|
|
15
|
+
});
|
|
16
|
+
export function appError(code, message, details) {
|
|
17
|
+
return { code, message, ...details };
|
|
18
|
+
}
|
|
19
|
+
export function exitCodeOf(code) {
|
|
20
|
+
return EXIT_BY_CODE[code];
|
|
21
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export const CORE_PROBE = {
|
|
2
|
+
paths: [".claude", ".claude/settings.json", "AGENTS.md"],
|
|
3
|
+
json: [],
|
|
4
|
+
text: [],
|
|
5
|
+
tree: [],
|
|
6
|
+
};
|
|
7
|
+
export function mergeProbes(probes) {
|
|
8
|
+
const union = (pick) => [...new Set(probes.flatMap(pick))];
|
|
9
|
+
return {
|
|
10
|
+
paths: union((probe) => probe.paths),
|
|
11
|
+
json: union((probe) => probe.json),
|
|
12
|
+
text: union((probe) => probe.text),
|
|
13
|
+
tree: probes.flatMap((probe) => probe.tree),
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
export function hasPath(facts, path) {
|
|
17
|
+
return facts.present.includes(path);
|
|
18
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export function debtTotal(debt) {
|
|
2
|
+
return Object.values(debt).reduce((sum, count) => sum + count, 0);
|
|
3
|
+
}
|
|
4
|
+
export function nextSteps(summary) {
|
|
5
|
+
const debtRules = Object.entries(summary.debt).filter(([, count]) => count > 0).toSorted((a, b) => b[1] - a[1]);
|
|
6
|
+
return [
|
|
7
|
+
...(summary.install === null ? [] : [`install the missing packages, then run \`guardrails init\` again: ${summary.install}`]),
|
|
8
|
+
...summary.blocked.map((item) => `${item.id}: ${item.fix}`),
|
|
9
|
+
...summary.deferred.flatMap((item) => item.notes),
|
|
10
|
+
...(summary.errors > 0 ? [`fix the ${String(summary.errors)} errors (type errors or violations of rules at error): \`guardrails check --json\``] : []),
|
|
11
|
+
...(debtRules.length > 0 ? [`pay down debt, biggest first: ${debtRules.slice(0, 5).map(([rule, count]) => `${rule} (${String(count)})`).join(", ")}. A rule moves to error on its own when it reaches 0.`] : []),
|
|
12
|
+
"commit the result on a branch `type/kebab-case`, open a PR, and run `guardrails check --json` after every change",
|
|
13
|
+
"apply the repo ruleset when the owner agrees: `sh .guardrails/github/branch-protection.sh` (init never runs it)",
|
|
14
|
+
];
|
|
15
|
+
}
|
|
16
|
+
export function renderInitText(summary, steps) {
|
|
17
|
+
return [
|
|
18
|
+
`packs: ${summary.packs.join(", ")}`,
|
|
19
|
+
`installed ${String(summary.applied.length)} constraints (${String(summary.alreadyInstalled)} already there, ${String(summary.notApplicable)} not applicable)`,
|
|
20
|
+
...summary.applied.filter((item) => item.level === "warn").map((item) => ` warn: ${item.id} (baseline set, can only go down)`),
|
|
21
|
+
...summary.deferred.map((item) => ` deferred: ${item.id}`),
|
|
22
|
+
...summary.blocked.map((item) => ` blocked: ${item.id}: ${item.reason}`),
|
|
23
|
+
`debt: ${String(debtTotal(summary.debt))} violations in ${String(Object.keys(summary.debt).length)} rules at warn; errors: ${String(summary.errors)}`,
|
|
24
|
+
...(summary.backups.length > 0 ? [`backups of edited files: ${summary.backups.join(", ")}`] : []),
|
|
25
|
+
"next:",
|
|
26
|
+
...steps.map((step, index) => ` ${String(index + 1)}. ${step}`),
|
|
27
|
+
].join("\n");
|
|
28
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { err, fromThrowing, ok } from "./result.js";
|
|
2
|
+
const COMMENT_OR_STRING = /("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g;
|
|
3
|
+
const TRAILING_COMMA = /,(\s*[}\]])/g;
|
|
4
|
+
export function stripJsonComments(source) {
|
|
5
|
+
return source.replace(COMMENT_OR_STRING, (_match, quoted) => quoted ?? "").replace(TRAILING_COMMA, "$1");
|
|
6
|
+
}
|
|
7
|
+
export function isRecord(value) {
|
|
8
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
9
|
+
}
|
|
10
|
+
export function parseStrictJson(source) {
|
|
11
|
+
return fromThrowing(() => JSON.parse(source), (cause) => (cause instanceof Error ? cause.message : "invalid JSON"));
|
|
12
|
+
}
|
|
13
|
+
export function parseJsonc(source) {
|
|
14
|
+
const parsed = parseStrictJson(stripJsonComments(source));
|
|
15
|
+
return parsed.ok ? parsed.value : null;
|
|
16
|
+
}
|
|
17
|
+
export function parseJsoncRecord(source) {
|
|
18
|
+
const parsed = parseJsonc(source);
|
|
19
|
+
return isRecord(parsed) ? parsed : null;
|
|
20
|
+
}
|
|
21
|
+
export function stringifyJson(value) {
|
|
22
|
+
return `${JSON.stringify(value, null, 2)}\n`;
|
|
23
|
+
}
|
|
24
|
+
export function stringifyWithIndent(value, indent) {
|
|
25
|
+
return `${JSON.stringify(value, null, indent)}\n`;
|
|
26
|
+
}
|
|
27
|
+
export function detectIndent(raw) {
|
|
28
|
+
return /^([ \t]+)"/m.exec(raw)?.[1] ?? " ";
|
|
29
|
+
}
|
|
30
|
+
export function objectAt(value, key) {
|
|
31
|
+
const found = value[key];
|
|
32
|
+
return isRecord(found) ? found : {};
|
|
33
|
+
}
|
|
34
|
+
export function stringArrayAt(value, key) {
|
|
35
|
+
const found = value[key];
|
|
36
|
+
return Array.isArray(found) ? found.filter((item) => typeof item === "string") : [];
|
|
37
|
+
}
|
|
38
|
+
export function parseRecordStrict(source) {
|
|
39
|
+
const parsed = parseStrictJson(source);
|
|
40
|
+
if (!parsed.ok)
|
|
41
|
+
return parsed;
|
|
42
|
+
return isRecord(parsed.value) ? ok(parsed.value) : err("not a JSON object");
|
|
43
|
+
}
|