@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
package/lib/inputs.mjs ADDED
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Expansión de entradas del usuario a ficheros reales.
3
+ *
4
+ * Vive aparte de las herramientas porque la API del Workspace necesita exactamente las mismas
5
+ * reglas (protección de productos, límites, omisión de árboles) y duplicarlas sería una segunda
6
+ * política que puede divergir. Es puro: no escribe ni abre la base.
7
+ */
8
+
9
+ import { readdirSync } from 'node:fs';
10
+ import { join } from 'node:path';
11
+
12
+ import { RagError } from './errors.mjs';
13
+ import { PROTECTED_SEGMENTS, classifyPath } from './policy.mjs';
14
+
15
+ export const SKIP_DIRECTORIES = new Set(['.git', 'node_modules', '.dsh', 'dist', 'build', 'coverage']);
16
+
17
+ /**
18
+ * Recorre un directorio y acumula ficheros. No sigue enlaces simbólicos ni junctions, omite árboles
19
+ * que no aportan conocimiento y **nunca** desciende a un producto protegido. El límite se comprueba
20
+ * mientras se recorre, no después de llenar memoria.
21
+ */
22
+ export function walkDirectory(directory, files, limit) {
23
+ let entries;
24
+ try {
25
+ entries = readdirSync(directory, { withFileTypes: true });
26
+ } catch (cause) {
27
+ throw new RagError('source-unreadable', 'no se puede leer el directorio', { cause, details: { path: directory } });
28
+ }
29
+ for (const entry of entries) {
30
+ const lower = entry.name.toLowerCase();
31
+ if (entry.isSymbolicLink()) continue;
32
+ const child = join(directory, entry.name);
33
+ if (entry.isDirectory()) {
34
+ if (SKIP_DIRECTORIES.has(lower) || PROTECTED_SEGMENTS.includes(lower)) continue;
35
+ walkDirectory(child, files, limit);
36
+ } else if (entry.isFile()) {
37
+ if (files.length >= limit) {
38
+ throw new RagError('too-many-files', `la ingesta supera el máximo de ${limit} ficheros`, {
39
+ details: { limit, path: directory },
40
+ });
41
+ }
42
+ files.push(child);
43
+ }
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Expande rutas de entrada a una lista de ficheros reales. Una lista con cualquier ruta protegida
49
+ * falla entera antes de escribir; los directorios se recorren con los límites de la configuración.
50
+ */
51
+ export function expandInputs(requested, { cwd, roots, ragRootPath, limit }) {
52
+ const files = [];
53
+ for (const path of requested) {
54
+ const item = classifyPath(path, { cwd, roots, ragRootPath, allowDirectory: true });
55
+ if (item.directory) walkDirectory(item.realPath, files, limit);
56
+ else files.push(item.realPath);
57
+ }
58
+ const unique = [...new Set(files)].sort();
59
+ if (unique.length === 0) throw new RagError('invalid-argument', 'las rutas no contienen ningún fichero indexable');
60
+ if (unique.length > limit) {
61
+ throw new RagError('too-many-files', `la ingesta supera el máximo de ${limit} ficheros`, {
62
+ details: { requested: unique.length },
63
+ });
64
+ }
65
+ // La clasificación final vuelve a comprobar protección y enlaces duros sobre cada fichero real.
66
+ return unique.map((path) => classifyPath(path, { cwd, roots, ragRootPath }));
67
+ }
@@ -0,0 +1,252 @@
1
+ /**
2
+ * Estados de almacén y verificación de identidad (PA4-A / PA4-C).
3
+ *
4
+ * Un almacén de ámbito puede estar en siete estados. La diferencia importante es **cómo se
5
+ * reacciona**: una ausencia (`missing`) no es una biblioteca vacía ni una corrupción; una
6
+ * indisponibilidad (`unavailable`) se puede reintentar; una corrupción (`corrupt`) no se abre ni se
7
+ * sobrescribe jamás. Todos los estados se detectan abriendo en **solo lectura**: clasificar nunca
8
+ * crea, migra ni repara.
9
+ *
10
+ * La identidad del almacén se verifica contra el ámbito esperado antes de confiar en él:
11
+ * `scope_id`, `scope_kind`, perfil y `store_state`. Un almacén de otro ámbito, de otro perfil o con
12
+ * estado `corrupt` se cierra con `scope-store-corrupt` / `scope-forbidden`.
13
+ */
14
+
15
+ import { existsSync, lstatSync } from 'node:fs';
16
+ import { join } from 'node:path';
17
+ import { DatabaseSync } from 'node:sqlite';
18
+
19
+ import { RagError } from './errors.mjs';
20
+ import { scopeRoot } from './profile.mjs';
21
+ import { APPLICATION_ID, SCHEMA_VERSION } from './schema.mjs';
22
+
23
+ /** Estados de almacén reconocidos. `recovering`/`recovered` los escribe el recuperador. */
24
+ export const LIBRARY_STATES = Object.freeze([
25
+ 'present',
26
+ 'missing',
27
+ 'unreadable',
28
+ 'corrupt',
29
+ 'unavailable',
30
+ 'recovering',
31
+ 'recovered',
32
+ ]);
33
+
34
+ /** Estados que no permiten servir datos. */
35
+ export const BLOCKING_STATES = Object.freeze(['missing', 'unreadable', 'corrupt', 'unavailable', 'recovering']);
36
+
37
+ /** Estados que se pueden reintentar sin intervención humana. */
38
+ export const RETRYABLE_STATES = Object.freeze(['unavailable', 'recovering']);
39
+
40
+ export const STORE_FILE = 'rag.sqlite3';
41
+
42
+ /** Ruta del fichero de almacén de un ámbito. */
43
+ export function storeFileOf(profileRootPath, scopeId) {
44
+ return join(scopeRoot(profileRootPath, scopeId), STORE_FILE);
45
+ }
46
+
47
+ const SQLITE_BUSY = new Set([5, 6]);
48
+ const SQLITE_CORRUPT = new Set([11, 26]);
49
+
50
+ /** Traduce un error de SQLite a un estado de almacén, sin inventar diagnósticos. */
51
+ export function classifySqliteError(error) {
52
+ const errcode = Number(error?.errcode ?? 0);
53
+ const errno = Number(error?.errno ?? 0);
54
+ if (SQLITE_BUSY.has(errcode) || ['SQLITE_BUSY', 'SQLITE_LOCKED'].includes(error?.code)) {
55
+ return { state: 'unavailable', reason: 'busy', retryable: true };
56
+ }
57
+ if (SQLITE_CORRUPT.has(errcode)) {
58
+ return { state: 'corrupt', reason: error?.errstr ?? 'not-a-database', retryable: false };
59
+ }
60
+ if (errcode === 14 || errno === 2 || errno === 13 || /unable to open/i.test(String(error?.message ?? ''))) {
61
+ return { state: 'unreadable', reason: 'unopenable', retryable: false };
62
+ }
63
+ if (['EACCES', 'EPERM'].includes(error?.code)) {
64
+ return { state: 'unreadable', reason: 'permission', retryable: false };
65
+ }
66
+ if (error?.code === 'ENOENT') return { state: 'missing', reason: 'store-absent', retryable: false };
67
+ // Un error desconocido no demuestra corrupción: marcarlo `corrupt` bloquearía el ámbito para siempre
68
+ // por un fallo transitorio. Se declara no disponible y reintentable, sin filtrar el mensaje crudo
69
+ // (que suele contener rutas absolutas) al consumidor.
70
+ return { state: 'unavailable', reason: 'io-error', retryable: true };
71
+ }
72
+
73
+ function readMetaRows(db, keys) {
74
+ const placeholders = keys.map(() => '?').join(',');
75
+ const rows = db.prepare(`SELECT key, value FROM meta WHERE key IN (${placeholders})`).all(...keys);
76
+ const meta = {};
77
+ for (const row of rows) meta[row.key] = row.value;
78
+ return meta;
79
+ }
80
+
81
+ /**
82
+ * Verifica que el almacén abierto pertenece al ámbito y perfil esperados.
83
+ *
84
+ * @returns {{ok: true, meta: Record<string,string>} | {ok: false, reason: string, details: object}}
85
+ */
86
+ export function verifyStoreIdentity(db, { scope, profileKey, requireState = false } = {}) {
87
+ let meta;
88
+ try {
89
+ meta = readMetaRows(db, ['scope_id', 'scope_kind', 'profile_id', 'profile_key', 'store_state', 'schema_version']);
90
+ } catch (error) {
91
+ return { ok: false, reason: 'unreadable-meta', details: { message: String(error?.message ?? error) } };
92
+ }
93
+ if (!meta.scope_id) {
94
+ return { ok: false, reason: 'missing-scope-id', details: { scopeId: scope.id } };
95
+ }
96
+ if (meta.scope_id !== scope.id) {
97
+ return { ok: false, reason: 'foreign-scope', details: { expected: scope.id, found: meta.scope_id } };
98
+ }
99
+ if (meta.scope_kind && meta.scope_kind !== scope.kind) {
100
+ return { ok: false, reason: 'foreign-kind', details: { expected: scope.kind, found: meta.scope_kind } };
101
+ }
102
+ if (profileKey) {
103
+ // `profile_id` es el nombre del contrato PA0; `profile_key` es lo que escribieron los almacenes
104
+ // de PA3. Se aceptan ambos y se exige que coincidan si están los dos.
105
+ let declared = 0;
106
+ for (const key of ['profile_id', 'profile_key']) {
107
+ if (meta[key] === undefined || meta[key] === '') continue;
108
+ declared += 1;
109
+ if (meta[key] !== profileKey) {
110
+ return { ok: false, reason: 'foreign-profile', details: { expected: profileKey, found: meta[key], key } };
111
+ }
112
+ }
113
+ // Un almacén que no declara perfil no se adopta: no hay forma de saber de quién es.
114
+ if (declared === 0) return { ok: false, reason: 'missing-profile', details: { scopeId: scope.id } };
115
+ }
116
+ if (meta.store_state === 'corrupt') {
117
+ return { ok: false, reason: 'marked-corrupt', details: { scopeId: scope.id } };
118
+ }
119
+ if (meta.store_state === 'migrating') {
120
+ return { ok: false, reason: 'migrating', details: { scopeId: scope.id }, retryable: true };
121
+ }
122
+ if (requireState && meta.store_state === undefined) {
123
+ return { ok: false, reason: 'missing-store-state', details: { scopeId: scope.id } };
124
+ }
125
+ return { ok: true, meta };
126
+ }
127
+
128
+ /**
129
+ * Clasifica un almacén sin modificarlo. Abre en solo lectura y comprueba cabecera, versión,
130
+ * `quick_check` e identidad.
131
+ *
132
+ * @returns {{state: string, reason: string, retryable: boolean, scopeId: string, kind: string,
133
+ * path: string, bytes: number|null, meta: Record<string,string>|null}}
134
+ */
135
+ export function classifyScopeStore({ profileRootPath, profileKey, scope, checkIntegrity = true } = {}) {
136
+ const path = storeFileOf(profileRootPath, scope.id);
137
+ const base = {
138
+ scopeId: scope.id,
139
+ scopeKind: scope.kind ?? null,
140
+ kind: scope.kind ?? null,
141
+ path,
142
+ bytes: null,
143
+ meta: null,
144
+ };
145
+ const dir = scopeRoot(profileRootPath, scope.id);
146
+ if (!existsSync(dir)) return { ...base, state: 'missing', reason: 'directory-absent', retryable: false };
147
+ let stat;
148
+ try {
149
+ stat = lstatSync(path);
150
+ } catch (error) {
151
+ if (error?.code === 'ENOENT') return { ...base, state: 'missing', reason: 'store-absent', retryable: false };
152
+ const classified = classifySqliteError(error);
153
+ return { ...base, ...classified };
154
+ }
155
+ base.bytes = stat.size;
156
+ if (stat.isSymbolicLink()) return { ...base, state: 'unreadable', reason: 'store-is-link', retryable: false };
157
+
158
+ let db;
159
+ try {
160
+ db = new DatabaseSync(path, { readOnly: true });
161
+ db.exec('PRAGMA busy_timeout = 250');
162
+ } catch (error) {
163
+ return { ...base, ...classifySqliteError(error) };
164
+ }
165
+ try {
166
+ let applicationId;
167
+ let version;
168
+ try {
169
+ applicationId = Number(db.prepare('PRAGMA application_id').get().application_id);
170
+ version = Number(db.prepare('PRAGMA user_version').get().user_version);
171
+ base.meta = readMetaRows(db, ['scope_id', 'scope_kind', 'profile_id', 'profile_key', 'store_state', 'schema_version']);
172
+ } catch (error) {
173
+ return { ...base, ...classifySqliteError(error) };
174
+ }
175
+ if (applicationId !== APPLICATION_ID) {
176
+ return { ...base, state: 'corrupt', reason: 'foreign-application', retryable: false };
177
+ }
178
+ if (!Number.isInteger(version) || version < 1 || version > SCHEMA_VERSION) {
179
+ return { ...base, state: 'corrupt', reason: 'unsupported-version', retryable: false };
180
+ }
181
+ if (checkIntegrity) {
182
+ try {
183
+ const check = db.prepare('PRAGMA quick_check').all();
184
+ const joined = check.map((row) => String(row.quick_check)).join(',');
185
+ if (joined !== 'ok') return { ...base, state: 'corrupt', reason: 'quick-check', retryable: false };
186
+ // Las referencias rotas (chunks sin fuente, por ejemplo) no rompen el fichero pero sí la
187
+ // confianza en los datos: el contrato exige integridad, no sólo que SQLite lea.
188
+ const broken = db.prepare('PRAGMA foreign_key_check').all();
189
+ if (broken.length > 0) {
190
+ return { ...base, state: 'corrupt', reason: 'foreign-keys', retryable: false, findings: broken.slice(0, 5) };
191
+ }
192
+ } catch (error) {
193
+ return { ...base, ...classifySqliteError(error) };
194
+ }
195
+ }
196
+ const identity = verifyStoreIdentity(db, { scope, profileKey });
197
+ if (!identity.ok) {
198
+ if (identity.reason === 'migrating') return { ...base, state: 'unavailable', reason: 'migrating', retryable: true };
199
+ return { ...base, state: 'corrupt', reason: identity.reason, retryable: false, identity: identity.details };
200
+ }
201
+ if (identity.meta.store_state === 'recovered') {
202
+ return { ...base, state: 'recovered', reason: 'recovered', retryable: false };
203
+ }
204
+ if (identity.meta.store_state === 'recovering') {
205
+ return { ...base, state: 'recovering', reason: 'recovering', retryable: true };
206
+ }
207
+ return { ...base, state: 'present', reason: 'ok', retryable: false };
208
+ } finally {
209
+ try {
210
+ db.close();
211
+ } catch {
212
+ // cerrar dos veces no es un fallo
213
+ }
214
+ }
215
+ }
216
+
217
+ /** `true` si el estado permite servir datos. */
218
+ export function isServable(state) {
219
+ return state === 'present' || state === 'recovered';
220
+ }
221
+
222
+ /**
223
+ * Error accionable para un estado que bloquea. No convierte una ausencia en «vacío»: la ausencia es
224
+ * `scope-store-unavailable` con `reason: 'missing'`, la corrupción es `scope-store-corrupt`.
225
+ */
226
+ export function libraryStateError(entry, { scopeId, scopeKind } = {}) {
227
+ const details = {
228
+ scopeId: scopeId ?? entry.scopeId,
229
+ scopeKind: scopeKind ?? entry.scopeKind,
230
+ reason: entry.reason,
231
+ state: entry.state,
232
+ retryable: entry.retryable === true,
233
+ };
234
+ if (entry.state === 'corrupt') {
235
+ return new RagError('scope-store-corrupt', 'el almacén del ámbito está corrupto; no se abre ni se sobrescribe', {
236
+ details,
237
+ });
238
+ }
239
+ return new RagError('scope-store-unavailable', 'el almacén del ámbito no está disponible', { details });
240
+ }
241
+
242
+ /** Catálogo de metadatos que un almacén debe declarar (para informes y doctor). */
243
+ export function requiredStoreMeta() {
244
+ return Object.freeze({
245
+ scope_id: 'identificador del ámbito dueño',
246
+ scope_kind: 'prj | lib',
247
+ profile_id: 'perfil lógico (se acepta profile_key heredado de PA3)',
248
+ schema_version: 'versión del esquema de almacén',
249
+ store_state: 'ready | migrating | corrupt',
250
+ created_at: 'marca de creación',
251
+ });
252
+ }
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Mantenimiento (M3/M5): `forget` y `reindex` con alcance exacto, transacciones y auditoría.
3
+ *
4
+ * `forget` borra la fuente y todo lo que cuelga de ella (chunks, vectores, etiquetas, FTS por cascada).
5
+ * `reindex` reconstruye lo que se pide: `fts` global en una transacción, `vectors` por fuente.
6
+ * Ambas operaciones son sensibles: la herramienta exige aprobación humana **antes** de llamar aquí.
7
+ */
8
+
9
+ import { appendAudit } from './audit.mjs';
10
+ import { ftsIntegrityCheck, ftsRebuild, withTransaction } from './db.mjs';
11
+ import { embedText, vectorToBlob } from './embed.mjs';
12
+ import { RagError } from './errors.mjs';
13
+ import { getSource } from './search.mjs';
14
+
15
+ function bumpRevision(db) {
16
+ db.prepare("UPDATE meta SET value = CAST(CAST(value AS INTEGER) + 1 AS TEXT) WHERE key = 'index_revision'").run();
17
+ }
18
+
19
+ /** Borra una fuente por id o URI. Devuelve lo borrado. */
20
+ export function forgetSource(db, { ref, now = Date.now(), actor = 'model', sessionId = null, callId = null } = {}) {
21
+ const source = getSource(db, ref);
22
+ return withTransaction(db, () => {
23
+ const chunks = db.prepare('SELECT COUNT(*) AS n FROM chunks WHERE source_id = ?').get(source.id).n;
24
+ db.prepare('DELETE FROM sources WHERE id = ?').run(source.id);
25
+ bumpRevision(db);
26
+ appendAudit(db, {
27
+ at: now,
28
+ actor,
29
+ sessionId,
30
+ callId,
31
+ tool: 'lifecode_rag_forget',
32
+ action: 'forget',
33
+ target: source.id,
34
+ outcome: 'ok',
35
+ details: { uri: source.uri, chunks },
36
+ });
37
+ return { deleted: true, sourceId: source.id, uri: source.uri, chunks };
38
+ });
39
+ }
40
+
41
+ /** Reconstruye la FTS completa desde `chunks` y verifica el resultado dentro de la misma transacción. */
42
+ export function reindexFts(db, { now = Date.now(), actor = 'model', sessionId = null, callId = null } = {}) {
43
+ return withTransaction(db, () => {
44
+ ftsRebuild(db);
45
+ ftsIntegrityCheck(db);
46
+ bumpRevision(db);
47
+ const chunks = db.prepare('SELECT COUNT(*) AS n FROM chunks').get().n;
48
+ appendAudit(db, {
49
+ at: now, actor, sessionId, callId, tool: 'lifecode_rag_reindex', action: 'reindex.fts',
50
+ target: null, outcome: 'ok', details: { chunks },
51
+ });
52
+ return { rebuiltChunks: chunks };
53
+ });
54
+ }
55
+
56
+ /**
57
+ * Recalcula los vectores de todas las fuentes, una transacción por fuente.
58
+ * `signal` se comprueba entre fuentes: la cancelación no deja una fuente a medio reindexar.
59
+ */
60
+ export function reindexVectors(db, {
61
+ config, now = Date.now(), actor = 'model', sessionId = null, callId = null, signal = null,
62
+ } = {}) {
63
+ const sources = db.prepare('SELECT id FROM sources ORDER BY id ASC').all();
64
+ const model = config.embedding.provider;
65
+ const dim = config.embedding.dim;
66
+ let chunks = 0;
67
+ let done = 0;
68
+
69
+ for (const source of sources) {
70
+ if (signal?.aborted) throw new RagError('cancelled', 'reindex de vectores cancelado', { details: { done, total: sources.length } });
71
+ const rows = db.prepare('SELECT chunk_key, text FROM chunks WHERE source_id = ? ORDER BY ordinal ASC').all(source.id);
72
+ const prepared = rows.map((row) => ({ ...row, vector: embedText(row.text, config.embedding) }));
73
+ withTransaction(db, () => {
74
+ db.prepare('DELETE FROM vectors WHERE chunk_key IN (SELECT chunk_key FROM chunks WHERE source_id = ?)').run(source.id);
75
+ const insert = db.prepare('INSERT INTO vectors (chunk_key, model, dim, vec) VALUES (?, ?, ?, ?)');
76
+ for (const row of prepared) insert.run(row.chunk_key, model, dim, vectorToBlob(row.vector));
77
+ bumpRevision(db);
78
+ appendAudit(db, {
79
+ at: now, actor, sessionId, callId, tool: 'lifecode_rag_reindex', action: 'reindex.vectors', target: source.id,
80
+ outcome: 'ok', details: { chunks: prepared.length, model, dim },
81
+ });
82
+ });
83
+ chunks += prepared.length;
84
+ done += 1;
85
+ }
86
+
87
+ // I4: los vectores del modelo activo cubren exactamente los chunks. Si quedó un vector de otro
88
+ // modelo (o falta alguno), se dice con conteos en vez de mezclar en silencio.
89
+ const chunkCount = db.prepare('SELECT COUNT(*) AS n FROM chunks').get().n;
90
+ const vectorCount = db.prepare('SELECT COUNT(*) AS n FROM vectors WHERE model = ?').get(model).n;
91
+ if (chunkCount !== vectorCount) {
92
+ throw new RagError('vector-index-incomplete', 'el índice de vectores no cubre todos los chunks', {
93
+ details: { chunks: chunkCount, vectors: vectorCount, model, dim },
94
+ });
95
+ }
96
+ return { sources: done, chunks, model, dim };
97
+ }
98
+
99
+ /**
100
+ * Reindexado por operación, en el orden que fija la resolución v2.1: `fta` primero, luego vectores.
101
+ * @param {'fts'|'vectors'|'all'} operation
102
+ */
103
+ export function reindex(db, { operation, config, now = Date.now(), actor = 'model', sessionId = null, callId = null, signal = null } = {}) {
104
+ if (!['fts', 'vectors', 'all'].includes(operation)) {
105
+ throw new RagError('invalid-argument', `operación de reindex no válida: ${operation}`);
106
+ }
107
+ const result = { operation, fts: null, vectors: null };
108
+ if (operation === 'fts' || operation === 'all') result.fts = reindexFts(db, { now, actor, sessionId, callId });
109
+ if (operation === 'vectors' || operation === 'all') {
110
+ result.vectors = reindexVectors(db, { config, now, actor, sessionId, callId, signal });
111
+ }
112
+ return result;
113
+ }
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Métricas agregadas (M3). Sólo se guardan **números** por día, métrica y dimensión cerrada: ni consultas,
3
+ * ni prompts, ni respuestas, ni rutas de usuario. `dim` es un enum de facto que fija el llamador.
4
+ *
5
+ * `metrics_daily` es la única tabla; el detalle por consulta no se persiste. Los percentiles se estiman
6
+ * por histograma de cubos y se etiquetan como estimación en la API.
7
+ */
8
+
9
+ import { RagError } from './errors.mjs';
10
+
11
+ /** Lista cerrada: una métrica nueva exige tocar este módulo y su prueba. */
12
+ export const METRICS = Object.freeze([
13
+ 'query.count',
14
+ 'query.ms',
15
+ 'query.ms_bucket',
16
+ 'query.empty',
17
+ 'context.builds',
18
+ 'context.tokens',
19
+ 'context.truncated',
20
+ 'ingest.documents',
21
+ 'ingest.chunks',
22
+ 'ingest.skipped',
23
+ 'ingest.ms',
24
+ 'errors',
25
+ 'automation.runs',
26
+ 'automation.indexed',
27
+ 'automation.failed',
28
+ ]);
29
+
30
+ export const DIM_PATTERN = /^[a-z0-9][a-z0-9_.:-]{0,63}$/;
31
+
32
+ export function dayOf(at = Date.now()) {
33
+ return new Date(at).toISOString().slice(0, 10);
34
+ }
35
+
36
+ /** Cubos de latencia; el último es abierto y se informa como «≥ 1000 ms». */
37
+ export const LATENCY_BUCKETS = Object.freeze([
38
+ [0, 10, '0-10'],
39
+ [10, 25, '10-25'],
40
+ [25, 50, '25-50'],
41
+ [50, 100, '50-100'],
42
+ [100, 250, '100-250'],
43
+ [250, 500, '250-500'],
44
+ [500, 1_000, '500-1000'],
45
+ [1_000, Infinity, '1000+'],
46
+ ]);
47
+
48
+ export function latencyBucket(ms) {
49
+ const value = Number(ms);
50
+ for (const [min, max, label] of LATENCY_BUCKETS) {
51
+ if (value >= min && value < max) return label;
52
+ }
53
+ return '1000+';
54
+ }
55
+
56
+ function validate(metric, dim) {
57
+ if (!METRICS.includes(metric)) throw new RagError('internal', `métrica no declarada: ${metric}`);
58
+ if (typeof dim !== 'string' || (dim !== '' && !DIM_PATTERN.test(dim))) {
59
+ throw new RagError('internal', `dimensión de métrica inválida: ${dim}`);
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Suma `value` a la celda (día, métrica, dimensión). Es un UPSERT aditivo: dos ejecuciones del mismo día
65
+ * acumulan, nunca se pisan.
66
+ */
67
+ export function recordMetric(db, { metric, value = 1, dim = '', at = Date.now() }) {
68
+ validate(metric, dim);
69
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
70
+ throw new RagError('internal', 'valor de métrica no finito');
71
+ }
72
+ db.prepare(`INSERT INTO metrics_daily (day, metric, dim, value, updated_at) VALUES (?, ?, ?, ?, ?)
73
+ ON CONFLICT(day, metric, dim) DO UPDATE SET value = value + excluded.value, updated_at = excluded.updated_at`)
74
+ .run(dayOf(at), metric, dim, value, at);
75
+ }
76
+
77
+ /** Varias métricas en una transacción; el llamador decide si el fallo es fatal o best-effort.
78
+ * Si ya hay una transacción abierta (ingesta, reindexado), se reutiliza: anidar `BEGIN` en
79
+ * SQLite falla y las métricas deben ser parte de la misma unidad atómica. */
80
+ export function recordMetrics(db, entries, { immediate = false } = {}) {
81
+ if (entries.length === 0) return;
82
+ const nested = db.isTransaction === true;
83
+ if (!nested) db.exec(immediate ? 'BEGIN IMMEDIATE' : 'BEGIN');
84
+ try {
85
+ for (const entry of entries) recordMetric(db, entry);
86
+ if (!nested) db.exec('COMMIT');
87
+ } catch (error) {
88
+ if (!nested) { try { db.exec('ROLLBACK'); } catch { /* la reversión puede haber ocurrido ya */ } }
89
+ throw error;
90
+ }
91
+ }
92
+
93
+ function sinceDay(days, now) {
94
+ const start = now - (Math.max(1, days) - 1) * 86_400_000;
95
+ return dayOf(start);
96
+ }
97
+
98
+ /** Totales por métrica y dimensión en la ventana. */
99
+ export function summary(db, { days = 7, now = Date.now() } = {}) {
100
+ const from = sinceDay(days, now);
101
+ const rows = db.prepare(`SELECT metric, dim, SUM(value) AS total FROM metrics_daily
102
+ WHERE day >= ? GROUP BY metric, dim ORDER BY metric ASC, dim ASC`).all(from);
103
+ return {
104
+ days,
105
+ from,
106
+ metrics: rows.map((row) => ({ metric: row.metric, dim: row.dim, total: Number(row.total) })),
107
+ };
108
+ }
109
+
110
+ /** Serie diaria de una métrica (todas sus dimensiones sumadas o filtradas). */
111
+ export function series(db, { metric, days = 30, dim = undefined, now = Date.now() } = {}) {
112
+ if (!METRICS.includes(metric)) throw new RagError('invalid-argument', `métrica desconocida: ${metric}`);
113
+ const from = sinceDay(days, now);
114
+ const rows = dim === undefined
115
+ ? db.prepare(`SELECT day, SUM(value) AS value FROM metrics_daily WHERE metric = ? AND day >= ? GROUP BY day ORDER BY day ASC`).all(metric, from)
116
+ : db.prepare(`SELECT day, SUM(value) AS value FROM metrics_daily WHERE metric = ? AND dim = ? AND day >= ? GROUP BY day ORDER BY day ASC`).all(metric, dim, from);
117
+ return { metric, days, from, points: rows.map((row) => ({ day: row.day, value: Number(row.value) })) };
118
+ }
119
+
120
+ /**
121
+ * Estimación de percentil desde el histograma de cubos. Devuelve el borde superior del cubo que contiene
122
+ * la posición pedida y lo declara como estimación: no es un percentil exacto.
123
+ */
124
+ export function estimatePercentile(buckets, percentile) {
125
+ const total = buckets.reduce((sum, bucket) => sum + bucket.count, 0);
126
+ if (total === 0) return null;
127
+ const target = Math.min(1, Math.max(0, percentile)) * total;
128
+ let acc = 0;
129
+ for (const bucket of buckets) {
130
+ acc += bucket.count;
131
+ if (acc >= target) {
132
+ return { value: bucket.upper, label: bucket.label, estimated: true, samples: total };
133
+ }
134
+ }
135
+ return { value: buckets.at(-1)?.upper ?? null, label: buckets.at(-1)?.label ?? null, estimated: true, samples: total };
136
+ }
137
+
138
+ export function latencyDistribution(db, { days = 7, now = Date.now() } = {}) {
139
+ const from = sinceDay(days, now);
140
+ const rows = db.prepare(`SELECT dim, SUM(value) AS count FROM metrics_daily
141
+ WHERE metric = 'query.ms_bucket' AND day >= ? GROUP BY dim`).all(from);
142
+ const byLabel = new Map(rows.map((row) => [row.dim, Number(row.count)]));
143
+ const buckets = LATENCY_BUCKETS.map(([min, max, label]) => ({
144
+ label,
145
+ lower: min,
146
+ upper: max === Infinity ? null : max,
147
+ count: byLabel.get(label) ?? 0,
148
+ }));
149
+ return { days, from, buckets, p50: estimatePercentile(buckets, 0.5), p95: estimatePercentile(buckets, 0.95) };
150
+ }
151
+
152
+ /** Purga por retención. Devuelve filas borradas; el llamador audita la operación. */
153
+ export function purgeMetrics(db, { beforeDay, at = Date.now() } = {}) {
154
+ if (typeof beforeDay !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(beforeDay)) {
155
+ throw new RagError('invalid-argument', 'beforeDay debe ser YYYY-MM-DD');
156
+ }
157
+ const result = db.prepare('DELETE FROM metrics_daily WHERE day < ?').run(beforeDay);
158
+ return { deleted: Number(result.changes), beforeDay, at };
159
+ }
160
+
161
+ /** Ventana de retención en días a partir de la configuración y `now`. */
162
+ export function retentionCutoff(config, now = Date.now()) {
163
+ return dayOf(now - config.metrics.retentionDays * 86_400_000);
164
+ }