@meiti/healer 0.7.0 → 0.7.2

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/check.mjs CHANGED
@@ -15,7 +15,7 @@ import path from 'node:path';
15
15
  import { rutasDelProyecto, archivosDelProyecto, resumenOmitidos } from './mcp/proyecto.mjs';
16
16
 
17
17
  const API = (process.env.HEALER_API_URL || 'https://healer-api.meiti.dev').replace(/\/$/, '');
18
- const VERSION = '0.7.0';
18
+ const VERSION = '0.7.1';
19
19
  const es = /^es/i.test(process.env.HEALER_LANG || Intl.DateTimeFormat().resolvedOptions().locale || '');
20
20
  const tx = (en, esp) => (es ? esp : en);
21
21
 
@@ -188,9 +188,17 @@ export async function instalarHook(raiz, { bloquear = false, completo = false }
188
188
  fs.mkdirSync(c.carpeta, { recursive: true });
189
189
  const escribir = (nombre, bloque) => {
190
190
  const ruta = path.join(c.carpeta, nombre);
191
- let actual = '';
191
+ let actual = null;
192
192
  try { actual = fs.readFileSync(ruta, 'utf8'); } catch { /* no había */ }
193
- fs.writeFileSync(ruta, bloque ? conBloque(actual, bloque) : sinBloque(actual));
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));
194
202
  try { fs.chmodSync(ruta, 0o755); } catch { /* Windows: git for Windows lo corre igual */ }
195
203
  };
196
204
  escribir('pre-commit', bloquePreCommit({ bloquear }));
package/mcp/servidor.mjs CHANGED
@@ -16,10 +16,35 @@ import readline from 'node:readline';
16
16
  import { archivosDelProyecto, resumenOmitidos } from './proyecto.mjs';
17
17
  import { revisarLocal, textoLocal, revisarCompleto, instalarHook, quitarHook, estadoHook } from '../check.mjs';
18
18
 
19
- const VERSION = '0.8.0';
19
+ const VERSION = '0.8.2';
20
20
  const API = (process.env.HEALER_API_URL || 'https://healer-api.meiti.dev').replace(/\/$/, '');
21
21
  const leerClave = () => String(process.env.CLAUDE_PLUGIN_OPTION_API_KEY || '').trim();
22
- const ESTADO = path.join(os.tmpdir(), 'healer-claude-code');
22
+ // 🔒 [2026-11-26, sugerencia de la vigilancia de Healer] El estado de cada trabajo (la carpeta del proyecto y lo propuesto) decide dónde
23
+ // escribe healer_aplicar. Antes vivía en una carpeta temporal compartida y con permisos por defecto: en una máquina con varios
24
+ // usuarios, otro podía plantar un JSON y hacer escribir archivos donde quisiera. Ahora la carpeta es de este usuario (0700), cada
25
+ // archivo es 0600, y en Linux/macOS no se confía en una carpeta o un archivo que sea de otro dueño.
26
+ const usuarioDelSistema = (() => { try { return os.userInfo().username.replace(/[^\w.-]/g, '_') || 'usuario'; } catch { return 'usuario'; } })();
27
+ const ESTADO = path.join(os.tmpdir(), `healer-claude-code-${usuarioDelSistema}`);
28
+ const esMio = (ruta) => {
29
+ if (typeof process.getuid !== 'function') return true; // Windows: la carpeta temporal ya es del usuario
30
+ const s = fs.statSync(ruta);
31
+ return s.uid === process.getuid();
32
+ };
33
+ function prepararEstado() {
34
+ fs.mkdirSync(ESTADO, { recursive: true, mode: 0o700 });
35
+ if (!esMio(ESTADO)) throw new Error(`The state folder ${ESTADO} belongs to another user: remove it and try again.`);
36
+ try { fs.chmodSync(ESTADO, 0o700); } catch { /* Windows */ }
37
+ }
38
+ function leerEstado(jobId) {
39
+ const a = archivoDeTrabajo(jobId);
40
+ if (!fs.existsSync(a)) return null;
41
+ if (!esMio(ESTADO) || !esMio(a)) throw new Error(`The stored state of job ${jobId} belongs to another user: it is not used.`);
42
+ return JSON.parse(fs.readFileSync(a, 'utf8'));
43
+ }
44
+ function guardarEstado(jobId, datos) {
45
+ prepararEstado();
46
+ fs.writeFileSync(archivoDeTrabajo(jobId), JSON.stringify(datos), { mode: 0o600 });
47
+ }
23
48
 
24
49
  const sha256 = (texto) => crypto.createHash('sha256').update(texto, 'utf8').digest('hex');
25
50
 
@@ -45,7 +70,18 @@ async function revisar({ ruta, nivel, tests, confirmar_free, solo_revisar, bug }
45
70
  if (!fs.existsSync(raiz) || !fs.statSync(raiz).isDirectory()) throw new Error(`Folder not found: ${raiz}.`);
46
71
  const { files, binary_files, total, omitidos_lista } = archivosDelProyecto(raiz);
47
72
  if (!Object.keys(files).length) throw new Error('No text files to send were found in that folder.');
48
- if (Array.isArray(tests) && tests.length && !files['.healer.json']) files['.healer.json'] = JSON.stringify({ tests }, null, 2);
73
+ // 🧪 [2026-11-26, sugerencia de la vigilancia de Healer] Si el proyecto ya tenía .healer.json, los tests pedidos se descartaban en
74
+ // silencio y Healer corría la suite completa. Ahora se suman a ese archivo (solo en lo que se manda, el del proyecto no cambia).
75
+ let avisoTests = '';
76
+ if (Array.isArray(tests) && tests.length) {
77
+ if (!files['.healer.json']) files['.healer.json'] = JSON.stringify({ tests }, null, 2);
78
+ else {
79
+ let config;
80
+ try { config = JSON.parse(files['.healer.json']); } catch { throw new Error('.healer.json is not valid JSON, so the tests you asked for cannot be added to it. Fix it, or send without tests.'); }
81
+ files['.healer.json'] = JSON.stringify({ ...config, tests }, null, 2);
82
+ avisoTests = `For this run, the tests you asked for replace the "tests" of .healer.json${Array.isArray(config.tests) && config.tests.length ? ` (${config.tests.join(', ')})` : ''}; the file in the project is not changed.`;
83
+ }
84
+ }
49
85
  const appId = `claude-code/${path.basename(raiz).replace(/[^\w.-]/g, '-').slice(0, 60) || 'proyecto'}`;
50
86
  // 🔐 [2026-11-16] Sin nivel propio (antes free por defecto): vale la política de la organización (pro salvo que el dueño cambie).
51
87
  // Si tocaría free y la organización pide preguntar, Healer responde 409 y no se encola nada.
@@ -56,9 +92,9 @@ async function revisar({ ruta, nivel, tests, confirmar_free, solo_revisar, bug }
56
92
  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' : ''}.`;
57
93
  throw e;
58
94
  }
59
- fs.mkdirSync(ESTADO, { recursive: true });
60
- fs.writeFileSync(archivoDeTrabajo(envio.job_id), JSON.stringify({ raiz, appId, enviado: new Date().toISOString() }));
95
+ guardarEstado(envio.job_id, { raiz, appId, enviado: new Date().toISOString() });
61
96
  return [
97
+ ...(avisoTests ? [avisoTests] : []),
62
98
  `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}` : ''}).`,
63
99
  `${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)}` : ''}`,
64
100
  'Healer runs the tests in an isolated sandbox and repairs what fails. It usually takes a few minutes: check with healer_resultado.'
@@ -104,7 +140,10 @@ function informePantalla(r) {
104
140
  }
105
141
 
106
142
  async function resultado({ job_id, esperar_segundos }) {
107
- const limite = Date.now() + Math.min(Math.max(Number(esperar_segundos) || 45, 0), 50) * 1000;
143
+ // ⏱️ [2026-11-26, sugerencia de la vigilancia de Healer] `Number(0) || 45` convertía un 0 pedido en 45 s: no había forma de
144
+ // consultar sin esperar. Sin valor (o con uno inválido) siguen siendo 45 s.
145
+ const pedido = esperar_segundos === undefined || esperar_segundos === null || esperar_segundos === '' ? NaN : Number(esperar_segundos);
146
+ const limite = Date.now() + Math.min(Math.max(Number.isFinite(pedido) ? pedido : 45, 0), 50) * 1000;
108
147
  let r;
109
148
  for (;;) {
110
149
  r = await api('GET', `/v1/repair/${encodeURIComponent(job_id)}`);
@@ -117,10 +156,10 @@ async function resultado({ job_id, esperar_segundos }) {
117
156
  if (r.status === 'error') return `Healer could not finish: ${r.error || 'unknown error'}.`;
118
157
  if (r.tipo === 'pantalla') return informePantalla(r);
119
158
 
120
- const meta = fs.existsSync(archivoDeTrabajo(job_id)) ? JSON.parse(fs.readFileSync(archivoDeTrabajo(job_id), 'utf8')) : null;
159
+ const meta = leerEstado(job_id);
121
160
  const cambiados = r.changed_files || [];
122
161
  // La propuesta queda guardada para healer_aplicar (y para mirarla con calma).
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]])) }));
162
+ if (meta) guardarEstado(job_id, ({ ...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]])) }));
124
163
 
125
164
  const lineas = [];
126
165
  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;
@@ -235,9 +274,8 @@ function diffDe(antes, despues) {
235
274
  }
236
275
 
237
276
  async function aplicar({ job_id, archivos, acepto_puntaje_menor }) {
238
- const archivo = archivoDeTrabajo(job_id);
239
- if (!fs.existsSync(archivo)) throw new Error('No proposal stored for that job: call healer_resultado first.');
240
- const t = JSON.parse(fs.readFileSync(archivo, 'utf8'));
277
+ const t = leerEstado(job_id);
278
+ if (!t) throw new Error('No proposal stored for that job: call healer_resultado first.');
241
279
  if (!t.changed_files?.length) return 'That job has no changes to apply.';
242
280
  // Solo lo que el usuario aprobó (si mandó "archivos"); un nombre que Healer no cambió frena todo.
243
281
  const pedidos = Array.isArray(archivos) && archivos.length ? archivos.map(String) : null;
@@ -258,14 +296,19 @@ async function aplicar({ job_id, archivos, acepto_puntaje_menor }) {
258
296
  return t.base_hashes[ruta] && (actual === null || sha256(actual) !== t.base_hashes[ruta]);
259
297
  });
260
298
  if (distintos.length) return `Not applied: these files changed since they were sent to Healer: ${distintos.join(', ')}. Send the project again with healer_revisar.`;
299
+ // 🧱 [2026-11-26, sugerencia de la vigilancia de Healer] Todo o nada: antes una ruta fuera del proyecto frenaba a mitad de camino,
300
+ // con los archivos anteriores ya escritos, y un archivo sin contenido se saltaba pero se informaba como aplicado. Ahora se revisa
301
+ // todo antes de escribir el primero.
302
+ const fuera = elegidos.filter((ruta) => !path.resolve(t.raiz, ruta).startsWith(t.raiz + path.sep));
303
+ if (fuera.length) throw new Error(`Nothing was written: path(s) outside the project: ${fuera.join(', ')}.`);
304
+ const sinContenido = elegidos.filter((ruta) => typeof t.files?.[ruta] !== 'string');
305
+ if (sinContenido.length) throw new Error(`Nothing was written: the stored proposal has no content for ${sinContenido.join(', ')}. Call healer_resultado again.`);
261
306
  for (const ruta of elegidos) {
262
307
  const destino = path.resolve(t.raiz, ruta);
263
- if (!destino.startsWith(t.raiz + path.sep)) throw new Error(`Path outside the project: ${ruta}`);
264
- if (typeof t.files[ruta] !== 'string') continue;
265
308
  fs.mkdirSync(path.dirname(destino), { recursive: true });
266
309
  fs.writeFileSync(destino, t.files[ruta]);
267
310
  }
268
- fs.writeFileSync(archivo, JSON.stringify({ ...t, aplicado: new Date().toISOString(), aplicados: elegidos }));
311
+ guardarEstado(job_id, { ...t, aplicado: new Date().toISOString(), aplicados: elegidos });
269
312
  const descartados = t.changed_files.filter((c) => !elegidos.includes(c));
270
313
  // Le cuenta a Healer qué se aplicó y qué no (solo para medir qué cambios valen la pena; si falla, no importa).
271
314
  await api('POST', `/v1/repair/${encodeURIComponent(job_id)}/decision`, { aplicados: elegidos, descartados, via: 'plugin_local' }).catch(() => {});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@meiti/healer",
3
- "version": "0.7.0",
3
+ "version": "0.7.2",
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": {