@designerbyron/lifecode-rag 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +191 -2
  3. package/bin/lifecode-rag.mjs +449 -0
  4. package/client.js +2801 -0
  5. package/cordis.patch.yml +3 -0
  6. package/docs/ARCHITECTURE-v0.2.md +269 -0
  7. package/docs/AUTO-DISCOVERY.md +111 -0
  8. package/docs/AUTOMATION-POLICIES.md +232 -0
  9. package/docs/CONTRATO-v0.1.md +195 -0
  10. package/docs/EMBEDDING-PROVIDERS.md +105 -0
  11. package/docs/OBSERVABILITY.md +241 -0
  12. package/docs/PA-UI-0-API-CONTRACT.md +802 -0
  13. package/docs/PERFORMANCE-BUDGETS.md +118 -0
  14. package/docs/PROJECT-AWARE-ARCHITECTURE.md +580 -0
  15. package/docs/PROJECT-AWARE-DATA-CONTRACT.md +411 -0
  16. package/docs/PROJECT-AWARE-ERROR-CONTRACT.md +112 -0
  17. package/docs/PROJECT-AWARE-SESSION-CONTRACT.md +120 -0
  18. package/docs/WORKSPACE-API.md +239 -0
  19. package/icon.svg +7 -0
  20. package/index.js +198 -0
  21. package/lib/audit-export.mjs +70 -0
  22. package/lib/audit.mjs +120 -0
  23. package/lib/auto-context.mjs +322 -0
  24. package/lib/automation.mjs +214 -0
  25. package/lib/chunk.mjs +100 -0
  26. package/lib/config-resolve.mjs +119 -0
  27. package/lib/context.mjs +150 -0
  28. package/lib/conversation-events.mjs +145 -0
  29. package/lib/db.mjs +309 -0
  30. package/lib/diagnose.mjs +197 -0
  31. package/lib/discovery.mjs +402 -0
  32. package/lib/doctor.mjs +82 -0
  33. package/lib/embed.mjs +96 -0
  34. package/lib/embedders.mjs +103 -0
  35. package/lib/errors.mjs +227 -0
  36. package/lib/exec-context.mjs +238 -0
  37. package/lib/extract.mjs +260 -0
  38. package/lib/harness-workspaces.mjs +85 -0
  39. package/lib/hash.mjs +34 -0
  40. package/lib/ingest.mjs +239 -0
  41. package/lib/inputs.mjs +67 -0
  42. package/lib/library-state.mjs +252 -0
  43. package/lib/maintenance.mjs +113 -0
  44. package/lib/metrics.mjs +164 -0
  45. package/lib/migrate.mjs +373 -0
  46. package/lib/operations.mjs +132 -0
  47. package/lib/pa-api.mjs +517 -0
  48. package/lib/paths.mjs +345 -0
  49. package/lib/policy.mjs +125 -0
  50. package/lib/profile.mjs +128 -0
  51. package/lib/readmodel.mjs +159 -0
  52. package/lib/recovery.mjs +557 -0
  53. package/lib/registry-schema.mjs +206 -0
  54. package/lib/registry.mjs +406 -0
  55. package/lib/resolve.mjs +311 -0
  56. package/lib/retention.mjs +143 -0
  57. package/lib/revocation.mjs +124 -0
  58. package/lib/roots-structure.mjs +224 -0
  59. package/lib/schema.mjs +173 -0
  60. package/lib/scope-ops.mjs +379 -0
  61. package/lib/scope-stores.mjs +128 -0
  62. package/lib/search.mjs +345 -0
  63. package/lib/selection.mjs +150 -0
  64. package/lib/server.mjs +335 -0
  65. package/lib/session-identity.mjs +51 -0
  66. package/lib/sessions.mjs +343 -0
  67. package/lib/sync-scheduler.mjs +354 -0
  68. package/lib/sync.mjs +755 -0
  69. package/lib/tags.mjs +45 -0
  70. package/lib/tools.mjs +364 -0
  71. package/lib/trusted-roots.mjs +149 -0
  72. package/lib/worker-context.mjs +22 -0
  73. package/package.json +67 -5
@@ -0,0 +1,379 @@
1
+ /**
2
+ * Operaciones sobre los ámbitos autorizados (PA3).
3
+ *
4
+ * Semántica decidida para no romper el contrato público v0.1:
5
+ *
6
+ * ingest escribe **sólo** en el almacén del proyecto; las bibliotecas son de sólo lectura.
7
+ * search consulta el proyecto y las bibliotecas concedidas, agrega por puntuación y no mezcla
8
+ * resultados no autorizados.
9
+ * context igual que search, con presupuesto global.
10
+ * get busca en los ámbitos efectivos; si el mismo `ref` aparece en más de uno, falla por
11
+ * ambigüedad en vez de elegir uno.
12
+ * list enumera **sólo** el proyecto: las bibliotecas se catalogan fuera de RAG.
13
+ * forget borra **sólo** en el proyecto y rechaza borrar una fuente que vive en una biblioteca.
14
+ * reindex reconstruye **sólo** el proyecto; una biblioteca la reindexa su dueño.
15
+ *
16
+ * Todo lo que abre un almacén lo hace a través del contexto autorizado (`exec-context.mjs`), que ya
17
+ * validó identidad, perfil, selección y grants.
18
+ */
19
+
20
+ import { RagError } from './errors.mjs';
21
+ import { assembleContextAsync } from './context.mjs';
22
+ import { getSource, listSources, search, selectBySource } from './search.mjs';
23
+ import { forgetSource, reindex as reindexStore } from './maintenance.mjs';
24
+ import { clearSyncState } from './sync.mjs';
25
+ import { expandInputs, walkDirectory } from './inputs.mjs';
26
+ import { ingestFiles } from './ingest.mjs';
27
+ import { recordMetrics } from './metrics.mjs';
28
+ import { withTransaction } from './db.mjs';
29
+
30
+ function scopeMeta(scope, state, extra = {}) {
31
+ return { scope_id: scope.id, scope_kind: scope.kind, scope_name: scope.name, state, ...extra };
32
+ }
33
+
34
+ /**
35
+ * Abre un ámbito para lectura con la semántica PA4:
36
+ * - el proyecto sin almacén es un proyecto vacío legítimo (`null`);
37
+ * - una **biblioteca** sin almacén no es una biblioteca vacía: su ausencia no se interpreta como
38
+ * «sin resultados» y mucho menos se crea en silencio;
39
+ * - un almacén temporalmente ocupado se reintenta **una** vez; corrupto o ilegible no se reintenta.
40
+ */
41
+ function openForRead(ctx, scope) {
42
+ const attempt = () => ctx.open(scope, { create: false });
43
+ let db;
44
+ try {
45
+ db = attempt();
46
+ } catch (error) {
47
+ const retryable = error instanceof RagError && error.details?.retryable === true;
48
+ if (!retryable) throw error;
49
+ db = attempt();
50
+ }
51
+ if (db || scope.kind === 'prj') return db;
52
+ throw new RagError('scope-store-unavailable', 'el almacén de la biblioteca no existe', {
53
+ details: {
54
+ reason: 'library-missing', scope_id: scope.id, scope_kind: scope.kind, state: 'missing', retryable: false,
55
+ },
56
+ });
57
+ }
58
+
59
+ /**
60
+ * Busca en todos los ámbitos efectivos y agrega.
61
+ *
62
+ * PA4: cada ámbito autorizado tiene que poder consultarse. Desde que v0.1 no puede expresar
63
+ * «resultado parcial», un ámbito que no se puede leer (ausente, corrupto, revocado) **aborta la
64
+ * búsqueda** en vez de devolver un subconjunto que parecería exhaustivo. El proyecto caído siempre
65
+ * abortaba; ahora también una biblioteca.
66
+ */
67
+ export async function searchScopes(ctx, {
68
+ query, limit, collection, tags, tagMode, strategy, config, embedder, now, scopes: only = null,
69
+ diversity = 'fragment',
70
+ }) {
71
+ const max = Math.min(config.search.maxLimit, Math.max(1, Math.trunc(Number(limit) || config.search.limit)));
72
+ const perScope = Math.min(config.search.maxLimit, Math.max(max, max * 2));
73
+ const collected = [];
74
+ const scopes = [];
75
+ const started = Date.now();
76
+ let mode = 'empty';
77
+
78
+ for (const scope of only ?? ctx.scopes) {
79
+ const db = openForRead(ctx, scope);
80
+ if (!db) {
81
+ scopes.push(scopeMeta(scope, 'uninitialized'));
82
+ continue;
83
+ }
84
+ const result = await search(db, {
85
+ query,
86
+ limit: perScope,
87
+ collection,
88
+ tags,
89
+ tagMode: tagMode ?? 'any',
90
+ strategy,
91
+ config,
92
+ diversity,
93
+ embedder,
94
+ now,
95
+ record: scope.kind === 'prj',
96
+ });
97
+ for (const row of result.results) {
98
+ collected.push({ ...row, scopeId: scope.id, scopeKind: scope.kind });
99
+ }
100
+ mode = result.mode;
101
+ scopes.push(scopeMeta(scope, 'searched', { results: result.results.length, truncated: result.vectors.truncated }));
102
+ }
103
+
104
+ // Punto de control de PA4-B: si la autorización cambió mientras se consultaba, no se devuelve nada.
105
+ ctx.checkpoint('search:return');
106
+ collected.sort((a, b) => (b.score ?? 0) - (a.score ?? 0) || (b.rrf ?? 0) - (a.rrf ?? 0) || a.chunkKey.localeCompare(b.chunkKey));
107
+ // La selección documental se aplica tras el merge y antes del recorte final: el re-orden por `score`
108
+ // desharía el orden que fijó el motor. Es idempotente, así que aplicarla en ambos niveles es seguro.
109
+ const ordered = diversity === 'source'
110
+ ? selectBySource(collected, { limit: max, maxPerSource: config.search.maxPerSource })
111
+ : collected;
112
+ return {
113
+ results: ordered.slice(0, max),
114
+ mode,
115
+ elapsedMs: Math.round((Date.now() - started) * 100) / 100,
116
+ scopes,
117
+ partial: false,
118
+ errors: [],
119
+ };
120
+ }
121
+
122
+ /** Contexto ensamblado sobre los ámbitos efectivos. */
123
+ export async function contextScopes(ctx, {
124
+ query, budgetTokens, maxChunks, collection, tags, config, embedder, now, strategy, scopes: only = null,
125
+ }) {
126
+ const candidates = await searchScopes(ctx, {
127
+ query,
128
+ limit: Math.min(config.search.maxLimit, Math.max((maxChunks ?? config.context.maxChunks) * 3, 12)),
129
+ collection,
130
+ tags,
131
+ config,
132
+ embedder,
133
+ now,
134
+ strategy,
135
+ scopes: only,
136
+ });
137
+ const assembled = await assembleContextAsync({
138
+ results: candidates.results,
139
+ config,
140
+ embedder,
141
+ budgetTokens,
142
+ maxChunks,
143
+ });
144
+ try {
145
+ const project = ctx.project();
146
+ const db = project ? ctx.open(project, { create: false }) : null;
147
+ if (db) {
148
+ withTransaction(db, () => recordMetrics(db, [
149
+ { metric: 'context.builds', value: 1, dim: 'scope', at: now },
150
+ { metric: 'context.tokens', value: assembled.tokens, dim: 'estimated', at: now },
151
+ ...(assembled.truncated ? [{ metric: 'context.truncated', value: 1, dim: 'budget', at: now }] : []),
152
+ ]));
153
+ }
154
+ } catch { /* una métrica no puede tumbar un contexto correcto */ }
155
+ // `context` alimenta citas verificables: presentar un contexto incompleto como completo sería peor que
156
+ // fallar. `searchScopes` ya cierra en falso cualquier ámbito autorizado ilegible; esto queda como red
157
+ // de seguridad si alguna ruta futura vuelve a producir parciales.
158
+ if (candidates.partial) {
159
+ throw new RagError('scope-store-unavailable', 'no se pudo abrir algún ámbito autorizado', {
160
+ details: { errors: candidates.errors },
161
+ });
162
+ }
163
+ // Último punto de control DESPUÉS de leer y ensamblar, justo antes de devolver el texto al modelo.
164
+ ctx.checkpoint('context:return');
165
+ return assembled;
166
+ }
167
+
168
+ function chunksOf(db, sourceId, limit) {
169
+ return db.prepare(`SELECT chunk_key, ordinal, title, heading, text, char_start, char_end
170
+ FROM chunks WHERE source_id = ? ORDER BY ordinal ASC LIMIT ?`).all(sourceId, limit);
171
+ }
172
+
173
+ /**
174
+ * Resuelve una referencia en los ámbitos efectivos. Un `ref` que existe en más de un ámbito es
175
+ * ambiguo: no se elige por orden de iteración.
176
+ */
177
+ export function getAcross(ctx, { ref, limit = 50 } = {}) {
178
+ const matches = [];
179
+ for (const scope of ctx.scopes) {
180
+ const db = openForRead(ctx, scope);
181
+ if (!db) continue;
182
+ try {
183
+ const source = getSource(db, String(ref));
184
+ matches.push({ scope, db, source });
185
+ } catch (error) {
186
+ if (!(error instanceof RagError) || error.code !== 'source-not-found') throw error;
187
+ }
188
+ }
189
+ // Antes de decidir «no existe» o «es ambiguo» se confirma que la autorización sigue en pie. Se
190
+ // comprueba al final, con los datos ya leídos: validar antes de leer y entregar después dejaba una
191
+ // ventana en la que la lectura ocurría con una autorización que ya no existía.
192
+ if (matches.length === 0) {
193
+ ctx.checkpoint('get:not-found');
194
+ throw new RagError('source-not-found', 'no existe una fuente con esa referencia en los ámbitos autorizados', {
195
+ details: { ref: String(ref), scopes: ctx.scopes.map((scope) => scope.id) },
196
+ });
197
+ }
198
+ if (matches.length > 1) {
199
+ ctx.checkpoint('get:ambiguous');
200
+ throw new RagError('invalid-argument', 'la referencia existe en más de un ámbito y no es inequívoca', {
201
+ details: {
202
+ reason: 'ambiguous-ref',
203
+ ref: String(ref),
204
+ scopes: matches.map((match) => match.scope.id),
205
+ },
206
+ });
207
+ }
208
+ const [{ scope, db, source }] = matches;
209
+ const capped = Math.min(Number.isInteger(limit) && limit > 0 ? limit : 50, 200);
210
+ const payload = {
211
+ scopeId: scope.id,
212
+ scopeKind: scope.kind,
213
+ source: {
214
+ id: source.id, collection: source.collection, uri: source.uri, title: source.title, mime: source.mime,
215
+ sha256: source.sha256, bytes: source.bytes, indexedAt: source.indexed_at,
216
+ },
217
+ chunks: chunksOf(db, source.id, capped).map((chunk) => ({
218
+ chunkKey: chunk.chunk_key, ordinal: chunk.ordinal, heading: chunk.heading,
219
+ charStart: chunk.char_start, charEnd: chunk.char_end, text: chunk.text,
220
+ })),
221
+ };
222
+ ctx.checkpoint('get:return');
223
+ return payload;
224
+ }
225
+
226
+ /** Lista sólo el proyecto. */
227
+ export function listProject(ctx, { collection, tag, limit = 50, offset = 0 } = {}) {
228
+ const scope = ctx.project();
229
+ if (!scope) throw new RagError('internal', 'el contexto no contiene un proyecto');
230
+ const db = openForRead(ctx, scope);
231
+ if (!db) {
232
+ ctx.checkpoint('list:return');
233
+ return { total: 0, rows: [] };
234
+ }
235
+ const listed = listSources(db, {
236
+ collection,
237
+ tag,
238
+ limit: Math.min(Number.isInteger(limit) && limit > 0 ? limit : 50, 200),
239
+ offset: Number.isInteger(offset) && offset >= 0 ? offset : 0,
240
+ });
241
+ ctx.checkpoint('list:return');
242
+ return listed;
243
+ }
244
+
245
+ /** ¿Existe la fuente en alguna biblioteca concedida? Se usa para rechazar borrados cruzados. */
246
+ function findInLibraries(ctx, ref) {
247
+ for (const scope of ctx.libraries()) {
248
+ const db = openForRead(ctx, scope);
249
+ if (!db) continue;
250
+ try {
251
+ return { scope, source: getSource(db, String(ref)) };
252
+ } catch (error) {
253
+ if (!(error instanceof RagError) || error.code !== 'source-not-found') throw error;
254
+ }
255
+ }
256
+ return null;
257
+ }
258
+
259
+ /** Borra una fuente del proyecto. Nunca toca una biblioteca. */
260
+ export function forgetInProject(ctx, { ref, exec, now }) {
261
+ const scope = ctx.project();
262
+ if (!scope) throw new RagError('internal', 'el contexto no contiene un proyecto');
263
+ const db = openForRead(ctx, scope);
264
+ if (!db) {
265
+ throw new RagError('source-not-found', 'el proyecto no tiene almacén todavía', {
266
+ details: { ref: String(ref), scope_id: scope.id },
267
+ });
268
+ }
269
+ let source;
270
+ try {
271
+ source = getSource(db, String(ref));
272
+ } catch (error) {
273
+ if (!(error instanceof RagError) || error.code !== 'source-not-found') throw error;
274
+ const library = findInLibraries(ctx, ref);
275
+ if (library) {
276
+ throw new RagError('invalid-argument', 'la fuente pertenece a una biblioteca y no se puede borrar desde el proyecto', {
277
+ details: { reason: 'library-read-only', ref: String(ref), scope_id: library.scope.id },
278
+ });
279
+ }
280
+ throw error;
281
+ }
282
+ // El borrado es destructivo: se confirma la autorización justo antes de devolver el «preview».
283
+ ctx.checkpoint('forget:preview');
284
+ return {
285
+ scope,
286
+ preview: source,
287
+ run() {
288
+ // Segunda comprobación inmediatamente antes del efecto destructivo. Si el grant se revocó entre
289
+ // la vista previa y la confirmación, no se borra nada. Si se revoca **después** del COMMIT, lo
290
+ // borrado no se deshace: la atomicidad de `forget` termina en su COMMIT y así se documenta.
291
+ ctx.assertAuthorized(scope, 'forget:write');
292
+ const forgotten = forgetSource(db, {
293
+ ref: source.id,
294
+ now,
295
+ actor: 'model',
296
+ sessionId: exec.agent?.id ?? null,
297
+ callId: exec.callId,
298
+ });
299
+ // El estado de sincronización no puede seguir afirmando que ese fichero está presente.
300
+ clearSyncState({
301
+ registryDb: ctx.registry,
302
+ scopeKind: scope.kind,
303
+ scopeId: scope.id,
304
+ roots: scope.roots ?? [],
305
+ uri: source.uri,
306
+ });
307
+ return forgotten;
308
+ },
309
+ };
310
+ }
311
+
312
+ /** Reindexa sólo el proyecto. */
313
+ export function reindexProject(ctx, { operation, config, now, exec }) {
314
+ const scope = ctx.project();
315
+ if (!scope) throw new RagError('internal', 'el contexto no contiene un proyecto');
316
+ const db = openForRead(ctx, scope);
317
+ if (!db) {
318
+ throw new RagError('scope-store-unavailable', 'el proyecto no tiene almacén todavía', {
319
+ details: { scope_id: scope.id },
320
+ });
321
+ }
322
+ ctx.checkpoint('reindex:preview');
323
+ return {
324
+ scope,
325
+ run() {
326
+ ctx.assertAuthorized(scope, 'reindex:write');
327
+ return reindexStore(db, {
328
+ operation,
329
+ config,
330
+ now,
331
+ actor: 'model',
332
+ sessionId: exec.agent?.id ?? null,
333
+ callId: exec.callId,
334
+ signal: exec.signal,
335
+ });
336
+ },
337
+ };
338
+ }
339
+
340
+ /** Ingesta en el proyecto: expande y clasifica antes de abrir el almacén. */
341
+ export function planIngest(ctx, { requested, cwd, config }) {
342
+ const scope = ctx.project();
343
+ if (!scope) throw new RagError('internal', 'el contexto no contiene un proyecto');
344
+ const roots = scope.roots.map((root) => root.path);
345
+ const classified = expandInputs(requested, {
346
+ cwd,
347
+ roots,
348
+ ragRootPath: ctx.profileRoot,
349
+ limit: config.maxFilesPerIngest,
350
+ });
351
+ return { scope, classified };
352
+ }
353
+
354
+ export async function runIngest(ctx, {
355
+ scope, files, collection, tags, force, now, config, embedder, actor = 'model',
356
+ }) {
357
+ // La escritura sólo va al proyecto y sólo si sigue autorizado justo antes de abrir.
358
+ ctx.assertAuthorized(scope, 'ingest:open');
359
+ const db = ctx.open(scope, { create: true });
360
+ const result = await ingestFiles({
361
+ db,
362
+ root: scope.dir,
363
+ files,
364
+ collection,
365
+ tags,
366
+ force,
367
+ now,
368
+ config,
369
+ embedder,
370
+ actor,
371
+ authorize: () => ctx.assertAuthorized(scope, 'ingest:file'),
372
+ });
373
+ // Cada fichero se confirma en su propio COMMIT: una revocación posterior impide seguir escribiendo y
374
+ // devolver datos del ámbito, pero no deshace lo ya confirmado. Se revalida para dejar constancia.
375
+ ctx.revalidate({ checkpoint: 'ingest:return', strict: false });
376
+ return result;
377
+ }
378
+
379
+ export { walkDirectory };
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Almacenes de ámbito (PA3, endurecido en PA4).
3
+ *
4
+ * Cada ámbito (proyecto o biblioteca) tiene su propio `rag.sqlite3` bajo
5
+ * `<raíz de perfil>/scopes/<scope_id>/`. No hay un almacén común: abrir un ámbito es la única forma
6
+ * de leerlo, y el `scope_id` grabado en `meta` impide que dos ámbitos se confundan aunque alguien
7
+ * mueva directorios.
8
+ *
9
+ * PA4 añade tres cosas:
10
+ * - la identidad se verifica completa (`scope_id`, `scope_kind`, perfil y `store_state`), no sólo el
11
+ * `scope_id`;
12
+ * - un almacén marcado `corrupt` o en migración no se abre: se distingue corrupción de
13
+ * indisponibilidad;
14
+ * - los almacenes nuevos declaran `profile_id` y `store_state='ready'`, y los heredados de PA3
15
+ * (que sólo tienen `profile_key`) siguen abriéndose.
16
+ *
17
+ * La apertura no decide autorización: eso ocurre antes, en `exec-context.mjs`.
18
+ */
19
+
20
+ import { existsSync } from 'node:fs';
21
+ import { join } from 'node:path';
22
+
23
+ import { closeDatabase, openDatabase, writeMeta } from './db.mjs';
24
+ import { RagError } from './errors.mjs';
25
+ import { scopeRoot } from './profile.mjs';
26
+ import { STORE_FILE, libraryStateError, verifyStoreIdentity } from './library-state.mjs';
27
+
28
+ /** Directorio del almacén de un ámbito. */
29
+ export function scopeStoreDir(profileRootPath, scopeId) {
30
+ return scopeRoot(profileRootPath, scopeId);
31
+ }
32
+
33
+ /** Ruta del fichero del almacén de un ámbito. */
34
+ export function scopeStoreFile(profileRootPath, scopeId) {
35
+ return join(scopeStoreDir(profileRootPath, scopeId), STORE_FILE);
36
+ }
37
+
38
+ /** ¿Existe ya el fichero del ámbito? No lo abre. */
39
+ export function scopeStoreExists(profileRootPath, scopeId) {
40
+ return existsSync(scopeStoreFile(profileRootPath, scopeId));
41
+ }
42
+
43
+ function declareIdentity(db, { scope, key }) {
44
+ writeMeta(db, 'scope_id', scope.id);
45
+ writeMeta(db, 'scope_kind', scope.kind);
46
+ writeMeta(db, 'profile_id', key);
47
+ writeMeta(db, 'profile_key', key);
48
+ writeMeta(db, 'store_state', 'ready');
49
+ }
50
+
51
+ /**
52
+ * Abre el almacén de un ámbito.
53
+ *
54
+ * @returns {import('node:sqlite').DatabaseSync|null} `null` si no existe y `create` es falso.
55
+ * @throws {RagError} `scope-store-corrupt` si el fichero no es el de este ámbito o no es utilizable;
56
+ * `scope-store-unavailable` si está en migración; `scope-forbidden` si pertenece a otro perfil.
57
+ */
58
+ export function openScopeStore({
59
+ profileRoot: profileRootPath, profileKey: key, scope, create = false, now = Date.now(),
60
+ } = {}) {
61
+ const root = scopeStoreDir(profileRootPath, scope.id);
62
+ const file = scopeStoreFile(profileRootPath, scope.id);
63
+ if (!create && !existsSync(file)) return null;
64
+
65
+ let opened;
66
+ try {
67
+ opened = openDatabase({ root, create, now });
68
+ } catch (error) {
69
+ if (error instanceof RagError && error.code === 'store-not-initialized') return null;
70
+ if (error instanceof RagError && error.code === 'store-busy') {
71
+ // Contención no es corrupción: el llamador puede reintentar y la sesión conserva su autorización.
72
+ throw new RagError('scope-store-unavailable', `el almacén del ámbito ${scope.id} está bloqueado`, {
73
+ cause: error,
74
+ details: {
75
+ scopeId: scope.id,
76
+ scope_id: scope.id,
77
+ scope_kind: scope.kind,
78
+ reason: 'busy',
79
+ retryable: true,
80
+ path: root,
81
+ },
82
+ });
83
+ }
84
+ if (error instanceof RagError && ['store-not-rag', 'store-corrupt', 'store-version-unsupported', 'fts-integrity'].includes(error.code)) {
85
+ throw new RagError('scope-store-corrupt', `el almacén del ámbito ${scope.id} no es utilizable`, {
86
+ cause: error,
87
+ details: { scopeId: scope.id, scope_id: scope.id, scope_kind: scope.kind, underlying: error.code, path: root },
88
+ });
89
+ }
90
+ throw error;
91
+ }
92
+
93
+ const db = opened.db;
94
+ try {
95
+ if (create && opened.created) declareIdentity(db, { scope, key });
96
+ const identity = verifyStoreIdentity(db, { scope, profileKey: key });
97
+ if (!identity.ok) {
98
+ if (identity.reason === 'foreign-profile') {
99
+ throw new RagError('scope-forbidden', 'el almacén pertenece a otro perfil', {
100
+ details: { scope_id: scope.id, ...identity.details },
101
+ });
102
+ }
103
+ if (identity.reason === 'migrating') {
104
+ throw libraryStateError(
105
+ { state: 'unavailable', reason: 'migrating', retryable: true, scopeId: scope.id, scopeKind: scope.kind },
106
+ { scopeId: scope.id, scopeKind: scope.kind },
107
+ );
108
+ }
109
+ // Adoptar la identidad de un fichero que ya existía sería confiar en un almacén ajeno: sólo se
110
+ // declara cuando lo acabamos de crear nosotros en esta misma llamada.
111
+ if (identity.reason === 'missing-scope-id' && opened.created) {
112
+ declareIdentity(db, { scope, key });
113
+ } else if (identity.reason === 'missing-scope-id' && create) {
114
+ throw new RagError('scope-store-corrupt', `el almacén del ámbito ${scope.id} existe sin identidad declarada`, {
115
+ details: { scopeId: scope.id, scope_id: scope.id, scope_kind: scope.kind, reason: identity.reason, path: root },
116
+ });
117
+ } else {
118
+ throw new RagError('scope-store-corrupt', `el almacén del ámbito ${scope.id} no declara su identidad completa`, {
119
+ details: { scopeId: scope.id, scope_id: scope.id, scope_kind: scope.kind, reason: identity.reason, ...identity.details, path: root },
120
+ });
121
+ }
122
+ }
123
+ return db;
124
+ } catch (error) {
125
+ closeDatabase(db);
126
+ throw error;
127
+ }
128
+ }