@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
package/lib/sync.mjs ADDED
@@ -0,0 +1,755 @@
1
+ /**
2
+ * Sincronización por ámbito (PA5).
3
+ *
4
+ * Un ciclo observa **todas** las raíces autorizadas de un ámbito y reconcilia lo observado con lo que
5
+ * el almacén ya tiene. Reglas que no se negocian:
6
+ *
7
+ * 1. Una observación incompleta (permisos, E/S, truncamiento por límite) **no** marca `missing`:
8
+ * `missing` sólo significa «recorrí la raíz entera y el fichero no estaba».
9
+ * 2. `missing` no borra nada: conserva fuentes, chunks, vectores, etiquetas, auditoría y grants.
10
+ * El olvido definitivo sigue siendo una acción humana (`forget`).
11
+ * 3. La reaparición con el mismo hash restaura `present` sin reindexar ni duplicar.
12
+ * 4. Cada fichero se confirma en su propia transacción: una cancelación o un fallo deja lo anterior
13
+ * completo y lo siguiente sin empezar.
14
+ * 5. El ciclo queda en el ledger `operations`/`operation_steps` (`kind='sync'`) y en la auditoría del
15
+ * registro y del ámbito.
16
+ */
17
+
18
+ import { createHash } from 'node:crypto';
19
+ import { readFileSync, readdirSync, statSync } from 'node:fs';
20
+ import { basename, join, relative, sep } from 'node:path';
21
+ import { performance } from 'node:perf_hooks';
22
+
23
+ import { appendAudit } from './audit.mjs';
24
+ import { ftsIntegrityCheck, readMeta, withTransaction } from './db.mjs';
25
+ import { RagError } from './errors.mjs';
26
+ import { createEmbedder } from './embedders.mjs';
27
+ import { mimeOf } from './extract.mjs';
28
+ import { SKIP_DIRECTORIES } from './inputs.mjs';
29
+ import { ingestFiles } from './ingest.mjs';
30
+ import { beginOperation, finishOperation, listInterruptedOperations, recordStep } from './operations.mjs';
31
+ import { PROTECTED_SEGMENTS, isSensitiveName } from './policy.mjs';
32
+ import { appendRegistryAudit } from './registry.mjs';
33
+ import { openScopeStore } from './scope-stores.mjs';
34
+
35
+ export const SYNC_STATES = Object.freeze(['present', 'missing', 'unreadable']);
36
+ export const SYNC_OPERATION_KIND = 'sync';
37
+
38
+ /**
39
+ * Reloj del presupuesto. Debe ser **monotónico**: `Date.now()` puede saltar hacia atrás (ajuste de
40
+ * hora, NTP, cambio manual) y alargaría el tick sin límite, o saltar hacia delante y cortarlo antes de
41
+ * tiempo. `performance.now()` no se ve afectado por el reloj del sistema. El reloj de pared
42
+ * (`now`) se sigue usando para las marcas de tiempo que se guardan y se auditan.
43
+ */
44
+ function defaultMonotonic() {
45
+ return performance.now();
46
+ }
47
+
48
+ /** Clave estable de una fuente dentro de una raíz: ruta relativa en forma POSIX. */
49
+ export function sourceKeyOf(rootPath, filePath) {
50
+ return relative(rootPath, filePath).split(sep).join('/');
51
+ }
52
+
53
+ /**
54
+ * Recorre una raíz sin seguir enlaces y sin bajar a árboles que no aportan conocimiento.
55
+ * Devuelve `complete:false` ante cualquier fallo o truncamiento: el llamador **no** puede deducir
56
+ * desapariciones de un recorrido incompleto.
57
+ */
58
+ export function walkRoot(rootPath, { limit = 20_000, skipDirectories = SKIP_DIRECTORIES } = {}) {
59
+ const files = [];
60
+ const stack = [rootPath];
61
+ while (stack.length > 0) {
62
+ const directory = stack.pop();
63
+ let entries;
64
+ try {
65
+ entries = readdirSync(directory, { withFileTypes: true });
66
+ } catch (cause) {
67
+ return {
68
+ files,
69
+ complete: false,
70
+ error: { path: directory, code: cause?.code ?? 'source-unreadable', message: cause?.message ?? 'no se puede leer el directorio' },
71
+ };
72
+ }
73
+ // Orden estable: el corte por `limit` debe recortar el MISMO subconjunto en cada pasada, o un
74
+ // fichero puede no entrar nunca en el lote y el diagnóstico deja de ser reproducible.
75
+ entries.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));
76
+ for (const entry of entries) {
77
+ if (entry.isSymbolicLink()) continue;
78
+ const child = join(directory, entry.name);
79
+ if (entry.isDirectory()) {
80
+ const lower = entry.name.toLowerCase();
81
+ if (skipDirectories.has(lower) || PROTECTED_SEGMENTS.includes(lower)) continue;
82
+ stack.push(child);
83
+ } else if (entry.isFile()) {
84
+ if (files.length >= limit) {
85
+ return {
86
+ files,
87
+ complete: false,
88
+ error: { path: rootPath, code: 'too-many-files', message: `la raíz supera el límite de ${limit} ficheros por pasada` },
89
+ };
90
+ }
91
+ files.push(child);
92
+ }
93
+ }
94
+ }
95
+ return { files, complete: true, error: null };
96
+ }
97
+
98
+ function sha256Bytes(bytes) {
99
+ return createHash('sha256').update(bytes).digest('hex');
100
+ }
101
+
102
+ /** Lee un fichero y devuelve su huella. Nunca lanza: describe el fallo. */
103
+ export function probeFile(filePath, { maxBytes = null } = {}) {
104
+ try {
105
+ const stat = statSync(filePath);
106
+ if (!stat.isFile()) return { ok: false, code: 'path-unsupported', message: 'no es un fichero regular' };
107
+ // El límite se comprueba antes de leer: un fichero enorme no debe pagarse en cada pasada para
108
+ // acabar rechazado (y reintentado) siempre por el mismo motivo.
109
+ if (maxBytes !== null && stat.size > maxBytes) {
110
+ return { ok: false, code: 'too-large', message: `el fichero supera ${maxBytes} bytes`, bytes: stat.size };
111
+ }
112
+ const bytes = readFileSync(filePath);
113
+ return { ok: true, bytes: bytes.length, sha256: sha256Bytes(bytes) };
114
+ } catch (error) {
115
+ const code = error?.code === 'ENOENT' ? 'source-missing' : error?.code === 'EACCES' || error?.code === 'EPERM' ? 'source-unreadable' : 'source-unreadable';
116
+ return { ok: false, code, message: error?.message ?? 'no se puede leer el fichero' };
117
+ }
118
+ }
119
+
120
+ /** Filas de `sync_state` del ámbito, indexadas por `root_id \u0000 source_key`. */
121
+ export function readSyncRows(registryDb, { scopeKind, scopeId }) {
122
+ const rows = registryDb
123
+ .prepare(`SELECT root_id, source_key, status, last_seen_at, last_hash, missing_since, error_code, updated_at
124
+ FROM sync_state WHERE scope_kind = ? AND scope_id = ?`)
125
+ .all(scopeKind, scopeId);
126
+ const map = new Map();
127
+ for (const row of rows) map.set(`${row.root_id}\u0000${row.source_key}`, row);
128
+ return map;
129
+ }
130
+
131
+ function writeSyncRow(registryDb, {
132
+ scopeKind, scopeId, rootId, sourceKey, status, lastSeenAt = null, lastHash = null, missingSince = null, errorCode = null, now,
133
+ }) {
134
+ if (!SYNC_STATES.includes(status)) {
135
+ throw new RagError('invalid-argument', 'estado de sincronización inválido', { details: { status } });
136
+ }
137
+ registryDb.prepare(`INSERT INTO sync_state
138
+ (scope_kind, scope_id, root_id, source_key, status, last_seen_at, last_hash, missing_since, error_code, updated_at)
139
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
140
+ ON CONFLICT(scope_kind, scope_id, root_id, source_key) DO UPDATE SET
141
+ status = excluded.status,
142
+ last_seen_at = excluded.last_seen_at,
143
+ last_hash = excluded.last_hash,
144
+ missing_since = excluded.missing_since,
145
+ error_code = excluded.error_code,
146
+ updated_at = excluded.updated_at`)
147
+ .run(scopeKind, scopeId, rootId, sourceKey, status,
148
+ lastSeenAt === null ? null : String(lastSeenAt), lastHash, missingSince === null ? null : String(missingSince),
149
+ errorCode, String(now));
150
+ }
151
+
152
+ /**
153
+ * Publica en `sync_state` el resultado real de una ingesta.
154
+ *
155
+ * Sólo un fichero que la ingesta **confirmó** (`ingested` o `skipped`) se marca `present`; uno que
156
+ * falló se marca `unreadable` conservando su hash anterior; y uno que no aparece en ninguna de las
157
+ * dos listas se deja como estaba para que la pasada siguiente lo reintente. La regla importa: marcar
158
+ * `present` antes de ingerir (dentro de `authorize`) permitía que un corte del proceso publicara el
159
+ * hash nuevo sin la fuente, y la pasada siguiente lo leía como «sin cambios» y no lo indexaba nunca.
160
+ *
161
+ * @returns {{present:number, unreadable:number}} cuántas filas se publicaron de cada clase.
162
+ */
163
+ export function markSyncOutcome({ registryDb, scopeKind, scopeId, batch, result, started }) {
164
+ const confirmed = new Map();
165
+ for (const entry of [...(result.ingested ?? []), ...(result.skipped ?? [])]) {
166
+ if (typeof entry?.uri === 'string') confirmed.set(entry.uri, entry);
167
+ }
168
+ const failed = new Map();
169
+ for (const error of result.errors ?? []) {
170
+ if (typeof error?.path === 'string') failed.set(error.path, error);
171
+ }
172
+ let present = 0;
173
+ let unreadable = 0;
174
+ for (const item of batch) {
175
+ if (confirmed.has(item.abs)) {
176
+ withTransaction(registryDb, () => writeSyncRow(registryDb, {
177
+ scopeKind, scopeId, rootId: item.rootId, sourceKey: item.key, status: 'present',
178
+ lastSeenAt: started, lastHash: item.sha256, missingSince: null, errorCode: null, now: started,
179
+ }));
180
+ present += 1;
181
+ continue;
182
+ }
183
+ const error = failed.get(item.abs);
184
+ if (!error) continue;
185
+ withTransaction(registryDb, () => writeSyncRow(registryDb, {
186
+ scopeKind, scopeId, rootId: item.rootId, sourceKey: item.key, status: 'unreadable',
187
+ lastSeenAt: started, lastHash: item.previous?.last_hash ?? null, missingSince: null,
188
+ errorCode: error.code ?? 'internal', now: started,
189
+ }));
190
+ unreadable += 1;
191
+ }
192
+ return { present, unreadable };
193
+ }
194
+
195
+ /**
196
+ * Publica en `sync_state` lo que el almacén del ámbito **demuestra** que ya está indexado.
197
+ *
198
+ * Se usa cuando la ingesta no llega a devolver su resultado (cancelación, revocación o fallo fatal):
199
+ * `ingestFiles` confirma una transacción por fichero, así que «lo que está en `sources` con ese
200
+ * hash» es exactamente lo confirmado. El resto se queda sin marca y la pasada siguiente lo reintenta.
201
+ */
202
+ export function reconcileSyncFromStore({ registryDb, store, scopeKind, scopeId, batch, started }) {
203
+ let present = 0;
204
+ for (const item of batch) {
205
+ const row = store
206
+ .prepare('SELECT 1 AS ok FROM sources WHERE uri = ? AND sha256 = ? LIMIT 1')
207
+ .get(item.abs, item.sha256);
208
+ if (!row) continue;
209
+ withTransaction(registryDb, () => writeSyncRow(registryDb, {
210
+ scopeKind, scopeId, rootId: item.rootId, sourceKey: item.key, status: 'present',
211
+ lastSeenAt: started, lastHash: item.sha256, missingSince: null, errorCode: null, now: started,
212
+ }));
213
+ present += 1;
214
+ }
215
+ return { present };
216
+ }
217
+
218
+ /** Estado de sincronización agregado por ámbito, para `sync status`. */export function syncStatus(registryDb, { scopeKind, scopeId } = {}) {
219
+ const where = scopeKind && scopeId ? 'WHERE scope_kind = ? AND scope_id = ?' : '';
220
+ const params = scopeKind && scopeId ? [scopeKind, scopeId] : [];
221
+ const rows = registryDb
222
+ .prepare(`SELECT scope_kind, scope_id, status, COUNT(*) AS n, MAX(updated_at) AS last_at
223
+ FROM sync_state ${where} GROUP BY scope_kind, scope_id, status ORDER BY scope_kind, scope_id, status`)
224
+ .all(...params);
225
+ return rows.map((row) => ({ scope_kind: row.scope_kind, scope_id: row.scope_id, status: row.status, count: row.n, last_at: row.last_at }));
226
+ }
227
+
228
+ /**
229
+ * Comprueba que el ámbito se puede sincronizar **ahora**.
230
+ *
231
+ * La sincronización la ejecuta el perfil (humano o automatización), no una consulta del modelo, así que
232
+ * no consulta grants. Sí respeta el ciclo de vida: ámbito archivado, raíz revocada o sesión caída paran
233
+ * el ciclo. Cuando la pasada la inicia una sesión (`sessionId`), se revalida también su autorización
234
+ * vigente para no seguir trabajando para una sesión que ya perdió el ámbito.
235
+ */
236
+ export function assertScopeSyncable({ registryDb, scope, sessionId = null, now = Date.now } = {}) {
237
+ const table = scope.kind === 'prj' ? 'projects' : 'libraries';
238
+ const row = registryDb.prepare(`SELECT id, name, status FROM ${table} WHERE id = ?`).get(scope.id);
239
+ if (!row) {
240
+ throw new RagError('scope-forbidden', 'el ámbito no existe en el registro', { details: { scope_id: scope.id, scope_kind: scope.kind } });
241
+ }
242
+ if (row.status !== 'active') {
243
+ throw new RagError('scope-forbidden', 'el ámbito está archivado y no se sincroniza', {
244
+ details: { scope_id: scope.id, scope_kind: scope.kind, reason: scope.kind === 'prj' ? 'project-archived' : 'library-archived' },
245
+ });
246
+ }
247
+ const roots = registryDb
248
+ .prepare(`SELECT id, path, state FROM roots WHERE scope_kind = ? AND scope_id = ? AND state = 'authorized' ORDER BY path`)
249
+ .all(scope.kind, scope.id);
250
+ if (roots.length === 0) {
251
+ throw new RagError('sync-root-unavailable', 'el ámbito no tiene raíces autorizadas', {
252
+ details: { scope_id: scope.id, scope_kind: scope.kind, reason: 'no-roots' },
253
+ });
254
+ }
255
+ if (sessionId) {
256
+ const session = registryDb.prepare('SELECT session_id, project_id, state FROM session_scope WHERE session_id = ?').get(sessionId);
257
+ if (!session) {
258
+ throw new RagError('session-invalid', 'la sesión que inició la sincronización no existe', { details: { session_id: sessionId } });
259
+ }
260
+ if (session.state !== 'active') {
261
+ throw new RagError('session-expired', 'la sesión que inició la sincronización ya no está activa', {
262
+ details: { session_id: sessionId, state: session.state },
263
+ });
264
+ }
265
+ if (scope.kind === 'lib') {
266
+ const grant = registryDb
267
+ .prepare('SELECT id FROM grants WHERE project_id = ? AND library_id = ? AND revoked_at IS NULL')
268
+ .get(session.project_id, scope.id);
269
+ if (!grant) {
270
+ throw new RagError('grant-revoked', 'la biblioteca ya no está concedida al proyecto de la sesión', {
271
+ details: { session_id: sessionId, scope_id: scope.id, scope_kind: 'lib', reason: 'grant-revoked' },
272
+ });
273
+ }
274
+ }
275
+ }
276
+ return { scope: { kind: scope.kind, id: scope.id, name: row.name }, roots };
277
+ }
278
+
279
+ /** Verificación de integridad del almacén tras aplicar cambios. */
280
+ export function verifyScopeStore(db, { model = null, checkFts = true } = {}) {
281
+ const count = (sql, ...params) => db.prepare(sql).get(...params).n;
282
+ const counts = {
283
+ sources: count('SELECT COUNT(*) AS n FROM sources'),
284
+ chunks: count('SELECT COUNT(*) AS n FROM chunks'),
285
+ vectors: count('SELECT COUNT(*) AS n FROM vectors'),
286
+ };
287
+ const orphans = count('SELECT COUNT(*) AS n FROM chunks c LEFT JOIN sources s ON s.id = c.source_id WHERE s.id IS NULL');
288
+ const missingVectors = model
289
+ ? count('SELECT COUNT(*) AS n FROM chunks c LEFT JOIN vectors v ON v.chunk_key = c.chunk_key AND v.model = ? WHERE v.chunk_key IS NULL', model)
290
+ : 0;
291
+ // `integrity-check` de FTS es O(índice): se paga sólo cuando la pasada escribió, no en cada tick.
292
+ if (checkFts) ftsIntegrityCheck(db);
293
+ return { counts, orphans, missingVectors, fts: checkFts ? 'ok' : 'not-checked' };
294
+ }
295
+
296
+ /**
297
+ * Un ciclo de sincronización sobre un ámbito.
298
+ *
299
+ * @returns {Promise<{scope_kind:string, scope_id:string, operation:string|null, dry_run:boolean,
300
+ * scanned:number, observed:number, unchanged:number, new:number, changed:number, missing:number,
301
+ * unreadable:number, ingested:number, skipped:number, failed:number, cancelled:boolean,
302
+ * complete:boolean, roots:Array, verification:object|null, ms:number, errors:Array}>}
303
+ */
304
+ export async function syncScope({
305
+ registryDb, profileRoot, profileKey, scope, config, embedder = null, now = Date.now, signal = null,
306
+ limit = null, budgetMs = null, monotonic = null, actor = 'automation', sessionId = null, dryRun = false,
307
+ } = {}) {
308
+ if (!registryDb) throw new RagError('invalid-argument', 'la sincronización necesita el registro abierto');
309
+ if (!profileRoot || !profileKey) throw new RagError('invalid-argument', 'la sincronización necesita el perfil resuelto');
310
+
311
+ const started = now();
312
+ const maxFiles = Math.max(1, limit ?? config?.automation?.maxFilesPerRun ?? 50);
313
+ // Presupuesto de tiempo del tick (M6.7). `Infinity` = sin presupuesto (CLI y pruebas de motor).
314
+ // El presupuesto se mide con reloj MONOTÓNICO (M6.8, R-07): un ajuste del reloj del sistema no puede
315
+ // alargar ni acortar el tick. `started` (reloj de pared) sigue siendo la marca que se persiste.
316
+ const budget = Number.isFinite(budgetMs) && budgetMs > 0 ? budgetMs : null;
317
+ const clock = typeof monotonic === 'function' ? monotonic : defaultMonotonic;
318
+ const deadline = budget === null ? Infinity : clock() + budget;
319
+ const scopeKind = scope.kind;
320
+ const scopeId = scope.id;
321
+ const target = `${scopeKind}:${scopeId}`;
322
+ const summary = {
323
+ scope_kind: scopeKind, scope_id: scopeId, operation: null, dry_run: dryRun === true,
324
+ scanned: 0, observed: 0, unchanged: 0, new: 0, changed: 0, missing: 0, unreadable: 0, unsupported: 0, reappeared: 0,
325
+ sensitive: 0,
326
+ ingested: 0, skipped: 0, failed: 0, cancelled: false, complete: true, outcome: null,
327
+ budget_ms: budget, budget_exhausted: false, stop_reason: null,
328
+ roots: [], verification: null, ms: 0, errors: [],
329
+ };
330
+
331
+ const { roots } = assertScopeSyncable({ registryDb, scope, sessionId, now });
332
+ summary.roots = roots.map((root) => ({ root_id: root.id, path: root.path }));
333
+
334
+ // El modelo se toma del proveedor REAL, no de la config en crudo: con un proveedor remoto la
335
+ // etiqueta guardada en `vectors.model` es `remote:<modelo>` y comparar contra el nombre de la
336
+ // configuración marcaría todos los chunks como «sin vector» y el ámbito como corrupto.
337
+ //
338
+ // Compuerta de egreso: un proveedor remoto sólo se usa si la capa que llama ya lo construyó tras
339
+ // una aprobación humana. La sincronización automática no tiene canal de aprobación, así que no
340
+ // puede enviar texto a un tercero por su cuenta (antes lo hacía: `createEmbedder` sin `requireEgress`).
341
+ // Se decide ANTES de abrir la operación: un rechazo no debe dejar una fila `started` mintiendo.
342
+ const localEmbedder = config?.embedding?.provider === 'local-hash-v1' || !config?.embedding?.provider;
343
+ const provider = embedder ?? (localEmbedder ? createEmbedder(config) : null);
344
+ if (!provider) {
345
+ throw new RagError('egress-denied', 'la sincronización no puede usar un proveedor de embedding remoto sin aprobación', {
346
+ details: { reason: 'automation-egress', provider: config?.embedding?.provider ?? null },
347
+ });
348
+ }
349
+ const model = provider?.model ?? config?.embedding?.provider ?? null;
350
+
351
+ // Una pasada anterior interrumpida no se repite a ciegas: se cierra como `reconciled` y se documenta.
352
+ // La sincronización es idempotente (por hash), pero la fila abierta no puede quedar mintiendo.
353
+ for (const interrupted of listInterruptedOperations(registryDb, { kind: SYNC_OPERATION_KIND })) {
354
+ let previous = null;
355
+ try { previous = interrupted.detail ? JSON.parse(interrupted.detail) : null; } catch { previous = null; }
356
+ if (previous?.scope_id !== scopeId || previous?.scope_kind !== scopeKind) continue;
357
+ finishOperation(registryDb, {
358
+ operationId: interrupted.id,
359
+ state: 'reconciled',
360
+ now: started,
361
+ detail: { ...(previous ?? {}), reason: 'sync-interrumpida-reconciliada', reconciled_at: started },
362
+ });
363
+ }
364
+
365
+ const operation = dryRun
366
+ ? null
367
+ : beginOperation(registryDb, { kind: SYNC_OPERATION_KIND, now: started, detail: { scope_kind: scopeKind, scope_id: scopeId } });
368
+ if (operation) summary.operation = operation.id;
369
+
370
+ const rows = readSyncRows(registryDb, { scopeKind, scopeId });
371
+ const observations = new Map();
372
+ const observedKeys = new Set();
373
+ const seenRoots = new Set();
374
+ // Un único handle para comprobar presencia: se abre la primera vez que hace falta.
375
+ let presenceStore;
376
+ const presenceStoreOpen = () => {
377
+ if (presenceStore === undefined) {
378
+ try {
379
+ presenceStore = openScopeStore({ profileRoot, profileKey, scope: { kind: scopeKind, id: scopeId }, create: false, now: started });
380
+ } catch {
381
+ presenceStore = null;
382
+ }
383
+ }
384
+ return presenceStore ?? null;
385
+ };
386
+
387
+ try {
388
+ // ---- Observar ----
389
+ for (const root of roots) {
390
+ if (signal?.aborted) { summary.cancelled = true; break; }
391
+ const walkLimit = Math.max(maxFiles * 20, 1_000);
392
+ const walk = walkRoot(root.path, { limit: walkLimit });
393
+ summary.scanned += walk.files.length;
394
+ if (!walk.complete) {
395
+ summary.complete = false;
396
+ summary.errors.push({ root_id: root.id, path: walk.error?.path ?? root.path, code: walk.error?.code ?? 'sync-root-unavailable', message: walk.error?.message ?? 'recorrido incompleto' });
397
+ summary.roots[summary.roots.findIndex((item) => item.root_id === root.id)] = { root_id: root.id, path: root.path, complete: false, error: walk.error ?? null };
398
+ // Recorrido incompleto: esta raíz NO entra en `seenRoots`, así que no puede deducir
399
+ // desapariciones. Pero el prefijo que sí se recorrió se procesa igual: descartarlo dejaba la
400
+ // raíz sin sincronizar nunca y, con el walk cortado siempre en el mismo punto, sin avance.
401
+ } else {
402
+ seenRoots.add(root.id);
403
+ summary.roots[summary.roots.findIndex((item) => item.root_id === root.id)] = { root_id: root.id, path: root.path, complete: true, files: walk.files.length };
404
+ }
405
+ for (const file of walk.files) {
406
+ const key = `${root.id}\u0000${sourceKeyOf(root.path, file)}`;
407
+ if (observedKeys.has(key)) continue;
408
+ observedKeys.add(key);
409
+ observations.set(key, { rootId: root.id, rootPath: root.path, abs: file, key: sourceKeyOf(root.path, file), previous: rows.get(key) ?? null });
410
+ }
411
+ }
412
+
413
+ // ---- Planificar ----
414
+ const pending = [];
415
+ const maxBytes = Number.isInteger(config?.maxFileBytes) ? config.maxFileBytes : null;
416
+ for (const [key, item] of observations) {
417
+ // Nombre con forma de secreto (`.env`, `*.pem`, `id_rsa`…). Se excluye por política y se cuenta
418
+ // aparte: el índice no guarda credenciales y el operador ve cuántos ficheros se dejaron fuera.
419
+ // No se marca `unreadable`: no es un fallo, es una exclusión deliberada y estable.
420
+ if (isSensitiveName(basename(item.abs))) {
421
+ summary.sensitive += 1;
422
+ continue;
423
+ }
424
+ // Formato que el extractor no soporta (binarios, `.sqlite3`, imágenes…). El motor no puede
425
+ // indexarlo: no se lee, no se marca `unreadable` y no se reintenta en cada pasada. Se cuenta
426
+ // aparte para que el resultado siga siendo verificable y el recuento sea explícito.
427
+ if (mimeOf(item.abs) === undefined) {
428
+ summary.unsupported += 1;
429
+ continue;
430
+ }
431
+ const probe = probeFile(item.abs, { maxBytes });
432
+ if (!probe.ok) {
433
+ summary.unreadable += 1;
434
+ if (!dryRun) {
435
+ withTransaction(registryDb, () => writeSyncRow(registryDb, {
436
+ scopeKind, scopeId, rootId: item.rootId, sourceKey: item.key, status: 'unreadable',
437
+ lastSeenAt: started, lastHash: item.previous?.last_hash ?? null, missingSince: null,
438
+ errorCode: probe.code, now: started,
439
+ }));
440
+ }
441
+ summary.errors.push({ path: item.abs, code: probe.code, message: probe.message });
442
+ continue;
443
+ }
444
+ summary.observed += 1;
445
+ const previous = item.previous;
446
+ const restored = previous?.status === 'missing';
447
+ // «Sin cambios» exige que el estado anterior fuera `present`: un `unreadable` con el mismo hash
448
+ // no demuestra que la fuente esté indexada.
449
+ if (previous && previous.status === 'present' && previous.last_hash === probe.sha256) {
450
+ summary.unchanged += 1;
451
+ if (!dryRun) {
452
+ withTransaction(registryDb, () => writeSyncRow(registryDb, {
453
+ scopeKind, scopeId, rootId: item.rootId, sourceKey: item.key, status: 'present',
454
+ lastSeenAt: started, lastHash: probe.sha256, missingSince: null, errorCode: null, now: started,
455
+ }));
456
+ }
457
+ continue;
458
+ }
459
+ const sourceExists = scopeHasSource({ store: presenceStoreOpen(), profileRoot, profileKey, scope, uri: item.abs, sha256: probe.sha256 });
460
+ if (sourceExists === 'same') {
461
+ // Reaparición con el mismo hash: se restaura `present` sin reindexar ni duplicar.
462
+ if (restored) summary.reappeared += 1;
463
+ else summary.unchanged += 1;
464
+ if (!dryRun) {
465
+ withTransaction(registryDb, () => writeSyncRow(registryDb, {
466
+ scopeKind, scopeId, rootId: item.rootId, sourceKey: item.key, status: 'present',
467
+ lastSeenAt: started, lastHash: probe.sha256, missingSince: null, errorCode: null, now: started,
468
+ }));
469
+ }
470
+ continue;
471
+ }
472
+ if (previous?.last_hash && previous.last_hash !== probe.sha256) summary.changed += 1;
473
+ else summary.new += 1;
474
+ pending.push({ ...item, sha256: probe.sha256, bytes: probe.bytes });
475
+ }
476
+
477
+ // ---- Desapariciones (sólo con observación completa de su raíz) ----
478
+ for (const [key, row] of rows) {
479
+ if (row.status === 'missing') continue;
480
+ const [rootId, sourceKey] = key.split('\u0000');
481
+ if (!seenRoots.has(rootId)) continue;
482
+ if (observedKeys.has(key)) continue;
483
+ summary.missing += 1;
484
+ if (dryRun) continue;
485
+ withTransaction(registryDb, () => writeSyncRow(registryDb, {
486
+ scopeKind, scopeId, rootId, sourceKey, status: 'missing',
487
+ lastSeenAt: started, lastHash: row.last_hash, missingSince: started, errorCode: null, now: started,
488
+ }));
489
+ }
490
+
491
+ if (operation) recordStep(registryDb, { operationId: operation.id, step: 'observe', now: started, effectKey: `${operation.id}:observe` });
492
+
493
+ // ---- Aplicar ----
494
+ if (!dryRun && pending.length > 0) {
495
+ if (signal?.aborted) summary.cancelled = true;
496
+ else if (budget !== null && clock() >= deadline) {
497
+ // El presupuesto se agotó durante la observación: no se abre siquiera el lote. El trabajo queda
498
+ // pendiente para el siguiente tick, sin marcar nada como indexado.
499
+ summary.budget_exhausted = true;
500
+ summary.complete = false;
501
+ } else {
502
+ const db = openScopeStore({ profileRoot, profileKey, scope: { kind: scopeKind, id: scopeId }, create: true, now: started });
503
+ try {
504
+ const batch = pending.slice(0, maxFiles);
505
+ let result = null;
506
+ let budgetStopped = false;
507
+ try {
508
+ result = await ingestFiles({
509
+ db,
510
+ files: batch.map((item) => item.abs),
511
+ collection: 'default',
512
+ now: started,
513
+ config,
514
+ embedder: provider,
515
+ actor,
516
+ authorize: async (file) => {
517
+ if (signal?.aborted) {
518
+ throw new RagError('cancelled', 'la sincronización se canceló', { details: { reason: 'signal-aborted', where: 'sync:file' } });
519
+ }
520
+ // Presupuesto del tick: se corta entre fichero y fichero, nunca a mitad de una
521
+ // transacción. Se lanza desde `authorize` (antes de preparar el fichero), así que
522
+ // `ingestFiles` no llega a escribir nada del fichero siguiente.
523
+ if (budget !== null && clock() >= deadline) {
524
+ throw new RagError('cancelled', 'la sincronización agotó el presupuesto del tick', {
525
+ details: { reason: 'budget-exhausted', where: 'sync:file', budget_ms: budget },
526
+ });
527
+ }
528
+ // Revalidación por fichero: una revocación o un archivado a mitad para el ciclo.
529
+ assertScopeSyncable({ registryDb, scope, sessionId, now });
530
+ },
531
+ });
532
+ } catch (error) {
533
+ // Una ingesta interrumpida no devuelve lista de confirmados: se publica lo que el almacén
534
+ // demuestra que sí entró (una transacción por fichero), y el resto queda para reintentar.
535
+ const recovered = reconcileSyncFromStore({ registryDb, store: db, scopeKind, scopeId, batch, started });
536
+ if (recovered.present > 0) summary.ingested += recovered.present;
537
+ if (error?.details?.reason === 'budget-exhausted') {
538
+ // Agotar el presupuesto no es un fallo del ámbito: la pasada es parcial y lo confirmado
539
+ // se conserva. Se anota el paso `apply` para que el ledger no quede a medias.
540
+ budgetStopped = true;
541
+ summary.budget_exhausted = true;
542
+ summary.complete = false;
543
+ } else {
544
+ throw error;
545
+ }
546
+ }
547
+ if (budgetStopped) {
548
+ if (operation) recordStep(registryDb, { operationId: operation.id, step: 'apply', now: now(), effectKey: `${operation.id}:apply` });
549
+ } else {
550
+ // `sync_state` se marca DESPUÉS de la ingesta. Marcarlo antes (dentro de `authorize`) dejaba
551
+ // una ventana en la que un corte del proceso publicaba `present` con el hash nuevo sin que
552
+ // la fuente existiera: la pasada siguiente lo veía «sin cambios» y nunca se indexaba.
553
+ markSyncOutcome({ registryDb, scopeKind, scopeId, batch, result, started });
554
+ summary.ingested = result.ingested.length;
555
+ summary.skipped = result.skipped.length;
556
+ summary.failed = result.errors.length;
557
+ for (const error of result.errors) summary.errors.push(error);
558
+ if (pending.length > batch.length) {
559
+ summary.complete = false;
560
+ summary.errors.push({ path: null, code: 'too-many-files', message: `quedan ${pending.length - batch.length} ficheros para la siguiente pasada` });
561
+ }
562
+ if (operation) recordStep(registryDb, { operationId: operation.id, step: 'apply', now: now(), effectKey: `${operation.id}:apply` });
563
+ }
564
+ } finally {
565
+ try { db.close(); } catch { /* cerrar dos veces no es un fallo */ }
566
+ }
567
+ }
568
+ }
569
+
570
+ // ---- Verificar ----
571
+ // Se verifica SIEMPRE, haya o no ingesta: una pasada sin cambios también debe detectar huérfanos y
572
+ // vectores perdidos. La comprobación cara de FTS sólo se paga cuando la pasada escribió algo.
573
+ const verificationDb = openScopeStore({ profileRoot, profileKey, scope: { kind: scopeKind, id: scopeId }, create: false, now: started });
574
+ if (verificationDb) {
575
+ try {
576
+ summary.verification = verifyScopeStore(verificationDb, { model, checkFts: pending.length > 0 });
577
+ } finally {
578
+ try { verificationDb.close(); } catch { /* doble cierre */ }
579
+ }
580
+ if (summary.verification.orphans > 0 || summary.verification.missingVectors > 0) {
581
+ throw new RagError('scope-store-corrupt', 'la verificación posterior a la sincronización encontró incoherencias', {
582
+ details: { scope_id: scopeId, scope_kind: scopeKind, ...summary.verification },
583
+ });
584
+ }
585
+ if (operation) recordStep(registryDb, { operationId: operation.id, step: 'verify', now: now(), effectKey: `${operation.id}:verify` });
586
+ }
587
+
588
+ summary.ms = Math.max(0, now() - started);
589
+ // Un único predicado de éxito para el ledger, la auditoría y el CLI. `too-many-files` no es un
590
+ // fallo por sí mismo, pero una pasada que dejó trabajo pendiente tampoco es un éxito completo.
591
+ const realErrors = summary.errors.filter((error) => error.code !== 'too-many-files');
592
+ summary.outcome = summary.cancelled ? 'skipped' : realErrors.length > 0 ? 'failed' : summary.complete ? 'ok' : 'partial';
593
+ // Motivo de finalización, para que la observabilidad no tenga que deducirlo de los recuentos.
594
+ summary.stop_reason = summary.cancelled
595
+ ? 'cancelled'
596
+ : realErrors.length > 0
597
+ ? 'error'
598
+ : summary.budget_exhausted
599
+ ? 'budget'
600
+ : summary.complete
601
+ ? 'complete'
602
+ : 'file-limit';
603
+ if (operation) {
604
+ finishOperation(registryDb, {
605
+ operationId: operation.id,
606
+ // M6.7 §6: alcanzar el límite de ficheros o el presupuesto no es un fallo del ledger. Todos
607
+ // los pasos terminaron y cada efecto quedó confirmado; lo que falta es trabajo para el tick
608
+ // siguiente, y eso queda escrito en `detail.complete`. Antes se cerraba `failed`, que se leía
609
+ // como error de sincronización cuando no había ninguno (hallazgo de M6.5).
610
+ state: summary.cancelled || realErrors.length > 0 ? 'failed' : 'committed',
611
+ now: now(),
612
+ detail: { ...summary, errors: summary.errors.slice(0, 20) },
613
+ });
614
+ }
615
+ return summary;
616
+ } catch (error) {
617
+ summary.ms = Math.max(0, now() - started);
618
+ if (error?.code === 'cancelled') summary.cancelled = true;
619
+ if (operation) {
620
+ try {
621
+ finishOperation(registryDb, { operationId: operation.id, state: 'failed', now: now(), detail: { ...summary, failure: { code: error?.code ?? 'internal', message: error?.message ?? '' } } });
622
+ } catch { /* la operación no puede ocultar el fallo original */ }
623
+ }
624
+ if (error instanceof RagError) throw error;
625
+ throw new RagError('internal', `la sincronización falló: ${error?.message ?? 'error desconocido'}`, { cause: error });
626
+ } finally {
627
+ if (presenceStore) { try { presenceStore.close(); } catch { /* doble cierre */ } }
628
+ // Auditoría en los dos dominios. Nunca puede convertir un ciclo correcto en un fallo.
629
+ try {
630
+ if (!dryRun) {
631
+ const outcome = summary.outcome === 'partial' ? 'skipped' : summary.outcome ?? (summary.cancelled ? 'skipped' : summary.failed > 0 ? 'failed' : 'ok');
632
+ appendRegistryAudit(registryDb, {
633
+ at: now(),
634
+ actor,
635
+ session_id: sessionId,
636
+ action: 'sync.run',
637
+ target: scopeId,
638
+ outcome,
639
+ detail: { scope_kind: scopeKind, ...summary, errors: summary.errors.slice(0, 20) },
640
+ });
641
+ }
642
+ } catch { /* la auditoría del registro no puede tumbar el ciclo */ }
643
+ try {
644
+ if (!dryRun && summary.observed + summary.missing > 0) {
645
+ const db = openScopeStore({ profileRoot, profileKey, scope: { kind: scopeKind, id: scopeId }, create: false, now: now() });
646
+ if (db) {
647
+ try {
648
+ withTransaction(db, () => appendAudit(db, {
649
+ at: now(),
650
+ actor,
651
+ sessionId,
652
+ tool: 'lifecode_rag_sync',
653
+ action: 'sync.run',
654
+ target: scopeId,
655
+ outcome: (summary.outcome === 'partial' ? 'skipped' : summary.outcome) ?? (summary.cancelled ? 'skipped' : summary.failed > 0 ? 'failed' : 'ok'),
656
+ details: { new: summary.new, changed: summary.changed, missing: summary.missing, unchanged: summary.unchanged, ingested: summary.ingested, failed: summary.failed },
657
+ }));
658
+ } finally {
659
+ try { db.close(); } catch { /* idem */ }
660
+ }
661
+ }
662
+ }
663
+ } catch { /* idem */ }
664
+ }
665
+ }
666
+
667
+ /** ¿El almacén ya tiene una fuente con esta URI y hash? Devuelve `'same'`, `'different'` o `null`. */
668
+ function scopeHasSource({ store, profileRoot, profileKey, scope, uri, sha256 }) {
669
+ // Si la pasada ya tiene el almacén abierto, se reutiliza: abrir y cerrar por fichero ejecuta
670
+ // `quick_check`, la validación de FTS y la cabeza de auditoría una vez por fichero observado.
671
+ let db = store ?? null;
672
+ const owns = db === null;
673
+ try {
674
+ if (!db) db = openScopeStore({ profileRoot, profileKey, scope: { kind: scope.kind, id: scope.id }, create: false });
675
+ if (!db) return null;
676
+ const row = db.prepare('SELECT sha256 FROM sources WHERE uri = ?').get(uri);
677
+ if (!row) return null;
678
+ return row.sha256 === sha256 ? 'same' : 'different';
679
+ } catch {
680
+ return null;
681
+ } finally {
682
+ if (owns && db) { try { db.close(); } catch { /* idem */ } }
683
+ }
684
+ }
685
+
686
+ /**
687
+ * Ámbitos activos con al menos una raíz autorizada: lo que una pasada automática puede tocar.
688
+ * Un ámbito sin raíces no tiene nada que sincronizar y no se incluye (no es un error).
689
+ */
690
+ export function activeSyncScopes(registryDb) {
691
+ const rows = registryDb
692
+ .prepare(`SELECT scope_kind, scope_id, COUNT(*) AS roots FROM roots WHERE state = 'authorized' GROUP BY scope_kind, scope_id`)
693
+ .all();
694
+ if (rows.length === 0) return [];
695
+ const scopes = [];
696
+ for (const row of rows) {
697
+ const table = row.scope_kind === 'prj' ? 'projects' : 'libraries';
698
+ const item = registryDb.prepare(`SELECT id, name, status FROM ${table} WHERE id = ?`).get(row.scope_id);
699
+ if (!item || item.status !== 'active') continue;
700
+ scopes.push({ kind: row.scope_kind, id: item.id, name: item.name, roots: row.roots });
701
+ }
702
+ return scopes.sort((left, right) => `${left.kind}:${left.name}`.localeCompare(`${right.kind}:${right.name}`));
703
+ }
704
+
705
+ /**
706
+ * Sincronización de varios ámbitos: secuencial a propósito. Un perfil puede tener hasta ocho ámbitos
707
+ * abiertos, pero sincronizar en paralelo multiplicaría la contención de escritura sin ganar nada.
708
+ */
709
+ export async function syncScopes({ registryDb, profileRoot, profileKey, scopes, config, embedder = null, now = Date.now, signal = null, limit = null, budgetMs = null, monotonic = null, actor = 'automation', sessionId = null, dryRun = false }) {
710
+ const results = [];
711
+ for (const scope of scopes) {
712
+ if (signal?.aborted) break;
713
+ try {
714
+ results.push(await syncScope({ registryDb, profileRoot, profileKey, scope, config, embedder, now, signal, limit, budgetMs, monotonic, actor, sessionId, dryRun }));
715
+ } catch (error) {
716
+ if (signal?.aborted) break;
717
+ results.push({
718
+ scope_kind: scope.kind, scope_id: scope.id, operation: null, dry_run: dryRun === true,
719
+ scanned: 0, observed: 0, unchanged: 0, new: 0, changed: 0, missing: 0, unreadable: 0, unsupported: 0, reappeared: 0,
720
+ ingested: 0, skipped: 0, failed: 1, cancelled: false, complete: false, roots: [], verification: null,
721
+ ms: 0, errors: [{ path: null, code: error?.code ?? 'internal', message: error?.message ?? 'fallo de sincronización' }],
722
+ });
723
+ }
724
+ }
725
+ return results;
726
+ }
727
+
728
+ /**
729
+ * Al olvidar una fuente su fila de `sync_state` quedaría diciendo `present` de algo que ya no está en
730
+ * el almacén: la pasada siguiente lo vería «sin cambios» y el fichero no se reindexaría nunca.
731
+ * Devuelve cuántas filas se descartaron.
732
+ */
733
+ export function clearSyncState({ registryDb, scopeKind, scopeId, roots = [], uri }) {
734
+ if (!registryDb || !uri) return 0;
735
+ let cleared = 0;
736
+ for (const root of roots) {
737
+ if (!root?.path) continue;
738
+ const key = sourceKeyOf(root.path, uri);
739
+ if (key === '..' || key.startsWith('../')) continue;
740
+ const info = registryDb
741
+ .prepare('DELETE FROM sync_state WHERE scope_kind = ? AND scope_id = ? AND root_id = ? AND source_key = ?')
742
+ .run(scopeKind, scopeId, root.id, key);
743
+ cleared += Number(info?.changes ?? 0);
744
+ }
745
+ return cleared;
746
+ }
747
+
748
+ /** Metadatos de sincronización del almacén para diagnóstico (no cambia nada). */
749
+ export function storeSyncMeta(db) {
750
+ return {
751
+ scope_id: readMeta(db, 'scope_id'),
752
+ store_state: readMeta(db, 'store_state'),
753
+ index_revision: readMeta(db, 'index_revision'),
754
+ };
755
+ }