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,301 @@
|
|
|
1
|
+
import { constants } from 'node:fs';
|
|
2
|
+
import { open } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { setTimeout } from 'node:timers/promises';
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
import { calidadTexto, compararPorCalidad, compararPorCosteExacto, mismoCandidato, UMBRALES } from '../decision.js';
|
|
7
|
+
import { ErrorFabrica } from '../errores.js';
|
|
8
|
+
import { cuantil05, MAX_BYTES, MAX_PARAMETRO, sumarBeta } from '../evidencia.js';
|
|
9
|
+
import { leerCriterio } from '../preferencias.js';
|
|
10
|
+
import { carpetaPropia, escribirReemplazando, lstatSiExiste } from '../rastro.js';
|
|
11
|
+
import { ErrorCandadoOcupado, tomarCandadoArchivo } from './candado.js';
|
|
12
|
+
import type { EstadoEncargo, IAEncargo, InformeEncargo } from './ejecutar.js';
|
|
13
|
+
|
|
14
|
+
const ARCHIVO = 'evidencia-encargos.json';
|
|
15
|
+
const MIN_OBSERVACIONES = 3;
|
|
16
|
+
const MAX_OBSERVACIONES = 200;
|
|
17
|
+
const MAX_FILAS = 50;
|
|
18
|
+
const CADUCIDAD_CANDADO_MS = 5 * 60_000;
|
|
19
|
+
const PERIODO_EXPLORACION = 4;
|
|
20
|
+
const IAS = ['codex', 'antigravity'] as const;
|
|
21
|
+
|
|
22
|
+
export const ResultadoValoracion = z.enum(['aplicado', 'corregido', 'descartado']);
|
|
23
|
+
export type ResultadoValoracion = z.infer<typeof ResultadoValoracion>;
|
|
24
|
+
|
|
25
|
+
const Observacion = z.object({
|
|
26
|
+
id: z.string().min(1),
|
|
27
|
+
fecha: z.iso.datetime().optional(),
|
|
28
|
+
valor: z.union([z.literal(0), z.literal(0.5), z.literal(1)]).nullable(),
|
|
29
|
+
tokens: z.number().positive(),
|
|
30
|
+
segundos: z.number().nonnegative(),
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
const Clave = z.object({
|
|
34
|
+
ia: z.enum(IAS),
|
|
35
|
+
modelo: z.string().min(1),
|
|
36
|
+
esfuerzo: z.string().min(1).nullable(),
|
|
37
|
+
});
|
|
38
|
+
type Clave = z.infer<typeof Clave>;
|
|
39
|
+
|
|
40
|
+
const Fila = Clave.extend({
|
|
41
|
+
alfa: z.number().min(1).max(MAX_PARAMETRO),
|
|
42
|
+
beta: z.number().min(1).max(MAX_PARAMETRO),
|
|
43
|
+
observaciones: z.number().int().nonnegative(),
|
|
44
|
+
pendientes: z.number().int().nonnegative().default(0),
|
|
45
|
+
tokensMedios: z.number().nonnegative(),
|
|
46
|
+
segundosMedios: z.number().nonnegative(),
|
|
47
|
+
corte: z.iso.datetime().optional(),
|
|
48
|
+
encargos: z.array(Observacion).min(1),
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
const Evidencia = z.object({
|
|
52
|
+
version: z.literal(1),
|
|
53
|
+
turnoExploracion: z.number().int().min(0).max(PERIODO_EXPLORACION - 1),
|
|
54
|
+
fracasosSinMedida: z.object({
|
|
55
|
+
codex: z.number().int().nonnegative(),
|
|
56
|
+
antigravity: z.number().int().nonnegative(),
|
|
57
|
+
}).default(() => ({ codex: 0, antigravity: 0 })),
|
|
58
|
+
filas: z.array(Fila),
|
|
59
|
+
}).refine(({ filas }) => {
|
|
60
|
+
const claves = new Set<string>();
|
|
61
|
+
const ids = new Set<string>();
|
|
62
|
+
for (const { ia, modelo, esfuerzo, encargos, observaciones, pendientes } of filas) {
|
|
63
|
+
const clave = JSON.stringify([ia, modelo, esfuerzo]);
|
|
64
|
+
if (claves.has(clave)) return false;
|
|
65
|
+
claves.add(clave);
|
|
66
|
+
const sinValorar = encargos.filter(({ valor }) => valor === null).length;
|
|
67
|
+
if (sinValorar > pendientes || encargos.length - sinValorar > observaciones) return false;
|
|
68
|
+
for (const { id } of encargos) {
|
|
69
|
+
if (ids.has(id)) return false;
|
|
70
|
+
ids.add(id);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return true;
|
|
74
|
+
});
|
|
75
|
+
type Evidencia = z.infer<typeof Evidencia>;
|
|
76
|
+
type Fila = z.infer<typeof Fila>;
|
|
77
|
+
|
|
78
|
+
function recortarHistorial(fila: Fila): void {
|
|
79
|
+
const expulsados = fila.encargos.splice(0, Math.max(0, fila.encargos.length - MAX_OBSERVACIONES));
|
|
80
|
+
for (const { fecha } of expulsados) {
|
|
81
|
+
if (fecha !== undefined && (fila.corte === undefined || fecha > fila.corte)) fila.corte = fecha;
|
|
82
|
+
}
|
|
83
|
+
// También corrige los pendientes expulsados por versiones anteriores.
|
|
84
|
+
fila.pendientes = fila.encargos.filter(({ valor }) => valor === null).length;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function serializarRecortando(evidencia: Evidencia): string {
|
|
88
|
+
const filas = evidencia.filas.map((fila) => ({
|
|
89
|
+
fila,
|
|
90
|
+
fecha: fila.encargos.reduce((ultima, { fecha }) => fecha !== undefined && fecha > ultima ? fecha : ultima, ''),
|
|
91
|
+
}));
|
|
92
|
+
filas.sort((a, b) => a.fila.observaciones - b.fila.observaciones || a.fecha.localeCompare(b.fecha));
|
|
93
|
+
const expulsar = () => {
|
|
94
|
+
const siguiente = filas.shift();
|
|
95
|
+
if (siguiente !== undefined) evidencia.filas.splice(evidencia.filas.indexOf(siguiente.fila), 1);
|
|
96
|
+
};
|
|
97
|
+
while (evidencia.filas.length > MAX_FILAS) expulsar();
|
|
98
|
+
let texto = `${JSON.stringify(evidencia)}\n`;
|
|
99
|
+
while (Buffer.byteLength(texto) > MAX_BYTES) {
|
|
100
|
+
expulsar();
|
|
101
|
+
texto = `${JSON.stringify(evidencia)}\n`;
|
|
102
|
+
}
|
|
103
|
+
return texto;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async function leerEvidencia(home: string): Promise<Evidencia> {
|
|
107
|
+
const vacia: Evidencia = { version: 1, turnoExploracion: 0, fracasosSinMedida: { codex: 0, antigravity: 0 }, filas: [] };
|
|
108
|
+
const nexakit = path.join(home, '.nexakit');
|
|
109
|
+
const fabrica = path.join(nexakit, 'fabrica');
|
|
110
|
+
for (const carpeta of [nexakit, fabrica]) {
|
|
111
|
+
const info = await lstatSiExiste(carpeta);
|
|
112
|
+
if (info === null) return vacia;
|
|
113
|
+
if (!info.isDirectory()) throw new ErrorFabrica(`La evidencia de encargos requiere una carpeta real en ${carpeta}`);
|
|
114
|
+
}
|
|
115
|
+
const ruta = path.join(fabrica, ARCHIVO);
|
|
116
|
+
const info = await lstatSiExiste(ruta);
|
|
117
|
+
if (info === null) return vacia;
|
|
118
|
+
if (!info.isFile() || info.nlink > 1) throw new ErrorFabrica('La evidencia de encargos debe ser un archivo normal sin enlaces');
|
|
119
|
+
const archivo = await open(ruta, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
120
|
+
try {
|
|
121
|
+
const abierto = await archivo.stat();
|
|
122
|
+
if (!abierto.isFile() || abierto.nlink > 1) throw new ErrorFabrica('La evidencia de encargos debe ser un archivo normal sin enlaces');
|
|
123
|
+
if (abierto.size > MAX_BYTES) throw new ErrorFabrica('La evidencia de encargos supera 1 MiB');
|
|
124
|
+
const bytes = Buffer.alloc(MAX_BYTES + 1);
|
|
125
|
+
let longitud = 0;
|
|
126
|
+
while (longitud < bytes.length) {
|
|
127
|
+
const { bytesRead } = await archivo.read(bytes, longitud, bytes.length - longitud, null);
|
|
128
|
+
if (bytesRead === 0) break;
|
|
129
|
+
longitud += bytesRead;
|
|
130
|
+
}
|
|
131
|
+
if (longitud > MAX_BYTES) throw new ErrorFabrica('La evidencia de encargos supera 1 MiB');
|
|
132
|
+
const contenido = bytes.toString('utf8', 0, longitud);
|
|
133
|
+
let datos: unknown;
|
|
134
|
+
try {
|
|
135
|
+
datos = JSON.parse(contenido);
|
|
136
|
+
} catch {
|
|
137
|
+
throw new ErrorFabrica('El formato de la evidencia de encargos no es válido');
|
|
138
|
+
}
|
|
139
|
+
const evidencia = Evidencia.safeParse(datos);
|
|
140
|
+
if (!evidencia.success) throw new ErrorFabrica('El formato de la evidencia de encargos no es válido');
|
|
141
|
+
for (const fila of evidencia.data.filas) recortarHistorial(fila);
|
|
142
|
+
return evidencia.data;
|
|
143
|
+
} finally {
|
|
144
|
+
await archivo.close();
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Serializa las actualizaciones de CLI, MCP y encargos, incluso entre procesos. */
|
|
149
|
+
async function actualizarEvidencia<T>(home: string, cambiar: (evidencia: Evidencia) => { valor: T; guardar: boolean }): Promise<T> {
|
|
150
|
+
const nexakit = path.join(home, '.nexakit');
|
|
151
|
+
const fabrica = path.join(nexakit, 'fabrica');
|
|
152
|
+
await carpetaPropia(nexakit, 'La evidencia de encargos');
|
|
153
|
+
await carpetaPropia(fabrica, 'La evidencia de encargos');
|
|
154
|
+
const rutaCandado = path.join(fabrica, '.candado-evidencia-encargos');
|
|
155
|
+
const limite = Date.now() + 5_000;
|
|
156
|
+
for (;;) {
|
|
157
|
+
const candado = await tomarCandadoArchivo(rutaCandado, { caducidadMs: CADUCIDAD_CANDADO_MS }).catch((error: unknown) => {
|
|
158
|
+
if (!(error instanceof ErrorCandadoOcupado)) throw error;
|
|
159
|
+
if (Date.now() >= limite) throw new ErrorFabrica('La evidencia de encargos está ocupada; vuelve a intentarlo');
|
|
160
|
+
return null;
|
|
161
|
+
});
|
|
162
|
+
if (candado === null) {
|
|
163
|
+
await setTimeout(25);
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
try {
|
|
167
|
+
const evidencia = await leerEvidencia(home);
|
|
168
|
+
const { valor, guardar } = cambiar(evidencia);
|
|
169
|
+
if (guardar) {
|
|
170
|
+
const texto = serializarRecortando(evidencia);
|
|
171
|
+
await escribirReemplazando(path.join(fabrica, ARCHIVO), texto, async () => {
|
|
172
|
+
await candado.renovar();
|
|
173
|
+
if (!candado.vigente()) throw new ErrorFabrica('Caducó el candado de evidencia de encargos; vuelve a intentarlo');
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
return valor;
|
|
177
|
+
} finally {
|
|
178
|
+
await candado.liberar();
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const VALORES = { aplicado: 1, corregido: 0.5, descartado: 0 } as const;
|
|
184
|
+
const FRACASOS = new Set<EstadoEncargo>(['invalido', 'fallido', 'tiempo-agotado']);
|
|
185
|
+
|
|
186
|
+
/** Actualiza los acumulados con la diferencia respecto de la valoración anterior. */
|
|
187
|
+
function anotar(evidencia: Evidencia, clave: Clave, medida: z.infer<typeof Observacion>, automatica: boolean): boolean {
|
|
188
|
+
const anterior = evidencia.filas.find((fila) => fila.encargos.some(({ id }) => id === medida.id));
|
|
189
|
+
const fila = evidencia.filas.find((f) => mismoCandidato(f, clave));
|
|
190
|
+
if (anterior !== undefined && anterior !== fila) throw new ErrorFabrica('El informe no coincide con la IA, modelo o esfuerzo ya registrados');
|
|
191
|
+
const indice = fila?.encargos.findIndex(({ id }) => id === medida.id) ?? -1;
|
|
192
|
+
const previa = fila?.encargos[indice];
|
|
193
|
+
if (previa !== undefined && (automatica || previa.valor === medida.valor)) return false;
|
|
194
|
+
if (!automatica && previa === undefined && fila?.corte !== undefined &&
|
|
195
|
+
medida.fecha !== undefined && medida.fecha <= fila.corte) {
|
|
196
|
+
throw new ErrorFabrica('El encargo ya no está en el historial de valoraciones de este modelo');
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const nuevasValoradas = Number(medida.valor !== null && (previa === undefined || previa.valor === null));
|
|
200
|
+
const aciertos = (medida.valor ?? 0) - (previa?.valor ?? 0);
|
|
201
|
+
const observaciones = (fila?.observaciones ?? 0) + nuevasValoradas;
|
|
202
|
+
const media = (anterior: number, valor: number): number =>
|
|
203
|
+
nuevasValoradas === 0 ? anterior : anterior + (valor - anterior) / observaciones;
|
|
204
|
+
const encargos = [...(fila?.encargos ?? [])];
|
|
205
|
+
if (previa === undefined) encargos.push(medida);
|
|
206
|
+
else encargos[indice] = { ...previa, fecha: previa.fecha ?? medida.fecha, valor: medida.valor };
|
|
207
|
+
const actualizada: Fila = {
|
|
208
|
+
...clave,
|
|
209
|
+
...sumarBeta(fila, aciertos, nuevasValoradas - aciertos),
|
|
210
|
+
observaciones,
|
|
211
|
+
pendientes: 0,
|
|
212
|
+
tokensMedios: media(fila?.tokensMedios ?? 0, previa?.tokens ?? medida.tokens),
|
|
213
|
+
segundosMedios: media(fila?.segundosMedios ?? 0, previa?.segundos ?? medida.segundos),
|
|
214
|
+
corte: fila?.corte,
|
|
215
|
+
encargos,
|
|
216
|
+
};
|
|
217
|
+
recortarHistorial(actualizada);
|
|
218
|
+
if (fila === undefined) evidencia.filas.push(actualizada);
|
|
219
|
+
else evidencia.filas[evidencia.filas.indexOf(fila)] = actualizada;
|
|
220
|
+
return true;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function datosDeObservacion(informe: InformeEncargo, valor: z.infer<typeof Observacion>['valor']) {
|
|
224
|
+
const clave = Clave.safeParse(informe);
|
|
225
|
+
const fecha = Observacion.shape.fecha.safeParse(informe.fecha);
|
|
226
|
+
const medida = Observacion.safeParse({ id: informe.id, fecha: fecha.data, valor, tokens: informe.tokens?.total, segundos: informe.segundos });
|
|
227
|
+
return clave.success && medida.success ? { clave: clave.data, medida: medida.data } : null;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
export async function registrarValoracion(home: string, informe: InformeEncargo, resultado: ResultadoValoracion): Promise<boolean> {
|
|
231
|
+
const soloDescartado = FRACASOS.has(informe.estado) || informe.estado === 'sin-cambios';
|
|
232
|
+
if (soloDescartado && resultado !== 'descartado') {
|
|
233
|
+
throw new ErrorFabrica('Un encargo inválido, fallido, con tiempo agotado o sin cambios solo admite la valoración «descartado»');
|
|
234
|
+
}
|
|
235
|
+
if (informe.estado === 'cancelado') return false;
|
|
236
|
+
if (informe.estado !== 'ok' && !soloDescartado) throw new ErrorFabrica('El estado del informe del encargo no es válido');
|
|
237
|
+
const datos = datosDeObservacion(informe, VALORES[resultado]);
|
|
238
|
+
if (datos === null) return false;
|
|
239
|
+
return actualizarEvidencia(home, (evidencia) => ({
|
|
240
|
+
valor: true,
|
|
241
|
+
guardar: anotar(evidencia, datos.clave, datos.medida, false),
|
|
242
|
+
}));
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
export async function registrarEjecucion(home: string, informe: InformeEncargo, avanzarExploracion: boolean): Promise<void> {
|
|
246
|
+
if (informe.estado === 'cancelado') return;
|
|
247
|
+
const fracaso = FRACASOS.has(informe.estado);
|
|
248
|
+
const datos = datosDeObservacion(informe, fracaso ? 0 : null);
|
|
249
|
+
const fracasoSinMedida = fracaso && datos === null ? informe.ia : null;
|
|
250
|
+
if (datos === null && !avanzarExploracion && fracasoSinMedida === null) return;
|
|
251
|
+
await actualizarEvidencia(home, (evidencia) => {
|
|
252
|
+
if (avanzarExploracion) evidencia.turnoExploracion = (evidencia.turnoExploracion + 1) % PERIODO_EXPLORACION;
|
|
253
|
+
if (fracasoSinMedida !== null) evidencia.fracasosSinMedida[fracasoSinMedida] += 1;
|
|
254
|
+
const anotado = datos !== null && anotar(evidencia, datos.clave, datos.medida, true);
|
|
255
|
+
return { valor: undefined, guardar: avanzarExploracion || anotado || fracasoSinMedida !== null };
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
export async function hayEvidenciaDeEncargos(home: string, disponibles: readonly IAEncargo[]): Promise<boolean> {
|
|
260
|
+
const evidencia = await leerEvidencia(home);
|
|
261
|
+
return disponibles.some((ia) => totalDeIA(evidencia, ia) >= MIN_OBSERVACIONES);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function totalDeIA({ filas, fracasosSinMedida }: Evidencia, ia: IAEncargo): number {
|
|
265
|
+
return filas.reduce((total, fila) => total + (fila.ia === ia ? fila.observaciones + fila.pendientes : 0), fracasosSinMedida[ia]);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
export async function elegirConEvidencia<T extends Clave>(
|
|
269
|
+
home: string,
|
|
270
|
+
candidatos: readonly T[],
|
|
271
|
+
normales: readonly T[],
|
|
272
|
+
): Promise<{ eleccion: T | null; explicacion?: string; avanzarExploracion: boolean; exploracion?: true }> {
|
|
273
|
+
const criterio = await leerCriterio(home);
|
|
274
|
+
const evidencia = await leerEvidencia(home);
|
|
275
|
+
const { filas, turnoExploracion } = evidencia;
|
|
276
|
+
const explorable = normales.find(({ ia }) => totalDeIA(evidencia, ia) < MIN_OBSERVACIONES);
|
|
277
|
+
const avanzarExploracion = explorable !== undefined &&
|
|
278
|
+
candidatos.some(({ ia }) => totalDeIA(evidencia, ia) >= MIN_OBSERVACIONES);
|
|
279
|
+
if (avanzarExploracion && turnoExploracion === PERIODO_EXPLORACION - 1) {
|
|
280
|
+
return {
|
|
281
|
+
eleccion: explorable,
|
|
282
|
+
explicacion: `Elección: se prueba ${explorable.ia} a propósito porque aún tiene pocos encargos valorados`,
|
|
283
|
+
avanzarExploracion,
|
|
284
|
+
exploracion: true,
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
const medidos = candidatos.flatMap((candidato) => {
|
|
288
|
+
const fila = filas.find((f) => mismoCandidato(f, candidato) && f.observaciones >= MIN_OBSERVACIONES && f.pendientes <= f.observaciones);
|
|
289
|
+
return fila === undefined ? [] : [{ candidato, fila, calidad: cuantil05(fila.alfa, fila.beta), costeConocido: true }];
|
|
290
|
+
});
|
|
291
|
+
const baratos = criterio === 'barato' ? medidos.filter(({ calidad }) => calidad >= UMBRALES.bajo) : [];
|
|
292
|
+
const mejor = baratos.length > 0 ? baratos.sort(compararPorCosteExacto)[0] : medidos.sort(compararPorCalidad)[0];
|
|
293
|
+
if (mejor === undefined) return { eleccion: null, avanzarExploracion };
|
|
294
|
+
const { candidato, calidad, fila } = mejor;
|
|
295
|
+
const nombre = [candidato.ia, candidato.modelo, candidato.esfuerzo].filter(Boolean).join(' ');
|
|
296
|
+
return {
|
|
297
|
+
eleccion: candidato,
|
|
298
|
+
explicacion: `Elección: por tus encargos anteriores, ${nombre} (${fila.observaciones} encargos valorados, calidad estimada ≥ ${calidadTexto(calidad)}; criterio global: ${criterio})`,
|
|
299
|
+
avanzarExploracion,
|
|
300
|
+
};
|
|
301
|
+
}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Análisis del parche que devuelve un encargo (`git diff --binary --no-renames`), hecho sobre los MISMOS bytes que se
|
|
3
|
+
* guardan en `cambios.diff`: rutas, modos y destinos de los enlaces simbólicos salen del parche y no del disco, que la
|
|
4
|
+
* IA (o un proceso que dejara vivo) podría cambiar entre el diff y la comprobación.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/** Una entrada del parche: un archivo creado, cambiado o borrado. */
|
|
8
|
+
export interface EntradaParche {
|
|
9
|
+
/** Ruta relativa, con `/`. */
|
|
10
|
+
ruta: string;
|
|
11
|
+
/** Modo nuevo (`120000` enlace, `160000` gitlink, `000000` borrado); `''` si el parche no lo dice. */
|
|
12
|
+
modo: string;
|
|
13
|
+
/** Destino del enlace simbólico (solo con modo `120000`); `null` si el parche no permite leerlo con certeza. */
|
|
14
|
+
destino?: string | null;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const ESCAPES: Record<string, number> = { a: 7, b: 8, t: 9, n: 10, v: 11, f: 12, r: 13, '"': 34, '\\': 92 };
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Lee una ruta entrecomillada al estilo C de git (`"a/raro\"q"`) desde `inicio` (la comilla). Devuelve sus bytes y la
|
|
21
|
+
* posición siguiente a la comilla de cierre, o `null` si está mal formada.
|
|
22
|
+
*/
|
|
23
|
+
function leerEntrecomillada(linea: string, inicio: number): { bytes: number[]; fin: number } | null {
|
|
24
|
+
const bytes: number[] = [];
|
|
25
|
+
for (let i = inicio + 1; i < linea.length; i += 1) {
|
|
26
|
+
const c = linea[i] as string;
|
|
27
|
+
if (c === '"') return { bytes, fin: i + 1 };
|
|
28
|
+
if (c !== '\\') {
|
|
29
|
+
bytes.push(c.charCodeAt(0) & 0xff);
|
|
30
|
+
continue;
|
|
31
|
+
}
|
|
32
|
+
const s = linea[i + 1];
|
|
33
|
+
if (s === undefined) return null;
|
|
34
|
+
const escape = ESCAPES[s];
|
|
35
|
+
if (/[0-7]/u.test(s)) {
|
|
36
|
+
const octal = linea.slice(i + 1, i + 4);
|
|
37
|
+
if (!/^[0-7]{3}$/u.test(octal)) return null;
|
|
38
|
+
bytes.push(Number.parseInt(octal, 8) & 0xff);
|
|
39
|
+
i += 3;
|
|
40
|
+
} else if (escape !== undefined) {
|
|
41
|
+
bytes.push(escape);
|
|
42
|
+
i += 1;
|
|
43
|
+
} else return null;
|
|
44
|
+
}
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Texto `latin1` (un carácter por byte) a UTF-8. */
|
|
49
|
+
const deBytes = (texto: string): string => Buffer.from(texto, 'latin1').toString('utf8');
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Ruta de una cabecera `diff --git a/<ruta> b/<ruta>` (sin renombrados las dos son iguales). `null` si no se puede leer
|
|
53
|
+
* con certeza.
|
|
54
|
+
*/
|
|
55
|
+
function rutaDeCabecera(linea: string): string | null {
|
|
56
|
+
const resto = linea.slice('diff --git '.length);
|
|
57
|
+
if (resto.startsWith('"')) {
|
|
58
|
+
const a = leerEntrecomillada(resto, 0);
|
|
59
|
+
if (a === null || resto[a.fin] !== ' ') return null;
|
|
60
|
+
const segundo = resto.slice(a.fin + 1);
|
|
61
|
+
const b = segundo.startsWith('"') ? leerEntrecomillada(segundo, 0) : null;
|
|
62
|
+
const textoA = Buffer.from(a.bytes).toString('latin1');
|
|
63
|
+
const textoB = b === null ? segundo : Buffer.from(b.bytes).toString('latin1');
|
|
64
|
+
if (!textoA.startsWith('a/') || !textoB.startsWith('b/') || textoA.slice(2) !== textoB.slice(2)) return null;
|
|
65
|
+
return deBytes(textoA.slice(2));
|
|
66
|
+
}
|
|
67
|
+
// Sin comillas: `a/<ruta> b/<ruta>`, con la misma ruta dos veces (puede llevar espacios).
|
|
68
|
+
if ((resto.length - 5) % 2 !== 0 || !resto.startsWith('a/')) return null;
|
|
69
|
+
const largo = (resto.length - 5) / 2;
|
|
70
|
+
const ruta = resto.slice(2, 2 + largo);
|
|
71
|
+
if (resto.slice(2 + largo) !== ` b/${ruta}`) return null;
|
|
72
|
+
return deBytes(ruta);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
interface Borrador {
|
|
76
|
+
ruta: string;
|
|
77
|
+
modo: string;
|
|
78
|
+
/** Líneas del lado nuevo (contexto y añadidas) de todos los trozos. */
|
|
79
|
+
nuevas: string[];
|
|
80
|
+
/** La última línea nueva no acaba en salto de línea. */
|
|
81
|
+
sinSaltoFinal: boolean;
|
|
82
|
+
trozos: number;
|
|
83
|
+
/** El primer trozo empieza en la línea 1 (o 0, archivo nuevo) del lado nuevo. */
|
|
84
|
+
desdeElPrincipio: boolean;
|
|
85
|
+
binario: boolean;
|
|
86
|
+
valida: boolean;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function destinoDe(b: Borrador): string | null {
|
|
90
|
+
// Un destino de enlace es una sola línea sin salto final; cualquier otra forma no se puede leer con certeza.
|
|
91
|
+
if (b.binario || b.trozos !== 1 || !b.desdeElPrincipio || b.nuevas.length !== 1 || !b.sinSaltoFinal) return null;
|
|
92
|
+
return deBytes(b.nuevas[0] as string);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Entradas del parche, en su orden. Una cabecera que no se puede leer da una entrada con ruta `''` y modo `''`, para
|
|
97
|
+
* que quien analiza falle cerrado.
|
|
98
|
+
*/
|
|
99
|
+
export function analizarParche(parche: Buffer): EntradaParche[] {
|
|
100
|
+
const entradas: EntradaParche[] = [];
|
|
101
|
+
let actual: Borrador | undefined;
|
|
102
|
+
let enTrozo = false;
|
|
103
|
+
let ultimaFueNueva = false;
|
|
104
|
+
const cerrar = (): void => {
|
|
105
|
+
if (actual === undefined) return;
|
|
106
|
+
const entrada: EntradaParche = { ruta: actual.valida ? actual.ruta : '', modo: actual.valida ? actual.modo : '' };
|
|
107
|
+
if (actual.modo === '120000') entrada.destino = actual.valida ? destinoDe(actual) : null;
|
|
108
|
+
entradas.push(entrada);
|
|
109
|
+
actual = undefined;
|
|
110
|
+
};
|
|
111
|
+
for (const linea of parche.toString('latin1').split('\n')) {
|
|
112
|
+
if (linea.startsWith('diff --git ')) {
|
|
113
|
+
cerrar();
|
|
114
|
+
const ruta = rutaDeCabecera(linea);
|
|
115
|
+
actual = { ruta: ruta ?? '', modo: '', nuevas: [], sinSaltoFinal: false, trozos: 0, desdeElPrincipio: false, binario: false, valida: ruta !== null };
|
|
116
|
+
enTrozo = false;
|
|
117
|
+
ultimaFueNueva = false;
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
if (actual === undefined) continue;
|
|
121
|
+
if (linea.startsWith('@@ ')) {
|
|
122
|
+
enTrozo = true;
|
|
123
|
+
actual.trozos += 1;
|
|
124
|
+
const nuevo = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/u.exec(linea);
|
|
125
|
+
if (actual.trozos === 1) actual.desdeElPrincipio = nuevo !== null && Number(nuevo[1]) <= 1;
|
|
126
|
+
ultimaFueNueva = false;
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
if (enTrozo) {
|
|
130
|
+
const c = linea[0];
|
|
131
|
+
if (c === '+' || c === ' ') {
|
|
132
|
+
actual.nuevas.push(linea.slice(1));
|
|
133
|
+
actual.sinSaltoFinal = false;
|
|
134
|
+
ultimaFueNueva = true;
|
|
135
|
+
} else if (c === '\\') {
|
|
136
|
+
if (ultimaFueNueva) actual.sinSaltoFinal = true;
|
|
137
|
+
} else if (c === '-') ultimaFueNueva = false;
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
// Cabecera extendida de la entrada.
|
|
141
|
+
let m: RegExpExecArray | null;
|
|
142
|
+
if ((m = /^new file mode (\d{6})$/u.exec(linea)) !== null) actual.modo = m[1] as string;
|
|
143
|
+
else if (/^deleted file mode \d{6}$/u.test(linea)) actual.modo = '000000';
|
|
144
|
+
else if ((m = /^new mode (\d{6})$/u.exec(linea)) !== null) actual.modo = m[1] as string;
|
|
145
|
+
else if ((m = /^index [0-9a-f]+\.\.[0-9a-f]+ (\d{6})$/u.exec(linea)) !== null) {
|
|
146
|
+
if (actual.modo === '') actual.modo = m[1] as string;
|
|
147
|
+
} else if (linea === 'GIT binary patch' || linea.startsWith('Binary files ')) actual.binario = true;
|
|
148
|
+
}
|
|
149
|
+
cerrar();
|
|
150
|
+
return entradas;
|
|
151
|
+
}
|