@meiti/healer 0.4.0 → 0.7.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/mcp/servidor.mjs CHANGED
@@ -13,93 +13,13 @@ import os from 'node:os';
13
13
  import path from 'node:path';
14
14
  import crypto from 'node:crypto';
15
15
  import readline from 'node:readline';
16
+ import { archivosDelProyecto, resumenOmitidos } from './proyecto.mjs';
17
+ import { revisarLocal, textoLocal, revisarCompleto, instalarHook, quitarHook, estadoHook } from '../check.mjs';
16
18
 
17
- const VERSION = '0.5.0';
19
+ const VERSION = '0.8.0';
18
20
  const API = (process.env.HEALER_API_URL || 'https://healer-api.meiti.dev').replace(/\/$/, '');
19
21
  const leerClave = () => String(process.env.CLAUDE_PLUGIN_OPTION_API_KEY || '').trim();
20
22
  const ESTADO = path.join(os.tmpdir(), 'healer-claude-code');
21
- const TOPE_ARCHIVO = 1_000_000;
22
- const TOPE_TOTAL = 18 * 1024 * 1024;
23
- const IGNORAR = new Set(['.git', 'node_modules', '.venv', 'venv', 'dist', 'build', '.next', 'coverage', '__pycache__', '.healer', '.turbo', '.cache']);
24
-
25
- // ───────────────────────────── Proyecto ─────────────────────────────
26
-
27
- // Archivos de secretos: nunca salen de la máquina, aunque el proyecto se haya olvidado de ignorarlos.
28
- const SECRETO = /^(\.env(\..+)?|.*\.(pem|key|p12|pfx|keystore|jks)|id_(rsa|dsa|ecdsa|ed25519)(\.pub)?|\.npmrc|\.pypirc|\.netrc|credentials(\.json)?)$/i;
29
- const PLANTILLA_ENV = /^\.env\.(example|sample|template|dist)$/i;
30
-
31
- // Una línea de .gitignore → expresión regular sobre la ruta relativa a la carpeta del .gitignore. Cubre lo que se usa en
32
- // la práctica: comentarios, "!" para volver a incluir, "/" final (solo carpetas), "/" inicial o en el medio (anclado),
33
- // *, ?, ** y [clases]. Antes esto lo hacía `git ls-files`; se hace acá para que el plugin no ejecute ningún programa.
34
- function reglaGitignore(linea) {
35
- let l = linea.replace(/\r$/, '');
36
- if (!l.trim() || l.startsWith('#')) return null;
37
- l = l.replace(/(?<!\\)\s+$/, '');
38
- const negada = l.startsWith('!');
39
- if (negada) l = l.slice(1);
40
- l = l.replace(/^\\([#!])/, '$1');
41
- const soloCarpeta = l.endsWith('/');
42
- if (soloCarpeta) l = l.slice(0, -1);
43
- const anclada = l.includes('/');
44
- if (l.startsWith('/')) l = l.slice(1);
45
- let re = '';
46
- for (let i = 0; i < l.length; i++) {
47
- const c = l[i];
48
- if (c === '*' && l[i + 1] === '*') {
49
- if (l[i + 2] === '/') { re += '(?:.*/)?'; i += 2; } else { re += '.*'; i += 1; }
50
- } else if (c === '*') re += '[^/]*';
51
- else if (c === '?') re += '[^/]';
52
- 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 += '\\['; }
53
- else if (c === '\\' && i + 1 < l.length) { re += l[i + 1].replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); i++; }
54
- else re += c.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
55
- }
56
- return { negada, soloCarpeta, re: new RegExp(anclada ? `^${re}$` : `(?:^|/)${re}$`) };
57
- }
58
-
59
- function leerReglas(archivo, base) {
60
- try { return fs.readFileSync(archivo, 'utf8').split('\n').map(reglaGitignore).filter(Boolean).map((r) => ({ ...r, base })); } catch { return []; }
61
- }
62
-
63
- // Gana la última regla que coincide, como en git. `rel` es la ruta relativa a la raíz del proyecto.
64
- function ignorado(rel, esCarpeta, reglas) {
65
- let resultado = false;
66
- for (const r of reglas) {
67
- if (r.soloCarpeta && !esCarpeta) continue;
68
- const local = r.base ? (rel.startsWith(r.base + '/') ? rel.slice(r.base.length + 1) : null) : rel;
69
- if (local !== null && r.re.test(local)) resultado = !r.negada;
70
- }
71
- return resultado;
72
- }
73
-
74
- function archivosDelProyecto(raiz) {
75
- // Lo que git mandaría: respeta los .gitignore del proyecto (en cada carpeta) y .git/info/exclude.
76
- const rutas = [];
77
- const recorrer = (dir, rel, reglas) => {
78
- const propias = [...reglas, ...leerReglas(path.join(dir, '.gitignore'), rel)];
79
- for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
80
- if (IGNORAR.has(e.name) || e.isSymbolicLink()) continue;
81
- const r = rel ? `${rel}/${e.name}` : e.name;
82
- if (ignorado(r, e.isDirectory(), propias)) continue;
83
- if (e.isDirectory()) recorrer(path.join(dir, e.name), r, propias);
84
- else if (e.isFile() && (!SECRETO.test(e.name) || PLANTILLA_ENV.test(e.name))) rutas.push(r);
85
- }
86
- };
87
- recorrer(raiz, '', leerReglas(path.join(raiz, '.git', 'info', 'exclude'), ''));
88
- const files = {};
89
- let total = 0;
90
- let omitidos = 0;
91
- for (const ruta of rutas) {
92
- if (ruta.split('/').some((parte) => IGNORAR.has(parte))) continue;
93
- const p = path.join(raiz, ruta);
94
- let buf;
95
- try { const info = fs.statSync(p); if (!info.isFile() || info.size > TOPE_ARCHIVO) { omitidos++; continue; } buf = fs.readFileSync(p); } catch { continue; }
96
- if (buf.includes(0)) { omitidos++; continue; } // binario
97
- if (total + buf.length > TOPE_TOTAL) { omitidos++; continue; }
98
- files[ruta] = buf.toString('utf8');
99
- total += buf.length;
100
- }
101
- return { files, total, omitidos };
102
- }
103
23
 
104
24
  const sha256 = (texto) => crypto.createHash('sha256').update(texto, 'utf8').digest('hex');
105
25
 
@@ -123,7 +43,7 @@ const archivoDeTrabajo = (jobId) => path.join(ESTADO, `${String(jobId).replace(/
123
43
  async function revisar({ ruta, nivel, tests, confirmar_free, solo_revisar, bug }) {
124
44
  const raiz = path.resolve(ruta || process.cwd());
125
45
  if (!fs.existsSync(raiz) || !fs.statSync(raiz).isDirectory()) throw new Error(`Folder not found: ${raiz}.`);
126
- const { files, total, omitidos } = archivosDelProyecto(raiz);
46
+ const { files, binary_files, total, omitidos_lista } = archivosDelProyecto(raiz);
127
47
  if (!Object.keys(files).length) throw new Error('No text files to send were found in that folder.');
128
48
  if (Array.isArray(tests) && tests.length && !files['.healer.json']) files['.healer.json'] = JSON.stringify({ tests }, null, 2);
129
49
  const appId = `claude-code/${path.basename(raiz).replace(/[^\w.-]/g, '-').slice(0, 60) || 'proyecto'}`;
@@ -131,7 +51,7 @@ async function revisar({ ruta, nivel, tests, confirmar_free, solo_revisar, bug }
131
51
  // Si tocaría free y la organización pide preguntar, Healer responde 409 y no se encola nada.
132
52
  let envio;
133
53
  try {
134
- envio = await api('POST', '/v1/repair', { files, app_id: appId, ...(nivel === 'free' || nivel === 'pro' ? { ai_level: nivel } : {}), ...(confirmar_free === true ? { confirm_free: true } : {}), ...(solo_revisar === true ? { review_only: true } : {}), ...(typeof bug === 'string' && bug.trim() ? { bug_report: bug.trim().slice(0, 4000) } : {}) });
54
+ envio = await api('POST', '/v1/repair', { files, ...(Object.keys(binary_files).length ? { binary_files } : {}), app_id: appId, ...(nivel === 'free' || nivel === 'pro' ? { ai_level: nivel } : {}), ...(confirmar_free === true ? { confirm_free: true } : {}), ...(solo_revisar === true ? { review_only: true } : {}), ...(typeof bug === 'string' && bug.trim() ? { bug_report: bug.trim().slice(0, 4000) } : {}), ...(omitidos_lista.length ? { omitted_files: omitidos_lista } : {}) });
135
55
  } catch (e) {
136
56
  if (e.status === 409) return `Needs the user's confirmation, nothing was queued: ${e.datos?.message}\nIn this tool, "confirm_free" is confirmar_free: true${e.datos?.reason === 'cupo_agotado' ? ', and "review_only" is solo_revisar: true' : ''}.`;
137
57
  throw e;
@@ -140,7 +60,7 @@ async function revisar({ ruta, nivel, tests, confirmar_free, solo_revisar, bug }
140
60
  fs.writeFileSync(archivoDeTrabajo(envio.job_id), JSON.stringify({ raiz, appId, enviado: new Date().toISOString() }));
141
61
  return [
142
62
  `Sent to Healer: job ${envio.job_id} (${envio.ai_level === 'none' ? 'review only, no AI' : `${envio.ai_level} level`}${envio.ai_level_reason ? `, ${({ pedido: 'requested', organizacion: 'organization default', cupo: 'single repairs', confirmado: 'confirmed by the user', auto: 'organization allows free automatically', solo_revisar: 'review only' })[envio.ai_level_reason] || envio.ai_level_reason}` : ''}).`,
143
- `${Object.keys(files).length} files, ${Math.round(total / 1024)} KB${omitidos ? `, ${omitidos} skipped (binary or too large)` : ''}.`,
63
+ `${Object.keys(files).length} files${Object.keys(binary_files).length ? ` + ${Object.keys(binary_files).length} binary` : ''}, ${Math.round(total / 1024)} KB.${omitidos_lista.length ? ` ${resumenOmitidos(omitidos_lista)}` : ''}`,
144
64
  'Healer runs the tests in an isolated sandbox and repairs what fails. It usually takes a few minutes: check with healer_resultado.'
145
65
  ].join('\n');
146
66
  }
@@ -149,14 +69,14 @@ async function revisar({ ruta, nivel, tests, confirmar_free, solo_revisar, bug }
149
69
  async function revisarPantalla({ ruta, start_command, port, pages }) {
150
70
  const raiz = path.resolve(ruta || process.cwd());
151
71
  if (!fs.existsSync(raiz) || !fs.statSync(raiz).isDirectory()) throw new Error(`Folder not found: ${raiz}.`);
152
- const { files, total, omitidos } = archivosDelProyecto(raiz);
72
+ const { files, total, omitidos_lista } = archivosDelProyecto(raiz);
153
73
  if (!Object.keys(files).length) throw new Error('No text files to send were found in that folder.');
154
74
  const appId = `claude-code/${path.basename(raiz).replace(/[^\w.-]/g, '-').slice(0, 60) || 'proyecto'}`;
155
75
  // Sin start_command, port ni pages, Healer los busca (.healer.json "screen", la última corrida que funcionó, package.json).
156
76
  const envio = await api('POST', '/v1/screen', { files, app_id: appId, start_command: start_command || undefined, port: port || undefined, pages: Array.isArray(pages) && pages.length ? pages : undefined });
157
77
  return [
158
78
  `Screen review started: job ${envio.job_id}.`,
159
- `${Object.keys(files).length} files, ${Math.round(total / 1024)} KB${omitidos ? `, ${omitidos} skipped (binary or too large)` : ''}.`,
79
+ `${Object.keys(files).length} files, ${Math.round(total / 1024)} KB.${omitidos_lista.length ? ` ${resumenOmitidos(omitidos_lista)}` : ''}`,
160
80
  'Healer starts the app in its sandbox and checks the pages, without repairing anything. It usually takes under a minute: check with healer_resultado.'
161
81
  ].join('\n');
162
82
  }
@@ -192,7 +112,8 @@ async function resultado({ job_id, esperar_segundos }) {
192
112
  await new Promise((ok) => setTimeout(ok, 5000));
193
113
  }
194
114
  // El servidor manda en qué va (proyecto, minutos, etapa, lo hecho): se muestra eso en vez de solo "running".
195
- if (r.status === 'queued' || r.status === 'running') return `${r.progress?.message || `Still ${r.status}.`}\nCall healer_resultado again in a moment.\nJob id: ${job_id}`;
115
+ // [2026-11-23] Igual que el conector remoto: el cliente no recibe avisos y deja de preguntar al terminar su turno.
116
+ if (r.status === 'queued' || r.status === 'running') return `${r.progress?.message || `Still ${r.status}.`}\nKeep checking: call healer_resultado again now with the same job id. Do not tell the user it finished until this tool returns the result.\nIf you have to end your turn first, tell the user it is still running and that they can ask you to check job ${job_id} again.\nJob id: ${job_id}`;
196
117
  if (r.status === 'error') return `Healer could not finish: ${r.error || 'unknown error'}.`;
197
118
  if (r.tipo === 'pantalla') return informePantalla(r);
198
119
 
@@ -202,7 +123,7 @@ async function resultado({ job_id, esperar_segundos }) {
202
123
  if (meta) fs.writeFileSync(archivoDeTrabajo(job_id), JSON.stringify({ ...meta, terminado: new Date().toISOString(), status: r.status, changed_files: cambiados, base_hashes: r.base_hashes || {}, ...(r.requires_acceptance ? { requires_acceptance: r.requires_acceptance } : {}), files: Object.fromEntries(cambiados.map((c) => [c, r.files?.[c]])) }));
203
124
 
204
125
  const lineas = [];
205
- const titulo = { production_ready: 'Production ready: every check passes.', unresolved: r.partial_fix ? 'Partial delivery: some failures fixed, some remain.' : 'Unresolved: Healer could not leave every check passing.', unsupported_stack: 'Unsupported stack: no supported language was found to verify.' }[r.status] || r.status;
126
+ const titulo = r.not_accepted ? `Not accepted: ${r.not_accepted.reason} Healer only reviewed it; nothing was repaired and it does not count as a repair success or failure.` : { production_ready: 'Production ready: every check passes.', unresolved: r.partial_fix ? 'Partial delivery: some failures fixed, some remain.' : 'Unresolved: Healer could not leave every check passing.', unsupported_stack: 'Unsupported stack: no supported language was found to verify.' }[r.status] || r.status;
206
127
  lineas.push(`Result: ${titulo}`);
207
128
  // 🔐 [2026-11-16] Siempre se dice con qué nivel corrió y por qué.
208
129
  if (r.ai_level) lineas.push(`AI level: ${r.ai_level === 'none' ? 'none (review only)' : r.ai_level}${r.ai_level_reason ? ` (${({ pedido: 'requested', organizacion: 'organization default', cupo: 'single repairs', confirmado: 'confirmed by the user', auto: 'organization allows free automatically', solo_revisar: 'review only', benchmark: 'benchmark' })[r.ai_level_reason] || r.ai_level_reason})` : ''}.`);
@@ -228,8 +149,26 @@ async function resultado({ job_id, esperar_segundos }) {
228
149
  for (const x of r.report.support_updates || []) lineas.push(`Optional support update: ${x}`);
229
150
  } else if (r.failures) lineas.push(`Failures: ${r.failures.found ?? '?'} found, ${r.failures.fixed ?? '?'} fixed.${(r.failures.remaining || []).length ? ` Remaining: ${r.failures.remaining.map((f) => `[${f.origen}] ${String(f.detalle).slice(0, 160)}`).join(' | ')}` : ''}`);
230
151
  if (r.audit_report?.vulnerabilities_found) lineas.push(`Security: ${r.audit_report.vulnerabilities_found} findings (${(r.audit_report.findings || []).slice(0, 5).map((f) => `${f.archivo}:${f.linea} ${f.severidad}`).join(', ')}).`);
231
- if (r.pentagono_report?.puntaje != null) lineas.push(`Quality score (Pentagon): ${r.pentagono_report.puntaje}/100.`);
232
- if ((r.pending_improvements || []).length) lineas.push(`Non-blocking suggestions: ${r.pending_improvements.length} (not applied).`);
152
+ if (r.files_left_out?.length) lineas.push(`${resumenOmitidos(r.files_left_out)} The checks ran without them: if one is needed to build or test, the result can fail for that reason.`);
153
+ // 📋 [2026-11-25] De dónde sale el puntaje (pentagono_report.desglose, lo calcula Healer) y qué dice cada sugerencia.
154
+ const pr = r.pentagono_report;
155
+ if (pr?.puntaje != null) {
156
+ lineas.push(`Quality score (Pentagon): ${pr.puntaje}/100${pr.critico ? ' (needs attention)' : ''}.${pr.desglose ? ' Where the points went:' : ''}`);
157
+ const nombres = { quality: 'Code quality', dead_code: 'Dead code', dependencies: 'Dependencies (known vulnerabilities)' };
158
+ for (const p of pr.desglose || []) {
159
+ const sev = Object.entries(p.by_severity || {}).map(([s, n]) => `${n} ${s}`).join(', ');
160
+ lineas.push(`- ${nombres[p.parte] || p.parte} (${(p.tools || []).join(', ')}): -${p.deducted} of max ${p.cap}${p.at_cap ? ' (at its cap)' : ''}; ${p.findings ? `${p.findings} finding(s): ${sev}` : 'no findings'}.`);
161
+ for (const h of p.top || []) lineas.push(` ${h.severity} ${h.package ?? (h.file ? `${h.file}${h.line ? `:${h.line}` : ''}` : '')}: ${h.message}`);
162
+ if (p.findings > (p.top || []).length) lineas.push(` ... and ${p.findings - p.top.length} more`);
163
+ }
164
+ if (pr.aceptados?.length) lineas.push(`Accepted in .healer.json (do not deduct): ${pr.aceptados.map((a) => `${a.paquete ?? a.mensaje} (${a.motivo})`).join('; ')}.`);
165
+ }
166
+ const sug = r.pending_improvements || [];
167
+ if (sug.length) {
168
+ lineas.push(`Non-blocking suggestions (not applied): ${sug.length}.`);
169
+ for (const s of sug.slice(0, 10)) lineas.push(`- ${s.archivo}: ${String(s.diagnostico).slice(0, 300)}`);
170
+ if (sug.length > 10) lineas.push(`- ... and ${sug.length - 10} more (all of them are in the Healer panel).`);
171
+ }
233
172
  if (!cambiados.length) {
234
173
  lineas.push('No file changes to apply.');
235
174
  return lineas.join('\n');
@@ -361,6 +300,23 @@ async function info() {
361
300
  return lineas.join('\n');
362
301
  }
363
302
 
303
+ // 🧭 [2026-11-26] healer check y el hook antes de cada commit (ver ../check.mjs). healer_check sin completo no manda nada.
304
+ async function chequear({ ruta, archivos, completo }) {
305
+ const raiz = path.resolve(ruta || process.cwd());
306
+ if (completo === true) return (await revisarCompleto({ raiz })).texto;
307
+ const lista = Array.isArray(archivos) && archivos.length ? archivos.map(String) : null;
308
+ return textoLocal(await revisarLocal({ raiz, archivos: lista }), { archivos: lista });
309
+ }
310
+ async function hookDeCommit({ ruta, accion, bloquear, completo }) {
311
+ const raiz = path.resolve(ruta || process.cwd());
312
+ if (accion === 'on') return instalarHook(raiz, { bloquear: bloquear === true, completo: completo === true });
313
+ if (accion === 'off') return quitarHook(raiz);
314
+ const e = estadoHook(raiz);
315
+ if (e.error) return e.error;
316
+ if (e.externa) return `Hooks live in "${e.externa}" (husky or core.hooksPath): Healer does not manage them; add the healer line to its pre-commit file.`;
317
+ return e.activo ? `On: ${e.bloquea ? 'blocks the commit on errors' : 'warns, never blocks'}; full review after each commit: ${e.completo ? 'on' : 'off'}.` : 'Off.';
318
+ }
319
+
364
320
  const HERRAMIENTAS = [
365
321
  {
366
322
  name: 'healer_info',
@@ -384,6 +340,18 @@ const HERRAMIENTAS = [
384
340
  },
385
341
  run: revisar
386
342
  },
343
+ {
344
+ name: 'healer_check',
345
+ description: 'Check the project with Healer rules, locally and in seconds: nothing leaves this computer and no AI is used. The rules come from real bugs (hand-copied lists that fell behind, Express routes that shadow each other, ALTER before CREATE, INSERT OR REPLACE that wipes columns, dotenv imported late, a route without the check its siblings have). Pass archivos to see only what touches those files (for example, the files of a commit). completo: true sends the project to Healer for a full review without AI (Pentagon, Semgrep, tests); it is skipped when Healer already watches the repo.',
346
+ inputSchema: { type: 'object', properties: { ruta: { type: 'string', description: 'Project folder. Defaults to the current working directory.' }, archivos: { type: 'array', items: { type: 'string' }, description: 'Optional: only findings in these files (paths relative to the project).' }, completo: { type: 'boolean', description: 'Full review in Healer without AI. Only when the user asks for it.' } } },
347
+ run: chequear
348
+ },
349
+ {
350
+ name: 'healer_hook',
351
+ description: 'Turn on or off the Healer check before every commit in this repo (a git hook), or see its state. Only when the user asks. On: it warns and never blocks, unless bloquear is true (blocks on errors in the files of the commit). completo: true also sends a full review without AI after each commit, in the background, except when Healer already watches the repo (no double runs). If the repo keeps its hooks elsewhere (husky), it says what line to add instead of touching team files.',
352
+ inputSchema: { type: 'object', properties: { ruta: { type: 'string', description: 'Project folder. Defaults to the current working directory.' }, accion: { type: 'string', enum: ['on', 'off', 'status'] }, bloquear: { type: 'boolean' }, completo: { type: 'boolean' } }, required: ['accion'] },
353
+ run: hookDeCommit
354
+ },
387
355
  {
388
356
  name: 'healer_resultado',
389
357
  description: 'Check a Healer job. Waits up to ~45 s; if it is still running, call it again. When finished, returns the summary and the diff of the proposed changes, without writing anything.',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@meiti/healer",
3
- "version": "0.4.0",
3
+ "version": "0.7.0",
4
4
  "description": "Connect Healer to Claude Code (and any MCP agent) in a minute: a short code, one click in the browser, done.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -11,6 +11,9 @@
11
11
  "instalar.mjs",
12
12
  "healer-mcp.mjs",
13
13
  "mcp/servidor.mjs",
14
+ "mcp/proyecto.mjs",
15
+ "check.mjs",
16
+ "reglas.mjs",
14
17
  "README.md",
15
18
  "LICENSE"
16
19
  ],
@@ -32,6 +35,6 @@
32
35
  ],
33
36
  "license": "MIT",
34
37
  "scripts": {
35
- "prepack": "node -e \"require('fs').mkdirSync('mcp',{recursive:true});require('fs').copyFileSync('../claude-code/plugins/healer-local/mcp/servidor.mjs','mcp/servidor.mjs')\""
38
+ "prepack": "node -e \"const fs=require('fs');fs.mkdirSync('mcp',{recursive:true});for(const f of ['mcp/servidor.mjs','mcp/proyecto.mjs','check.mjs','reglas.mjs'])fs.copyFileSync('../claude-code/plugins/healer-local/'+f,f)\""
36
39
  }
37
40
  }