@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
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ivan Garcia
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,209 @@
1
- # Temporary Holding Version
1
+ # guardrails
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ CLI que una IA corre para montar en un proyecto un entorno restrictivo que valida su código: la IA genera, y el entorno responde "arregla esto" (con archivo, línea, regla y cómo arreglarlo) o "todo bien".
4
+
5
+ ## El problema y la idea
6
+
7
+ Un agente repite los mismos errores: un `any`, un comentario que explica código confuso, un estado mutado, un import que cruza capas. La salida habitual es escribir más prosa (un `CLAUDE.md` más largo) y esperar que la siga. La prosa no falla cuando se ignora; un check sí.
8
+
9
+ La idea viene de la charla *All Code Is Slop (Except Mine)* de Lauren Tan: cada error repetido se convierte en un check determinista, con un mensaje que dice cómo arreglarlo. El agente no juzga su propio código; lo juzgan ESLint, `tsc`, los hooks y el CI. Así el agente puede trabajar rápido y sin supervisión, porque el entorno atrapa lo malo.
10
+
11
+ ## Uso en 3 comandos
12
+
13
+ Requiere Node 22 o superior. Sin instalar nada:
14
+
15
+ ```sh
16
+ npx @whil/guardrails init --owner @tu-usuario
17
+ ```
18
+
19
+ Para que el CI y los hooks usen el comando `guardrails`, añádelo al proyecto como devDependency:
20
+
21
+ ```sh
22
+ pnpm add -D --save-exact @whil/guardrails
23
+ ```
24
+
25
+ Dentro del proyecto de destino (los paquetes `eslint`, `typescript-eslint` y `typescript` ya deben estar instalados):
26
+
27
+ ```sh
28
+ guardrails init --owner @tu-usuario
29
+ guardrails check
30
+ ```
31
+
32
+ `init` detecta el proyecto, activa los packs que correspondan, instala el set más fuerte y termina con los pasos siguientes para la IA. Salida real sobre un repo de prueba con código heredado:
33
+
34
+ ```
35
+ packs: js-ts
36
+ installed 30 constraints (1 already there, 1 not applicable)
37
+ blocked: tests: tests needs: @vitest/coverage-v8 (vitest runner with coverage)
38
+ debt: 6 violations in 6 rules at warn; errors: 0
39
+ backups of edited files: .guardrails/backup/package.json, .guardrails/backup/tsconfig.json
40
+ next:
41
+ 1. install the missing packages, then run `guardrails init` again: pnpm add -D --save-exact @vitest/coverage-v8
42
+ 2. tests: Run `pnpm add -D --save-exact @vitest/coverage-v8`, then `guardrails apply tests` again.
43
+ 3. pay down debt, biggest first: @typescript-eslint/no-explicit-any (1), @typescript-eslint/no-non-null-assertion (1), ...
44
+ 4. commit the result on a branch `type/kebab-case`, open a PR, and run `guardrails check --json` after every change
45
+ 5. apply the repo ruleset when the owner agrees: `sh .guardrails/github/branch-protection.sh` (init never runs it)
46
+ ```
47
+
48
+ Y `check` sobre ese repo (las reglas con violaciones previas quedan en `warn` dentro de un baseline):
49
+
50
+ ```
51
+ src/total.ts:1:1 warn [guardrails/no-comments] Comments are forbidden: ...
52
+ src/total.ts:3:3 warn [guardrails/no-let] `let` invites reassignment. ...
53
+ src/total.ts:7:31 warn [@typescript-eslint/no-explicit-any] Unexpected any. ...
54
+ deuda dentro del baseline: 6 avisos; no pueden aumentar
55
+ ```
56
+
57
+ Si el agente añade una violación nueva, el `check` falla (exit 1) con un diagnóstico accionable:
58
+
59
+ ```json
60
+ {
61
+ "file": "eslint/guardrails/rules.json",
62
+ "tool": "ratchet",
63
+ "rule": "ratchet/guardrails/no-let",
64
+ "message": "guardrails/no-let has 2 violations, the baseline allows 1. Violations of a rule at warn can only go down.",
65
+ "severity": "error",
66
+ "fix": "Fix the new guardrails/no-let violations listed above (they are the warnings for this rule). When the count reaches 0 the rule is promoted to error by itself."
67
+ }
68
+ ```
69
+
70
+ ## El flujo de la IA
71
+
72
+ 1. **Generar** el cambio en una rama `type/kebab-case`.
73
+ 2. **Check local**: `guardrails check --json` después de cada cambio, hasta que `verdict` sea `clean` (o `debt`: solo quedan avisos dentro del baseline). Antes de eso, el hook de Claude ya corre lint y typecheck tras cada edición.
74
+ 3. **Push** y PR contra `main`. El CI corre lint, typecheck, tests y `check`; el job `status` publica un comentario único y actualizable en el PR con el diagnóstico JSON, lo sube como artifact (`guardrails-diagnostics`) y marca el check requerido `status`.
75
+ 4. **`guardrails pr-repair --wait --json`**: espera los checks y, si fallan, devuelve `failing[].diagnostics[]` (`check`, `file`, `line`, `rule` o `test`, `message`, `fix`) y el contador `attempts`.
76
+ 5. **Reparar**, volver al check local, push, y repetir el paso 4 hasta `verdict: green`; entonces `gh pr merge --auto --squash`.
77
+ 6. **Tope de 3 intentos**: si tres pushes de reparación no ponen el PR en verde, `verdict` es `escalate` (exit 3): la IA se detiene y pide ayuda a una persona con `failing[]`.
78
+
79
+ Los tests corren en el CI, no en la máquina de la IA salvo que se pida.
80
+
81
+ ## Comandos
82
+
83
+ Todos aceptan `--json`, no hacen preguntas y usan los mismos códigos de salida: 0 ok, 1 hallazgos, 2 uso incorrecto, 3 precondición o dependencia faltante, 4 verificación fallida.
84
+
85
+ | Comando | Qué hace |
86
+ | --- | --- |
87
+ | `init` | Un solo paso: detecta, activa packs, instala el set más fuerte en lote, fija el baseline y escribe AGENTS.md. Idempotente. `--dry-run`, `--install`, `--owner` |
88
+ | `detect` | Lee el repo, activa packs y escribe `.guardrails/profile.json` |
89
+ | `plan` | Huecos entre el repo y el catálogo (`gap`, `installed`, `not-applicable`) |
90
+ | `apply <id>` | Instala una restricción y la verifica (`--dry-run`) |
91
+ | `check [rutas]` | Diagnósticos con archivo, línea, regla y cómo arreglarlo |
92
+ | `audit` | Métricas: violaciones, `eslint-disable` sin razón, reglas en warn, protección de rama (`--offline` omite GitHub) |
93
+ | `self-check` | `check` + `audit` en una sola pasada |
94
+ | `add-rule <nombre>` | Crea una regla de lint con su test a partir de una corrección |
95
+ | `learn` | Propone reglas nuevas desde el historial |
96
+ | `pr-status` | Checks fallidos del PR actual como JSON accionable (solo lectura) |
97
+ | `pr-repair` | `pr-status` más el contador de intentos; escala a los 3 |
98
+ | `agents-md` | Escribe en AGENTS.md el flujo para la IA |
99
+
100
+ ## Catálogo de restricciones
101
+
102
+ `init` instala todas las que aplican. Una regla que ya tiene violaciones entra en `warn`; si está en 0 entra en `error`.
103
+
104
+ | Grupo | Restricciones | Por qué |
105
+ | --- | --- | --- |
106
+ | Comentarios | `no-comments`, `no-ts-ignore`, `require-disable-reason`, `unused-disable-directives` | Un comentario indica un nombre malo; un `disable` sin razón es la forma más barata de callar una regla |
107
+ | Tipos | `no-any`, `no-non-null-assertion`, `no-enum`, `no-floating-promises`, `readonly-params`, `ts-strict-max` (tsconfig) | `any` y `!` apagan el type checker; una promesa sin manejar traga su error; `strict` máximo convierte clases de errores en errores de compilación |
108
+ | Inmutabilidad | `no-let`, `no-mutation` (`no-delete`, `no-member-assignment`, `no-mutating-array-methods`, `no-param-reassign`), `readonly-by-default` | La mutación hace el flujo de datos intrazable |
109
+ | Capas y tamaño | `import-boundaries`, `no-default-export`, `max-complexity` (10), `max-function-length` (40), `no-console`, `exact-deps` | Los límites de capas mantienen el dominio puro; funciones largas o ramificadas son donde se cuelan los bugs; las versiones exactas hacen explícita cada actualización |
110
+ | Tests | `tests`, regla de PR, ratchet de cobertura | Ver abajo |
111
+ | Entorno del agente | `claude-check-on-edit`, `claude-deny-bypass`, `git-pre-commit`, `git-commit-msg` | El error llega en el mismo turno; el agente no puede saltar hooks, forzar push ni empujar a la rama base |
112
+
113
+ Tests: `tests` instala el runner con cobertura y su paso en el CI. En `check`, todo archivo de lógica (`.ts`, `.js` y variantes) que cambió respecto a la rama base necesita un `.test` o `.spec` al lado. Los componentes `.tsx`, los estilos, los tipos, las carpetas `app` e `infra` y los archivos `index`, `cli`, `main`, `types`, `styles` y `theme` están exentos. La cobertura de líneas solo puede subir: el piso vive en `.guardrails/baseline.json`.
114
+
115
+ Los umbrales numéricos (10, 40, 60, 3…) están juntos, con su razón, en `src/core/domain/thresholds.ts`.
116
+
117
+ ## Packs
118
+
119
+ El núcleo no conoce ningún lenguaje: pide a los packs activos sus restricciones, herramientas, hooks y pasos de CI. Los packs se apilan con `extends` y `detect` puede activar varios a la vez; el perfil (`.guardrails/profile.json`) lista los activos.
120
+
121
+ | Pack | Extiende | Se activa con | Añade |
122
+ | --- | --- | --- | --- |
123
+ | `js-ts` | | `package.json` (0,6) y `tsconfig.json` (1) | Todo el catálogo base, ESLint, `tsc`, Vitest |
124
+ | `node` | `js-ts` | un servidor o CLI (`express`, `fastify`, `commander`…) o `bin` | `env-through-config`, `no-process-exit`, `no-module-cache` |
125
+ | `react` | `js-ts` | dependencia `react` | `rules-of-hooks`, `effects-in-hooks`, `no-state-mutation`, `pure-components`, `hook-body-order`, `restrict-timers`; con React Compiler `no-manual-memoization`; con TanStack Query `query-key-constant` y `cache-policy-constant` |
126
+ | `react-native` | `react` | `react-native` o `expo` | `rn-no-heavy-inline-styles`, `rn-virtualized-lists`, `rn-no-logic-in-render`, `rn-native-import-limits`; Jest con `jest-expo` en vez de Vitest |
127
+ | `nextjs` | `react` | dependencia `next` | `next-no-unnecessary-use-client`, `next-server-client-boundary`, `next-thin-routes`, `next-thin-api-routes` (App Router y Pages Router) |
128
+
129
+ Un pack se activa con confianza de 0,5 o más. Next con React activa `js-ts`, `react` y `nextjs`.
130
+
131
+ ## Capa de GitHub
132
+
133
+ `init` genera estos archivos; ninguno se ejecuta contra GitHub por sí solo.
134
+
135
+ - **CI bloqueante** (`guardrails-ci.yml`): lint, typecheck, tests con cobertura, build y `guardrails check`, sin `|| true` ni `continue-on-error`. Jobs `check` y `status`.
136
+ - **Ruleset de la rama base**: JSON más `branch-protection.sh` en `.guardrails/github/`. Exige PR, los checks `check` y `status`, rama al día, sin force-push, sin borrado y sin bypass. Se aplica solo si una persona lo pide (`guardrails apply branch-protection --execute`).
137
+ - **Auto-merge** (`guardrails-auto-merge.yml`): al etiquetar un PR con `automerge` corre `gh pr merge --auto --squash`, que espera a que todos los checks estén en verde.
138
+ - **Rollback** (`guardrails-rollback.yml`): abre un PR de revert (`gh workflow run guardrails-rollback.yml -f sha=<sha>`) que pasa por el mismo CI, más un smoke posterior al merge que abre un issue si la rama base se rompe.
139
+ - **Dependabot**: actualizaciones semanales por ecosistema.
140
+ - **CODEOWNERS** (`--owner @usuario`; `init` lo deduce del remoto `origin`) y **plantilla de PR** con la lista de verificación.
141
+
142
+ `audit` comprueba con `gh api` que la protección de la rama base esté activa.
143
+
144
+ ## Ratchet y learn: el entorno se automejora
145
+
146
+ **Ratchet.** En un proyecto existente, `init` no rompe nada: lo que ya cumple va a `error` y lo demás a `warn`, con el conteo actual en `.guardrails/baseline.json`. En cada `check`:
147
+
148
+ - una regla en `warn` no puede tener más violaciones que su baseline (si las tiene, error `ratchet/<regla>`);
149
+ - si las violaciones bajan, el baseline baja con ellas;
150
+ - al llegar a 0, la regla sube sola a `error`.
151
+
152
+ La cobertura sigue la misma lógica con un piso que solo sube. `exact-deps` también entra al ratchet.
153
+
154
+ **Learn.** `guardrails learn` lee cuatro fuentes y propone qué instalar o crear: el historial de `check` (`.guardrails/history.jsonl`, una regla que aparece en 3 o más ejecuciones es un patrón), los commits `fix` y `revert`, los comentarios de review y los logs de CI fallidos (los dos últimos con `gh`). Cada propuesta trae la evidencia y el comando: `guardrails apply <id>`, `add-rule` o pagar deuda del baseline, de la mayor a la menor.
155
+
156
+ ## Añadir una regla o un pack
157
+
158
+ **Regla.** Cuando la IA recibe una corrección que una regla podría atrapar:
159
+
160
+ ```sh
161
+ guardrails add-rule no-fetch-en-componentes \
162
+ --message "Llama a la API desde la capa de servicios" \
163
+ --selector "CallExpression[callee.name='fetch']" \
164
+ --bad "fetch(url);" --good "getUser(id);"
165
+ ```
166
+
167
+ Genera la regla y su test en `eslint/guardrails/rules/`, la instala en `warn` y mide las violaciones existentes. Cuando lleguen a 0, `add-rule <nombre> --promote` la sube a `error`. Las reglas son `.mjs` para que ESLint las cargue sin paso de build.
168
+
169
+ **Pack.** Un ecosistema nuevo es una carpeta `src/packs/<id>/` que exporta un `Pack` (`src/core/domain/pack.ts`) y una línea en `src/packs/index.ts`. El pack declara `detect`, `profile`, su catálogo de `constraints`, los adaptadores de herramientas (linter, typecheck, formatter, test), `analyze`, y los hooks y pasos de CI que aporta. El núcleo nunca importa un pack, y `.guardrails/layers.json` lo hace cumplir con `import-boundaries`. AGENTS.md explica el detalle para Python o Go; esos packs no existen todavía.
170
+
171
+ ## Estado y limitaciones
172
+
173
+ - **Solo JavaScript y TypeScript.** Los cinco packs son de ese ecosistema; Python y Go están documentados, no implementados.
174
+ - **Preparado para npm como `@whil/guardrails`, aún sin primer publish.** Lo probado hasta ahora es ejecutar `node <ruta>/dist/cli.js` sobre fixtures; la instalación desde el registro no está probada.
175
+ - **Probado en fixtures**, no en proyectos reales de terceros. El flujo de PR (`pr-status`, `pr-repair`, comentario y artifact del CI) se ejercita en este repo.
176
+ - `init` no instala dependencias salvo con `--install`; si faltan (`eslint`, `typescript-eslint`, el runner de tests), las lista como primer paso.
177
+ - Los hooks y el CI generados asumen GitHub.
178
+ - Los mensajes del CLI están en inglés, salvo dos líneas del resumen de `check`, que están en español.
179
+ - Los tests de las reglas (`*.test.mjs`) se ejecutan con `add-rule`; el CI del repo corre los de Vitest.
180
+
181
+ ## Release
182
+
183
+ El comando sigue siendo `guardrails`. Para publicar una versión:
184
+
185
+ ```sh
186
+ npm version patch --no-git-tag-version
187
+ git checkout -b chore/release-0.1.1
188
+ git commit -am "chore(release): 0.1.1"
189
+ ```
190
+
191
+ Abre el PR, espera `check` y `status` en verde y haz merge. Luego, desde `main`:
192
+
193
+ ```sh
194
+ git tag v0.1.1
195
+ git push origin v0.1.1
196
+ ```
197
+
198
+ El tag `v*` dispara `.github/workflows/publish.yml`, que:
199
+
200
+ 1. comprueba que el tag coincida con la versión de `package.json`;
201
+ 2. corre versiones exactas, lint, typecheck, tests, build y `self-check`;
202
+ 3. verifica con `scripts/check-pack.mjs` que el paquete solo contiene `dist`, `catalog-assets`, `README.md`, `LICENSE` y `package.json`, sin tests y sin archivos de `dist` que no tengan fuente en `src` (el mismo paso corre en el CI de cada PR; `pnpm build` limpia `dist` antes de compilar);
203
+ 4. publica con `npm publish --provenance --access public`, con el secret `NPM_TOKEN` del repo.
204
+
205
+ El primer publish y el `NPM_TOKEN` los pone una persona; el workflow no imprime el token.
206
+
207
+ La procedencia (`--provenance`) solo la acepta npm desde GitHub Actions con un repo público, así que está en el flag del workflow y no en `publishConfig`. Un `npm publish` local no la lleva; si el repo pasara a privado habría que quitar el flag.
208
+
209
+ Este repo se valida con sus propias reglas: `pnpm self-check`. Plan y decisiones: `planning/plan.md`.
@@ -0,0 +1,37 @@
1
+ #!/bin/sh
2
+ file=$(node -e 'let s="";process.stdin.on("data",(d)=>{s+=d}).on("end",()=>{try{process.stdout.write(String(JSON.parse(s).tool_input?.file_path??""))}catch{}})')
3
+ [ -n "$file" ] || exit 0
4
+
5
+ case "$file" in
6
+ *.ts | *.tsx | *.js | *.jsx | *.mjs) ;;
7
+ *) exit 0 ;;
8
+ esac
9
+ [ -f "$file" ] || exit 0
10
+
11
+ root=$(git -C "$(dirname "$file")" rev-parse --show-toplevel 2>/dev/null) || exit 0
12
+ case "$file" in
13
+ "$root"/node_modules/* | "$root"/dist/* | "$root"/.next/*) exit 0 ;;
14
+ esac
15
+ cd "$root" || exit 0
16
+
17
+ if [ -f pnpm-lock.yaml ]; then pm=pnpm
18
+ elif [ -f yarn.lock ]; then pm=yarn
19
+ elif [ -f bun.lock ] || [ -f bun.lockb ]; then pm=bun
20
+ else pm=npm
21
+ fi
22
+ has_script() { node -e 'process.exit(require("./package.json").scripts?.[process.argv[1]] ? 0 : 1)' "$1" 2>/dev/null; }
23
+
24
+ if [ -x node_modules/.bin/eslint ]; then
25
+ if ! output=$(./node_modules/.bin/eslint "$file" 2>&1); then
26
+ printf 'guardrails: eslint found problems in %s. Fix the cause (each message says how). Do not add eslint-disable, @ts-ignore or any to silence it:\n%s\n' "$file" "$output" >&2
27
+ exit 2
28
+ fi
29
+ fi
30
+
31
+ if has_script typecheck; then
32
+ if ! output=$("$pm" run --silent typecheck 2>&1); then
33
+ printf 'guardrails: typecheck failed after editing %s. Fix the type errors below at their source:\n%s\n' "$file" "$output" >&2
34
+ exit 2
35
+ fi
36
+ fi
37
+ exit 0
@@ -0,0 +1,21 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { fileURLToPath } from "node:url";
3
+ import { guardrailsPlugin } from "./index.mjs";
4
+
5
+ const state = JSON.parse(readFileSync(new URL("./rules.json", import.meta.url), "utf8"));
6
+ const repoRoot = fileURLToPath(new URL("../../", import.meta.url));
7
+ const entries = Object.entries(state.rules);
8
+
9
+ const typedParser = state.typedParser
10
+ ? [{ files: ["**/*.{ts,tsx,mts,cts}"], languageOptions: { parserOptions: { projectService: true, tsconfigRootDir: repoRoot } } }]
11
+ : [];
12
+
13
+ export const guardrailsConfig = [
14
+ { plugins: { guardrails: guardrailsPlugin }, linterOptions: state.linterOptions },
15
+ ...typedParser,
16
+ ...entries.map(([name, entry]) => ({
17
+ ...(entry.files ? { files: entry.files } : {}),
18
+ ...(entry.ignores ? { ignores: entry.ignores } : {}),
19
+ rules: { [name]: [entry.level, ...(entry.options ?? [])] },
20
+ })),
21
+ ];
@@ -0,0 +1,21 @@
1
+ import { RuleTester } from "eslint";
2
+ import { describe, it } from "node:test";
3
+
4
+ RuleTester.describe = describe;
5
+ RuleTester.it = it;
6
+ RuleTester.itOnly = it.only;
7
+
8
+ export async function makeTester({ typed = false } = {}) {
9
+ const tseslint = await import("typescript-eslint").catch(() => null);
10
+ return new RuleTester({
11
+ languageOptions: {
12
+ ecmaVersion: "latest",
13
+ sourceType: "module",
14
+ ...(tseslint ? { parser: tseslint.parser } : {}),
15
+ parserOptions: {
16
+ ecmaFeatures: { jsx: true },
17
+ ...(typed ? { projectService: { allowDefaultProject: ["*.ts"] }, tsconfigRootDir: process.cwd() } : {}),
18
+ },
19
+ },
20
+ });
21
+ }
@@ -0,0 +1,35 @@
1
+ const CONSTANT_NAME = /^[A-Z][A-Z0-9_]*$/;
2
+ const POLICY_KEYS = ["staleTime", "gcTime"];
3
+
4
+ export const cachePolicyConstant = {
5
+ meta: {
6
+ type: "problem",
7
+ schema: [],
8
+ messages: {
9
+ inline:
10
+ "`{{name}}` takes a named constant (`USER_STALE_TIME_MS`, `NEVER_STALE_TIME`), not a literal: the cache policy lives in one cache constants module or next to the hook's query key, so it is read and changed in one place.",
11
+ },
12
+ },
13
+ create(context) {
14
+ return {
15
+ Property(node) {
16
+ if (
17
+ node.key.type !== "Identifier" ||
18
+ !POLICY_KEYS.includes(node.key.name)
19
+ )
20
+ return;
21
+ if (node.parent.type !== "ObjectExpression") return;
22
+ if (
23
+ node.value.type === "Identifier" &&
24
+ CONSTANT_NAME.test(node.value.name)
25
+ )
26
+ return;
27
+ context.report({
28
+ node: node.value,
29
+ messageId: "inline",
30
+ data: { name: node.key.name },
31
+ });
32
+ },
33
+ };
34
+ },
35
+ };
@@ -0,0 +1,26 @@
1
+ const SERVER_ONLY = /^(server-only|next\/headers|node:.+|fs|fs\/promises|path|child_process|crypto|os)$|\/server(\/|$)/;
2
+
3
+ function isClientFile(program) {
4
+ return program.body.some((statement) => statement.type === "ExpressionStatement" && statement.directive === "use client");
5
+ }
6
+
7
+ export const clientImportsServer = {
8
+ meta: {
9
+ type: "problem",
10
+ schema: [],
11
+ messages: {
12
+ server: "A 'use client' file imports `{{source}}`, which only exists on the server. It breaks the build or leaks server code to the browser. Fetch the data in a server component and pass it as props, or call a server action or route handler from the client.",
13
+ },
14
+ },
15
+ create(context) {
16
+ const state = { client: false };
17
+ return {
18
+ Program(program) {
19
+ state.client = isClientFile(program);
20
+ },
21
+ ImportDeclaration(node) {
22
+ if (state.client && SERVER_ONLY.test(String(node.source.value))) context.report({ node, messageId: "server", data: { source: String(node.source.value) } });
23
+ },
24
+ };
25
+ },
26
+ };
@@ -0,0 +1,46 @@
1
+ const EFFECT_HOOKS = ["useEffect", "useLayoutEffect", "useInsertionEffect"];
2
+
3
+ export const effectsInHooks = {
4
+ meta: {
5
+ type: "problem",
6
+ schema: [],
7
+ messages: {
8
+ effect:
9
+ "`{{name}}` is only allowed inside a named hook (`use*.ts(x)` or a hook folder). Effects in components hide the external system they sync with and get copied. Move it to a hook named after what it does (`useAutosave`, `useDocumentTitle`) and call that hook.",
10
+ },
11
+ },
12
+ create(context) {
13
+ return {
14
+ ImportDeclaration(node) {
15
+ if (node.source.value !== "react") return;
16
+ node.specifiers
17
+ .filter(
18
+ (specifier) =>
19
+ specifier.type === "ImportSpecifier" &&
20
+ EFFECT_HOOKS.includes(specifier.imported.name),
21
+ )
22
+ .forEach((specifier) =>
23
+ context.report({
24
+ node: specifier,
25
+ messageId: "effect",
26
+ data: { name: specifier.imported.name },
27
+ }),
28
+ );
29
+ },
30
+ MemberExpression(node) {
31
+ if (node.object.type !== "Identifier" || node.object.name !== "React")
32
+ return;
33
+ if (
34
+ node.property.type !== "Identifier" ||
35
+ !EFFECT_HOOKS.includes(node.property.name)
36
+ )
37
+ return;
38
+ context.report({
39
+ node: node.property,
40
+ messageId: "effect",
41
+ data: { name: node.property.name },
42
+ });
43
+ },
44
+ };
45
+ },
46
+ };
@@ -0,0 +1,26 @@
1
+ function isProcessEnv(node) {
2
+ return (
3
+ node.object.type === "Identifier" &&
4
+ node.object.name === "process" &&
5
+ !node.computed &&
6
+ node.property.type === "Identifier" &&
7
+ node.property.name === "env"
8
+ );
9
+ }
10
+
11
+ export const envThroughConfig = {
12
+ meta: {
13
+ type: "problem",
14
+ schema: [],
15
+ messages: {
16
+ env: "`process.env` is read outside a config file. A missing variable then fails late, in the first request that needs it. Read it once in a config module (`src/config.ts`, `src/config/*.ts` or `env.ts`), validate it there and import the typed value.",
17
+ },
18
+ },
19
+ create(context) {
20
+ return {
21
+ MemberExpression(node) {
22
+ if (isProcessEnv(node)) context.report({ node, messageId: "env" });
23
+ },
24
+ };
25
+ },
26
+ };
@@ -0,0 +1,169 @@
1
+ const BLOCKS = [
2
+ "hooks",
3
+ "valores derivados",
4
+ "handlers",
5
+ "useEffectEvent",
6
+ "efectos",
7
+ "render",
8
+ ];
9
+ const EFFECT_HOOKS = ["useEffect", "useLayoutEffect", "useInsertionEffect"];
10
+ const DERIVED_HOOKS = ["useMemo", "useCallback"];
11
+ const NESTED_SCOPES = [
12
+ "ArrowFunctionExpression",
13
+ "FunctionExpression",
14
+ "FunctionDeclaration",
15
+ ];
16
+ const IGNORED_STATEMENTS = [
17
+ "TSTypeAliasDeclaration",
18
+ "TSInterfaceDeclaration",
19
+ "EmptyStatement",
20
+ ];
21
+
22
+ function isComponentOrHookName(name) {
23
+ return /^[A-Z]/.test(name) || /^use[A-Z0-9]/.test(name);
24
+ }
25
+
26
+ function calleeName(call) {
27
+ if (call.callee.type === "Identifier") return call.callee.name;
28
+ if (
29
+ call.callee.type === "MemberExpression" &&
30
+ call.callee.property.type === "Identifier"
31
+ )
32
+ return call.callee.property.name;
33
+ return null;
34
+ }
35
+
36
+ function isHookName(name) {
37
+ return name !== null && /^use[A-Z0-9]/.test(name);
38
+ }
39
+
40
+ function findHookCalls(node, visitorKeys) {
41
+ if (node === null || typeof node !== "object") return [];
42
+ if (Array.isArray(node))
43
+ return node.flatMap((child) => findHookCalls(child, visitorKeys));
44
+ if (NESTED_SCOPES.includes(node.type)) return [];
45
+ const own =
46
+ node.type === "CallExpression" && isHookName(calleeName(node))
47
+ ? [calleeName(node)]
48
+ : [];
49
+ const children = (visitorKeys[node.type] ?? []).flatMap((key) =>
50
+ findHookCalls(node[key], visitorKeys),
51
+ );
52
+ return [...own, ...children];
53
+ }
54
+
55
+ function blockOfHook(name, resultIsUsed) {
56
+ if (EFFECT_HOOKS.includes(name)) return 4;
57
+ if (name === "useEffectEvent") return 3;
58
+ if (DERIVED_HOOKS.includes(name)) return 1;
59
+ return resultIsUsed ? 0 : 4;
60
+ }
61
+
62
+ function isFunctionInit(init) {
63
+ return (
64
+ init !== null &&
65
+ (init.type === "ArrowFunctionExpression" ||
66
+ init.type === "FunctionExpression")
67
+ );
68
+ }
69
+
70
+ function endsInReturn(statement) {
71
+ if (statement.type === "ReturnStatement") return true;
72
+ if (statement.type !== "BlockStatement") return false;
73
+ return statement.body.at(-1)?.type === "ReturnStatement";
74
+ }
75
+
76
+ function isGuardClause(statement) {
77
+ return (
78
+ statement.type === "IfStatement" &&
79
+ statement.alternate === null &&
80
+ endsInReturn(statement.consequent)
81
+ );
82
+ }
83
+
84
+ function isJsxInit(init) {
85
+ if (init === null) return false;
86
+ if (init.type === "JSXElement" || init.type === "JSXFragment") return true;
87
+ if (init.type === "ConditionalExpression")
88
+ return isJsxInit(init.consequent) || isJsxInit(init.alternate);
89
+ if (init.type === "LogicalExpression") return isJsxInit(init.right);
90
+ return false;
91
+ }
92
+
93
+ function guardBlock(highest) {
94
+ return highest <= 1 ? 1 : 5;
95
+ }
96
+
97
+ function blockOfStatement(statement, visitorKeys) {
98
+ if (IGNORED_STATEMENTS.includes(statement.type)) return null;
99
+ if (statement.type === "FunctionDeclaration") return 2;
100
+ if (statement.type === "ExpressionStatement") {
101
+ const hooks = findHookCalls(statement.expression, visitorKeys);
102
+ return hooks.length > 0 ? blockOfHook(hooks[0], false) : 5;
103
+ }
104
+ if (statement.type === "VariableDeclaration") {
105
+ const inits = statement.declarations.map((declarator) => declarator.init);
106
+ if (inits.every(isFunctionInit)) return 2;
107
+ if (inits.some(isJsxInit)) return 5;
108
+ const hooks = findHookCalls(inits, visitorKeys);
109
+ if (hooks.length === 0) return 1;
110
+ return Math.min(...hooks.map((name) => blockOfHook(name, true)));
111
+ }
112
+ return 5;
113
+ }
114
+
115
+ function functionName(node) {
116
+ if (node.type === "FunctionDeclaration") return node.id?.name ?? null;
117
+ if (
118
+ node.parent?.type === "VariableDeclarator" &&
119
+ node.parent.id.type === "Identifier"
120
+ )
121
+ return node.parent.id.name;
122
+ return null;
123
+ }
124
+
125
+ export const hookBodyOrder = {
126
+ meta: {
127
+ type: "problem",
128
+ schema: [],
129
+ messages: {
130
+ outOfOrder:
131
+ "{{current}} después de {{previous}} en `{{name}}`. El cuerpo de un componente o hook va siempre en bloques sin intercalar: hooks → valores derivados y guard clauses (`if (...) return`) → handlers → useEffectEvent → efectos (useEffect y hooks cuyo resultado no se usa) → render (early returns, consts JSX intermedios y el return final); intercalado, cada lector y cada agente copia otro orden. Arreglo: mueve la línea a su bloque; si un hook necesita un valor derivado o un handler, deriva ese valor dentro del hook que lo usa o en un helper de módulo, y si un render temprano necesita ir antes, sepáralo en un componente gate.",
132
+ },
133
+ },
134
+ create(context) {
135
+ const { visitorKeys } = context.sourceCode;
136
+ function check(node) {
137
+ const name = functionName(node);
138
+ if (name === null || !isComponentOrHookName(name)) return;
139
+ if (node.body.type !== "BlockStatement") return;
140
+ node.body.body.reduce(
141
+ (highest, statement) => {
142
+ const block = isGuardClause(statement)
143
+ ? guardBlock(highest.block)
144
+ : blockOfStatement(statement, visitorKeys);
145
+ if (block === null) return highest;
146
+ if (block < highest.block) {
147
+ context.report({
148
+ node: statement,
149
+ messageId: "outOfOrder",
150
+ data: {
151
+ current: BLOCKS[block],
152
+ previous: BLOCKS[highest.block],
153
+ name,
154
+ },
155
+ });
156
+ return highest;
157
+ }
158
+ return { block };
159
+ },
160
+ { block: 0 },
161
+ );
162
+ }
163
+ return {
164
+ FunctionDeclaration: check,
165
+ FunctionExpression: check,
166
+ ArrowFunctionExpression: check,
167
+ };
168
+ },
169
+ };