@designerbyron/lifecode-rag 0.0.0-stage → 1.0.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 (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +191 -2
  3. package/bin/lifecode-rag.mjs +449 -0
  4. package/client.js +2801 -0
  5. package/cordis.patch.yml +3 -0
  6. package/docs/ARCHITECTURE-v0.2.md +269 -0
  7. package/docs/AUTO-DISCOVERY.md +111 -0
  8. package/docs/AUTOMATION-POLICIES.md +232 -0
  9. package/docs/CONTRATO-v0.1.md +195 -0
  10. package/docs/EMBEDDING-PROVIDERS.md +105 -0
  11. package/docs/OBSERVABILITY.md +241 -0
  12. package/docs/PA-UI-0-API-CONTRACT.md +802 -0
  13. package/docs/PERFORMANCE-BUDGETS.md +118 -0
  14. package/docs/PROJECT-AWARE-ARCHITECTURE.md +580 -0
  15. package/docs/PROJECT-AWARE-DATA-CONTRACT.md +411 -0
  16. package/docs/PROJECT-AWARE-ERROR-CONTRACT.md +112 -0
  17. package/docs/PROJECT-AWARE-SESSION-CONTRACT.md +120 -0
  18. package/docs/WORKSPACE-API.md +239 -0
  19. package/icon.svg +7 -0
  20. package/index.js +198 -0
  21. package/lib/audit-export.mjs +70 -0
  22. package/lib/audit.mjs +120 -0
  23. package/lib/auto-context.mjs +322 -0
  24. package/lib/automation.mjs +214 -0
  25. package/lib/chunk.mjs +100 -0
  26. package/lib/config-resolve.mjs +119 -0
  27. package/lib/context.mjs +150 -0
  28. package/lib/conversation-events.mjs +145 -0
  29. package/lib/db.mjs +309 -0
  30. package/lib/diagnose.mjs +197 -0
  31. package/lib/discovery.mjs +402 -0
  32. package/lib/doctor.mjs +82 -0
  33. package/lib/embed.mjs +96 -0
  34. package/lib/embedders.mjs +103 -0
  35. package/lib/errors.mjs +227 -0
  36. package/lib/exec-context.mjs +238 -0
  37. package/lib/extract.mjs +260 -0
  38. package/lib/harness-workspaces.mjs +85 -0
  39. package/lib/hash.mjs +34 -0
  40. package/lib/ingest.mjs +239 -0
  41. package/lib/inputs.mjs +67 -0
  42. package/lib/library-state.mjs +252 -0
  43. package/lib/maintenance.mjs +113 -0
  44. package/lib/metrics.mjs +164 -0
  45. package/lib/migrate.mjs +373 -0
  46. package/lib/operations.mjs +132 -0
  47. package/lib/pa-api.mjs +517 -0
  48. package/lib/paths.mjs +345 -0
  49. package/lib/policy.mjs +125 -0
  50. package/lib/profile.mjs +128 -0
  51. package/lib/readmodel.mjs +159 -0
  52. package/lib/recovery.mjs +557 -0
  53. package/lib/registry-schema.mjs +206 -0
  54. package/lib/registry.mjs +406 -0
  55. package/lib/resolve.mjs +311 -0
  56. package/lib/retention.mjs +143 -0
  57. package/lib/revocation.mjs +124 -0
  58. package/lib/roots-structure.mjs +224 -0
  59. package/lib/schema.mjs +173 -0
  60. package/lib/scope-ops.mjs +379 -0
  61. package/lib/scope-stores.mjs +128 -0
  62. package/lib/search.mjs +345 -0
  63. package/lib/selection.mjs +150 -0
  64. package/lib/server.mjs +335 -0
  65. package/lib/session-identity.mjs +51 -0
  66. package/lib/sessions.mjs +343 -0
  67. package/lib/sync-scheduler.mjs +354 -0
  68. package/lib/sync.mjs +755 -0
  69. package/lib/tags.mjs +45 -0
  70. package/lib/tools.mjs +364 -0
  71. package/lib/trusted-roots.mjs +149 -0
  72. package/lib/worker-context.mjs +22 -0
  73. package/package.json +67 -5
@@ -0,0 +1,322 @@
1
+ /**
2
+ * Contexto recuperado antes de responder (PA6).
3
+ *
4
+ * El host expone `agent/pre-step` (waterfall) con la identidad real del agente y la señal de
5
+ * cancelación. Ahí se puede **añadir un mensaje de usuario** al lote que entra en el paso, lo que
6
+ * garantiza que el contexto viaje en la misma petición al modelo. `agent.inject()` no sirve para eso:
7
+ * su contrato dice «next pre-step», así que puede caer en el paso siguiente y perderse la petición
8
+ * actual (ver `eval/pa6/PA6-DECISIONS.md`, D-PA6-01).
9
+ *
10
+ * Reglas:
11
+ * - Desactivado por defecto (`config.autoContext.enabled`): inyectar cambia lo que ve el modelo.
12
+ * - Sólo en el primer paso de un turno y sólo con un prompt humano; nunca sobre resultados de
13
+ * herramienta ni sobre nuestro propio mensaje (evita bucles y ruido).
14
+ * - La autorización se resuelve con el MISMO camino que las herramientas (`withAuthorizedContext`):
15
+ * sin caché de grants, con revocación efectiva y cierre de almacenes.
16
+ * - Cualquier fallo se ignora: un turno sin contexto es aceptable; un turno roto por el RAG, no.
17
+ * - Dedupe por `(sessionId, turn, hash)`: el mismo texto no se inyecta dos veces en el mismo turno.
18
+ */
19
+
20
+ import { createHash, randomUUID } from 'node:crypto';
21
+ import { createEmbedder } from './embedders.mjs';
22
+ import { withAuthorizedContext } from './exec-context.mjs';
23
+ import { contextScopes, searchScopes } from './scope-ops.mjs';
24
+ import { isRagError } from './errors.mjs';
25
+
26
+ /** Kind propio en `MessageSourceMap`; los consumidores ignoran kinds que no conocen. */
27
+ export const AUTO_CONTEXT_SOURCE = Object.freeze({ kind: 'lifecode-rag', form: 'recall' });
28
+
29
+ /** Marcador visible del bloque inyectado; también sirve para reconocerlo si vuelve por el pipeline. */
30
+ export const AUTO_CONTEXT_HEADER = '[LifeCode RAG · contexto recuperado]';
31
+
32
+ const MAX_QUERY_CHARS = 1_000;
33
+ const REMEMBER_TURNS = 64;
34
+
35
+ /**
36
+ * Palabras que no aportan señal léxica. Sin esta lista la puerta de `searchScopes` se abría con
37
+ * «de», «la» o «que» y el prefijo FTS (`"de"*`) coincidía con casi cualquier documento, así que se
38
+ * inyectaba ruido en cada turno (hallazgo del adaptador, PA-quality).
39
+ */
40
+ const STOPWORDS = new Set([
41
+ 'a', 'al', 'algo', 'algún', 'alguno', 'ante', 'antes', 'aquel', 'aquí', 'así', 'aun', 'aunque',
42
+ 'bien', 'cada', 'como', 'cómo', 'con', 'contra', 'cual', 'cuál', 'cuando', 'cuándo', 'de', 'del',
43
+ 'desde', 'donde', 'dónde', 'dos', 'el', 'él', 'ella', 'ellas', 'ellos', 'en', 'entonces', 'entre',
44
+ 'era', 'es', 'esa', 'ese', 'eso', 'esta', 'está', 'estas', 'este', 'esto', 'estos', 'fue', 'ha',
45
+ 'hacia', 'hasta', 'hay', 'la', 'las', 'le', 'les', 'lo', 'los', 'más', 'me', 'mi', 'mis', 'mucho',
46
+ 'muy', 'nada', 'ni', 'no', 'nos', 'nosotros', 'o', 'otra', 'otro', 'para', 'pero', 'poco', 'por',
47
+ 'porque', 'que', 'qué', 'quien', 'quién', 'se', 'sea', 'según', 'ser', 'si', 'sí', 'sin', 'sobre',
48
+ 'solo', 'sólo', 'son', 'su', 'sus', 'tal', 'también', 'te', 'tiene', 'tienen', 'todo', 'todos', 'tu',
49
+ 'tus', 'un', 'una', 'uno', 'unos', 'y', 'ya', 'yo', 'the', 'and', 'for', 'with', 'this', 'that',
50
+ ]);
51
+
52
+ /** ¿El texto tiene al menos un término con contenido? Evita abrir la puerta con sólo stopwords. */
53
+ export function hasContentTerm(text) {
54
+ if (typeof text !== 'string') return false;
55
+ return text
56
+ .toLowerCase()
57
+ .split(/[^\p{L}\p{N}]+/u)
58
+ .some((token) => token.length >= 2 && !STOPWORDS.has(token));
59
+ }
60
+
61
+ function hashOf(text) {
62
+ return createHash('sha256').update(text, 'utf8').digest('hex');
63
+ }
64
+
65
+ /** Texto plano de los bloques de una `UserMessage` del host. */
66
+ function textOfMessage(message) {
67
+ const blocks = Array.isArray(message?.content) ? message.content : [];
68
+ const parts = [];
69
+ for (const block of blocks) {
70
+ if (block && block.type === 'text' && typeof block.text === 'string') parts.push(block.text);
71
+ }
72
+ return parts.join('\n').trim();
73
+ }
74
+
75
+ /**
76
+ * Quita los recordatorios de sistema que el host (o hooks) añaden al prompt: no son la pregunta del
77
+ * usuario y ensucian la consulta léxica.
78
+ */
79
+ export function stripSystemReminders(text) {
80
+ if (typeof text !== 'string') return '';
81
+ return text
82
+ .replace(/<system-reminder>[\s\S]*?<\/system-reminder>/gi, ' ')
83
+ .replace(/<system_reminder>[\s\S]*?<\/system_reminder>/gi, ' ')
84
+ .replace(/\s+/g, ' ')
85
+ .trim();
86
+ }
87
+
88
+ /**
89
+ * ¿Estos mensajes son un prompt humano nuevo? Se exige `source.kind === 'user'` (o ausente) y que no
90
+ * lleve el marcador de contexto inyectado. Los resultados de herramienta llegan en el mismo evento en
91
+ * pasos posteriores, y `step > 1` los descarta antes de llegar aquí.
92
+ */
93
+ export function isHumanPrompt(message) {
94
+ if (!message || message.role !== 'user') return false;
95
+ const kind = message.source?.kind;
96
+ if (typeof kind === 'string' && kind !== 'user') return false;
97
+ const text = textOfMessage(message);
98
+ if (text.length < 8) return false;
99
+ return !text.includes(AUTO_CONTEXT_HEADER);
100
+ }
101
+
102
+ /** Consulta para la recuperación: el último prompt humano del lote, sin recordatorios de sistema. */
103
+ export function queryFromMessages(messages) {
104
+ const list = Array.isArray(messages) ? messages : [];
105
+ for (let index = list.length - 1; index >= 0; index -= 1) {
106
+ const message = list[index];
107
+ if (!isHumanPrompt(message)) continue;
108
+ const text = stripSystemReminders(textOfMessage(message));
109
+ if (text.length >= 8) return text.slice(0, MAX_QUERY_CHARS);
110
+ }
111
+ return '';
112
+ }
113
+
114
+ /**
115
+ * Compone el bloque inyectado. Se recorta por `maxChars` y se numeran las citas para que el modelo
116
+ * pueda referirse a ellas; nunca se inventan fragmentos.
117
+ */
118
+ export function renderContext({ projectName = null, scopes = [], citations = [], text = '', maxChars = 1_600 } = {}) {
119
+ const body = typeof text === 'string' ? text.trim() : '';
120
+ if (!body) return '';
121
+ const scopeNames = scopes.map((scope) => scope.name).filter((name) => typeof name === 'string' && name);
122
+ const scopeLine = projectName
123
+ ? `Proyecto: ${projectName}${scopeNames.length > 0 ? ` · bibliotecas: ${scopeNames.join(', ')}` : ''}`
124
+ : '';
125
+ const header = [AUTO_CONTEXT_HEADER, scopeLine].filter(Boolean).join('\n');
126
+ const citeLine = citations.length > 0
127
+ ? `\n\nCitas: ${citations.slice(0, 20).map((cite, index) => `${index + 1}. ${cite.title || cite.uri || cite.chunkKey}`).join(' · ')}`
128
+ : '';
129
+ const budget = Math.max(200, maxChars) - header.length - citeLine.length - 2;
130
+ if (budget <= 0) return '';
131
+ const clipped = body.length > budget ? `${body.slice(0, Math.max(0, budget - 1)).trimEnd()}…` : body;
132
+ const rendered = `${header}\n\n${clipped}${citeLine}`;
133
+ return rendered.length > maxChars ? `${rendered.slice(0, maxChars - 1).trimEnd()}…` : rendered;
134
+ }
135
+
136
+ /** Construye la `UserMessage` del host sin importar nada de `@deepseek-ai/*`. */
137
+ export function contextMessage(text) {
138
+ return {
139
+ id: randomUUID(),
140
+ role: 'user',
141
+ content: [{ type: 'text', text }],
142
+ source: { ...AUTO_CONTEXT_SOURCE },
143
+ };
144
+ }
145
+
146
+ /**
147
+ * Recupera el contexto para una sesión. Devuelve `null` cuando no hay nada que inyectar o cuando la
148
+ * recuperación no es posible; nunca lanza hacia el host.
149
+ *
150
+ * @param {object} options
151
+ * @param {object} options.services Servicios del host (`env`, `workingDirectory`, `approval`…).
152
+ * @param {object} options.agent `Agent` real del host (identidad de sesión).
153
+ * @param {AbortSignal} [options.signal]
154
+ * @param {string} options.query
155
+ * @param {object} options.config
156
+ */
157
+ export async function collectContext({ services, agent, signal, query, config }) {
158
+ const policy = config.autoContext;
159
+ if (!policy.enabled || typeof query !== 'string' || query.trim() === '') return null;
160
+ if (signal?.aborted) return null;
161
+ // Sin canal de aprobación no hay egreso: con un proveedor remoto el hook automático no puede
162
+ // enviar la pregunta ni los fragmentos a un tercero, así que se recupera sólo por léxico.
163
+ const localProvider = !config?.embedding?.provider || config.embedding.provider === 'local-hash-v1';
164
+ let embedder = null;
165
+ if (localProvider) {
166
+ try {
167
+ embedder = createEmbedder(config);
168
+ } catch {
169
+ embedder = null;
170
+ }
171
+ }
172
+ const strategy = embedder ? undefined : 'fts';
173
+ return withAuthorizedContext(
174
+ { services, exec: { agent, signal, callId: 'auto-context' } },
175
+ async (ctx) => {
176
+ // Una biblioteca concedida pero todavía sin almacén no aporta nada y hace fallar el conjunto
177
+ // (la ausencia de una biblioteca no es una biblioteca vacía, PA4). Aquí se omite en vez de
178
+ // abortar el contexto del turno; las herramientas siguen fallando en cerrado.
179
+ const scopes = ctx.scopes.filter((scope) => scope.kind !== 'lib' || scope.exists !== false);
180
+ if (signal?.aborted) return null;
181
+ // Puerta léxica: con `hybrid`, la búsqueda vectorial siempre devuelve vecinos, aunque el turno no
182
+ // hable de nada indexado. Inyectar esos vecinos sería ruido y gasto de tokens en cada petición,
183
+ // así que sólo se inyecta cuando al menos un término de la consulta aparece de verdad en el
184
+ // índice (D-PA6-02). Los stopwords no cuentan como señal.
185
+ if (!hasContentTerm(query)) return null;
186
+ const lexical = await searchScopes(ctx, {
187
+ query,
188
+ limit: 1,
189
+ strategy: 'fts',
190
+ config,
191
+ embedder: null,
192
+ scopes,
193
+ now: typeof services.now === 'function' ? services.now() : Date.now(),
194
+ });
195
+ if (lexical.results.length === 0) return null;
196
+ if (signal?.aborted) return null;
197
+ const assembled = await contextScopes(ctx, {
198
+ query,
199
+ budgetTokens: policy.budgetTokens,
200
+ maxChunks: policy.maxChunks,
201
+ strategy,
202
+ scopes,
203
+ config,
204
+ embedder,
205
+ now: typeof services.now === 'function' ? services.now() : Date.now(),
206
+ });
207
+ const rendered = renderContext({
208
+ projectName: ctx.resolved?.projectName ?? null,
209
+ scopes: scopes.filter((scope) => scope.kind === 'lib'),
210
+ citations: assembled.citations ?? [],
211
+ text: assembled.text ?? '',
212
+ maxChars: policy.maxChars,
213
+ });
214
+ if (!rendered) return null;
215
+ return {
216
+ text: rendered,
217
+ tokens: assembled.tokens ?? null,
218
+ citations: assembled.citations ?? [],
219
+ scopes: scopes.map((scope) => scope.id),
220
+ };
221
+ },
222
+ );
223
+ }
224
+
225
+ /**
226
+ * Adaptador del hook: decide si en este paso toca inyectar, respeta el dedupe y devuelve la
227
+ * `UserMessage` lista o `null`. No lanza: el host no debe romperse por el RAG.
228
+ */
229
+ export function createAutoContext({ services, config, logger = console, now = () => Date.now() } = {}) {
230
+ const seen = new Map();
231
+ const warned = new Map();
232
+ const policy = config?.autoContext ?? null;
233
+
234
+ function markSeen(sessionId, turn, digest) {
235
+ let entry = seen.get(sessionId);
236
+ if (!entry || entry.size >= REMEMBER_TURNS) {
237
+ entry = new Set();
238
+ seen.set(sessionId, entry);
239
+ }
240
+ const key = `${turn}:${digest}`;
241
+ if (entry.has(key)) return false;
242
+ entry.add(key);
243
+ return true;
244
+ }
245
+
246
+ /**
247
+ * Limita el tiempo del hook: `agent/pre-step` está en el camino crítico de la respuesta, así que
248
+ * se abandona la recuperación al vencer en vez de retrasar el turno. El trabajo que no responde a
249
+ * la señal queda acotado por el timeout del proveedor (20 s) y su rechazo se ignora.
250
+ */
251
+ function withBudget(promise, timeoutMs, signal) {
252
+ const ms = Math.max(100, Number(timeoutMs) || 2_000);
253
+ let timer;
254
+ const budget = new Promise((resolve) => {
255
+ timer = setTimeout(() => resolve(null), ms);
256
+ timer.unref?.();
257
+ });
258
+ const aborted = new Promise((resolve) => {
259
+ if (!signal) return;
260
+ if (signal.aborted) resolve(null);
261
+ else signal.addEventListener('abort', () => resolve(null), { once: true });
262
+ });
263
+ promise.catch(() => {});
264
+ return Promise.race([promise, budget, aborted]).finally(() => clearTimeout(timer));
265
+ }
266
+
267
+ /** Un fallo real (registro caído, almacén corrupto, revocación) no debe ser invisible. */
268
+ function warnOnce(sessionId, code, message) {
269
+ let codes = warned.get(sessionId);
270
+ if (!codes) {
271
+ codes = new Set();
272
+ warned.set(sessionId, codes);
273
+ }
274
+ if (codes.has(code)) return;
275
+ codes.add(code);
276
+ logger.warn?.(`lifecode-rag contexto no disponible (${code}): ${message}`);
277
+ }
278
+
279
+ /**
280
+ * @param {object} payload Payload de `agent/pre-step`.
281
+ * @param {object[]} messages Mensajes que entran en el paso (ya decididos por el host).
282
+ * @returns {Promise<object|null>} `UserMessage` a añadir o `null`.
283
+ */
284
+ async function messageFor({ agent, turn, step, signal }, messages) {
285
+ const policyNow = config?.autoContext;
286
+ if (!policyNow?.enabled) return null;
287
+ if (step !== 1) return null;
288
+ if (!Number.isInteger(turn) || turn < 1) return null;
289
+ if (!agent || typeof agent !== 'object') return null;
290
+ if (signal?.aborted) return null;
291
+ const query = queryFromMessages(messages);
292
+ if (!query) return null;
293
+ const digest = hashOf(query);
294
+ if (seen.get(agent.id)?.has(`${turn}:${digest}`)) return null;
295
+ try {
296
+ const collected = await withBudget(
297
+ collectContext({ services, agent, signal, query, config }),
298
+ policyNow.timeoutMs,
299
+ signal,
300
+ );
301
+ if (!collected) return null;
302
+ // Se marca SÓLO lo que se inyectó: un fallo no consume el turno (antes se marcaba al empezar).
303
+ markSeen(agent.id, turn, digest);
304
+ logger.debug?.(`lifecode-rag contexto: ${collected.citations.length} citas, ${collected.text.length} caracteres`);
305
+ return contextMessage(collected.text);
306
+ } catch (error) {
307
+ // Revocación, almacén caído, sesión inválida…: se ignora y el turno sigue sin contexto, pero
308
+ // el operador se entera una vez por sesión en vez de no verlo nunca.
309
+ const code = isRagError(error) ? error.code : 'internal';
310
+ warnOnce(agent.id, code, error?.message ?? String(error));
311
+ return null;
312
+ }
313
+ }
314
+
315
+ return {
316
+ messageFor,
317
+ policy,
318
+ status() {
319
+ return { enabled: Boolean(config?.autoContext?.enabled), ...(config?.autoContext ?? {}) };
320
+ },
321
+ };
322
+ }
@@ -0,0 +1,214 @@
1
+ /**
2
+ * Automatización controlada (M4).
3
+ *
4
+ * La política es explícita: sólo se vigilan `automation.watchRoots` declaradas por una persona en
5
+ * `config.json`, y sólo con `automation.enabled: true`. No hay descubrimiento implícito de carpetas.
6
+ * Cada pasada:
7
+ * 1. recorre las raíces (sin seguir enlaces) y descarta los ficheros que ya están al día por sha256;
8
+ * 2. ingiere como máximo `maxFilesPerRun`, de más reciente a más antiguo, uno a uno, para poder
9
+ * cancelar entre ficheros;
10
+ * 3. audita la pasada y purga métricas fuera de retención.
11
+ *
12
+ * Nunca borra fuentes: si un fichero desaparece, se deja de reindexar y se informa como ausente.
13
+ */
14
+
15
+ import { createHash } from 'node:crypto';
16
+ import { readFileSync, statSync } from 'node:fs';
17
+
18
+ import { appendAudit } from './audit.mjs';
19
+ import { closeDatabase, openDatabase } from './db.mjs';
20
+ import { createEmbedder } from './embedders.mjs';
21
+ import { RagError } from './errors.mjs';
22
+ import { walkDirectory } from './inputs.mjs';
23
+ import { ingestFiles } from './ingest.mjs';
24
+ import { purgeMetrics, recordMetrics, retentionCutoff } from './metrics.mjs';
25
+ import { workerConfig } from './worker-context.mjs';
26
+ import { loadConfig, ragRoot } from './paths.mjs';
27
+ import { assertSupportedFormat, isProbablyBinary } from './extract.mjs';
28
+
29
+ const state = new WeakMap();
30
+
31
+ function sha256File(path) {
32
+ return createHash('sha256').update(readFileSync(path)).digest('hex');
33
+ }
34
+
35
+ function collectionFor(path, mappings) {
36
+ const entries = Object.entries(mappings ?? {}).sort((a, b) => b[0].length - a[0].length);
37
+ for (const [prefix, collection] of entries) {
38
+ if (path.toLowerCase().startsWith(prefix.toLowerCase())) return collection;
39
+ }
40
+ return 'default';
41
+ }
42
+
43
+ function knownDigests(db) {
44
+ const map = new Map();
45
+ for (const row of db.prepare('SELECT uri, sha256 FROM sources').all()) map.set(row.uri, row.sha256);
46
+ return map;
47
+ }
48
+
49
+ /** Ficheros candidatos de una raíz, ordenados por mtime descendente. */
50
+ function candidates(root, limit) {
51
+ const files = [];
52
+ walkDirectory(root, files, Math.max(limit * 20, 1_000));
53
+ const rows = [];
54
+ for (const path of files) {
55
+ try {
56
+ const stat = statSync(path);
57
+ if (!stat.isFile()) continue;
58
+ rows.push({ path, mtime: stat.mtimeMs, size: stat.size });
59
+ } catch { /* desapareció entre el recorrido y el stat */ }
60
+ }
61
+ rows.sort((a, b) => b.mtime - a.mtime);
62
+ return rows;
63
+ }
64
+
65
+ export function createAutomation({ root = ragRoot(), env = process.env, now = () => Date.now(), logger = console, config = null, dataRoot = null } = {}) {
66
+ let timer = null;
67
+ let running = false;
68
+ const status = { enabled: false, running: false, lastRunAt: null, lastResult: null, roots: [], intervalMs: null };
69
+
70
+ function currentConfig() {
71
+ return workerConfig({ config, dataRoot, root, env }).config;
72
+ }
73
+
74
+ function statusSnapshot() {
75
+ const config = currentConfig();
76
+ return {
77
+ ...status,
78
+ enabled: timer !== null,
79
+ configured: config.automation.enabled,
80
+ intervalMs: config.automation.intervalMs,
81
+ roots: config.automation.watchRoots,
82
+ };
83
+ }
84
+
85
+ async function runOnce({ signal = undefined } = {}) {
86
+ const config = currentConfig();
87
+ if (running) return { skipped: true, reason: 'already-running' };
88
+ if (!config.automation.enabled) return { skipped: true, reason: 'disabled' };
89
+ if (config.automation.watchRoots.length === 0) return { skipped: true, reason: 'no-watch-roots' };
90
+
91
+ running = true;
92
+ status.running = true;
93
+ const started = now();
94
+ const outcome = { at: started, roots: config.automation.watchRoots.length, scanned: 0, considered: 0, ingested: 0, skipped: 0, failed: 0, absent: 0, cancelled: false, errors: [] };
95
+ try {
96
+ const opened = openDatabase({ root, create: true, now: started });
97
+ let digests;
98
+ try { digests = knownDigests(opened.db); } finally { closeDatabase(opened.db); }
99
+
100
+ const pending = [];
101
+ for (const watch of config.automation.watchRoots) {
102
+ let rows;
103
+ try {
104
+ rows = candidates(watch, config.automation.maxFilesPerRun);
105
+ } catch (error) {
106
+ outcome.errors.push({ path: watch, code: error.code ?? 'internal', message: error.message });
107
+ continue;
108
+ }
109
+ outcome.scanned += rows.length;
110
+ for (const row of rows) {
111
+ if (signal?.aborted) { outcome.cancelled = true; break; }
112
+ if (!isProbablyBinary(readFileSync(row.path))) {
113
+ try { assertSupportedFormat(row.path); } catch { continue; }
114
+ } else {
115
+ continue;
116
+ }
117
+ let digest;
118
+ try { digest = sha256File(row.path); } catch { continue; }
119
+ if (digests.get(row.path) === digest) continue;
120
+ pending.push({ ...row, digest, collection: collectionFor(row.path, config.automation.collections) });
121
+ }
122
+ if (outcome.cancelled) break;
123
+ }
124
+ outcome.considered = pending.length;
125
+ pending.sort((a, b) => b.mtime - a.mtime);
126
+ const batch = pending.slice(0, config.automation.maxFilesPerRun);
127
+ const embedder = createEmbedder(config);
128
+
129
+ for (const item of batch) {
130
+ if (signal?.aborted) { outcome.cancelled = true; break; }
131
+ try {
132
+ const result = await ingestFiles({
133
+ root, files: [item.path], collection: item.collection, now: now(), config, embedder, actor: 'automation',
134
+ });
135
+ outcome.ingested += result.ingested.length;
136
+ outcome.skipped += result.skipped.length;
137
+ outcome.failed += result.errors.length;
138
+ for (const error of result.errors) outcome.errors.push(error);
139
+ } catch (error) {
140
+ outcome.failed += 1;
141
+ outcome.errors.push({ path: item.path, code: error.code ?? 'internal', message: error.message });
142
+ }
143
+ }
144
+
145
+ // Retención de métricas: sólo agregados, nunca datos de usuario.
146
+ const finished = now();
147
+ outcome.ms = finished - started;
148
+ try {
149
+ const opened2 = openDatabase({ root, create: false });
150
+ try {
151
+ if (config.metrics.enabled) purgeMetrics(opened2.db, { beforeDay: retentionCutoff(config, finished), at: finished });
152
+ appendAudit(opened2.db, {
153
+ at: finished,
154
+ actor: 'automation',
155
+ tool: 'lifecode_rag_automation',
156
+ action: 'automation.run',
157
+ target: config.automation.watchRoots.join(','),
158
+ outcome: outcome.cancelled ? 'skipped' : outcome.failed > 0 ? 'failed' : 'ok',
159
+ details: { ...outcome, errors: outcome.errors.slice(0, 20) },
160
+ });
161
+ recordMetrics(opened2.db, [
162
+ { metric: 'automation.runs', value: 1, dim: outcome.cancelled ? 'cancelled' : 'ok', at: finished },
163
+ { metric: 'automation.indexed', value: outcome.ingested, dim: 'default', at: finished },
164
+ { metric: 'automation.failed', value: outcome.failed, dim: 'default', at: finished },
165
+ ]);
166
+ } finally { closeDatabase(opened2.db); }
167
+ } catch (error) {
168
+ logger.warn?.(`lifecode-rag: no se pudo auditar la pasada de automatización: ${error.message}`);
169
+ }
170
+
171
+ status.lastRunAt = finished;
172
+ status.lastResult = outcome;
173
+ return outcome;
174
+ } catch (error) {
175
+ if (!(error instanceof RagError) && error?.code !== undefined) throw error;
176
+ outcome.errors.push({ path: null, code: error.code ?? 'internal', message: error.message });
177
+ status.lastResult = outcome;
178
+ throw error;
179
+ } finally {
180
+ running = false;
181
+ status.running = false;
182
+ }
183
+ }
184
+
185
+ function start() {
186
+ const config = currentConfig();
187
+ if (!config.automation.enabled) {
188
+ status.enabled = false;
189
+ return { started: false, reason: 'disabled' };
190
+ }
191
+ if (timer) return { started: true, already: true };
192
+ status.enabled = true;
193
+ status.intervalMs = config.automation.intervalMs;
194
+ timer = setInterval(() => { runOnce().catch((error) => logger.warn?.(`lifecode-rag automatización: ${error.message}`)); }, config.automation.intervalMs);
195
+ timer.unref?.();
196
+ return { started: true, intervalMs: config.automation.intervalMs, roots: config.automation.watchRoots };
197
+ }
198
+
199
+ function stop() {
200
+ if (timer) clearInterval(timer);
201
+ timer = null;
202
+ status.enabled = false;
203
+ return { stopped: true };
204
+ }
205
+
206
+ return { start, stop, runOnce, status: statusSnapshot };
207
+ }
208
+
209
+ export function automationFor(deps) {
210
+ if (state.has(deps)) return state.get(deps);
211
+ const automation = createAutomation(deps);
212
+ state.set(deps, automation);
213
+ return automation;
214
+ }
package/lib/chunk.mjs ADDED
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Chunking (M2): cortes contiguos sobre el texto normalizado, con solape y contexto de encabezado.
3
+ *
4
+ * Decisión: los offsets (`char_start`/`char_end`) son exactos sobre el texto normalizado, y el solape
5
+ * se implementa **retrocediendo el inicio** del siguiente chunk, no duplicando texto en memoria. Así
6
+ * una cita puede verificarse siempre contra el fichero original con `slice(start, end)`.
7
+ */
8
+
9
+ import { RagError } from './errors.mjs';
10
+
11
+ const HEADING = /^(#{1,6})[ \t]+(\S.*)$/;
12
+
13
+ /** Posiciones de encabezado Markdown (y `===`/`---` de setext, sólo si la línea anterior no está vacía). */
14
+ function headingIndex(text) {
15
+ const headings = [];
16
+ let offset = 0;
17
+ for (const line of text.split('\n')) {
18
+ const match = HEADING.exec(line.trim());
19
+ if (match) headings.push({ index: offset, text: match[2].trim() });
20
+ offset += line.length + 1;
21
+ }
22
+ return headings;
23
+ }
24
+
25
+ function headingAt(headings, position) {
26
+ let found = null;
27
+ for (const heading of headings) {
28
+ if (heading.index > position) break;
29
+ found = heading.text;
30
+ }
31
+ return found;
32
+ }
33
+
34
+ /** Busca un corte hacia atrás desde `candidate`, sin bajar de `floor`, prefiriendo párrafo > línea > frase > espacio. */
35
+ function snapBack(text, candidate, floor) {
36
+ const patterns = ['\n\n', '\n', '. ', '? ', '! ', '; ', ', ', ' '];
37
+ for (const pattern of patterns) {
38
+ const at = text.lastIndexOf(pattern, candidate);
39
+ if (at >= floor) return at + pattern.length;
40
+ }
41
+ return candidate;
42
+ }
43
+
44
+ /**
45
+ * Divide el texto en chunks.
46
+ * @param {string} text texto normalizado
47
+ * @param {{targetChars?:number, maxChars?:number, overlapChars?:number}} options
48
+ * @returns {Array<{ordinal:number, text:string, heading:string|null, charStart:number, charEnd:number, tokenEst:number}>}
49
+ */
50
+ export function chunkText(text, options = {}) {
51
+ const targetChars = options.targetChars ?? 1_200;
52
+ const maxChars = options.maxChars ?? 2_000;
53
+ const overlapChars = Math.min(options.overlapChars ?? 120, Math.floor(targetChars / 2));
54
+
55
+ if (typeof text !== 'string') throw new RagError('internal', 'chunkText espera un string');
56
+ if (!(targetChars > 0) || !(maxChars >= targetChars) || !(overlapChars >= 0)) {
57
+ throw new RagError('invalid-config', 'límites de chunking incoherentes', { details: { targetChars, maxChars, overlapChars } });
58
+ }
59
+ if (text.trim() === '') return [];
60
+
61
+ const headings = headingIndex(text);
62
+ const chunks = [];
63
+ let position = 0;
64
+
65
+ while (position < text.length) {
66
+ while (position < text.length && /\s/.test(text[position])) position += 1;
67
+ if (position >= text.length) break;
68
+
69
+ const remaining = text.length - position;
70
+ let end;
71
+ if (remaining <= maxChars) {
72
+ end = text.length;
73
+ } else {
74
+ const candidate = Math.min(position + targetChars, position + maxChars);
75
+ end = snapBack(text, candidate, position + Math.floor(targetChars * 0.6));
76
+ if (end <= position) end = Math.min(position + maxChars, text.length);
77
+ }
78
+
79
+ const slice = text.slice(position, end);
80
+ if (slice.trim() !== '') {
81
+ chunks.push({
82
+ ordinal: chunks.length,
83
+ text: slice,
84
+ heading: headingAt(headings, position),
85
+ charStart: position,
86
+ charEnd: end,
87
+ tokenEst: Math.ceil(slice.length / 4),
88
+ });
89
+ }
90
+
91
+ if (end >= text.length) break;
92
+ let next = end - overlapChars;
93
+ if (next <= position) next = end;
94
+ // No empezar a mitad de palabra: avanzar al siguiente espacio si el solape cayó dentro de una.
95
+ while (next < text.length && next > position && !/\s/.test(text[next - 1])) next += 1;
96
+ position = next;
97
+ }
98
+
99
+ return chunks;
100
+ }