@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,74 @@
|
|
|
1
|
+
import { capped } from "../../domain/diagnostics.js";
|
|
2
|
+
import { mergeChanges } from "../../domain/changes.js";
|
|
3
|
+
import { appError, EXIT } from "../../domain/errors.js";
|
|
4
|
+
import { stringifyJson } from "../../domain/json.js";
|
|
5
|
+
import { andThen, err, map, ok } from "../../domain/result.js";
|
|
6
|
+
import { writeManaged } from "../../infra/fs.js";
|
|
7
|
+
import { flagBool, flagString } from "../args.js";
|
|
8
|
+
import { findConstraint } from "../catalog.js";
|
|
9
|
+
import { commandsOf } from "../ci-plan.js";
|
|
10
|
+
import { PROFILE_PATH, buildSession } from "../session.js";
|
|
11
|
+
const VIOLATION_LIMIT = 100;
|
|
12
|
+
export function preflight(constraint, { profile, packs }) {
|
|
13
|
+
const reason = constraint.notApplicable(profile);
|
|
14
|
+
if (reason !== null)
|
|
15
|
+
return appError("not-applicable", `${constraint.id} does not apply to this repo: ${reason}`, { rule: constraint.id, fix: "Skip this constraint; `guardrails plan` lists only the applicable gaps." });
|
|
16
|
+
const requires = constraint.requires(profile, packs);
|
|
17
|
+
if (requires.length === 0)
|
|
18
|
+
return null;
|
|
19
|
+
const names = requires.map((requirement) => requirement.pkg);
|
|
20
|
+
const command = commandsOf(packs)?.installDev(profile, names) ?? `install ${names.join(" ")}`;
|
|
21
|
+
return appError("missing-dependency", `${constraint.id} needs: ${requires.map((requirement) => `${requirement.pkg} (${requirement.reason})`).join("; ")}`, {
|
|
22
|
+
rule: constraint.id,
|
|
23
|
+
fix: `Run \`${command}\`, then \`guardrails apply ${constraint.id}\` again.`,
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
function report(constraint, ctx, installed) {
|
|
27
|
+
const checks = constraint.verify(ctx);
|
|
28
|
+
const failed = checks.filter((check) => !check.ok);
|
|
29
|
+
const diagnostics = installed.violations.map((violation) => ({ ...violation, tool: "lint", fix: "Fix the violation at its source; the rule message says how." }));
|
|
30
|
+
const shown = capped(diagnostics, VIOLATION_LIMIT);
|
|
31
|
+
const changes = mergeChanges(installed.changes);
|
|
32
|
+
const lines = [
|
|
33
|
+
`${constraint.id}: ${failed.length === 0 ? "installed" : "installed but verification failed"}`,
|
|
34
|
+
...changes.filter((change) => change.action !== "unchanged").map((change) => ` ${change.action} ${change.path}`),
|
|
35
|
+
...checks.map((check) => ` [${check.ok ? "ok" : "FAIL"}] ${check.name}: ${check.detail}`),
|
|
36
|
+
...installed.notes.map((note) => ` note: ${note}`),
|
|
37
|
+
...(diagnostics.length > 0 ? [` ${diagnostics.length} existing violations; first ones:`, ...shown.items.slice(0, 10).map((item) => ` ${item.file}:${item.line} ${item.rule}: ${item.message}`)] : []),
|
|
38
|
+
];
|
|
39
|
+
return {
|
|
40
|
+
exit: failed.length > 0 ? EXIT.verify : diagnostics.length > 0 ? EXIT.findings : EXIT.ok,
|
|
41
|
+
data: {
|
|
42
|
+
id: constraint.id,
|
|
43
|
+
installed: failed.length === 0,
|
|
44
|
+
changes,
|
|
45
|
+
levels: installed.levels,
|
|
46
|
+
notes: installed.notes,
|
|
47
|
+
checks,
|
|
48
|
+
violations: { count: diagnostics.length, truncated: shown.truncated, items: shown.items },
|
|
49
|
+
next: diagnostics.length > 0 ? "Fix the violations (guardrails check --json), then run guardrails apply again to promote the rule to error." : "guardrails plan --json",
|
|
50
|
+
},
|
|
51
|
+
text: lines.join("\n"),
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
function run(args, constraint, session, registry) {
|
|
55
|
+
const root = args.cwd;
|
|
56
|
+
const owner = flagString(args, "owner");
|
|
57
|
+
const ctx = { root, profile: session.profile, packs: session.packs, ...(owner === undefined ? {} : { owner }), execute: flagBool(args, "execute") };
|
|
58
|
+
if (flagBool(args, "dry-run")) {
|
|
59
|
+
return ok({ exit: EXIT.ok, data: { id: constraint.id, dryRun: true, installed: constraint.isInstalled(ctx), title: constraint.title, layer: constraint.layer }, text: `dry run: would apply ${constraint.id} (${constraint.title})` });
|
|
60
|
+
}
|
|
61
|
+
return andThen(constraint.install(ctx), (installed) => map(buildSession(root, registry), (fresh) => {
|
|
62
|
+
writeManaged(root, PROFILE_PATH, stringifyJson(fresh.profile));
|
|
63
|
+
return report(constraint, { ...ctx, profile: fresh.profile, packs: fresh.packs }, installed);
|
|
64
|
+
}));
|
|
65
|
+
}
|
|
66
|
+
export function applyCommand(args, registry) {
|
|
67
|
+
const [id] = args.positionals;
|
|
68
|
+
if (id === undefined)
|
|
69
|
+
return err(appError("usage", "apply needs a constraint id", { fix: "Run `guardrails plan --json` and pass one of the ids: `guardrails apply <id>`." }));
|
|
70
|
+
return andThen(buildSession(args.cwd, registry), (session) => andThen(findConstraint(session.packs, id), ({ constraint }) => {
|
|
71
|
+
const blocked = preflight(constraint, session);
|
|
72
|
+
return blocked === null ? run(args, constraint, session, registry) : err(blocked);
|
|
73
|
+
}));
|
|
74
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { failingReasons } from "../../domain/audit-report.js";
|
|
2
|
+
import { EXIT } from "../../domain/errors.js";
|
|
3
|
+
import { protectionUnknown } from "../../domain/protection.js";
|
|
4
|
+
import { andThen, ok } from "../../domain/result.js";
|
|
5
|
+
import { checkProtection } from "../../infra/gh.js";
|
|
6
|
+
import { analyze, optionsFrom } from "../analysis.js";
|
|
7
|
+
import { flagBool } from "../args.js";
|
|
8
|
+
import { catalogOf } from "../catalog.js";
|
|
9
|
+
import { buildSession } from "../session.js";
|
|
10
|
+
const LAYER_CONSTRAINTS = { claudeHook: "claude-check-on-edit", preCommit: "git-pre-commit", commitMsg: "git-commit-msg", ci: "ci-workflow", branchProtectionFiles: "branch-protection" };
|
|
11
|
+
export function reportAudit(analysis, offline) {
|
|
12
|
+
const { root, profile, packs } = analysis;
|
|
13
|
+
const ctx = { root, profile, packs };
|
|
14
|
+
const applicable = catalogOf(packs).filter((entry) => entry.constraint.notApplicable(profile) === null);
|
|
15
|
+
const installed = applicable.filter((entry) => entry.constraint.isInstalled(ctx));
|
|
16
|
+
const protection = offline ? protectionUnknown("offline: --offline skips the GitHub query") : checkProtection(root, profile.git.remote, profile.git.baseBranch);
|
|
17
|
+
const failing = failingReasons({ packFailing: analysis.results.flatMap((result) => result.failing), protection, notInstalled: applicable.length - installed.length });
|
|
18
|
+
const layers = Object.fromEntries(Object.entries(LAYER_CONSTRAINTS).map(([key, id]) => [key, catalogOf(packs).find((entry) => entry.constraint.id === id)?.constraint.isInstalled(ctx) ?? false]));
|
|
19
|
+
const metrics = {
|
|
20
|
+
packs: Object.fromEntries(analysis.results.map((result) => [result.pack, result.metrics])),
|
|
21
|
+
catalog: { applicable: applicable.length, installed: installed.length, gaps: applicable.filter((entry) => !installed.includes(entry)).map((entry) => entry.constraint.id) },
|
|
22
|
+
layers,
|
|
23
|
+
branchProtection: { baseBranch: profile.git.baseBranch, status: protection.status, source: protection.source, missing: protection.missing, reason: protection.reason },
|
|
24
|
+
};
|
|
25
|
+
const text = [
|
|
26
|
+
...analysis.results.flatMap((result) => result.lines),
|
|
27
|
+
`catalog: ${installed.length}/${applicable.length} applicable constraints installed`,
|
|
28
|
+
`branch protection (${profile.git.baseBranch}): ${protection.status}${protection.reason === null ? "" : ` (${protection.reason})`}`,
|
|
29
|
+
failing.length === 0 ? "audit clean" : `fix: ${failing.join("; ")}`,
|
|
30
|
+
].join("\n");
|
|
31
|
+
return ok({ exit: failing.length === 0 ? EXIT.ok : EXIT.findings, data: { metrics, failing, cached: analysis.cached, phasesMs: analysis.phasesMs }, text });
|
|
32
|
+
}
|
|
33
|
+
export async function auditCommand(args, registry) {
|
|
34
|
+
const session = buildSession(args.cwd, registry);
|
|
35
|
+
if (!session.ok)
|
|
36
|
+
return session;
|
|
37
|
+
return andThen(await analyze(args.cwd, session.value.profile, session.value.packs, [], optionsFrom(args)), (analysis) => reportAudit(analysis, flagBool(args, "offline")));
|
|
38
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { DIAGNOSTIC_LIMIT, mergeAnalyses, renderCheckText, summarize } from "../../domain/check-report.js";
|
|
2
|
+
import { capped } from "../../domain/diagnostics.js";
|
|
3
|
+
import { appError, EXIT } from "../../domain/errors.js";
|
|
4
|
+
import { andThen, err, ok } from "../../domain/result.js";
|
|
5
|
+
import { analyze, optionsFrom } from "../analysis.js";
|
|
6
|
+
import { recordHistory } from "../../infra/learn-sources.js";
|
|
7
|
+
import { buildSession } from "../session.js";
|
|
8
|
+
function countByRule(diagnostics) {
|
|
9
|
+
return diagnostics.reduce((acc, item) => ({ ...acc, [item.rule]: (acc[item.rule] ?? 0) + 1 }), {});
|
|
10
|
+
}
|
|
11
|
+
export function reportCheck(analysis) {
|
|
12
|
+
const merged = mergeAnalyses(analysis.results);
|
|
13
|
+
if (merged.ran && analysis.full)
|
|
14
|
+
recordHistory(analysis.root, { at: new Date().toISOString(), rules: countByRule(merged.diagnostics) });
|
|
15
|
+
if (!merged.ran) {
|
|
16
|
+
const fix = analysis.results.map((result) => result.missingFix).find((hint) => hint !== null) ?? "Install the tools the active packs need and run `guardrails plan`.";
|
|
17
|
+
return err(appError("missing-dependency", `nothing could run: ${merged.skipped.map((item) => `${item.tool}: ${item.reason}`).join("; ")}`, { fix }));
|
|
18
|
+
}
|
|
19
|
+
const summary = summarize(merged.diagnostics);
|
|
20
|
+
const shown = capped(merged.diagnostics, DIAGNOSTIC_LIMIT);
|
|
21
|
+
const verdict = summary.errors > 0 ? "fix" : summary.warnings > 0 ? "debt" : "clean";
|
|
22
|
+
return ok({
|
|
23
|
+
exit: summary.errors > 0 ? EXIT.findings : EXIT.ok,
|
|
24
|
+
data: { verdict, cached: analysis.cached, packs: analysis.profile.packs.map((pack) => pack.id), summary, skipped: merged.skipped, truncated: shown.truncated, phasesMs: analysis.phasesMs, diagnostics: shown.items },
|
|
25
|
+
text: renderCheckText(shown.items, summary, shown.truncated, merged.skipped),
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
export async function checkCommand(args, registry) {
|
|
29
|
+
const session = buildSession(args.cwd, registry);
|
|
30
|
+
if (!session.ok)
|
|
31
|
+
return session;
|
|
32
|
+
return andThen(await analyze(args.cwd, session.value.profile, session.value.packs, args.positionals, optionsFrom(args)), reportCheck);
|
|
33
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { EXIT } from "../../domain/errors.js";
|
|
2
|
+
import { stringifyJson } from "../../domain/json.js";
|
|
3
|
+
import { summarizeProfile } from "../../domain/profile.js";
|
|
4
|
+
import { map } from "../../domain/result.js";
|
|
5
|
+
import { writeManaged } from "../../infra/fs.js";
|
|
6
|
+
import { PROFILE_PATH, buildSession } from "../session.js";
|
|
7
|
+
export function detectCommand(root, registry) {
|
|
8
|
+
return map(buildSession(root, registry), ({ profile, packs }) => {
|
|
9
|
+
const change = writeManaged(root, PROFILE_PATH, stringifyJson(profile));
|
|
10
|
+
return {
|
|
11
|
+
exit: EXIT.ok,
|
|
12
|
+
data: { packs: profile.packs, profile, profilePath: PROFILE_PATH, change: change.action, next: "guardrails plan --json" },
|
|
13
|
+
text: `${summarizeProfile(profile, packs)}\nprofile ${change.action}: ${PROFILE_PATH}\nnext: guardrails plan`,
|
|
14
|
+
};
|
|
15
|
+
});
|
|
16
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { EXIT } from "../../domain/errors.js";
|
|
2
|
+
import { debtTotal, nextSteps, renderInitText } from "../../domain/init-report.js";
|
|
3
|
+
import { stringifyJson } from "../../domain/json.js";
|
|
4
|
+
import { baselineFromCounts } from "../../domain/ratchet.js";
|
|
5
|
+
import { ok } from "../../domain/result.js";
|
|
6
|
+
import { writeBaseline } from "../../infra/baseline.js";
|
|
7
|
+
import { backupFiles, ensureLines, runShellSync } from "../../infra/backup.js";
|
|
8
|
+
import { writeManaged } from "../../infra/fs.js";
|
|
9
|
+
import { analyze, optionsFrom } from "../analysis.js";
|
|
10
|
+
import { flagBool, flagString } from "../args.js";
|
|
11
|
+
import { catalogOf } from "../catalog.js";
|
|
12
|
+
import { commandsOf } from "../ci-plan.js";
|
|
13
|
+
import { PROFILE_PATH, buildSession } from "../session.js";
|
|
14
|
+
import { agentsMdCommand } from "./agents-md.js";
|
|
15
|
+
import { preflight } from "./apply.js";
|
|
16
|
+
const EDITED_FILES = ["package.json", "tsconfig.json", "eslint.config.mjs", "eslint.config.js", ".claude/settings.json", "AGENTS.md", ".gitignore"];
|
|
17
|
+
const IGNORED = [".guardrails/profile.json", ".guardrails/backup/", ".guardrails/history.jsonl"];
|
|
18
|
+
function ownerOf(args, session) {
|
|
19
|
+
const flag = flagString(args, "owner");
|
|
20
|
+
const remote = session.profile.git.remote;
|
|
21
|
+
return flag ?? (remote === null ? undefined : `@${remote.owner}`);
|
|
22
|
+
}
|
|
23
|
+
function ctxOf(args, session) {
|
|
24
|
+
const owner = ownerOf(args, session);
|
|
25
|
+
return { root: args.cwd, profile: session.profile, packs: session.packs, gradual: true, ...(owner === undefined ? {} : { owner }) };
|
|
26
|
+
}
|
|
27
|
+
function triage(session, ctx) {
|
|
28
|
+
const entries = catalogOf(session.packs);
|
|
29
|
+
const applicable = entries.filter((entry) => entry.constraint.notApplicable(session.profile) === null);
|
|
30
|
+
const pending = applicable.filter((entry) => !entry.constraint.isInstalled(ctx));
|
|
31
|
+
const checked = pending.map((entry) => ({ entry, error: preflight(entry.constraint, session) }));
|
|
32
|
+
return {
|
|
33
|
+
gaps: checked.filter((item) => item.error === null).map((item) => item.entry),
|
|
34
|
+
blocked: checked.flatMap((item) => (item.error === null ? [] : [{ id: item.entry.constraint.id, reason: item.error.message, fix: item.error.fix }])),
|
|
35
|
+
installed: applicable.length - pending.length,
|
|
36
|
+
notApplicable: entries.length - applicable.length,
|
|
37
|
+
missing: [...new Set(pending.flatMap((entry) => entry.constraint.requires(session.profile, session.packs).map((requirement) => requirement.pkg)))],
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
function installGroup(ctx, group) {
|
|
41
|
+
const first = group[0]?.batch;
|
|
42
|
+
if (first === undefined)
|
|
43
|
+
return [];
|
|
44
|
+
const result = first.run(ctx, group.flatMap((constraint) => (constraint.batch === undefined ? [] : [constraint.batch.payload])));
|
|
45
|
+
return group.map((constraint) => ({ id: constraint.id, result }));
|
|
46
|
+
}
|
|
47
|
+
function installAll(ctx, gaps) {
|
|
48
|
+
const constraints = gaps.map((entry) => entry.constraint);
|
|
49
|
+
const batchIds = [...new Set(constraints.flatMap((constraint) => (constraint.batch === undefined ? [] : [constraint.batch.id])))];
|
|
50
|
+
const batched = batchIds.flatMap((id) => installGroup(ctx, constraints.filter((constraint) => constraint.batch?.id === id)));
|
|
51
|
+
const single = constraints.filter((constraint) => constraint.batch === undefined).map((constraint) => ({ id: constraint.id, result: constraint.install(ctx) }));
|
|
52
|
+
return [...batched, ...single];
|
|
53
|
+
}
|
|
54
|
+
function summarizeOutcomes(outcomes) {
|
|
55
|
+
const done = outcomes.flatMap((item) => (item.result.ok ? [{ id: item.id, outcome: item.result.value }] : []));
|
|
56
|
+
const rows = done.map((item) => ({ id: item.id, level: Object.values(item.outcome.levels).includes("deferred") ? "deferred" : "installed", notes: item.outcome.notes }));
|
|
57
|
+
return {
|
|
58
|
+
applied: rows.filter((row) => row.level !== "deferred"),
|
|
59
|
+
deferred: rows.filter((row) => row.level === "deferred"),
|
|
60
|
+
failed: outcomes.flatMap((item) => (item.result.ok ? [] : [{ id: item.id, reason: item.result.error.message, fix: item.result.error.fix }])),
|
|
61
|
+
changes: done.flatMap((item) => item.outcome.changes),
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
function dryRun(args, session, found) {
|
|
65
|
+
const install = found.missing.length === 0 ? null : (commandsOf(session.packs)?.installDev(session.profile, found.missing) ?? null);
|
|
66
|
+
const ids = found.gaps.map((entry) => entry.constraint.id);
|
|
67
|
+
return ok({
|
|
68
|
+
exit: EXIT.ok,
|
|
69
|
+
data: { dryRun: true, packs: session.profile.packs.map((pack) => pack.id), wouldApply: ids, blocked: found.blocked, alreadyInstalled: found.installed, notApplicable: found.notApplicable, install, wouldBackUp: EDITED_FILES },
|
|
70
|
+
text: [`dry run in ${args.cwd}`, `packs: ${session.profile.packs.map((pack) => pack.id).join(", ")}`, `would apply ${String(ids.length)}: ${ids.join(", ")}`, ...found.blocked.map((item) => `blocked: ${item.id}: ${item.reason}`), ...(install === null ? [] : [`install first: ${install}`])].join("\n"),
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
function tryInstall(args, session, found) {
|
|
74
|
+
const command = found.missing.length === 0 ? null : (commandsOf(session.packs)?.installDev(session.profile, found.missing) ?? null);
|
|
75
|
+
if (command !== null && flagBool(args, "install"))
|
|
76
|
+
runShellSync(args.cwd, command);
|
|
77
|
+
return command;
|
|
78
|
+
}
|
|
79
|
+
export async function initCommand(args, registry) {
|
|
80
|
+
const first = buildSession(args.cwd, registry);
|
|
81
|
+
if (!first.ok)
|
|
82
|
+
return first;
|
|
83
|
+
const found = triage(first.value, ctxOf(args, first.value));
|
|
84
|
+
if (flagBool(args, "dry-run"))
|
|
85
|
+
return dryRun(args, first.value, found);
|
|
86
|
+
const command = tryInstall(args, first.value, found);
|
|
87
|
+
const session = flagBool(args, "install") && command !== null ? buildSession(args.cwd, registry) : first;
|
|
88
|
+
if (!session.ok)
|
|
89
|
+
return session;
|
|
90
|
+
return finishInit(args, session.value, registry, command);
|
|
91
|
+
}
|
|
92
|
+
async function finishInit(args, session, registry, command) {
|
|
93
|
+
const ctx = ctxOf(args, session);
|
|
94
|
+
const found = triage(session, ctx);
|
|
95
|
+
const stillMissing = flagBool(args, "install") ? [] : found.missing;
|
|
96
|
+
const backups = backupFiles(args.cwd, EDITED_FILES);
|
|
97
|
+
const gitignore = ensureLines(args.cwd, ".gitignore", IGNORED);
|
|
98
|
+
const done = summarizeOutcomes(installAll(ctx, found.gaps));
|
|
99
|
+
const fresh = buildSession(args.cwd, registry);
|
|
100
|
+
if (!fresh.ok)
|
|
101
|
+
return fresh;
|
|
102
|
+
const analyzed = await analyze(args.cwd, fresh.value.profile, fresh.value.packs, [], optionsFrom(args));
|
|
103
|
+
if (!analyzed.ok)
|
|
104
|
+
return analyzed;
|
|
105
|
+
const analysis = analyzed.value;
|
|
106
|
+
const debt = analysis.results.reduce((all, result) => ({ ...all, ...result.debt }), {});
|
|
107
|
+
const baseline = writeBaseline(args.cwd, baselineFromCounts(debt));
|
|
108
|
+
const agents = agentsMdCommand(args.cwd, registry);
|
|
109
|
+
const profile = writeManaged(args.cwd, PROFILE_PATH, stringifyJson(fresh.value.profile));
|
|
110
|
+
const errors = analysis.results.flatMap((result) => result.diagnostics).filter((item) => item.severity === "error" && item.tool !== "ratchet").length;
|
|
111
|
+
const summary = {
|
|
112
|
+
packs: fresh.value.profile.packs.map((pack) => pack.id),
|
|
113
|
+
applied: done.applied,
|
|
114
|
+
alreadyInstalled: found.installed,
|
|
115
|
+
notApplicable: found.notApplicable,
|
|
116
|
+
blocked: [...found.blocked, ...done.failed],
|
|
117
|
+
deferred: done.deferred,
|
|
118
|
+
debt,
|
|
119
|
+
errors,
|
|
120
|
+
install: stillMissing.length === 0 ? null : command,
|
|
121
|
+
changes: [...done.changes, gitignore, baseline, profile, ...(agents.ok ? [{ path: "AGENTS.md", action: "updated" }] : [])],
|
|
122
|
+
backups,
|
|
123
|
+
};
|
|
124
|
+
const steps = nextSteps(summary);
|
|
125
|
+
const clean = summary.blocked.length === 0 && errors === 0 && summary.install === null;
|
|
126
|
+
return ok({ exit: clean ? EXIT.ok : EXIT.findings, data: { ...summary, debtTotal: debtTotal(debt), phasesMs: analysis.phasesMs, next: steps }, text: renderInitText(summary, steps) });
|
|
127
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { EXIT } from "../../domain/errors.js";
|
|
2
|
+
import { proposeDebt, proposeInstalls, proposeRecurring, tally, total } from "../../domain/learn.js";
|
|
3
|
+
import { map } from "../../domain/result.js";
|
|
4
|
+
import { readBaseline } from "../../infra/baseline.js";
|
|
5
|
+
import { ciFailureLines, fixCommitSubjects, readHistory, reviewComments } from "../../infra/learn-sources.js";
|
|
6
|
+
import { flagBool } from "../args.js";
|
|
7
|
+
import { catalogOf } from "../catalog.js";
|
|
8
|
+
import { buildSession } from "../session.js";
|
|
9
|
+
function pendingIds(session) {
|
|
10
|
+
const ctx = { root: session.root, profile: session.profile, packs: session.packs };
|
|
11
|
+
return new Set(catalogOf(session.packs).filter((entry) => entry.constraint.notApplicable(session.profile) === null && !entry.constraint.isInstalled(ctx)).map((entry) => entry.constraint.id));
|
|
12
|
+
}
|
|
13
|
+
function signalsOf(packs) {
|
|
14
|
+
return packs.flatMap((pack) => pack.signals ?? []);
|
|
15
|
+
}
|
|
16
|
+
function gather(session, offline) {
|
|
17
|
+
const { root, profile, packs } = session;
|
|
18
|
+
const signals = signalsOf(packs);
|
|
19
|
+
const repo = profile.git.remote === null ? null : `${profile.git.remote.owner}/${profile.git.remote.repo}`;
|
|
20
|
+
const history = readHistory(root);
|
|
21
|
+
const commits = fixCommitSubjects(root);
|
|
22
|
+
const reviews = offline || repo === null ? { texts: [], available: false } : reviewComments(root, repo);
|
|
23
|
+
const ci = offline || repo === null ? { texts: [], available: false } : ciFailureLines(root);
|
|
24
|
+
const baseline = readBaseline(root).rules;
|
|
25
|
+
const ruleNames = Object.keys(baseline);
|
|
26
|
+
const installs = proposeInstalls([
|
|
27
|
+
{ source: "fix-commits", tallies: tally(commits, signals) },
|
|
28
|
+
{ source: "reviews", tallies: tally(reviews.texts, signals) },
|
|
29
|
+
{ source: "ci", tallies: tally(ci.texts, signals) },
|
|
30
|
+
], pendingIds(session));
|
|
31
|
+
const debt = proposeDebt(baseline);
|
|
32
|
+
return {
|
|
33
|
+
proposals: [...installs, ...proposeRecurring(history), ...debt],
|
|
34
|
+
sources: { "check-history": `${String(history.length)} runs`, "fix-commits": `${String(commits.length)} lines`, reviews: reviews.available ? `${String(reviews.texts.length)} comments` : "unavailable (offline, no remote or gh)", ci: ci.available ? `${String(ci.texts.length)} log lines` : "unavailable (offline, no remote or gh)", baseline: `${String(ruleNames.length)} rules` },
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
function render(proposals, sources) {
|
|
38
|
+
return [
|
|
39
|
+
`sources: ${Object.entries(sources).map(([name, detail]) => `${name} ${detail}`).join("; ")}`,
|
|
40
|
+
...(proposals.length === 0 ? ["no proposals yet: run `guardrails check` more often so the history fills, or add --offline false with gh access"] : proposals.slice(0, 15).map((item) => `${item.kind} ${item.id} (${String(total(item.evidence))} signals): ${item.command}`)),
|
|
41
|
+
].join("\n");
|
|
42
|
+
}
|
|
43
|
+
export function learnCommand(args, registry) {
|
|
44
|
+
return map(buildSession(args.cwd, registry), (session) => {
|
|
45
|
+
const { proposals, sources } = gather(session, flagBool(args, "offline"));
|
|
46
|
+
return { exit: EXIT.ok, data: { sources, count: proposals.length, proposals }, text: render(proposals, sources) };
|
|
47
|
+
});
|
|
48
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { EXIT } from "../../domain/errors.js";
|
|
2
|
+
import { stringifyJson } from "../../domain/json.js";
|
|
3
|
+
import { map } from "../../domain/result.js";
|
|
4
|
+
import { writeManaged } from "../../infra/fs.js";
|
|
5
|
+
import { flagBool } from "../args.js";
|
|
6
|
+
import { catalogOf } from "../catalog.js";
|
|
7
|
+
import { commandsOf } from "../ci-plan.js";
|
|
8
|
+
import { PROFILE_PATH, buildSession } from "../session.js";
|
|
9
|
+
function itemOf({ constraint, pack }, ctx) {
|
|
10
|
+
const { profile } = ctx;
|
|
11
|
+
const base = { id: constraint.id, pack, title: constraint.title, layer: constraint.layer, why: constraint.why, apply: `guardrails apply ${constraint.id}` };
|
|
12
|
+
const reason = constraint.notApplicable(profile);
|
|
13
|
+
if (reason !== null)
|
|
14
|
+
return { ...base, status: "not-applicable", reason, requires: [] };
|
|
15
|
+
const done = constraint.isInstalled(ctx);
|
|
16
|
+
return { ...base, status: done ? "installed" : "gap", requires: done ? [] : constraint.requires(profile, ctx.packs) };
|
|
17
|
+
}
|
|
18
|
+
const MARK = { gap: "GAP ", installed: "ok ", "not-applicable": "n/a " };
|
|
19
|
+
function render(items, install) {
|
|
20
|
+
const gaps = items.filter((item) => item.status === "gap").length;
|
|
21
|
+
const count = (status) => items.filter((item) => item.status === status).length;
|
|
22
|
+
return [
|
|
23
|
+
...items.map((item) => `${MARK[item.status]} ${item.id} [${item.pack}]${item.reason === undefined ? "" : ` (${item.reason})`}`),
|
|
24
|
+
`${count("installed")} installed, ${gaps} gaps, ${count("not-applicable")} not applicable`,
|
|
25
|
+
...(install === null ? [] : [`first install the packages: ${install}`]),
|
|
26
|
+
...(gaps > 0 ? ["then: guardrails apply <id> for each GAP, in the order above"] : []),
|
|
27
|
+
].join("\n");
|
|
28
|
+
}
|
|
29
|
+
export function planCommand(args, registry) {
|
|
30
|
+
return map(buildSession(args.cwd, registry), ({ profile, packs }) => {
|
|
31
|
+
writeManaged(args.cwd, PROFILE_PATH, stringifyJson(profile));
|
|
32
|
+
const ctx = { root: args.cwd, profile, packs };
|
|
33
|
+
const items = catalogOf(packs).map((entry) => itemOf(entry, ctx));
|
|
34
|
+
const gaps = items.filter((item) => item.status === "gap");
|
|
35
|
+
const packages = [...new Set(gaps.flatMap((item) => item.requires.map((requirement) => requirement.pkg)))];
|
|
36
|
+
const install = packages.length === 0 ? null : (commandsOf(packs)?.installDev(profile, packages) ?? `install: ${packages.join(" ")}`);
|
|
37
|
+
const counts = { installed: items.filter((item) => item.status === "installed").length, gaps: gaps.length, notApplicable: items.filter((item) => item.status === "not-applicable").length };
|
|
38
|
+
return { exit: flagBool(args, "fail-on-gaps") && gaps.length > 0 ? EXIT.findings : EXIT.ok, data: { packs: profile.packs.map((pack) => pack.id), counts, install, items }, text: render(items, install) };
|
|
39
|
+
});
|
|
40
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { EXIT } from "../../domain/errors.js";
|
|
2
|
+
import { parseLog } from "../../domain/log-parse.js";
|
|
3
|
+
import { renderComment } from "../../domain/pr-comment.js";
|
|
4
|
+
import { attemptsOf, clearPr, failedShas, nextStep, recordFailure, verdictOf } from "../../domain/pr-loop.js";
|
|
5
|
+
import { andThen, ok } from "../../domain/result.js";
|
|
6
|
+
import { jobLog, readLoopState, readPr, upsertComment, waitForChecks, writeLoopState } from "../../infra/pr.js";
|
|
7
|
+
import { flagBool, flagString } from "../args.js";
|
|
8
|
+
import { buildSession } from "../session.js";
|
|
9
|
+
const fixesOf = (packs) => packs.reduce((all, pack) => ({ ...all, ...pack.fixes }), {});
|
|
10
|
+
const withFix = (fixes, entry) => {
|
|
11
|
+
const known = entry.rule === null ? undefined : fixes[entry.rule];
|
|
12
|
+
return known === undefined ? entry : { ...entry, fix: known };
|
|
13
|
+
};
|
|
14
|
+
function failingChecks(root, pr, ignore, fixes) {
|
|
15
|
+
return pr.checks
|
|
16
|
+
.filter((check) => check.state === "fail" && !ignore.includes(check.name))
|
|
17
|
+
.map((check) => ({ check: check.name, url: check.url, diagnostics: parseLog(check.name, check.jobId === null ? "" : jobLog(root, check.jobId)).map((entry) => withFix(fixes, entry)) }));
|
|
18
|
+
}
|
|
19
|
+
function settle(root, pr, base, record) {
|
|
20
|
+
const state = readLoopState(root);
|
|
21
|
+
const next = base === "fix" ? recordFailure(state, pr.number, pr.head) : base === "green" ? clearPr(state, pr.number) : state;
|
|
22
|
+
if (record && next !== state)
|
|
23
|
+
writeLoopState(root, next);
|
|
24
|
+
const attempts = attemptsOf(failedShas(next, pr.number));
|
|
25
|
+
return { verdict: base === "fix" && attempts.left === 0 ? "escalate" : base, report: { attempts } };
|
|
26
|
+
}
|
|
27
|
+
function build(root, pr, args, fixes, record) {
|
|
28
|
+
const ignore = (flagString(args, "ignore") ?? "").split(",").filter((name) => name !== "");
|
|
29
|
+
const base = verdictOf(pr.checks, ignore, flagBool(args, "ignore-pending"));
|
|
30
|
+
const settled = settle(root, pr, base, record);
|
|
31
|
+
return {
|
|
32
|
+
verdict: settled.verdict,
|
|
33
|
+
pr: { number: pr.number, url: pr.url, head: pr.head, branch: pr.branch, base: pr.base },
|
|
34
|
+
attempts: settled.report.attempts,
|
|
35
|
+
checks: pr.checks.map(({ name, state, url }) => ({ name, state, url })),
|
|
36
|
+
failing: base === "fix" ? failingChecks(root, pr, ignore, fixes) : [],
|
|
37
|
+
next: nextStep(settled.verdict, settled.report.attempts),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
function textOf(report) {
|
|
41
|
+
const rows = report.failing.flatMap((failing) => [`${failing.check}: ${String(failing.diagnostics.length)} to fix`, ...failing.diagnostics.map((entry) => ` ${entry.file}${entry.line > 0 ? `:${String(entry.line)}` : ""} [${entry.rule ?? entry.test ?? "-"}] ${entry.message}\n fix: ${entry.fix}`)]);
|
|
42
|
+
return [`PR #${String(report.pr.number)}: ${report.verdict}`, ...rows, report.next].join("\n");
|
|
43
|
+
}
|
|
44
|
+
function output(report, commented) {
|
|
45
|
+
const exit = report.verdict === "green" ? EXIT.ok : report.verdict === "escalate" ? EXIT.precondition : EXIT.findings;
|
|
46
|
+
return { exit, data: { ...report, commented }, text: textOf(report) };
|
|
47
|
+
}
|
|
48
|
+
async function load(args) {
|
|
49
|
+
const number = flagString(args, "pr");
|
|
50
|
+
const first = readPr(args.cwd, number);
|
|
51
|
+
if (!first.ok || !flagBool(args, "wait"))
|
|
52
|
+
return first;
|
|
53
|
+
await waitForChecks(args.cwd, first.value.number);
|
|
54
|
+
return readPr(args.cwd, String(first.value.number));
|
|
55
|
+
}
|
|
56
|
+
async function run(args, registry, record) {
|
|
57
|
+
const session = buildSession(args.cwd, registry);
|
|
58
|
+
const fixes = session.ok ? fixesOf(session.value.packs) : {};
|
|
59
|
+
return andThen(await load(args), (pr) => {
|
|
60
|
+
const report = build(args.cwd, pr, args, fixes, record);
|
|
61
|
+
const commented = flagBool(args, "comment") ? upsertComment(args.cwd, pr.number, renderComment(report)) : null;
|
|
62
|
+
return ok(output(report, commented));
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
export const prStatusCommand = (args, registry) => run(args, registry, false);
|
|
66
|
+
export const prRepairCommand = (args, registry) => run(args, registry, true);
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { EXIT } from "../../domain/errors.js";
|
|
2
|
+
import { andThen, ok } from "../../domain/result.js";
|
|
3
|
+
import { analyze, optionsFrom } from "../analysis.js";
|
|
4
|
+
import { flagBool } from "../args.js";
|
|
5
|
+
import { buildSession } from "../session.js";
|
|
6
|
+
import { reportAudit } from "./audit.js";
|
|
7
|
+
import { reportCheck } from "./check.js";
|
|
8
|
+
export async function selfCheckCommand(args, registry) {
|
|
9
|
+
const session = buildSession(args.cwd, registry);
|
|
10
|
+
if (!session.ok)
|
|
11
|
+
return session;
|
|
12
|
+
const analyzed = await analyze(args.cwd, session.value.profile, session.value.packs, [], optionsFrom(args));
|
|
13
|
+
if (!analyzed.ok)
|
|
14
|
+
return analyzed;
|
|
15
|
+
const analysis = analyzed.value;
|
|
16
|
+
return andThen(reportCheck(analysis), (check) => andThen(reportAudit(analysis, flagBool(args, "offline")), (audit) => {
|
|
17
|
+
const clean = check.exit === EXIT.ok && audit.exit === EXIT.ok;
|
|
18
|
+
return ok({ exit: clean ? EXIT.ok : EXIT.findings, data: { cached: analysis.cached, verdict: clean ? (check.data["verdict"] === "debt" ? "debt" : "clean") : "fix", check: check.data, audit: audit.data, phasesMs: analysis.phasesMs }, text: `${check.text}\n${audit.text}` });
|
|
19
|
+
}));
|
|
20
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { appError } from "../domain/errors.js";
|
|
2
|
+
import { andThen, collect, err, map, ok } from "../domain/result.js";
|
|
3
|
+
import { readAsset } from "../infra/assets.js";
|
|
4
|
+
import { preCommitScript } from "./hooks-script.js";
|
|
5
|
+
import { exists, writeIfAbsent } from "../infra/fs.js";
|
|
6
|
+
import { gitConfigGet, gitConfigSet, runCommitMsgHook, shellSyntax } from "../infra/hooks.js";
|
|
7
|
+
import { installed } from "../domain/constraint.js";
|
|
8
|
+
export const HOOKS_DIR = ".githooks";
|
|
9
|
+
const notApplicable = (profile) => (profile.git.isRepo ? null : "not a git repository");
|
|
10
|
+
function hooksActive(ctx) {
|
|
11
|
+
return ctx.profile.git.hooksPath === HOOKS_DIR || ctx.packs.some((pack) => pack.hooks?.bootstrap?.active(ctx) === true);
|
|
12
|
+
}
|
|
13
|
+
function activateHooks(ctx) {
|
|
14
|
+
const { root, profile } = ctx;
|
|
15
|
+
if (profile.git.hooksPath === HOOKS_DIR)
|
|
16
|
+
return ok([]);
|
|
17
|
+
if (profile.git.hooksPath !== null) {
|
|
18
|
+
return err(appError("conflict", `core.hooksPath already points to ${profile.git.hooksPath}`, {
|
|
19
|
+
file: `${profile.git.hooksPath}/pre-commit`,
|
|
20
|
+
fix: `Copy the guardrails hook into ${profile.git.hooksPath}/ by hand (see catalog-assets/githooks in the guardrails package), or run \`git config core.hooksPath ${HOOKS_DIR}\` yourself if you want to move the hooks.`,
|
|
21
|
+
}));
|
|
22
|
+
}
|
|
23
|
+
const result = gitConfigSet(root, "core.hooksPath", HOOKS_DIR);
|
|
24
|
+
return result.ok ? ok([{ path: ".git/config (core.hooksPath)", action: "updated" }]) : err(appError("verify-failed", `git config core.hooksPath failed: ${result.detail}`, { fix: `Run \`git config core.hooksPath ${HOOKS_DIR}\` in the repo.` }));
|
|
25
|
+
}
|
|
26
|
+
function ensureBootstrap(ctx) {
|
|
27
|
+
const steps = ctx.packs.flatMap((pack) => {
|
|
28
|
+
const bootstrap = pack.hooks?.bootstrap;
|
|
29
|
+
return bootstrap === null || bootstrap === undefined ? [] : [bootstrap.ensure(ctx)];
|
|
30
|
+
});
|
|
31
|
+
return map(collect(steps), (lists) => lists.flat());
|
|
32
|
+
}
|
|
33
|
+
function installHook(ctx, name, content) {
|
|
34
|
+
return andThen(writeIfAbsent(ctx.root, `${HOOKS_DIR}/${name}`, content, `git-${name}`, 0o755), (file) => andThen(activateHooks(ctx), (hooks) => andThen(ensureBootstrap(ctx), (boot) => installed([file, ...hooks, ...boot]))));
|
|
35
|
+
}
|
|
36
|
+
function hookChecks(ctx, name) {
|
|
37
|
+
const syntax = shellSyntax(ctx.root, `${HOOKS_DIR}/${name}`);
|
|
38
|
+
const hooksPath = gitConfigGet(ctx.root, "core.hooksPath");
|
|
39
|
+
return [
|
|
40
|
+
{ name: `${name} exists`, ok: exists(ctx.root, `${HOOKS_DIR}/${name}`), detail: `${HOOKS_DIR}/${name}` },
|
|
41
|
+
{ name: `${name} shell syntax`, ok: syntax.ok, detail: syntax.detail },
|
|
42
|
+
{ name: "core.hooksPath", ok: hooksPath === HOOKS_DIR, detail: hooksPath === "" ? "unset" : hooksPath },
|
|
43
|
+
];
|
|
44
|
+
}
|
|
45
|
+
export const gitPreCommit = {
|
|
46
|
+
id: "git-pre-commit",
|
|
47
|
+
title: "pre-commit runs the linters on staged files and the typechecks",
|
|
48
|
+
layer: "git-hook",
|
|
49
|
+
why: "A commit that fails lint or types never leaves the agent's machine.",
|
|
50
|
+
notApplicable,
|
|
51
|
+
requires: () => [],
|
|
52
|
+
isInstalled: (ctx) => exists(ctx.root, `${HOOKS_DIR}/pre-commit`) && hooksActive(ctx),
|
|
53
|
+
install: (ctx) => installHook(ctx, "pre-commit", preCommitScript(ctx.profile, ctx.packs)),
|
|
54
|
+
verify: (ctx) => hookChecks(ctx, "pre-commit"),
|
|
55
|
+
};
|
|
56
|
+
export const gitCommitMsg = {
|
|
57
|
+
id: "git-commit-msg",
|
|
58
|
+
title: "commit-msg enforces Conventional Commits",
|
|
59
|
+
layer: "git-hook",
|
|
60
|
+
why: "A predictable history makes reverts and releases mechanical.",
|
|
61
|
+
notApplicable,
|
|
62
|
+
requires: () => [],
|
|
63
|
+
isInstalled: (ctx) => exists(ctx.root, `${HOOKS_DIR}/commit-msg`) && hooksActive(ctx),
|
|
64
|
+
install: (ctx) => installHook(ctx, "commit-msg", readAsset("githooks/commit-msg")),
|
|
65
|
+
verify: (ctx) => {
|
|
66
|
+
const hook = `${HOOKS_DIR}/commit-msg`;
|
|
67
|
+
const rejects = runCommitMsgHook(ctx.root, hook, "did some stuff");
|
|
68
|
+
const accepts = runCommitMsgHook(ctx.root, hook, "feat(core): add thing");
|
|
69
|
+
return [
|
|
70
|
+
...hookChecks(ctx, "commit-msg"),
|
|
71
|
+
{ name: "commit-msg rejects a free-form subject", ok: rejects !== 0, detail: `exit ${rejects}` },
|
|
72
|
+
{ name: "commit-msg accepts a Conventional Commit", ok: accepts === 0, detail: `exit ${accepts}` },
|
|
73
|
+
];
|
|
74
|
+
},
|
|
75
|
+
};
|