@whil/guardrails 0.1.0 → 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/README.md +15 -1
- package/dist/cli.js +4 -1
- package/dist/config/runtime.js +15 -0
- package/dist/core/app/analysis.js +71 -3
- package/dist/core/app/args.js +2 -0
- package/dist/core/app/commands/audit.js +3 -3
- package/dist/core/app/commands/check.js +3 -3
- package/dist/core/app/commands/init.js +5 -2
- package/dist/core/app/commands/self-check.js +6 -3
- package/dist/core/domain/agents-md.js +15 -3
- package/dist/core/domain/errors.js +1 -0
- package/dist/core/domain/perf.js +65 -0
- package/dist/core/infra/exec.js +3 -2
- package/dist/core/infra/hash.js +10 -0
- package/dist/core/infra/lock.js +102 -0
- package/dist/core/infra/result-cache.js +49 -0
- package/dist/packs/js-ts/app/analysis.js +15 -8
- package/dist/packs/js-ts/domain/ts-options.js +3 -0
- package/dist/packs/js-ts/infra/tsc.js +12 -4
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -88,7 +88,7 @@ Todos aceptan `--json`, no hacen preguntas y usan los mismos códigos de salida:
|
|
|
88
88
|
| `detect` | Lee el repo, activa packs y escribe `.guardrails/profile.json` |
|
|
89
89
|
| `plan` | Huecos entre el repo y el catálogo (`gap`, `installed`, `not-applicable`) |
|
|
90
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 |
|
|
91
|
+
| `check [rutas...]` | Diagnósticos con archivo, línea, regla y cómo arreglarlo; con rutas, solo esos archivos |
|
|
92
92
|
| `audit` | Métricas: violaciones, `eslint-disable` sin razón, reglas en warn, protección de rama (`--offline` omite GitHub) |
|
|
93
93
|
| `self-check` | `check` + `audit` en una sola pasada |
|
|
94
94
|
| `add-rule <nombre>` | Crea una regla de lint con su test a partir de una corrección |
|
|
@@ -153,6 +153,20 @@ La cobertura sigue la misma lógica con un piso que solo sube. `exact-deps` tamb
|
|
|
153
153
|
|
|
154
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
155
|
|
|
156
|
+
## Rendimiento y concurrencia
|
|
157
|
+
|
|
158
|
+
Varios agentes corriendo `check`, `tsc` y `eslint` sobre todo el repo a la vez dejaron una laptop inutilizable. El CLI lo hace imposible sin que el agente tenga que acordarse de nada, para `check`, `audit`, `self-check` e `init`:
|
|
159
|
+
|
|
160
|
+
- **Una corrida pesada por máquina y por repo.** Un lock en el directorio de caché del usuario (`~/Library/Caches/guardrails` en macOS, `$XDG_CACHE_HOME/guardrails` o `~/.cache/guardrails` en Linux, o `GUARDRAILS_CACHE_DIR`) guarda el pid de quien lo tiene. La segunda corrida espera en cola y avisa por stderr (`guardrails: otra corrida en curso en <repo>, esperando`); nunca lanza una segunda en paralelo. Si el pid ya no existe (crash, kill) el lock se libera solo. Si la espera pasa de `GUARDRAILS_LOCK_TIMEOUT_MS` (600000 por defecto, o `--lock-timeout <segundos>`), falla con `error[busy]` y exit 3.
|
|
161
|
+
- **Caché por contenido del árbol.** La clave es el hash del contenido de los archivos del repo (tracked y sin trackear, sin `.gitignore`), el HEAD, la rama base, la versión del CLI, los packs y las rutas. Si nada cambió desde la última corrida, devuelve el resultado guardado sin ejecutar `eslint` ni `tsc` (`cached: true` en el JSON). Quien esperaba en la cola también lo aprovecha cuando la corrida anterior ya produjo el resultado. `--no-cache` fuerza una corrida nueva. Solo se guarda un resultado donde todas las herramientas corrieron y la corrida no modificó archivos.
|
|
162
|
+
- **`tsc` incremental por defecto**, con `--tsBuildInfoFile` en el directorio de caché (nunca en el repo). Nunca se pasa `--incremental false`.
|
|
163
|
+
- **Modo por rutas.** `guardrails check src/foo src/bar/x.ts` corre `eslint` solo sobre esas rutas y filtra los errores de `tsc` a esas rutas (el typecheck sigue leyendo el proyecto, pero incremental). Un agente valida su carpeta sin analizar el repo entero.
|
|
164
|
+
- **Tope de procesos y memoria.** `GUARDRAILS_MAX_JOBS` (1 por defecto) es el máximo de corridas pesadas por máquina; con 1, `eslint` y `tsc` también corren uno detrás del otro. Los procesos hijos llevan `NODE_OPTIONS=--max-old-space-size=<GUARDRAILS_MAX_OLD_SPACE_MB>` (2048 por defecto) salvo que ya traigan uno.
|
|
165
|
+
|
|
166
|
+
El bloque que `init` y `agents-md` escriben en AGENTS.md lo explica a los agentes: validar con rutas, no relanzar mientras una corrida espera, no pasar `--incremental false` ni correr `tsc`/`eslint` a mano sobre todo el repo.
|
|
167
|
+
|
|
168
|
+
Límite conocido: los hooks generados (`.claude/hooks/guardrails-check.sh`, pre-commit) siguen llamando a `eslint` y al script `typecheck` del repo directamente, sin pasar por el lock.
|
|
169
|
+
|
|
156
170
|
## Añadir una regla o un pack
|
|
157
171
|
|
|
158
172
|
**Regla.** Cuando la IA recibe una corrección que una regla podría atrapar:
|
package/dist/cli.js
CHANGED
|
@@ -16,7 +16,9 @@ One step: init. Flow: detect -> plan -> apply <id> -> check (loop) -> audit. Eve
|
|
|
16
16
|
plan gaps between the repo and the constraint catalog
|
|
17
17
|
apply <id> [--dry-run] install a constraint and verify it
|
|
18
18
|
codeowners needs --owner @user; branch-protection --execute runs gh api
|
|
19
|
-
check [paths...]
|
|
19
|
+
check [paths...] [--no-cache] [--lock-timeout s]
|
|
20
|
+
every active pack's linters, typechecks and rules: diagnostics with file, line, rule, fix;
|
|
21
|
+
with paths, only those files (tsc errors filtered by path); one heavy run per machine, results cached by tree hash
|
|
20
22
|
add-rule <name> --message ... [--selector --bad --good --files --pack] | --promote
|
|
21
23
|
scaffold a lint rule + test from a correction (the pack that owns rules)
|
|
22
24
|
audit metrics per pack: violations, suppressions without reason, rules in warn
|
|
@@ -28,6 +30,7 @@ One step: init. Flow: detect -> plan -> apply <id> -> check (loop) -> audit. Eve
|
|
|
28
30
|
|
|
29
31
|
Global flags: --json --cwd <dir> -h (audit, self-check: --offline skips the GitHub query)
|
|
30
32
|
Exit codes: 0 ok, 1 findings, 2 usage, 3 precondition/conflict/missing dependency, 4 verification failed.
|
|
33
|
+
Env: GUARDRAILS_MAX_JOBS (heavy runs per machine, default 1), GUARDRAILS_LOCK_TIMEOUT_MS, GUARDRAILS_MAX_OLD_SPACE_MB, GUARDRAILS_CACHE_DIR.
|
|
31
34
|
JSON output includes timingMs for the command (check, audit and self-check add phasesMs).
|
|
32
35
|
`;
|
|
33
36
|
async function main(argv) {
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { homedir, platform } from "node:os";
|
|
2
|
+
import { cacheDirFor, DEFAULT_LOCK_TIMEOUT_MS, DEFAULT_MAX_JOBS, DEFAULT_MAX_OLD_SPACE_MB, mergeNodeOptions, positiveInt } from "../core/domain/perf.js";
|
|
3
|
+
export function readRuntime() {
|
|
4
|
+
const env = process.env;
|
|
5
|
+
return {
|
|
6
|
+
maxJobs: positiveInt(env["GUARDRAILS_MAX_JOBS"], DEFAULT_MAX_JOBS),
|
|
7
|
+
lockTimeoutMs: positiveInt(env["GUARDRAILS_LOCK_TIMEOUT_MS"], DEFAULT_LOCK_TIMEOUT_MS),
|
|
8
|
+
maxOldSpaceMb: positiveInt(env["GUARDRAILS_MAX_OLD_SPACE_MB"], DEFAULT_MAX_OLD_SPACE_MB),
|
|
9
|
+
cacheDir: cacheDirFor({ override: env["GUARDRAILS_CACHE_DIR"], xdg: env["XDG_CACHE_HOME"], home: homedir(), platform: platform() }),
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
export function childEnv() {
|
|
13
|
+
const env = process.env;
|
|
14
|
+
return { ...env, NODE_OPTIONS: mergeNodeOptions(env["NODE_OPTIONS"], readRuntime().maxOldSpaceMb) };
|
|
15
|
+
}
|
|
@@ -1,6 +1,74 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { readRuntime } from "../../config/runtime.js";
|
|
5
|
+
import { cacheable, normalizeScope } from "../domain/perf.js";
|
|
6
|
+
import { ok } from "../domain/result.js";
|
|
7
|
+
import { repoKey, sha256 } from "../infra/hash.js";
|
|
8
|
+
import { acquireLease, pidAlive } from "../infra/lock.js";
|
|
9
|
+
import { readCached, treeKey, writeCached } from "../infra/result-cache.js";
|
|
10
|
+
import { flagBool, flagString } from "./args.js";
|
|
1
11
|
import { timed } from "./timing.js";
|
|
2
|
-
export
|
|
3
|
-
const
|
|
12
|
+
export function optionsFrom(args) {
|
|
13
|
+
const seconds = Number(flagString(args, "lock-timeout"));
|
|
14
|
+
return { noCache: flagBool(args, "no-cache"), lockTimeoutMs: Number.isFinite(seconds) && seconds > 0 ? Math.round(seconds * 1000) : null };
|
|
15
|
+
}
|
|
16
|
+
function cliVersion() {
|
|
17
|
+
const parsed = JSON.parse(readFileSync(join(fileURLToPath(new URL(".", import.meta.url)), "..", "..", "..", "package.json"), "utf8"));
|
|
18
|
+
const version = typeof parsed === "object" && parsed !== null ? parsed.version : undefined;
|
|
19
|
+
return typeof version === "string" ? version : "unknown";
|
|
20
|
+
}
|
|
21
|
+
function keyOf(root, profile, packs, scope) {
|
|
22
|
+
const extra = [`cli:${cliVersion()}`, `packs:${packs.map((pack) => pack.id).join(",")}`, `scope:${scope.join(",")}`, `node:${process.version}`];
|
|
23
|
+
return treeKey(root, extra, profile.git.baseBranch);
|
|
24
|
+
}
|
|
25
|
+
function build(root, profile, packs, scope, results, phasesMs, cached) {
|
|
26
|
+
return { root, profile, packs, results, phasesMs, full: scope.length === 0, cached };
|
|
27
|
+
}
|
|
28
|
+
async function execute(root, profile, packs, scope) {
|
|
29
|
+
const wall = await timed(() => Promise.all(packs.map((pack) => pack.analyze({ root, profile, packs }, scope))));
|
|
4
30
|
const phases = wall.value.flatMap((result) => Object.entries(result.phasesMs).map(([name, ms]) => [`${result.pack}.${name}`, ms]));
|
|
5
|
-
return
|
|
31
|
+
return build(root, profile, packs, scope, wall.value, { ...Object.fromEntries(phases), parallelMs: wall.ms }, false);
|
|
32
|
+
}
|
|
33
|
+
function fromCache(target) {
|
|
34
|
+
const hit = target.key === null ? null : readCached(target.slot, target.key);
|
|
35
|
+
return hit === null ? null : build(target.root, target.profile, target.packs, target.scope, hit, { cacheHit: 0 }, true);
|
|
36
|
+
}
|
|
37
|
+
async function runLocked(target) {
|
|
38
|
+
const settled = fromCache(target);
|
|
39
|
+
if (settled !== null)
|
|
40
|
+
return settled;
|
|
41
|
+
const analysis = await execute(target.root, target.profile, target.packs, target.scope);
|
|
42
|
+
const unchanged = target.key !== null && keyOf(target.root, target.profile, target.packs, target.scope) === target.key;
|
|
43
|
+
if (target.key !== null && unchanged && cacheable(analysis.results))
|
|
44
|
+
writeCached(target.slot, target.key, analysis.results);
|
|
45
|
+
return analysis;
|
|
46
|
+
}
|
|
47
|
+
export async function analyze(root, profile, packs, paths, options) {
|
|
48
|
+
const runtime = readRuntime();
|
|
49
|
+
const scope = normalizeScope(root, paths);
|
|
50
|
+
const slot = { dir: runtime.cacheDir, repoKey: repoKey(root), scopeKey: sha256([packs.map((pack) => pack.id).join(","), "\0", scope.join("\0")]).slice(0, 16) };
|
|
51
|
+
const target = { root, profile, packs, scope, slot, key: options.noCache ? null : keyOf(root, profile, packs, scope) };
|
|
52
|
+
const hit = fromCache(target);
|
|
53
|
+
if (hit !== null)
|
|
54
|
+
return ok(hit);
|
|
55
|
+
const lease = await acquireLease({
|
|
56
|
+
dir: join(runtime.cacheDir, "locks"),
|
|
57
|
+
repoKey: slot.repoKey,
|
|
58
|
+
repo: root,
|
|
59
|
+
maxJobs: runtime.maxJobs,
|
|
60
|
+
timeoutMs: options.lockTimeoutMs ?? runtime.lockTimeoutMs,
|
|
61
|
+
pollMs: 250,
|
|
62
|
+
log: (message) => process.stderr.write(`${message}\n`),
|
|
63
|
+
isAlive: pidAlive,
|
|
64
|
+
pid: process.pid,
|
|
65
|
+
});
|
|
66
|
+
if (!lease.ok)
|
|
67
|
+
return lease;
|
|
68
|
+
try {
|
|
69
|
+
return ok(await runLocked(target));
|
|
70
|
+
}
|
|
71
|
+
finally {
|
|
72
|
+
lease.value.release();
|
|
73
|
+
}
|
|
6
74
|
}
|
package/dist/core/app/args.js
CHANGED
|
@@ -25,6 +25,8 @@ const OPTIONS = {
|
|
|
25
25
|
comment: { type: "boolean" },
|
|
26
26
|
ignore: { type: "string" },
|
|
27
27
|
"ignore-pending": { type: "boolean" },
|
|
28
|
+
"no-cache": { type: "boolean" },
|
|
29
|
+
"lock-timeout": { type: "string" },
|
|
28
30
|
};
|
|
29
31
|
const isCommand = (value) => COMMANDS.includes(value);
|
|
30
32
|
export function parseCli(argv, defaultCwd) {
|
|
@@ -3,7 +3,7 @@ import { EXIT } from "../../domain/errors.js";
|
|
|
3
3
|
import { protectionUnknown } from "../../domain/protection.js";
|
|
4
4
|
import { andThen, ok } from "../../domain/result.js";
|
|
5
5
|
import { checkProtection } from "../../infra/gh.js";
|
|
6
|
-
import { analyze } from "../analysis.js";
|
|
6
|
+
import { analyze, optionsFrom } from "../analysis.js";
|
|
7
7
|
import { flagBool } from "../args.js";
|
|
8
8
|
import { catalogOf } from "../catalog.js";
|
|
9
9
|
import { buildSession } from "../session.js";
|
|
@@ -28,11 +28,11 @@ export function reportAudit(analysis, offline) {
|
|
|
28
28
|
`branch protection (${profile.git.baseBranch}): ${protection.status}${protection.reason === null ? "" : ` (${protection.reason})`}`,
|
|
29
29
|
failing.length === 0 ? "audit clean" : `fix: ${failing.join("; ")}`,
|
|
30
30
|
].join("\n");
|
|
31
|
-
return ok({ exit: failing.length === 0 ? EXIT.ok : EXIT.findings, data: { metrics, failing, phasesMs: analysis.phasesMs }, text });
|
|
31
|
+
return ok({ exit: failing.length === 0 ? EXIT.ok : EXIT.findings, data: { metrics, failing, cached: analysis.cached, phasesMs: analysis.phasesMs }, text });
|
|
32
32
|
}
|
|
33
33
|
export async function auditCommand(args, registry) {
|
|
34
34
|
const session = buildSession(args.cwd, registry);
|
|
35
35
|
if (!session.ok)
|
|
36
36
|
return session;
|
|
37
|
-
return andThen(
|
|
37
|
+
return andThen(await analyze(args.cwd, session.value.profile, session.value.packs, [], optionsFrom(args)), (analysis) => reportAudit(analysis, flagBool(args, "offline")));
|
|
38
38
|
}
|
|
@@ -2,7 +2,7 @@ import { DIAGNOSTIC_LIMIT, mergeAnalyses, renderCheckText, summarize } from "../
|
|
|
2
2
|
import { capped } from "../../domain/diagnostics.js";
|
|
3
3
|
import { appError, EXIT } from "../../domain/errors.js";
|
|
4
4
|
import { andThen, err, ok } from "../../domain/result.js";
|
|
5
|
-
import { analyze } from "../analysis.js";
|
|
5
|
+
import { analyze, optionsFrom } from "../analysis.js";
|
|
6
6
|
import { recordHistory } from "../../infra/learn-sources.js";
|
|
7
7
|
import { buildSession } from "../session.js";
|
|
8
8
|
function countByRule(diagnostics) {
|
|
@@ -21,7 +21,7 @@ export function reportCheck(analysis) {
|
|
|
21
21
|
const verdict = summary.errors > 0 ? "fix" : summary.warnings > 0 ? "debt" : "clean";
|
|
22
22
|
return ok({
|
|
23
23
|
exit: summary.errors > 0 ? EXIT.findings : EXIT.ok,
|
|
24
|
-
data: { verdict, packs: analysis.profile.packs.map((pack) => pack.id), summary, skipped: merged.skipped, truncated: shown.truncated, phasesMs: analysis.phasesMs, diagnostics: shown.items },
|
|
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
25
|
text: renderCheckText(shown.items, summary, shown.truncated, merged.skipped),
|
|
26
26
|
});
|
|
27
27
|
}
|
|
@@ -29,5 +29,5 @@ export async function checkCommand(args, registry) {
|
|
|
29
29
|
const session = buildSession(args.cwd, registry);
|
|
30
30
|
if (!session.ok)
|
|
31
31
|
return session;
|
|
32
|
-
return andThen(
|
|
32
|
+
return andThen(await analyze(args.cwd, session.value.profile, session.value.packs, args.positionals, optionsFrom(args)), reportCheck);
|
|
33
33
|
}
|
|
@@ -6,7 +6,7 @@ import { ok } from "../../domain/result.js";
|
|
|
6
6
|
import { writeBaseline } from "../../infra/baseline.js";
|
|
7
7
|
import { backupFiles, ensureLines, runShellSync } from "../../infra/backup.js";
|
|
8
8
|
import { writeManaged } from "../../infra/fs.js";
|
|
9
|
-
import { analyze } from "../analysis.js";
|
|
9
|
+
import { analyze, optionsFrom } from "../analysis.js";
|
|
10
10
|
import { flagBool, flagString } from "../args.js";
|
|
11
11
|
import { catalogOf } from "../catalog.js";
|
|
12
12
|
import { commandsOf } from "../ci-plan.js";
|
|
@@ -99,7 +99,10 @@ async function finishInit(args, session, registry, command) {
|
|
|
99
99
|
const fresh = buildSession(args.cwd, registry);
|
|
100
100
|
if (!fresh.ok)
|
|
101
101
|
return fresh;
|
|
102
|
-
const
|
|
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;
|
|
103
106
|
const debt = analysis.results.reduce((all, result) => ({ ...all, ...result.debt }), {});
|
|
104
107
|
const baseline = writeBaseline(args.cwd, baselineFromCounts(debt));
|
|
105
108
|
const agents = agentsMdCommand(args.cwd, registry);
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { EXIT } from "../../domain/errors.js";
|
|
2
2
|
import { andThen, ok } from "../../domain/result.js";
|
|
3
|
-
import { analyze } from "../analysis.js";
|
|
3
|
+
import { analyze, optionsFrom } from "../analysis.js";
|
|
4
4
|
import { flagBool } from "../args.js";
|
|
5
5
|
import { buildSession } from "../session.js";
|
|
6
6
|
import { reportAudit } from "./audit.js";
|
|
@@ -9,9 +9,12 @@ export async function selfCheckCommand(args, registry) {
|
|
|
9
9
|
const session = buildSession(args.cwd, registry);
|
|
10
10
|
if (!session.ok)
|
|
11
11
|
return session;
|
|
12
|
-
const
|
|
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;
|
|
13
16
|
return andThen(reportCheck(analysis), (check) => andThen(reportAudit(analysis, flagBool(args, "offline")), (audit) => {
|
|
14
17
|
const clean = check.exit === EXIT.ok && audit.exit === EXIT.ok;
|
|
15
|
-
return ok({ exit: clean ? EXIT.ok : EXIT.findings, data: { verdict: clean ? (check.data["verdict"] === "debt" ? "debt" : "clean") : "fix", check: check.data, audit: audit.data, phasesMs: analysis.phasesMs }, text: `${check.text}\n${audit.text}` });
|
|
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}` });
|
|
16
19
|
}));
|
|
17
20
|
}
|
|
@@ -12,8 +12,8 @@ function flowSection(g) {
|
|
|
12
12
|
`1. \`${g("detect --json")}\`: read the repo and write \`.guardrails/profile.json\`.`,
|
|
13
13
|
`2. \`${g("plan --json")}\`: list gaps against the constraint catalog (\`items[].status\` is \`gap\`, \`installed\` or \`not-applicable\`). If \`install\` is set, run that command first.`,
|
|
14
14
|
`3. \`${g("apply <id> --json")}\` for each gap, in plan order. It installs the rule, hook or workflow and verifies it. Rules start at \`warn\` if the repo already violates them and move to \`error\` once violations reach 0.`,
|
|
15
|
-
`4. \`${g("check --json")}\`: after every change. Fix every entry in \`diagnostics[]\` (\`file\`, \`line\`, \`rule\`, \`message\`, \`fix\`) and run it again until \`verdict\` is \`clean\` (or \`debt\`: only warnings inside the baseline remain). The ratchet: a rule at warn may have at most the baseline count of violations, it can only go down, and at 0 it moves to error by itself. More than the baseline is an error \`ratchet/<rule>\`.`,
|
|
16
|
-
`5. \`${g("audit --json")}\` (or \`${g("self-check --json")}\` for check + audit with eslint and tsc run once
|
|
15
|
+
`4. \`${g("check --json")}\`: after every change (inside a task, \`${g("check <paths...> --json")}\` on just your files). Fix every entry in \`diagnostics[]\` (\`file\`, \`line\`, \`rule\`, \`message\`, \`fix\`) and run it again until \`verdict\` is \`clean\` (or \`debt\`: only warnings inside the baseline remain). The ratchet: a rule at warn may have at most the baseline count of violations, it can only go down, and at 0 it moves to error by itself. More than the baseline is an error \`ratchet/<rule>\`.`,
|
|
16
|
+
`5. \`${g("audit --json")}\` (or \`${g("self-check --json")}\` for check + audit with eslint and tsc run once): metrics (violations, \`eslint-disable\` without reason, rules at warn, branch protection).`,
|
|
17
17
|
`6. \`${g('add-rule <name> --message "<how to fix>" --selector "<esquery>" --bad "<code>" --good "<code>" --json')}\`: when you were corrected for a mistake a rule could catch, turn the correction into a rule plus test. Clean existing violations to 0, then \`add-rule <name> --promote\`.`,
|
|
18
18
|
`7. \`${g("learn --json")}\`: proposes new constraints and rules from your check history, fix commits, review comments and CI failures. Run it after a stretch of work and apply what it proposes with \`apply <id>\` or \`add-rule\`.`,
|
|
19
19
|
"",
|
|
@@ -30,6 +30,18 @@ function flowSection(g) {
|
|
|
30
30
|
"Errors in JSON look like `{ ok: false, error: { code, message, file, rule, fix } }`: change `file` as `fix` says.",
|
|
31
31
|
];
|
|
32
32
|
}
|
|
33
|
+
function performanceSection(g) {
|
|
34
|
+
return [
|
|
35
|
+
"### Performance: one heavy run per machine",
|
|
36
|
+
"",
|
|
37
|
+
"`check`, `audit` and `self-check` run eslint and tsc over the repo. Many agents doing that at once froze a laptop, so the CLI serializes them without you doing anything: a lock per machine and per repo (in the user cache dir, with the pid, so a crashed run frees it), a result cache keyed by the content of the tree, tsc in incremental mode and a memory cap on the child processes.",
|
|
38
|
+
"",
|
|
39
|
+
`- Validate your own folder, not the repo: \`${g("check <paths...> --json")}\` lints only those files and keeps the tsc errors that are in those paths. Use the full \`check\` once, before the PR.`,
|
|
40
|
+
"- If stderr says `otra corrida en curso en <repo>, esperando`, another run holds the lock. Do not start another one, do not kill it, do not run eslint or tsc by hand: wait, the command returns by itself. When it finishes and nothing changed, the answer comes from the cache (`cached: true` in the JSON).",
|
|
41
|
+
"- Never pass `--incremental false` to tsc and never run `tsc` or `eslint` over the whole repo yourself: use the commands above.",
|
|
42
|
+
"- `--no-cache` forces a fresh run. `--lock-timeout <seconds>` (or `GUARDRAILS_LOCK_TIMEOUT_MS`, default 600000) sets how long to wait before failing with `error[busy]` (exit 3: wait and run again, do not loop). `GUARDRAILS_MAX_JOBS` (default 1) is the number of heavy runs per machine and `GUARDRAILS_MAX_OLD_SPACE_MB` (default 2048) caps the memory of the child processes.",
|
|
43
|
+
];
|
|
44
|
+
}
|
|
33
45
|
function prLoopSection(g, base) {
|
|
34
46
|
return [
|
|
35
47
|
"### PR loop: CI answers, you fix",
|
|
@@ -79,7 +91,7 @@ const NEW_PACK_SECTION = [
|
|
|
79
91
|
"The core never imports a pack, so adding one cannot break another: `import-boundaries` enforces it. Reuse a base pack with `extends` (a Django pack would extend `python`) so shared constraints are declared once, and keep `domain` pure with I/O in `infra`, as every pack does. Nothing in `src/core` changes: `detect` activates the pack when its confidence is at least 0.5, `plan` and `apply` list its constraints, and `check` and `audit` run its `analyze`. This is documented, not implemented: there is no Python or Go pack in the repo.",
|
|
80
92
|
];
|
|
81
93
|
export function renderAgentsBlock(profile, packs, g) {
|
|
82
|
-
return [BLOCK_START, ...flowSection(g), "", ...prLoopSection(g, profile.git.baseBranch), "", ...packsSection(profile, packs), "", ...NEW_PACK_SECTION, "", ...rulesSection(profile.git.baseBranch), BLOCK_END, ""].join("\n");
|
|
94
|
+
return [BLOCK_START, ...flowSection(g), "", ...performanceSection(g), "", ...prLoopSection(g, profile.git.baseBranch), "", ...packsSection(profile, packs), "", ...NEW_PACK_SECTION, "", ...rulesSection(profile.git.baseBranch), BLOCK_END, ""].join("\n");
|
|
83
95
|
}
|
|
84
96
|
export function mergeAgentsMd(existing, block) {
|
|
85
97
|
if (existing === null || existing.trim() === "")
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { isAbsolute, posix, relative, sep } from "node:path";
|
|
2
|
+
import { isRecord, parseStrictJson } from "./json.js";
|
|
3
|
+
export const DEFAULT_MAX_JOBS = 1;
|
|
4
|
+
export const DEFAULT_LOCK_TIMEOUT_MS = 600_000;
|
|
5
|
+
export const DEFAULT_MAX_OLD_SPACE_MB = 2048;
|
|
6
|
+
const OLD_SPACE_FLAG = "--max-old-space-size";
|
|
7
|
+
export function positiveInt(raw, fallback) {
|
|
8
|
+
const value = raw === undefined || raw.trim() === "" ? Number.NaN : Number(raw);
|
|
9
|
+
return Number.isFinite(value) && value >= 1 ? Math.floor(value) : fallback;
|
|
10
|
+
}
|
|
11
|
+
export function mergeNodeOptions(existing, maxOldSpaceMb) {
|
|
12
|
+
const current = existing?.trim() ?? "";
|
|
13
|
+
return current.includes(OLD_SPACE_FLAG) ? current : `${current} ${OLD_SPACE_FLAG}=${String(maxOldSpaceMb)}`.trim();
|
|
14
|
+
}
|
|
15
|
+
export function cacheDirFor(input) {
|
|
16
|
+
if (input.override !== undefined && input.override !== "")
|
|
17
|
+
return input.override;
|
|
18
|
+
if (input.xdg !== undefined && input.xdg !== "")
|
|
19
|
+
return posix.join(input.xdg, "guardrails");
|
|
20
|
+
return input.platform === "darwin" ? posix.join(input.home, "Library", "Caches", "guardrails") : posix.join(input.home, ".cache", "guardrails");
|
|
21
|
+
}
|
|
22
|
+
export function normalizeScope(root, paths) {
|
|
23
|
+
const relatives = paths.map((path) => (isAbsolute(path) ? relative(root, path) : path).split(sep).join("/"));
|
|
24
|
+
const cleaned = relatives.map((path) => posix.normalize(path).replace(/\/+$/, "")).filter((path) => path !== "" && path !== ".");
|
|
25
|
+
return [...new Set(cleaned)].toSorted();
|
|
26
|
+
}
|
|
27
|
+
export function inScope(file, scope) {
|
|
28
|
+
if (scope.length === 0)
|
|
29
|
+
return true;
|
|
30
|
+
const normalized = posix.normalize(file.split(sep).join("/"));
|
|
31
|
+
return scope.some((entry) => normalized === entry || normalized.startsWith(`${entry}/`));
|
|
32
|
+
}
|
|
33
|
+
export function scopeItems(items, scope) {
|
|
34
|
+
return scope.length === 0 ? items : items.filter((item) => inScope(item.file, scope));
|
|
35
|
+
}
|
|
36
|
+
export function renderLockInfo(info) {
|
|
37
|
+
return JSON.stringify(info);
|
|
38
|
+
}
|
|
39
|
+
export function parseLockInfo(text) {
|
|
40
|
+
const parsed = parseStrictJson(text);
|
|
41
|
+
if (!parsed.ok || !isRecord(parsed.value))
|
|
42
|
+
return null;
|
|
43
|
+
const { pid, repo, startedAt } = parsed.value;
|
|
44
|
+
return typeof pid === "number" && Number.isInteger(pid) && typeof repo === "string" && typeof startedAt === "number" ? { pid, repo, startedAt } : null;
|
|
45
|
+
}
|
|
46
|
+
export function waitingMessage(holder, fallbackRepo) {
|
|
47
|
+
return `guardrails: otra corrida en curso en ${holder?.repo ?? fallbackRepo}, esperando`;
|
|
48
|
+
}
|
|
49
|
+
const isStringArray = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
|
|
50
|
+
function hasScalarFields(value) {
|
|
51
|
+
return typeof value["pack"] === "string" && typeof value["ran"] === "boolean" && (value["missingFix"] === null || typeof value["missingFix"] === "string");
|
|
52
|
+
}
|
|
53
|
+
function hasCollectionFields(value) {
|
|
54
|
+
const records = ["metrics", "debt", "phasesMs"].every((name) => isRecord(value[name]));
|
|
55
|
+
return records && Array.isArray(value["diagnostics"]) && Array.isArray(value["skipped"]) && isStringArray(value["failing"]) && isStringArray(value["lines"]);
|
|
56
|
+
}
|
|
57
|
+
function isStoredAnalysis(value) {
|
|
58
|
+
return isRecord(value) && hasScalarFields(value) && hasCollectionFields(value);
|
|
59
|
+
}
|
|
60
|
+
export function parseStoredResults(value) {
|
|
61
|
+
return Array.isArray(value) && value.length > 0 && value.every(isStoredAnalysis) ? value : null;
|
|
62
|
+
}
|
|
63
|
+
export function cacheable(results) {
|
|
64
|
+
return results.some((result) => result.ran) && results.every((result) => result.ran || result.skipped.length === 0);
|
|
65
|
+
}
|
package/dist/core/infra/exec.js
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import { execFile, spawnSync } from "node:child_process";
|
|
2
|
+
import { childEnv } from "../../config/runtime.js";
|
|
2
3
|
const MAX_BUFFER = 256 * 1024 * 1024;
|
|
3
4
|
export function runSync(command, args, cwd, input) {
|
|
4
|
-
const result = spawnSync(command, [...args], { cwd, encoding: "utf8", maxBuffer: MAX_BUFFER, ...(input === undefined ? {} : { input }) });
|
|
5
|
+
const result = spawnSync(command, [...args], { cwd, encoding: "utf8", maxBuffer: MAX_BUFFER, env: childEnv(), ...(input === undefined ? {} : { input }) });
|
|
5
6
|
return { status: result.status ?? 1, stdout: result.stdout, stderr: result.stderr };
|
|
6
7
|
}
|
|
7
8
|
export function runAsync(command, args, cwd) {
|
|
8
9
|
return new Promise((resolve) => {
|
|
9
|
-
execFile(command, [...args], { cwd, encoding: "utf8", maxBuffer: MAX_BUFFER }, (error, stdout, stderr) => {
|
|
10
|
+
execFile(command, [...args], { cwd, encoding: "utf8", maxBuffer: MAX_BUFFER, env: childEnv() }, (error, stdout, stderr) => {
|
|
10
11
|
const code = error === null ? 0 : error.code;
|
|
11
12
|
resolve({ status: typeof code === "number" ? code : error === null ? 0 : 1, stdout, stderr });
|
|
12
13
|
});
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { realpathSync } from "node:fs";
|
|
3
|
+
export function sha256(parts) {
|
|
4
|
+
const hash = createHash("sha256");
|
|
5
|
+
parts.forEach((part) => hash.update(part));
|
|
6
|
+
return hash.digest("hex");
|
|
7
|
+
}
|
|
8
|
+
export function repoKey(root) {
|
|
9
|
+
return sha256([realpathSync(root)]).slice(0, 16);
|
|
10
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { linkSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { appError } from "../domain/errors.js";
|
|
4
|
+
import { parseLockInfo, renderLockInfo, waitingMessage } from "../domain/perf.js";
|
|
5
|
+
import { err, ok } from "../domain/result.js";
|
|
6
|
+
export function pidAlive(pid) {
|
|
7
|
+
try {
|
|
8
|
+
process.kill(pid, 0);
|
|
9
|
+
return true;
|
|
10
|
+
}
|
|
11
|
+
catch (cause) {
|
|
12
|
+
return cause.code === "EPERM";
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
function readText(path) {
|
|
16
|
+
try {
|
|
17
|
+
return readFileSync(path, "utf8");
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
function removeQuietly(path) {
|
|
24
|
+
try {
|
|
25
|
+
unlinkSync(path);
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function create(path, text, pid) {
|
|
32
|
+
const temp = `${path}.${String(pid)}.${String(Math.random()).slice(2)}.tmp`;
|
|
33
|
+
writeFileSync(temp, text);
|
|
34
|
+
try {
|
|
35
|
+
linkSync(temp, path);
|
|
36
|
+
return true;
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
finally {
|
|
42
|
+
removeQuietly(temp);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
function staleText(path, isAlive) {
|
|
46
|
+
const text = readText(path);
|
|
47
|
+
if (text === null)
|
|
48
|
+
return "";
|
|
49
|
+
const info = parseLockInfo(text);
|
|
50
|
+
return info === null || !isAlive(info.pid) ? text : null;
|
|
51
|
+
}
|
|
52
|
+
function tryTake(path, text, options) {
|
|
53
|
+
if (create(path, text, options.pid))
|
|
54
|
+
return true;
|
|
55
|
+
const stale = staleText(path, options.isAlive);
|
|
56
|
+
if (stale === null)
|
|
57
|
+
return false;
|
|
58
|
+
if (stale !== "" && readText(path) === stale)
|
|
59
|
+
removeQuietly(path);
|
|
60
|
+
return create(path, text, options.pid);
|
|
61
|
+
}
|
|
62
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
63
|
+
async function takeAny(paths, text, options, deadline, announced) {
|
|
64
|
+
const taken = paths.find((path) => tryTake(path, text, options));
|
|
65
|
+
if (taken !== undefined)
|
|
66
|
+
return { path: taken };
|
|
67
|
+
if (Date.now() >= deadline)
|
|
68
|
+
return { path: null };
|
|
69
|
+
if (!announced) {
|
|
70
|
+
const holder = paths.map((path) => readText(path)).flatMap((content) => (content === null ? [] : [parseLockInfo(content)]))[0] ?? null;
|
|
71
|
+
options.log(waitingMessage(holder, options.repo));
|
|
72
|
+
}
|
|
73
|
+
await sleep(options.pollMs);
|
|
74
|
+
return takeAny(paths, text, options, deadline, true);
|
|
75
|
+
}
|
|
76
|
+
function busy(options) {
|
|
77
|
+
return appError("busy", `another guardrails run held the lock on ${options.repo} for ${String(Math.round(options.timeoutMs / 1000))}s`, {
|
|
78
|
+
fix: "Do not start another run while one is in progress: wait for it, then run `guardrails check <paths...>` on your folder. To wait longer, raise GUARDRAILS_LOCK_TIMEOUT_MS or pass --lock-timeout <seconds>.",
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
export async function acquireLease(options) {
|
|
82
|
+
mkdirSync(options.dir, { recursive: true });
|
|
83
|
+
const info = { pid: options.pid, repo: options.repo, startedAt: Date.now() };
|
|
84
|
+
const text = renderLockInfo(info);
|
|
85
|
+
const deadline = Date.now() + options.timeoutMs;
|
|
86
|
+
const repoLock = await takeAny([join(options.dir, `repo-${options.repoKey}.lock`)], text, options, deadline, false);
|
|
87
|
+
if (repoLock.path === null)
|
|
88
|
+
return err(busy(options));
|
|
89
|
+
const slots = Array.from({ length: options.maxJobs }, (_unused, index) => join(options.dir, `machine-${String(index)}.lock`));
|
|
90
|
+
const slot = await takeAny(slots, text, options, deadline, false);
|
|
91
|
+
const held = slot.path === null ? [repoLock.path] : [repoLock.path, slot.path];
|
|
92
|
+
const release = () => {
|
|
93
|
+
held.filter((path) => readText(path) === text).forEach((path) => {
|
|
94
|
+
removeQuietly(path);
|
|
95
|
+
});
|
|
96
|
+
};
|
|
97
|
+
if (slot.path === null) {
|
|
98
|
+
release();
|
|
99
|
+
return err(busy(options));
|
|
100
|
+
}
|
|
101
|
+
return ok({ release });
|
|
102
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { isRecord, parseStrictJson } from "../domain/json.js";
|
|
4
|
+
import { parseStoredResults } from "../domain/perf.js";
|
|
5
|
+
import { runSync } from "./exec.js";
|
|
6
|
+
import { sha256 } from "./hash.js";
|
|
7
|
+
const EXCLUDED = new Set([".guardrails/history.jsonl", ".guardrails/profile.json"]);
|
|
8
|
+
const LARGE_FILE_BYTES = 2 * 1024 * 1024;
|
|
9
|
+
const EXTRA_FILES = ["coverage/coverage-summary.json", "node_modules/.modules.yaml", "node_modules/.package-lock.json", "node_modules/.yarn-state.yml"];
|
|
10
|
+
function fileFingerprint(root, rel) {
|
|
11
|
+
const path = join(root, rel);
|
|
12
|
+
if (!existsSync(path))
|
|
13
|
+
return `${rel}\0missing`;
|
|
14
|
+
const stat = statSync(path);
|
|
15
|
+
if (!stat.isFile())
|
|
16
|
+
return `${rel}\0special`;
|
|
17
|
+
return stat.size > LARGE_FILE_BYTES ? `${rel}\0${String(stat.size)}\0${String(stat.mtimeMs)}` : sha256([`${rel}\0`, readFileSync(path, "latin1")]);
|
|
18
|
+
}
|
|
19
|
+
function gitLine(root, args) {
|
|
20
|
+
const result = runSync("git", args, root);
|
|
21
|
+
return result.status === 0 ? result.stdout.trim() : "";
|
|
22
|
+
}
|
|
23
|
+
export function treeKey(root, extra, baseBranch) {
|
|
24
|
+
const listed = runSync("git", ["ls-files", "-z", "--cached", "--others", "--exclude-standard"], root);
|
|
25
|
+
if (listed.status !== 0)
|
|
26
|
+
return null;
|
|
27
|
+
const files = [...new Set(listed.stdout.split("\0").filter((file) => file !== "" && !EXCLUDED.has(file)))].toSorted();
|
|
28
|
+
const refs = [gitLine(root, ["rev-parse", "HEAD"]), gitLine(root, ["rev-parse", "--verify", "--quiet", `origin/${baseBranch}`]), gitLine(root, ["rev-parse", "--verify", "--quiet", baseBranch])];
|
|
29
|
+
return sha256([...extra, ...refs, ...[...files, ...EXTRA_FILES].map((file) => fileFingerprint(root, file))].map((part) => `${part}\n`));
|
|
30
|
+
}
|
|
31
|
+
function slotPath(slot) {
|
|
32
|
+
return join(slot.dir, "results", slot.repoKey, `${slot.scopeKey}.json`);
|
|
33
|
+
}
|
|
34
|
+
export function readCached(slot, key) {
|
|
35
|
+
const path = slotPath(slot);
|
|
36
|
+
if (!existsSync(path))
|
|
37
|
+
return null;
|
|
38
|
+
const parsed = parseStrictJson(readFileSync(path, "utf8"));
|
|
39
|
+
if (!parsed.ok || !isRecord(parsed.value) || parsed.value["key"] !== key)
|
|
40
|
+
return null;
|
|
41
|
+
return parseStoredResults(parsed.value["results"]);
|
|
42
|
+
}
|
|
43
|
+
export function writeCached(slot, key, results) {
|
|
44
|
+
const path = slotPath(slot);
|
|
45
|
+
mkdirSync(join(slot.dir, "results", slot.repoKey), { recursive: true });
|
|
46
|
+
const temp = `${path}.${String(process.pid)}.tmp`;
|
|
47
|
+
writeFileSync(temp, JSON.stringify({ key, results }));
|
|
48
|
+
renameSync(temp, path);
|
|
49
|
+
}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { objectAt } from "../../../core/domain/json.js";
|
|
2
|
+
import { readRuntime } from "../../../config/runtime.js";
|
|
3
|
+
import { scopeItems } from "../../../core/domain/perf.js";
|
|
2
4
|
import { timed, timedSync } from "../../../core/app/timing.js";
|
|
3
5
|
import { readJsonRecord, exists } from "../../../core/infra/fs.js";
|
|
4
6
|
import { jsTs } from "../domain/data.js";
|
|
@@ -18,12 +20,17 @@ function missingFix(data) {
|
|
|
18
20
|
return `Install the tools (${installDevCommand(data.packageManager, ["eslint", "typescript-eslint", "typescript"])}) and run \`guardrails plan\` to see which constraints to apply.`;
|
|
19
21
|
}
|
|
20
22
|
async function runTools(root, data, paths) {
|
|
21
|
-
const
|
|
22
|
-
|
|
23
|
-
const
|
|
24
|
-
return
|
|
25
|
-
}
|
|
26
|
-
|
|
23
|
+
const lintTask = () => timed(() => (hasEslint(root) ? lintRepoAsync(root, data, paths) : Promise.resolve(null)));
|
|
24
|
+
const tscTask = async () => {
|
|
25
|
+
const run = await timed(() => (data.typescript.present ? runTscAsync(root) : Promise.resolve(null)));
|
|
26
|
+
return { ...run, value: run.value === null ? null : { ...run.value, diagnostics: scopeItems(run.value.diagnostics, paths) } };
|
|
27
|
+
};
|
|
28
|
+
if (readRuntime().maxJobs >= 2) {
|
|
29
|
+
const [lint, tsc] = await Promise.all([lintTask(), tscTask()]);
|
|
30
|
+
return { lint, tsc };
|
|
31
|
+
}
|
|
32
|
+
const lint = await lintTask();
|
|
33
|
+
const tsc = await tscTask();
|
|
27
34
|
return { lint, tsc };
|
|
28
35
|
}
|
|
29
36
|
function typeMetric(root, runs) {
|
|
@@ -86,7 +93,7 @@ function metricsOf(ctx, runs, scan, ratchet, promoted) {
|
|
|
86
93
|
export async function analyzeJsTs(ctx, paths) {
|
|
87
94
|
const data = jsTs(ctx.profile);
|
|
88
95
|
const runs = await runTools(ctx.root, data, paths);
|
|
89
|
-
const scan = timedSync(() => scanDisableDirectives(ctx.root, data));
|
|
96
|
+
const scan = timedSync(() => scopeItems(scanDisableDirectives(ctx.root, data), paths));
|
|
90
97
|
const base = toolDiagnostics(runs.lint.value, runs.tsc.value, fixesFor(ctx.packs));
|
|
91
98
|
const handled = new Set(base.filter((item) => item.rule === REASON_RULE).map((item) => `${item.file}:${item.line}`));
|
|
92
99
|
const ratchet = ratchetOf(ctx, runs);
|
|
@@ -95,7 +102,7 @@ export async function analyzeJsTs(ctx, paths) {
|
|
|
95
102
|
pack: "js-ts",
|
|
96
103
|
ran: runs.lint.value?.ran === true || runs.tsc.value?.ran === true,
|
|
97
104
|
debt: Object.fromEntries(ratchet.warnRules.map((rule) => [rule, ratchet.counts[rule] ?? 0])),
|
|
98
|
-
diagnostics: [...base, ...ratchet.result.regressions.map(ratchetDiagnostic), ...prRuleDiagnostics(ctx, paths), ...dependencyDiagnostics(data), ...disableDiagnostics(scan.value, handled)],
|
|
105
|
+
diagnostics: [...base, ...ratchet.result.regressions.map(ratchetDiagnostic), ...prRuleDiagnostics(ctx, paths), ...scopeItems(dependencyDiagnostics(data), paths), ...disableDiagnostics(scan.value, handled)],
|
|
99
106
|
skipped: skippedTools(runs.lint.value, runs.tsc.value),
|
|
100
107
|
missingFix: missingFix(data),
|
|
101
108
|
phasesMs: { eslint: runs.lint.ms, tsc: runs.tsc.ms, scan: scan.ms },
|
|
@@ -11,3 +11,6 @@ export function missingStrictOptions(compilerOptions) {
|
|
|
11
11
|
.filter(([name, value]) => compilerOptions[name] !== value)
|
|
12
12
|
.map(([name]) => name);
|
|
13
13
|
}
|
|
14
|
+
export function tscArgs(buildInfoFile) {
|
|
15
|
+
return ["--noEmit", "--pretty", "false", "--incremental", "--tsBuildInfoFile", buildInfoFile];
|
|
16
|
+
}
|
|
@@ -1,8 +1,11 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { mkdirSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { readRuntime } from "../../../config/runtime.js";
|
|
4
|
+
import { repoKey } from "../../../core/infra/hash.js";
|
|
5
|
+
import { tscArgs } from "../domain/ts-options.js";
|
|
2
6
|
import { parseTscOutput } from "../domain/diagnostics-js.js";
|
|
3
7
|
import { exists } from "../../../core/infra/fs.js";
|
|
4
8
|
import { runAsync, runSync } from "../../../core/infra/exec.js";
|
|
5
|
-
const ARGS = ["--noEmit", "--pretty", "false"];
|
|
6
9
|
const MISSING = Object.freeze({ ran: false, diagnostics: [], error: "tsc is not installed in node_modules" });
|
|
7
10
|
function bin(root) {
|
|
8
11
|
return join(root, "node_modules", ".bin", "tsc");
|
|
@@ -13,9 +16,14 @@ function toOutcome(result) {
|
|
|
13
16
|
return { ran: false, diagnostics, error: (result.stdout || result.stderr).trim().slice(0, 500) };
|
|
14
17
|
return { ran: true, diagnostics, error: null };
|
|
15
18
|
}
|
|
19
|
+
function buildInfoFile(root) {
|
|
20
|
+
const file = join(readRuntime().cacheDir, "tsbuildinfo", repoKey(root), "tsc.tsbuildinfo");
|
|
21
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
22
|
+
return file;
|
|
23
|
+
}
|
|
16
24
|
export function runTsc(root) {
|
|
17
|
-
return exists(root, "node_modules/.bin/tsc") ? toOutcome(runSync(bin(root),
|
|
25
|
+
return exists(root, "node_modules/.bin/tsc") ? toOutcome(runSync(bin(root), tscArgs(buildInfoFile(root)), root)) : MISSING;
|
|
18
26
|
}
|
|
19
27
|
export async function runTscAsync(root) {
|
|
20
|
-
return exists(root, "node_modules/.bin/tsc") ? toOutcome(await runAsync(bin(root),
|
|
28
|
+
return exists(root, "node_modules/.bin/tsc") ? toOutcome(await runAsync(bin(root), tscArgs(buildInfoFile(root)), root)) : MISSING;
|
|
21
29
|
}
|
package/package.json
CHANGED