nexakit 0.12.1 → 0.13.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.
Files changed (81) hide show
  1. package/README.md +9 -5
  2. package/assets/runtime/package-lock.json +2 -2
  3. package/dist/fabrica/banco/ejecutar.js +16 -8
  4. package/dist/fabrica/cli.js +269 -25
  5. package/dist/fabrica/conectores/antigravity.js +511 -12
  6. package/dist/fabrica/conectores/codex.js +400 -18
  7. package/dist/fabrica/consolidar.js +64 -27
  8. package/dist/fabrica/decision.js +43 -21
  9. package/dist/fabrica/disco.js +220 -9
  10. package/dist/fabrica/ejecutor.js +138 -75
  11. package/dist/fabrica/encargo/candado.js +274 -0
  12. package/dist/fabrica/encargo/ejecutar.js +827 -0
  13. package/dist/fabrica/encargo/evidencia.js +308 -0
  14. package/dist/fabrica/encargo/parche.js +146 -0
  15. package/dist/fabrica/encargo/worktree.js +394 -0
  16. package/dist/fabrica/enrutador.js +76 -27
  17. package/dist/fabrica/esquemas.js +8 -1
  18. package/dist/fabrica/evidencia.js +6 -3
  19. package/dist/fabrica/jsonrpc.js +53 -5
  20. package/dist/fabrica/mcp.js +147 -12
  21. package/dist/fabrica/preferencias.js +56 -0
  22. package/dist/fabrica/rastro.js +70 -14
  23. package/dist/fabrica/sesion.js +7 -3
  24. package/dist/fabrica/tabla-modelos.json +4 -2
  25. package/dist/fabrica/veredictos.js +15 -11
  26. package/package.json +1 -1
  27. package/plugins/huellas.json +4 -4
  28. package/plugins/nexakit-modelo/.claude-plugin/plugin.json +1 -1
  29. package/plugins/nexakit-modelo/hooks/barra.js +22 -1
  30. package/plugins/nexakit-modelo/hooks/decidir.js +2 -2
  31. package/plugins/nexakit-modelo/hooks/register.js +94 -6
  32. package/plugins/nexakit-modelo/tests/register.test.ts +253 -0
  33. package/plugins/niveles/.claude-plugin/plugin.json +1 -1
  34. package/plugins/niveles/agents/cazador-de-flakes.md +1 -0
  35. package/plugins/niveles/agents/cierre-de-memoria.md +1 -0
  36. package/plugins/niveles/agents/investigador.md +1 -0
  37. package/plugins/niveles/agents/nivel-alto.md +1 -0
  38. package/plugins/niveles/agents/nivel-exigente.md +1 -0
  39. package/plugins/niveles/agents/nivel-ligero.md +1 -0
  40. package/plugins/niveles/agents/nivel-normal.md +1 -0
  41. package/plugins/niveles/agents/revisor-de-calidad.md +1 -0
  42. package/plugins/niveles/agents/sincronizador-docs.md +1 -0
  43. package/plugins/niveles/agents/subir-al-repo.md +1 -0
  44. package/skills/elegir-modelo/SKILL.md +3 -3
  45. package/skills/elegir-modelo/modelos.mjs +1 -1
  46. package/skills/fabrica/SKILL.md +27 -8
  47. package/src/agent-models.js +1 -1
  48. package/src/antigravity-recommendation.js +14 -7
  49. package/src/codex-team.js +2 -1
  50. package/src/fabrica/banco/ejecutar.ts +20 -10
  51. package/src/fabrica/cli.ts +257 -24
  52. package/src/fabrica/conectores/antigravity.ts +508 -12
  53. package/src/fabrica/conectores/codex.ts +410 -17
  54. package/src/fabrica/conectores/tipos.ts +4 -0
  55. package/src/fabrica/consolidar.ts +92 -33
  56. package/src/fabrica/decision.ts +50 -22
  57. package/src/fabrica/disco.ts +237 -10
  58. package/src/fabrica/ejecutor.ts +144 -69
  59. package/src/fabrica/encargo/candado.ts +287 -0
  60. package/src/fabrica/encargo/ejecutar.ts +953 -0
  61. package/src/fabrica/encargo/evidencia.ts +301 -0
  62. package/src/fabrica/encargo/parche.ts +151 -0
  63. package/src/fabrica/encargo/worktree.ts +427 -0
  64. package/src/fabrica/enrutador.ts +71 -27
  65. package/src/fabrica/esquemas.ts +10 -1
  66. package/src/fabrica/evidencia.ts +7 -3
  67. package/src/fabrica/jsonrpc.ts +51 -5
  68. package/src/fabrica/mcp.ts +166 -12
  69. package/src/fabrica/preferencias.ts +66 -0
  70. package/src/fabrica/rastro.ts +69 -14
  71. package/src/fabrica/sesion.ts +7 -3
  72. package/src/fabrica/tabla-modelos.json +4 -2
  73. package/src/fabrica/veredictos.ts +18 -14
  74. package/src/gemini-tools.js +1 -1
  75. package/src/level-agents.js +2 -0
  76. package/src/model-command.d.ts +29 -0
  77. package/src/model-command.js +2 -2
  78. package/src/regla-ordenes-simples.d.ts +2 -0
  79. package/src/regla-ordenes-simples.js +4 -0
  80. package/src/review-instructions.js +39 -10
  81. package/src/toolkit-cli.js +7 -3
@@ -0,0 +1,427 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { randomBytes } from 'node:crypto';
3
+ import { chmod, lstat, mkdir, readdir, readFile, realpath, rm, symlink } from 'node:fs/promises';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { prefijoRepoTemporal } from '../banco/ejecutar.js';
7
+ import { ErrorFabrica } from '../errores.js';
8
+ import { carpetaPropia, codigoError, escribirReemplazando } from '../rastro.js';
9
+ import { procesoVivo } from './candado.js';
10
+
11
+ const MAX_BUFFER = 64 * 1024 * 1024;
12
+
13
+ /** Worktree aislado donde una IA programa un encargo. */
14
+ export interface Worktree {
15
+ /** Id aleatorio y neutro; es la carpeta de `~/.nexakit/encargos/`. */
16
+ id: string;
17
+ /** Carpeta del worktree: `~/.nexakit/encargos/<id>/repo`. */
18
+ dir: string;
19
+ /** Commit de HEAD del que parte el encargo. */
20
+ base: string;
21
+ /** Repo real del que sale el worktree (nunca se escribe en él). */
22
+ raiz: string;
23
+ /** Gitdir real del worktree (`<repo>/.git/worktrees/<nombre>`), fijado al crearlo: el `.git` del worktree no es de fiar. */
24
+ gitDir: string;
25
+ /** Lo que conviene saber (por ejemplo, cambios sin commit que no se copian). */
26
+ avisos: string[];
27
+ }
28
+
29
+ /** Variables de git que cambian dónde opera o cómo se configura: no se heredan. */
30
+ const VARIABLES_GIT = [
31
+ 'GIT_DIR',
32
+ 'GIT_INDEX_FILE',
33
+ 'GIT_WORK_TREE',
34
+ 'GIT_OBJECT_DIRECTORY',
35
+ 'GIT_ALTERNATE_OBJECT_DIRECTORIES',
36
+ 'GIT_COMMON_DIR',
37
+ 'GIT_NAMESPACE',
38
+ 'GIT_PREFIX',
39
+ ];
40
+
41
+ function entornoSaneado(): NodeJS.ProcessEnv {
42
+ const entorno: NodeJS.ProcessEnv = { ...process.env };
43
+ for (const clave of Object.keys(entorno)) {
44
+ if (VARIABLES_GIT.includes(clave.toUpperCase()) || clave.toUpperCase().startsWith('GIT_CONFIG')) delete entorno[clave];
45
+ }
46
+ // Sin escrituras opcionales (refrescar el índice, por ejemplo): un `git status` no debe tocar el repo real.
47
+ entorno['GIT_OPTIONAL_LOCKS'] = '0';
48
+ return entorno;
49
+ }
50
+
51
+ /** Ejecuta git con el entorno saneado y devuelve la salida cruda, sin decodificar. */
52
+ function gitBytes(cwd: string, args: string[]): Promise<Buffer> {
53
+ return new Promise((resolve, reject) => {
54
+ execFile(
55
+ 'git',
56
+ [
57
+ '-c',
58
+ 'core.quotepath=off',
59
+ '-c',
60
+ 'color.ui=false',
61
+ '-c',
62
+ 'core.autocrlf=false',
63
+ ...(process.platform === 'win32' ? ['-c', 'core.longpaths=true'] : []),
64
+ ...args,
65
+ ],
66
+ { cwd, encoding: 'buffer', maxBuffer: MAX_BUFFER, windowsHide: true, env: entornoSaneado() },
67
+ (error, stdout, stderr) => {
68
+ if (error) {
69
+ const codigo = (error as NodeJS.ErrnoException).code;
70
+ const motivo =
71
+ codigo === 'ENOENT'
72
+ ? 'no se encontró git en el PATH o la carpeta de trabajo no existe'
73
+ : codigo === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER'
74
+ ? `la salida supera el tope de ${MAX_BUFFER} bytes`
75
+ : stderr.toString('utf8').trim();
76
+ reject(new ErrorFabrica(`git ${args.find((a) => !a.startsWith('-')) ?? ''} falló: ${motivo}`, { cause: error }));
77
+ } else resolve(stdout);
78
+ },
79
+ );
80
+ });
81
+ }
82
+
83
+ const git = async (cwd: string, args: string[]): Promise<string> => (await gitBytes(cwd, args)).toString('utf8');
84
+
85
+ /**
86
+ * Argumentos para las órdenes que corren sobre el worktree, que controla la IA: se fija el gitdir y el árbol de
87
+ * trabajo (el archivo `.git` del worktree puede estar reescrito) y se apagan fsmonitor, hooks y la caché de no rastreados.
88
+ */
89
+ function argsSobreWorktree(w: Worktree, args: string[]): string[] {
90
+ return [
91
+ `--git-dir=${w.gitDir}`,
92
+ `--work-tree=${w.dir}`,
93
+ '-c',
94
+ 'core.fsmonitor=false',
95
+ '-c',
96
+ `core.hooksPath=${os.devNull}`,
97
+ '-c',
98
+ 'core.untrackedCache=false',
99
+ // Ni submódulos ni repos anidados: git entraría en ellos y aplicaría su configuración (filtros `clean` incluidos).
100
+ '-c',
101
+ 'diff.ignoreSubmodules=all',
102
+ '-c',
103
+ 'submodule.recurse=false',
104
+ ...args,
105
+ ];
106
+ }
107
+
108
+ const mensajeDe = (error: unknown): string => (error instanceof Error ? error.message : String(error));
109
+
110
+ const borrarCarpeta = (ruta: string): Promise<void> => rm(ruta, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
111
+
112
+ /**
113
+ * Enlaza `node_modules` del repo real en el worktree para que la IA pueda compilar y probar sin red.
114
+ * Solo si es una carpeta real (no un enlace) y git la tiene ignorada, también ya como enlace dentro del worktree: así no entra en el diff ni dispara el análisis
115
+ * de enlaces que salen del repo. Codex escribe con sandbox por ruta real (no puede tocar el `node_modules` real) y
116
+ * Antigravity veta componentes que sean enlaces. En macOS Codex solo puede leer de la carpeta personal el camino hasta la
117
+ * copia y este `node_modules` (ver `conectores/codex.ts`); en Linux y Windows su sandbox acota la escritura, no la
118
+ * lectura, y puede LEER todo el disco. Quien encarga revisa el diff y el resumen antes de aplicarlo o compartirlo.
119
+ * `borrarWorktree` borra el enlace sin seguirlo.
120
+ */
121
+ async function enlazarNodeModules(raiz: string, dir: string): Promise<void> {
122
+ const origen = path.join(raiz, 'node_modules');
123
+ const info = await lstat(origen).catch(() => null);
124
+ if (info === null || !info.isDirectory() || info.isSymbolicLink()) return;
125
+ try {
126
+ await git(raiz, ['check-ignore', '-q', 'node_modules']);
127
+ } catch {
128
+ return;
129
+ }
130
+ const enlace = path.join(dir, 'node_modules');
131
+ await symlink(origen, enlace, process.platform === 'win32' ? 'junction' : 'dir');
132
+ // Un patrón `node_modules/` (solo carpetas) ignora la carpeta real pero no el enlace, que entraría en el diff: se quita.
133
+ // (En Windows git ve la junction como carpeta y la ignora: `check-ignore` acierta y se queda, sin entrar en el diff.)
134
+ try {
135
+ await git(dir, ['check-ignore', '-q', 'node_modules']);
136
+ } catch {
137
+ await rm(enlace, { force: true });
138
+ }
139
+ }
140
+
141
+ export interface OpcionesCrearWorktree {
142
+ /** Solo para pruebas: se llama justo después de crear el worktree; si lanza, se prueba la limpieza. */
143
+ despuesDeCrear?: () => Promise<void>;
144
+ }
145
+
146
+ /**
147
+ * Crea un worktree desacoplado de HEAD en `~/.nexakit/encargos/<id>/repo` (carpetas `0o700`, sin seguir enlaces).
148
+ * El encargo parte de HEAD: si el árbol de la persona tiene cambios sin commit, se avisa y no se copian.
149
+ */
150
+ export async function crearWorktree(raiz: string, home: string, opciones: OpcionesCrearWorktree = {}): Promise<Worktree> {
151
+ const base = (await git(raiz, ['rev-parse', '--verify', 'HEAD'])).trim();
152
+ const avisos: string[] = [];
153
+ if ((await git(raiz, ['status', '--porcelain', '-z'])).length > 0) {
154
+ avisos.push('El árbol tiene cambios sin commit: el encargo parte de HEAD y no los incluye.');
155
+ }
156
+
157
+ const nexakit = path.join(home, '.nexakit');
158
+ await mkdir(nexakit, { recursive: true, mode: 0o700 });
159
+ await carpetaPropia(nexakit, 'Los encargos');
160
+ const encargos = path.join(nexakit, 'encargos');
161
+ await carpetaPropia(encargos, 'Los encargos');
162
+
163
+ for (let intento = 0; intento < 16; intento += 1) {
164
+ const id = `${prefijoRepoTemporal()}${randomBytes(3).toString('hex')}`;
165
+ const carpeta = path.join(encargos, id);
166
+ try {
167
+ await mkdir(carpeta, { mode: 0o700 });
168
+ } catch (error) {
169
+ if (codigoError(error) === 'EEXIST') continue;
170
+ throw error;
171
+ }
172
+ await chmod(carpeta, 0o700);
173
+ const dir = path.join(carpeta, 'repo');
174
+ try {
175
+ // El candado dice de quién es el encargo: si ese proceso muere, el barrido de huérfanos puede borrar el worktree.
176
+ await escribirReemplazando(path.join(carpeta, CANDADO), `${JSON.stringify({ pid: process.pid, raiz })}\n`);
177
+ // Sin hooks: el `post-checkout` del repo real correría sobre él antes de la comprobación del disco.
178
+ await git(raiz, ['-c', `core.hooksPath=${os.devNull}`, 'worktree', 'add', '--detach', '--quiet', '--', dir, base]);
179
+ await chmod(dir, 0o700);
180
+ await enlazarNodeModules(raiz, dir);
181
+ await opciones.despuesDeCrear?.();
182
+ // Ahora el `.git` del worktree es el que escribió git: se guarda su gitdir real, que no volverá a leerse de ahí.
183
+ const gitDir = path.resolve(dir, (await git(dir, ['rev-parse', '--absolute-git-dir'])).trim());
184
+ return { id, dir, base, raiz, gitDir, avisos };
185
+ } catch (error) {
186
+ // Primero se quita el worktree y su carpeta; `prune` va al final para no dejar ninguna entrada en `.git/worktrees`.
187
+ await git(raiz, ['worktree', 'remove', '--force', dir]).catch(() => {});
188
+ await borrarCarpeta(carpeta).catch(() => {});
189
+ await git(raiz, ['worktree', 'prune']).catch(() => {});
190
+ throw error;
191
+ }
192
+ }
193
+ throw new ErrorFabrica('No se pudo reservar un id libre para el encargo');
194
+ }
195
+
196
+ /** Tope de entradas que recorre `buscarGitAnidado`: más allá, el encargo no se comprueba y se rechaza. */
197
+ const MAX_ENTRADAS_RECORRIDO = 1_000_000;
198
+
199
+ /** `.git` también con otra caja, puntos o espacios finales (Windows) o el nombre corto de NTFS. */
200
+ const esNombreGit = (nombre: string): boolean => {
201
+ const normal = nombre.toLowerCase().replace(/[. ]+$/u, '');
202
+ return normal === '.git' || normal === 'git~1';
203
+ };
204
+
205
+ /**
206
+ * Primer `.git` anidado (carpeta, archivo o enlace) dentro del worktree, como ruta relativa con `/`, o `null`. Recorre con
207
+ * el tipo de `readdir` (sin seguir enlaces) y salta solo el `.git` de la raíz. Hay que llamarla antes de cualquier orden
208
+ * git sobre el worktree tras el turno: git entraría en un repo anidado y ejecutaría los filtros de su configuración,
209
+ * fuera de todo sandbox. Lanza si no puede leer una carpeta o si hay demasiadas entradas.
210
+ */
211
+ export async function buscarGitAnidado(dir: string): Promise<string | null> {
212
+ const pendientes: string[] = [''];
213
+ let vistas = 0;
214
+ while (pendientes.length > 0) {
215
+ const relativa = pendientes.pop() as string;
216
+ const entradas = await readdir(relativa === '' ? dir : path.join(dir, ...relativa.split('/')), { withFileTypes: true });
217
+ for (const entrada of entradas) {
218
+ vistas += 1;
219
+ if (vistas > MAX_ENTRADAS_RECORRIDO) throw new ErrorFabrica(`la copia tiene más de ${MAX_ENTRADAS_RECORRIDO} entradas`);
220
+ const ruta = relativa === '' ? entrada.name : `${relativa}/${entrada.name}`;
221
+ if (esNombreGit(entrada.name)) {
222
+ if (relativa === '' && entrada.name === '.git') continue;
223
+ return ruta;
224
+ }
225
+ // Los enlaces (también el de `node_modules`) no se siguen.
226
+ if (entrada.isDirectory() && !entrada.isSymbolicLink()) pendientes.push(ruta);
227
+ }
228
+ }
229
+ return null;
230
+ }
231
+
232
+ /**
233
+ * Diff del worktree contra su base, con los archivos nuevos (`git add -N`) y los binarios (`--binary`), listo para
234
+ * `git apply`, sin renombrados ni submódulos. Se devuelve como bytes: un archivo que no está en UTF-8 se corrompería al
235
+ * decodificarlo. Vacío si no hubo cambios. Antes hay que descartar los repos anidados con `buscarGitAnidado`.
236
+ */
237
+ export async function diffDelWorktree(w: Worktree): Promise<Buffer> {
238
+ try {
239
+ await gitBytes(w.dir, argsSobreWorktree(w, ['add', '-N', '--all', '--', '.']));
240
+ return await gitBytes(
241
+ w.dir,
242
+ argsSobreWorktree(w, [
243
+ 'diff',
244
+ '--binary',
245
+ '--no-renames',
246
+ '--no-relative',
247
+ '--ignore-submodules=all',
248
+ '--no-ext-diff',
249
+ '--no-textconv',
250
+ '--no-color',
251
+ '--src-prefix=a/',
252
+ '--dst-prefix=b/',
253
+ w.base,
254
+ '--',
255
+ ]),
256
+ );
257
+ } catch (error) {
258
+ throw new ErrorFabrica(`No se pudo leer el diff del encargo: ${mensajeDe(error)}`, { cause: error });
259
+ }
260
+ }
261
+
262
+ /** Un cambio del worktree respecto de su base. */
263
+ export interface CambioWorktree {
264
+ /** Ruta relativa, con `/`. */
265
+ ruta: string;
266
+ /** Modo del archivo ya cambiado (`120000` es un enlace simbólico; `000000`, un borrado). */
267
+ modo: string;
268
+ }
269
+
270
+ /**
271
+ * Cambios del worktree contra su base (`git diff --raw -z --no-renames`), con la ruta y el modo nuevo de cada uno, sin
272
+ * decodificar nombres raros. Debe llamarse después de `diffDelWorktree`, que registra los archivos nuevos. El encargo no
273
+ * la usa: analiza el propio parche guardado (`analizarParche`), que no puede cambiar entre el diff y la comprobación.
274
+ */
275
+ export async function cambiosDelWorktree(w: Worktree): Promise<CambioWorktree[]> {
276
+ let crudo: string;
277
+ try {
278
+ crudo = (
279
+ await gitBytes(w.dir, argsSobreWorktree(w, ['diff', '--raw', '-z', '--no-renames', '--no-relative', '--ignore-submodules=all', '--no-ext-diff', '--no-textconv', w.base, '--']))
280
+ ).toString('utf8');
281
+ } catch (error) {
282
+ throw new ErrorFabrica(`No se pudo analizar el diff del encargo: ${mensajeDe(error)}`, { cause: error });
283
+ }
284
+ // Formato: `:<modo previo> <modo nuevo> <sha previo> <sha nuevo> <estado>\0<ruta>\0` por cambio.
285
+ const partes = crudo.split('\0');
286
+ const cambios: CambioWorktree[] = [];
287
+ for (let i = 0; i + 1 < partes.length; i += 2) {
288
+ const meta = /^:\d+ (\d+) /u.exec(partes[i] ?? '');
289
+ const ruta = partes[i + 1];
290
+ if (meta?.[1] === undefined || ruta === undefined || ruta === '') continue;
291
+ cambios.push({ ruta, modo: meta[1] });
292
+ }
293
+ return cambios;
294
+ }
295
+
296
+ /**
297
+ * Raíz del repo que contiene `cwd` (`git rev-parse --show-toplevel`, con el entorno saneado). Lanza si `cwd` no está
298
+ * en un repo de git.
299
+ */
300
+ export async function raizDelRepoGit(cwd: string): Promise<string> {
301
+ const raiz = (await git(cwd, ['rev-parse', '--show-toplevel'])).trim();
302
+ if (raiz === '') throw new ErrorFabrica('No se pudo averiguar la raíz del repo');
303
+ return path.resolve(raiz);
304
+ }
305
+
306
+ /**
307
+ * Quita el worktree y limpia el registro de git. Nunca lanza: si algo falla, devuelve el aviso (y `null` si todo fue bien).
308
+ * No ejecuta git sobre el worktree (que controla la IA y puede traer un repo anidado): borra la carpeta sin seguir enlaces
309
+ * y después `git worktree prune` en el repo real limpia su entrada de `.git/worktrees`.
310
+ */
311
+ export async function borrarWorktree(w: Worktree): Promise<string | null> {
312
+ const fallos: string[] = [];
313
+ try {
314
+ await borrarCarpeta(w.dir);
315
+ } catch (error) {
316
+ fallos.push(mensajeDe(error));
317
+ }
318
+ try {
319
+ await git(w.raiz, ['worktree', 'prune']);
320
+ } catch (error) {
321
+ fallos.push(mensajeDe(error));
322
+ }
323
+ return fallos.length === 0 ? null : `No se pudo borrar bien el worktree ${w.dir} (${fallos.join('; ')}); revisa con «git worktree list» y bórralo a mano.`;
324
+ }
325
+
326
+ // ---------------------------------------------------------------------------------------------
327
+ // Huérfanos
328
+
329
+ const CANDADO = 'candado.json';
330
+ /** Una carpeta sin candado se respeta este tiempo: puede estar creándose ahora mismo en otro proceso. */
331
+ const GRACIA_SIN_CANDADO_MS = 5 * 60_000;
332
+
333
+ async function leerCandadoWorktree(carpeta: string): Promise<{ pid: number; raiz: string } | null> {
334
+ try {
335
+ const archivo = path.join(carpeta, CANDADO);
336
+ const info = await lstat(archivo);
337
+ if (!info.isFile()) return null;
338
+ const dato: unknown = JSON.parse(await readFile(archivo, 'utf8'));
339
+ if (typeof dato !== 'object' || dato === null) return null;
340
+ const { pid, raiz } = dato as { pid?: unknown; raiz?: unknown };
341
+ return typeof pid === 'number' && typeof raiz === 'string' ? { pid, raiz } : null;
342
+ } catch {
343
+ return null;
344
+ }
345
+ }
346
+
347
+ /**
348
+ * Clave para comparar rutas. En Windows git imprime `C:/Users/...` (barras normales) y la ruta real viene con `\` y quizá con
349
+ * otra caja de letras, así que ahí se igualan separadores y caja; en POSIX la ruta se compara tal cual.
350
+ */
351
+ function claveDeRuta(ruta: string): string {
352
+ const sinFinal = ruta.replace(/\r$/u, '');
353
+ if (process.platform !== 'win32') return sinFinal;
354
+ return sinFinal.replace(/\\/gu, '/').replace(/\/+$/u, '').toLowerCase();
355
+ }
356
+
357
+ /** `true` si el repo `raiz` tiene registrado `dir` como worktree (`git worktree list`); solo entonces se ejecuta `remove` o `prune`. */
358
+ async function worktreeRegistrado(raiz: string, dir: string): Promise<boolean> {
359
+ try {
360
+ const listado = (await git(raiz, ['worktree', 'list', '--porcelain'])).split('\n');
361
+ const buscados = new Set([claveDeRuta(dir), claveDeRuta(await realpath(dir).catch(() => dir))]);
362
+ return listado.some((l) => l.startsWith('worktree ') && buscados.has(claveDeRuta(l.slice('worktree '.length))));
363
+ } catch {
364
+ return false;
365
+ }
366
+ }
367
+
368
+ /**
369
+ * Borra los worktrees que dejó un encargo muerto (un proceso que cayó sin limpiar): carpetas
370
+ * `~/.nexakit/encargos/<id>/repo` cuyo candado ya no tiene un proceso vivo. Solo toca carpetas reales dentro de
371
+ * `~/.nexakit/encargos/`, nunca sigue enlaces y conserva `informe.json` y `cambios.diff`. Nunca lanza; devuelve un
372
+ * aviso por cada worktree borrado o que no se pudo borrar.
373
+ */
374
+ export async function barrerHuerfanos(home: string, ahora: number = Date.now()): Promise<string[]> {
375
+ const avisos: string[] = [];
376
+ const nexakit = path.join(home, '.nexakit');
377
+ const encargos = path.join(nexakit, 'encargos');
378
+ let nombres: string[];
379
+ try {
380
+ // Ni `~/.nexakit` ni `encargos` pueden ser enlaces: el barrido no sale de la carpeta propia.
381
+ const raizNexakit = await lstat(nexakit);
382
+ if (!raizNexakit.isDirectory() || raizNexakit.isSymbolicLink()) return avisos;
383
+ const info = await lstat(encargos);
384
+ if (!info.isDirectory() || info.isSymbolicLink()) return avisos;
385
+ nombres = await readdir(encargos);
386
+ } catch {
387
+ return avisos;
388
+ }
389
+ for (const nombre of nombres) {
390
+ try {
391
+ const carpeta = path.join(encargos, nombre);
392
+ const info = await lstat(carpeta);
393
+ if (!info.isDirectory() || info.isSymbolicLink()) continue;
394
+ const repo = await lstat(path.join(carpeta, 'repo')).catch(() => null);
395
+ // Un `repo` que sea un enlace u otra cosa no se toca: solo se borra un worktree real.
396
+ if (repo === null || !repo.isDirectory() || repo.isSymbolicLink()) continue;
397
+ const candado = await leerCandadoWorktree(carpeta);
398
+ if (candado === null ? ahora - info.mtimeMs < GRACIA_SIN_CANDADO_MS : procesoVivo(candado.pid)) continue;
399
+ const aviso = await quitarWorktreeDeCarpeta(carpeta, nombre);
400
+ if (aviso !== undefined) avisos.push(aviso ?? `Se borró el worktree huérfano de un encargo anterior (${nombre}).`);
401
+ } catch (error) {
402
+ avisos.push(`No se pudo revisar la carpeta de encargo ${nombre}: ${mensajeDe(error)}`);
403
+ }
404
+ }
405
+ return avisos;
406
+ }
407
+
408
+ /**
409
+ * Quita el worktree `repo` (y la carpeta `tmp`) de una carpeta de encargo cuyo proceso ya no vive. Solo ejecuta git en
410
+ * la raíz del candado si ese repo tiene registrado el worktree; si no, solo borra la carpeta (ejecutar git en otro repo
411
+ * lo tocaría sin motivo). Devuelve `undefined` si no había worktree real, `null` si se borró bien y el aviso si no.
412
+ * Lanza si el proceso del candado sigue vivo.
413
+ */
414
+ export async function quitarWorktreeDeCarpeta(carpeta: string, nombre: string = path.basename(carpeta)): Promise<string | null | undefined> {
415
+ const candado = await leerCandadoWorktree(carpeta);
416
+ if (candado !== null && procesoVivo(candado.pid)) throw new ErrorFabrica(`el encargo ${nombre} sigue en curso (proceso ${candado.pid})`);
417
+ await borrarCarpeta(path.join(carpeta, 'tmp')).catch(() => {});
418
+ const dir = path.join(carpeta, 'repo');
419
+ const repo = await lstat(dir).catch(() => null);
420
+ if (repo === null || !repo.isDirectory() || repo.isSymbolicLink()) return undefined;
421
+ const raizRepo = candado?.raiz;
422
+ if (raizRepo !== undefined && path.isAbsolute(raizRepo) && (await worktreeRegistrado(raizRepo, dir))) {
423
+ return borrarWorktree({ id: nombre, dir, base: '', raiz: raizRepo, gitDir: '', avisos: [] });
424
+ }
425
+ await borrarCarpeta(dir);
426
+ return null;
427
+ }
@@ -6,7 +6,8 @@ import { clasificar, leerDiff, type Categoria } from './diff.js';
6
6
  import { ErrorFabrica } from './errores.js';
7
7
  import { caducada, cargar, type Evidencia } from './evidencia.js';
8
8
  import { ESTACIONES, TABLA_MODELOS_INICIAL } from './estaciones.js';
9
- import { NOMBRES_ESTACION, type ConfigFabrica, type IA, type NombreEstacion } from './esquemas.js';
9
+ import { leerPreferencias } from './preferencias.js';
10
+ import { claveEstacion, IAExterna, NOMBRES_ESTACION, type ConfigFabrica, type IA, type NombreEstacion } from './esquemas.js';
10
11
 
11
12
  /** Catálogo vivo de una IA: modelos y esfuerzos que admite cada uno. */
12
13
  export type Catalogos = Partial<Record<IA, Array<{ modelo: string; esfuerzos: string[] }>>>;
@@ -15,6 +16,8 @@ export type EstadoEstacion = 'propuesta' | 'sin-modelo' | 'omitida';
15
16
 
16
17
  export interface EstacionRecorrido {
17
18
  estacion: NombreEstacion;
19
+ /** Identifica una ejecución adicional de código, incluso si se quita del recorrido. */
20
+ revisionDe?: IAExterna;
18
21
  ia: IA | null;
19
22
  modelo: string | null;
20
23
  esfuerzo: string | null;
@@ -116,8 +119,10 @@ function clave(c: Candidato): string {
116
119
  }
117
120
 
118
121
  /** Lista ordenada de candidatos: la tabla inicial, adaptada a lo que pide la configuración. */
119
- function candidatosDe(estacion: NombreEstacion, cfg: ConfigEstacion | undefined, descartes: string[]): Candidato[] {
120
- const tabla: Candidato[] = (TABLA_MODELOS_INICIAL[estacion] ?? []).map((c) => ({ ...c }));
122
+ function candidatosDe(estacion: NombreEstacion, cfg: ConfigEstacion | undefined, descartes: string[], revisionDe?: IAExterna): Candidato[] {
123
+ const tabla: Candidato[] = (TABLA_MODELOS_INICIAL[estacion] ?? [])
124
+ .filter((c) => estacion !== 'codigo' || c.ia === (revisionDe ?? 'claude'))
125
+ .map((c) => ({ ...c }));
121
126
  let lista = tabla;
122
127
  if (cfg?.modelo !== undefined) {
123
128
  const enTabla = tabla.find((c) => c.modelo === cfg.modelo && (cfg.ia === undefined || c.ia === cfg.ia));
@@ -229,8 +234,8 @@ function candidatosConEvidencia(
229
234
 
230
235
  /**
231
236
  * Propone el recorrido: qué estaciones se activan con este diff, y qué IA, modelo y esfuerzo usa cada una.
232
- * Las estaciones externas se deciden con la evidencia medida (`~/.nexakit/fabrica/evidencia.json` bajo `home`): el modelo más
233
- * barato que alcanza la calidad que pide el riesgo. Sin datos manda la tabla manual, y la configuración del repo
237
+ * Las estaciones externas se deciden con la evidencia medida y el criterio global bajo `home`.
238
+ * Sin datos manda la tabla manual, y la configuración del repo
234
239
  * (`ia` o `modelo` fijados) manda siempre. Las estaciones de Claude siguen la tabla.
235
240
  */
236
241
  export async function proponer(entrada: {
@@ -247,13 +252,17 @@ export async function proponer(entrada: {
247
252
  const config = await cargarConfig(raiz);
248
253
  const diff = await leerDiff(raiz, base);
249
254
  const categorias = clasificar(diff.archivos, config);
250
- const { evidencia, aviso: avisoEvidencia } = await cargar(home, ahora);
255
+ const [{ evidencia, aviso: avisoEvidencia }, { criterio, revisionCruzada }] = await Promise.all([
256
+ cargar(home, ahora),
257
+ leerPreferencias(home),
258
+ ]);
251
259
 
252
260
  const avisosEstaciones: string[] = [];
253
261
  let usoEvidencia = false;
254
262
 
255
- const estaciones: EstacionRecorrido[] = NOMBRES_ESTACION.map((estacion): EstacionRecorrido => {
263
+ function proponerEstacion(estacion: NombreEstacion, revisionDe?: IAExterna): EstacionRecorrido {
256
264
  const cfg = config.estaciones?.[estacion];
265
+ const nombre = claveEstacion(estacion, revisionDe);
257
266
  const regla = ACTIVACION[estacion];
258
267
  const omitida = (motivo: string): EstacionRecorrido => ({
259
268
  estacion,
@@ -270,12 +279,13 @@ export async function proponer(entrada: {
270
279
  if (cfg?.activa === false) return omitida('desactivada en la configuración');
271
280
  const porDiff = regla.categoria === null || categorias.has(regla.categoria);
272
281
  if (!porDiff && cfg?.activa !== true) return omitida(regla.sinActivar);
273
- const motivo = porDiff ? regla.motivo : 'activada en la configuración';
282
+ const motivo = revisionDe !== undefined ? 'revisión cruzada de código' : porDiff ? regla.motivo : 'activada en la configuración';
274
283
 
275
284
  const descartes: string[] = [];
276
- const manual = candidatosDe(estacion, cfg, descartes);
285
+ const manual = candidatosDe(estacion, revisionDe === undefined ? cfg : undefined, descartes, revisionDe);
277
286
  const propuesta = (c: Candidato, explicacion: string, calidad: number | null): EstacionRecorrido => ({
278
287
  estacion,
288
+ ...(revisionDe === undefined ? {} : { revisionDe }),
279
289
  ia: c.ia,
280
290
  modelo: c.modelo,
281
291
  // Antigravity lleva el esfuerzo dentro del id del modelo.
@@ -295,7 +305,7 @@ export async function proponer(entrada: {
295
305
  });
296
306
 
297
307
  const fijada = cfg?.ia !== undefined || cfg?.modelo !== undefined;
298
- if (fijada || manual[0]?.ia === 'claude') {
308
+ if (revisionDe === undefined && (fijada || manual[0]?.ia === 'claude')) {
299
309
  // Lo fijado en la configuración y las estaciones de Claude no se deciden por evidencia: manda la tabla.
300
310
  for (const c of manual) {
301
311
  const razon = descarte(c, catalogos);
@@ -311,25 +321,49 @@ export async function proponer(entrada: {
311
321
  }
312
322
 
313
323
  const disponibles: Candidato[] = [];
314
- for (const c of candidatosConEvidencia(estacion, manual, cfg, catalogos, evidencia)) {
324
+ for (const c of candidatosConEvidencia(estacion, manual, revisionDe === undefined ? cfg : undefined, catalogos, evidencia)) {
325
+ if (revisionDe !== undefined && c.ia !== revisionDe) continue;
315
326
  const razon = descarte(c, catalogos);
316
327
  if (razon === null) disponibles.push(c);
317
328
  else descartes.push(razon);
318
329
  }
330
+ // Si la tabla y la evidencia no ofrecen ningún par vivo, usa el orden del catálogo.
331
+ const porCatalogo = revisionDe !== undefined && disponibles.length === 0;
332
+ if (porCatalogo) {
333
+ for (const { modelo, esfuerzos } of catalogos[revisionDe] ?? []) {
334
+ if (revisionDe === 'antigravity') disponibles.push({ ia: revisionDe, modelo, esfuerzo: null });
335
+ else for (const esfuerzo of esfuerzos) disponibles.push({ ia: revisionDe, modelo, esfuerzo });
336
+ }
337
+ }
319
338
  if (disponibles.length === 0) return sinModelo();
320
339
 
321
340
  usoEvidencia = true;
322
341
  const riesgo = riesgoDe(categorias, estacion);
323
- const decision = elegir({ estacion, riesgo, candidatos: disponibles, evidencia });
342
+ const decision = elegir({ estacion, riesgo, candidatos: disponibles, evidencia, criterio });
324
343
  if (decision.sinDatos) {
325
- avisosEstaciones.push(`${estacion}: sin datos medidos: ejecuta el banco con \`nexakit fabrica banco planificar\`; mientras, se usa la tabla manual`);
344
+ const fuente = porCatalogo ? 'el orden del catálogo' : 'la tabla manual';
345
+ avisosEstaciones.push(`${nombre}: sin datos medidos: ejecuta el banco con \`nexakit fabrica banco planificar\`; mientras, se usa ${fuente}`);
326
346
  } else if (!decision.alcanzaUmbral) {
327
347
  avisosEstaciones.push(
328
- `${estacion}: ningún modelo alcanza la calidad que pide el riesgo ${riesgo} (${String(UMBRALES[riesgo]).replace('.', ',')}): ${ORDEN_BANCO} para medir más`,
348
+ `${nombre}: ningún modelo alcanza la calidad que pide el riesgo ${riesgo} (${String(UMBRALES[riesgo]).replace('.', ',')}): ${ORDEN_BANCO} para medir más`,
329
349
  );
330
350
  }
331
- return propuesta(decision.eleccion, decision.explicacion, decision.calidad);
332
- });
351
+ const explicacion = porCatalogo ? decision.explicacion.replace('la tabla manual', 'el orden del catálogo') : decision.explicacion;
352
+ return propuesta(decision.eleccion, explicacion, decision.calidad);
353
+ }
354
+
355
+ const estaciones: EstacionRecorrido[] = [];
356
+ for (const estacion of NOMBRES_ESTACION) {
357
+ const principal = proponerEstacion(estacion);
358
+ estaciones.push(principal);
359
+ if (estacion !== 'codigo' || principal.estado === 'omitida' || !revisionCruzada) continue;
360
+ for (const ia of IAExterna.options) {
361
+ if (principal.ia === ia) continue;
362
+ const revision = proponerEstacion(estacion, ia);
363
+ if (revision.estado === 'propuesta') estaciones.push(revision);
364
+ else avisosEstaciones.push(`Se omite la revisión cruzada de código con ${ia}: no hay modelos disponibles`);
365
+ }
366
+ }
333
367
 
334
368
  const avisos: string[] = [];
335
369
  if (usoEvidencia) {
@@ -388,20 +422,23 @@ function validarEleccion(estacion: string, ia: IA, modelo: string, esfuerzo: str
388
422
  export function aplicarCambios(recorrido: Recorrido, cambios: CambioRecorrido[]): Recorrido {
389
423
  const estaciones = structuredClone(recorrido.estaciones);
390
424
  for (const cambio of cambios) {
391
- const actual = estaciones.find((e) => e.estacion === cambio.estacion);
425
+ const actual = estaciones.find((e) => claveEstacion(e.estacion, e.revisionDe) === cambio.estacion);
392
426
  if (actual === undefined) throw new ErrorFabrica(`La estación ${cambio.estacion} no existe en el recorrido`);
393
427
 
394
428
  if (cambio.quitar === true) {
395
- Object.assign(actual, {
396
- ia: null,
397
- modelo: null,
398
- esfuerzo: null,
399
- ordenesPermitidas: [],
400
- explicacion: '',
401
- calidad: null,
402
- motivo: 'quitada por la persona',
403
- estado: 'omitida',
404
- } satisfies Partial<EstacionRecorrido>);
429
+ const quitar = actual.revisionDe === undefined ? estaciones.filter((e) => e.estacion === actual.estacion) : [actual];
430
+ for (const e of quitar) {
431
+ Object.assign(e, {
432
+ ia: null,
433
+ modelo: null,
434
+ esfuerzo: null,
435
+ ordenesPermitidas: [],
436
+ explicacion: '',
437
+ calidad: null,
438
+ motivo: 'quitada por la persona',
439
+ estado: 'omitida',
440
+ } satisfies Partial<EstacionRecorrido>);
441
+ }
405
442
  continue;
406
443
  }
407
444
  if (cambio.ia === undefined && cambio.modelo === undefined && cambio.esfuerzo === undefined) continue;
@@ -411,6 +448,9 @@ export function aplicarCambios(recorrido: Recorrido, cambios: CambioRecorrido[])
411
448
  if (ia === null || modelo === null) {
412
449
  throw new ErrorFabrica(`Para activar la estación ${cambio.estacion} indica la IA y el modelo`);
413
450
  }
451
+ if (actual.revisionDe !== undefined && ia !== actual.revisionDe) {
452
+ throw new ErrorFabrica(`La revisión ${cambio.estacion} usa ${actual.revisionDe}`);
453
+ }
414
454
  const mismaIa = ia === actual.ia;
415
455
  const mismoModelo = modelo === actual.modelo;
416
456
  const esfuerzo = cambio.esfuerzo ?? (mismaIa && mismoModelo ? actual.esfuerzo : null);
@@ -429,6 +469,10 @@ export function aplicarCambios(recorrido: Recorrido, cambios: CambioRecorrido[])
429
469
  estado: 'propuesta',
430
470
  } satisfies Partial<EstacionRecorrido>);
431
471
  }
472
+ const iasCodigo = estaciones.filter((e) => e.estacion === 'codigo' && e.estado === 'propuesta').map((e) => e.ia);
473
+ if (new Set(iasCodigo).size !== iasCodigo.length) {
474
+ throw new ErrorFabrica('La estación codigo solo admite una ejecución por IA');
475
+ }
432
476
  return {
433
477
  ...recorrido,
434
478
  estaciones,
@@ -1,6 +1,8 @@
1
1
  import { z } from 'zod';
2
2
 
3
- export const IA = z.enum(['codex', 'antigravity', 'claude']);
3
+ export const IAExterna = z.enum(['codex', 'antigravity']);
4
+ export type IAExterna = z.infer<typeof IAExterna>;
5
+ export const IA = z.enum([...IAExterna.options, 'claude']);
4
6
  export type IA = z.infer<typeof IA>;
5
7
 
6
8
  export const NOMBRES_ESTACION = [
@@ -15,6 +17,11 @@ export const NOMBRES_ESTACION = [
15
17
  export const NombreEstacion = z.enum(NOMBRES_ESTACION);
16
18
  export type NombreEstacion = z.infer<typeof NombreEstacion>;
17
19
 
20
+ /** Identifica la ejecución de una estación en el recorrido y en el rastro. */
21
+ export function claveEstacion(estacion: NombreEstacion, revisionDe?: IAExterna): string {
22
+ return revisionDe === undefined ? estacion : `${estacion}-${revisionDe}`;
23
+ }
24
+
18
25
  const Nivel = z.enum(['alta', 'media', 'baja']);
19
26
 
20
27
  export const Hallazgo = z.object({
@@ -56,6 +63,8 @@ export const ConfigFabrica = z.object({
56
63
  )
57
64
  .optional(),
58
65
  paralelismo: z.number().int().min(1).max(8).default(4),
66
+ /** Tope de estaciones a la vez por IA, además del global (por defecto Antigravity 2). */
67
+ paralelismoPorIa: z.partialRecord(IA, z.number().int().min(1).max(8)).optional(),
59
68
  });
60
69
  export type ConfigFabrica = z.infer<typeof ConfigFabrica>;
61
70