nexakit 0.12.1 → 0.13.0

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