@designerbyron/lifecode-rag 0.0.0-stage → 1.1.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 +220 -2
  3. package/bin/lifecode-rag.mjs +449 -0
  4. package/client.js +3515 -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 +887 -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 +231 -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 +946 -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 +606 -0
  55. package/lib/resolve.mjs +318 -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 +225 -0
  64. package/lib/server.mjs +340 -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,260 @@
1
+ /**
2
+ * Extracción y normalización de texto (M2).
3
+ *
4
+ * Formatos de la v1: texto y familia textual. No se interpreta PDF/DOCX: se rechazan con
5
+ * `path-unsupported` en vez de intentar heurísticas que producirían basura indexada.
6
+ *
7
+ * Invariantes:
8
+ * - Un fichero binario (NUL en la cabecera) se rechaza; no se indexa «lo que se pueda».
9
+ * - UTF-8 inválido se rechaza; no se sustituye por U+FFFD silenciosamente.
10
+ * - La normalización es determinista: NFC, LF, sin BOM, sin NUL, sin espacios finales.
11
+ */
12
+
13
+ import { RagError } from './errors.mjs';
14
+
15
+ /** Extensiones aceptadas y su MIME. La lista es deliberadamente corta y explícita. */
16
+ export const FORMATS = Object.freeze({
17
+ '.txt': 'text/plain',
18
+ '.text': 'text/plain',
19
+ '.log': 'text/plain',
20
+ '.md': 'text/markdown',
21
+ '.markdown': 'text/markdown',
22
+ '.html': 'text/html',
23
+ '.htm': 'text/html',
24
+ '.xhtml': 'text/html',
25
+ '.json': 'application/json',
26
+ '.jsonl': 'application/x-ndjson',
27
+ '.ndjson': 'application/x-ndjson',
28
+ '.csv': 'text/csv',
29
+ '.tsv': 'text/tab-separated-values',
30
+ '.yaml': 'application/yaml',
31
+ '.yml': 'application/yaml',
32
+ '.xml': 'application/xml',
33
+ // Código: se indexa como texto; el lenguaje no cambia el pipeline.
34
+ '.js': 'text/plain', '.mjs': 'text/plain', '.cjs': 'text/plain', '.ts': 'text/plain',
35
+ '.jsx': 'text/plain', '.tsx': 'text/plain', '.py': 'text/plain', '.rb': 'text/plain',
36
+ '.php': 'text/plain', '.java': 'text/plain', '.cs': 'text/plain', '.go': 'text/plain',
37
+ '.rs': 'text/plain', '.c': 'text/plain', '.h': 'text/plain', '.cpp': 'text/plain',
38
+ '.hpp': 'text/plain', '.sh': 'text/plain', '.ps1': 'text/plain', '.sql': 'text/plain',
39
+ '.css': 'text/plain', '.scss': 'text/plain', '.vue': 'text/plain', '.svelte': 'text/plain',
40
+ '.toml': 'text/plain', '.ini': 'text/plain', '.cfg': 'text/plain', '.conf': 'text/plain',
41
+ });
42
+
43
+ const MIME_BY_EXTENSION = new Map(Object.entries(FORMATS));
44
+
45
+ /** Extensión en minúsculas, incluida la del último segmento (`.d.ts` → `.ts`). */
46
+ export function extensionOf(filePath) {
47
+ const name = String(filePath).replace(/\\/g, '/').split('/').pop() ?? '';
48
+ const dot = name.lastIndexOf('.');
49
+ return dot <= 0 ? '' : name.slice(dot).toLowerCase();
50
+ }
51
+
52
+ /** MIME declarado o derivado de la extensión. `undefined` si el formato no está soportado. */
53
+ export function mimeOf(filePath, declared = undefined) {
54
+ if (typeof declared === 'string' && declared !== '') return declared;
55
+ return MIME_BY_EXTENSION.get(extensionOf(filePath));
56
+ }
57
+
58
+ /** Rechaza un formato no soportado con el motivo concreto. */
59
+ export function assertSupportedFormat(filePath, declared = undefined) {
60
+ const mime = mimeOf(filePath, declared);
61
+ if (mime === undefined) {
62
+ throw new RagError('path-unsupported', `formato no soportado: ${extensionOf(filePath) || '(sin extensión)'}`, {
63
+ details: { path: filePath },
64
+ });
65
+ }
66
+ return mime;
67
+ }
68
+
69
+ /** ¿Parece binario? Un NUL en la cabecera es la señal barata y fiable que usa Git. */
70
+ export function isProbablyBinary(bytes) {
71
+ const limit = Math.min(bytes.length, 8_000);
72
+ for (let i = 0; i < limit; i += 1) if (bytes[i] === 0) return true;
73
+ return false;
74
+ }
75
+
76
+ /** Decodifica UTF-8 estricto quitando el BOM. Un byte inválido es un error, no un reemplazo. */
77
+ export function decodeUtf8(bytes) {
78
+ let text;
79
+ try {
80
+ text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
81
+ } catch (cause) {
82
+ throw new RagError('source-unreadable', 'el fichero no es UTF-8 válido', { cause });
83
+ }
84
+ return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
85
+ }
86
+
87
+ const ENTITIES = Object.freeze({
88
+ amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ',
89
+ aacute: 'á', eacute: 'é', iacute: 'í', oacute: 'ó', uacute: 'ú', uuml: 'ü', ntilde: 'ñ',
90
+ Aacute: 'Á', Eacute: 'É', Iacute: 'Í', Oacute: 'Ó', Uacute: 'Ú', Uuml: 'Ü', Ntilde: 'Ñ',
91
+ iexcl: '¡', iquest: '¿', laquo: '«', raquo: '»', mdash: '—', ndash: '–', hellip: '…',
92
+ });
93
+
94
+ /** Decodifica entidades HTML habituales y numéricas. */
95
+ export function decodeEntities(text) {
96
+ return text.replace(/&(#x?[0-9a-fA-F]+|[a-zA-Z]+);/g, (whole, body) => {
97
+ if (body.startsWith('#x') || body.startsWith('#X')) {
98
+ const code = Number.parseInt(body.slice(2), 16);
99
+ return Number.isFinite(code) ? String.fromCodePoint(code) : whole;
100
+ }
101
+ if (body.startsWith('#')) {
102
+ const code = Number.parseInt(body.slice(1), 10);
103
+ return Number.isFinite(code) ? String.fromCodePoint(code) : whole;
104
+ }
105
+ return Object.hasOwn(ENTITIES, body) ? ENTITIES[body] : whole;
106
+ });
107
+ }
108
+
109
+ const BLOCK_TAGS = /<\/(?:p|div|section|article|li|tr|h[1-6]|blockquote|pre|table|ul|ol|dl|dt|dd|figure|figcaption)>|<br\s*\/?>/gi;
110
+
111
+ /** HTML → texto legible: fuera script/style/comentarios, bloques a saltos, entidades decodificadas. */
112
+ export function extractHtml(html) {
113
+ return decodeEntities(
114
+ html
115
+ .replace(/<!--[\s\S]*?-->/g, ' ')
116
+ .replace(/<(script|style|noscript|template|svg)\b[^>]*>[\s\S]*?<\/\1>/gi, ' ')
117
+ .replace(BLOCK_TAGS, '\n')
118
+ .replace(/<[^>]+>/g, ' '),
119
+ ).replace(/[ \t\u00a0]+/g, ' ').replace(/^[ \t]+|[ \t]+$/gm, '');
120
+ }
121
+
122
+ /** XML → texto: se conserva el contenido y los saltos, no la estructura de etiquetas. */
123
+ export function extractXml(xml) {
124
+ return decodeEntities(
125
+ xml
126
+ .replace(/<\?[\s\S]*?\?>/g, ' ')
127
+ .replace(/<!--[\s\S]*?-->/g, ' ')
128
+ .replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, '$1')
129
+ .replace(/<\/[^>]+>/g, '\n')
130
+ .replace(/<[^>]+>/g, ' '),
131
+ ).replace(/[ \t\u00a0]+/g, ' ').replace(/^[ \t]+|[ \t]+$/gm, '');
132
+ }
133
+
134
+ /** JSON → texto con claves y valores, en líneas. Un JSON inválido se rechaza. */
135
+ export function extractJson(source) {
136
+ let value;
137
+ try {
138
+ value = JSON.parse(source);
139
+ } catch (cause) {
140
+ throw new RagError('source-unreadable', 'JSON inválido', { cause, details: { format: 'json' } });
141
+ }
142
+ return flattenJson(value).join('\n');
143
+ }
144
+
145
+ function flattenJson(value, prefix = '', out = [], depth = 0) {
146
+ if (depth > 32) return out;
147
+ if (value === null || typeof value !== 'object') {
148
+ out.push(prefix === '' ? String(value) : `${prefix}: ${String(value)}`);
149
+ return out;
150
+ }
151
+ if (Array.isArray(value)) {
152
+ value.forEach((item) => flattenJson(item, `${prefix}[]`, out, depth + 1));
153
+ return out;
154
+ }
155
+ for (const [key, item] of Object.entries(value)) {
156
+ flattenJson(item, prefix === '' ? key : `${prefix}.${key}`, out, depth + 1);
157
+ }
158
+ return out;
159
+ }
160
+
161
+ /** JSONL → una línea por objeto; una línea inválida invalida el fichero entero. */
162
+ export function extractJsonl(source) {
163
+ const lines = source.split('\n');
164
+ const out = [];
165
+ for (let index = 0; index < lines.length; index += 1) {
166
+ const line = lines[index].trim();
167
+ if (line === '') continue;
168
+ let value;
169
+ try {
170
+ value = JSON.parse(line);
171
+ } catch (cause) {
172
+ throw new RagError('source-unreadable', `JSONL inválido en la línea ${index + 1}`, { cause });
173
+ }
174
+ out.push(...flattenJson(value));
175
+ }
176
+ return out.join('\n');
177
+ }
178
+
179
+ /** Parser mínimo CSV/TSV con comillas dobles y comillas escapadas. */
180
+ export function parseDelimited(source, delimiter) {
181
+ const rows = [];
182
+ let row = [];
183
+ let field = '';
184
+ let quoted = false;
185
+ for (let i = 0; i < source.length; i += 1) {
186
+ const char = source[i];
187
+ if (quoted) {
188
+ if (char === '"' && source[i + 1] === '"') { field += '"'; i += 1; }
189
+ else if (char === '"') quoted = false;
190
+ else field += char;
191
+ } else if (char === '"' && field === '') quoted = true;
192
+ else if (char === delimiter) { row.push(field); field = ''; }
193
+ else if (char === '\n' || char === '\r') {
194
+ if (char === '\r' && source[i + 1] === '\n') i += 1;
195
+ row.push(field);
196
+ if (row.some((cell) => cell.trim() !== '')) rows.push(row);
197
+ row = []; field = '';
198
+ } else field += char;
199
+ }
200
+ row.push(field);
201
+ if (row.some((cell) => cell.trim() !== '')) rows.push(row);
202
+ return rows;
203
+ }
204
+
205
+ /** CSV/TSV → texto tabular legible: `cabecera = valor; …` por fila. */
206
+ export function extractDelimited(source, delimiter) {
207
+ const rows = parseDelimited(source, delimiter);
208
+ if (rows.length === 0) return '';
209
+ const header = rows[0].map((cell) => cell.trim());
210
+ const out = [];
211
+ rows.slice(1).forEach((row, index) => {
212
+ const cells = row.map((cell, column) => {
213
+ const key = header[column] === '' ? `col${column + 1}` : header[column];
214
+ return `${key} = ${cell.trim()}`;
215
+ });
216
+ out.push(`fila ${index + 1}: ${cells.join('; ')}`);
217
+ });
218
+ return out.join('\n');
219
+ }
220
+
221
+ /** Normalización final, idempotente: NFC, LF, sin NUL, sin espacios finales, como mucho un salto doble. */
222
+ export function normalizeText(text) {
223
+ return text
224
+ .normalize('NFC')
225
+ .replace(/\r\n?/g, '\n')
226
+ .replace(/\u0000/g, '')
227
+ .replace(/[ \t]+\n/g, '\n')
228
+ .replace(/[ \t]{2,}/g, ' ')
229
+ .replace(/\n{3,}/g, '\n\n')
230
+ .trim();
231
+ }
232
+
233
+ /**
234
+ * Punto de entrada de la extracción. Devuelve `{text, mime}` ya normalizado.
235
+ * `title` lo aporta quien llama (nombre del fichero o `<title>` si es HTML).
236
+ */
237
+ export function extractText(bytes, { path, mime: declared } = {}) {
238
+ if (!(bytes instanceof Uint8Array)) {
239
+ throw new RagError('internal', 'extractText espera Uint8Array');
240
+ }
241
+ if (isProbablyBinary(bytes)) {
242
+ throw new RagError('binary-file', 'el fichero parece binario', { details: { path } });
243
+ }
244
+ const mime = assertSupportedFormat(path ?? '', declared);
245
+ const raw = decodeUtf8(bytes);
246
+ if (raw.trim() === '') throw new RagError('source-unreadable', 'el fichero está vacío', { details: { path } });
247
+
248
+ let text;
249
+ if (mime === 'text/html') text = extractHtml(raw);
250
+ else if (mime === 'application/xml') text = extractXml(raw);
251
+ else if (mime === 'application/json') text = extractJson(raw);
252
+ else if (mime === 'application/x-ndjson') text = extractJsonl(raw);
253
+ else if (mime === 'text/csv') text = extractDelimited(raw, ',');
254
+ else if (mime === 'text/tab-separated-values') text = extractDelimited(raw, '\t');
255
+ else text = raw;
256
+
257
+ const normalized = normalizeText(text);
258
+ if (normalized === '') throw new RagError('source-unreadable', 'el fichero no contiene texto utilizable', { details: { path } });
259
+ return { text: normalized, mime };
260
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Harness Open Projects.
3
+ *
4
+ * DeepSeek Harness mantiene un registro durable de *workspaces*: cada uno tiene una ruta
5
+ * canónica, un título y las sesiones que lo tienen abierto (`sessionIds`). LifeCode RAG usa
6
+ * ese registro como la señal de «qué proyectos tiene abiertos la persona», en lugar de asumir
7
+ * que `cwd` describe todos los proyectos o de confiar en una carpeta contenedora.
8
+ *
9
+ * Lo que este módulo aporta:
10
+ * - normaliza los workspaces vivos a una forma estable y sin objetos del host;
11
+ * - resuelve el workspace de una sesión y el que contiene un `cwd`;
12
+ * - **no** autoriza nada: la autorización de lectura sigue siendo un `trusted root`
13
+ * explícito (ver `trusted-roots.mjs`), evaluado por `resolve.mjs`. Un proyecto abierto
14
+ * sin autorización produce un rechazo con el comando exacto que la persona debe ejecutar.
15
+ */
16
+
17
+ import { pathKeyFor } from './registry.mjs';
18
+
19
+ /** Forma interna de un proyecto abierto: sólo datos serializables. */
20
+ export function normalizeWorkspace(workspace) {
21
+ if (!workspace || typeof workspace.path !== 'string' || workspace.path.trim() === '') return null;
22
+ const sessionIds = Array.isArray(workspace.sessionIds)
23
+ ? workspace.sessionIds.filter((id) => typeof id === 'string' && id !== '')
24
+ : [];
25
+ return {
26
+ id: typeof workspace.id === 'string' ? workspace.id : null,
27
+ path: workspace.path,
28
+ pathKey: pathKeyFor(workspace.path),
29
+ title: typeof workspace.title === 'string' && workspace.title.trim() !== ''
30
+ ? workspace.title
31
+ : workspace.path,
32
+ sessionIds,
33
+ };
34
+ }
35
+
36
+ /**
37
+ * Lee el registro de workspaces del host y devuelve los proyectos abiertos.
38
+ *
39
+ * `registry` es el servicio `workspaceRegistry` (o cualquier objeto con `list()`). Los
40
+ * workspaces cuyo directorio ya no existe (`status() !== 'ok'`) se omiten: un proyecto
41
+ * abierto que desapareció del disco no debe convertirse en un ámbito candidato.
42
+ */
43
+ export async function listOpenProjects(registry) {
44
+ if (!registry || typeof registry.list !== 'function') return [];
45
+ let raw;
46
+ try {
47
+ raw = registry.list();
48
+ } catch {
49
+ return [];
50
+ }
51
+ if (!Array.isArray(raw)) return [];
52
+ const projects = [];
53
+ for (const workspace of raw) {
54
+ const normalized = normalizeWorkspace(workspace);
55
+ if (!normalized) continue;
56
+ if (typeof workspace.status === 'function') {
57
+ try {
58
+ const status = await workspace.status();
59
+ if (status !== 'ok') continue;
60
+ } catch {
61
+ continue;
62
+ }
63
+ }
64
+ projects.push(normalized);
65
+ }
66
+ return projects;
67
+ }
68
+
69
+ /** El proyecto abierto más específico que contiene la clave dada. */
70
+ export function openProjectForCwd(projects, cwdKey) {
71
+ if (!cwdKey || !Array.isArray(projects)) return null;
72
+ let best = null;
73
+ for (const project of projects) {
74
+ const inside = cwdKey === project.pathKey || cwdKey.startsWith(`${project.pathKey}/`);
75
+ if (!inside) continue;
76
+ if (!best || project.pathKey.length > best.pathKey.length) best = project;
77
+ }
78
+ return best;
79
+ }
80
+
81
+ /** El proyecto abierto al que el host asocia esta sesión. */
82
+ export function openProjectForSession(projects, sessionId) {
83
+ if (!sessionId || !Array.isArray(projects)) return null;
84
+ return projects.find((project) => project.sessionIds.includes(sessionId)) ?? null;
85
+ }
package/lib/hash.mjs ADDED
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Hashes de contenido de LifeCode RAG.
3
+ *
4
+ * El hash es la identidad del texto normalizado: dos ingestas del mismo documento no deben reindexar
5
+ * si el hash coincide. Se calcula sobre UTF-8 con `node:crypto`; no hay dependencias.
6
+ */
7
+
8
+ import { createHash } from 'node:crypto';
9
+
10
+ /** SHA-256 en hexadecimal minúscula de un `Buffer`, `Uint8Array` o cadena UTF-8. */
11
+ export function sha256Hex(value) {
12
+ const hash = createHash('sha256');
13
+ if (typeof value === 'string') hash.update(value, 'utf8');
14
+ else if (value instanceof Uint8Array) hash.update(value);
15
+ else throw new TypeError('sha256Hex espera string o Uint8Array');
16
+ return hash.digest('hex');
17
+ }
18
+
19
+ /**
20
+ * Huella de una fuente para decidir reutilización: normaliza saltos de línea (CRLF/CR → LF) y recorta el
21
+ * final. El texto que se indexa ya pasó por la extracción; aquí sólo se evita que un cambio de saltos
22
+ * de línea cuente como contenido distinto.
23
+ */
24
+ export function contentDigest(text) {
25
+ if (typeof text !== 'string') throw new TypeError('contentDigest espera string');
26
+ return sha256Hex(text.replace(/\r\n?/g, '\n').replace(/\n+$/u, '\n'));
27
+ }
28
+
29
+ /** Identificador estable de un chunk dentro de su fuente: `<source_id>#<ordinal>`. */
30
+ export function chunkKey(sourceId, ordinal) {
31
+ if (typeof sourceId !== 'string' || sourceId === '') throw new TypeError('sourceId vacío');
32
+ if (!Number.isInteger(ordinal) || ordinal < 0) throw new TypeError('ordinal inválido');
33
+ return `${sourceId}#${ordinal}`;
34
+ }
package/lib/ingest.mjs ADDED
@@ -0,0 +1,239 @@
1
+ /**
2
+ * Ingesta (M2): preparar todo antes de tocar el almacén y sustituir por fichero en una sola transacción.
3
+ *
4
+ * Fases explícitas, tal como exige el contrato del proyecto:
5
+ * lectura → digest → extracción → normalización → chunking → embeddings (sin escrituras)
6
+ * transacción: fuente + chunks + vectores + etiquetas + auditoría (todo o nada)
7
+ *
8
+ * Una fuente fallida **no deja fila** en `sources`: el fallo se reporta en el resultado y en la
9
+ * auditoría. Reingerir un fichero sin cambios no reescribe nada (`skipped`).
10
+ */
11
+
12
+ import { createHash } from 'node:crypto';
13
+ import { readFileSync, statSync } from 'node:fs';
14
+ import { basename, resolve } from 'node:path';
15
+
16
+ import { appendAudit } from './audit.mjs';
17
+ import { chunkText } from './chunk.mjs';
18
+ import { normalizeTags } from './tags.mjs';
19
+ import { vectorToBlob } from './embed.mjs';
20
+ import { createEmbedder } from './embedders.mjs';
21
+ import { RagError } from './errors.mjs';
22
+ import { extractText } from './extract.mjs';
23
+ import { contentDigest, sha256Hex } from './hash.mjs';
24
+ import { openDatabase, storeFailure, withTransaction } from './db.mjs';
25
+ import { recordMetrics } from './metrics.mjs';
26
+
27
+ /** Id estable y legible derivado de la URI canónica: reingerir la misma ruta sustituye, no duplica. */
28
+ export function sourceIdFor(uri) {
29
+ return `src_${createHash('sha256').update(String(uri), 'utf8').digest('hex').slice(0, 16)}`;
30
+ }
31
+
32
+ /** Título legible: primer encabezado Markdown o `<title>` HTML; si no, el nombre del fichero. */
33
+ export function titleOf(text, filePath, mime) {
34
+ if (mime === 'text/html') {
35
+ const match = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(text);
36
+ if (match?.[1]?.trim()) return match[1].trim().slice(0, 200);
37
+ }
38
+ const heading = /^#{1,6}[ \t]+(.+)$/m.exec(text);
39
+ if (heading?.[1]?.trim()) return heading[1].trim().slice(0, 200);
40
+ return basename(filePath);
41
+ }
42
+
43
+ /**
44
+ * Fase de preparación: lee y calcula sin escribir nada.
45
+ * @returns {{path:string, uri:string, title:string, mime:string, bytes:number, sha256:string, text:string,
46
+ * chunks:Array<{ordinal:number,text:string,heading:string|null,charStart:number,charEnd:number,tokenEst:number}>,
47
+ * vectors:Float32Array[]}}
48
+ */
49
+ export async function prepareDocument(filePath, { config, uri = undefined, embedder = undefined } = {}) {
50
+ const absolutePath = resolve(filePath);
51
+ let stats;
52
+ try {
53
+ stats = statSync(absolutePath);
54
+ } catch (cause) {
55
+ throw new RagError('source-unreadable', 'no se puede leer el fichero', { cause, details: { path: absolutePath } });
56
+ }
57
+ if (!stats.isFile()) {
58
+ throw new RagError('path-unsupported', 'no es un fichero regular', { details: { path: absolutePath } });
59
+ }
60
+ if (stats.size === 0) throw new RagError('source-unreadable', 'el fichero está vacío', { details: { path: absolutePath } });
61
+ if (stats.size > config.maxFileBytes) {
62
+ throw new RagError('too-large', `el fichero supera ${config.maxFileBytes} bytes`, {
63
+ details: { path: absolutePath, bytes: stats.size },
64
+ });
65
+ }
66
+
67
+ let bytes;
68
+ try {
69
+ bytes = readFileSync(absolutePath);
70
+ } catch (cause) {
71
+ throw new RagError('source-unreadable', 'fallo de lectura', { cause, details: { path: absolutePath } });
72
+ }
73
+ const { text, mime } = extractText(bytes, { path: absolutePath });
74
+ const chunks = chunkText(text, config.chunk);
75
+ if (chunks.length === 0) throw new RagError('source-unreadable', 'el texto no produjo chunks', { details: { path: absolutePath } });
76
+ const title = titleOf(text, absolutePath, mime);
77
+
78
+ // Los vectores se calculan aquí, antes de abrir transacción: un fallo de embedding no toca el almacén.
79
+ const provider = embedder ?? createEmbedder(config);
80
+ const vectors = await provider.embed(chunks.map((chunk) => chunk.text));
81
+
82
+ return {
83
+ path: absolutePath,
84
+ uri: uri ?? absolutePath,
85
+ title,
86
+ mime,
87
+ bytes: bytes.length,
88
+ sha256: sha256Hex(bytes),
89
+ digest: contentDigest(text),
90
+ text,
91
+ chunks,
92
+ vectors,
93
+ embeddingModel: provider.model,
94
+ embeddingKind: provider.kind,
95
+ };
96
+ }
97
+
98
+ /**
99
+ * Escribe un documento preparado. Devuelve `{id, uri, chunks, skipped}`.
100
+ * El llamador debe estar dentro de una transacción o usar `upsertDocument`.
101
+ */
102
+ export function writeDocument(db, prepared, { collection = 'default', tags = [], now = Date.now(), force = false, config } = {}) {
103
+ const existing = db.prepare('SELECT id, sha256 FROM sources WHERE uri = ?').get(prepared.uri);
104
+ if (existing && existing.sha256 === prepared.sha256 && !force) {
105
+ // AC16: cambiar sólo las etiquetas no re-trocea, no toca FTS/vectores y no sube index_revision.
106
+ const current = db.prepare('SELECT tag FROM source_tags WHERE source_id = ? ORDER BY tag').all(existing.id).map((row) => row.tag);
107
+ const next = [...tags].sort();
108
+ if (current.join('\u0000') !== next.join('\u0000')) {
109
+ db.prepare('DELETE FROM source_tags WHERE source_id = ?').run(existing.id);
110
+ const insertTag = db.prepare('INSERT INTO source_tags (source_id, tag) VALUES (?, ?)');
111
+ for (const tag of next) insertTag.run(existing.id, tag);
112
+ db.prepare('UPDATE sources SET updated_at = ? WHERE id = ?').run(now, existing.id);
113
+ return { id: existing.id, uri: prepared.uri, chunks: 0, skipped: false, tagsUpdated: true, replacedChunks: 0, reason: 'tags-updated' };
114
+ }
115
+ return { id: existing.id, uri: prepared.uri, chunks: 0, skipped: true, tagsUpdated: false, reason: 'unchanged' };
116
+ }
117
+ const id = existing?.id ?? sourceIdFor(prepared.uri);
118
+
119
+ const previous = existing ? db.prepare('SELECT COUNT(*) AS n FROM chunks WHERE source_id = ?').get(id).n : 0;
120
+ if (existing) db.prepare('DELETE FROM chunks WHERE source_id = ?').run(id);
121
+
122
+ if (existing) {
123
+ db.prepare(`UPDATE sources SET collection = ?, title = ?, mime = ?, sha256 = ?, bytes = ?, char_count = ?,
124
+ metadata = ?, updated_at = ?, indexed_at = ? WHERE id = ?`)
125
+ .run(collection, prepared.title, prepared.mime, prepared.sha256, prepared.bytes, prepared.text.length,
126
+ '{}', now, now, id);
127
+ } else {
128
+ const created = now;
129
+ db.prepare(`INSERT INTO sources (id, collection, uri, title, mime, sha256, bytes, char_count, metadata, created_at, updated_at, indexed_at)
130
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, '{}', ?, ?, ?)`)
131
+ .run(id, collection, prepared.uri, prepared.title, prepared.mime, prepared.sha256, prepared.bytes,
132
+ prepared.text.length, created, now, now);
133
+ }
134
+
135
+ const insertChunk = db.prepare(`INSERT INTO chunks (chunk_key, source_id, ordinal, title, heading, text, char_start, char_end, token_est)
136
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`);
137
+ const insertVector = db.prepare('INSERT INTO vectors (chunk_key, model, dim, vec) VALUES (?, ?, ?, ?)');
138
+ const model = prepared.embeddingModel ?? config.embedding.provider;
139
+ prepared.chunks.forEach((chunk, index) => {
140
+ const chunkKey = `${id}#${chunk.ordinal}`;
141
+ insertChunk.run(chunkKey, id, chunk.ordinal, prepared.title, chunk.heading, chunk.text,
142
+ chunk.charStart, chunk.charEnd, chunk.tokenEst);
143
+ const vector = prepared.vectors[index];
144
+ insertVector.run(chunkKey, model, vector.length, vectorToBlob(vector));
145
+ });
146
+
147
+ db.prepare('DELETE FROM source_tags WHERE source_id = ?').run(id);
148
+ const insertTag = db.prepare('INSERT INTO source_tags (source_id, tag) VALUES (?, ?)');
149
+ for (const tag of tags) insertTag.run(id, tag);
150
+
151
+ db.prepare("UPDATE meta SET value = CAST(CAST(value AS INTEGER) + 1 AS TEXT) WHERE key = 'index_revision'").run();
152
+ return { id, uri: prepared.uri, chunks: prepared.chunks.length, skipped: false, replacedChunks: previous };
153
+ }
154
+
155
+ /**
156
+ * Ingesta de una lista de ficheros. Cada fichero es atómico por separado; un fallo no revierte los demás.
157
+ * @returns {{ingested:Array, skipped:Array, errors:Array<{path:string, code:string, message:string}>}}
158
+ */
159
+ export async function ingestFiles({
160
+ root, db = undefined, files, collection = 'default', tags = [], now = Date.now(), force = false, config, embedder = undefined, actor = 'model',
161
+ authorize = null,
162
+ }) {
163
+ const normalizedTags = normalizeTags(tags);
164
+ const provider = embedder ?? createEmbedder(config);
165
+ // PA3: la herramienta ya abrió el almacén del ámbito autorizado; en ese caso la conexión es
166
+ // prestada y no se cierra aquí. El uso directo (CLI, pruebas) sigue abriendo por su cuenta.
167
+ const opened = db ? { db } : openDatabase({ root, create: true, now });
168
+ const ingested = [];
169
+ const skipped = [];
170
+ const errors = [];
171
+ const started = Date.now();
172
+ try {
173
+ for (const file of files) {
174
+ // PA4-B: la autorización se comprueba entre fichero y fichero. Cada fichero es su propia
175
+ // transacción, así que abortar aquí no deja escritura a medias: lo confirmado queda confirmado.
176
+ if (authorize) await authorize(file);
177
+ try {
178
+ const prepared = await prepareDocument(file, { config, embedder: provider });
179
+ const result = withTransaction(opened.db, () => {
180
+ const written = writeDocument(opened.db, prepared, { collection, tags: normalizedTags, now, force, config });
181
+ appendAudit(opened.db, {
182
+ at: now,
183
+ actor,
184
+ tool: 'lifecode_rag_ingest',
185
+ action: written.skipped ? 'ingest.skip' : written.tagsUpdated ? 'ingest.tags' : 'ingest',
186
+ target: prepared.uri,
187
+ outcome: written.skipped ? 'skipped' : 'ok',
188
+ details: { sourceId: written.id, chunks: written.chunks, bytes: prepared.bytes, replace: Boolean(written.replacedChunks), embedding: prepared.embeddingModel },
189
+ });
190
+ const entries = written.skipped
191
+ ? [{ metric: 'ingest.skipped', value: 1, dim: collection, at: now }]
192
+ : [
193
+ { metric: 'ingest.documents', value: 1, dim: collection, at: now },
194
+ { metric: 'ingest.chunks', value: written.chunks, dim: collection, at: now },
195
+ ];
196
+ recordMetrics(opened.db, entries);
197
+ return written;
198
+ });
199
+ (result.skipped ? skipped : ingested).push({ id: result.id, uri: result.uri, chunks: result.chunks, title: prepared.title, tagsUpdated: result.tagsUpdated === true, reason: result.reason ?? null });
200
+ } catch (error) {
201
+ // Un fallo de SQLite o de disco no puede tumbar la ingesta de los demás ficheros; se normaliza
202
+ // al contrato de errores para que el resultado sea uniforme y auditable. La contención se
203
+ // traduce a `store-busy` (reintentable) en vez de dejar escapar el `database is locked` crudo.
204
+ const failure = error instanceof RagError
205
+ ? error
206
+ : storeFailure(error, { path: file })
207
+ ?? new RagError('internal', error?.message ?? 'fallo desconocido al ingerir', { cause: error });
208
+ errors.push({
209
+ path: file,
210
+ code: failure.code,
211
+ message: failure.message,
212
+ ...(failure.details?.retryable === true ? { retryable: true } : {}),
213
+ });
214
+ try {
215
+ withTransaction(opened.db, () => {
216
+ appendAudit(opened.db, {
217
+ at: now,
218
+ actor,
219
+ tool: 'lifecode_rag_ingest',
220
+ action: 'ingest',
221
+ target: String(file),
222
+ outcome: 'failed',
223
+ details: { code: failure.code, message: failure.message },
224
+ });
225
+ recordMetrics(opened.db, [{ metric: 'errors', value: 1, dim: failure.code, at: now }]);
226
+ });
227
+ } catch { /* la auditoría del fallo no debe ocultar el fallo original */ }
228
+ }
229
+ }
230
+ try {
231
+ withTransaction(opened.db, () => recordMetrics(opened.db, [
232
+ { metric: 'ingest.ms', value: Math.max(1, Date.now() - started), dim: collection, at: now },
233
+ ]));
234
+ } catch { /* la métrica no puede convertir una ingesta correcta en un fallo */ }
235
+ return { ingested, skipped, errors };
236
+ } finally {
237
+ if (!db) opened.db.close();
238
+ }
239
+ }