@meiti/healer 0.5.0 → 0.7.1
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 +14 -0
- package/check.mjs +272 -0
- package/instalar.mjs +7 -1
- package/mcp/proyecto.mjs +141 -0
- package/mcp/servidor.mjs +59 -91
- package/package.json +5 -2
- package/reglas.mjs +17 -0
package/README.md
CHANGED
|
@@ -21,6 +21,20 @@ Prefer to let your agent do it? Tell it: **"Install Healer: meiti.dev/healer/ins
|
|
|
21
21
|
| `--no-browser` | Do not open the browser, just print the link |
|
|
22
22
|
| `--reconnect` | Get a new key even if one is already saved |
|
|
23
23
|
|
|
24
|
+
## Check before every commit
|
|
25
|
+
|
|
26
|
+
```
|
|
27
|
+
npx @meiti/healer check # Healer rules on the whole project, in seconds, nothing leaves your computer
|
|
28
|
+
npx @meiti/healer hook on # run it before every commit in this repo (warns, never blocks)
|
|
29
|
+
npx @meiti/healer hook on --block # block the commit when a file of the commit has an error
|
|
30
|
+
npx @meiti/healer hook on --full # also send a full review without AI after each commit, in the background
|
|
31
|
+
npx @meiti/healer hook off # remove it (any hook you already had stays exactly as it was)
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
The rules come from real bugs that passed linters and tests: hand-copied lists that fell behind, Express routes that shadow each other, `ALTER TABLE` before its `CREATE TABLE`, `INSERT OR REPLACE` that wipes columns, `dotenv` imported after your own modules, and a route without the check its siblings have. If something is on purpose, say so next to it: `// healer-ignore: <rule> <reason>`. If the project has ESLint installed and configured, the hook also lints the files of the commit.
|
|
35
|
+
|
|
36
|
+
The full review (`--full`, or `npx @meiti/healer check --full`) runs Healer's Pentagon, Semgrep and your tests in its sandbox, without AI and without repairing. It is never sent when Healer already watches the repository: the watch reviews every push by itself, with AI, so you never get two runs of the same change. If the repo keeps its hooks elsewhere (husky or `core.hooksPath`), Healer does not touch those team files: it tells you the line to add.
|
|
37
|
+
|
|
24
38
|
## For other MCP agents
|
|
25
39
|
|
|
26
40
|
This package also ships the Healer MCP server, which reads the saved key:
|
package/check.mjs
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
// 🧭 healer check y healer hook (2026-11-26, pedido del usuario: "usarla antes de cada commit ... un modo auto activable en el
|
|
2
|
+
// plugin o en cada integración directamente por el usuario"). Dos capas:
|
|
3
|
+
//
|
|
4
|
+
// 1. Local, en segundos, sin mandar nada: las reglas de Healer (reglas.mjs, empaquetado de sanador/src/chequeos) sobre el
|
|
5
|
+
// proyecto, mostrando lo de los archivos del commit. Avisa y no frena, salvo que se pida --strict.
|
|
6
|
+
// 2. Completa (--full): el proyecto va a Healer en modo review_only (Pentágono, Semgrep y tests en el sandbox, sin IA y sin
|
|
7
|
+
// reparar). Si Healer ya vigila el repo, NO se manda: la vigilancia revisa ese cambio después del push, y con IA. Lo
|
|
8
|
+
// decide el cliente (pregunta antes) y lo vuelve a decidir el servidor (rechaza el envío si llega igual).
|
|
9
|
+
//
|
|
10
|
+
// Igual que el servidor MCP, este módulo no ejecuta ningún programa: la lista de archivos del commit se la pasa el hook (que es un
|
|
11
|
+
// script de git y corre git), y ESLint lo corre el hook si el proyecto lo tiene. El hook se instala solo si la persona lo pide.
|
|
12
|
+
import fs from 'node:fs';
|
|
13
|
+
import os from 'node:os';
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
import { rutasDelProyecto, archivosDelProyecto, resumenOmitidos } from './mcp/proyecto.mjs';
|
|
16
|
+
|
|
17
|
+
const API = (process.env.HEALER_API_URL || 'https://healer-api.meiti.dev').replace(/\/$/, '');
|
|
18
|
+
const VERSION = '0.7.1';
|
|
19
|
+
const es = /^es/i.test(process.env.HEALER_LANG || Intl.DateTimeFormat().resolvedOptions().locale || '');
|
|
20
|
+
const tx = (en, esp) => (es ? esp : en);
|
|
21
|
+
|
|
22
|
+
function leerClave() {
|
|
23
|
+
const env = String(process.env.HEALER_API_KEY || process.env.CLAUDE_PLUGIN_OPTION_API_KEY || '').trim();
|
|
24
|
+
if (env) return env;
|
|
25
|
+
try { return String(JSON.parse(fs.readFileSync(path.join(os.homedir(), '.healer', 'config.json'), 'utf8')).api_key || '').trim(); } catch { return ''; }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function api(metodo, ruta, cuerpo) {
|
|
29
|
+
const clave = leerClave();
|
|
30
|
+
if (!clave) throw new Error(tx('Healer is not connected on this computer. Run: npx @meiti/healer', 'Healer no está conectado en esta computadora. Corre: npx @meiti/healer'));
|
|
31
|
+
const r = await fetch(API + ruta, { method: metodo, headers: { 'x-api-key': clave, 'content-type': 'application/json', 'user-agent': `healer-check/${VERSION}` }, body: cuerpo ? JSON.stringify(cuerpo) : undefined });
|
|
32
|
+
const datos = await r.json().catch(() => ({}));
|
|
33
|
+
if (!r.ok) { const e = new Error(`Healer ${r.status}: ${datos.error || datos.message || 'no detail'}`); e.status = r.status; e.datos = datos; throw e; }
|
|
34
|
+
return datos;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// ───────────────────────────── Capa 1: local ─────────────────────────────
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Corre las reglas sobre el proyecto (respetando sus .gitignore) y devuelve los hallazgos. Con `archivos`, solo los que tocan
|
|
41
|
+
* esos archivos (en una lista, si cualquiera de las dos está en el commit). Nada sale de la máquina.
|
|
42
|
+
*/
|
|
43
|
+
export async function revisarLocal({ raiz, archivos = null }) {
|
|
44
|
+
const inicio = Date.now();
|
|
45
|
+
const { correrReglasPropias } = await import('./reglas.mjs');
|
|
46
|
+
const seguidas = new Set(rutasDelProyecto(raiz));
|
|
47
|
+
const r = correrReglasPropias(raiz, (rel) => seguidas.has(rel));
|
|
48
|
+
const delCommit = archivos ? new Set(archivos.map((a) => a.replace(/\\/g, '/'))) : null;
|
|
49
|
+
const hallazgos = delCommit ? r.hallazgos.filter((h) => delCommit.has(h.archivo) || (h.tambien && delCommit.has(h.tambien.archivo))) : r.hallazgos;
|
|
50
|
+
return { hallazgos, revisados: r.archivos_revisados, total_en_proyecto: r.hallazgos.length, errores: r.errores, ms: Date.now() - inicio };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function textoLocal(r, { archivos = null } = {}) {
|
|
54
|
+
const l = [];
|
|
55
|
+
const donde = archivos ? tx(`in the ${archivos.length} file(s) of this commit`, `en los ${archivos.length} archivo(s) de este commit`) : tx('in the project', 'en el proyecto');
|
|
56
|
+
if (!r.hallazgos.length) {
|
|
57
|
+
l.push(`✓ Healer: ${tx('no findings', 'sin hallazgos')} ${donde} (${r.revisados} ${tx('files read', 'archivos leídos')}, ${(r.ms / 1000).toFixed(1)} s).`);
|
|
58
|
+
} else {
|
|
59
|
+
l.push(`⚠ Healer: ${r.hallazgos.length} ${tx('finding(s)', 'hallazgo(s)')} ${donde} (${(r.ms / 1000).toFixed(1)} s):`);
|
|
60
|
+
for (const h of r.hallazgos.slice(0, 20)) l.push(` ${h.severidad === 'error' ? '✗' : '!'} ${h.archivo}:${h.linea} [${h.regla}] ${h.mensaje}`);
|
|
61
|
+
if (r.hallazgos.length > 20) l.push(` ... ${tx('and', 'y')} ${r.hallazgos.length - 20} ${tx('more', 'más')}`);
|
|
62
|
+
l.push(tx(' If something is on purpose, say so next to it: healer-ignore: <rule> <reason>', ' Si algo es a propósito, dilo junto al código: healer-ignore: <regla> <motivo>'));
|
|
63
|
+
}
|
|
64
|
+
if (archivos && r.total_en_proyecto > r.hallazgos.length) l.push(tx(` (${r.total_en_proyecto - r.hallazgos.length} more in files outside this commit: npx @meiti/healer check)`, ` (${r.total_en_proyecto - r.hallazgos.length} más en archivos fuera de este commit: npx @meiti/healer check)`));
|
|
65
|
+
if (r.errores.length) l.push(` ${tx('Rules that could not run', 'Reglas que no pudieron correr')}: ${r.errores.join(' | ')}`);
|
|
66
|
+
return l.join('\n');
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// ───────────────────────────── Capa 2: completa (Healer, sin IA) ─────────────────────────────
|
|
70
|
+
|
|
71
|
+
// El repo de GitHub del proyecto (owner/repo), leído de .git/config: con él Healer sabe si ya lo vigila.
|
|
72
|
+
function carpetaGit(raiz) {
|
|
73
|
+
const g = path.join(raiz, '.git');
|
|
74
|
+
try {
|
|
75
|
+
if (fs.statSync(g).isDirectory()) return g;
|
|
76
|
+
const m = fs.readFileSync(g, 'utf8').match(/gitdir:\s*(.+)/); // worktree o submódulo
|
|
77
|
+
return m ? path.resolve(raiz, m[1].trim()) : null;
|
|
78
|
+
} catch { return null; }
|
|
79
|
+
}
|
|
80
|
+
export function repoDeGithub(raiz) {
|
|
81
|
+
const git = carpetaGit(raiz);
|
|
82
|
+
if (!git) return null;
|
|
83
|
+
let config = '';
|
|
84
|
+
try { config = fs.readFileSync(path.join(git, 'config'), 'utf8'); } catch { try { config = fs.readFileSync(path.join(path.dirname(path.dirname(git)), 'config'), 'utf8'); } catch { return null; } }
|
|
85
|
+
const origen = config.split(/\n(?=\[)/).find((b) => /^\[remote "origin"\]/.test(b)) || '';
|
|
86
|
+
const url = (origen.match(/^\s*url\s*=\s*(.+)$/m) || [])[1]?.trim() || '';
|
|
87
|
+
const m = url.match(/github\.com[:/]([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+?)(?:\.git)?\/?$/);
|
|
88
|
+
return m ? m[1].toLowerCase() : null;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export async function revisarCompleto({ raiz }) {
|
|
92
|
+
const repo = repoDeGithub(raiz);
|
|
93
|
+
if (repo) {
|
|
94
|
+
const v = await api('GET', `/v1/watch?repo=${encodeURIComponent(repo)}`).catch(() => null);
|
|
95
|
+
if (v?.watched) return { omitido: 'vigilancia', repo, texto: tx(`Healer already watches ${repo}: the full review runs by itself after the push (with AI), so nothing was sent now.`, `Healer ya vigila ${repo}: la revisión completa corre sola después del push (con IA), así que ahora no se mandó nada.`) };
|
|
96
|
+
}
|
|
97
|
+
const { files, binary_files, total, omitidos_lista } = archivosDelProyecto(raiz);
|
|
98
|
+
if (!Object.keys(files).length) throw new Error(tx('No text files to send were found.', 'No encontré archivos de texto para mandar.'));
|
|
99
|
+
const appId = `hook/${(repo || path.basename(raiz)).replace(/[^\w.\/-]/g, '-').slice(0, 80)}`;
|
|
100
|
+
const envio = await api('POST', '/v1/repair', { files, ...(Object.keys(binary_files).length ? { binary_files } : {}), app_id: appId, review_only: true, ...(repo ? { repo } : {}), origin: 'healer-check', ...(omitidos_lista.length ? { omitted_files: omitidos_lista } : {}) });
|
|
101
|
+
if (envio.status === 'covered_by_watch') return { omitido: 'vigilancia', repo, texto: envio.message };
|
|
102
|
+
return {
|
|
103
|
+
job_id: envio.job_id,
|
|
104
|
+
texto: [
|
|
105
|
+
tx(`Sent to Healer for a full review without AI: job ${envio.job_id}.`, `Mandado a Healer para una revisión completa sin IA: trabajo ${envio.job_id}.`),
|
|
106
|
+
`${Object.keys(files).length} ${tx('files', 'archivos')}, ${Math.round(total / 1024)} KB.${omitidos_lista.length ? ` ${resumenOmitidos(omitidos_lista)}` : ''}`,
|
|
107
|
+
tx('It takes a few minutes; the result shows in the Healer panel (meiti.dev/healer) under', 'Tarda unos minutos; el resultado aparece en el panel de Healer (meiti.dev/healer) en') + ` ${appId}.`
|
|
108
|
+
].join('\n')
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// ───────────────────────────── El hook ─────────────────────────────
|
|
113
|
+
|
|
114
|
+
const INICIO = '# >>> healer';
|
|
115
|
+
const FIN = '# <<< healer';
|
|
116
|
+
const EXT_ESLINT = '\\.(js|jsx|ts|tsx|mjs|cjs)$';
|
|
117
|
+
|
|
118
|
+
function bloquePreCommit({ bloquear }) {
|
|
119
|
+
return [
|
|
120
|
+
`${INICIO} (npx @meiti/healer hook off ${tx('removes it', 'lo quita')})`,
|
|
121
|
+
// HEALER_CLI permite probar una versión local sin publicarla. Sin --strict, un fallo de npx (sin internet) nunca frena el commit.
|
|
122
|
+
'HEALER_ARCHIVOS=$(git diff --cached --name-only --diff-filter=ACMR)',
|
|
123
|
+
'if [ -n "$HEALER_ARCHIVOS" ]; then',
|
|
124
|
+
` printf '%s\\n' "$HEALER_ARCHIVOS" | \${HEALER_CLI:-npx -y @meiti/healer} check --stdin-files${bloquear ? ' --strict || exit 1' : ' || true'}`,
|
|
125
|
+
// ESLint lo corre git, no Healer: solo si el proyecto lo tiene instalado y configurado, y solo sobre los archivos del commit.
|
|
126
|
+
' if [ -x node_modules/.bin/eslint ] && ls eslint.config.* .eslintrc* >/dev/null 2>&1; then',
|
|
127
|
+
` printf '%s\\n' "$HEALER_ARCHIVOS" | grep -E '${EXT_ESLINT}' | tr '\\n' '\\0' | xargs -0 -r node_modules/.bin/eslint --no-error-on-unmatched-pattern${bloquear ? ' || exit 1' : ' || true'}`,
|
|
128
|
+
' fi',
|
|
129
|
+
'fi',
|
|
130
|
+
FIN
|
|
131
|
+
].join('\n');
|
|
132
|
+
}
|
|
133
|
+
function bloquePostCommit() {
|
|
134
|
+
return [
|
|
135
|
+
`${INICIO} (npx @meiti/healer hook off ${tx('removes it', 'lo quita')})`,
|
|
136
|
+
// En segundo plano: el commit ya terminó y no espera. Si Healer ya vigila el repo, no manda nada (ver revisarCompleto).
|
|
137
|
+
'(${HEALER_CLI:-npx -y @meiti/healer} check --full --quiet >/dev/null 2>&1 &)',
|
|
138
|
+
FIN
|
|
139
|
+
].join('\n');
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// Dónde viven los hooks del repo. Si el repo eligió otra carpeta (core.hooksPath, como husky), esos archivos suelen ser del equipo:
|
|
143
|
+
// no se tocan, se dice qué agregar.
|
|
144
|
+
function carpetaHooks(raiz) {
|
|
145
|
+
const git = carpetaGit(raiz);
|
|
146
|
+
if (!git) return { error: tx('This folder is not a git repository.', 'Esta carpeta no es un repositorio de git.') };
|
|
147
|
+
let config = '';
|
|
148
|
+
try { config = fs.readFileSync(path.join(git, 'config'), 'utf8'); } catch { /* sin config */ }
|
|
149
|
+
const propia = (config.match(/^\s*hooksPath\s*=\s*(.+)$/m) || [])[1]?.trim();
|
|
150
|
+
if (propia) return { externa: propia };
|
|
151
|
+
// En un worktree, los hooks son los del repo principal.
|
|
152
|
+
const comun = fs.existsSync(path.join(git, 'commondir')) ? path.resolve(git, fs.readFileSync(path.join(git, 'commondir'), 'utf8').trim()) : git;
|
|
153
|
+
return { carpeta: path.join(comun, 'hooks') };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function sinBloque(texto) {
|
|
157
|
+
const i = texto.indexOf(INICIO), f = texto.indexOf(FIN);
|
|
158
|
+
if (i < 0 || f < i) return texto;
|
|
159
|
+
// Se va el bloque con su salto de línea: el hook que ya existía queda exactamente como estaba.
|
|
160
|
+
return texto.slice(0, i) + texto.slice(f + FIN.length).replace(/^\r?\n/, '');
|
|
161
|
+
}
|
|
162
|
+
function conBloque(texto, bloque) {
|
|
163
|
+
const limpio = sinBloque(texto || '#!/bin/sh\n');
|
|
164
|
+
const lineas = limpio.split('\n');
|
|
165
|
+
// Va después del shebang: un hook existente que termina con "exit 0" no lo saltea.
|
|
166
|
+
const conShebang = lineas[0].startsWith('#!') ? 1 : 0;
|
|
167
|
+
if (!conShebang) lineas.unshift('#!/bin/sh');
|
|
168
|
+
lineas.splice(1, 0, bloque);
|
|
169
|
+
return lineas.join('\n').replace(/\n*$/, '\n');
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export function estadoHook(raiz) {
|
|
173
|
+
const c = carpetaHooks(raiz);
|
|
174
|
+
if (c.error) return { error: c.error };
|
|
175
|
+
if (c.externa) return { externa: c.externa, activo: false };
|
|
176
|
+
const leer = (n) => { try { return fs.readFileSync(path.join(c.carpeta, n), 'utf8'); } catch { return ''; } };
|
|
177
|
+
const pre = leer('pre-commit'), post = leer('post-commit');
|
|
178
|
+
return { activo: pre.includes(INICIO), bloquea: pre.includes(INICIO) && pre.includes('--strict'), completo: post.includes(INICIO), repo: repoDeGithub(raiz) };
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export async function instalarHook(raiz, { bloquear = false, completo = false } = {}) {
|
|
182
|
+
const c = carpetaHooks(raiz);
|
|
183
|
+
if (c.error) throw new Error(c.error);
|
|
184
|
+
if (c.externa) {
|
|
185
|
+
return tx(`This repo keeps its hooks in "${c.externa}" (husky or core.hooksPath), which usually belongs to the whole team, so I did not touch it. Add this line to its pre-commit file:`, `Este repo guarda sus hooks en "${c.externa}" (husky o core.hooksPath), que suele ser de todo el equipo, así que no lo toqué. Agrega esta línea a su archivo pre-commit:`)
|
|
186
|
+
+ `\n git diff --cached --name-only --diff-filter=ACMR | npx -y @meiti/healer check --stdin-files${bloquear ? ' --strict' : ''}`;
|
|
187
|
+
}
|
|
188
|
+
fs.mkdirSync(c.carpeta, { recursive: true });
|
|
189
|
+
const escribir = (nombre, bloque) => {
|
|
190
|
+
const ruta = path.join(c.carpeta, nombre);
|
|
191
|
+
let actual = null;
|
|
192
|
+
try { actual = fs.readFileSync(ruta, 'utf8'); } catch { /* no había */ }
|
|
193
|
+
// Sin bloque que poner: si el archivo no existía no se crea, y si solo tenía el nuestro se borra (antes quedaba vacío).
|
|
194
|
+
if (!bloque) {
|
|
195
|
+
if (actual === null) return;
|
|
196
|
+
const limpio = sinBloque(actual);
|
|
197
|
+
if (!limpio.replace(/^#!.*$/m, '').trim()) { fs.rmSync(ruta, { force: true }); return; }
|
|
198
|
+
fs.writeFileSync(ruta, limpio);
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
fs.writeFileSync(ruta, conBloque(actual ?? '', bloque));
|
|
202
|
+
try { fs.chmodSync(ruta, 0o755); } catch { /* Windows: git for Windows lo corre igual */ }
|
|
203
|
+
};
|
|
204
|
+
escribir('pre-commit', bloquePreCommit({ bloquear }));
|
|
205
|
+
escribir('post-commit', completo ? bloquePostCommit() : null);
|
|
206
|
+
const lineas = [tx('Healer will check every commit in this repo, locally and in a few seconds (nothing leaves your computer).', 'Healer va a revisar cada commit de este repo, local y en unos segundos (no sale nada de tu computadora).')];
|
|
207
|
+
lineas.push(bloquear ? tx('It blocks the commit if it finds an error in the files of the commit.', 'Frena el commit si encuentra un error en los archivos del commit.') : tx('It warns and never blocks the commit.', 'Avisa y nunca frena el commit.'));
|
|
208
|
+
if (completo) {
|
|
209
|
+
const repo = repoDeGithub(raiz);
|
|
210
|
+
const v = repo ? await api('GET', `/v1/watch?repo=${encodeURIComponent(repo)}`).catch(() => null) : null;
|
|
211
|
+
lineas.push(v?.watched
|
|
212
|
+
? tx(`Full review after each commit: on, but Healer already watches ${repo}, so it will not send anything while the watch is on (no double runs).`, `Revisión completa después de cada commit: encendida, pero Healer ya vigila ${repo}, así que no va a mandar nada mientras la vigilancia esté encendida (sin ejecuciones dobles).`)
|
|
213
|
+
: tx('Full review after each commit: on (in Healer, without AI, in the background).', 'Revisión completa después de cada commit: encendida (en Healer, sin IA, en segundo plano).'));
|
|
214
|
+
}
|
|
215
|
+
return lineas.join('\n');
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export function quitarHook(raiz) {
|
|
219
|
+
const c = carpetaHooks(raiz);
|
|
220
|
+
if (c.error) throw new Error(c.error);
|
|
221
|
+
if (c.externa) return tx(`This repo keeps its hooks in "${c.externa}": remove the healer line from its pre-commit file.`, `Este repo guarda sus hooks en "${c.externa}": quita la línea de healer de su archivo pre-commit.`);
|
|
222
|
+
for (const nombre of ['pre-commit', 'post-commit']) {
|
|
223
|
+
const ruta = path.join(c.carpeta, nombre);
|
|
224
|
+
let actual;
|
|
225
|
+
try { actual = fs.readFileSync(ruta, 'utf8'); } catch { continue; }
|
|
226
|
+
const limpio = sinBloque(actual);
|
|
227
|
+
// Si solo quedaba nuestro bloque, el archivo se borra: un hook vacío no aporta nada.
|
|
228
|
+
if (/^#!.*\n?\s*$/.test(limpio.trim() + '\n') || !limpio.trim()) fs.rmSync(ruta, { force: true }); else fs.writeFileSync(ruta, limpio);
|
|
229
|
+
}
|
|
230
|
+
return tx('Healer no longer checks the commits of this repo.', 'Healer ya no revisa los commits de este repo.');
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// ───────────────────────────── Línea de comandos ─────────────────────────────
|
|
234
|
+
|
|
235
|
+
const leerStdin = () => new Promise((resolver) => {
|
|
236
|
+
if (process.stdin.isTTY) return resolver('');
|
|
237
|
+
let d = '';
|
|
238
|
+
process.stdin.setEncoding('utf8');
|
|
239
|
+
process.stdin.on('data', (c) => { d += c; });
|
|
240
|
+
process.stdin.on('end', () => resolver(d));
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
export async function cli(args) {
|
|
244
|
+
const [comando, ...resto] = args;
|
|
245
|
+
const raiz = process.cwd();
|
|
246
|
+
if (comando === 'hook') {
|
|
247
|
+
const accion = resto[0] || 'status';
|
|
248
|
+
if (accion === 'on') console.log(await instalarHook(raiz, { bloquear: resto.includes('--block'), completo: resto.includes('--full') }));
|
|
249
|
+
else if (accion === 'off') console.log(quitarHook(raiz));
|
|
250
|
+
else {
|
|
251
|
+
const e = estadoHook(raiz);
|
|
252
|
+
if (e.error) { console.log(e.error); return 1; }
|
|
253
|
+
if (e.externa) console.log(tx(`Hooks live in "${e.externa}" (husky or core.hooksPath): Healer does not manage them here.`, `Los hooks viven en "${e.externa}" (husky o core.hooksPath): Healer no los maneja desde acá.`));
|
|
254
|
+
else console.log(e.activo ? `${tx('On', 'Encendido')}: ${e.bloquea ? tx('blocks on errors', 'frena con errores') : tx('warns only', 'solo avisa')}; ${tx('full review after commit', 'revisión completa después del commit')}: ${e.completo ? tx('on', 'encendida') : tx('off', 'apagada')}.` : tx('Off. Turn it on with: npx @meiti/healer hook on', 'Apagado. Se enciende con: npx @meiti/healer hook on'));
|
|
255
|
+
}
|
|
256
|
+
return 0;
|
|
257
|
+
}
|
|
258
|
+
// check
|
|
259
|
+
const silencioso = resto.includes('--quiet');
|
|
260
|
+
if (resto.includes('--full')) {
|
|
261
|
+
try {
|
|
262
|
+
const r = await revisarCompleto({ raiz });
|
|
263
|
+
if (!silencioso) console.log(r.texto);
|
|
264
|
+
} catch (e) { if (!silencioso) console.log(String(e?.message || e)); return silencioso ? 0 : 1; }
|
|
265
|
+
return 0;
|
|
266
|
+
}
|
|
267
|
+
const archivos = resto.includes('--stdin-files') ? (await leerStdin()).split(/\r?\n/).map((s) => s.trim()).filter(Boolean) : null;
|
|
268
|
+
const r = await revisarLocal({ raiz, archivos });
|
|
269
|
+
if (resto.includes('--json')) console.log(JSON.stringify(r));
|
|
270
|
+
else if (!silencioso || r.hallazgos.length) console.log(textoLocal(r, { archivos }));
|
|
271
|
+
return resto.includes('--strict') && r.hallazgos.some((h) => h.severidad === 'error') ? 1 : 0;
|
|
272
|
+
}
|
package/instalar.mjs
CHANGED
|
@@ -229,4 +229,10 @@ async function main() {
|
|
|
229
229
|
console.log(gris(`${T.listoOtros} npx -y -p @meiti/healer healer-mcp\n`));
|
|
230
230
|
}
|
|
231
231
|
|
|
232
|
-
|
|
232
|
+
// 🧭 [2026-11-26] npx @meiti/healer check | hook (ver check.mjs). Un fallo del chequeo nunca frena un commit, salvo con --strict.
|
|
233
|
+
if (args[0] === 'check' || args[0] === 'hook') {
|
|
234
|
+
import('./check.mjs').then((m) => m.cli(args)).then((codigo) => process.exit(codigo ?? 0))
|
|
235
|
+
.catch((e) => { console.error(String(e?.message || e)); process.exit(args.includes('--strict') ? 1 : 0); });
|
|
236
|
+
} else {
|
|
237
|
+
main().catch((e) => { console.error(`\n${T.error} ${e.message}`); process.exit(1); });
|
|
238
|
+
}
|
package/mcp/proyecto.mjs
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// 📁 [2026-11-26] Qué archivos del proyecto salen de la máquina: lo que git mandaría según los .gitignore, nunca archivos de
|
|
2
|
+
// secretos, con los mismos topes que el servidor. Vivía adentro de mcp/servidor.mjs; se separó para que healer check (check.mjs)
|
|
3
|
+
// use exactamente la misma selección que healer_revisar. Sin dependencias y sin ejecutar ningún programa.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
|
|
7
|
+
const TOPE_ARCHIVO = 1_000_000;
|
|
8
|
+
// 🔒 [2026-11-21, metaxy] Un lockfile grande (uv.lock de 322 paquetes) pasaba el tope de 1 MB y no se mandaba: sin él, Healer
|
|
9
|
+
// instalaba otras versiones que las del dueño (un plugin de pytest más nuevo rompía todo). Los lockfiles pasan hasta 15 MB; el
|
|
10
|
+
// tope total no cambia.
|
|
11
|
+
const LOCKFILES = new Set(['uv.lock', 'poetry.lock', 'pdm.lock', 'Pipfile.lock', 'package-lock.json', 'npm-shrinkwrap.json', 'yarn.lock', 'pnpm-lock.yaml', 'bun.lock']);
|
|
12
|
+
// 📦 [PROYECTOS GRANDES, 2026-11-25] Misma regla que el servidor (src/mcp/seleccion.ts, valores por defecto de Core): el código
|
|
13
|
+
// tiene su tope propio, entra primero, y todo lo que queda afuera se lista y viaja con el trabajo (omitted_files).
|
|
14
|
+
const MB = 1024 * 1024;
|
|
15
|
+
const ES_CODIGO = /\.(js|jsx|ts|tsx|mjs|cjs|mts|cts|py|pyi|vue|svelte|json|toml|ya?ml|cfg|ini|sql|sh|css|scss|sass|less|lock)$/i;
|
|
16
|
+
const topeDe = (ruta) => (LOCKFILES.has(ruta.split('/').pop()) ? 15 * MB : ES_CODIGO.test(ruta) ? 4 * MB : TOPE_ARCHIVO);
|
|
17
|
+
const TOPE_TOTAL = 48 * MB;
|
|
18
|
+
const TEXTO_MOTIVO = { too_large: 'too large', total_limit: 'did not fit in the upload', binary_type: 'binary type Healer does not take', binary_too_large: 'binary over 1 MB' };
|
|
19
|
+
export function resumenOmitidos(lista, maximo = 8) {
|
|
20
|
+
if (!lista?.length) return '';
|
|
21
|
+
const tam = (b) => (b >= MB ? `${(b / MB).toFixed(1)} MB` : `${Math.max(1, Math.round(b / 1024))} KB`);
|
|
22
|
+
const partes = lista.slice(0, maximo).map((o) => `${o.path} (${tam(o.bytes)}, ${TEXTO_MOTIVO[o.reason] ?? o.reason})`);
|
|
23
|
+
return `${lista.length} file(s) left out of this run: ${partes.join(', ')}${lista.length > maximo ? `, and ${lista.length - maximo} more` : ''}.`;
|
|
24
|
+
}
|
|
25
|
+
const IGNORAR = new Set(['.git', 'node_modules', '.venv', 'venv', 'dist', 'build', '.next', 'coverage', '__pycache__', '.healer', '.turbo', '.cache']);
|
|
26
|
+
|
|
27
|
+
// ───────────────────────────── Proyecto ─────────────────────────────
|
|
28
|
+
|
|
29
|
+
// Archivos de secretos: nunca salen de la máquina, aunque el proyecto se haya olvidado de ignorarlos.
|
|
30
|
+
const SECRETO = /^(\.env(\..+)?|.*\.(pem|key|p12|pfx|keystore|jks)|id_(rsa|dsa|ecdsa|ed25519)(\.pub)?|\.npmrc|\.pypirc|\.netrc|credentials(\.json)?)$/i;
|
|
31
|
+
const PLANTILLA_ENV = /^\.env\.(example|sample|template|dist)$/i;
|
|
32
|
+
|
|
33
|
+
// Una línea de .gitignore → expresión regular sobre la ruta relativa a la carpeta del .gitignore. Cubre lo que se usa en
|
|
34
|
+
// la práctica: comentarios, "!" para volver a incluir, "/" final (solo carpetas), "/" inicial o en el medio (anclado),
|
|
35
|
+
// *, ?, ** y [clases]. Antes esto lo hacía `git ls-files`; se hace acá para que el plugin no ejecute ningún programa.
|
|
36
|
+
function reglaGitignore(linea) {
|
|
37
|
+
let l = linea.replace(/\r$/, '');
|
|
38
|
+
if (!l.trim() || l.startsWith('#')) return null;
|
|
39
|
+
l = l.replace(/(?<!\\)\s+$/, '');
|
|
40
|
+
const negada = l.startsWith('!');
|
|
41
|
+
if (negada) l = l.slice(1);
|
|
42
|
+
l = l.replace(/^\\([#!])/, '$1');
|
|
43
|
+
const soloCarpeta = l.endsWith('/');
|
|
44
|
+
if (soloCarpeta) l = l.slice(0, -1);
|
|
45
|
+
const anclada = l.includes('/');
|
|
46
|
+
if (l.startsWith('/')) l = l.slice(1);
|
|
47
|
+
let re = '';
|
|
48
|
+
for (let i = 0; i < l.length; i++) {
|
|
49
|
+
const c = l[i];
|
|
50
|
+
if (c === '*' && l[i + 1] === '*') {
|
|
51
|
+
if (l[i + 2] === '/') { re += '(?:.*/)?'; i += 2; } else { re += '.*'; i += 1; }
|
|
52
|
+
} else if (c === '*') re += '[^/]*';
|
|
53
|
+
else if (c === '?') re += '[^/]';
|
|
54
|
+
else if (c === '[') { const fin = l.indexOf(']', i + 1); if (fin > i) { re += '[' + l.slice(i + 1, fin).replace(/^!/, '^').replace(/\\/g, '\\\\') + ']'; i = fin; } else re += '\\['; }
|
|
55
|
+
else if (c === '\\' && i + 1 < l.length) { re += l[i + 1].replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); i++; }
|
|
56
|
+
else re += c.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
57
|
+
}
|
|
58
|
+
return { negada, soloCarpeta, re: new RegExp(anclada ? `^${re}$` : `(?:^|/)${re}$`) };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function leerReglas(archivo, base) {
|
|
62
|
+
try { return fs.readFileSync(archivo, 'utf8').split('\n').map(reglaGitignore).filter(Boolean).map((r) => ({ ...r, base })); } catch { return []; }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Gana la última regla que coincide, como en git. `rel` es la ruta relativa a la raíz del proyecto.
|
|
66
|
+
function ignorado(rel, esCarpeta, reglas) {
|
|
67
|
+
let resultado = false;
|
|
68
|
+
for (const r of reglas) {
|
|
69
|
+
if (r.soloCarpeta && !esCarpeta) continue;
|
|
70
|
+
const local = r.base ? (rel.startsWith(r.base + '/') ? rel.slice(r.base.length + 1) : null) : rel;
|
|
71
|
+
if (local !== null && r.re.test(local)) resultado = !r.negada;
|
|
72
|
+
}
|
|
73
|
+
return resultado;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// Las rutas que git mandaría (relativas a la raíz), sin leer su contenido: respeta los .gitignore del proyecto (en cada carpeta)
|
|
77
|
+
// y .git/info/exclude, y nunca incluye archivos de secretos. La usan archivosDelProyecto y healer check.
|
|
78
|
+
export function rutasDelProyecto(raiz) {
|
|
79
|
+
const rutas = [];
|
|
80
|
+
const recorrer = (dir, rel, reglas) => {
|
|
81
|
+
const propias = [...reglas, ...leerReglas(path.join(dir, '.gitignore'), rel)];
|
|
82
|
+
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
83
|
+
if (IGNORAR.has(e.name) || e.isSymbolicLink()) continue;
|
|
84
|
+
const r = rel ? `${rel}/${e.name}` : e.name;
|
|
85
|
+
if (ignorado(r, e.isDirectory(), propias)) continue;
|
|
86
|
+
if (e.isDirectory()) recorrer(path.join(dir, e.name), r, propias);
|
|
87
|
+
else if (e.isFile() && (!SECRETO.test(e.name) || PLANTILLA_ENV.test(e.name))) rutas.push(r);
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
recorrer(raiz, '', leerReglas(path.join(raiz, '.git', 'info', 'exclude'), ''));
|
|
91
|
+
return rutas;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function archivosDelProyecto(raiz) {
|
|
95
|
+
const rutas = rutasDelProyecto(raiz); // 🧱 [2026-11-21, pixelmatch-py: 39 tests con FileNotFoundError] Los binarios (imágenes, fixtures, datos) no se mandaban: los
|
|
96
|
+
// tests que los leen fallaban en Healer y pasaban en la máquina del dueño. Van en binary_files (base64), hasta 1 MB cada uno,
|
|
97
|
+
// sin compilados ni videos, y DESPUÉS de todo el código: nunca desplazan un archivo de texto del tope total.
|
|
98
|
+
const files = {};
|
|
99
|
+
const binary_files = {};
|
|
100
|
+
const binariosPendientes = [];
|
|
101
|
+
const textosPendientes = [];
|
|
102
|
+
const omitidos_lista = [];
|
|
103
|
+
let total = 0;
|
|
104
|
+
const BINARIO_EXCLUIDO = /\.(pyc|pyo|so|dll|dylib|exe|o|a|obj|class|jar|war|whl|egg|mp4|mov|avi|mkv|webm|iso|dmg|7z|rar)$/i;
|
|
105
|
+
for (const ruta of rutas) {
|
|
106
|
+
if (ruta.split('/').some((parte) => IGNORAR.has(parte))) continue;
|
|
107
|
+
const p = path.join(raiz, ruta);
|
|
108
|
+
let buf;
|
|
109
|
+
try {
|
|
110
|
+
const info = fs.statSync(p);
|
|
111
|
+
if (!info.isFile()) continue;
|
|
112
|
+
// Un archivo más grande que cualquier tope ni se lee: se anota como demasiado grande (o binario, si lo parece por su tipo).
|
|
113
|
+
if (info.size > Math.max(topeDe(ruta), TOPE_ARCHIVO)) { omitidos_lista.push({ path: ruta, reason: BINARIO_EXCLUIDO.test(ruta) ? 'binary_type' : 'too_large', bytes: info.size }); continue; }
|
|
114
|
+
buf = fs.readFileSync(p);
|
|
115
|
+
} catch { continue; }
|
|
116
|
+
if (buf.includes(0)) {
|
|
117
|
+
if (BINARIO_EXCLUIDO.test(ruta)) omitidos_lista.push({ path: ruta, reason: 'binary_type', bytes: buf.length });
|
|
118
|
+
else if (buf.length > TOPE_ARCHIVO) omitidos_lista.push({ path: ruta, reason: 'binary_too_large', bytes: buf.length });
|
|
119
|
+
else binariosPendientes.push([ruta, buf]);
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
if (buf.length > topeDe(ruta)) { omitidos_lista.push({ path: ruta, reason: 'too_large', bytes: buf.length }); continue; }
|
|
123
|
+
// Primero el código y la configuración; los demás textos después y los binarios al final.
|
|
124
|
+
if (!ES_CODIGO.test(ruta)) { textosPendientes.push([ruta, buf]); continue; }
|
|
125
|
+
if (total + buf.length > TOPE_TOTAL) { omitidos_lista.push({ path: ruta, reason: 'total_limit', bytes: buf.length }); continue; }
|
|
126
|
+
files[ruta] = buf.toString('utf8');
|
|
127
|
+
total += buf.length;
|
|
128
|
+
}
|
|
129
|
+
for (const [ruta, buf] of textosPendientes) {
|
|
130
|
+
if (total + buf.length > TOPE_TOTAL) { omitidos_lista.push({ path: ruta, reason: 'total_limit', bytes: buf.length }); continue; }
|
|
131
|
+
files[ruta] = buf.toString('utf8');
|
|
132
|
+
total += buf.length;
|
|
133
|
+
}
|
|
134
|
+
for (const [ruta, buf] of binariosPendientes) {
|
|
135
|
+
const b64 = buf.toString('base64');
|
|
136
|
+
if (total + b64.length > TOPE_TOTAL) { omitidos_lista.push({ path: ruta, reason: 'total_limit', bytes: buf.length }); continue; }
|
|
137
|
+
binary_files[ruta] = b64;
|
|
138
|
+
total += b64.length;
|
|
139
|
+
}
|
|
140
|
+
return { files, binary_files, total, omitidos: omitidos_lista.length, omitidos_lista };
|
|
141
|
+
}
|