@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.
Files changed (146) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +222 -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 +57 -0
  38. package/dist/config/runtime.js +15 -0
  39. package/dist/core/app/analysis.js +74 -0
  40. package/dist/core/app/args.js +46 -0
  41. package/dist/core/app/catalog.js +20 -0
  42. package/dist/core/app/ci-plan.js +14 -0
  43. package/dist/core/app/claude.js +37 -0
  44. package/dist/core/app/commands/add-rule.js +32 -0
  45. package/dist/core/app/commands/agents-md.js +13 -0
  46. package/dist/core/app/commands/apply.js +74 -0
  47. package/dist/core/app/commands/audit.js +38 -0
  48. package/dist/core/app/commands/check.js +33 -0
  49. package/dist/core/app/commands/detect.js +16 -0
  50. package/dist/core/app/commands/init.js +127 -0
  51. package/dist/core/app/commands/learn.js +48 -0
  52. package/dist/core/app/commands/plan.js +40 -0
  53. package/dist/core/app/commands/pr-status.js +66 -0
  54. package/dist/core/app/commands/self-check.js +20 -0
  55. package/dist/core/app/git.js +75 -0
  56. package/dist/core/app/github.js +146 -0
  57. package/dist/core/app/hooks-script.js +27 -0
  58. package/dist/core/app/output.js +17 -0
  59. package/dist/core/app/run.js +32 -0
  60. package/dist/core/app/session.js +18 -0
  61. package/dist/core/app/timing.js +11 -0
  62. package/dist/core/domain/agents-md.js +104 -0
  63. package/dist/core/domain/audit-report.js +7 -0
  64. package/dist/core/domain/changes.js +8 -0
  65. package/dist/core/domain/check-report.js +23 -0
  66. package/dist/core/domain/claude-settings.js +42 -0
  67. package/dist/core/domain/constraint.js +7 -0
  68. package/dist/core/domain/diagnostics.js +3 -0
  69. package/dist/core/domain/errors.js +21 -0
  70. package/dist/core/domain/facts.js +18 -0
  71. package/dist/core/domain/init-report.js +28 -0
  72. package/dist/core/domain/json.js +43 -0
  73. package/dist/core/domain/learn.js +78 -0
  74. package/dist/core/domain/log-parse.js +99 -0
  75. package/dist/core/domain/pack-defaults.js +17 -0
  76. package/dist/core/domain/pack.js +1 -0
  77. package/dist/core/domain/perf.js +65 -0
  78. package/dist/core/domain/pr-comment.js +45 -0
  79. package/dist/core/domain/pr-loop.js +85 -0
  80. package/dist/core/domain/profile.js +25 -0
  81. package/dist/core/domain/protection.js +43 -0
  82. package/dist/core/domain/ratchet.js +40 -0
  83. package/dist/core/domain/registry.js +32 -0
  84. package/dist/core/domain/remote.js +4 -0
  85. package/dist/core/domain/result.js +25 -0
  86. package/dist/core/domain/thresholds.js +9 -0
  87. package/dist/core/domain/types.js +1 -0
  88. package/dist/core/domain/workflows.js +252 -0
  89. package/dist/core/infra/assets.js +7 -0
  90. package/dist/core/infra/backup.js +31 -0
  91. package/dist/core/infra/baseline.js +8 -0
  92. package/dist/core/infra/changes.js +17 -0
  93. package/dist/core/infra/exec.js +15 -0
  94. package/dist/core/infra/facts.js +61 -0
  95. package/dist/core/infra/fs.js +87 -0
  96. package/dist/core/infra/gh.js +32 -0
  97. package/dist/core/infra/hash.js +10 -0
  98. package/dist/core/infra/hooks.js +31 -0
  99. package/dist/core/infra/learn-sources.js +40 -0
  100. package/dist/core/infra/lock.js +102 -0
  101. package/dist/core/infra/pr.js +48 -0
  102. package/dist/core/infra/result-cache.js +49 -0
  103. package/dist/packs/index.js +6 -0
  104. package/dist/packs/js-ts/app/add-rule.js +116 -0
  105. package/dist/packs/js-ts/app/analysis.js +111 -0
  106. package/dist/packs/js-ts/app/bootstrap.js +16 -0
  107. package/dist/packs/js-ts/app/eslint-constraints.js +155 -0
  108. package/dist/packs/js-ts/app/eslint-files.js +56 -0
  109. package/dist/packs/js-ts/app/fixes.js +3 -0
  110. package/dist/packs/js-ts/app/pr-rules.js +30 -0
  111. package/dist/packs/js-ts/app/project.js +87 -0
  112. package/dist/packs/js-ts/app/tests.js +63 -0
  113. package/dist/packs/js-ts/domain/catalog-specs.js +147 -0
  114. package/dist/packs/js-ts/domain/ci.js +47 -0
  115. package/dist/packs/js-ts/domain/data.js +34 -0
  116. package/dist/packs/js-ts/domain/diagnostics-js.js +17 -0
  117. package/dist/packs/js-ts/domain/disables.js +11 -0
  118. package/dist/packs/js-ts/domain/eslint-output.js +46 -0
  119. package/dist/packs/js-ts/domain/eslint-state.js +80 -0
  120. package/dist/packs/js-ts/domain/hooks.js +49 -0
  121. package/dist/packs/js-ts/domain/pr-diagnostics.js +33 -0
  122. package/dist/packs/js-ts/domain/pr-tests.js +27 -0
  123. package/dist/packs/js-ts/domain/profile-pure.js +51 -0
  124. package/dist/packs/js-ts/domain/profile.js +112 -0
  125. package/dist/packs/js-ts/domain/report.js +74 -0
  126. package/dist/packs/js-ts/domain/rule-templates.js +44 -0
  127. package/dist/packs/js-ts/domain/signals.js +14 -0
  128. package/dist/packs/js-ts/domain/testing.js +33 -0
  129. package/dist/packs/js-ts/domain/ts-options.js +16 -0
  130. package/dist/packs/js-ts/index.js +50 -0
  131. package/dist/packs/js-ts/infra/eslint.js +50 -0
  132. package/dist/packs/js-ts/infra/scan.js +25 -0
  133. package/dist/packs/js-ts/infra/tsc.js +29 -0
  134. package/dist/packs/nextjs/domain/data.js +9 -0
  135. package/dist/packs/nextjs/domain/profile.js +21 -0
  136. package/dist/packs/nextjs/domain/specs.js +33 -0
  137. package/dist/packs/nextjs/index.js +23 -0
  138. package/dist/packs/node/domain/specs.js +23 -0
  139. package/dist/packs/node/index.js +26 -0
  140. package/dist/packs/react/domain/data.js +9 -0
  141. package/dist/packs/react/domain/specs.js +63 -0
  142. package/dist/packs/react/index.js +30 -0
  143. package/dist/packs/react-native/domain/specs.js +29 -0
  144. package/dist/packs/react-native/domain/testing.js +20 -0
  145. package/dist/packs/react-native/index.js +30 -0
  146. package/package.json +60 -4
@@ -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,65 @@
1
+ import { isAbsolute, posix, relative, sep } from "node:path";
2
+ import { isRecord, parseStrictJson } from "./json.js";
3
+ export const DEFAULT_MAX_JOBS = 1;
4
+ export const DEFAULT_LOCK_TIMEOUT_MS = 600_000;
5
+ export const DEFAULT_MAX_OLD_SPACE_MB = 2048;
6
+ const OLD_SPACE_FLAG = "--max-old-space-size";
7
+ export function positiveInt(raw, fallback) {
8
+ const value = raw === undefined || raw.trim() === "" ? Number.NaN : Number(raw);
9
+ return Number.isFinite(value) && value >= 1 ? Math.floor(value) : fallback;
10
+ }
11
+ export function mergeNodeOptions(existing, maxOldSpaceMb) {
12
+ const current = existing?.trim() ?? "";
13
+ return current.includes(OLD_SPACE_FLAG) ? current : `${current} ${OLD_SPACE_FLAG}=${String(maxOldSpaceMb)}`.trim();
14
+ }
15
+ export function cacheDirFor(input) {
16
+ if (input.override !== undefined && input.override !== "")
17
+ return input.override;
18
+ if (input.xdg !== undefined && input.xdg !== "")
19
+ return posix.join(input.xdg, "guardrails");
20
+ return input.platform === "darwin" ? posix.join(input.home, "Library", "Caches", "guardrails") : posix.join(input.home, ".cache", "guardrails");
21
+ }
22
+ export function normalizeScope(root, paths) {
23
+ const relatives = paths.map((path) => (isAbsolute(path) ? relative(root, path) : path).split(sep).join("/"));
24
+ const cleaned = relatives.map((path) => posix.normalize(path).replace(/\/+$/, "")).filter((path) => path !== "" && path !== ".");
25
+ return [...new Set(cleaned)].toSorted();
26
+ }
27
+ export function inScope(file, scope) {
28
+ if (scope.length === 0)
29
+ return true;
30
+ const normalized = posix.normalize(file.split(sep).join("/"));
31
+ return scope.some((entry) => normalized === entry || normalized.startsWith(`${entry}/`));
32
+ }
33
+ export function scopeItems(items, scope) {
34
+ return scope.length === 0 ? items : items.filter((item) => inScope(item.file, scope));
35
+ }
36
+ export function renderLockInfo(info) {
37
+ return JSON.stringify(info);
38
+ }
39
+ export function parseLockInfo(text) {
40
+ const parsed = parseStrictJson(text);
41
+ if (!parsed.ok || !isRecord(parsed.value))
42
+ return null;
43
+ const { pid, repo, startedAt } = parsed.value;
44
+ return typeof pid === "number" && Number.isInteger(pid) && typeof repo === "string" && typeof startedAt === "number" ? { pid, repo, startedAt } : null;
45
+ }
46
+ export function waitingMessage(holder, fallbackRepo) {
47
+ return `guardrails: otra corrida en curso en ${holder?.repo ?? fallbackRepo}, esperando`;
48
+ }
49
+ const isStringArray = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
50
+ function hasScalarFields(value) {
51
+ return typeof value["pack"] === "string" && typeof value["ran"] === "boolean" && (value["missingFix"] === null || typeof value["missingFix"] === "string");
52
+ }
53
+ function hasCollectionFields(value) {
54
+ const records = ["metrics", "debt", "phasesMs"].every((name) => isRecord(value[name]));
55
+ return records && Array.isArray(value["diagnostics"]) && Array.isArray(value["skipped"]) && isStringArray(value["failing"]) && isStringArray(value["lines"]);
56
+ }
57
+ function isStoredAnalysis(value) {
58
+ return isRecord(value) && hasScalarFields(value) && hasCollectionFields(value);
59
+ }
60
+ export function parseStoredResults(value) {
61
+ return Array.isArray(value) && value.length > 0 && value.every(isStoredAnalysis) ? value : null;
62
+ }
63
+ export function cacheable(results) {
64
+ return results.some((result) => result.ran) && results.every((result) => result.ran || result.skipped.length === 0);
65
+ }
@@ -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
+ }
@@ -0,0 +1,85 @@
1
+ import { isRecord } from "./json.js";
2
+ import { THRESHOLDS } from "./thresholds.js";
3
+ export const EMPTY_STATE = Object.freeze({ prs: Object.freeze({}) });
4
+ export const MARKER = "<!-- guardrails-pr-diagnostics -->";
5
+ const text = (value) => (typeof value === "string" ? value : "");
6
+ function runState(status, conclusion) {
7
+ if (status !== "COMPLETED")
8
+ return "pending";
9
+ if (conclusion === "SUCCESS" || conclusion === "NEUTRAL")
10
+ return "pass";
11
+ return conclusion === "SKIPPED" ? "skipped" : "fail";
12
+ }
13
+ function contextState(state) {
14
+ if (state === "SUCCESS")
15
+ return "pass";
16
+ return state === "PENDING" || state === "EXPECTED" ? "pending" : "fail";
17
+ }
18
+ function checkOf(entry) {
19
+ const isRun = entry["__typename"] === "CheckRun";
20
+ const url = text(isRun ? entry["detailsUrl"] : entry["targetUrl"]);
21
+ return {
22
+ name: text(isRun ? entry["name"] : entry["context"]),
23
+ state: isRun ? runState(text(entry["status"]), text(entry["conclusion"])) : contextState(text(entry["state"])),
24
+ url,
25
+ jobId: /\/job\/(\d+)/.exec(url)?.[1] ?? null,
26
+ };
27
+ }
28
+ export function parsePr(value) {
29
+ if (!isRecord(value) || typeof value["number"] !== "number")
30
+ return null;
31
+ const rollup = Array.isArray(value["statusCheckRollup"]) ? value["statusCheckRollup"] : [];
32
+ return {
33
+ number: value["number"],
34
+ url: text(value["url"]),
35
+ head: text(value["headRefOid"]),
36
+ branch: text(value["headRefName"]),
37
+ base: text(value["baseRefName"]),
38
+ checks: rollup.filter(isRecord).map(checkOf),
39
+ };
40
+ }
41
+ export function verdictOf(checks, ignore, ignorePending) {
42
+ const relevant = checks.filter((check) => !ignore.includes(check.name));
43
+ if (relevant.some((check) => check.state === "fail"))
44
+ return "fix";
45
+ return !ignorePending && relevant.some((check) => check.state === "pending") ? "pending" : "green";
46
+ }
47
+ export function parseState(source) {
48
+ const parsed = source === null ? null : safeParse(source);
49
+ const prs = isRecord(parsed) ? parsed["prs"] : null;
50
+ if (!isRecord(prs))
51
+ return EMPTY_STATE;
52
+ return { prs: Object.fromEntries(Object.entries(prs).map(([key, shas]) => [key, Array.isArray(shas) ? shas.filter((sha) => typeof sha === "string") : []])) };
53
+ }
54
+ function safeParse(source) {
55
+ try {
56
+ return JSON.parse(source);
57
+ }
58
+ catch {
59
+ return null;
60
+ }
61
+ }
62
+ export function failedShas(state, pr) {
63
+ return state.prs[String(pr)] ?? [];
64
+ }
65
+ export function recordFailure(state, pr, sha) {
66
+ const known = failedShas(state, pr);
67
+ return known.includes(sha) ? state : { prs: { ...state.prs, [String(pr)]: [...known, sha] } };
68
+ }
69
+ export function clearPr(state, pr) {
70
+ return { prs: Object.fromEntries(Object.entries(state.prs).filter(([key]) => key !== String(pr))) };
71
+ }
72
+ export function attemptsOf(shas) {
73
+ const used = Math.max(0, shas.length - 1);
74
+ const limit = THRESHOLDS.repairAttempts.value;
75
+ return { used, left: Math.max(0, limit - used), limit };
76
+ }
77
+ export function nextStep(verdict, attempts) {
78
+ if (verdict === "green")
79
+ return "All checks are green: merge with `gh pr merge --auto --squash`.";
80
+ if (verdict === "pending")
81
+ return "Checks are still running: run `guardrails pr-status --wait --json` again.";
82
+ if (verdict === "escalate")
83
+ return `Stop. ${String(attempts.limit)} repair attempts did not turn the PR green. Ask a human for help and hand over failing[] from this output.`;
84
+ return `Fix every entry in failing[].diagnostics (file, line, rule or test, fix), run \`guardrails check --json\` until clean, commit, push to this branch, then run \`guardrails pr-repair --wait --json\` again. ${String(attempts.left)} of ${String(attempts.limit)} attempts left.`;
85
+ }
@@ -0,0 +1,25 @@
1
+ import { parseRemote } from "./remote.js";
2
+ export function deriveProfile(facts, packs, active) {
3
+ return {
4
+ version: 2,
5
+ name: facts.rootName,
6
+ packs: active,
7
+ stack: Object.fromEntries(packs.map((pack) => [pack.id, pack.profile(facts)])),
8
+ git: {
9
+ isRepo: facts.git.isRepo,
10
+ hooksPath: facts.git.hooksPath,
11
+ baseBranch: facts.git.baseBranch,
12
+ remote: facts.git.originUrl === null ? null : parseRemote(facts.git.originUrl),
13
+ },
14
+ ci: { github: facts.workflows.length > 0, workflows: facts.workflows },
15
+ claude: { dir: facts.present.includes(".claude"), settings: facts.present.includes(".claude/settings.json") },
16
+ agentsMd: facts.present.includes("AGENTS.md"),
17
+ };
18
+ }
19
+ export function summarizeProfile(profile, packs) {
20
+ return [
21
+ `${profile.name}: packs ${profile.packs.map((pack) => `${pack.id} (${pack.confidence})`).join(", ")}`,
22
+ ...packs.flatMap((pack) => pack.describe(profile).map((line) => `${pack.id}: ${line}`)),
23
+ `git hooks path: ${profile.git.hooksPath ?? "none"}, CI workflows: ${profile.ci.workflows.length}`,
24
+ ].join("\n");
25
+ }
@@ -0,0 +1,43 @@
1
+ import { isRecord } from "./json.js";
2
+ const REQUIRED_RULES = ["pull_request", "required_status_checks", "non_fast_forward", "deletion"];
3
+ export const protectionUnknown = (reason) => ({ status: "unknown", source: null, missing: [], reason });
4
+ function fromMissing(source, missing) {
5
+ return { status: missing.length === 0 ? "active" : "missing", source, missing, reason: null };
6
+ }
7
+ function ruleTypes(ruleset) {
8
+ const rules = ruleset["rules"];
9
+ if (!Array.isArray(rules))
10
+ return [];
11
+ return rules.flatMap((rule) => (isRecord(rule) && typeof rule["type"] === "string" ? [rule["type"]] : []));
12
+ }
13
+ function targetsBranch(ruleset, base) {
14
+ const conditions = ruleset["conditions"];
15
+ const refName = isRecord(conditions) ? conditions["ref_name"] : null;
16
+ const include = isRecord(refName) && Array.isArray(refName["include"]) ? refName["include"] : [];
17
+ return include.some((ref) => ref === `refs/heads/${base}` || ref === "~DEFAULT_BRANCH" || ref === "~ALL");
18
+ }
19
+ export function evaluateRuleset(ruleset, base) {
20
+ if (ruleset["enforcement"] !== "active" || !targetsBranch(ruleset, base)) {
21
+ return { status: "missing", source: "ruleset", missing: ["active ruleset targeting the base branch"], reason: null };
22
+ }
23
+ const types = ruleTypes(ruleset);
24
+ const bypass = ruleset["bypass_actors"];
25
+ const bypassing = Array.isArray(bypass) && bypass.length > 0 ? ["no bypass actors"] : [];
26
+ return fromMissing("ruleset", [...REQUIRED_RULES.filter((type) => !types.includes(type)), ...bypassing]);
27
+ }
28
+ function hasChecks(protection) {
29
+ const checks = protection["required_status_checks"];
30
+ return isRecord(checks) && Array.isArray(checks["contexts"]) && checks["contexts"].length > 0;
31
+ }
32
+ function enabled(value) {
33
+ return isRecord(value) && value["enabled"] === true;
34
+ }
35
+ export function evaluateClassic(protection) {
36
+ const missing = [
37
+ ...(isRecord(protection["required_pull_request_reviews"]) ? [] : ["pull request required"]),
38
+ ...(hasChecks(protection) ? [] : ["required status checks"]),
39
+ ...(enabled(protection["allow_force_pushes"]) ? ["no force-push"] : []),
40
+ ...(enabled(protection["enforce_admins"]) ? [] : ["no admin bypass"]),
41
+ ];
42
+ return fromMissing("branch-protection", missing);
43
+ }
@@ -0,0 +1,40 @@
1
+ import { isRecord } from "./json.js";
2
+ export const EMPTY_BASELINE = Object.freeze({ version: 1, rules: Object.freeze({}) });
3
+ export const BASELINE_PATH = ".guardrails/baseline.json";
4
+ export function parseBaseline(value) {
5
+ const rules = isRecord(value) ? value["rules"] : null;
6
+ if (!isRecord(rules))
7
+ return EMPTY_BASELINE;
8
+ const coverage = isRecord(value) ? value["coverage"] : undefined;
9
+ return {
10
+ version: 1,
11
+ rules: Object.fromEntries(Object.entries(rules).filter((entry) => typeof entry[1] === "number" && entry[1] > 0)),
12
+ ...(typeof coverage === "number" && coverage > 0 ? { coverage } : {}),
13
+ };
14
+ }
15
+ export function serializeBaseline(baseline) {
16
+ const sorted = Object.fromEntries(Object.entries(baseline.rules).toSorted(([a], [b]) => a.localeCompare(b)));
17
+ return `${JSON.stringify({ version: 1, rules: sorted, ...(baseline.coverage === undefined ? {} : { coverage: baseline.coverage }) }, null, 2)}\n`;
18
+ }
19
+ export function evaluateRatchet(input) {
20
+ const entries = input.warnRules.map((rule) => ({ rule, count: input.counts[rule] ?? 0, baseline: input.baseline.rules[rule] ?? 0 }));
21
+ const regressions = entries.filter((entry) => entry.count > entry.baseline);
22
+ const tolerated = entries.filter((entry) => entry.count > 0 && entry.count <= entry.baseline);
23
+ const promotable = entries.filter((entry) => entry.count === 0).map((entry) => entry.rule);
24
+ const lowered = Object.fromEntries(tolerated.map((entry) => [entry.rule, entry.count]));
25
+ const untouched = Object.fromEntries(Object.entries(input.baseline.rules).filter(([rule]) => !input.warnRules.includes(rule)));
26
+ return { regressions, tolerated, promotable, next: { version: 1, rules: { ...untouched, ...lowered }, ...(input.baseline.coverage === undefined ? {} : { coverage: input.baseline.coverage }) } };
27
+ }
28
+ export function baselineFromCounts(counts) {
29
+ return { version: 1, rules: Object.fromEntries(Object.entries(counts).filter(([, count]) => count > 0)) };
30
+ }
31
+ const roundDown = (value) => Math.floor(value * 100) / 100;
32
+ export function evaluateCoverage(floor, measured) {
33
+ if (measured === null)
34
+ return { regression: null, next: floor };
35
+ if (floor !== undefined && measured < floor)
36
+ return { regression: { floor, measured }, next: floor };
37
+ const raised = roundDown(measured);
38
+ return { regression: null, next: floor === undefined || raised > floor ? (raised > 0 ? raised : floor) : floor };
39
+ }
40
+ export const coverageLowered = (before, after) => before !== undefined && (after === undefined || after < before);
@@ -0,0 +1,32 @@
1
+ import { appError } from "./errors.js";
2
+ import { err, map, ok } from "./result.js";
3
+ export const ACTIVATION_THRESHOLD = 0.5;
4
+ function byId(registry, id) {
5
+ return registry.find((pack) => pack.id === id);
6
+ }
7
+ function closure(registry, seeds) {
8
+ const missing = seeds.flatMap((id) => byId(registry, id)?.extends ?? []).filter((id) => byId(registry, id) === undefined);
9
+ if (missing.length > 0) {
10
+ return err(appError("unknown-pack", `a pack extends "${missing[0] ?? ""}" which is not registered`, { file: "src/packs/index.ts", fix: "Register the missing pack in src/packs/index.ts or remove it from `extends`." }));
11
+ }
12
+ const next = [...new Set([...seeds, ...seeds.flatMap((id) => byId(registry, id)?.extends ?? [])])];
13
+ return next.length === seeds.length ? ok(next) : closure(registry, next);
14
+ }
15
+ function depth(registry, id, seen) {
16
+ const pack = byId(registry, id);
17
+ if (pack === undefined || seen.includes(id))
18
+ return 0;
19
+ return pack.extends.reduce((max, parent) => Math.max(max, depth(registry, parent, [...seen, id]) + 1), 0);
20
+ }
21
+ export function resolvePacks(registry, facts) {
22
+ const detections = registry.map((pack) => ({ id: pack.id, detection: pack.detect(facts) }));
23
+ const direct = detections.filter((entry) => entry.detection.confidence >= ACTIVATION_THRESHOLD).map((entry) => entry.id);
24
+ return map(closure(registry, direct), (ids) => {
25
+ const packs = registry.filter((pack) => ids.includes(pack.id)).toSorted((a, b) => depth(registry, a.id, []) - depth(registry, b.id, []));
26
+ const active = packs.map((pack) => {
27
+ const found = detections.find((entry) => entry.id === pack.id)?.detection;
28
+ return { id: pack.id, confidence: found?.confidence ?? 1, evidence: found?.evidence ?? [] };
29
+ });
30
+ return { packs, active };
31
+ });
32
+ }
@@ -0,0 +1,4 @@
1
+ export function parseRemote(url) {
2
+ const match = /github\.com[:/]([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/.exec(url.trim());
3
+ return match === null ? null : { owner: match[1] ?? "", repo: match[2] ?? "" };
4
+ }
@@ -0,0 +1,25 @@
1
+ export const ok = (value) => ({ ok: true, value });
2
+ export const err = (error) => ({ ok: false, error });
3
+ export function map(result, transform) {
4
+ return result.ok ? ok(transform(result.value)) : result;
5
+ }
6
+ export function andThen(result, next) {
7
+ return result.ok ? next(result.value) : result;
8
+ }
9
+ export function collect(results) {
10
+ const [failed] = results.flatMap((result) => (result.ok ? [] : [result]));
11
+ if (failed !== undefined)
12
+ return failed;
13
+ return ok(results.flatMap((result) => (result.ok ? [result.value] : [])));
14
+ }
15
+ export function valueOr(result, fallback) {
16
+ return result.ok ? result.value : fallback;
17
+ }
18
+ export function fromThrowing(attempt, onError) {
19
+ try {
20
+ return ok(attempt());
21
+ }
22
+ catch (cause) {
23
+ return err(onError(cause));
24
+ }
25
+ }
@@ -0,0 +1,9 @@
1
+ export const THRESHOLDS = {
2
+ complexity: { value: 10, why: "ESLint's own default for complexity; above it a function has more paths than a reader or a test suite follows." },
3
+ functionLines: { value: 40, why: "Roughly one screen: a function longer than this is doing more than one job." },
4
+ routeLines: { value: 60, why: "A route file only wires data to a view; this leaves room for imports, metadata and one fetch." },
5
+ apiRouteLines: { value: 40, why: "A handler parses the request, calls a service and returns; more is business logic that belongs in a service." },
6
+ inlineStyleProperties: { value: 2, why: "One or two dynamic values (opacity, transform) are legitimate inline; a third means a static style that belongs in StyleSheet.create." },
7
+ repairAttempts: { value: 3, why: "Three fix-push-recheck rounds cover a real mistake and its knock-on failures; a fourth red run means the agent is guessing and a human should look." },
8
+ recurringRuns: { value: 3, why: "A rule violated in three separate checks is a pattern, not a slip." },
9
+ };
@@ -0,0 +1 @@
1
+ export {};