@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.
- package/LICENSE +21 -0
- package/README.md +191 -2
- package/bin/lifecode-rag.mjs +449 -0
- package/client.js +2801 -0
- package/cordis.patch.yml +3 -0
- package/docs/ARCHITECTURE-v0.2.md +269 -0
- package/docs/AUTO-DISCOVERY.md +111 -0
- package/docs/AUTOMATION-POLICIES.md +232 -0
- package/docs/CONTRATO-v0.1.md +195 -0
- package/docs/EMBEDDING-PROVIDERS.md +105 -0
- package/docs/OBSERVABILITY.md +241 -0
- package/docs/PA-UI-0-API-CONTRACT.md +802 -0
- package/docs/PERFORMANCE-BUDGETS.md +118 -0
- package/docs/PROJECT-AWARE-ARCHITECTURE.md +580 -0
- package/docs/PROJECT-AWARE-DATA-CONTRACT.md +411 -0
- package/docs/PROJECT-AWARE-ERROR-CONTRACT.md +112 -0
- package/docs/PROJECT-AWARE-SESSION-CONTRACT.md +120 -0
- package/docs/WORKSPACE-API.md +239 -0
- package/icon.svg +7 -0
- package/index.js +198 -0
- package/lib/audit-export.mjs +70 -0
- package/lib/audit.mjs +120 -0
- package/lib/auto-context.mjs +322 -0
- package/lib/automation.mjs +214 -0
- package/lib/chunk.mjs +100 -0
- package/lib/config-resolve.mjs +119 -0
- package/lib/context.mjs +150 -0
- package/lib/conversation-events.mjs +145 -0
- package/lib/db.mjs +309 -0
- package/lib/diagnose.mjs +197 -0
- package/lib/discovery.mjs +402 -0
- package/lib/doctor.mjs +82 -0
- package/lib/embed.mjs +96 -0
- package/lib/embedders.mjs +103 -0
- package/lib/errors.mjs +227 -0
- package/lib/exec-context.mjs +238 -0
- package/lib/extract.mjs +260 -0
- package/lib/harness-workspaces.mjs +85 -0
- package/lib/hash.mjs +34 -0
- package/lib/ingest.mjs +239 -0
- package/lib/inputs.mjs +67 -0
- package/lib/library-state.mjs +252 -0
- package/lib/maintenance.mjs +113 -0
- package/lib/metrics.mjs +164 -0
- package/lib/migrate.mjs +373 -0
- package/lib/operations.mjs +132 -0
- package/lib/pa-api.mjs +517 -0
- package/lib/paths.mjs +345 -0
- package/lib/policy.mjs +125 -0
- package/lib/profile.mjs +128 -0
- package/lib/readmodel.mjs +159 -0
- package/lib/recovery.mjs +557 -0
- package/lib/registry-schema.mjs +206 -0
- package/lib/registry.mjs +406 -0
- package/lib/resolve.mjs +311 -0
- package/lib/retention.mjs +143 -0
- package/lib/revocation.mjs +124 -0
- package/lib/roots-structure.mjs +224 -0
- package/lib/schema.mjs +173 -0
- package/lib/scope-ops.mjs +379 -0
- package/lib/scope-stores.mjs +128 -0
- package/lib/search.mjs +345 -0
- package/lib/selection.mjs +150 -0
- package/lib/server.mjs +335 -0
- package/lib/session-identity.mjs +51 -0
- package/lib/sessions.mjs +343 -0
- package/lib/sync-scheduler.mjs +354 -0
- package/lib/sync.mjs +755 -0
- package/lib/tags.mjs +45 -0
- package/lib/tools.mjs +364 -0
- package/lib/trusted-roots.mjs +149 -0
- package/lib/worker-context.mjs +22 -0
- package/package.json +67 -5
package/lib/db.mjs
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Apertura, inicialización y comprobaciones baratas del almacén SQLite de LifeCode RAG.
|
|
3
|
+
*
|
|
4
|
+
* `node:sqlite` es una capacidad del propio host (Node 24 / Electron 44), no una dependencia: el
|
|
5
|
+
* plugin no importa nada de `@deepseek-ai/*`. El fichero lleva `application_id` propio para que un
|
|
6
|
+
* `rag.sqlite3` de otro producto se rechace en vez de interpretarse.
|
|
7
|
+
*
|
|
8
|
+
* Apertura = comprobación **barata**: `PRAGMA quick_check` y coherencia de la cabeza de auditoría.
|
|
9
|
+
* `integrity-check` de FTS es O(índice) y sólo corre en `doctor`, `reindex` y tras migrar.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { existsSync, mkdirSync, statSync } from 'node:fs';
|
|
13
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
14
|
+
|
|
15
|
+
import { RagError } from './errors.mjs';
|
|
16
|
+
import { storePaths } from './paths.mjs';
|
|
17
|
+
import { APPLICATION_ID, DDL, DDL_V3, EXPECTED_TABLES, SCHEMA_VERSION, initialMeta } from './schema.mjs';
|
|
18
|
+
|
|
19
|
+
/** Configuración de conexión: durabilidad de auditoría y espera acotada, nunca bloqueo indefinido. */
|
|
20
|
+
export function configureConnection(db, { file = true } = {}) {
|
|
21
|
+
db.exec('PRAGMA busy_timeout = 5000');
|
|
22
|
+
db.exec('PRAGMA foreign_keys = ON');
|
|
23
|
+
if (file) {
|
|
24
|
+
db.exec('PRAGMA journal_mode = WAL');
|
|
25
|
+
db.exec('PRAGMA synchronous = FULL');
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function pragmaNumber(db, name) {
|
|
30
|
+
const row = db.prepare(`PRAGMA ${name}`).get();
|
|
31
|
+
return Number(row?.[name] ?? 0);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function tableNames(db) {
|
|
35
|
+
return db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all().map((row) => row.name);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** `quick_check` debe responder exactamente `ok`. */
|
|
39
|
+
export function quickCheck(db) {
|
|
40
|
+
const rows = db.prepare('PRAGMA quick_check').all();
|
|
41
|
+
if (rows.length !== 1 || rows[0]?.quick_check !== 'ok') {
|
|
42
|
+
throw new RagError('store-corrupt', 'quick_check no devolvió ok', { details: { rows: rows.slice(0, 5) } });
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** ¿La cabeza declarada en `meta` coincide con la última fila de `audit`? Detecta truncaciones y huecos. */
|
|
47
|
+
export function assertAuditHead(db) {
|
|
48
|
+
const declared = Number(readMeta(db, 'audit_head_seq') ?? '0');
|
|
49
|
+
const actual = Number(db.prepare('SELECT COALESCE(MAX(seq), 0) AS max_seq FROM audit').get()?.max_seq ?? 0);
|
|
50
|
+
if (declared !== actual) {
|
|
51
|
+
throw new RagError('store-corrupt', 'la cabeza de auditoría no coincide con la tabla', {
|
|
52
|
+
details: { declared, actual },
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* `integrity-check` de la FTS externa. Con `rank = 1` compara el contenido indexado con `chunks`; una
|
|
59
|
+
* fila huérfana o un texto divergente lo hacen fallar. Es costoso: no se llama en cada apertura.
|
|
60
|
+
*/
|
|
61
|
+
export function ftsIntegrityCheck(db) {
|
|
62
|
+
try {
|
|
63
|
+
db.exec("INSERT INTO chunks_fts(chunks_fts, rank) VALUES('integrity-check', 1)");
|
|
64
|
+
} catch (error) {
|
|
65
|
+
throw new RagError('fts-integrity', 'el índice de texto no coincide con los chunks', { cause: error });
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Reconstruye la FTS desde `chunks`. Idempotente; se usa tras migrar y en `reindex`. */
|
|
70
|
+
export function ftsRebuild(db) {
|
|
71
|
+
db.exec("INSERT INTO chunks_fts(chunks_fts) VALUES('rebuild')");
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function readMeta(db, key) {
|
|
75
|
+
const row = db.prepare('SELECT value FROM meta WHERE key = ?').get(key);
|
|
76
|
+
return row?.value;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function writeMeta(db, key, value) {
|
|
80
|
+
db.prepare('INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value')
|
|
81
|
+
.run(key, String(value));
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Transacción con reversión garantizada. `work` es síncrono: mantenerlo así evita awaits dentro del lock. */
|
|
85
|
+
export function withTransaction(db, work, { immediate = true } = {}) {
|
|
86
|
+
db.exec(immediate ? 'BEGIN IMMEDIATE' : 'BEGIN');
|
|
87
|
+
try {
|
|
88
|
+
const result = work();
|
|
89
|
+
db.exec('COMMIT');
|
|
90
|
+
return result;
|
|
91
|
+
} catch (error) {
|
|
92
|
+
try { db.exec('ROLLBACK'); } catch { /* el ROLLBACK puede fallar si SQLite ya revirtió */ }
|
|
93
|
+
throw error;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function initialize(db, now) {
|
|
98
|
+
withTransaction(db, () => {
|
|
99
|
+
for (const statement of DDL) db.exec(statement);
|
|
100
|
+
db.exec(`PRAGMA application_id = ${APPLICATION_ID}`);
|
|
101
|
+
db.exec(`PRAGMA user_version = ${SCHEMA_VERSION}`);
|
|
102
|
+
const insert = db.prepare('INSERT INTO meta (key, value) VALUES (?, ?)');
|
|
103
|
+
for (const [key, value] of initialMeta(now)) insert.run(key, value);
|
|
104
|
+
});
|
|
105
|
+
if (pragmaNumber(db, 'application_id') !== APPLICATION_ID) {
|
|
106
|
+
throw new RagError('store-corrupt', 'no se pudo fijar application_id');
|
|
107
|
+
}
|
|
108
|
+
if (pragmaNumber(db, 'user_version') !== SCHEMA_VERSION) {
|
|
109
|
+
throw new RagError('store-corrupt', 'no se pudo fijar user_version');
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Migración secuencial. Sólo existe 2 → 3: la v1 nunca se publicó y no se finge soporte.
|
|
115
|
+
* Todo ocurre en una transacción; si algo falla, el fichero queda en su versión anterior.
|
|
116
|
+
*/
|
|
117
|
+
function migrate(db, from, now) {
|
|
118
|
+
if (from === 2) {
|
|
119
|
+
withTransaction(db, () => {
|
|
120
|
+
for (const statement of DDL_V3) db.exec(statement);
|
|
121
|
+
db.exec(`PRAGMA user_version = ${SCHEMA_VERSION}`);
|
|
122
|
+
writeMeta(db, 'schema_version', SCHEMA_VERSION);
|
|
123
|
+
writeMeta(db, 'migrated_at', now);
|
|
124
|
+
});
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
throw new RagError('store-version-unsupported', 'no hay migración desde esta versión', {
|
|
128
|
+
details: { found: from, supported: SCHEMA_VERSION },
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Tamaño en bytes de un fichero, para dejar constancia del daño sin lanzar por el camino. */
|
|
133
|
+
function sizeOf(path) {
|
|
134
|
+
try {
|
|
135
|
+
return statSync(path).size;
|
|
136
|
+
} catch {
|
|
137
|
+
return null;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Abre el almacén. `create: true` es la única vía que crea el árbol y el fichero (`init`), y sólo cuando
|
|
143
|
+
* no existe nada: sobre un fichero existente nunca se inicializa encima.
|
|
144
|
+
*
|
|
145
|
+
* @returns {{ db: DatabaseSync, paths: ReturnType<typeof storePaths>, created: boolean }}
|
|
146
|
+
*/
|
|
147
|
+
export function openDatabase({ root, create = false, now = Date.now() } = {}) {
|
|
148
|
+
const paths = storePaths(root);
|
|
149
|
+
const existed = existsSync(paths.database);
|
|
150
|
+
if (!existed && !create) {
|
|
151
|
+
throw new RagError('store-not-initialized', 'el almacén no existe; ejecuta init o ingiere un documento', {
|
|
152
|
+
details: { path: paths.database },
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
if (create && !existsSync(paths.root)) mkdirSync(paths.root, { recursive: true });
|
|
156
|
+
if (create && !existsSync(paths.backups)) mkdirSync(paths.backups, { recursive: true });
|
|
157
|
+
|
|
158
|
+
let db;
|
|
159
|
+
try {
|
|
160
|
+
db = new DatabaseSync(paths.database);
|
|
161
|
+
} catch (error) {
|
|
162
|
+
throw openError(error, paths.database);
|
|
163
|
+
}
|
|
164
|
+
try { configureConnection(db, { file: true });
|
|
165
|
+
const appId = pragmaNumber(db, 'application_id');
|
|
166
|
+
const version = pragmaNumber(db, 'user_version');
|
|
167
|
+
const tables = tableNames(db);
|
|
168
|
+
|
|
169
|
+
if (tables.length === 0) {
|
|
170
|
+
if (appId !== 0) throw new RagError('store-not-rag', 'application_id presente sin esquema');
|
|
171
|
+
if (existed) {
|
|
172
|
+
// El fichero EXISTÍA y no tiene esquema: un corte durante un checkpoint, un disco lleno o una
|
|
173
|
+
// copia truncada. Inicializar encima destruiría la única prueba de lo que había. Se trata como
|
|
174
|
+
// corrupto y la recuperación es explícita, nunca implícita.
|
|
175
|
+
throw new RagError('store-corrupt', 'el fichero del almacén existe pero no tiene esquema utilizable', {
|
|
176
|
+
details: { path: paths.database, bytes: sizeOf(paths.database) },
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
if (!create) {
|
|
180
|
+
throw new RagError('store-not-initialized', 'el fichero existe pero no tiene esquema', {
|
|
181
|
+
details: { path: paths.database },
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
initialize(db, now);
|
|
185
|
+
} else {
|
|
186
|
+
if (appId !== APPLICATION_ID) {
|
|
187
|
+
throw new RagError('store-not-rag', 'el fichero no es un almacén de LifeCode RAG', {
|
|
188
|
+
details: { applicationId: appId },
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
if (version > SCHEMA_VERSION) {
|
|
192
|
+
throw new RagError('store-version-unsupported', 'el almacén es de una versión más nueva', {
|
|
193
|
+
details: { found: version, supported: SCHEMA_VERSION },
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
if (version < SCHEMA_VERSION) migrate(db, version, now);
|
|
197
|
+
const currentTables = tableNames(db);
|
|
198
|
+
const missing = EXPECTED_TABLES.filter((name) => !currentTables.includes(name));
|
|
199
|
+
if (missing.length > 0) {
|
|
200
|
+
throw new RagError('store-corrupt', 'faltan tablas del esquema', { details: { missing } });
|
|
201
|
+
}
|
|
202
|
+
quickCheck(db);
|
|
203
|
+
ftsTableIsExternal(db);
|
|
204
|
+
assertAuditHead(db);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
return { db, paths, created: !existed };
|
|
208
|
+
} catch (error) {
|
|
209
|
+
try { db.close(); } catch { /* cerrar tras un fallo no debe ocultar el fallo original */ }
|
|
210
|
+
if (isBusyError(error)) {
|
|
211
|
+
throw new RagError('store-busy', 'el almacén está bloqueado por otra conexión', {
|
|
212
|
+
details: { path: paths.database, errcode: Number(error?.errcode ?? 0) },
|
|
213
|
+
cause: error,
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
if (isCorruptionError(error)) {
|
|
217
|
+
throw new RagError('store-corrupt', 'el fichero del almacén no es una base de datos utilizable', {
|
|
218
|
+
details: { path: paths.database, errcode: Number(error?.errcode ?? 0) },
|
|
219
|
+
cause: error,
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
throw error;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** `true` si el error de SQLite es contención (busy/locked) y no corrupción. */
|
|
227
|
+
export function isBusyError(error) {
|
|
228
|
+
const errcode = Number(error?.errcode ?? 0);
|
|
229
|
+
if (errcode === 5 || errcode === 6) return true;
|
|
230
|
+
return /SQLITE_BUSY|SQLITE_LOCKED|database is locked/i.test(String(error?.code ?? '') + String(error?.message ?? ''));
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* `true` si SQLite dice que el fichero no es una base de datos o está dañada (11 = corrupt,
|
|
235
|
+
* 26 = not a database). Se comprueba antes que la contención y se distingue de un fichero que sólo
|
|
236
|
+
* no se puede abrir por permisos.
|
|
237
|
+
*/
|
|
238
|
+
export function isCorruptionError(error) {
|
|
239
|
+
const errcode = Number(error?.errcode ?? 0);
|
|
240
|
+
if (errcode === 11 || errcode === 26) return true;
|
|
241
|
+
return /SQLITE_CORRUPT|SQLITE_NOTADB|file is not a database|database disk image is malformed|malformed database/i.test(
|
|
242
|
+
String(error?.code ?? '') + ' ' + String(error?.message ?? ''),
|
|
243
|
+
);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** Traduce un fallo al abrir el fichero: un fichero ilegible no es una base corrupta. */
|
|
247
|
+
function openError(error, path) {
|
|
248
|
+
if (isBusyError(error)) {
|
|
249
|
+
return new RagError('store-busy', 'el almacén está bloqueado por otra conexión', {
|
|
250
|
+
details: { path },
|
|
251
|
+
cause: error,
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
if (error?.code === 'EACCES' || error?.code === 'EPERM') {
|
|
255
|
+
return new RagError('source-unreadable', 'el almacén no se puede leer por permisos', {
|
|
256
|
+
details: { path },
|
|
257
|
+
cause: error,
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
return error;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Traduce un fallo de SQLite surgido **con la conexión ya abierta** (por ejemplo una escritura que
|
|
265
|
+
* encuentra otra conexión con el bloqueo tomado). Sin esto, `node:sqlite` deja escapar el mensaje
|
|
266
|
+
* crudo `database is locked` como error `internal`, que ni es del contrato ni dice que reintentar
|
|
267
|
+
* baste. Devuelve `null` cuando el fallo no es de almacén y el llamador debe decidir otra cosa.
|
|
268
|
+
*
|
|
269
|
+
* La contención es transitoria, no pérdida de autorización ni corrupción: se marca `store-busy`
|
|
270
|
+
* para que el consumidor sepa que puede reintentar la misma operación.
|
|
271
|
+
*/
|
|
272
|
+
export function storeFailure(error, { path = null } = {}) {
|
|
273
|
+
if (isBusyError(error)) {
|
|
274
|
+
return new RagError('store-busy', 'el almacén está ocupado por otra operación; reintenta', {
|
|
275
|
+
details: { path, retryable: true },
|
|
276
|
+
cause: error,
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
if (isCorruptionError(error)) {
|
|
280
|
+
return new RagError('store-corrupt', 'el fichero del almacén no es una base de datos utilizable', {
|
|
281
|
+
details: { path },
|
|
282
|
+
cause: error,
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
return null;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** La FTS debe ser externa y apuntar a `chunks`: si alguien la recreó interna, el diseño cambió. */
|
|
289
|
+
function ftsTableIsExternal(db) {
|
|
290
|
+
const row = db.prepare("SELECT sql FROM sqlite_master WHERE name = 'chunks_fts'").get();
|
|
291
|
+
const sql = String(row?.sql ?? '');
|
|
292
|
+
if (!/CREATE VIRTUAL TABLE/i.test(sql) || !/content\s*=\s*'chunks'/i.test(sql) || !/content_rowid\s*=\s*'id'/i.test(sql)) {
|
|
293
|
+
throw new RagError('store-corrupt', 'chunks_fts no es una tabla externa sobre chunks', { details: { sql } });
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
export function closeDatabase(db) {
|
|
298
|
+
try { db.close(); } catch { /* doble cierre tolerable */ }
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** Abre, ejecuta y cierra pase lo que pase. Para una operación de herramienta, el handle no sobrevive. */
|
|
302
|
+
export function withDatabase(options, work) {
|
|
303
|
+
const opened = openDatabase(options);
|
|
304
|
+
try {
|
|
305
|
+
return work(opened);
|
|
306
|
+
} finally {
|
|
307
|
+
closeDatabase(opened.db);
|
|
308
|
+
}
|
|
309
|
+
}
|
package/lib/diagnose.mjs
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Diagnóstico del perfil Project-Aware (sólo lectura).
|
|
3
|
+
*
|
|
4
|
+
* Responde a la pregunta operativa «¿está sano lo que tengo instalado?» sin abrir nada en
|
|
5
|
+
* escritura y sin tocar el registro: perfil y configuración efectiva, integridad del registro y
|
|
6
|
+
* de cada almacén de ámbito, cadenas de auditoría, recuentos, sincronización y selección humana.
|
|
7
|
+
*
|
|
8
|
+
* No repara nada a propósito: un diagnóstico que escribe deja de ser un diagnóstico.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
12
|
+
import { existsSync, readFileSync, statSync } from 'node:fs';
|
|
13
|
+
import { createHash } from 'node:crypto';
|
|
14
|
+
import { join } from 'node:path';
|
|
15
|
+
|
|
16
|
+
import { verifyAuditChain } from './audit.mjs';
|
|
17
|
+
import { closeRegistry, openRegistry, registryIntegrity } from './registry.mjs';
|
|
18
|
+
import { classifyScopeStore, isServable } from './library-state.mjs';
|
|
19
|
+
import { listRecoveryArtifacts } from './recovery.mjs';
|
|
20
|
+
import { loadConfig } from './paths.mjs';
|
|
21
|
+
import { resolveConfig, resolveDataRoot, resolveProfileKey } from './config-resolve.mjs';
|
|
22
|
+
import { profileKey, profileRoot, registryPath } from './profile.mjs';
|
|
23
|
+
|
|
24
|
+
const sha256 = (path) => createHash('sha256').update(readFileSync(path)).digest('hex');
|
|
25
|
+
|
|
26
|
+
function countsOf(storeFile) {
|
|
27
|
+
let store;
|
|
28
|
+
try {
|
|
29
|
+
store = new DatabaseSync(storeFile, { readOnly: true });
|
|
30
|
+
store.exec('PRAGMA busy_timeout = 2000');
|
|
31
|
+
const one = (sql) => Number(store.prepare(sql).get()?.n ?? 0);
|
|
32
|
+
const model = store.prepare("SELECT value FROM meta WHERE key = 'embedding_model'").get()?.value ?? null;
|
|
33
|
+
const result = {
|
|
34
|
+
sources: one('SELECT COUNT(*) AS n FROM sources'),
|
|
35
|
+
chunks: one('SELECT COUNT(*) AS n FROM chunks'),
|
|
36
|
+
vectors: one('SELECT COUNT(*) AS n FROM vectors'),
|
|
37
|
+
fts: one('SELECT COUNT(*) AS n FROM chunks_fts'),
|
|
38
|
+
orphanChunks: one('SELECT COUNT(*) AS n FROM chunks c LEFT JOIN sources s ON s.id = c.source_id WHERE s.id IS NULL'),
|
|
39
|
+
missingVectors: model
|
|
40
|
+
? one('SELECT COUNT(*) AS n FROM chunks c LEFT JOIN vectors v ON v.chunk_key = c.chunk_key AND v.model = ' + `'${String(model).replaceAll("'", "''")}'` + ' WHERE v.chunk_key IS NULL')
|
|
41
|
+
: null,
|
|
42
|
+
// Windows no distingue mayúsculas en rutas: un renombrado que sólo cambia el caso puede dejar dos
|
|
43
|
+
// fuentes para el mismo fichero. Se cuenta para que el usuario lo vea y decida; no se repara aquí.
|
|
44
|
+
caseCollisions: one(
|
|
45
|
+
'SELECT COUNT(*) AS n FROM (SELECT lower(uri) AS u FROM sources GROUP BY lower(uri) HAVING COUNT(*) > 1)',
|
|
46
|
+
),
|
|
47
|
+
schemaVersion: Number(store.prepare('PRAGMA user_version').get().user_version),
|
|
48
|
+
};
|
|
49
|
+
result.audit = verifyAuditChain(store);
|
|
50
|
+
return result;
|
|
51
|
+
} catch (error) {
|
|
52
|
+
return { error: error.code ?? 'unreadable', message: error.message };
|
|
53
|
+
} finally {
|
|
54
|
+
if (store) store.close();
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* @param {{env?:object, argv?:string[], now?:() => number}} [options]
|
|
60
|
+
* @returns {{ok:boolean, profile:object, registry:object|null, scopes:object[], selections:object[], problems:string[]}}
|
|
61
|
+
*/
|
|
62
|
+
export function diagnoseProfile({ env = process.env, argv = process.argv, now = () => Date.now() } = {}) {
|
|
63
|
+
const key = profileKey(env, argv);
|
|
64
|
+
const root = profileRoot(env, argv);
|
|
65
|
+
const configPath = join(root, 'config.json');
|
|
66
|
+
const problems = [];
|
|
67
|
+
|
|
68
|
+
const config = {
|
|
69
|
+
path: configPath,
|
|
70
|
+
exists: existsSync(configPath),
|
|
71
|
+
bytes: existsSync(configPath) ? statSync(configPath).size : null,
|
|
72
|
+
sha256: existsSync(configPath) ? sha256(configPath) : null,
|
|
73
|
+
};
|
|
74
|
+
try {
|
|
75
|
+
// Configuración efectiva (perfil > global > defaults), la misma que aplican las herramientas.
|
|
76
|
+
const loaded = resolveConfig({ dataRoot: resolveDataRoot(env), profileKey: resolveProfileKey(env) }).config;
|
|
77
|
+
config.effectiveSearch = { diversity: loaded.search.diversity, strategy: loaded.search.strategy, limit: loaded.search.limit };
|
|
78
|
+
config.automation = {
|
|
79
|
+
enabled: loaded.automation.enabled,
|
|
80
|
+
intervalMs: loaded.automation.intervalMs,
|
|
81
|
+
maxFilesPerRun: loaded.automation.maxFilesPerRun,
|
|
82
|
+
tickBudgetMs: loaded.automation.tickBudgetMs,
|
|
83
|
+
};
|
|
84
|
+
config.autoContext = { enabled: loaded.autoContext.enabled, timeoutMs: loaded.autoContext.timeoutMs };
|
|
85
|
+
config.embedding = { provider: loaded.embedding.provider, dim: loaded.embedding.dim };
|
|
86
|
+
if (loaded.automation.enabled) problems.push('automation.enabled=true: la sincronización periódica está activa');
|
|
87
|
+
} catch (error) {
|
|
88
|
+
config.error = error.code ?? 'invalid-config';
|
|
89
|
+
problems.push(`configuración ilegible: ${config.error}`);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const report = {
|
|
93
|
+
generatedAt: new Date(now()).toISOString(),
|
|
94
|
+
profile: { key, root, config },
|
|
95
|
+
registry: null,
|
|
96
|
+
scopes: [],
|
|
97
|
+
selections: [],
|
|
98
|
+
problems,
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
const registryFile = registryPath(root);
|
|
102
|
+
if (!existsSync(registryFile)) {
|
|
103
|
+
report.registry = { path: registryFile, exists: false };
|
|
104
|
+
problems.push('el perfil no tiene registro Project-Aware (todavía no hay proyecto registrado)');
|
|
105
|
+
return { ...report, ok: false };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
let opened;
|
|
109
|
+
try {
|
|
110
|
+
opened = openRegistry({ root, create: false, now: now() });
|
|
111
|
+
} catch (error) {
|
|
112
|
+
report.registry = { path: registryFile, exists: true, error: error.code ?? 'registry-unavailable', message: error.message };
|
|
113
|
+
problems.push(`registro ilegible: ${report.registry.error}`);
|
|
114
|
+
return { ...report, ok: false };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
try {
|
|
118
|
+
const db = opened.db;
|
|
119
|
+
const integrity = registryIntegrity(db);
|
|
120
|
+
const projects = db.prepare('SELECT id, name, status FROM projects ORDER BY created_at').all();
|
|
121
|
+
const libraries = db.prepare('SELECT id, name, status FROM libraries ORDER BY name').all();
|
|
122
|
+
const roots = db.prepare('SELECT id, scope_kind, scope_id, path, state FROM roots ORDER BY path').all();
|
|
123
|
+
const grants = db.prepare('SELECT project_id, library_id FROM grants WHERE revoked_at IS NULL').all();
|
|
124
|
+
const sessions = db.prepare('SELECT session_id, project_id, state, revision, selection_source, selected_by FROM session_scope').all();
|
|
125
|
+
const unfinished = db.prepare("SELECT id, kind FROM operations WHERE state = 'started'").all();
|
|
126
|
+
const syncRows = db
|
|
127
|
+
.prepare('SELECT scope_kind, scope_id, status, COUNT(*) AS n FROM sync_state GROUP BY scope_kind, scope_id, status')
|
|
128
|
+
.all();
|
|
129
|
+
|
|
130
|
+
report.registry = {
|
|
131
|
+
path: registryFile,
|
|
132
|
+
exists: true,
|
|
133
|
+
bytes: statSync(registryFile).size,
|
|
134
|
+
sha256: sha256(registryFile),
|
|
135
|
+
quickCheck: integrity.quickCheck,
|
|
136
|
+
foreignKeys: integrity.foreignKeys,
|
|
137
|
+
audit: integrity.audit,
|
|
138
|
+
projects,
|
|
139
|
+
libraries,
|
|
140
|
+
roots,
|
|
141
|
+
grants,
|
|
142
|
+
sessionCount: sessions.length,
|
|
143
|
+
unfinishedOperations: unfinished,
|
|
144
|
+
};
|
|
145
|
+
report.selections = sessions;
|
|
146
|
+
|
|
147
|
+
if (integrity.quickCheck !== 'ok') problems.push(`registro: quick_check=${integrity.quickCheck}`);
|
|
148
|
+
if (integrity.foreignKeys !== 0) problems.push(`registro: ${integrity.foreignKeys} violaciones de clave ajena`);
|
|
149
|
+
if (!integrity.audit?.ok) problems.push(`registro: cadena de auditoría rota en ${integrity.audit?.brokenAt}`);
|
|
150
|
+
if (unfinished.length > 0) problems.push(`registro: ${unfinished.length} operación(es) sin cerrar`);
|
|
151
|
+
|
|
152
|
+
const scopes = [
|
|
153
|
+
...projects.map((project) => ({ kind: 'prj', id: project.id, name: project.name, status: project.status })),
|
|
154
|
+
...libraries.map((library) => ({ kind: 'lib', id: library.id, name: library.name, status: library.status })),
|
|
155
|
+
];
|
|
156
|
+
for (const scope of scopes) {
|
|
157
|
+
const entry = classifyScopeStore({ profileRootPath: root, profileKey: key, scope, checkIntegrity: true });
|
|
158
|
+
const row = {
|
|
159
|
+
scopeId: scope.id,
|
|
160
|
+
kind: scope.kind,
|
|
161
|
+
name: scope.name,
|
|
162
|
+
status: scope.status,
|
|
163
|
+
state: entry.state,
|
|
164
|
+
reason: entry.reason ?? null,
|
|
165
|
+
path: entry.path ?? null,
|
|
166
|
+
bytes: entry.bytes ?? null,
|
|
167
|
+
artifacts: listRecoveryArtifacts({ profileRootPath: root, scope }).length,
|
|
168
|
+
roots: roots.filter((r) => r.scope_kind === scope.kind && r.scope_id === scope.id).map((r) => ({ path: r.path, state: r.state })),
|
|
169
|
+
sync: syncRows
|
|
170
|
+
.filter((r) => r.scope_kind === scope.kind && r.scope_id === scope.id)
|
|
171
|
+
.reduce((acc, r) => ({ ...acc, [r.status]: r.n }), {}),
|
|
172
|
+
};
|
|
173
|
+
if (isServable(entry.state) && entry.path && existsSync(entry.path)) row.counts = countsOf(entry.path);
|
|
174
|
+
report.scopes.push(row);
|
|
175
|
+
if (!isServable(entry.state)) {
|
|
176
|
+
problems.push(`ámbito ${scope.id} (${scope.name ?? scope.kind}): estado ${entry.state}${entry.reason ? ` (${entry.reason})` : ''}`);
|
|
177
|
+
}
|
|
178
|
+
const counts = row.counts;
|
|
179
|
+
if (counts && !counts.error) {
|
|
180
|
+
if (counts.chunks !== counts.fts) problems.push(`ámbito ${scope.id}: FTS ${counts.fts} ≠ chunks ${counts.chunks}`);
|
|
181
|
+
if (counts.orphanChunks) problems.push(`ámbito ${scope.id}: ${counts.orphanChunks} chunks huérfanos`);
|
|
182
|
+
if (counts.missingVectors) problems.push(`ámbito ${scope.id}: ${counts.missingVectors} vectores faltantes`);
|
|
183
|
+
if (counts.caseCollisions) {
|
|
184
|
+
problems.push(
|
|
185
|
+
`ámbito ${scope.id}: ${counts.caseCollisions} ruta(s) duplicadas sólo por mayúsculas/minúsculas ` +
|
|
186
|
+
'(renombrado de caso); revisa las fuentes y usa forget en la duplicada',
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
if (!counts.audit?.ok) problems.push(`ámbito ${scope.id}: cadena de auditoría rota en ${counts.audit?.brokenAt}`);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
} finally {
|
|
193
|
+
closeRegistry(opened.db);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
return { ...report, ok: problems.length === 0 };
|
|
197
|
+
}
|