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
|
@@ -0,0 +1,287 @@
|
|
|
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
|
+
|
|
8
|
+
/** `true` si el proceso `pid` sigue vivo (también cuando existe pero no se puede señalar). */
|
|
9
|
+
export function procesoVivo(pid: number): boolean {
|
|
10
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
11
|
+
try {
|
|
12
|
+
process.kill(pid, 0);
|
|
13
|
+
return true;
|
|
14
|
+
} catch (error) {
|
|
15
|
+
return codigoError(error) === 'EPERM';
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface DatosCandado {
|
|
20
|
+
pid: number;
|
|
21
|
+
/** Id del encargo; `null` hasta que existe su worktree. */
|
|
22
|
+
id: string | null;
|
|
23
|
+
fecha: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const rutaCandado = (home: string): string => path.join(home, '.nexakit', 'encargos', '.candado');
|
|
27
|
+
|
|
28
|
+
interface Inspeccion {
|
|
29
|
+
/** Texto tal cual; `null` si no es un archivo normal o es demasiado grande. */
|
|
30
|
+
crudo: string | null;
|
|
31
|
+
datos: DatosCandado | null;
|
|
32
|
+
mtimeMs: number;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Lee un archivo de candado sin seguir enlaces; `null` si no existe. */
|
|
36
|
+
function inspeccionar(archivo: string): Inspeccion | null {
|
|
37
|
+
try {
|
|
38
|
+
const info = lstatSync(archivo, { throwIfNoEntry: false });
|
|
39
|
+
if (info === undefined) return null;
|
|
40
|
+
const ilegible: Inspeccion = { crudo: null, datos: null, mtimeMs: info.mtimeMs };
|
|
41
|
+
if (!info.isFile() || info.size > 4096) return ilegible;
|
|
42
|
+
const fd = openSync(archivo, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
43
|
+
try {
|
|
44
|
+
const crudo = readFileSync(fd, 'utf8');
|
|
45
|
+
let datos: DatosCandado | null = null;
|
|
46
|
+
try {
|
|
47
|
+
const dato: unknown = JSON.parse(crudo);
|
|
48
|
+
if (typeof dato === 'object' && dato !== null) {
|
|
49
|
+
const { pid, id, fecha } = dato as { pid?: unknown; id?: unknown; fecha?: unknown };
|
|
50
|
+
if (typeof pid === 'number') datos = { pid, id: typeof id === 'string' ? id : null, fecha: typeof fecha === 'string' ? fecha : '' };
|
|
51
|
+
}
|
|
52
|
+
} catch {
|
|
53
|
+
datos = null;
|
|
54
|
+
}
|
|
55
|
+
return { crudo, datos, mtimeMs: info.mtimeMs };
|
|
56
|
+
} finally {
|
|
57
|
+
closeSync(fd);
|
|
58
|
+
}
|
|
59
|
+
} catch {
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Lee el candado global de encargos sin seguir enlaces; `null` si no existe o no se entiende. */
|
|
65
|
+
export function leerCandado(home: string): DatosCandado | null {
|
|
66
|
+
return inspeccionar(rutaCandado(home))?.datos ?? null;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** El encargo vivo que tiene el candado (de este u otro proceso), o `null`. */
|
|
70
|
+
export function encargoVivo(home: string): DatosCandado | null {
|
|
71
|
+
const dato = leerCandado(home);
|
|
72
|
+
return dato !== null && procesoVivo(dato.pid) ? dato : null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Lanza si hay un encargo vivo: los recorridos de la fábrica no arrancan mientras tanto. */
|
|
76
|
+
export function exigirSinEncargo(home: string): void {
|
|
77
|
+
const vivo = encargoVivo(home);
|
|
78
|
+
if (vivo !== null) {
|
|
79
|
+
throw new ErrorFabrica(`Ya hay un encargo en curso (${vivo.id ?? 'preparándose'}, proceso ${vivo.pid}); espera a que termine o cancélalo`);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export interface CandadoEncargos {
|
|
84
|
+
/** Anota el id del encargo en cuanto existe su worktree. */
|
|
85
|
+
asignarId(id: string): Promise<void>;
|
|
86
|
+
/** Renueva la fecha si el candado sigue siendo propio. */
|
|
87
|
+
renovar(): Promise<void>;
|
|
88
|
+
/** Comprueba que sigue siendo suyo y, si tiene caducidad, que aún puede escribir. */
|
|
89
|
+
vigente(): boolean;
|
|
90
|
+
/** Lo libera, pero solo si sigue siendo de este proceso. */
|
|
91
|
+
liberar(): Promise<void>;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Un candado vacío o ilegible solo se da por muerto pasado este tiempo: puede estar escribiéndose. */
|
|
95
|
+
export const GRACIA_ILEGIBLE_MS = 30_000;
|
|
96
|
+
|
|
97
|
+
const OTRO_EN_MARCHA = 'Hay otro encargo en marcha; vuelve a intentarlo en unos segundos';
|
|
98
|
+
|
|
99
|
+
export class ErrorCandadoOcupado extends ErrorFabrica {}
|
|
100
|
+
|
|
101
|
+
type OperacionLink = (existente: string, nuevo: string) => Promise<void>;
|
|
102
|
+
|
|
103
|
+
/** Escribe `texto` en un archivo nuevo (`wx`, `0o600`); falla con `EEXIST` si ya existe. */
|
|
104
|
+
async function crearExclusivo(archivo: string, texto: string): Promise<void> {
|
|
105
|
+
const fd = await open(archivo, 'wx', 0o600);
|
|
106
|
+
try {
|
|
107
|
+
await fd.chmod(0o600);
|
|
108
|
+
await fd.writeFile(texto);
|
|
109
|
+
} finally {
|
|
110
|
+
await fd.close();
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Enlaza el temporal ya escrito con el nombre del candado (`link` falla con `EEXIST` si ya hay uno). Ante cualquier otro
|
|
116
|
+
* error de `link` (sin enlaces duros: `EPERM`, `ENOTSUP`, `EXDEV`, `ENOSYS`, FAT, red, Windows...) recurre a `wx`.
|
|
117
|
+
*/
|
|
118
|
+
async function enlazarOCrear(temporal: string, archivo: string, texto: string, enlazar: OperacionLink): Promise<void> {
|
|
119
|
+
try {
|
|
120
|
+
await enlazar(temporal, archivo);
|
|
121
|
+
} catch (error) {
|
|
122
|
+
if (codigoError(error) === 'EEXIST') throw error;
|
|
123
|
+
await crearExclusivo(archivo, texto);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Publica el candado de forma atómica: escribe un temporal completo y lo enlaza, de modo que nadie lee nunca un candado
|
|
129
|
+
* a medias. `enlazar` solo se inyecta en pruebas.
|
|
130
|
+
*/
|
|
131
|
+
export async function publicarCandado(archivo: string, texto: string, enlazar: OperacionLink = link): Promise<void> {
|
|
132
|
+
const temporal = `${archivo}.${randomBytes(6).toString('hex')}.tmp`;
|
|
133
|
+
try {
|
|
134
|
+
await crearExclusivo(temporal, texto);
|
|
135
|
+
await enlazarOCrear(temporal, archivo, texto, enlazar);
|
|
136
|
+
} finally {
|
|
137
|
+
await unlink(temporal).catch(() => {});
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** `true` si lo inspeccionado ahora es exactamente lo que se juzgó muerto. */
|
|
142
|
+
const mismoCandado = (juzgado: Inspeccion, actual: Inspeccion | null): boolean => {
|
|
143
|
+
if (actual === null || actual.crudo !== juzgado.crudo) return false;
|
|
144
|
+
if (juzgado.datos !== null) return actual.datos?.pid === juzgado.datos.pid && actual.datos.fecha === juzgado.datos.fecha;
|
|
145
|
+
return Date.now() - actual.mtimeMs > GRACIA_ILEGIBLE_MS;
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
/** Borra una entrada sin seguir enlaces: un enlace simbólico se quita a sí mismo, un directorio vacío se quita con `rmdir`. */
|
|
149
|
+
async function quitarSinSeguir(ruta: string): Promise<void> {
|
|
150
|
+
const info = lstatSync(ruta, { throwIfNoEntry: false });
|
|
151
|
+
if (info === undefined) return;
|
|
152
|
+
if (info.isDirectory()) await rmdir(ruta);
|
|
153
|
+
else await unlink(ruta);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Borra los temporales (`.candado.*.tmp`, `.candado.*.muerto`) con más de 30 s: restos de un proceso que murió a medias. */
|
|
157
|
+
async function limpiarTemporales(archivo: string): Promise<void> {
|
|
158
|
+
const carpeta = path.dirname(archivo);
|
|
159
|
+
let nombres: string[];
|
|
160
|
+
try {
|
|
161
|
+
nombres = await readdir(carpeta);
|
|
162
|
+
} catch {
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
for (const nombre of nombres) {
|
|
166
|
+
if (!nombre.startsWith(`${path.basename(archivo)}.`) || !/\.(?:tmp|muerto)$/u.test(nombre)) continue;
|
|
167
|
+
const ruta = path.join(carpeta, nombre);
|
|
168
|
+
try {
|
|
169
|
+
const info = lstatSync(ruta, { throwIfNoEntry: false });
|
|
170
|
+
if (info === undefined || info.isDirectory() || Date.now() - info.mtimeMs <= GRACIA_ILEGIBLE_MS) continue;
|
|
171
|
+
await unlink(ruta);
|
|
172
|
+
} catch {
|
|
173
|
+
// Otro proceso lo borró antes o no se puede: se deja.
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Opciones internas del candado. */
|
|
179
|
+
export interface OpcionesCandado {
|
|
180
|
+
caducidadMs?: number;
|
|
181
|
+
/** Se ejecuta con el candado auxiliar de robo ya tomado y antes de volver a inspeccionar `.candado`. */
|
|
182
|
+
alAntesDeRobar?: () => void | Promise<void>;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Roba un candado juzgado muerto. Solo quien crea el directorio auxiliar `.candado.robo` (con `mkdir`, atómico) puede
|
|
187
|
+
* robar; dentro vuelve a inspeccionar `.candado` y, si sigue siendo exactamente el juzgado, lo borra y publica el suyo.
|
|
188
|
+
* Devuelve `true` si lo tomó y `false` si hay que volver a juzgar. Si no puede, lanza «Hay otro encargo en marcha».
|
|
189
|
+
*/
|
|
190
|
+
async function robarCandado(archivo: string, juzgado: Inspeccion, texto: string, opciones: OpcionesCandado): Promise<boolean> {
|
|
191
|
+
const robo = `${archivo}.robo`;
|
|
192
|
+
try {
|
|
193
|
+
await mkdir(robo, { mode: 0o700 });
|
|
194
|
+
} catch (error) {
|
|
195
|
+
const codigo = codigoError(error);
|
|
196
|
+
if (codigo === 'ENOENT') return false;
|
|
197
|
+
if (codigo !== 'EEXIST') throw error;
|
|
198
|
+
const info = lstatSync(robo, { throwIfNoEntry: false });
|
|
199
|
+
if (info === undefined) return false;
|
|
200
|
+
if (Date.now() - info.mtimeMs <= GRACIA_ILEGIBLE_MS) throw new ErrorCandadoOcupado(OTRO_EN_MARCHA);
|
|
201
|
+
// Auxiliar abandonado por un proceso que murió a medias: se borra y se vuelve a intentar.
|
|
202
|
+
await quitarSinSeguir(robo).catch(() => {});
|
|
203
|
+
return false;
|
|
204
|
+
}
|
|
205
|
+
try {
|
|
206
|
+
await opciones.alAntesDeRobar?.();
|
|
207
|
+
const actual = inspeccionar(archivo);
|
|
208
|
+
if (actual === null) return false;
|
|
209
|
+
if (!mismoCandado(juzgado, actual)) throw new ErrorCandadoOcupado(OTRO_EN_MARCHA);
|
|
210
|
+
await quitarSinSeguir(archivo);
|
|
211
|
+
try {
|
|
212
|
+
await publicarCandado(archivo, texto);
|
|
213
|
+
} catch (error) {
|
|
214
|
+
if (codigoError(error) === 'EEXIST') return false;
|
|
215
|
+
throw error;
|
|
216
|
+
}
|
|
217
|
+
return true;
|
|
218
|
+
} finally {
|
|
219
|
+
await rmdir(robo).catch(() => {});
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Toma el candado global de encargos, `~/.nexakit/encargos/.candado`, publicado de forma atómica con `0o600`. Si existe
|
|
225
|
+
* 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
|
|
226
|
+
* candado auxiliar creado con `mkdir` (`.candado.robo`): dentro vuelve a comprobar que sigue siendo el candado juzgado
|
|
227
|
+
* (si no, se rinde) y lo sustituye por el suyo. Antes borra los temporales con más de 30 s.
|
|
228
|
+
*/
|
|
229
|
+
export async function tomarCandadoEncargos(home: string, opciones: OpcionesCandado = {}): Promise<CandadoEncargos> {
|
|
230
|
+
const nexakit = path.join(home, '.nexakit');
|
|
231
|
+
await mkdir(nexakit, { recursive: true, mode: 0o700 });
|
|
232
|
+
await carpetaPropia(nexakit, 'Los encargos');
|
|
233
|
+
await carpetaPropia(path.join(nexakit, 'encargos'), 'Los encargos');
|
|
234
|
+
return tomarCandadoArchivo(rutaCandado(home), opciones);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** Toma un candado en una carpeta privada que el llamador ya comprobó. */
|
|
238
|
+
export async function tomarCandadoArchivo(archivo: string, opciones: OpcionesCandado = {}): Promise<CandadoEncargos> {
|
|
239
|
+
await limpiarTemporales(archivo);
|
|
240
|
+
let datos: DatosCandado & { nonce: string } = {
|
|
241
|
+
pid: process.pid, id: null, fecha: new Date().toISOString(), nonce: randomBytes(16).toString('hex'),
|
|
242
|
+
};
|
|
243
|
+
const contenido = (actual: typeof datos): string => `${JSON.stringify(actual)}\n`;
|
|
244
|
+
let propios = contenido(datos);
|
|
245
|
+
let tomado = false;
|
|
246
|
+
for (let intento = 0; intento < 5 && !tomado; intento += 1) {
|
|
247
|
+
try {
|
|
248
|
+
await publicarCandado(archivo, propios);
|
|
249
|
+
tomado = true;
|
|
250
|
+
} catch (error) {
|
|
251
|
+
if (codigoError(error) !== 'EEXIST') throw error;
|
|
252
|
+
const juzgado = inspeccionar(archivo);
|
|
253
|
+
if (juzgado === null) continue;
|
|
254
|
+
const fecha = Date.parse(juzgado.datos?.fecha ?? '');
|
|
255
|
+
const caducado = opciones.caducidadMs !== undefined &&
|
|
256
|
+
(!Number.isFinite(fecha) || Date.now() - fecha > opciones.caducidadMs);
|
|
257
|
+
if (!caducado && juzgado.datos !== null && procesoVivo(juzgado.datos.pid)) {
|
|
258
|
+
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`);
|
|
259
|
+
}
|
|
260
|
+
if (juzgado.datos === null && Date.now() - juzgado.mtimeMs <= GRACIA_ILEGIBLE_MS) throw new ErrorCandadoOcupado(OTRO_EN_MARCHA);
|
|
261
|
+
tomado = await robarCandado(archivo, juzgado, propios, opciones);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
if (!tomado) throw new ErrorCandadoOcupado('No se pudo tomar el candado de encargos; vuelve a intentarlo');
|
|
265
|
+
const esPropio = (): boolean => inspeccionar(archivo)?.crudo === propios;
|
|
266
|
+
const vigente = (): boolean =>
|
|
267
|
+
esPropio() && (opciones.caducidadMs === undefined || Date.now() - Date.parse(datos.fecha) <= opciones.caducidadMs);
|
|
268
|
+
const actualizar = async (cambios: Partial<Pick<DatosCandado, 'id' | 'fecha'>>): Promise<void> => {
|
|
269
|
+
if (!esPropio()) return;
|
|
270
|
+
const siguientes = { ...datos, ...cambios };
|
|
271
|
+
const nuevo = contenido(siguientes);
|
|
272
|
+
await escribirReemplazando(archivo, nuevo, () => {
|
|
273
|
+
if (!vigente()) throw new ErrorCandadoOcupado(OTRO_EN_MARCHA);
|
|
274
|
+
});
|
|
275
|
+
propios = nuevo;
|
|
276
|
+
datos = siguientes;
|
|
277
|
+
};
|
|
278
|
+
return {
|
|
279
|
+
asignarId: (id) => actualizar({ id }),
|
|
280
|
+
renovar: () => actualizar({ fecha: new Date().toISOString() }),
|
|
281
|
+
vigente,
|
|
282
|
+
async liberar(): Promise<void> {
|
|
283
|
+
if (!esPropio()) return;
|
|
284
|
+
await unlink(archivo).catch(() => {});
|
|
285
|
+
},
|
|
286
|
+
};
|
|
287
|
+
}
|