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.
- package/README.md +9 -5
- package/assets/runtime/package-lock.json +2 -2
- package/dist/fabrica/banco/ejecutar.js +16 -8
- package/dist/fabrica/cli.js +269 -25
- package/dist/fabrica/conectores/antigravity.js +511 -12
- package/dist/fabrica/conectores/codex.js +400 -18
- package/dist/fabrica/consolidar.js +64 -27
- package/dist/fabrica/decision.js +43 -21
- package/dist/fabrica/disco.js +220 -9
- package/dist/fabrica/ejecutor.js +138 -75
- package/dist/fabrica/encargo/candado.js +274 -0
- package/dist/fabrica/encargo/ejecutar.js +827 -0
- package/dist/fabrica/encargo/evidencia.js +308 -0
- package/dist/fabrica/encargo/parche.js +146 -0
- package/dist/fabrica/encargo/worktree.js +394 -0
- package/dist/fabrica/enrutador.js +76 -27
- package/dist/fabrica/esquemas.js +8 -1
- package/dist/fabrica/evidencia.js +6 -3
- package/dist/fabrica/jsonrpc.js +53 -5
- package/dist/fabrica/mcp.js +147 -12
- package/dist/fabrica/preferencias.js +56 -0
- package/dist/fabrica/rastro.js +70 -14
- package/dist/fabrica/sesion.js +7 -3
- package/dist/fabrica/tabla-modelos.json +4 -2
- package/dist/fabrica/veredictos.js +15 -11
- package/package.json +1 -1
- package/plugins/huellas.json +4 -4
- package/plugins/nexakit-modelo/.claude-plugin/plugin.json +1 -1
- package/plugins/nexakit-modelo/hooks/barra.js +22 -1
- package/plugins/nexakit-modelo/hooks/decidir.js +2 -2
- package/plugins/nexakit-modelo/hooks/register.js +94 -6
- package/plugins/nexakit-modelo/tests/register.test.ts +253 -0
- package/plugins/niveles/.claude-plugin/plugin.json +1 -1
- package/plugins/niveles/agents/cazador-de-flakes.md +1 -0
- package/plugins/niveles/agents/cierre-de-memoria.md +1 -0
- package/plugins/niveles/agents/investigador.md +1 -0
- package/plugins/niveles/agents/nivel-alto.md +1 -0
- package/plugins/niveles/agents/nivel-exigente.md +1 -0
- package/plugins/niveles/agents/nivel-ligero.md +1 -0
- package/plugins/niveles/agents/nivel-normal.md +1 -0
- package/plugins/niveles/agents/revisor-de-calidad.md +1 -0
- package/plugins/niveles/agents/sincronizador-docs.md +1 -0
- package/plugins/niveles/agents/subir-al-repo.md +1 -0
- package/skills/elegir-modelo/SKILL.md +3 -3
- package/skills/elegir-modelo/modelos.mjs +1 -1
- package/skills/fabrica/SKILL.md +27 -8
- package/src/agent-models.js +1 -1
- package/src/antigravity-recommendation.js +14 -7
- package/src/codex-team.js +2 -1
- package/src/fabrica/banco/ejecutar.ts +20 -10
- package/src/fabrica/cli.ts +257 -24
- package/src/fabrica/conectores/antigravity.ts +508 -12
- package/src/fabrica/conectores/codex.ts +410 -17
- package/src/fabrica/conectores/tipos.ts +4 -0
- package/src/fabrica/consolidar.ts +92 -33
- package/src/fabrica/decision.ts +50 -22
- package/src/fabrica/disco.ts +237 -10
- package/src/fabrica/ejecutor.ts +144 -69
- package/src/fabrica/encargo/candado.ts +287 -0
- package/src/fabrica/encargo/ejecutar.ts +953 -0
- package/src/fabrica/encargo/evidencia.ts +301 -0
- package/src/fabrica/encargo/parche.ts +151 -0
- package/src/fabrica/encargo/worktree.ts +427 -0
- package/src/fabrica/enrutador.ts +71 -27
- package/src/fabrica/esquemas.ts +10 -1
- package/src/fabrica/evidencia.ts +7 -3
- package/src/fabrica/jsonrpc.ts +51 -5
- package/src/fabrica/mcp.ts +166 -12
- package/src/fabrica/preferencias.ts +66 -0
- package/src/fabrica/rastro.ts +69 -14
- package/src/fabrica/sesion.ts +7 -3
- package/src/fabrica/tabla-modelos.json +4 -2
- package/src/fabrica/veredictos.ts +18 -14
- package/src/gemini-tools.js +1 -1
- package/src/level-agents.js +2 -0
- package/src/model-command.d.ts +29 -0
- package/src/model-command.js +2 -2
- package/src/regla-ordenes-simples.d.ts +2 -0
- package/src/regla-ordenes-simples.js +4 -0
- package/src/review-instructions.js +39 -10
- package/src/toolkit-cli.js +7 -3
package/dist/fabrica/ejecutor.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createHash, randomBytes } from 'node:crypto';
|
|
2
2
|
import os from 'node:os';
|
|
3
3
|
import { leerDiff } from './diff.js';
|
|
4
|
-
import {
|
|
4
|
+
import { clasificarCambios, instantanea } from './disco.js';
|
|
5
5
|
import { calcularCoste, comprobarHuella, descarte } from './enrutador.js';
|
|
6
6
|
import { ErrorFabrica } from './errores.js';
|
|
7
7
|
import { ESTACIONES } from './estaciones.js';
|
|
@@ -9,7 +9,13 @@ import { cortarEnPalabra, limpiarTexto, MAX_LECCIONES_ENCARGO, MAX_REGLA, paraEn
|
|
|
9
9
|
import * as rastro from './rastro.js';
|
|
10
10
|
/** Estaciones externas a la vez, salvo que la configuración diga otra cosa. */
|
|
11
11
|
export const PARALELISMO = 4;
|
|
12
|
-
/**
|
|
12
|
+
/**
|
|
13
|
+
* Estaciones a la vez de una misma IA, además del tope global. Antigravity va con 2: en un recorrido real con 4 sesiones
|
|
14
|
+
* a la vez (seguridad, pruebas, código y documentación), dos terminaron en menos de un minuto y las otras dos agotaron los
|
|
15
|
+
* 15 minutos sin respuesta. Una IA que no figura aquí solo tiene el tope global.
|
|
16
|
+
*/
|
|
17
|
+
export const PARALELISMO_POR_IA = { antigravity: 2 };
|
|
18
|
+
/** Tiempo máximo de cada estación, contado desde que arranca de verdad (no mientras espera plaza): 15 minutos. */
|
|
13
19
|
export const TIEMPO_MAXIMO_MS = 900_000;
|
|
14
20
|
/** Lo que se espera a un conector tras abortarlo, y a un catálogo vivo: 30 segundos. */
|
|
15
21
|
export const GRACIA_MS = 30_000;
|
|
@@ -25,7 +31,7 @@ const CANCELADA = 'cancelada por la persona';
|
|
|
25
31
|
const MODELO_RETIRADO = 'el modelo ya no está en el catálogo';
|
|
26
32
|
const SIN_RESPUESTA = 'el revisor no respondió a la cancelación';
|
|
27
33
|
/** Marca de una espera que venció su tope. */
|
|
28
|
-
const AGOTADO = Symbol('agotado');
|
|
34
|
+
export const AGOTADO = Symbol('agotado');
|
|
29
35
|
const registro = new Map();
|
|
30
36
|
/** Ids terminados en memoria, del más antiguo al más reciente. */
|
|
31
37
|
const terminados = [];
|
|
@@ -38,7 +44,7 @@ function retirarAntiguos(id) {
|
|
|
38
44
|
}
|
|
39
45
|
}
|
|
40
46
|
/** Resuelve con `AGOTADO` si la promesa no termina en `ms`. */
|
|
41
|
-
function conTope(promesa, ms) {
|
|
47
|
+
export function conTope(promesa, ms) {
|
|
42
48
|
let reloj;
|
|
43
49
|
const tope = new Promise((resolve) => {
|
|
44
50
|
reloj = setTimeout(() => resolve(AGOTADO), ms);
|
|
@@ -46,7 +52,7 @@ function conTope(promesa, ms) {
|
|
|
46
52
|
return Promise.race([promesa, tope]).finally(() => clearTimeout(reloj));
|
|
47
53
|
}
|
|
48
54
|
/** Como `conTope`, pero el plazo empieza cuando se aborta la señal. */
|
|
49
|
-
function conGracia(promesa, señal, ms) {
|
|
55
|
+
export function conGracia(promesa, señal, ms) {
|
|
50
56
|
let reloj;
|
|
51
57
|
let alAbortar = () => { };
|
|
52
58
|
const gracia = new Promise((resolve) => {
|
|
@@ -67,6 +73,8 @@ class Semaforo {
|
|
|
67
73
|
libres;
|
|
68
74
|
cola = [];
|
|
69
75
|
constructor(plazas) {
|
|
76
|
+
if (!Number.isInteger(plazas) || plazas < 1)
|
|
77
|
+
throw new ErrorFabrica('Un semáforo necesita un número entero de plazas mayor que cero');
|
|
70
78
|
this.libres = plazas;
|
|
71
79
|
}
|
|
72
80
|
async adquirir() {
|
|
@@ -152,6 +160,14 @@ async function leccionesDelRepo(home, raiz, estacion, avisos) {
|
|
|
152
160
|
return [];
|
|
153
161
|
}
|
|
154
162
|
}
|
|
163
|
+
/** Cuántas rutas ignoradas se nombran en el aviso; el resto se cuenta. */
|
|
164
|
+
const MAX_IGNORADOS_AVISO = 10;
|
|
165
|
+
/** Aviso de escrituras en archivos que Git ignora: no invalidan el recorrido, pero se dicen. */
|
|
166
|
+
export function avisoIgnorados(rutas) {
|
|
167
|
+
const nombradas = rutas.slice(0, MAX_IGNORADOS_AVISO).map((ruta) => limpiarTexto(ruta));
|
|
168
|
+
const resto = rutas.length - nombradas.length;
|
|
169
|
+
return `escrituras en archivos ignorados (probablemente de otra herramienta): ${nombradas.join(', ')}${resto > 0 ? ` y ${resto} más` : ''}`;
|
|
170
|
+
}
|
|
155
171
|
function mensajeDe(error) {
|
|
156
172
|
return error instanceof Error ? error.message : String(error);
|
|
157
173
|
}
|
|
@@ -191,7 +207,7 @@ function contenidoActivo(ej) {
|
|
|
191
207
|
modelo: ej.detalle[i]?.modelo ?? null,
|
|
192
208
|
esfuerzo: ej.detalle[i]?.esfuerzo ?? null,
|
|
193
209
|
estado: fila.estado,
|
|
194
|
-
tokens: ej.tokens.get(fila
|
|
210
|
+
tokens: ej.tokens.get(fila) ?? 0,
|
|
195
211
|
})),
|
|
196
212
|
};
|
|
197
213
|
}
|
|
@@ -249,89 +265,121 @@ function marcar(fila, estado, motivo) {
|
|
|
249
265
|
fila.motivo = motivo;
|
|
250
266
|
}
|
|
251
267
|
const RESULTADOS = new Set(['ok', 'fallida', 'cancelada']);
|
|
252
|
-
async function correrEstacion(ej, trabajo,
|
|
253
|
-
|
|
268
|
+
async function correrEstacion(ej, trabajo, plazas, timeoutMs, graciaMs) {
|
|
269
|
+
const deLaIa = plazas.porIa.get(trabajo.ia);
|
|
270
|
+
await deLaIa?.adquirir();
|
|
271
|
+
let asentada = Promise.resolve();
|
|
254
272
|
try {
|
|
255
|
-
|
|
256
|
-
return;
|
|
257
|
-
const control = new AbortController();
|
|
258
|
-
ej.controladores.add(control);
|
|
259
|
-
let agotado = false;
|
|
260
|
-
const reloj = setTimeout(() => {
|
|
261
|
-
agotado = true;
|
|
262
|
-
control.abort(new ErrorFabrica(TIEMPO_AGOTADO));
|
|
263
|
-
}, timeoutMs);
|
|
264
|
-
marcar(trabajo.fila, 'en-curso');
|
|
265
|
-
void persistir(ej);
|
|
266
|
-
publicarActivo(ej);
|
|
267
|
-
let resultado;
|
|
268
|
-
let sinRespuesta = false;
|
|
273
|
+
await plazas.global.adquirir();
|
|
269
274
|
try {
|
|
270
|
-
|
|
271
|
-
const alProgreso = ({ tokens }) => {
|
|
272
|
-
if (trabajo.fila.estado !== 'en-curso' || !Number.isFinite(tokens))
|
|
273
|
-
return;
|
|
274
|
-
ej.tokens.set(trabajo.fila.estacion, tokens);
|
|
275
|
-
publicarActivo(ej);
|
|
276
|
-
};
|
|
277
|
-
const llamada = Promise.resolve().then(() => trabajo.conector.ejecutar(trabajo.encargo, control.signal, alProgreso));
|
|
278
|
-
const respuesta = await conGracia(llamada, control.signal, graciaMs);
|
|
279
|
-
if (respuesta === AGOTADO) {
|
|
280
|
-
sinRespuesta = true;
|
|
281
|
-
throw new ErrorFabrica(SIN_RESPUESTA);
|
|
282
|
-
}
|
|
283
|
-
resultado = respuesta;
|
|
284
|
-
if (typeof resultado !== 'object' || resultado === null || !RESULTADOS.has(resultado.estado)) {
|
|
285
|
-
throw new ErrorFabrica('respuesta no válida');
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
catch (error) {
|
|
289
|
-
resultado = {
|
|
290
|
-
estado: 'fallida',
|
|
291
|
-
crudo: '',
|
|
292
|
-
modeloInformado: null,
|
|
293
|
-
tokens: null,
|
|
294
|
-
denegaciones: [],
|
|
295
|
-
motivo: `el conector falló: ${mensajeDe(error)}`,
|
|
296
|
-
};
|
|
275
|
+
asentada = (await correrConPlaza(ej, trabajo, timeoutMs, graciaMs)).asentada;
|
|
297
276
|
}
|
|
298
277
|
finally {
|
|
299
|
-
|
|
300
|
-
ej.controladores.delete(control);
|
|
278
|
+
plazas.global.liberar();
|
|
301
279
|
}
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
else
|
|
310
|
-
final = resultado;
|
|
311
|
-
// Primero el archivo de la estación, para que un estado terminado siempre tenga su resultado.
|
|
312
|
-
try {
|
|
313
|
-
await rastro.guardarEstacion(ej.estado.dir, trabajo.fila.estacion, trabajo.encargoRastro, final);
|
|
280
|
+
}
|
|
281
|
+
finally {
|
|
282
|
+
if (deLaIa !== undefined) {
|
|
283
|
+
// Un conector que no responde a la cancelación puede seguir con la sesión viva: la plaza de la IA se retiene
|
|
284
|
+
// hasta que la llamada se asiente o pasen `graciaMs` más, para no sumar sesiones colgadas al tope. No retrasa
|
|
285
|
+
// el recorrido: la plaza se libera en segundo plano.
|
|
286
|
+
void conTope(asentada, graciaMs).then(() => deLaIa.liberar());
|
|
314
287
|
}
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
/** La estación ya tiene todas sus plazas: aquí empieza a contar su tiempo máximo. */
|
|
291
|
+
async function correrConPlaza(ej, trabajo, timeoutMs, graciaMs) {
|
|
292
|
+
if (ej.cancelado || trabajo.fila.estado !== 'pendiente')
|
|
293
|
+
return { asentada: Promise.resolve() };
|
|
294
|
+
const control = new AbortController();
|
|
295
|
+
ej.controladores.add(control);
|
|
296
|
+
let agotado = false;
|
|
297
|
+
const reloj = setTimeout(() => {
|
|
298
|
+
agotado = true;
|
|
299
|
+
control.abort(new ErrorFabrica(TIEMPO_AGOTADO));
|
|
300
|
+
}, timeoutMs);
|
|
301
|
+
marcar(trabajo.fila, 'en-curso');
|
|
302
|
+
void persistir(ej);
|
|
303
|
+
publicarActivo(ej);
|
|
304
|
+
let resultado;
|
|
305
|
+
let sinRespuesta = false;
|
|
306
|
+
// Se asienta cuando el conector devuelve (o rechaza), aunque ya no se espere por él.
|
|
307
|
+
let asentada = Promise.resolve();
|
|
308
|
+
try {
|
|
309
|
+
// `then` convierte también una excepción síncrona del conector en un rechazo.
|
|
310
|
+
const alProgreso = ({ tokens }) => {
|
|
311
|
+
if (trabajo.fila.estado !== 'en-curso' || !Number.isFinite(tokens))
|
|
312
|
+
return;
|
|
313
|
+
ej.tokens.set(trabajo.fila, tokens);
|
|
320
314
|
publicarActivo(ej);
|
|
315
|
+
};
|
|
316
|
+
const llamada = Promise.resolve().then(() => trabajo.conector.ejecutar(trabajo.encargo, control.signal, alProgreso));
|
|
317
|
+
asentada = llamada.then(() => undefined, () => undefined);
|
|
318
|
+
const respuesta = await conGracia(llamada, control.signal, graciaMs);
|
|
319
|
+
if (respuesta === AGOTADO) {
|
|
320
|
+
sinRespuesta = true;
|
|
321
|
+
throw new ErrorFabrica(SIN_RESPUESTA);
|
|
322
|
+
}
|
|
323
|
+
resultado = respuesta;
|
|
324
|
+
if (typeof resultado !== 'object' || resultado === null || !RESULTADOS.has(resultado.estado)) {
|
|
325
|
+
throw new ErrorFabrica('respuesta no válida');
|
|
321
326
|
}
|
|
322
327
|
}
|
|
328
|
+
catch (error) {
|
|
329
|
+
resultado = {
|
|
330
|
+
estado: 'fallida',
|
|
331
|
+
crudo: '',
|
|
332
|
+
modeloInformado: null,
|
|
333
|
+
tokens: null,
|
|
334
|
+
denegaciones: [],
|
|
335
|
+
motivo: `el conector falló: ${mensajeDe(error)}`,
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
finally {
|
|
339
|
+
clearTimeout(reloj);
|
|
340
|
+
ej.controladores.delete(control);
|
|
341
|
+
}
|
|
342
|
+
let final;
|
|
343
|
+
if (sinRespuesta)
|
|
344
|
+
final = { ...resultado, estado: 'fallida', motivo: SIN_RESPUESTA };
|
|
345
|
+
else if (agotado)
|
|
346
|
+
final = { ...resultado, estado: 'fallida', motivo: TIEMPO_AGOTADO };
|
|
347
|
+
else if (ej.cancelado)
|
|
348
|
+
final = { ...resultado, estado: 'cancelada', motivo: CANCELADA };
|
|
349
|
+
else
|
|
350
|
+
final = resultado;
|
|
351
|
+
// Primero el archivo de la estación, para que un estado terminado siempre tenga su resultado.
|
|
352
|
+
try {
|
|
353
|
+
await rastro.guardarEstacion(ej.estado.dir, trabajo.fila.estacion, trabajo.encargoRastro, final, trabajo.fila.revisionDe);
|
|
354
|
+
}
|
|
323
355
|
finally {
|
|
324
|
-
|
|
356
|
+
if (final.tokens !== null)
|
|
357
|
+
ej.tokens.set(trabajo.fila, final.tokens.total);
|
|
358
|
+
marcar(trabajo.fila, final.estado, final.motivo);
|
|
359
|
+
void persistir(ej);
|
|
360
|
+
publicarActivo(ej);
|
|
325
361
|
}
|
|
362
|
+
// Dentro de un objeto: devolver la promesa tal cual haría que `async` la esperase.
|
|
363
|
+
return { asentada };
|
|
326
364
|
}
|
|
327
|
-
async function correr(ej, trabajos, antes, raiz, paralelismo, timeoutMs, graciaMs, poda) {
|
|
328
|
-
const
|
|
329
|
-
|
|
365
|
+
async function correr(ej, trabajos, antes, raiz, paralelismo, porIa, timeoutMs, graciaMs, poda) {
|
|
366
|
+
const plazas = {
|
|
367
|
+
global: new Semaforo(paralelismo),
|
|
368
|
+
porIa: new Map(Object.entries(porIa)
|
|
369
|
+
.filter((par) => par[1] !== undefined)
|
|
370
|
+
.map(([ia, tope]) => [ia, new Semaforo(tope)])),
|
|
371
|
+
};
|
|
372
|
+
const desenlaces = await Promise.allSettled(trabajos.map((t) => correrEstacion(ej, t, plazas, timeoutMs, graciaMs)));
|
|
330
373
|
const fallo = desenlaces.find((d) => d.status === 'rejected');
|
|
331
374
|
if (fallo !== undefined)
|
|
332
375
|
ej.estado.motivo = `no se pudo guardar el rastro: ${mensajeDe(fallo.reason)}`;
|
|
333
376
|
try {
|
|
334
|
-
|
|
377
|
+
// Una estación es de solo lectura: un archivo seguido o sin ignorar que cambia la invalida. Lo que Git ya ignoraba
|
|
378
|
+
// (la caché de un hook de otra herramienta, por ejemplo) solo se avisa.
|
|
379
|
+
const { invalidantes, ignorados } = clasificarCambios(antes, await instantanea(raiz));
|
|
380
|
+
ej.estado.escriturasDetectadas = invalidantes;
|
|
381
|
+
if (ignorados.length > 0)
|
|
382
|
+
(ej.estado.avisos ??= []).push(avisoIgnorados(ignorados));
|
|
335
383
|
}
|
|
336
384
|
catch (error) {
|
|
337
385
|
ej.estado.motivo ??= `no se pudo comprobar el disco tras el recorrido: ${mensajeDe(error)}`;
|
|
@@ -363,10 +411,19 @@ async function correr(ej, trabajos, antes, raiz, paralelismo, timeoutMs, graciaM
|
|
|
363
411
|
* cuanto el rastro existe y ejecuta las estaciones externas en segundo plano.
|
|
364
412
|
*/
|
|
365
413
|
export async function lanzar(r, opciones) {
|
|
366
|
-
const { raiz, conectores, paralelismo = PARALELISMO, timeoutMs = TIEMPO_MAXIMO_MS, graciaMs = GRACIA_MS, topeCatalogoMs = TOPE_CATALOGO_MS, home = os.homedir(), intervaloActivoMs = INTERVALO_ACTIVO_MS, sinLecciones = false, } = opciones;
|
|
414
|
+
const { raiz, conectores, paralelismo = PARALELISMO, paralelismoPorIa = {}, timeoutMs = TIEMPO_MAXIMO_MS, graciaMs = GRACIA_MS, topeCatalogoMs = TOPE_CATALOGO_MS, home = os.homedir(), intervaloActivoMs = INTERVALO_ACTIVO_MS, sinLecciones = false, } = opciones;
|
|
367
415
|
if (!Number.isInteger(paralelismo) || paralelismo < 1) {
|
|
368
416
|
throw new ErrorFabrica('El paralelismo debe ser un número entero mayor que cero');
|
|
369
417
|
}
|
|
418
|
+
// Un `undefined` explícito no borra el tope por defecto: se descarta.
|
|
419
|
+
const topesPorIa = { ...PARALELISMO_POR_IA };
|
|
420
|
+
for (const [ia, tope] of Object.entries(paralelismoPorIa)) {
|
|
421
|
+
if (tope === undefined)
|
|
422
|
+
continue;
|
|
423
|
+
if (!Number.isInteger(tope) || tope < 1)
|
|
424
|
+
throw new ErrorFabrica('El paralelismo por IA debe ser un número entero mayor que cero');
|
|
425
|
+
topesPorIa[ia] = tope;
|
|
426
|
+
}
|
|
370
427
|
for (const [valor, nombre] of [
|
|
371
428
|
[timeoutMs, 'El tiempo máximo por estación'],
|
|
372
429
|
[graciaMs, 'La espera tras cancelar'],
|
|
@@ -404,6 +461,11 @@ export async function lanzar(r, opciones) {
|
|
|
404
461
|
nonce = randomBytes(6).toString('hex');
|
|
405
462
|
for (const e of r.estaciones) {
|
|
406
463
|
const fila = { estacion: e.estacion, estado: 'pendiente' };
|
|
464
|
+
if (e.revisionDe !== undefined)
|
|
465
|
+
fila.revisionDe = e.revisionDe;
|
|
466
|
+
// La IA solo viaja en las filas de código: el consolidado cuenta con ella las coincidencias de la revisión cruzada.
|
|
467
|
+
if (e.estacion === 'codigo' && e.ia !== null)
|
|
468
|
+
fila.ia = e.ia;
|
|
407
469
|
filas.push(fila);
|
|
408
470
|
if (e.estado === 'omitida') {
|
|
409
471
|
marcar(fila, 'omitida', e.motivo);
|
|
@@ -447,6 +509,7 @@ export async function lanzar(r, opciones) {
|
|
|
447
509
|
const encargo = construirEncargo({ estacion: e, raiz, base: r.base, foco: r.foco, diff: diff.texto, nonce, lecciones });
|
|
448
510
|
trabajos.push({
|
|
449
511
|
fila,
|
|
512
|
+
ia: e.ia,
|
|
450
513
|
conector,
|
|
451
514
|
encargo,
|
|
452
515
|
// El rastro no guarda el diff pero sí las lecciones que se aplicaron: se ve qué datos recibió la estación.
|
|
@@ -484,7 +547,7 @@ export async function lanzar(r, opciones) {
|
|
|
484
547
|
publicarActivo(ej);
|
|
485
548
|
// La poda corre en segundo plano y nunca hace fallar el recorrido.
|
|
486
549
|
const poda = rastro.podar(home).then(() => undefined, () => undefined);
|
|
487
|
-
ej.fin = correr(ej, trabajos, antes, raiz, paralelismo, timeoutMs, graciaMs, poda).then((guardado) => {
|
|
550
|
+
ej.fin = correr(ej, trabajos, antes, raiz, paralelismo, topesPorIa, timeoutMs, graciaMs, poda).then((guardado) => {
|
|
488
551
|
// Si el estado final no llegó al disco, el recorrido se queda en memoria.
|
|
489
552
|
if (guardado)
|
|
490
553
|
retirarAntiguos(id);
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { closeSync, constants, lstatSync, openSync, readFileSync } from 'node:fs';
|
|
3
|
+
import { link, mkdir, open, readdir, rmdir, unlink } from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { ErrorFabrica } from '../errores.js';
|
|
6
|
+
import { carpetaPropia, codigoError, escribirReemplazando } from '../rastro.js';
|
|
7
|
+
/** `true` si el proceso `pid` sigue vivo (también cuando existe pero no se puede señalar). */
|
|
8
|
+
export function procesoVivo(pid) {
|
|
9
|
+
if (!Number.isInteger(pid) || pid <= 0)
|
|
10
|
+
return false;
|
|
11
|
+
try {
|
|
12
|
+
process.kill(pid, 0);
|
|
13
|
+
return true;
|
|
14
|
+
}
|
|
15
|
+
catch (error) {
|
|
16
|
+
return codigoError(error) === 'EPERM';
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
const rutaCandado = (home) => path.join(home, '.nexakit', 'encargos', '.candado');
|
|
20
|
+
/** Lee un archivo de candado sin seguir enlaces; `null` si no existe. */
|
|
21
|
+
function inspeccionar(archivo) {
|
|
22
|
+
try {
|
|
23
|
+
const info = lstatSync(archivo, { throwIfNoEntry: false });
|
|
24
|
+
if (info === undefined)
|
|
25
|
+
return null;
|
|
26
|
+
const ilegible = { crudo: null, datos: null, mtimeMs: info.mtimeMs };
|
|
27
|
+
if (!info.isFile() || info.size > 4096)
|
|
28
|
+
return ilegible;
|
|
29
|
+
const fd = openSync(archivo, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
30
|
+
try {
|
|
31
|
+
const crudo = readFileSync(fd, 'utf8');
|
|
32
|
+
let datos = null;
|
|
33
|
+
try {
|
|
34
|
+
const dato = JSON.parse(crudo);
|
|
35
|
+
if (typeof dato === 'object' && dato !== null) {
|
|
36
|
+
const { pid, id, fecha } = dato;
|
|
37
|
+
if (typeof pid === 'number')
|
|
38
|
+
datos = { pid, id: typeof id === 'string' ? id : null, fecha: typeof fecha === 'string' ? fecha : '' };
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
datos = null;
|
|
43
|
+
}
|
|
44
|
+
return { crudo, datos, mtimeMs: info.mtimeMs };
|
|
45
|
+
}
|
|
46
|
+
finally {
|
|
47
|
+
closeSync(fd);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/** Lee el candado global de encargos sin seguir enlaces; `null` si no existe o no se entiende. */
|
|
55
|
+
export function leerCandado(home) {
|
|
56
|
+
return inspeccionar(rutaCandado(home))?.datos ?? null;
|
|
57
|
+
}
|
|
58
|
+
/** El encargo vivo que tiene el candado (de este u otro proceso), o `null`. */
|
|
59
|
+
export function encargoVivo(home) {
|
|
60
|
+
const dato = leerCandado(home);
|
|
61
|
+
return dato !== null && procesoVivo(dato.pid) ? dato : null;
|
|
62
|
+
}
|
|
63
|
+
/** Lanza si hay un encargo vivo: los recorridos de la fábrica no arrancan mientras tanto. */
|
|
64
|
+
export function exigirSinEncargo(home) {
|
|
65
|
+
const vivo = encargoVivo(home);
|
|
66
|
+
if (vivo !== null) {
|
|
67
|
+
throw new ErrorFabrica(`Ya hay un encargo en curso (${vivo.id ?? 'preparándose'}, proceso ${vivo.pid}); espera a que termine o cancélalo`);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/** Un candado vacío o ilegible solo se da por muerto pasado este tiempo: puede estar escribiéndose. */
|
|
71
|
+
export const GRACIA_ILEGIBLE_MS = 30_000;
|
|
72
|
+
const OTRO_EN_MARCHA = 'Hay otro encargo en marcha; vuelve a intentarlo en unos segundos';
|
|
73
|
+
export class ErrorCandadoOcupado extends ErrorFabrica {
|
|
74
|
+
}
|
|
75
|
+
/** Escribe `texto` en un archivo nuevo (`wx`, `0o600`); falla con `EEXIST` si ya existe. */
|
|
76
|
+
async function crearExclusivo(archivo, texto) {
|
|
77
|
+
const fd = await open(archivo, 'wx', 0o600);
|
|
78
|
+
try {
|
|
79
|
+
await fd.chmod(0o600);
|
|
80
|
+
await fd.writeFile(texto);
|
|
81
|
+
}
|
|
82
|
+
finally {
|
|
83
|
+
await fd.close();
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Enlaza el temporal ya escrito con el nombre del candado (`link` falla con `EEXIST` si ya hay uno). Ante cualquier otro
|
|
88
|
+
* error de `link` (sin enlaces duros: `EPERM`, `ENOTSUP`, `EXDEV`, `ENOSYS`, FAT, red, Windows...) recurre a `wx`.
|
|
89
|
+
*/
|
|
90
|
+
async function enlazarOCrear(temporal, archivo, texto, enlazar) {
|
|
91
|
+
try {
|
|
92
|
+
await enlazar(temporal, archivo);
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
if (codigoError(error) === 'EEXIST')
|
|
96
|
+
throw error;
|
|
97
|
+
await crearExclusivo(archivo, texto);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Publica el candado de forma atómica: escribe un temporal completo y lo enlaza, de modo que nadie lee nunca un candado
|
|
102
|
+
* a medias. `enlazar` solo se inyecta en pruebas.
|
|
103
|
+
*/
|
|
104
|
+
export async function publicarCandado(archivo, texto, enlazar = link) {
|
|
105
|
+
const temporal = `${archivo}.${randomBytes(6).toString('hex')}.tmp`;
|
|
106
|
+
try {
|
|
107
|
+
await crearExclusivo(temporal, texto);
|
|
108
|
+
await enlazarOCrear(temporal, archivo, texto, enlazar);
|
|
109
|
+
}
|
|
110
|
+
finally {
|
|
111
|
+
await unlink(temporal).catch(() => { });
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/** `true` si lo inspeccionado ahora es exactamente lo que se juzgó muerto. */
|
|
115
|
+
const mismoCandado = (juzgado, actual) => {
|
|
116
|
+
if (actual === null || actual.crudo !== juzgado.crudo)
|
|
117
|
+
return false;
|
|
118
|
+
if (juzgado.datos !== null)
|
|
119
|
+
return actual.datos?.pid === juzgado.datos.pid && actual.datos.fecha === juzgado.datos.fecha;
|
|
120
|
+
return Date.now() - actual.mtimeMs > GRACIA_ILEGIBLE_MS;
|
|
121
|
+
};
|
|
122
|
+
/** Borra una entrada sin seguir enlaces: un enlace simbólico se quita a sí mismo, un directorio vacío se quita con `rmdir`. */
|
|
123
|
+
async function quitarSinSeguir(ruta) {
|
|
124
|
+
const info = lstatSync(ruta, { throwIfNoEntry: false });
|
|
125
|
+
if (info === undefined)
|
|
126
|
+
return;
|
|
127
|
+
if (info.isDirectory())
|
|
128
|
+
await rmdir(ruta);
|
|
129
|
+
else
|
|
130
|
+
await unlink(ruta);
|
|
131
|
+
}
|
|
132
|
+
/** Borra los temporales (`.candado.*.tmp`, `.candado.*.muerto`) con más de 30 s: restos de un proceso que murió a medias. */
|
|
133
|
+
async function limpiarTemporales(archivo) {
|
|
134
|
+
const carpeta = path.dirname(archivo);
|
|
135
|
+
let nombres;
|
|
136
|
+
try {
|
|
137
|
+
nombres = await readdir(carpeta);
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
for (const nombre of nombres) {
|
|
143
|
+
if (!nombre.startsWith(`${path.basename(archivo)}.`) || !/\.(?:tmp|muerto)$/u.test(nombre))
|
|
144
|
+
continue;
|
|
145
|
+
const ruta = path.join(carpeta, nombre);
|
|
146
|
+
try {
|
|
147
|
+
const info = lstatSync(ruta, { throwIfNoEntry: false });
|
|
148
|
+
if (info === undefined || info.isDirectory() || Date.now() - info.mtimeMs <= GRACIA_ILEGIBLE_MS)
|
|
149
|
+
continue;
|
|
150
|
+
await unlink(ruta);
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
// Otro proceso lo borró antes o no se puede: se deja.
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Roba un candado juzgado muerto. Solo quien crea el directorio auxiliar `.candado.robo` (con `mkdir`, atómico) puede
|
|
159
|
+
* robar; dentro vuelve a inspeccionar `.candado` y, si sigue siendo exactamente el juzgado, lo borra y publica el suyo.
|
|
160
|
+
* Devuelve `true` si lo tomó y `false` si hay que volver a juzgar. Si no puede, lanza «Hay otro encargo en marcha».
|
|
161
|
+
*/
|
|
162
|
+
async function robarCandado(archivo, juzgado, texto, opciones) {
|
|
163
|
+
const robo = `${archivo}.robo`;
|
|
164
|
+
try {
|
|
165
|
+
await mkdir(robo, { mode: 0o700 });
|
|
166
|
+
}
|
|
167
|
+
catch (error) {
|
|
168
|
+
const codigo = codigoError(error);
|
|
169
|
+
if (codigo === 'ENOENT')
|
|
170
|
+
return false;
|
|
171
|
+
if (codigo !== 'EEXIST')
|
|
172
|
+
throw error;
|
|
173
|
+
const info = lstatSync(robo, { throwIfNoEntry: false });
|
|
174
|
+
if (info === undefined)
|
|
175
|
+
return false;
|
|
176
|
+
if (Date.now() - info.mtimeMs <= GRACIA_ILEGIBLE_MS)
|
|
177
|
+
throw new ErrorCandadoOcupado(OTRO_EN_MARCHA);
|
|
178
|
+
// Auxiliar abandonado por un proceso que murió a medias: se borra y se vuelve a intentar.
|
|
179
|
+
await quitarSinSeguir(robo).catch(() => { });
|
|
180
|
+
return false;
|
|
181
|
+
}
|
|
182
|
+
try {
|
|
183
|
+
await opciones.alAntesDeRobar?.();
|
|
184
|
+
const actual = inspeccionar(archivo);
|
|
185
|
+
if (actual === null)
|
|
186
|
+
return false;
|
|
187
|
+
if (!mismoCandado(juzgado, actual))
|
|
188
|
+
throw new ErrorCandadoOcupado(OTRO_EN_MARCHA);
|
|
189
|
+
await quitarSinSeguir(archivo);
|
|
190
|
+
try {
|
|
191
|
+
await publicarCandado(archivo, texto);
|
|
192
|
+
}
|
|
193
|
+
catch (error) {
|
|
194
|
+
if (codigoError(error) === 'EEXIST')
|
|
195
|
+
return false;
|
|
196
|
+
throw error;
|
|
197
|
+
}
|
|
198
|
+
return true;
|
|
199
|
+
}
|
|
200
|
+
finally {
|
|
201
|
+
await rmdir(robo).catch(() => { });
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Toma el candado global de encargos, `~/.nexakit/encargos/.candado`, publicado de forma atómica con `0o600`. Si existe
|
|
206
|
+
* con un proceso vivo, lanza. Si el proceso murió (o está vacío o ilegible desde hace más de 30 s), lo roba con un
|
|
207
|
+
* candado auxiliar creado con `mkdir` (`.candado.robo`): dentro vuelve a comprobar que sigue siendo el candado juzgado
|
|
208
|
+
* (si no, se rinde) y lo sustituye por el suyo. Antes borra los temporales con más de 30 s.
|
|
209
|
+
*/
|
|
210
|
+
export async function tomarCandadoEncargos(home, opciones = {}) {
|
|
211
|
+
const nexakit = path.join(home, '.nexakit');
|
|
212
|
+
await mkdir(nexakit, { recursive: true, mode: 0o700 });
|
|
213
|
+
await carpetaPropia(nexakit, 'Los encargos');
|
|
214
|
+
await carpetaPropia(path.join(nexakit, 'encargos'), 'Los encargos');
|
|
215
|
+
return tomarCandadoArchivo(rutaCandado(home), opciones);
|
|
216
|
+
}
|
|
217
|
+
/** Toma un candado en una carpeta privada que el llamador ya comprobó. */
|
|
218
|
+
export async function tomarCandadoArchivo(archivo, opciones = {}) {
|
|
219
|
+
await limpiarTemporales(archivo);
|
|
220
|
+
let datos = {
|
|
221
|
+
pid: process.pid, id: null, fecha: new Date().toISOString(), nonce: randomBytes(16).toString('hex'),
|
|
222
|
+
};
|
|
223
|
+
const contenido = (actual) => `${JSON.stringify(actual)}\n`;
|
|
224
|
+
let propios = contenido(datos);
|
|
225
|
+
let tomado = false;
|
|
226
|
+
for (let intento = 0; intento < 5 && !tomado; intento += 1) {
|
|
227
|
+
try {
|
|
228
|
+
await publicarCandado(archivo, propios);
|
|
229
|
+
tomado = true;
|
|
230
|
+
}
|
|
231
|
+
catch (error) {
|
|
232
|
+
if (codigoError(error) !== 'EEXIST')
|
|
233
|
+
throw error;
|
|
234
|
+
const juzgado = inspeccionar(archivo);
|
|
235
|
+
if (juzgado === null)
|
|
236
|
+
continue;
|
|
237
|
+
const fecha = Date.parse(juzgado.datos?.fecha ?? '');
|
|
238
|
+
const caducado = opciones.caducidadMs !== undefined &&
|
|
239
|
+
(!Number.isFinite(fecha) || Date.now() - fecha > opciones.caducidadMs);
|
|
240
|
+
if (!caducado && juzgado.datos !== null && procesoVivo(juzgado.datos.pid)) {
|
|
241
|
+
throw new ErrorCandadoOcupado(`Ya hay un encargo en curso (${juzgado.datos.id ?? 'preparándose'}, proceso ${juzgado.datos.pid}); espera a que termine o cancélalo`);
|
|
242
|
+
}
|
|
243
|
+
if (juzgado.datos === null && Date.now() - juzgado.mtimeMs <= GRACIA_ILEGIBLE_MS)
|
|
244
|
+
throw new ErrorCandadoOcupado(OTRO_EN_MARCHA);
|
|
245
|
+
tomado = await robarCandado(archivo, juzgado, propios, opciones);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
if (!tomado)
|
|
249
|
+
throw new ErrorCandadoOcupado('No se pudo tomar el candado de encargos; vuelve a intentarlo');
|
|
250
|
+
const esPropio = () => inspeccionar(archivo)?.crudo === propios;
|
|
251
|
+
const vigente = () => esPropio() && (opciones.caducidadMs === undefined || Date.now() - Date.parse(datos.fecha) <= opciones.caducidadMs);
|
|
252
|
+
const actualizar = async (cambios) => {
|
|
253
|
+
if (!esPropio())
|
|
254
|
+
return;
|
|
255
|
+
const siguientes = { ...datos, ...cambios };
|
|
256
|
+
const nuevo = contenido(siguientes);
|
|
257
|
+
await escribirReemplazando(archivo, nuevo, () => {
|
|
258
|
+
if (!vigente())
|
|
259
|
+
throw new ErrorCandadoOcupado(OTRO_EN_MARCHA);
|
|
260
|
+
});
|
|
261
|
+
propios = nuevo;
|
|
262
|
+
datos = siguientes;
|
|
263
|
+
};
|
|
264
|
+
return {
|
|
265
|
+
asignarId: (id) => actualizar({ id }),
|
|
266
|
+
renovar: () => actualizar({ fecha: new Date().toISOString() }),
|
|
267
|
+
vigente,
|
|
268
|
+
async liberar() {
|
|
269
|
+
if (!esPropio())
|
|
270
|
+
return;
|
|
271
|
+
await unlink(archivo).catch(() => { });
|
|
272
|
+
},
|
|
273
|
+
};
|
|
274
|
+
}
|