@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,155 @@
1
+ import { OWN_PREFIX, sampleFile } from "../domain/catalog-specs.js";
2
+ import { UNUSED_DIRECTIVE_RULE, severityOf, violationsOf } from "../domain/eslint-output.js";
3
+ import { RULES_JSON, userConfigHasTypedParser, withRule } from "../domain/eslint-state.js";
4
+ import { appError } from "../../../core/domain/errors.js";
5
+ import { isRecord } from "../../../core/domain/json.js";
6
+ import { andThen, err, ok } from "../../../core/domain/result.js";
7
+ import { jsTs } from "../domain/data.js";
8
+ import { hasEslint, lintRepo, printConfigRules, probeRules } from "../infra/eslint.js";
9
+ import { readText } from "../../../core/infra/fs.js";
10
+ import { copyOwnRule, readState, wireEslintConfig, writeIndexAndConfig, writeState } from "./eslint-files.js";
11
+ const isOwn = (name) => name.startsWith(OWN_PREFIX);
12
+ const ownId = (def) => def.name.slice(OWN_PREFIX.length);
13
+ function baseNotApplicable(profile) {
14
+ if (!jsTs(profile).typescript.present)
15
+ return "TypeScript not detected";
16
+ return jsTs(profile).eslint.config !== null && !jsTs(profile).eslint.flat ? "legacy .eslintrc config; guardrails needs ESLint flat config (eslint.config.*)" : null;
17
+ }
18
+ function probeFilename(profile, def) {
19
+ const scoped = def?.files?.(profile)[0];
20
+ if (scoped !== undefined)
21
+ return sampleFile(scoped);
22
+ const first = jsTs(profile).paths.sourceGlobs[0];
23
+ return `${first === undefined ? "." : (first.split("/**")[0] ?? ".")}/__guardrails_probe__.ts`;
24
+ }
25
+ function requirements(profile, usesTypescriptEslint) {
26
+ const { eslint } = jsTs(profile);
27
+ const needsPlugin = usesTypescriptEslint ? !eslint.typescriptPlugin : eslint.config === null && !eslint.typescriptEslintPackage;
28
+ return [
29
+ ...(eslint.installed ? [] : [{ pkg: "eslint", reason: "guardrails rules run through ESLint" }]),
30
+ ...(needsPlugin ? [{ pkg: "typescript-eslint", reason: "TypeScript parser and @typescript-eslint rules" }] : []),
31
+ ];
32
+ }
33
+ function entryFor(def, profile, level) {
34
+ const options = def.options?.(profile);
35
+ const ignores = def.ignores?.(profile);
36
+ return {
37
+ level,
38
+ files: def.files?.(profile) ?? jsTs(profile).paths.sourceGlobs,
39
+ ...(ignores === undefined || ignores.length === 0 ? {} : { ignores }),
40
+ ...(options === undefined ? {} : { options }),
41
+ ...(def.typed === true ? { typed: true } : {}),
42
+ };
43
+ }
44
+ function warnState(ctx, current, defs, linterWarn) {
45
+ const config = jsTs(ctx.profile).eslint.config;
46
+ const configText = config === null ? "" : (readText(ctx.root, config) ?? "");
47
+ const typedParser = current.typedParser || (defs.some((def) => def.typed === true) && !userConfigHasTypedParser(configText));
48
+ const rules = defs.reduce((state, def) => withRule(state, def.name, entryFor(def, ctx.profile, current.rules[def.name]?.level === "error" ? "error" : "warn")), { ...current, typedParser });
49
+ const unused = linterWarn && current.linterOptions.reportUnusedDisableDirectives === undefined ? { reportUnusedDisableDirectives: "warn" } : current.linterOptions;
50
+ return { ...rules, linterOptions: unused };
51
+ }
52
+ function promote(ctx, defs, linterWarn, base, lint) {
53
+ const levels = Object.fromEntries(defs.map((def) => [def.name, violationsOf(lint, def.name).length === 0 ? "error" : "warn"]));
54
+ const withLevels = defs.reduce((state, def) => withRule(state, def.name, entryFor(def, ctx.profile, levels[def.name] === "error" ? "error" : "warn")), base);
55
+ const unusedClean = violationsOf(lint, UNUSED_DIRECTIVE_RULE).length === 0;
56
+ const linterOptions = linterWarn ? { reportUnusedDisableDirectives: unusedClean ? "error" : "warn" } : withLevels.linterOptions;
57
+ return { state: { ...withLevels, linterOptions }, levels };
58
+ }
59
+ export function installEslintRules(ctx, defs, linterWarn) {
60
+ const { root } = ctx;
61
+ if (!hasEslint(root)) {
62
+ return err(appError("missing-dependency", "eslint is not installed in node_modules", { file: "package.json", fix: "Install eslint (and typescript-eslint) as exact devDependencies with the package manager, then run apply again." }));
63
+ }
64
+ return andThen(readState(root), (current) => {
65
+ const base = warnState(ctx, current, defs, linterWarn);
66
+ const written = [...defs.filter((def) => isOwn(def.name)).flatMap((def) => copyOwnRule(root, ownId(def))), writeState(root, base), ...writeIndexAndConfig(root)];
67
+ return andThen(wireEslintConfig(ctx), (wiring) => finalize(ctx, defs, linterWarn, base, [...written, ...wiring]));
68
+ });
69
+ }
70
+ function finalize(ctx, defs, linterWarn, base, changes) {
71
+ const lint = lintRepo(ctx.root, jsTs(ctx.profile));
72
+ if (!lint.ran) {
73
+ return err(appError("verify-failed", `eslint could not run after installing the rules: ${lint.error ?? "unknown error"}`, { file: jsTs(ctx.profile).eslint.config ?? "eslint.config.mjs", fix: "Fix the ESLint configuration error above (missing plugin or parser is the usual cause), then run apply again. Files written so far were kept." }));
74
+ }
75
+ const promoted = promote(ctx, defs, linterWarn, base, lint);
76
+ const pending = defs.filter((def) => promoted.levels[def.name] === "warn").map((def) => def.name);
77
+ return ok({
78
+ changes: [...changes, writeState(ctx.root, promoted.state)],
79
+ notes: pending.length === 0 ? [] : [`${pending.join(", ")} stay at warn until violations reach 0: fix them (guardrails check), then run the same apply again to promote them to error.`],
80
+ violations: defs.flatMap((def) => violationsOf(lint, def.name)),
81
+ levels: promoted.levels,
82
+ });
83
+ }
84
+ function registeredCheck(def, state) {
85
+ const entry = state.rules[def.name];
86
+ return { name: `${def.name} registered`, ok: entry !== undefined, detail: entry === undefined ? `missing from ${RULES_JSON}` : `level ${entry.level}` };
87
+ }
88
+ function activeCheck(def, configured) {
89
+ const severity = configured === null ? null : severityOf(configured[def.name]);
90
+ return { name: `${def.name} active in ESLint`, ok: severity !== null && severity !== "off", detail: severity === null ? "eslint --print-config failed; fix the ESLint config" : `eslint resolves it as ${severity}` };
91
+ }
92
+ function probeCheck(ctx, def) {
93
+ if (def.probe === undefined || ctx.gradual === true || !hasEslint(ctx.root))
94
+ return [];
95
+ const probe = probeRules(ctx.root, probeFilename(ctx.profile, def), def.probe);
96
+ if (!probe.usable)
97
+ return [];
98
+ return [{ name: `${def.name} fires on a violating snippet`, ok: probe.rules.has(def.name), detail: probe.rules.has(def.name) ? "probe reported the rule" : "probe did not report the rule" }];
99
+ }
100
+ function ruleChecks(ctx, def, state, configured) {
101
+ return [registeredCheck(def, state), activeCheck(def, configured), ...probeCheck(ctx, def)];
102
+ }
103
+ export function verifyEslintRules(ctx, defs) {
104
+ const state = readState(ctx.root);
105
+ if (!state.ok)
106
+ return [{ name: RULES_JSON, ok: false, detail: state.error.message }];
107
+ const files = [...new Set(defs.map((def) => probeFilename(ctx.profile, def)))];
108
+ const configs = Object.fromEntries(files.map((file) => [file, hasEslint(ctx.root) ? printConfigRules(ctx.root, file) : null]));
109
+ return defs.flatMap((def) => ruleChecks(ctx, def, state.value, configs[probeFilename(ctx.profile, def)] ?? null));
110
+ }
111
+ function isBatchPayload(value) {
112
+ return isRecord(value) && Array.isArray(value["defs"]) && typeof value["linterWarn"] === "boolean";
113
+ }
114
+ function runBatch(ctx, payloads) {
115
+ const items = payloads.filter(isBatchPayload);
116
+ return installEslintRules(ctx, items.flatMap((item) => item.defs), items.some((item) => item.linterWarn));
117
+ }
118
+ const batchOf = (payload) => ({ id: "eslint", payload, run: runBatch });
119
+ export function eslintConstraint(spec) {
120
+ const usesTs = spec.rules.some((def) => def.name.startsWith("@typescript-eslint/"));
121
+ return {
122
+ batch: batchOf({ defs: spec.rules, linterWarn: false }),
123
+ id: spec.id,
124
+ title: spec.title,
125
+ layer: "lint",
126
+ why: spec.why,
127
+ notApplicable: (profile) => baseNotApplicable(profile) ?? spec.applies?.(profile) ?? null,
128
+ requires: (profile) => requirements(profile, usesTs),
129
+ isInstalled: ({ root }) => {
130
+ const state = readState(root);
131
+ return state.ok && spec.rules.every((def) => state.value.rules[def.name] !== undefined);
132
+ },
133
+ install: (ctx) => installEslintRules(ctx, spec.rules, false),
134
+ verify: (ctx) => verifyEslintRules(ctx, spec.rules),
135
+ };
136
+ }
137
+ export const unusedDisableDirectives = {
138
+ batch: batchOf({ defs: [], linterWarn: true }),
139
+ id: "unused-disable-directives",
140
+ title: "Unused eslint-disable directives fail the lint",
141
+ layer: "lint",
142
+ why: "A disable that no longer suppresses anything hides that the code was fixed; the directive should be deleted.",
143
+ notApplicable: baseNotApplicable,
144
+ requires: (profile) => requirements(profile, false),
145
+ isInstalled: ({ root }) => {
146
+ const state = readState(root);
147
+ return state.ok && state.value.linterOptions.reportUnusedDisableDirectives !== undefined;
148
+ },
149
+ install: (ctx) => installEslintRules(ctx, [], true),
150
+ verify: ({ root }) => {
151
+ const state = readState(root);
152
+ const level = state.ok ? state.value.linterOptions.reportUnusedDisableDirectives : undefined;
153
+ return [{ name: "reportUnusedDisableDirectives set", ok: level !== undefined, detail: level ?? `missing from ${RULES_JSON}` }];
154
+ },
155
+ };
@@ -0,0 +1,56 @@
1
+ import { PLUGIN_DIR, RULES_JSON, newConfigText, parseRulesState, renderPluginIndex, serializeState, wireConfigText } from "../domain/eslint-state.js";
2
+ import { appError } from "../../../core/domain/errors.js";
3
+ import { collect, err, ok } from "../../../core/domain/result.js";
4
+ import { readAsset } from "../../../core/infra/assets.js";
5
+ import { listDir, readText, writeManaged } from "../../../core/infra/fs.js";
6
+ import { jsTs } from "../domain/data.js";
7
+ export function readState(root) {
8
+ const parsed = parseRulesState(readText(root, RULES_JSON));
9
+ if (parsed.ok)
10
+ return parsed;
11
+ return err(appError("unsupported-config", `${RULES_JSON} is not valid JSON`, { file: RULES_JSON, fix: `Fix the JSON syntax in ${RULES_JSON}; guardrails owns this file and keeps one entry per rule.` }));
12
+ }
13
+ export function writeState(root, state) {
14
+ return writeManaged(root, RULES_JSON, serializeState(state));
15
+ }
16
+ export function installedRuleIds(root) {
17
+ return listDir(root, `${PLUGIN_DIR}/rules`)
18
+ .filter((file) => file.endsWith(".mjs") && !file.endsWith(".test.mjs") && !file.startsWith("_"))
19
+ .map((file) => file.slice(0, -".mjs".length));
20
+ }
21
+ export function copyOwnRule(root, id) {
22
+ return [
23
+ writeManaged(root, `${PLUGIN_DIR}/rules/${id}.mjs`, readAsset(`eslint-rules/${id}.mjs`)),
24
+ writeManaged(root, `${PLUGIN_DIR}/rules/_rule-tester.mjs`, readAsset("eslint-rules/_rule-tester.mjs")),
25
+ ];
26
+ }
27
+ export function writeIndexAndConfig(root) {
28
+ return [
29
+ writeManaged(root, `${PLUGIN_DIR}/index.mjs`, renderPluginIndex(installedRuleIds(root))),
30
+ writeManaged(root, `${PLUGIN_DIR}/config.mjs`, readAsset("eslint-guardrails/config.mjs")),
31
+ ];
32
+ }
33
+ export function wireEslintConfig(ctx) {
34
+ const { root, profile } = ctx;
35
+ const data = jsTs(profile);
36
+ const config = data.eslint.config;
37
+ if (config === null) {
38
+ const created = newConfigText(data);
39
+ return created === null
40
+ ? err(appError("missing-dependency", "no ESLint config and typescript-eslint is not a dependency, so guardrails cannot create one", { file: "package.json", fix: "Install eslint and typescript-eslint as exact devDependencies, then run apply again." }))
41
+ : ok([writeManaged(root, "eslint.config.mjs", created)]);
42
+ }
43
+ if (data.eslint.guardrailsWired)
44
+ return ok([]);
45
+ const wired = config.endsWith(".mjs") || config.endsWith(".js") ? wireConfigText(readText(root, config) ?? "") : null;
46
+ return wired === null
47
+ ? err(appError("unsupported-config", `cannot add the guardrails config to ${config} automatically`, {
48
+ file: config,
49
+ fix: `Add \`import { guardrailsConfig } from "./eslint/guardrails/config.mjs";\` and spread \`...guardrailsConfig\` into the exported array of ${config} (.mjs or .js with \`export default [...]\` or defineConfig([...])), then run apply again.`,
50
+ }))
51
+ : ok([writeManaged(root, config, wired)]);
52
+ }
53
+ export function allWritten(results) {
54
+ const collected = collect(results);
55
+ return collected.ok ? ok(collected.value.flat()) : collected;
56
+ }
@@ -0,0 +1,3 @@
1
+ export function fixesFor(packs) {
2
+ return packs.reduce((all, pack) => ({ ...all, ...pack.fixes }), {});
3
+ }
@@ -0,0 +1,30 @@
1
+ import { BASELINE_PATH, coverageLowered, evaluateCoverage, parseBaseline } from "../../../core/domain/ratchet.js";
2
+ import { baseRef, changedFiles, readAtRef } from "../../../core/infra/changes.js";
3
+ import { readBaseline, writeBaseline } from "../../../core/infra/baseline.js";
4
+ import { exists, readText } from "../../../core/infra/fs.js";
5
+ import { parseJsonc } from "../../../core/domain/json.js";
6
+ import { coverageDiagnostic, loweredDiagnostic, missingTestDiagnostic } from "../domain/pr-diagnostics.js";
7
+ import { missingTests } from "../domain/pr-tests.js";
8
+ import { measuredLines, pickTesting } from "../domain/testing.js";
9
+ function loweredAgainstBase(ctx, ref) {
10
+ const before = ref === null ? null : readAtRef(ctx.root, ref, BASELINE_PATH);
11
+ const previous = before === null ? undefined : parseBaseline(parseJsonc(before)).coverage;
12
+ const current = readBaseline(ctx.root).coverage;
13
+ return previous !== undefined && coverageLowered(previous, current) ? [loweredDiagnostic(previous, current, BASELINE_PATH)] : [];
14
+ }
15
+ function coverageStep(ctx) {
16
+ const spec = pickTesting(ctx.packs);
17
+ const measured = spec === null ? null : measuredLines(readText(ctx.root, spec.coverageSummary));
18
+ const baseline = readBaseline(ctx.root);
19
+ const result = evaluateCoverage(baseline.coverage, measured);
20
+ if (result.next !== undefined && result.next !== baseline.coverage && ctx.readOnly !== true)
21
+ writeBaseline(ctx.root, { ...baseline, coverage: result.next });
22
+ return result.regression === null || measured === null ? [] : [coverageDiagnostic(result.regression.floor, measured, BASELINE_PATH)];
23
+ }
24
+ export function prRuleDiagnostics(ctx, paths) {
25
+ if (paths.length > 0)
26
+ return [];
27
+ const ref = baseRef(ctx.root, ctx.profile.git.baseBranch);
28
+ const missing = ref === null ? [] : missingTests(changedFiles(ctx.root, ref), (path) => exists(ctx.root, path), (path) => readText(ctx.root, path) ?? "").map(missingTestDiagnostic);
29
+ return [...missing, ...loweredAgainstBase(ctx, ref), ...coverageStep(ctx)];
30
+ }
@@ -0,0 +1,87 @@
1
+ import { STRICT_OPTIONS, missingStrictOptions } from "../domain/ts-options.js";
2
+ import { jsTs } from "../domain/data.js";
3
+ import { objectAt } from "../../../core/domain/json.js";
4
+ import { readAsset } from "../../../core/infra/assets.js";
5
+ import { editJsonFile, exists, readJsonRecord, writeIfAbsent } from "../../../core/infra/fs.js";
6
+ import { runNodeScript } from "../../../core/infra/hooks.js";
7
+ import { runTsc } from "../infra/tsc.js";
8
+ import { installDevCommand } from "../domain/profile-pure.js";
9
+ import { andThen, map, ok } from "../../../core/domain/result.js";
10
+ const strictMissing = (root) => {
11
+ const tsconfig = readJsonRecord(root, "tsconfig.json");
12
+ return missingStrictOptions(tsconfig === null ? {} : objectAt(tsconfig, "compilerOptions"));
13
+ };
14
+ export const tsStrictMax = {
15
+ id: "ts-strict-max",
16
+ title: "tsconfig at maximum strictness",
17
+ layer: "types",
18
+ why: "strict plus noUncheckedIndexedAccess, exactOptionalPropertyTypes and noImplicitOverride turn whole classes of agent mistakes into compile errors.",
19
+ notApplicable: (profile) => (jsTs(profile).typescript.tsconfig === null ? "no tsconfig.json" : null),
20
+ requires: () => [],
21
+ isInstalled: ({ root }) => readJsonRecord(root, "tsconfig.json") !== null && strictMissing(root).length === 0,
22
+ install: (ctx) => {
23
+ const before = ctx.gradual === true ? runTsc(ctx.root).diagnostics.length : 0;
24
+ const original = readJsonRecord(ctx.root, "tsconfig.json");
25
+ return andThen(editJsonFile(ctx.root, "tsconfig.json", (value) => ({ ...value, compilerOptions: { ...objectAt(value, "compilerOptions"), ...STRICT_OPTIONS } }), false), (change) => {
26
+ const after = ctx.gradual === true ? runTsc(ctx.root).diagnostics.length : 0;
27
+ if (ctx.gradual === true && after > before && original !== null) {
28
+ return map(editJsonFile(ctx.root, "tsconfig.json", () => original, false), () => ({
29
+ changes: [{ path: "tsconfig.json", action: "unchanged" }],
30
+ notes: [`deferred: the strict options add ${String(after - before)} type errors. Fix them in a branch with the options on, then run \`guardrails apply ts-strict-max\`.`],
31
+ violations: [],
32
+ levels: { "ts-strict-max": "deferred" },
33
+ }));
34
+ }
35
+ return ok({ changes: [change], notes: ["Stricter options can surface new type errors: run the typecheck and fix them at the source."], violations: [], levels: {} });
36
+ });
37
+ },
38
+ verify: ({ root }) => {
39
+ const missing = strictMissing(root);
40
+ const tsc = runTsc(root);
41
+ return [
42
+ { name: "tsconfig strict options", ok: missing.length === 0, detail: missing.length === 0 ? "all set" : `missing: ${missing.join(", ")}` },
43
+ { name: "typecheck under the new options", ok: true, detail: tsc.ran ? `${tsc.diagnostics.length} type errors to fix (run guardrails check)` : `skipped: ${tsc.error ?? "tsc unavailable"}` },
44
+ ];
45
+ },
46
+ };
47
+ function missingScripts(profile) {
48
+ const data = jsTs(profile);
49
+ return {
50
+ ...(!data.scripts.typecheck && data.typescript.present ? { typecheck: "tsc --noEmit" } : {}),
51
+ ...(!data.scripts.lint && data.eslint.version !== null ? { lint: "eslint ." } : {}),
52
+ };
53
+ }
54
+ export const pkgScripts = {
55
+ id: "pkg-scripts",
56
+ title: "package.json has lint and typecheck scripts",
57
+ layer: "api",
58
+ why: "Hooks, CI and the agent all call the same two scripts; one definition keeps them identical.",
59
+ notApplicable: (profile) => (!jsTs(profile).typescript.present && jsTs(profile).eslint.version === null ? "no TypeScript and no ESLint to script" : null),
60
+ requires: () => [],
61
+ isInstalled: ({ profile }) => Object.keys(missingScripts(profile)).length === 0,
62
+ install: ({ root, profile }) => map(editJsonFile(root, "package.json", (value) => ({ ...value, scripts: { ...objectAt(value, "scripts"), ...missingScripts(profile) } }), false), (change) => ({ changes: [change], notes: [], violations: [], levels: {} })),
63
+ verify: ({ root }) => {
64
+ const scripts = objectAt(readJsonRecord(root, "package.json") ?? {}, "scripts");
65
+ return ["lint", "typecheck"].map((name) => ({ name: `script ${name}`, ok: name in scripts, detail: name in scripts ? "present" : "missing" }));
66
+ },
67
+ };
68
+ const hasExactScript = (root) => typeof objectAt(readJsonRecord(root, "package.json") ?? {}, "scripts")["check-exact-deps"] === "string";
69
+ export const exactDeps = {
70
+ id: "exact-deps",
71
+ title: "Dependencies pinned to exact versions",
72
+ layer: "api",
73
+ why: "An update must be an explicit change; ranges let an install silently change what runs.",
74
+ notApplicable: () => null,
75
+ requires: () => [],
76
+ isInstalled: ({ root }) => exists(root, "scripts/check-exact-deps.mjs") && hasExactScript(root),
77
+ install: ({ root, profile }) => andThen(writeIfAbsent(root, "scripts/check-exact-deps.mjs", readAsset("scripts/check-exact-deps.mjs"), "exact-deps"), (copy) => map(editJsonFile(root, "package.json", (value) => ({ ...value, scripts: { "check-exact-deps": "node scripts/check-exact-deps.mjs", ...objectAt(value, "scripts") } }), false), (script) => ({
78
+ changes: [copy, script],
79
+ notes: jsTs(profile).exactDeps.ok ? [] : [`${jsTs(profile).exactDeps.loose.length} dependencies use ranges; pin them: ${installDevCommand(jsTs(profile).packageManager, ["<pkg>@<exact version>"])}`],
80
+ violations: [],
81
+ levels: {},
82
+ }))),
83
+ verify: ({ root }) => {
84
+ const status = runNodeScript(root, "scripts/check-exact-deps.mjs");
85
+ return [{ name: "check-exact-deps runs", ok: status === 0 || status === 1, detail: status === 0 ? "no loose dependencies" : "script works; loose dependencies listed by guardrails check" }];
86
+ },
87
+ };
@@ -0,0 +1,63 @@
1
+ import { appError } from "../../../core/domain/errors.js";
2
+ import { objectAt } from "../../../core/domain/json.js";
3
+ import { andThen, err, map, ok } from "../../../core/domain/result.js";
4
+ import { CI_FILE, ensureCiStep } from "../../../core/domain/workflows.js";
5
+ import { editJsonFile, exists, readJsonRecord, readText, writeIfAbsent, writeManaged } from "../../../core/infra/fs.js";
6
+ import { jsTs } from "../domain/data.js";
7
+ import { packageRunCommand } from "../domain/profile-pure.js";
8
+ import { pickTesting } from "../domain/testing.js";
9
+ const stepOf = (ctx) => ` - run: ${packageRunCommand(jsTs(ctx.profile).packageManager, "test")}`;
10
+ const testScript = (root) => {
11
+ const script = objectAt(readJsonRecord(root, "package.json") ?? {}, "scripts")["test"];
12
+ return typeof script === "string" ? script : "";
13
+ };
14
+ function noRunner() {
15
+ return appError("not-applicable", "no active pack declares a test runner", { rule: "tests", fix: "Activate a js-ts based pack (`guardrails detect`)." });
16
+ }
17
+ function configChange(ctx, spec) {
18
+ return exists(ctx.root, spec.configFile) ? ok({ path: spec.configFile, action: "unchanged" }) : writeIfAbsent(ctx.root, spec.configFile, spec.config(ctx.profile), "tests");
19
+ }
20
+ function ciChange(ctx) {
21
+ const text = readText(ctx.root, CI_FILE);
22
+ return text === null ? { path: CI_FILE, action: "unchanged" } : writeManaged(ctx.root, CI_FILE, ensureCiStep(text, stepOf(ctx), "guardrails check --json"));
23
+ }
24
+ function install(ctx) {
25
+ const spec = pickTesting(ctx.packs);
26
+ if (spec === null)
27
+ return err(noRunner());
28
+ return andThen(configChange(ctx, spec), (config) => map(editJsonFile(ctx.root, "package.json", (value) => ({ ...value, scripts: { test: spec.script, ...objectAt(value, "scripts") } }), false), (script) => ({
29
+ changes: [config, script, ciChange(ctx)],
30
+ notes: [`Tests run in CI (${spec.runner}); run them locally only when asked. Coverage floor lives in .guardrails/baseline.json and only goes up.`],
31
+ violations: [],
32
+ levels: {},
33
+ })));
34
+ }
35
+ function verify(ctx) {
36
+ const spec = pickTesting(ctx.packs);
37
+ if (spec === null)
38
+ return [{ name: "test runner declared", ok: false, detail: "no pack declares one" }];
39
+ const config = readText(ctx.root, spec.configFile) ?? "";
40
+ const ci = readText(ctx.root, CI_FILE);
41
+ return [
42
+ { name: `${spec.configFile} reports json-summary coverage`, ok: config.includes("json-summary"), detail: spec.configFile },
43
+ { name: `script test runs ${spec.runner} with coverage`, ok: testScript(ctx.root).includes(spec.runner) && testScript(ctx.root).includes("--coverage"), detail: testScript(ctx.root) || "missing" },
44
+ { name: "CI runs the test script", ok: ci === null || ci.includes(stepOf(ctx).trim()), detail: ci === null ? "no CI workflow yet; ci-workflow adds the step" : CI_FILE },
45
+ ];
46
+ }
47
+ export const testsConstraint = {
48
+ id: "tests",
49
+ title: "Test runner with coverage, run in CI",
50
+ layer: "tests",
51
+ why: "CI is where tests run for every PR; the pack picks the runner (Vitest, or Jest with jest-expo on React Native) so the agent never chooses one.",
52
+ notApplicable: () => null,
53
+ requires: (profile, packs) => {
54
+ const spec = pickTesting(packs);
55
+ return spec === null ? [] : spec.packages.filter((pkg) => !jsTs(profile).dependencies.includes(pkg)).map((pkg) => ({ pkg, reason: `${spec.runner} runner with coverage` }));
56
+ },
57
+ isInstalled: (ctx) => {
58
+ const spec = pickTesting(ctx.packs);
59
+ return spec !== null && exists(ctx.root, spec.configFile) && verify(ctx).every((check) => check.ok);
60
+ },
61
+ install,
62
+ verify,
63
+ };
@@ -0,0 +1,147 @@
1
+ import { THRESHOLDS } from "../../../core/domain/thresholds.js";
2
+ import { jsTs, routeGlobsOf } from "./data.js";
3
+ export const OWN_PREFIX = "guardrails/";
4
+ export const own = (id) => `${OWN_PREFIX}${id}`;
5
+ const DOMAIN_MESSAGE = "A domain folder is pure: it may import only domain files and node:path. Move the I/O to the infra folder and call it from app.";
6
+ const INFRA_MESSAGE = "An infra folder is the thin I/O edge: it may import domain but never app. Move the orchestration to the app folder.";
7
+ const NODE_IO = "^node:(fs|fs/promises|child_process|os|process|net|http|https)$";
8
+ function layerEntries(roots) {
9
+ const alt = roots.join("|");
10
+ return [
11
+ { files: `^(${alt})/domain/`, forbid: [{ source: `^(${alt})/(app|infra)/`, allowTypeImports: false, message: DOMAIN_MESSAGE }, { source: NODE_IO, allowTypeImports: false, message: DOMAIN_MESSAGE }] },
12
+ { files: `^(${alt})/infra/`, forbid: [{ source: `^(${alt})/app/`, allowTypeImports: false, message: INFRA_MESSAGE }] },
13
+ ];
14
+ }
15
+ export function boundaryOptions(profile) {
16
+ const { paths, layerRules } = jsTs(profile);
17
+ const features = paths.featuresDir === null ? [] : [{ files: "^src/(?!features/[^/]+/)", forbid: [{ source: "^src/features/[^/]+/", allowTypeImports: false, message: BOUNDARY_MESSAGE }] }];
18
+ const layers = paths.layerRoots.length === 0 ? [] : layerEntries(paths.layerRoots);
19
+ const custom = layerRules.map((rule) => ({ files: rule.files, forbid: [{ source: rule.source, allowTypeImports: false, message: rule.message }] }));
20
+ return [[...features, ...layers, ...custom]];
21
+ }
22
+ const BOUNDARY_MESSAGE = "Import a feature only through its public entry point (`@/features/<name>`), never from its internal folders. If what you need is not exported there, add it to that entry point.";
23
+ export const JS_TS_SPECS = Object.freeze([
24
+ {
25
+ id: "no-comments",
26
+ title: "No comments in code",
27
+ why: "A comment means the name is wrong or the code does too much. Intent goes in names and types.",
28
+ rules: [{ name: own("no-comments"), fix: "Delete the comment and rename the variable or function until it says the same, or extract a named function. Allowed: eslint directives with `-- reason`, `/// <reference`, `@ts-expect-error <reason>`.", probe: "// hi\nexport const a = 1;\n" }],
29
+ },
30
+ {
31
+ id: "no-any",
32
+ title: "No any (explicit or `as any`)",
33
+ why: "`any` switches the type checker off for everything it touches.",
34
+ rules: [{ name: "@typescript-eslint/no-explicit-any", fix: "Replace `any` with the real type, `unknown` plus a type guard, or a generic. Never cast through `as any`." }],
35
+ },
36
+ {
37
+ id: "no-ts-ignore",
38
+ title: "No @ts-ignore; @ts-expect-error only with a reason",
39
+ why: "`@ts-ignore` hides errors forever, even after the code is fixed.",
40
+ rules: [
41
+ {
42
+ name: "@typescript-eslint/ban-ts-comment",
43
+ fix: "Fix the type error. If it is truly unavoidable use `// @ts-expect-error <reason of 10+ characters>`; `@ts-ignore` and `@ts-nocheck` are banned.",
44
+ options: () => [{ "ts-ignore": true, "ts-nocheck": true, "ts-check": false, "ts-expect-error": "allow-with-description", minimumDescriptionLength: 10 }],
45
+ },
46
+ ],
47
+ },
48
+ {
49
+ id: "no-non-null-assertion",
50
+ title: "No non-null assertions (`!`)",
51
+ why: "`value!` asserts what the code never checked.",
52
+ rules: [{ name: "@typescript-eslint/no-non-null-assertion", fix: "Narrow the value (`if (value === null) return ...`) or fix the type so the value cannot be missing." }],
53
+ },
54
+ {
55
+ id: "no-enum",
56
+ title: "No enums",
57
+ why: "Enums emit runtime code and break tree shaking.",
58
+ rules: [{ name: own("no-enum"), fix: 'Use an `as const` array or object and derive the union type: `export const STATUSES = ["idle", "done"] as const; export type Status = (typeof STATUSES)[number];`.', probe: "export enum A { B }\n" }],
59
+ },
60
+ {
61
+ id: "no-let",
62
+ title: "No let",
63
+ why: "`let` invites reassignment and hidden state.",
64
+ rules: [{ name: own("no-let"), fix: "Build the value with an expression (`map`, `filter`, `reduce`, `Object.fromEntries`) or a function with early returns and bind it with `const`.", probe: "let a = 1;\nexport { a };\n" }],
65
+ },
66
+ {
67
+ id: "no-console",
68
+ title: "No console",
69
+ why: "Stray logs leak data and hide real diagnostics.",
70
+ rules: [{ name: "no-console", fix: "Remove the console call. Use the project logger or surface the error in the UI.", probe: "console.log(1);\n" }],
71
+ },
72
+ {
73
+ id: "max-complexity",
74
+ title: "Cyclomatic complexity at most 10",
75
+ why: "Branchy functions are where agents introduce bugs.",
76
+ rules: [{ name: "complexity", options: () => [THRESHOLDS.complexity.value], fix: "Split the function: extract each branch into a named function, replace if/else chains with a lookup object or early returns.", probe: "export function f(a: number) {\n" + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map((n) => ` if (a === ${n}) return ${n};`).join("\n") + "\n return 0;\n}\n" }],
77
+ },
78
+ {
79
+ id: "max-function-length",
80
+ title: "Functions at most 40 lines",
81
+ why: "Long functions hide multiple responsibilities.",
82
+ rules: [{ name: "max-lines-per-function", options: () => [{ max: THRESHOLDS.functionLines.value, skipBlankLines: true, skipComments: true }], fix: "Extract cohesive blocks into named module-level functions until each is under 40 lines." }],
83
+ },
84
+ {
85
+ id: "no-mutation",
86
+ title: "No mutation of state, props, arguments, arrays or objects",
87
+ why: "Mutation makes data flow untraceable and breaks React and query-cache change detection.",
88
+ rules: [
89
+ { name: own("no-mutating-array-methods"), typed: true, fix: "Use the copying method: `toSorted`, `toReversed`, `toSpliced`, `with`, or spread into a new array." },
90
+ { name: own("no-member-assignment"), fix: "Return a new value: `{ ...value, field: next }`. Only `ref.current` and `module.exports` may be assigned.", probe: "const a = { b: 1 };\na.b = 2;\n" },
91
+ { name: own("no-delete"), fix: "Build a new object without the key: `const { [key]: _removed, ...rest } = value;`.", probe: "const a: { b?: number } = { b: 1 };\ndelete a.b;\n" },
92
+ { name: "no-param-reassign", options: () => [{ props: true }], fix: "Do not assign to a parameter or its properties; copy it into a new local value first." },
93
+ ],
94
+ },
95
+ {
96
+ id: "readonly-by-default",
97
+ title: "Class members readonly when never reassigned",
98
+ why: "Readonly by default makes accidental reassignment a type error.",
99
+ rules: [{ name: "@typescript-eslint/prefer-readonly", typed: true, fix: "Mark the private member `readonly`; it is never reassigned." }],
100
+ },
101
+ {
102
+ id: "require-disable-reason",
103
+ title: "eslint-disable needs a reason",
104
+ why: "A bare disable is the cheapest way for an agent to silence a rule.",
105
+ rules: [{ name: own("require-disable-reason"), fix: "Write `eslint-disable-next-line <rule> -- <why the rule cannot be satisfied here>`, or fix the code so no disable is needed.", probe: "// eslint-disable-next-line no-console\nconsole.log(1);\n" }],
106
+ },
107
+ {
108
+ id: "no-default-export",
109
+ title: "No default exports (except routes and config files)",
110
+ why: "Named exports keep imports greppable and renames safe.",
111
+ rules: [{ name: own("no-default-export"), ignores: routeGlobsOf, fix: "Use a named export: `export function ProjectCard() {}` and update the importers.", probe: "export default function A() {}\n" }],
112
+ },
113
+ {
114
+ id: "import-boundaries",
115
+ title: "Layer limits: features only through their entry point; domain stays pure, infra never imports app",
116
+ why: "Layer limits keep features independent, the domain free of I/O, and refactors local.",
117
+ applies: (profile) => (jsTs(profile).paths.featuresDir === null && jsTs(profile).paths.layerRoots.length === 0 && jsTs(profile).layerRules.length === 0 ? "no src/features, no domain|app|infra layers and no .guardrails/layers.json" : null),
118
+ rules: [{ name: own("import-boundaries"), options: boundaryOptions, fix: BOUNDARY_MESSAGE }],
119
+ },
120
+ {
121
+ id: "readonly-params",
122
+ title: "Parameters are deeply readonly",
123
+ why: "Readonly parameter types make mutating an argument a compile error.",
124
+ rules: [
125
+ {
126
+ name: "@typescript-eslint/prefer-readonly-parameter-types",
127
+ typed: true,
128
+ options: () => [{ ignoreInferredTypes: true, treatMethodsAsReadonly: true, allow: [{ from: "lib", name: ["RegExp", "Error"] }] }],
129
+ fix: "Declare the parameter with a readonly type: `readonly T[]`, `Readonly<T>` or a type whose fields are all `readonly`.",
130
+ },
131
+ ],
132
+ },
133
+ {
134
+ id: "no-floating-promises",
135
+ title: "Promises must be awaited or handled",
136
+ why: "A floating promise swallows its error.",
137
+ rules: [{ name: "@typescript-eslint/no-floating-promises", typed: true, fix: "`await` the promise, return it, or handle rejection with `.catch(...)`; use `void` only for deliberate fire-and-forget." }],
138
+ },
139
+ ]);
140
+ export const fixesOf = (specs) => Object.fromEntries(specs.flatMap((spec) => spec.rules.map((rule) => [rule.name, rule.fix])));
141
+ export function sampleFile(glob) {
142
+ return glob
143
+ .replace(/^\*\*\//, "")
144
+ .replace(/\/\*\*\//g, "/")
145
+ .replace(/\{([^},]+)[^}]*\}/g, "$1")
146
+ .replace(/\*/g, "__guardrails_probe__");
147
+ }
@@ -0,0 +1,47 @@
1
+ import { appError } from "../../../core/domain/errors.js";
2
+ import { jsTs } from "./data.js";
3
+ import { execCommand, installDevCommand, packageRunCommand } from "./profile-pure.js";
4
+ function installCommand(pm) {
5
+ if (pm === "pnpm")
6
+ return "pnpm install --frozen-lockfile --ignore-scripts";
7
+ if (pm === "yarn")
8
+ return "yarn install --frozen-lockfile --ignore-scripts";
9
+ if (pm === "bun")
10
+ return "bun install --frozen-lockfile";
11
+ return "npm ci --ignore-scripts";
12
+ }
13
+ export const JS_TS_COMMANDS = {
14
+ installDev: (profile, packages) => installDevCommand(jsTs(profile).packageManager, packages),
15
+ exec: (profile, bin, args) => execCommand(jsTs(profile).packageManager, bin, args),
16
+ cliRequirement: (profile) => (jsTs(profile).guardrails.installed ? [] : [{ pkg: "@whil/guardrails", reason: "the CI step runs `guardrails check --json`; add this CLI as a devDependency" }]),
17
+ };
18
+ export const JS_TS_CI = {
19
+ setup: (profile) => {
20
+ const pm = jsTs(profile).packageManager;
21
+ return [
22
+ ...(pm === "pnpm" ? [" - uses: pnpm/action-setup@v4"] : []),
23
+ ...(pm === "bun" ? [" - uses: oven-sh/setup-bun@v2"] : []),
24
+ " - uses: actions/setup-node@v4",
25
+ " with:",
26
+ " node-version: lts/*",
27
+ ...(pm === "bun" ? [] : [` cache: ${pm}`]),
28
+ ` - run: ${installCommand(pm)}`,
29
+ ];
30
+ },
31
+ steps: (profile) => {
32
+ const data = jsTs(profile);
33
+ const run = (script) => ` - run: ${packageRunCommand(data.packageManager, script)}`;
34
+ return [
35
+ ...(data.exactDeps.script ? [" - run: node scripts/check-exact-deps.mjs"] : []),
36
+ ...["lint", "typecheck", "test", "build"].filter((name) => data.scripts[name]).map(run),
37
+ ];
38
+ },
39
+ dependabot: () => [{ ecosystem: "npm", directory: "/" }],
40
+ preflight: (profile) => {
41
+ const data = jsTs(profile);
42
+ if (data.packageManager === "pnpm" && !data.packageManagerPinned) {
43
+ return appError("unsupported-config", "pnpm/action-setup needs the pnpm version in package.json", { file: "package.json", rule: "ci-workflow", fix: 'Add `"packageManager": "pnpm@<version>"` to package.json (see `pnpm --version`), then run apply again.' });
44
+ }
45
+ return !data.scripts.lint && !data.scripts.typecheck ? appError("not-applicable", "ci-workflow needs lint and typecheck scripts in package.json", { file: "package.json", rule: "ci-workflow", fix: "Run `guardrails apply pkg-scripts` first." }) : null;
46
+ },
47
+ };
@@ -0,0 +1,34 @@
1
+ import { isRecord } from "../../../core/domain/json.js";
2
+ export const EMPTY_JS_TS = {
3
+ name: "unnamed",
4
+ packageManager: "npm",
5
+ packageManagerPinned: false,
6
+ typescript: { present: false, version: null, tsconfig: null, strict: null },
7
+ eslint: { installed: false, version: null, config: null, flat: false, typescriptPlugin: false, typescriptEslintPackage: false, guardrailsWired: false },
8
+ dependencies: [],
9
+ tests: { runner: null },
10
+ paths: { srcDir: null, featuresDir: null, layerRoots: [], sourceGlobs: [], routeGlobs: [], hookGlobs: [] },
11
+ scripts: { lint: false, typecheck: false, test: false, build: false },
12
+ guardrails: { installed: false },
13
+ exactDeps: { ok: true, loose: [], script: false },
14
+ layerRules: [],
15
+ };
16
+ function isJsTsData(value) {
17
+ return isRecord(value) && typeof value["packageManager"] === "string" && isRecord(value["paths"]) && isRecord(value["eslint"]) && isRecord(value["scripts"]);
18
+ }
19
+ export function jsTs(profile) {
20
+ const value = profile.stack["js-ts"];
21
+ return isJsTsData(value) ? value : EMPTY_JS_TS;
22
+ }
23
+ export function hasDependency(profile, name) {
24
+ return jsTs(profile).dependencies.includes(name);
25
+ }
26
+ function globsOf(profile, key) {
27
+ return Object.values(profile.stack).flatMap((entry) => {
28
+ const value = entry[key];
29
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
30
+ });
31
+ }
32
+ export const routeGlobsOf = (profile) => [...jsTs(profile).paths.routeGlobs, ...globsOf(profile, "routeGlobs")];
33
+ export const hookGlobsOf = (profile) => [...jsTs(profile).paths.hookGlobs, ...globsOf(profile, "hookGlobs")];
34
+ export const isActive = (profile, id) => profile.packs.some((pack) => pack.id === id);