context-pilot-engine 0.7.4 → 0.8.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 (80) hide show
  1. package/dist/engine.d.ts +7 -0
  2. package/dist/engine.d.ts.map +1 -1
  3. package/dist/engine.js +38 -7
  4. package/dist/engine.js.map +1 -1
  5. package/dist/handoff.d.ts.map +1 -1
  6. package/dist/handoff.js +4 -0
  7. package/dist/handoff.js.map +1 -1
  8. package/dist/index.d.ts +24 -2
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +13 -1
  11. package/dist/index.js.map +1 -1
  12. package/dist/indexer/ignore.d.ts +15 -0
  13. package/dist/indexer/ignore.d.ts.map +1 -0
  14. package/dist/indexer/ignore.js +84 -0
  15. package/dist/indexer/ignore.js.map +1 -0
  16. package/dist/indexer/indexer.d.ts.map +1 -1
  17. package/dist/indexer/indexer.js +11 -10
  18. package/dist/indexer/indexer.js.map +1 -1
  19. package/dist/orquestador/brief.d.ts +22 -0
  20. package/dist/orquestador/brief.d.ts.map +1 -0
  21. package/dist/orquestador/brief.js +50 -0
  22. package/dist/orquestador/brief.js.map +1 -0
  23. package/dist/orquestador/conocimiento.d.ts +44 -0
  24. package/dist/orquestador/conocimiento.d.ts.map +1 -0
  25. package/dist/orquestador/conocimiento.js +143 -0
  26. package/dist/orquestador/conocimiento.js.map +1 -0
  27. package/dist/orquestador/copias.d.ts +12 -0
  28. package/dist/orquestador/copias.d.ts.map +1 -0
  29. package/dist/orquestador/copias.js +34 -0
  30. package/dist/orquestador/copias.js.map +1 -0
  31. package/dist/orquestador/guia.d.ts +37 -0
  32. package/dist/orquestador/guia.d.ts.map +1 -0
  33. package/dist/orquestador/guia.js +88 -0
  34. package/dist/orquestador/guia.js.map +1 -0
  35. package/dist/orquestador/inicio.d.ts +23 -0
  36. package/dist/orquestador/inicio.d.ts.map +1 -0
  37. package/dist/orquestador/inicio.js +201 -0
  38. package/dist/orquestador/inicio.js.map +1 -0
  39. package/dist/orquestador/lecciones.d.ts +18 -0
  40. package/dist/orquestador/lecciones.d.ts.map +1 -0
  41. package/dist/orquestador/lecciones.js +60 -0
  42. package/dist/orquestador/lecciones.js.map +1 -0
  43. package/dist/orquestador/ligero.d.ts +5 -0
  44. package/dist/orquestador/ligero.d.ts.map +1 -0
  45. package/dist/orquestador/ligero.js +7 -0
  46. package/dist/orquestador/ligero.js.map +1 -0
  47. package/dist/orquestador/medico.d.ts +55 -0
  48. package/dist/orquestador/medico.d.ts.map +1 -0
  49. package/dist/orquestador/medico.js +224 -0
  50. package/dist/orquestador/medico.js.map +1 -0
  51. package/dist/orquestador/policia.d.ts +34 -0
  52. package/dist/orquestador/policia.d.ts.map +1 -0
  53. package/dist/orquestador/policia.js +246 -0
  54. package/dist/orquestador/policia.js.map +1 -0
  55. package/dist/orquestador/reglas.d.ts +107 -0
  56. package/dist/orquestador/reglas.d.ts.map +1 -0
  57. package/dist/orquestador/reglas.js +239 -0
  58. package/dist/orquestador/reglas.js.map +1 -0
  59. package/dist/orquestador/runbooks.d.ts +36 -0
  60. package/dist/orquestador/runbooks.d.ts.map +1 -0
  61. package/dist/orquestador/runbooks.js +142 -0
  62. package/dist/orquestador/runbooks.js.map +1 -0
  63. package/dist/orquestador/texto.d.ts +7 -0
  64. package/dist/orquestador/texto.d.ts.map +1 -0
  65. package/dist/orquestador/texto.js +34 -0
  66. package/dist/orquestador/texto.js.map +1 -0
  67. package/dist/pilot/task.d.ts +6 -1
  68. package/dist/pilot/task.d.ts.map +1 -1
  69. package/dist/pilot/task.js +35 -1
  70. package/dist/pilot/task.js.map +1 -1
  71. package/dist/storage/schema.d.ts.map +1 -1
  72. package/dist/storage/schema.js +9 -0
  73. package/dist/storage/schema.js.map +1 -1
  74. package/dist/storage/sqlite.d.ts +7 -0
  75. package/dist/storage/sqlite.d.ts.map +1 -1
  76. package/dist/storage/sqlite.js +24 -3
  77. package/dist/storage/sqlite.js.map +1 -1
  78. package/dist/types.d.ts +18 -0
  79. package/dist/types.d.ts.map +1 -1
  80. package/package.json +3 -2
@@ -0,0 +1,201 @@
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "fs";
2
+ import { dirname, extname, join } from "path";
3
+ import { leerLecciones } from "./lecciones.js";
4
+ import { cargarReglas, ficheroReglas, tx } from "./reglas.js";
5
+ // Contexto al abrir sesión: el índice del feature map y las lecciones del proyecto, para que el agente los tenga
6
+ // antes de buscar a ciegas. Lo que le falte al proyecto para funcionar así (mapa, CLAUDE.md, lecciones, reglas
7
+ // propias) va en un bloque de configuración pendiente: el mapa se crea avisando; el resto, con el OK del usuario.
8
+ // Claude Code corta el texto de un hook hacia los 10.000 caracteres.
9
+ export const MAX_INICIO = 9500;
10
+ const MAX_MAPA = 4000;
11
+ /** Por debajo de esto un mapa no compensa: se encuentra todo con una búsqueda */
12
+ export const MIN_FICHEROS_MAPA = 15;
13
+ const pendienteMapa = (r) => ({
14
+ clave: "mapa_ausente",
15
+ modo: "hacer",
16
+ texto: tx("Feature map (docs/feature_map/): créalo en esta sesión con la skill feature-map, antes de la primera tarea o junto a ella. " +
17
+ "4-8 funcionalidades de usuario, cada fichero y función comprobado con grep; si tienes subagentes, reparte la localización en el barato. " +
18
+ "Desde la próxima sesión se carga solo y guía cada tarea.", "Feature map (docs/feature_map/): create it in this session with the feature-map skill, before the first task or alongside it. " +
19
+ "4-8 user-facing features, every file and function checked with grep; if you have subagents, hand the locating to the cheap one. " +
20
+ "From the next session it loads by itself and guides every task.", r),
21
+ });
22
+ const pendienteClaudeMd = (r) => ({
23
+ clave: "claude_md_ausente",
24
+ modo: "proponer",
25
+ texto: tx("CLAUDE.md: el proyecto no tiene instrucciones para agentes. Propón crearlo (/init o a mano): stack, cómo se prueba y se despliega, " +
26
+ "convenciones y ficheros que no se tocan.", "CLAUDE.md: the project has no instructions for agents. Propose creating it (/init or by hand): stack, how it is tested and deployed, " +
27
+ "conventions and files that must not be touched.", r),
28
+ });
29
+ const pendienteLecciones = (r) => ({
30
+ clave: "lecciones_ausentes",
31
+ modo: "al_corregir",
32
+ texto: tx("Lecciones (tasks/lessons.md): cuando el usuario te corrija, créalo y apunta la lección: un bloque «## título (fecha)» con una línea «- Regla: …». " +
33
+ "Se carga en cada sesión y viaja a los subagentes.", "Lessons (tasks/lessons.md): when the user corrects you, create it and record the lesson: a \"## title (date)\" block with a \"- Regla: …\" line. " +
34
+ "It is loaded in every session and travels to subagents.", r),
35
+ });
36
+ const pendienteReglas = (r) => ({
37
+ clave: "reglas_ausentes",
38
+ modo: "proponer",
39
+ texto: tx("Reglas propias (~/.context-pilot/reglas.json): ahora rigen las genéricas. Propón configurarlas con el usuario: ficheros protegidos, bases de datos " +
40
+ "cuyas tablas se cruzan entre proyectos, carpetas movidas (alias) y qué subagente hace cada tipo de trabajo. " +
41
+ "Ejemplo: docs/reglas.ejemplo.json del repo de context-pilot. Esto se propone una sola vez.", "Own rules (~/.context-pilot/reglas.json): the generic ones apply for now. Propose configuring them with the user: protected files, databases " +
42
+ "whose tables are shared across projects, moved folders (aliases) and which subagent does each kind of work. " +
43
+ "Example: docs/reglas.ejemplo.json in the context-pilot repo. This is proposed only once.", r),
44
+ });
45
+ const CODIGO = /^\.(php|js|mjs|cjs|ts|tsx|jsx|py|rb|go|rs|java|kt|cs|c|cc|cpp|h|hpp|swift|scala|vue|svelte|sql|html?)$/i;
46
+ const IGNORAR = new Set(["node_modules", "vendor", "dist", "build", "out", "target", ".git", ".next", "coverage", "__pycache__", ".venv", "venv"]);
47
+ /** Ficheros de código del proyecto, contando hasta `tope` (no hace falta el total). */
48
+ export function contarCodigo(root, tope = MIN_FICHEROS_MAPA, profundidad = 4) {
49
+ let n = 0;
50
+ const recorrer = (dir, nivel) => {
51
+ if (n >= tope || nivel > profundidad)
52
+ return;
53
+ let entradas;
54
+ try {
55
+ entradas = readdirSync(dir, { withFileTypes: true });
56
+ }
57
+ catch {
58
+ return;
59
+ }
60
+ for (const e of entradas) {
61
+ if (n >= tope)
62
+ return;
63
+ if (e.isDirectory()) {
64
+ if (!IGNORAR.has(e.name) && !e.name.startsWith("."))
65
+ recorrer(join(dir, e.name), nivel + 1);
66
+ }
67
+ else if (CODIGO.test(extname(e.name)))
68
+ n++;
69
+ }
70
+ };
71
+ recorrer(root, 0);
72
+ return n;
73
+ }
74
+ // Lo que se propone una sola vez en la máquina (no por proyecto) queda apuntado junto a las reglas
75
+ const ficheroOfrecido = () => join(dirname(ficheroReglas()), "ofrecido.json");
76
+ function yaOfrecido(clave) {
77
+ try {
78
+ return !!JSON.parse(readFileSync(ficheroOfrecido(), "utf8"))[clave];
79
+ }
80
+ catch {
81
+ return false;
82
+ }
83
+ }
84
+ function apuntarOfrecido(clave) {
85
+ try {
86
+ const f = ficheroOfrecido();
87
+ let previo = {};
88
+ try {
89
+ previo = JSON.parse(readFileSync(f, "utf8"));
90
+ }
91
+ catch {
92
+ previo = {};
93
+ }
94
+ mkdirSync(dirname(f), { recursive: true });
95
+ writeFileSync(f, JSON.stringify({ ...previo, [clave]: new Date().toISOString() }, null, 2));
96
+ }
97
+ catch {
98
+ // si no se puede apuntar, se volverá a proponer
99
+ }
100
+ }
101
+ const activo = (reglas, clave) => (reglas.medico[clave] ?? "aviso") !== "apagado";
102
+ const tieneInstrucciones = (root) => ["CLAUDE.md", "AGENTS.md", join(".claude", "CLAUDE.md")].some((f) => existsSync(join(root, f)));
103
+ /** Lo que le falta al proyecto, en el orden en que conviene hacerlo. */
104
+ export function pendientesDe(root, reglas = cargarReglas()) {
105
+ if (contarCodigo(root) < MIN_FICHEROS_MAPA)
106
+ return [];
107
+ const out = [];
108
+ if (!existsSync(join(root, "docs", "feature_map", "README.md")) && activo(reglas, "mapa_ausente"))
109
+ out.push(pendienteMapa(reglas));
110
+ if (!tieneInstrucciones(root) && activo(reglas, "claude_md_ausente"))
111
+ out.push(pendienteClaudeMd(reglas));
112
+ if (!existsSync(join(root, "tasks", "lessons.md")) && activo(reglas, "lecciones_ausentes"))
113
+ out.push(pendienteLecciones(reglas));
114
+ if (!existsSync(ficheroReglas()) && activo(reglas, "reglas_ausentes") && !yaOfrecido("reglas_ausentes"))
115
+ out.push(pendienteReglas(reglas));
116
+ return out;
117
+ }
118
+ export function textoPendientes(pendientes, reglas = cargarReglas()) {
119
+ const etiqueta = {
120
+ hacer: tx("lo haces tú, avisando", "you do it, telling the user", reglas),
121
+ proponer: tx("solo con su OK", "only with their OK", reglas),
122
+ al_corregir: tx("cuando toque", "when it applies", reglas),
123
+ };
124
+ return (tx("CONFIGURACIÓN PENDIENTE (context-pilot). Al empezar, dile al usuario en una lista corta qué falta y qué vas a hacer; " +
125
+ "lo marcado «solo con su OK» no lo hagas hasta que lo acepte. Si rechaza algo para siempre, pon \"medico\": { \"<clave>\": \"apagado\" } " +
126
+ "en ~/.context-pilot/reglas.json (con su OK) y no se volverá a proponer.", "PENDING SETUP (context-pilot). At the start, tell the user in a short list what is missing and what you are going to do; " +
127
+ "do not do anything marked \"only with their OK\" until they accept it. If they refuse something for good, set \"medico\": { \"<key>\": \"apagado\" } " +
128
+ "in ~/.context-pilot/reglas.json (with their OK) and it will not be proposed again.", reglas) +
129
+ "\n\n" +
130
+ pendientes.map((p) => `- [${p.clave}, ${etiqueta[p.modo]}] ${p.texto}`).join("\n"));
131
+ }
132
+ export function contextoInicial(root, reglas = cargarReglas()) {
133
+ const partes = [];
134
+ const ficheros = [];
135
+ const pendientes = pendientesDe(root, reglas);
136
+ if (pendientes.length) {
137
+ partes.push(textoPendientes(pendientes, reglas));
138
+ for (const p of pendientes)
139
+ if (p.clave === "reglas_ausentes")
140
+ apuntarOfrecido(p.clave);
141
+ }
142
+ const readme = join(root, "docs", "feature_map", "README.md");
143
+ const tabla = existsSync(readme)
144
+ ? readFileSync(readme, "utf8")
145
+ .split(/\r?\n/)
146
+ .filter((l) => l.startsWith("|"))
147
+ .join("\n")
148
+ .slice(0, MAX_MAPA)
149
+ : "";
150
+ if (tabla) {
151
+ partes.push(tx("FEATURE MAP del proyecto (docs/feature_map/). Antes de buscar dónde está una funcionalidad, localízala en esta tabla y lee SOLO su mapa. Si tocas o mueves una funcionalidad, actualiza su mapa.", "Project FEATURE MAP (docs/feature_map/). Before searching for where a feature lives, find it in this table and read ONLY its map. If you touch or move a feature, update its map.", reglas) +
152
+ "\n\n" +
153
+ tabla);
154
+ ficheros.push(readme);
155
+ }
156
+ const lessons = join(root, "tasks", "lessons.md");
157
+ const texto = existsSync(lessons) ? readFileSync(lessons, "utf8").trim() : "";
158
+ if (texto) {
159
+ const cabecera = tx("LECCIONES DEL PROYECTO (tasks/lessons.md), de obligado cumplimiento:", "PROJECT LESSONS (tasks/lessons.md), mandatory:", reglas) + "\n\n";
160
+ const libre = MAX_INICIO - partes.reduce((n, p) => n + p.length + 2, 0) - cabecera.length;
161
+ if (texto.length <= libre)
162
+ partes.push(cabecera + texto);
163
+ else
164
+ partes.push(cabecera + soloReglas(root, libre, reglas));
165
+ ficheros.push(lessons);
166
+ }
167
+ for (const rel of reglas.inicio ?? []) {
168
+ const f = join(root, rel);
169
+ const extra = existsSync(f) ? readFileSync(f, "utf8").trim() : "";
170
+ if (!extra)
171
+ continue;
172
+ const cabecera = tx(`REGLAS DEL PROYECTO (${rel}), de obligado cumplimiento:`, `PROJECT RULES (${rel}), mandatory:`, reglas) + "\n\n";
173
+ const libre = MAX_INICIO - partes.reduce((n, p) => n + p.length + 2, 0) - cabecera.length;
174
+ partes.push(extra.length <= libre
175
+ ? cabecera + extra
176
+ : tx(`LECTURA OBLIGATORIA: ${rel} no cabe aquí. Léelo entero antes de empezar.`, `MANDATORY READING: ${rel} does not fit here. Read it in full before starting.`, reglas));
177
+ ficheros.push(f);
178
+ }
179
+ if (!partes.length)
180
+ return null;
181
+ return { texto: partes.join("\n\n"), ficheros, ...(pendientes.length ? { pendientes: pendientes.map((p) => p.clave) } : {}) };
182
+ }
183
+ /** Cuando el fichero no cabe: la regla de cada lección, y el fichero para el detalle. */
184
+ function soloReglas(root, libre, reglas) {
185
+ const pie = tx("\n\nSolo van las reglas; el contexto de cada una está en tasks/lessons.md.", "\n\nOnly the rules are included; the context for each one is in tasks/lessons.md.", reglas);
186
+ const lista = leerLecciones(root).map((l) => `- ${l.titulo}: ${l.regla.replace(/\s+/g, " ")}`);
187
+ const caben = [];
188
+ let largo = 0;
189
+ for (const r of lista) {
190
+ if (largo + r.length + 1 > libre - pie.length - 120)
191
+ break;
192
+ caben.push(r);
193
+ largo += r.length + 1;
194
+ }
195
+ const faltan = lista.length - caben.length;
196
+ return (caben.join("\n") +
197
+ (faltan
198
+ ? tx(`\n\nLECTURA OBLIGATORIA: faltan ${faltan} lecciones que no caben; lee tasks/lessons.md antes de empezar.`, `\n\nMANDATORY READING: ${faltan} lessons do not fit; read tasks/lessons.md before starting.`, reglas)
199
+ : pie));
200
+ }
201
+ //# sourceMappingURL=inicio.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"inicio.js","sourceRoot":"","sources":["../../src/orquestador/inicio.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,WAAW,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,IAAI,CAAC;AACrF,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC9C,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAC/C,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,EAAE,EAA2B,MAAM,aAAa,CAAC;AAEvF,iHAAiH;AACjH,+GAA+G;AAC/G,kHAAkH;AAClH,qEAAqE;AAErE,MAAM,CAAC,MAAM,UAAU,GAAG,IAAI,CAAC;AAC/B,MAAM,QAAQ,GAAG,IAAI,CAAC;AACtB,iFAAiF;AACjF,MAAM,CAAC,MAAM,iBAAiB,GAAG,EAAE,CAAC;AAgBpC,MAAM,aAAa,GAAG,CAAC,CAAS,EAAa,EAAE,CAAC,CAAC;IAC/C,KAAK,EAAE,cAAc;IACrB,IAAI,EAAE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C,EAAE,EAAE,CAAC,KAAK,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,CAAC,CAAC;IAC/F,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,KAAK,MAAM,CAAC,IAAI,KAAK,EAAE,CAAC;QACtB,IAAI,KAAK,GAAG,CAAC,CAAC,MAAM,GAAG,CAAC,GAAG,KAAK,GAAG,GAAG,CAAC,MAAM,GAAG,GAAG;YAAE,MAAM;QAC3D,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACd,KAAK,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;IACxB,CAAC;IACD,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC;IAC3C,OAAO,CACL,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC;QAChB,CAAC,MAAM;YACL,CAAC,CAAC,EAAE,CACA,mCAAmC,MAAM,iEAAiE,EAC1G,0BAA0B,MAAM,6DAA6D,EAC7F,MAAM,CACP;YACH,CAAC,CAAC,GAAG,CAAC,CACT,CAAC;AACJ,CAAC"}
@@ -0,0 +1,18 @@
1
+ export interface Leccion {
2
+ proyecto: string;
3
+ titulo: string;
4
+ /** La línea "Regla: …" si la hay; si no, el bloque recortado */
5
+ regla: string;
6
+ texto: string;
7
+ }
8
+ export declare function leerLecciones(root: string): Leccion[];
9
+ export interface LeccionPuntuada extends Leccion {
10
+ puntos: number;
11
+ comunes: string[];
12
+ }
13
+ /**
14
+ * Lecciones que comparten vocabulario con la tarea, ponderado por rareza (idf) entre todas las lecciones.
15
+ * Hacen falta ≥3 raíces en común y una puntuación mínima: una sola palabra coincidente es casualidad.
16
+ */
17
+ export declare function leccionesPara(tarea: string, lecciones: Leccion[], limite?: number, minimo?: number): LeccionPuntuada[];
18
+ //# sourceMappingURL=lecciones.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lecciones.d.ts","sourceRoot":"","sources":["../../src/orquestador/lecciones.ts"],"names":[],"mappings":"AAMA,MAAM,WAAW,OAAO;IACtB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,gEAAgE;IAChE,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;CACf;AAED,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,EAAE,CA0BrD;AAED,MAAM,WAAW,eAAgB,SAAQ,OAAO;IAC9C,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,EAAE,CAAC;CACnB;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,EAAE,MAAM,SAAI,EAAE,MAAM,SAAI,GAAG,eAAe,EAAE,CAiB5G"}
@@ -0,0 +1,60 @@
1
+ import { existsSync, readFileSync } from "fs";
2
+ import { basename, join } from "path";
3
+ import { raices } from "./texto.js";
4
+ export function leerLecciones(root) {
5
+ const f = join(root, "tasks", "lessons.md");
6
+ if (!existsSync(f))
7
+ return [];
8
+ const proyecto = basename(root);
9
+ const out = [];
10
+ let actual = null;
11
+ const cerrar = () => {
12
+ if (!actual)
13
+ return;
14
+ const texto = actual.lineas.join("\n").trim();
15
+ const regla = actual.lineas.find((l) => /^\s*-?\s*\*{0,2}Regla\*{0,2}:/i.test(l));
16
+ out.push({
17
+ proyecto,
18
+ titulo: actual.titulo,
19
+ regla: (regla ?? texto).replace(/^\s*-?\s*\*{0,2}Regla\*{0,2}:\s*/i, "").trim().slice(0, 400),
20
+ texto,
21
+ });
22
+ };
23
+ for (const l of readFileSync(f, "utf8").split(/\r?\n/)) {
24
+ const m = l.match(/^##\s+(.+)$/);
25
+ if (m) {
26
+ cerrar();
27
+ actual = { titulo: m[1].trim(), lineas: [] };
28
+ }
29
+ else if (actual)
30
+ actual.lineas.push(l);
31
+ }
32
+ cerrar();
33
+ return out;
34
+ }
35
+ /**
36
+ * Lecciones que comparten vocabulario con la tarea, ponderado por rareza (idf) entre todas las lecciones.
37
+ * Hacen falta ≥3 raíces en común y una puntuación mínima: una sola palabra coincidente es casualidad.
38
+ */
39
+ export function leccionesPara(tarea, lecciones, limite = 3, minimo = 6) {
40
+ if (lecciones.length === 0)
41
+ return [];
42
+ const bolsas = lecciones.map((l) => new Set(raices(`${l.titulo} ${l.texto}`)));
43
+ const df = new Map();
44
+ for (const b of bolsas)
45
+ for (const r of b)
46
+ df.set(r, (df.get(r) ?? 0) + 1);
47
+ const n = lecciones.length;
48
+ const pedidas = raices(tarea);
49
+ return lecciones
50
+ .map((l, i) => {
51
+ const comunes = pedidas.filter((r) => bolsas[i].has(r));
52
+ // Cada raíz común vale 1 más su rareza: con pocas lecciones manda cuántas coinciden
53
+ const puntos = comunes.reduce((s, r) => s + 1 + Math.log(n / (df.get(r) ?? 1)), 0);
54
+ return { ...l, puntos, comunes };
55
+ })
56
+ .filter((l) => l.comunes.length >= 3 && l.puntos >= minimo)
57
+ .sort((a, b) => b.puntos - a.puntos)
58
+ .slice(0, limite);
59
+ }
60
+ //# sourceMappingURL=lecciones.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lecciones.js","sourceRoot":"","sources":["../../src/orquestador/lecciones.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAC9C,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACtC,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AAYpC,MAAM,UAAU,aAAa,CAAC,IAAY;IACxC,MAAM,CAAC,GAAG,IAAI,CAAC,IAAI,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC;IAC5C,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC;QAAE,OAAO,EAAE,CAAC;IAC9B,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AAC;IACnC,CAAC,CAAC;SACD,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,IAAI,CAAC,IAAI,CAAC,CAAC,MAAM,IAAI,MAAM,CAAC;SAC1D,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC;SACnC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;AACtB,CAAC"}
@@ -0,0 +1,5 @@
1
+ export * from "./reglas.js";
2
+ export * from "./texto.js";
3
+ export * from "./policia.js";
4
+ export * from "./medico.js";
5
+ //# sourceMappingURL=ligero.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ligero.d.ts","sourceRoot":"","sources":["../../src/orquestador/ligero.ts"],"names":[],"mappings":"AAEA,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC;AAC3B,cAAc,cAAc,CAAC;AAC7B,cAAc,aAAa,CAAC"}
@@ -0,0 +1,7 @@
1
+ // Entrada ligera del orquestador para los hooks que corren en cada herramienta (pre/post):
2
+ // sin SQLite ni tree-sitter, para no pagar la carga del motor en cada llamada.
3
+ export * from "./reglas.js";
4
+ export * from "./texto.js";
5
+ export * from "./policia.js";
6
+ export * from "./medico.js";
7
+ //# sourceMappingURL=ligero.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ligero.js","sourceRoot":"","sources":["../../src/orquestador/ligero.ts"],"names":[],"mappings":"AAAA,2FAA2F;AAC3F,+EAA+E;AAC/E,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC;AAC3B,cAAc,cAAc,CAAC;AAC7B,cAAc,aAAa,CAAC"}
@@ -0,0 +1,55 @@
1
+ import { type Nivel, type Reglas } from "./reglas.js";
2
+ export interface EstadoMedico {
3
+ /** comando normalizado → fallos seguidos */
4
+ fallos: Record<string, number>;
5
+ /** ruta absoluta → ms de la última edición sin deploy posterior */
6
+ sinDeploy: Record<string, number>;
7
+ mapaPendiente: Array<{
8
+ raiz: string;
9
+ rel: string;
10
+ }>;
11
+ editados: string[];
12
+ handoffGuardado: boolean;
13
+ /** Claves de lo que ya se dijo (regla:objeto) */
14
+ dichos: string[];
15
+ sesionBloqueada?: boolean;
16
+ }
17
+ export declare const ESTADO_MEDICO_VACIO: EstadoMedico;
18
+ export interface Hallazgo {
19
+ regla: "sintaxis" | "deploy_olvidado" | "mapa_pendiente" | "bucle" | "handoff_sin_guardar" | "sesion_larga";
20
+ nivel: Nivel;
21
+ texto: string;
22
+ /** Para decir cada cosa una vez */
23
+ clave: string;
24
+ }
25
+ /** Tokens de entrada de la última respuesta del chat principal (no de subagentes). */
26
+ export declare function tokensDeContexto(transcript: string): number;
27
+ export interface AvisoSesion {
28
+ bloquear: boolean;
29
+ /** Para el usuario */
30
+ mensaje: string;
31
+ /** Para el modelo */
32
+ contexto: string;
33
+ }
34
+ export declare function revisarSesion(tokens: number, estado: EstadoMedico, reglas?: Reglas): AvisoSesion | null;
35
+ export declare function raizConMapa(fichero: string): string | null;
36
+ export interface LlamadaHerramienta {
37
+ herramienta: string;
38
+ entrada: Record<string, unknown>;
39
+ /** Texto de la respuesta (stdout+stderr, o el JSON) */
40
+ salida: string;
41
+ /** La herramienta falló (PostToolUseFailure, exit ≠ 0, error) */
42
+ fallo: boolean;
43
+ cwd: string | null;
44
+ ahora?: number;
45
+ }
46
+ export declare const esEdicion: (h: string) => boolean;
47
+ export declare const esTerminal: (h: string) => boolean;
48
+ /** Actualiza el estado con una llamada terminada. Devuelve un hallazgo inmediato (bucle) o null. */
49
+ export declare function registrar(estado: EstadoMedico, ll: LlamadaHerramienta, reglas?: Reglas): Hallazgo | null;
50
+ /** Lo pendiente al cerrar, ordenado por prioridad; el llamador decide qué se dice según el nivel. */
51
+ export declare function revisarCierre(estado: EstadoMedico, reglas?: Reglas, ahora?: number): Hallazgo[];
52
+ /** Hallazgos que se dicen (no silenciados ni dichos ya); marca los dichos en el estado. */
53
+ export declare function filtrarDichos(estado: EstadoMedico, hallazgos: Hallazgo[], niveles?: Nivel[]): Hallazgo[];
54
+ export declare const esCodigo: (f: string) => boolean;
55
+ //# sourceMappingURL=medico.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"medico.d.ts","sourceRoot":"","sources":["../../src/orquestador/medico.ts"],"names":[],"mappings":"AAEA,OAAO,EAAoB,KAAK,KAAK,EAAE,KAAK,MAAM,EAAE,MAAM,aAAa,CAAC;AAMxE,MAAM,WAAW,YAAY;IAC3B,4CAA4C;IAC5C,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC/B,mEAAmE;IACnE,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAClC,aAAa,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,GAAG,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACpD,QAAQ,EAAE,MAAM,EAAE,CAAC;IACnB,eAAe,EAAE,OAAO,CAAC;IACzB,iDAAiD;IACjD,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,eAAe,CAAC,EAAE,OAAO,CAAC;CAC3B;AAED,eAAO,MAAM,mBAAmB,EAAE,YAAiH,CAAC;AAEpJ,MAAM,WAAW,QAAQ;IACvB,KAAK,EAAE,UAAU,GAAG,iBAAiB,GAAG,gBAAgB,GAAG,OAAO,GAAG,qBAAqB,GAAG,cAAc,CAAC;IAC5G,KAAK,EAAE,KAAK,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,mCAAmC;IACnC,KAAK,EAAE,MAAM,CAAC;CACf;AAQD,sFAAsF;AACtF,wBAAgB,gBAAgB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAuB3D;AAED,MAAM,WAAW,WAAW;IAC1B,QAAQ,EAAE,OAAO,CAAC;IAClB,sBAAsB;IACtB,OAAO,EAAE,MAAM,CAAC;IAChB,qBAAqB;IACrB,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,wBAAgB,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,GAAE,MAAuB,GAAG,WAAW,GAAG,IAAI,CAkCvH;AAQD,wBAAgB,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAS1D;AAyBD,MAAM,WAAW,kBAAkB;IACjC,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACjC,uDAAuD;IACvD,MAAM,EAAE,MAAM,CAAC;IACf,iEAAiE;IACjE,KAAK,EAAE,OAAO,CAAC;IACf,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAKD,eAAO,MAAM,SAAS,GAAI,GAAG,MAAM,YAAuI,CAAC;AAC3K,eAAO,MAAM,UAAU,GAAI,GAAG,MAAM,YAA8C,CAAC;AAGnF,oGAAoG;AACpG,wBAAgB,SAAS,CAAC,MAAM,EAAE,YAAY,EAAE,EAAE,EAAE,kBAAkB,EAAE,MAAM,GAAE,MAAuB,GAAG,QAAQ,GAAG,IAAI,CAiExH;AAID,qGAAqG;AACrG,wBAAgB,aAAa,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,GAAE,MAAuB,EAAE,KAAK,SAAa,GAAG,QAAQ,EAAE,CAuDnH;AAED,2FAA2F;AAC3F,wBAAgB,aAAa,CAAC,MAAM,EAAE,YAAY,EAAE,SAAS,EAAE,QAAQ,EAAE,EAAE,OAAO,GAAE,KAAK,EAA8C,GAAG,QAAQ,EAAE,CAMnJ;AAED,eAAO,MAAM,QAAQ,GAAI,GAAG,MAAM,YAAyD,CAAC"}
@@ -0,0 +1,224 @@
1
+ import { closeSync, existsSync, openSync, readdirSync, readFileSync, readSync, statSync } from "fs";
2
+ import { dirname, extname, join, posix, relative, resolve, sep } from "path";
3
+ import { cargarReglas, tx } from "./reglas.js";
4
+ import { raizProyecto } from "./policia.js";
5
+ export const ESTADO_MEDICO_VACIO = { fallos: {}, sinDeploy: {}, mapaPendiente: [], editados: [], handoffGuardado: false, dichos: [] };
6
+ const PRIORIDAD = ["sintaxis", "deploy_olvidado", "mapa_pendiente", "bucle", "handoff_sin_guardar", "sesion_larga"];
7
+ // ---------- Sesión larga ----------
8
+ const COLA = 4 * 1024 * 1024;
9
+ /** Tokens de entrada de la última respuesta del chat principal (no de subagentes). */
10
+ export function tokensDeContexto(transcript) {
11
+ const tam = statSync(transcript).size;
12
+ const desde = Math.max(0, tam - COLA);
13
+ const buf = Buffer.alloc(tam - desde);
14
+ const fd = openSync(transcript, "r");
15
+ try {
16
+ readSync(fd, buf, 0, buf.length, desde);
17
+ }
18
+ finally {
19
+ closeSync(fd);
20
+ }
21
+ const lineas = buf.toString("utf8").split("\n");
22
+ for (let i = lineas.length - 1; i >= 0; i--) {
23
+ if (!lineas[i].includes('"usage"'))
24
+ continue;
25
+ try {
26
+ const j = JSON.parse(lineas[i]);
27
+ if (j.type !== "assistant" || j.isSidechain || !j.message?.usage)
28
+ continue;
29
+ const u = j.message.usage;
30
+ return (u.input_tokens ?? 0) + (u.cache_read_input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0);
31
+ }
32
+ catch {
33
+ continue;
34
+ }
35
+ }
36
+ return 0;
37
+ }
38
+ export function revisarSesion(tokens, estado, reglas = cargarReglas()) {
39
+ const m = reglas.medico;
40
+ if (m.sesion_larga === "apagado" || m.sesion_larga === "silencio_trazado" || tokens < m.sesion_aviso)
41
+ return null;
42
+ const k = `${Math.round(tokens / 1000)}k`;
43
+ const consejo = tx("Guarda el handoff de context-pilot y abre una sesión nueva para la siguiente tarea, o usa /compact si sigues con la misma.", "Save the context-pilot handoff and open a new session for the next task, or use /compact if you stay in this one.", reglas);
44
+ if (tokens >= m.sesion_bloqueo && m.sesion_larga === "bloqueo_unico" && !estado.sesionBloqueada) {
45
+ estado.sesionBloqueada = true;
46
+ return {
47
+ bloquear: true,
48
+ mensaje: tx(`Sesión con ${k} tokens de contexto: cada mensaje ya es muy caro. ${consejo} Si quieres seguir aquí igualmente, reenvía el mensaje.`, `Session with ${k} tokens of context: every message is now very expensive. ${consejo} If you want to carry on here anyway, resend the message.`, reglas),
49
+ contexto: "",
50
+ };
51
+ }
52
+ // El aviso es una recomendación: se dice una vez al pasar cada umbral, no en cada mensaje; seguir lo decide el usuario
53
+ const clave = tokens >= m.sesion_bloqueo ? "sesion:limite" : "sesion:aviso";
54
+ if (estado.dichos.includes(clave))
55
+ return null;
56
+ estado.dichos.push(clave);
57
+ return {
58
+ bloquear: false,
59
+ mensaje: tx(`Sesión larga: ${k} tokens de contexto. ${consejo}`, `Long session: ${k} tokens of context. ${consejo}`, reglas),
60
+ contexto: tx(`La sesión lleva ${k} tokens de contexto. Al terminar la tarea en curso, guarda el handoff (context-pilot, action set) y menciona una vez al usuario que puede abrir una sesión nueva o usar /compact; si decide seguir, no lo repitas.`, `The session is at ${k} tokens of context. When the current task is done, save the handoff (context-pilot, action set) and mention once to the user that they can open a new session or use /compact; if they decide to continue, do not repeat it.`, reglas),
61
+ };
62
+ }
63
+ // ---------- Registro tras cada herramienta ----------
64
+ const EXCLUIR_MAPA = /(^|\/)(docs|tasks|old|vendor|node_modules|\.claude|\.git|TAREAS)\/|-MO-|\.min\.js$/i;
65
+ const DESPLEGABLE = /\.(php|js|css|html?|json|sql)$/i;
66
+ const NO_DESPLEGABLE = /(^|\/)(docs|tasks|\.claude|\.git|node_modules)\//i;
67
+ export function raizConMapa(fichero) {
68
+ let dir = dirname(resolve(fichero));
69
+ for (let i = 0; i < 12; i++) {
70
+ if (existsSync(join(dir, "docs", "feature_map")))
71
+ return dir;
72
+ const arriba = dirname(dir);
73
+ if (arriba === dir)
74
+ break;
75
+ dir = arriba;
76
+ }
77
+ return null;
78
+ }
79
+ function textoMapa(raiz) {
80
+ const dir = join(raiz, "docs", "feature_map");
81
+ try {
82
+ return readdirSync(dir)
83
+ .filter((n) => /\.md$/i.test(n))
84
+ .map((n) => readFileSync(join(dir, n), "utf8"))
85
+ .join("\n");
86
+ }
87
+ catch {
88
+ return null;
89
+ }
90
+ }
91
+ const nombrado = (texto, rel) => texto.includes(rel) || texto.includes(posix.basename(rel));
92
+ function anotarMapa(estado, raiz, rel) {
93
+ if (!/\.(php|js)$/i.test(rel) || EXCLUIR_MAPA.test(rel))
94
+ return;
95
+ const texto = textoMapa(raiz);
96
+ if (texto === null || nombrado(texto, rel))
97
+ return;
98
+ if (!estado.mapaPendiente.some((p) => p.raiz === raiz && p.rel === rel))
99
+ estado.mapaPendiente.push({ raiz, rel });
100
+ }
101
+ const normalizarComando = (c) => c.replace(/\s+/g, " ").trim().slice(0, 300);
102
+ const ficheroDe = (e) => [e.file_path, e.notebook_path, e.path, e.Path, e.TargetFile, e.AbsolutePath].find((v) => typeof v === "string" && v.length > 0) ?? null;
103
+ export const esEdicion = (h) => /^(Edit|Write|MultiEdit|NotebookEdit|edit_file|write_file|write_to_file|replace_file_content|multi_replace_file_content)$/.test(h);
104
+ export const esTerminal = (h) => /^(Bash|PowerShell|run_command)$/.test(h);
105
+ const comandoDe = (e) => String(e.command ?? e.CommandLine ?? "");
106
+ /** Actualiza el estado con una llamada terminada. Devuelve un hallazgo inmediato (bucle) o null. */
107
+ export function registrar(estado, ll, reglas = cargarReglas()) {
108
+ const ahora = ll.ahora ?? Date.now();
109
+ const h = ll.herramienta;
110
+ if (/handoff$/.test(h) && (ll.entrada.action === "set" || ll.entrada.action === "nota" || (!ll.entrada.action && ll.entrada.summary))) {
111
+ estado.handoffGuardado = true;
112
+ }
113
+ if (esEdicion(h) && !ll.fallo) {
114
+ const f = ficheroDe(ll.entrada);
115
+ if (f) {
116
+ const abs = resolve(ll.cwd ?? ".", f);
117
+ if (!estado.editados.includes(abs))
118
+ estado.editados.push(abs);
119
+ const raiz = raizProyecto(abs);
120
+ if (raiz) {
121
+ const rel = relative(raiz, abs).split(sep).join("/");
122
+ if (DESPLEGABLE.test(rel) && !NO_DESPLEGABLE.test(rel))
123
+ estado.sinDeploy[abs] = ahora;
124
+ }
125
+ // Ficheros nuevos de código sin mapa (Write crea; Edit no)
126
+ if (/^(Write|write_file|write_to_file)$/.test(h)) {
127
+ const rm = raizConMapa(abs);
128
+ if (rm)
129
+ anotarMapa(estado, rm, relative(rm, abs).split(sep).join("/"));
130
+ }
131
+ }
132
+ return null;
133
+ }
134
+ if (!esTerminal(h))
135
+ return null;
136
+ const cmd = comandoDe(ll.entrada);
137
+ if (/deploy\.js/.test(cmd)) {
138
+ // Cada "OK <destino> <rel> md5=…" es un fichero subido bien; quita sus pendientes
139
+ const subidos = new Set([...ll.salida.matchAll(/^OK\s+\S+\s+(\S+)\s+md5=/gm)].map((m) => m[1]));
140
+ if (subidos.size) {
141
+ for (const abs of Object.keys(estado.sinDeploy)) {
142
+ const raiz = raizProyecto(abs);
143
+ if (raiz && subidos.has(relative(raiz, abs).split(sep).join("/")))
144
+ delete estado.sinDeploy[abs];
145
+ }
146
+ }
147
+ const m = ll.salida.match(/AVISO MAPA: no aparecen en docs\/feature_map: (.+?)\. Si son/);
148
+ if (m) {
149
+ const raiz = raizConMapa(join(ll.cwd ?? process.cwd(), "x"));
150
+ if (raiz)
151
+ for (const rel of m[1].split(/,\s*/))
152
+ anotarMapa(estado, raiz, rel.trim());
153
+ }
154
+ }
155
+ const clave = normalizarComando(cmd);
156
+ if (!clave)
157
+ return null;
158
+ if (!ll.fallo) {
159
+ delete estado.fallos[clave];
160
+ return null;
161
+ }
162
+ const n = (estado.fallos[clave] ?? 0) + 1;
163
+ estado.fallos[clave] = n;
164
+ if (n < reglas.medico.fallos_seguidos)
165
+ return null;
166
+ return {
167
+ regla: "bucle",
168
+ nivel: reglas.medico.bucle,
169
+ clave: `bucle:${clave}`,
170
+ texto: tx(`El mismo comando ha fallado ${n} veces seguidas (${clave.slice(0, 120)}). Para y cambia de enfoque: lee el error entero, comprueba la ruta y el entorno, o delega el diagnóstico en el agente caro.`, `The same command has failed ${n} times in a row (${clave.slice(0, 120)}). Stop and change approach: read the whole error, check the path and the environment, or delegate the diagnosis to the expensive agent.`, reglas),
171
+ };
172
+ }
173
+ // ---------- Al cerrar el turno ----------
174
+ /** Lo pendiente al cerrar, ordenado por prioridad; el llamador decide qué se dice según el nivel. */
175
+ export function revisarCierre(estado, reglas = cargarReglas(), ahora = Date.now()) {
176
+ const m = reglas.medico;
177
+ const out = [];
178
+ estado.mapaPendiente = estado.mapaPendiente.filter((p) => {
179
+ const t = textoMapa(p.raiz);
180
+ return t !== null && !nombrado(t, p.rel);
181
+ });
182
+ if (estado.mapaPendiente.length) {
183
+ const lista = estado.mapaPendiente.map((p) => `${posix.basename(p.raiz.split(sep).join("/"))}/${p.rel}`).join(", ");
184
+ out.push({
185
+ regla: "mapa_pendiente",
186
+ nivel: m.mapa_pendiente,
187
+ clave: `mapa:${lista}`,
188
+ texto: tx(`Feature map pendiente: ${lista} no aparece(n) en docs/feature_map. Usa la skill feature-map para añadirlos a su funcionalidad (o crear su fichero y su línea en README.md). Si es un helper sin funcionalidad de usuario, nómbralo en la sección "Sin mapa" del README.md.`, `Feature map pending: ${lista} ${/,/.test(lista) ? "do" : "does"} not appear in docs/feature_map. Use the feature-map skill to add ${/,/.test(lista) ? "them" : "it"} to its feature (or create its file and its line in README.md). If it is a helper with no user-facing feature, name it in the "Sin mapa" section of README.md.`, reglas),
189
+ });
190
+ }
191
+ // Solo lo editado hace más de un instante: el turno pudo acabar justo antes del deploy
192
+ const sinDeploy = Object.keys(estado.sinDeploy).filter((f) => existsSync(f) && ahora - estado.sinDeploy[f] >= 0);
193
+ if (sinDeploy.length) {
194
+ const lista = sinDeploy.map((f) => {
195
+ const raiz = raizProyecto(f);
196
+ return raiz ? `${posix.basename(raiz.split(sep).join("/"))}/${relative(raiz, f).split(sep).join("/")}` : f;
197
+ });
198
+ out.push({
199
+ regla: "deploy_olvidado",
200
+ nivel: m.deploy_olvidado,
201
+ clave: `deploy:${lista.join(",")}`,
202
+ texto: tx(`Editado sin desplegar: ${lista.join(", ")}. Si el cambio está terminado, súbelo con node ~/.claude/hooks/deploy.js; si no, dilo en una línea.`, `Edited but not deployed: ${lista.join(", ")}. If the change is finished, upload it with node ~/.claude/hooks/deploy.js; if not, say so in one line.`, reglas),
203
+ });
204
+ }
205
+ if (estado.editados.length && !estado.handoffGuardado) {
206
+ out.push({
207
+ regla: "handoff_sin_guardar",
208
+ nivel: m.handoff_sin_guardar,
209
+ clave: `handoff:${estado.editados.length}`,
210
+ texto: tx("Hay cambios en esta sesión y no se ha guardado el handoff: guárdalo (context-pilot handoff, action set) con resumen, ficheros y pendientes.", "There are changes in this session and the handoff has not been saved: save it (context-pilot handoff, action set) with summary, files and pending steps.", reglas),
211
+ });
212
+ }
213
+ return out.sort((a, b) => PRIORIDAD.indexOf(a.regla) - PRIORIDAD.indexOf(b.regla));
214
+ }
215
+ /** Hallazgos que se dicen (no silenciados ni dichos ya); marca los dichos en el estado. */
216
+ export function filtrarDichos(estado, hallazgos, niveles = ["bloqueo_unico", "aviso", "deny", "ask"]) {
217
+ // El mapa es obligatorio: se repite en cada cierre mientras siga pendiente (el hook no bloquea dos veces seguidas)
218
+ const repetible = (h) => h.regla === "mapa_pendiente";
219
+ const decir = hallazgos.filter((h) => niveles.includes(h.nivel) && (repetible(h) || !estado.dichos.includes(h.clave)));
220
+ estado.dichos.push(...decir.filter((h) => !repetible(h)).map((h) => h.clave));
221
+ return decir;
222
+ }
223
+ export const esCodigo = (f) => /\.(php|js|mjs|cjs|ts|css|html?)$/i.test(extname(f));
224
+ //# sourceMappingURL=medico.js.map