@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,373 @@
1
+ /**
2
+ * Migración de un almacén v0.2 (un único `rag.sqlite3`) a un almacén de ámbito Project-Aware (PA1).
3
+ *
4
+ * Garantías que implementa `PROJECT-AWARE-ARCHITECTURE.md` §12:
5
+ * - El origen se abre **en solo lectura** y nunca se mueve ni se modifica.
6
+ * - Se copia a un ámbito nuevo, se verifica la igualdad y sólo entonces se registra el proyecto.
7
+ * - Cualquier fallo deja el origen intacto y no deja ámbito registrado (rollback explícito).
8
+ * - La copia conserva `chunk_key`, hashes, auditoría encadenada y metadatos de índice.
9
+ *
10
+ * Lo que **no** hace: no crea bibliotecas ni concesiones, no migra sesiones, no instala el plugin y
11
+ * no toca el perfil operativo. El proyecto y la raíz se pasan explícitamente porque la decisión es
12
+ * humana; esta función no los inventa.
13
+ */
14
+
15
+ import { createHash } from 'node:crypto';
16
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, statSync } from 'node:fs';
17
+ import { isAbsolute, join, resolve, dirname } from 'node:path';
18
+ import { DatabaseSync } from 'node:sqlite';
19
+
20
+ import { RagError } from './errors.mjs';
21
+ import { verifyAuditChain } from './audit.mjs';
22
+ import { closeDatabase, ftsIntegrityCheck, openDatabase, withTransaction } from './db.mjs';
23
+ import { openRegistry, addRoot, appendRegistryAudit, createProject, newId, pathKeyFor } from './registry.mjs';
24
+ import { profileRoot as defaultProfileRoot, scopeRoot as scopeRootFor, legacyRagRoot } from './profile.mjs';
25
+ import { APPLICATION_ID, SCHEMA_VERSION } from './schema.mjs';
26
+
27
+ const LEGACY_TABLES = ['meta', 'sources', 'chunks', 'vectors', 'source_tags', 'audit'];
28
+
29
+ function sha256File(path) {
30
+ return createHash('sha256').update(readFileSync(path)).digest('hex');
31
+ }
32
+
33
+ function count(db, table) {
34
+ return Number(db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get().n);
35
+ }
36
+
37
+ function openLegacyReadOnly(dbPath) {
38
+ if (!existsSync(dbPath)) {
39
+ throw new RagError('store-not-initialized', 'no hay almacén v0.2 que migrar', { details: { path: dbPath } });
40
+ }
41
+ const db = new DatabaseSync(dbPath, { readOnly: true });
42
+ try {
43
+ const appId = Number(db.prepare('PRAGMA application_id').get().application_id);
44
+ if (appId !== APPLICATION_ID) {
45
+ throw new RagError('store-not-rag', 'el almacén de origen no es de LifeCode RAG', { details: { path: dbPath } });
46
+ }
47
+ const version = Number(db.prepare('PRAGMA user_version').get().user_version);
48
+ if (version !== SCHEMA_VERSION) {
49
+ throw new RagError('store-version-unsupported', 'sólo se migra el esquema v0.2 (versión 3)', {
50
+ details: { found: version, expected: SCHEMA_VERSION },
51
+ });
52
+ }
53
+ const tables = new Set(db.prepare(`SELECT name FROM sqlite_master WHERE type='table'`).all().map((row) => row.name));
54
+ const missing = LEGACY_TABLES.filter((name) => !tables.has(name));
55
+ if (missing.length > 0) throw new RagError('store-corrupt', 'al almacén de origen le faltan tablas', { details: { missing } });
56
+ const check = db.prepare('PRAGMA integrity_check').all();
57
+ if (check.length !== 1 || check[0].integrity_check !== 'ok') {
58
+ throw new RagError('store-corrupt', 'integrity_check del origen falló', { details: { check } });
59
+ }
60
+ return db;
61
+ } catch (error) {
62
+ db.close();
63
+ throw error;
64
+ }
65
+ }
66
+
67
+ /** Inspección de solo lectura, sin escribir nada. */
68
+ export function inspectLegacyStore({ legacyRoot }) {
69
+ const dbPath = join(legacyRoot, 'rag.sqlite3');
70
+ const db = openLegacyReadOnly(dbPath);
71
+ try {
72
+ const chain = verifyAuditChain(db);
73
+ return {
74
+ path: dbPath,
75
+ schemaVersion: Number(db.prepare('PRAGMA user_version').get().user_version),
76
+ bytes: statSync(dbPath).size,
77
+ sha256: sha256File(dbPath),
78
+ counts: {
79
+ sources: count(db, 'sources'),
80
+ chunks: count(db, 'chunks'),
81
+ vectors: count(db, 'vectors'),
82
+ tags: count(db, 'source_tags'),
83
+ audit: count(db, 'audit'),
84
+ },
85
+ audit: chain,
86
+ };
87
+ } finally {
88
+ db.close();
89
+ }
90
+ }
91
+
92
+ function backupStore(dbPath, backupDir) {
93
+ mkdirSync(backupDir, { recursive: true });
94
+ const target = join(backupDir, 'rag.sqlite3');
95
+ copyFileSync(dbPath, target);
96
+ const before = sha256File(dbPath);
97
+ const after = sha256File(target);
98
+ if (before !== after) {
99
+ throw new RagError('internal', 'la copia de seguridad no coincide con el origen', { details: { before, after } });
100
+ }
101
+ return { path: target, sha256: after, bytes: statSync(target).size };
102
+ }
103
+
104
+ function controlQuery(db) {
105
+ const row = db.prepare('SELECT text FROM chunks ORDER BY id LIMIT 1').get();
106
+ if (!row) return { query: null, count: 0 };
107
+ const token = (row.text.match(/[\p{L}\p{N}]{4,}/u) ?? [null])[0];
108
+ if (!token) return { query: null, count: 0 };
109
+ const query = `"${token.replaceAll('"', '""')}"`;
110
+ const result = db.prepare('SELECT COUNT(*) AS n FROM chunks_fts WHERE chunks_fts MATCH ?').get(query);
111
+ return { query, count: Number(result.n) };
112
+ }
113
+
114
+ function copyStore(legacy, destination, { now }) {
115
+ const source = legacy.prepare('SELECT * FROM sources ORDER BY id').all();
116
+ const chunks = legacy.prepare('SELECT * FROM chunks ORDER BY id').all();
117
+ const vectors = legacy.prepare('SELECT * FROM vectors ORDER BY chunk_key, model').all();
118
+ const tags = legacy.prepare('SELECT * FROM source_tags ORDER BY source_id, tag').all();
119
+ const audit = legacy.prepare('SELECT * FROM audit ORDER BY seq').all();
120
+ const meta = legacy.prepare('SELECT key, value FROM meta').all();
121
+
122
+ const insertSource = destination.prepare(`INSERT INTO sources
123
+ (id, collection, uri, title, mime, sha256, bytes, char_count, metadata, created_at, updated_at, indexed_at)
124
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
125
+ for (const row of source) {
126
+ insertSource.run(row.id, row.collection, row.uri, row.title, row.mime, row.sha256, row.bytes,
127
+ row.char_count, row.metadata, row.created_at, row.updated_at, row.indexed_at);
128
+ }
129
+
130
+ const insertChunk = destination.prepare(`INSERT INTO chunks
131
+ (id, chunk_key, source_id, ordinal, title, heading, text, char_start, char_end, token_est)
132
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
133
+ for (const row of chunks) {
134
+ insertChunk.run(row.id, row.chunk_key, row.source_id, row.ordinal, row.title, row.heading,
135
+ row.text, row.char_start, row.char_end, row.token_est);
136
+ }
137
+
138
+ const insertVector = destination.prepare('INSERT INTO vectors (chunk_key, model, dim, vec) VALUES (?, ?, ?, ?)');
139
+ for (const row of vectors) insertVector.run(row.chunk_key, row.model, row.dim, row.vec);
140
+
141
+ const insertTag = destination.prepare('INSERT INTO source_tags (source_id, tag) VALUES (?, ?)');
142
+ for (const row of tags) insertTag.run(row.source_id, row.tag);
143
+
144
+ const insertAudit = destination.prepare(`INSERT INTO audit
145
+ (seq, at, actor, session_id, call_id, tool, action, target, outcome, details, prev_hash, hash)
146
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
147
+ for (const row of audit) {
148
+ insertAudit.run(row.seq, row.at, row.actor, row.session_id, row.call_id, row.tool, row.action,
149
+ row.target, row.outcome, row.details, row.prev_hash, row.hash);
150
+ }
151
+
152
+ const setMeta = destination.prepare('UPDATE meta SET value = ? WHERE key = ?');
153
+ const keep = new Set(['index_revision', 'embedding_model', 'audit_exported_seq', 'audit_head_seq', 'audit_head_hash', 'created_at']);
154
+ const copiedMeta = [];
155
+ for (const row of meta) {
156
+ if (!keep.has(row.key)) continue;
157
+ setMeta.run(row.value, row.key);
158
+ copiedMeta.push(row.key);
159
+ }
160
+ setMeta.run(String(now), 'migrated_at');
161
+ return { counts: { sources: source.length, chunks: chunks.length, vectors: vectors.length, tags: tags.length, audit: audit.length }, meta: copiedMeta };
162
+ }
163
+
164
+ function chunkTextMap(db) {
165
+ const map = new Map();
166
+ for (const row of db.prepare('SELECT chunk_key, text FROM chunks ORDER BY chunk_key').all()) map.set(row.chunk_key, row.text);
167
+ return map;
168
+ }
169
+
170
+ function sourceHashMap(db) {
171
+ const map = new Map();
172
+ for (const row of db.prepare('SELECT id, sha256 FROM sources ORDER BY id').all()) map.set(row.id, row.sha256);
173
+ return map;
174
+ }
175
+
176
+ function assertEqual(label, left, right) {
177
+ const a = JSON.stringify(left);
178
+ const b = JSON.stringify(right);
179
+ if (a !== b) throw new RagError('store-corrupt', `la verificación de migración falló: ${label}`, {
180
+ details: { phase: label },
181
+ });
182
+ }
183
+
184
+ /** Verificación de igualdad entre origen y destino; devuelve el informe reproducible. */
185
+ export function verifyMigration(legacy, destination) {
186
+ const legacyCounts = {
187
+ sources: count(legacy, 'sources'), chunks: count(legacy, 'chunks'), vectors: count(legacy, 'vectors'),
188
+ tags: count(legacy, 'source_tags'), audit: count(legacy, 'audit'),
189
+ };
190
+ const destinationCounts = {
191
+ sources: count(destination, 'sources'), chunks: count(destination, 'chunks'), vectors: count(destination, 'vectors'),
192
+ tags: count(destination, 'source_tags'), audit: count(destination, 'audit'),
193
+ };
194
+ assertEqual('counts', legacyCounts, destinationCounts);
195
+
196
+ assertEqual('source-hashes', [...sourceHashMap(legacy)], [...sourceHashMap(destination)]);
197
+ assertEqual('chunk-text', [...chunkTextMap(legacy)], [...chunkTextMap(destination)]);
198
+
199
+ const legacyAudit = verifyAuditChain(legacy);
200
+ const destinationAudit = verifyAuditChain(destination);
201
+ assertEqual('audit-origin', legacyAudit.ok, true);
202
+ assertEqual('audit-destination', destinationAudit.ok, true);
203
+ assertEqual('audit-count', legacyAudit.count, destinationAudit.count);
204
+
205
+ const check = destination.prepare('PRAGMA integrity_check').all();
206
+ assertEqual('integrity', check.length === 1 ? check[0].integrity_check : 'invalid', 'ok');
207
+ ftsIntegrityCheck(destination);
208
+ const controlLegacy = controlQuery(legacy);
209
+ const controlDestination = controlQuery(destination);
210
+ assertEqual('fts-control', controlLegacy.count, controlDestination.count);
211
+
212
+ const appId = Number(destination.prepare('PRAGMA application_id').get().application_id);
213
+ const version = Number(destination.prepare('PRAGMA user_version').get().user_version);
214
+ assertEqual('application-id', appId, APPLICATION_ID);
215
+ assertEqual('schema-version', version, SCHEMA_VERSION);
216
+
217
+ return {
218
+ counts: destinationCounts,
219
+ audit: destinationAudit,
220
+ fts: { ...controlDestination, matches: controlLegacy.count },
221
+ integrity: 'ok',
222
+ applicationId: appId,
223
+ schemaVersion: version,
224
+ };
225
+ }
226
+
227
+ /**
228
+ * Migra el almacén v0.2 del perfil a un ámbito de proyecto nuevo.
229
+ *
230
+ * @param {object} options
231
+ * @param {boolean} options.confirm confirmación humana explícita; sin ella no se escribe nada
232
+ * @param {string} options.projectName nombre del proyecto destino
233
+ * @param {string} options.rootPath raíz autorizada del proyecto (absoluta, existente)
234
+ * @param {string} [options.legacyRoot] raíz del almacén v0.2 (por defecto `$DSH_HOME/lifecode-rag`)
235
+ * @param {string} [options.profileRoot] raíz del perfil Project-Aware
236
+ */
237
+ export function migrateLegacyStore({
238
+ legacyRoot,
239
+ profileRoot,
240
+ projectName,
241
+ rootPath,
242
+ confirm = false,
243
+ now = Date.now(),
244
+ backupDir,
245
+ } = {}) {
246
+ if (confirm !== true) {
247
+ throw new RagError('approval-required', 'la migración exige confirmación humana explícita');
248
+ }
249
+ const sourceRoot = resolve(legacyRoot ?? legacyRagRoot());
250
+ if (profileRoot === undefined) profileRoot = defaultProfileRoot();
251
+ if (typeof projectName !== 'string' || projectName.trim() === '') {
252
+ throw new RagError('invalid-argument', 'falta el nombre del proyecto destino');
253
+ }
254
+ if (typeof rootPath !== 'string' || !isAbsolute(rootPath)) {
255
+ throw new RagError('invalid-argument', 'la raíz del proyecto debe ser una ruta absoluta');
256
+ }
257
+ if (!existsSync(rootPath) || !statSync(rootPath).isDirectory()) {
258
+ throw new RagError('source-unreadable', 'la raíz del proyecto no existe', { details: { path: rootPath } });
259
+ }
260
+
261
+ const legacy = { root: sourceRoot };
262
+ const legacyDbPath = join(legacy.root, 'rag.sqlite3');
263
+ const beforeSha = sha256File(legacyDbPath);
264
+ const source = openLegacyReadOnly(legacyDbPath);
265
+ let destinationDb = null;
266
+ let registryDb = null;
267
+ let scopeDir = null;
268
+ let project = null;
269
+ let rootRecord = null;
270
+ let operationId = null;
271
+ try {
272
+ const inspection = inspectLegacyStore({ legacyRoot: legacy.root });
273
+ assertEqual('legacy-audit', inspection.audit.ok, true);
274
+
275
+ const stamp = new Date(now).toISOString().replace(/[:.]/g, '-');
276
+ const backup = backupStore(legacyDbPath, backupDir ?? join(profileRoot, 'backups', `migration-${stamp}`));
277
+
278
+ const registry = openRegistry({ root: profileRoot, create: true, now });
279
+ registryDb = registry.db;
280
+ registryDb.exec('BEGIN IMMEDIATE');
281
+ project = createProject(registryDb, { name: projectName, now });
282
+ rootRecord = addRoot(registryDb, { scopeKind: 'prj', scopeId: project.id, path: rootPath, addedBy: 'human', now });
283
+ registryDb.exec('COMMIT');
284
+
285
+ scopeDir = scopeRootFor(profileRoot, project.id);
286
+ const opened = openDatabase({ root: scopeDir, create: true, now });
287
+ destinationDb = opened.db;
288
+
289
+ operationId = newId('op_', now);
290
+ const copy = withTransaction(destinationDb, () => ({
291
+ ...copyStore(source, destinationDb, { now }),
292
+ }));
293
+
294
+ const verification = verifyMigration(source, destinationDb);
295
+
296
+ withTransaction(registryDb, () => {
297
+ registryDb.prepare(`INSERT INTO operations (id, kind, state, started_at, finished_at, detail)
298
+ VALUES (?, 'migrate', 'committed', ?, ?, ?)`)
299
+ .run(operationId, now, now, JSON.stringify({ projectId: project.id, rootId: rootRecord.id, source: legacyDbPath }));
300
+ const step = registryDb.prepare(`INSERT INTO operation_steps (operation_id, step, state, effect_key, updated_at)
301
+ VALUES (?, ?, 'done', ?, ?)`);
302
+ for (const name of ['inspect', 'backup', 'copy', 'verify', 'commit']) {
303
+ step.run(operationId, name, `${operationId}:${name}`, now);
304
+ }
305
+ appendRegistryAudit(registryDb, {
306
+ at: now, actor: 'human', action: 'migrate', target: project.id, outcome: 'ok',
307
+ detail: JSON.stringify({ operationId, counts: verification.counts, backup: backup.path }),
308
+ });
309
+ });
310
+
311
+ if (sha256File(legacyDbPath) !== beforeSha) {
312
+ throw new RagError('internal', 'el almacén de origen cambió durante la migración');
313
+ }
314
+
315
+ return {
316
+ project: { id: project.id, name: project.name },
317
+ root: rootRecord,
318
+ scope: { id: project.id, path: scopeDir, database: join(scopeDir, 'rag.sqlite3') },
319
+ operationId,
320
+ backup,
321
+ counts: verification.counts,
322
+ verification,
323
+ legacy: { path: legacyDbPath, sha256: beforeSha, untouched: true },
324
+ meta: copy.meta,
325
+ };
326
+ } catch (error) {
327
+ // Rollback: nada del ámbito nuevo ni del registro debe sobrevivir a un fallo.
328
+ try {
329
+ if (destinationDb) closeDatabase(destinationDb);
330
+ } catch {
331
+ // ya cerrado
332
+ }
333
+ destinationDb = null;
334
+ if (scopeDir) {
335
+ try {
336
+ rmSync(scopeDir, { recursive: true, force: true });
337
+ // El directorio `scopes/` del perfil se creó para este intento: si quedó vacío, no se deja.
338
+ rmSync(dirname(scopeDir), { recursive: false });
339
+ } catch {
340
+ // el rollback no debe ocultar el error original
341
+ }
342
+ }
343
+ if (registryDb && project) {
344
+ try {
345
+ registryDb.exec('BEGIN IMMEDIATE');
346
+ if (rootRecord) registryDb.prepare('DELETE FROM roots WHERE id = ?').run(rootRecord.id);
347
+ registryDb.prepare('DELETE FROM projects WHERE id = ?').run(project.id);
348
+ registryDb.exec('COMMIT');
349
+ } catch {
350
+ try {
351
+ registryDb.exec('ROLLBACK');
352
+ } catch {
353
+ // sin transacción abierta
354
+ }
355
+ }
356
+ }
357
+ throw error;
358
+ } finally {
359
+ try {
360
+ source.close();
361
+ } catch {
362
+ // ya cerrado
363
+ }
364
+ if (destinationDb) closeDatabase(destinationDb);
365
+ if (registryDb) {
366
+ try {
367
+ registryDb.close();
368
+ } catch {
369
+ // ya cerrado
370
+ }
371
+ }
372
+ }
373
+ }
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Operaciones coordinadas (PA0 §9) usadas por los flujos de PA4.
3
+ *
4
+ * Una operación que se interrumpe deja una fila `started`. Eso **no** significa que no se escribiera
5
+ * nada: significa que el resultado es desconocido. La regla del contrato es que un efecto destructivo
6
+ * cuyo resultado es incierto no se repite: o se reconcilia con evidencia, o se marca `failed` y se
7
+ * deja la decisión a una persona.
8
+ *
9
+ * Este módulo no borra nada y no repite efectos: sólo registra, consulta y cierra operaciones.
10
+ */
11
+
12
+ import { RagError } from './errors.mjs';
13
+ import { newId } from './registry.mjs';
14
+
15
+ export const OPERATION_STATES = Object.freeze(['started', 'committed', 'failed', 'reconciled']);
16
+ export const STEP_STATES = Object.freeze(['pending', 'done', 'failed']);
17
+
18
+ /** Abre una operación en estado `started`. */
19
+ export function beginOperation(db, { kind, target, detail = null, now = Date.now(), id } = {}) {
20
+ if (typeof kind !== 'string' || kind.trim() === '') {
21
+ throw new RagError('invalid-argument', 'la operación necesita un tipo');
22
+ }
23
+ const operationId = id ?? newId('op_', now);
24
+ db.prepare(`INSERT INTO operations (id, kind, state, started_at, finished_at, detail)
25
+ VALUES (?, ?, 'started', ?, NULL, ?)`)
26
+ .run(operationId, kind, now, detail === null ? null : JSON.stringify(detail));
27
+ return { id: operationId, kind, target, state: 'started' };
28
+ }
29
+
30
+ /**
31
+ * Registra un paso. Repetir el mismo paso actualiza su estado (progreso normal); `effectKey` es la
32
+ * clave de idempotencia del efecto: un paso **distinto** no puede reutilizarla dentro de la misma
33
+ * operación, y el índice único parcial lo rechaza en vez de duplicar el trabajo.
34
+ */
35
+ export function recordStep(db, { operationId, step, state = 'done', effectKey = null, now = Date.now() } = {}) {
36
+ if (!STEP_STATES.includes(state)) {
37
+ throw new RagError('invalid-argument', 'estado de paso inválido', { details: { state } });
38
+ }
39
+ try {
40
+ db.prepare(`INSERT INTO operation_steps (operation_id, step, state, effect_key, updated_at)
41
+ VALUES (?, ?, ?, ?, ?)
42
+ ON CONFLICT(operation_id, step) DO UPDATE SET
43
+ state = excluded.state,
44
+ effect_key = excluded.effect_key,
45
+ updated_at = excluded.updated_at`)
46
+ .run(operationId, step, state, effectKey, now);
47
+ } catch (error) {
48
+ if (/UNIQUE|unique/.test(String(error?.message ?? ''))) {
49
+ return { ok: false, duplicate: true, operationId, step, effectKey };
50
+ }
51
+ throw error;
52
+ }
53
+ return { ok: true, operationId, step, state, effectKey };
54
+ }
55
+
56
+ /** Cierra la operación. `committed` exige que todos los pasos estén `done`. */
57
+ export function finishOperation(db, { operationId, state, now = Date.now(), detail = undefined } = {}) {
58
+ if (!['committed', 'failed', 'reconciled'].includes(state)) {
59
+ throw new RagError('invalid-argument', 'estado final de operación inválido', { details: { state } });
60
+ }
61
+ const steps = listSteps(db, operationId);
62
+ if (state === 'committed' && steps.some((step) => step.state !== 'done')) {
63
+ throw new RagError('operation-uncertain', 'la operación no se puede confirmar: hay pasos sin completar', {
64
+ details: { operationId, steps: steps.map((step) => ({ step: step.step, state: step.state })) },
65
+ });
66
+ }
67
+ const patch = detail === undefined ? null : JSON.stringify(detail);
68
+ const result = patch === null
69
+ ? db.prepare(`UPDATE operations SET state=?, finished_at=? WHERE id=?`).run(state, now, operationId)
70
+ : db.prepare(`UPDATE operations SET state=?, finished_at=?, detail=? WHERE id=?`).run(state, now, patch, operationId);
71
+ if (Number(result.changes) === 0) {
72
+ throw new RagError('invalid-argument', 'la operación no existe', { details: { operationId } });
73
+ }
74
+ return { id: operationId, state };
75
+ }
76
+
77
+ export function getOperation(db, operationId) {
78
+ const operation = db.prepare('SELECT * FROM operations WHERE id = ?').get(operationId) ?? null;
79
+ return operation ? { ...operation, steps: listSteps(db, operationId) } : null;
80
+ }
81
+
82
+ export function listSteps(db, operationId) {
83
+ return db.prepare('SELECT * FROM operation_steps WHERE operation_id = ? ORDER BY step').all(operationId);
84
+ }
85
+
86
+ /** Operaciones que quedaron abiertas: resultado desconocido hasta reconciliarlas. */
87
+ export function listInterruptedOperations(db, { kind } = {}) {
88
+ const rows = kind
89
+ ? db.prepare(`SELECT * FROM operations WHERE state='started' AND kind=? ORDER BY started_at, id`).all(kind)
90
+ : db.prepare(`SELECT * FROM operations WHERE state='started' ORDER BY started_at, id`).all();
91
+ return rows.map((row) => ({ ...row, steps: listSteps(db, row.id) }));
92
+ }
93
+
94
+ /**
95
+ * Reconcilia operaciones interrumpidas con la evidencia que aporte el llamador.
96
+ *
97
+ * `decide(operation)` devuelve `{state: 'committed'|'failed'|'reconciled', detail?}`. La función no
98
+ * ejecuta el trabajo otra vez: sólo cierra la fila con la conclusión documentada.
99
+ *
100
+ * @returns {Array<{id: string, from: string, to: string}>}
101
+ */
102
+ export function reconcileInterruptedOperations(db, { kind, decide, now = Date.now() } = {}) {
103
+ if (typeof decide !== 'function') throw new RagError('invalid-argument', 'reconciliar exige una función decide');
104
+ const changed = [];
105
+ for (const operation of listInterruptedOperations(db, { kind })) {
106
+ const verdict = decide(operation) ?? { state: 'failed', detail: { reason: 'sin-evidencia' } };
107
+ finishOperation(db, { operationId: operation.id, state: verdict.state, now, detail: verdict.detail });
108
+ changed.push({ id: operation.id, from: 'started', to: verdict.state });
109
+ }
110
+ return changed;
111
+ }
112
+
113
+ /**
114
+ * Falla en cerrado si hay una operación destructiva interrumpida de este tipo: repetirla podría
115
+ * duplicar un efecto que quizá ya ocurrió.
116
+ */
117
+ export function assertNoInterruptedOperation(db, { kind } = {}) {
118
+ const interrupted = listInterruptedOperations(db, { kind });
119
+ if (interrupted.length > 0) {
120
+ throw new RagError('operation-uncertain', 'hay una operación destructiva interrumpida sin reconciliar', {
121
+ details: {
122
+ kind: kind ?? null,
123
+ operations: interrupted.map((operation) => ({
124
+ id: operation.id,
125
+ started_at: operation.started_at,
126
+ steps: listSteps(db, operation.id).map((step) => ({ step: step.step, state: step.state })),
127
+ })),
128
+ },
129
+ });
130
+ }
131
+ return true;
132
+ }