@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.
Files changed (141) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +208 -2
  3. package/catalog-assets/claude-hooks/guardrails-check.sh +37 -0
  4. package/catalog-assets/eslint-guardrails/config.mjs +21 -0
  5. package/catalog-assets/eslint-rules/_rule-tester.mjs +21 -0
  6. package/catalog-assets/eslint-rules/cache-policy-constant.mjs +35 -0
  7. package/catalog-assets/eslint-rules/client-imports-server.mjs +26 -0
  8. package/catalog-assets/eslint-rules/effects-in-hooks.mjs +46 -0
  9. package/catalog-assets/eslint-rules/env-through-config.mjs +26 -0
  10. package/catalog-assets/eslint-rules/hook-body-order.mjs +169 -0
  11. package/catalog-assets/eslint-rules/import-boundaries.mjs +97 -0
  12. package/catalog-assets/eslint-rules/no-comments.mjs +35 -0
  13. package/catalog-assets/eslint-rules/no-default-export.mjs +20 -0
  14. package/catalog-assets/eslint-rules/no-delete.mjs +16 -0
  15. package/catalog-assets/eslint-rules/no-enum.mjs +14 -0
  16. package/catalog-assets/eslint-rules/no-heavy-inline-styles.mjs +20 -0
  17. package/catalog-assets/eslint-rules/no-let.mjs +14 -0
  18. package/catalog-assets/eslint-rules/no-logic-in-jsx.mjs +23 -0
  19. package/catalog-assets/eslint-rules/no-manual-memoization.mjs +45 -0
  20. package/catalog-assets/eslint-rules/no-member-assignment.mjs +28 -0
  21. package/catalog-assets/eslint-rules/no-module-cache.mjs +40 -0
  22. package/catalog-assets/eslint-rules/no-mutating-array-methods.mjs +85 -0
  23. package/catalog-assets/eslint-rules/no-process-exit.mjs +15 -0
  24. package/catalog-assets/eslint-rules/no-state-mutation.mjs +62 -0
  25. package/catalog-assets/eslint-rules/no-unnecessary-use-client.mjs +40 -0
  26. package/catalog-assets/eslint-rules/pure-components.mjs +48 -0
  27. package/catalog-assets/eslint-rules/query-key-constant.mjs +54 -0
  28. package/catalog-assets/eslint-rules/require-disable-reason.mjs +29 -0
  29. package/catalog-assets/eslint-rules/restrict-timers.mjs +35 -0
  30. package/catalog-assets/eslint-rules/rules-of-hooks.mjs +51 -0
  31. package/catalog-assets/eslint-rules/thin-api-routes.mjs +18 -0
  32. package/catalog-assets/eslint-rules/thin-routes.mjs +18 -0
  33. package/catalog-assets/eslint-rules/virtualized-lists.mjs +32 -0
  34. package/catalog-assets/githooks/commit-msg +13 -0
  35. package/catalog-assets/githooks/pre-commit +26 -0
  36. package/catalog-assets/scripts/check-exact-deps.mjs +26 -0
  37. package/dist/cli.js +54 -0
  38. package/dist/core/app/analysis.js +6 -0
  39. package/dist/core/app/args.js +44 -0
  40. package/dist/core/app/catalog.js +20 -0
  41. package/dist/core/app/ci-plan.js +14 -0
  42. package/dist/core/app/claude.js +37 -0
  43. package/dist/core/app/commands/add-rule.js +32 -0
  44. package/dist/core/app/commands/agents-md.js +13 -0
  45. package/dist/core/app/commands/apply.js +74 -0
  46. package/dist/core/app/commands/audit.js +38 -0
  47. package/dist/core/app/commands/check.js +33 -0
  48. package/dist/core/app/commands/detect.js +16 -0
  49. package/dist/core/app/commands/init.js +124 -0
  50. package/dist/core/app/commands/learn.js +48 -0
  51. package/dist/core/app/commands/plan.js +40 -0
  52. package/dist/core/app/commands/pr-status.js +66 -0
  53. package/dist/core/app/commands/self-check.js +17 -0
  54. package/dist/core/app/git.js +75 -0
  55. package/dist/core/app/github.js +146 -0
  56. package/dist/core/app/hooks-script.js +27 -0
  57. package/dist/core/app/output.js +17 -0
  58. package/dist/core/app/run.js +32 -0
  59. package/dist/core/app/session.js +18 -0
  60. package/dist/core/app/timing.js +11 -0
  61. package/dist/core/domain/agents-md.js +92 -0
  62. package/dist/core/domain/audit-report.js +7 -0
  63. package/dist/core/domain/changes.js +8 -0
  64. package/dist/core/domain/check-report.js +23 -0
  65. package/dist/core/domain/claude-settings.js +42 -0
  66. package/dist/core/domain/constraint.js +7 -0
  67. package/dist/core/domain/diagnostics.js +3 -0
  68. package/dist/core/domain/errors.js +20 -0
  69. package/dist/core/domain/facts.js +18 -0
  70. package/dist/core/domain/init-report.js +28 -0
  71. package/dist/core/domain/json.js +43 -0
  72. package/dist/core/domain/learn.js +78 -0
  73. package/dist/core/domain/log-parse.js +99 -0
  74. package/dist/core/domain/pack-defaults.js +17 -0
  75. package/dist/core/domain/pack.js +1 -0
  76. package/dist/core/domain/pr-comment.js +45 -0
  77. package/dist/core/domain/pr-loop.js +85 -0
  78. package/dist/core/domain/profile.js +25 -0
  79. package/dist/core/domain/protection.js +43 -0
  80. package/dist/core/domain/ratchet.js +40 -0
  81. package/dist/core/domain/registry.js +32 -0
  82. package/dist/core/domain/remote.js +4 -0
  83. package/dist/core/domain/result.js +25 -0
  84. package/dist/core/domain/thresholds.js +9 -0
  85. package/dist/core/domain/types.js +1 -0
  86. package/dist/core/domain/workflows.js +252 -0
  87. package/dist/core/infra/assets.js +7 -0
  88. package/dist/core/infra/backup.js +31 -0
  89. package/dist/core/infra/baseline.js +8 -0
  90. package/dist/core/infra/changes.js +17 -0
  91. package/dist/core/infra/exec.js +14 -0
  92. package/dist/core/infra/facts.js +61 -0
  93. package/dist/core/infra/fs.js +87 -0
  94. package/dist/core/infra/gh.js +32 -0
  95. package/dist/core/infra/hooks.js +31 -0
  96. package/dist/core/infra/learn-sources.js +40 -0
  97. package/dist/core/infra/pr.js +48 -0
  98. package/dist/packs/index.js +6 -0
  99. package/dist/packs/js-ts/app/add-rule.js +116 -0
  100. package/dist/packs/js-ts/app/analysis.js +104 -0
  101. package/dist/packs/js-ts/app/bootstrap.js +16 -0
  102. package/dist/packs/js-ts/app/eslint-constraints.js +155 -0
  103. package/dist/packs/js-ts/app/eslint-files.js +56 -0
  104. package/dist/packs/js-ts/app/fixes.js +3 -0
  105. package/dist/packs/js-ts/app/pr-rules.js +30 -0
  106. package/dist/packs/js-ts/app/project.js +87 -0
  107. package/dist/packs/js-ts/app/tests.js +63 -0
  108. package/dist/packs/js-ts/domain/catalog-specs.js +147 -0
  109. package/dist/packs/js-ts/domain/ci.js +47 -0
  110. package/dist/packs/js-ts/domain/data.js +34 -0
  111. package/dist/packs/js-ts/domain/diagnostics-js.js +17 -0
  112. package/dist/packs/js-ts/domain/disables.js +11 -0
  113. package/dist/packs/js-ts/domain/eslint-output.js +46 -0
  114. package/dist/packs/js-ts/domain/eslint-state.js +80 -0
  115. package/dist/packs/js-ts/domain/hooks.js +49 -0
  116. package/dist/packs/js-ts/domain/pr-diagnostics.js +33 -0
  117. package/dist/packs/js-ts/domain/pr-tests.js +27 -0
  118. package/dist/packs/js-ts/domain/profile-pure.js +51 -0
  119. package/dist/packs/js-ts/domain/profile.js +112 -0
  120. package/dist/packs/js-ts/domain/report.js +74 -0
  121. package/dist/packs/js-ts/domain/rule-templates.js +44 -0
  122. package/dist/packs/js-ts/domain/signals.js +14 -0
  123. package/dist/packs/js-ts/domain/testing.js +33 -0
  124. package/dist/packs/js-ts/domain/ts-options.js +13 -0
  125. package/dist/packs/js-ts/index.js +50 -0
  126. package/dist/packs/js-ts/infra/eslint.js +50 -0
  127. package/dist/packs/js-ts/infra/scan.js +25 -0
  128. package/dist/packs/js-ts/infra/tsc.js +21 -0
  129. package/dist/packs/nextjs/domain/data.js +9 -0
  130. package/dist/packs/nextjs/domain/profile.js +21 -0
  131. package/dist/packs/nextjs/domain/specs.js +33 -0
  132. package/dist/packs/nextjs/index.js +23 -0
  133. package/dist/packs/node/domain/specs.js +23 -0
  134. package/dist/packs/node/index.js +26 -0
  135. package/dist/packs/react/domain/data.js +9 -0
  136. package/dist/packs/react/domain/specs.js +63 -0
  137. package/dist/packs/react/index.js +30 -0
  138. package/dist/packs/react-native/domain/specs.js +29 -0
  139. package/dist/packs/react-native/domain/testing.js +20 -0
  140. package/dist/packs/react-native/index.js +30 -0
  141. package/package.json +60 -4
@@ -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,92 @@
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. 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, in parallel): 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 prLoopSection(g, base) {
34
+ return [
35
+ "### PR loop: CI answers, you fix",
36
+ "",
37
+ "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`.",
38
+ "",
39
+ `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.`,
40
+ `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.`,
41
+ `3. Fix every entry, run \`${g("check --json")}\` until \`verdict\` is \`clean\`, commit, push, and run \`pr-repair --wait\` again.`,
42
+ "4. Repeat until `verdict` is `green`, then `gh pr merge --auto --squash`.",
43
+ "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[]`.",
44
+ ];
45
+ }
46
+ function rulesSection(base) {
47
+ return [
48
+ "### Rules for you",
49
+ "",
50
+ "- 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.",
51
+ "- A rule you cannot satisfy is a rule to discuss with the user, not to bypass.",
52
+ `- Always work on a branch \`type/kebab-case\` and open a PR into \`${base}\`. Never push to \`${base}\`; never force-push.`,
53
+ "- Merge only through `gh pr merge --auto --squash`: it waits for every required check to be green.",
54
+ `- If \`${base}\` breaks, revert with the rollback workflow (\`gh workflow run guardrails-rollback.yml -f sha=<sha>\`) instead of patching forward.`,
55
+ "",
56
+ "### Layers, closest to you first",
57
+ "",
58
+ "1. Claude hook (`.claude/hooks/guardrails-check.sh`): linters and typechecks after every edit; its stderr is the fix list.",
59
+ "2. `.githooks/pre-commit`: linters on staged files and typechecks.",
60
+ "3. `.githooks/commit-msg`: Conventional Commits.",
61
+ "4. CI (`.github/workflows/guardrails-ci.yml`): blocking linters, typechecks, tests, build and `guardrails check --json`.",
62
+ ];
63
+ }
64
+ function packsSection(profile, packs) {
65
+ return [
66
+ "### Packs",
67
+ "",
68
+ "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: " +
69
+ profile.packs.map((active) => `\`${active.id}\` (confidence ${active.confidence})`).join(", ") +
70
+ ". Packs stack through `extends`; each declares its own constraint catalog.",
71
+ ...packs.map((pack) => `- \`${pack.id}\`: ${pack.title}`),
72
+ ];
73
+ }
74
+ const NEW_PACK_SECTION = [
75
+ "### Adding a pack for another language (Python, Go)",
76
+ "",
77
+ "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.",
78
+ "",
79
+ "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.",
80
+ ];
81
+ export function renderAgentsBlock(profile, packs, g) {
82
+ return [BLOCK_START, ...flowSection(g), "", ...prLoopSection(g, profile.git.baseBranch), "", ...packsSection(profile, packs), "", ...NEW_PACK_SECTION, "", ...rulesSection(profile.git.baseBranch), BLOCK_END, ""].join("\n");
83
+ }
84
+ export function mergeAgentsMd(existing, block) {
85
+ if (existing === null || existing.trim() === "")
86
+ return `# AGENTS.md\n\n${block}`;
87
+ const start = existing.indexOf(BLOCK_START);
88
+ const end = existing.indexOf(BLOCK_END);
89
+ if (start !== -1 && end > start)
90
+ return `${existing.slice(0, start)}${block}${existing.slice(end + BLOCK_END.length).replace(/^\n/, "")}`;
91
+ return `${existing.trimEnd()}\n\n${block}`;
92
+ }
@@ -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,7 @@
1
+ import { ok } from "./result.js";
2
+ export function outcome(changes, notes = []) {
3
+ return { changes, notes, violations: [], levels: {} };
4
+ }
5
+ export function installed(changes, notes = []) {
6
+ return ok(outcome(changes, notes));
7
+ }
@@ -0,0 +1,3 @@
1
+ export function capped(items, limit) {
2
+ return { items: items.slice(0, limit), truncated: items.length > limit };
3
+ }
@@ -0,0 +1,20 @@
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
+ "verify-failed": EXIT.verify,
13
+ internal: EXIT.verify,
14
+ });
15
+ export function appError(code, message, details) {
16
+ return { code, message, ...details };
17
+ }
18
+ export function exitCodeOf(code) {
19
+ return EXIT_BY_CODE[code];
20
+ }
@@ -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
+ }
@@ -0,0 +1,78 @@
1
+ import { THRESHOLDS } from "./thresholds.js";
2
+ export const HISTORY_PATH = ".guardrails/history.jsonl";
3
+ export const HISTORY_LIMIT = 200;
4
+ export const RECURRING_MIN_RUNS = THRESHOLDS.recurringRuns.value;
5
+ export function parseHistory(text) {
6
+ return (text ?? "").split("\n").flatMap((line) => {
7
+ if (line.trim() === "")
8
+ return [];
9
+ const parsed = safeParse(line);
10
+ return isRecord(parsed) && typeof parsed["at"] === "string" && isRecord(parsed["rules"]) ? [{ at: parsed["at"], rules: numericRecord(parsed["rules"]) }] : [];
11
+ });
12
+ }
13
+ function isRecord(value) {
14
+ return typeof value === "object" && value !== null && !Array.isArray(value);
15
+ }
16
+ function safeParse(line) {
17
+ try {
18
+ return JSON.parse(line);
19
+ }
20
+ catch {
21
+ return null;
22
+ }
23
+ }
24
+ function numericRecord(value) {
25
+ return Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "number"));
26
+ }
27
+ export function appendHistory(records, next) {
28
+ return [...records, next].slice(-HISTORY_LIMIT);
29
+ }
30
+ export function serializeHistory(records) {
31
+ return `${records.map((record) => JSON.stringify(record)).join("\n")}\n`;
32
+ }
33
+ export function recurringRules(records) {
34
+ const names = [...new Set(records.flatMap((record) => Object.keys(record.rules)))];
35
+ return names
36
+ .map((rule) => ({ rule, runs: records.filter((record) => (record.rules[rule] ?? 0) > 0).length }))
37
+ .filter((entry) => entry.runs >= RECURRING_MIN_RUNS)
38
+ .toSorted((a, b) => b.runs - a.runs);
39
+ }
40
+ export function tally(texts, signals) {
41
+ return signals.reduce((acc, signal) => {
42
+ const pattern = new RegExp(signal.pattern, "i");
43
+ const hits = texts.filter((text) => pattern.test(text));
44
+ if (hits.length === 0)
45
+ return acc;
46
+ const before = acc[signal.constraint];
47
+ return { ...acc, [signal.constraint]: { count: (before?.count ?? 0) + hits.length, sample: before?.sample ?? (hits[0] ?? "").slice(0, 120) } };
48
+ }, {});
49
+ }
50
+ export function proposeInstalls(sources, pending) {
51
+ const ids = [...new Set(sources.flatMap((entry) => Object.keys(entry.tallies)))].filter((id) => pending.has(id));
52
+ return ids
53
+ .map((id) => ({
54
+ kind: "install-constraint",
55
+ id,
56
+ command: `guardrails apply ${id}`,
57
+ evidence: sources.flatMap((entry) => {
58
+ const found = entry.tallies[id];
59
+ return found === undefined ? [] : [{ source: entry.source, count: found.count, sample: found.sample }];
60
+ }),
61
+ }))
62
+ .toSorted((a, b) => total(b.evidence) - total(a.evidence));
63
+ }
64
+ export const total = (evidence) => evidence.reduce((sum, item) => sum + item.count, 0);
65
+ export function proposeRecurring(records) {
66
+ return recurringRules(records).map((entry) => ({
67
+ kind: "recurring-violation",
68
+ id: entry.rule,
69
+ command: `guardrails add-rule <name> --from "<the correction you were given for ${entry.rule}>" --selector "<esquery>" --bad "<code>" --good "<code>"`,
70
+ evidence: [{ source: "check-history", count: entry.runs, sample: `${entry.rule} appeared in ${String(entry.runs)} of the last ${String(records.length)} checks` }],
71
+ }));
72
+ }
73
+ export function proposeDebt(debt) {
74
+ return Object.entries(debt)
75
+ .filter(([, count]) => count > 0)
76
+ .toSorted((a, b) => b[1] - a[1])
77
+ .map(([rule, count]) => ({ kind: "pay-debt", id: rule, command: `guardrails check --json`, evidence: [{ source: "baseline", count, sample: `${rule}: ${String(count)} violations in the baseline` }] }));
78
+ }
@@ -0,0 +1,99 @@
1
+ import { isRecord, parseStrictJson } from "./json.js";
2
+ const ANSI = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*[A-Za-z]`, "g");
3
+ const PREFIX = /^(?:[^\t\n]*\t[^\t\n]*\t)?\d{4}-\d\d-\d\dT[\d:.]+Z ?/;
4
+ const WORKSPACE = /^.*?\/work\/[^/]+\/[^/]+\//;
5
+ const TSC_PAREN = /^(.+?)\((\d+),\d+\): error (TS\d+): (.+)$/;
6
+ const TSC_COLON = /^(.+?):(\d+):\d+ - error (TS\d+): (.+)$/;
7
+ const ESLINT_FILE = /^(?:\/|\.\/|[A-Za-z]:)?[^\s].*\.(?:[cm]?[jt]sx?)$/;
8
+ const ESLINT_ROW = /^\s+(\d+):\d+\s+(error|warning)\s+(.*?)\s{2,}(\S+)\s*$/;
9
+ const VITEST_FAIL = /^\s*FAIL\s+(\S+)\s+>\s+(.+?)\s*$/;
10
+ const JEST_FILE = /^\s*FAIL\s+(\S+)\s*$/;
11
+ const JEST_CASE = /^\s*●\s+(.+?)\s*$/;
12
+ const LOCATION = /(?:❯\s+|\()?(\S+?\.(?:[cm]?[jt]sx?)):(\d+):\d+\)?\s*$/;
13
+ const TEST_FIX = "Read the assertion: fix the code if the behaviour is wrong, or the test if its expectation is outdated. CI reruns it; run it locally only when asked.";
14
+ const TSC_FIX = "Fix the type error at this location; do not use any, @ts-ignore or casts to silence it.";
15
+ const LINT_FIX = "Change the code as the rule message says; never add eslint-disable or lower the rule.";
16
+ export const relativePath = (path) => path.replace(WORKSPACE, "");
17
+ export function cleanLog(raw) {
18
+ return raw.replace(ANSI, "").split("\n").map((line) => line.replace(PREFIX, "").replace(/\r$/, ""));
19
+ }
20
+ const str = (value) => (typeof value === "string" ? value : "");
21
+ const item = (check, file, line, rule, test, message, fix) => ({ check, file: relativePath(file), line, rule, test, message, fix });
22
+ function fromDiagnostics(check, value) {
23
+ const nested = isRecord(value) && isRecord(value["check"]) ? value["check"] : value;
24
+ const list = isRecord(nested) && Array.isArray(nested["diagnostics"]) ? nested["diagnostics"] : [];
25
+ return list.filter(isRecord).map((entry) => item(check, str(entry["file"]), typeof entry["line"] === "number" ? entry["line"] : 0, typeof entry["rule"] === "string" ? entry["rule"] : null, null, str(entry["message"]), str(entry["fix"])));
26
+ }
27
+ function guardrailsJson(check, lines) {
28
+ const source = lines.join("\n");
29
+ const starts = [...source.matchAll(/^\{\n {2}"ok"/gm)].map((match) => match.index);
30
+ return starts.flatMap((start) => {
31
+ const end = source.indexOf("\n}", start);
32
+ const parsed = end === -1 ? null : parseStrictJson(source.slice(start, end + 2));
33
+ return parsed !== null && parsed.ok ? fromDiagnostics(check, parsed.value) : [];
34
+ });
35
+ }
36
+ function tsc(check, lines) {
37
+ return lines.flatMap((line) => {
38
+ const match = TSC_PAREN.exec(line) ?? TSC_COLON.exec(line);
39
+ return match === null ? [] : [item(check, match[1] ?? "", Number(match[2]), match[3] ?? null, null, match[4] ?? "", TSC_FIX)];
40
+ });
41
+ }
42
+ function eslintStylish(check, lines) {
43
+ return lines.reduce((state, line) => {
44
+ const row = ESLINT_ROW.exec(line);
45
+ if (row !== null && state.file !== "")
46
+ return { file: state.file, found: [...state.found, item(check, state.file, Number(row[1]), row[4] ?? null, null, row[3] ?? "", LINT_FIX)] };
47
+ return ESLINT_FILE.test(line) && !line.startsWith(" ") ? { file: line.trim(), found: state.found } : state;
48
+ }, { file: "", found: [] }).found;
49
+ }
50
+ function windowAfter(lines, index) {
51
+ const rest = lines.slice(index + 1, index + 30);
52
+ const stop = rest.findIndex((line) => VITEST_FAIL.test(line) || JEST_CASE.test(line));
53
+ return stop === -1 ? rest : rest.slice(0, stop);
54
+ }
55
+ function messageIn(window, fallback) {
56
+ return window.map((line) => line.trim()).find((line) => /Error|expected|received/i.test(line)) ?? fallback;
57
+ }
58
+ function locationIn(window, file) {
59
+ const found = window.flatMap((line) => {
60
+ const match = LOCATION.exec(line);
61
+ return match === null || (match[1] ?? "").includes("node_modules") ? [] : [{ file: match[1] ?? file, line: Number(match[2]) }];
62
+ })[0];
63
+ return found ?? { file, line: 0 };
64
+ }
65
+ function vitest(check, lines) {
66
+ return lines.flatMap((line, index) => {
67
+ const match = VITEST_FAIL.exec(line);
68
+ if (match === null)
69
+ return [];
70
+ const window = windowAfter(lines, index);
71
+ const where = locationIn(window, match[1] ?? "");
72
+ return [item(check, where.file, where.line, null, match[2] ?? "", messageIn(window, match[2] ?? "test failed"), TEST_FIX)];
73
+ });
74
+ }
75
+ function jest(check, lines) {
76
+ return lines.flatMap((line, index) => {
77
+ const match = JEST_CASE.exec(line);
78
+ if (match === null || /Test suite failed to run/.test(line))
79
+ return [];
80
+ const file = lines.slice(0, index).findLast((earlier) => JEST_FILE.test(earlier));
81
+ const base = file === undefined ? "" : (JEST_FILE.exec(file)?.[1] ?? "");
82
+ const window = windowAfter(lines, index);
83
+ const where = locationIn(window, base);
84
+ return [item(check, where.file, where.line, null, match[1] ?? "", messageIn(window, match[1] ?? "test failed"), TEST_FIX)];
85
+ });
86
+ }
87
+ function tail(check, lines) {
88
+ const errors = lines.filter((line) => line.includes("##[error]")).map((line) => line.replace("##[error]", "").trim());
89
+ const message = (errors.length > 0 ? errors : lines.filter((line) => line.trim() !== "").slice(-8)).join(" | ");
90
+ return [item(check, "", 0, null, null, message === "" ? "the check failed without output" : message, "Open the check URL, find the failing command and fix its cause; reproduce it with the matching package script.")];
91
+ }
92
+ const keyOf = (entry) => `${entry.file}:${String(entry.line)}:${entry.rule ?? ""}:${entry.test ?? ""}`;
93
+ export function parseLog(check, raw) {
94
+ const lines = cleanLog(raw);
95
+ const parsers = [guardrailsJson, tsc, eslintStylish, vitest, jest];
96
+ const found = parsers.flatMap((parse) => parse(check, lines));
97
+ const unique = found.filter((entry, index) => found.findIndex((other) => keyOf(other) === keyOf(entry)) === index);
98
+ return unique.length > 0 ? unique : tail(check, lines);
99
+ }
@@ -0,0 +1,17 @@
1
+ export function emptyAnalysis(pack) {
2
+ return { pack, ran: false, diagnostics: [], skipped: [], metrics: {}, failing: [], debt: {}, lines: [], missingFix: null, phasesMs: {} };
3
+ }
4
+ export function definePack(input) {
5
+ return {
6
+ extends: [],
7
+ constraints: [],
8
+ fixes: {},
9
+ tools: { linter: null, typecheck: null, formatter: null, test: null },
10
+ commands: null,
11
+ ci: null,
12
+ hooks: null,
13
+ analyze: () => Promise.resolve(emptyAnalysis(input.id)),
14
+ describe: () => [],
15
+ ...input,
16
+ };
17
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,45 @@
1
+ import { stringifyJson } from "./json.js";
2
+ import { MARKER } from "./pr-loop.js";
3
+ const ROW_LIMIT = 40;
4
+ const JSON_LIMIT = 40000;
5
+ const cell = (value) => value.replace(/\|/g, "\\|").replace(/\s+/g, " ").trim();
6
+ const place = (entry) => (entry.file === "" ? "-" : `${entry.file}${entry.line > 0 ? `:${String(entry.line)}` : ""}`);
7
+ function diagnosticRows(entries) {
8
+ return entries.slice(0, ROW_LIMIT).map((entry) => `| \`${cell(place(entry))}\` | ${cell(entry.rule ?? entry.test ?? "-")} | ${cell(entry.message)} | ${cell(entry.fix)} |`);
9
+ }
10
+ function failingSection(failing) {
11
+ return [
12
+ `#### ${failing.check}`,
13
+ "",
14
+ ...(failing.url === "" ? [] : [`[logs](${failing.url})`, ""]),
15
+ "| where | rule / test | message | fix |",
16
+ "| --- | --- | --- | --- |",
17
+ ...diagnosticRows(failing.diagnostics),
18
+ ...(failing.diagnostics.length > ROW_LIMIT ? [`| ... | | ${String(failing.diagnostics.length - ROW_LIMIT)} more in the JSON | |`] : []),
19
+ "",
20
+ ];
21
+ }
22
+ export function renderComment(report) {
23
+ const json = stringifyJson(report);
24
+ const body = json.length > JSON_LIMIT ? `${json.slice(0, JSON_LIMIT)}\n...truncated; the artifact has the full JSON` : json;
25
+ return [
26
+ MARKER,
27
+ `### Guardrails: ${report.verdict}`,
28
+ "",
29
+ `Head \`${report.pr.head.slice(0, 8)}\`. ${report.next}`,
30
+ "",
31
+ "| check | state |",
32
+ "| --- | --- |",
33
+ ...report.checks.map((check) => `| ${cell(check.name)} | ${check.state} |`),
34
+ "",
35
+ ...report.failing.flatMap(failingSection),
36
+ "<details><summary>Diagnostics JSON</summary>",
37
+ "",
38
+ "```json",
39
+ body.trimEnd(),
40
+ "```",
41
+ "",
42
+ "</details>",
43
+ "",
44
+ ].join("\n");
45
+ }