@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.
- package/LICENSE +21 -0
- package/README.md +220 -2
- package/bin/lifecode-rag.mjs +449 -0
- package/client.js +3515 -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 +887 -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 +231 -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 +946 -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 +606 -0
- package/lib/resolve.mjs +318 -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 +225 -0
- package/lib/server.mjs +340 -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/registry.mjs
ADDED
|
@@ -0,0 +1,606 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Registro Project-Aware (PA1): un `registry.sqlite3` por perfil con proyectos, bibliotecas,
|
|
3
|
+
* raíces autorizadas y auditoría propia del registro.
|
|
4
|
+
*
|
|
5
|
+
* Reglas que este módulo mantiene:
|
|
6
|
+
* - La integridad se comprueba al abrir: `application_id`, versión, tablas esperadas y cadena de
|
|
7
|
+
* auditoría. Un registro incoherente no se usa «a medias»: se cierra con `registry-corrupt`.
|
|
8
|
+
* - `roots.path_key` es único global; el esquema impone además que la raíz pertenezca a un proyecto
|
|
9
|
+
* o biblioteca existente mediante disparadores.
|
|
10
|
+
* - Crear un proyecto/biblioteca/raíz es una operación **humana**: `added_by` sólo admite
|
|
11
|
+
* `human`/`host`, y la función no acepta `model`.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
15
|
+
import { existsSync, mkdirSync } from 'node:fs';
|
|
16
|
+
import { dirname, isAbsolute } from 'node:path';
|
|
17
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
18
|
+
|
|
19
|
+
import { RagError } from './errors.mjs';
|
|
20
|
+
import { canonicalJson } from './audit.mjs';
|
|
21
|
+
import { withTransaction } from './db.mjs';
|
|
22
|
+
import { REGISTRY_APPLICATION_ID, REGISTRY_DDL, REGISTRY_MIGRATIONS, REGISTRY_VERSION } from './registry-schema.mjs';
|
|
23
|
+
import { registryPath } from './profile.mjs';
|
|
24
|
+
import {
|
|
25
|
+
assertRootStructure,
|
|
26
|
+
canonicalKey,
|
|
27
|
+
classifyRootRegistration,
|
|
28
|
+
findRootConflicts,
|
|
29
|
+
inspectRoot,
|
|
30
|
+
} from './roots-structure.mjs';
|
|
31
|
+
|
|
32
|
+
const REGISTRY_TABLES = Object.freeze([
|
|
33
|
+
'audit_registry',
|
|
34
|
+
'grants',
|
|
35
|
+
'libraries',
|
|
36
|
+
'meta',
|
|
37
|
+
'operation_steps',
|
|
38
|
+
'operations',
|
|
39
|
+
'pa_selection',
|
|
40
|
+
'projects',
|
|
41
|
+
'roots',
|
|
42
|
+
'session_scope',
|
|
43
|
+
'sync_state',
|
|
44
|
+
]);
|
|
45
|
+
|
|
46
|
+
const CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
|
|
47
|
+
let lastTime = 0;
|
|
48
|
+
let sequence = 0;
|
|
49
|
+
|
|
50
|
+
/** Identificador con forma ULID (26 caracteres Crockford en mayúsculas). */
|
|
51
|
+
export function newId(prefix, now = Date.now()) {
|
|
52
|
+
let time = Math.max(now, lastTime);
|
|
53
|
+
if (time === lastTime) {
|
|
54
|
+
sequence = (sequence + 1) % 0x1000;
|
|
55
|
+
if (sequence === 0) time += 1;
|
|
56
|
+
} else {
|
|
57
|
+
sequence = 0;
|
|
58
|
+
}
|
|
59
|
+
lastTime = time;
|
|
60
|
+
const timePart = Array.from({ length: 10 }, (_, index) => CROCKFORD[Math.floor(time / 32 ** (9 - index)) % 32]).join('');
|
|
61
|
+
const random = randomBytes(16);
|
|
62
|
+
let randomPart = '';
|
|
63
|
+
for (let index = 0; index < 16; index += 1) randomPart += CROCKFORD[random[index] % 32];
|
|
64
|
+
return `${prefix}${timePart}${randomPart}`;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Clave de ruta canónica para comparar raíces sin depender de mayúsculas, separadores ni enlaces
|
|
69
|
+
* (Windows). Desde PA4 canonicaliza con `realpath` cuando la ruta existe: dos rutas que apuntan a
|
|
70
|
+
* la misma carpeta física producen la misma clave.
|
|
71
|
+
*/
|
|
72
|
+
export function pathKeyFor(path) {
|
|
73
|
+
return canonicalKey(path);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function registryTables(db) {
|
|
77
|
+
return db.prepare(`SELECT name FROM sqlite_master WHERE type='table' ORDER BY name`).all().map((row) => row.name);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Abre el registro del perfil. Con `create` inicializa un registro vacío; sin él, un registro
|
|
82
|
+
* ausente es un error explícito, nunca un registro vacío implícito.
|
|
83
|
+
*/
|
|
84
|
+
export function openRegistry({ root, create = false, now = Date.now() } = {}) {
|
|
85
|
+
if (typeof root !== 'string' || !isAbsolute(root)) {
|
|
86
|
+
throw new RagError('invalid-config', 'la raíz del perfil debe ser una ruta absoluta');
|
|
87
|
+
}
|
|
88
|
+
const path = registryPath(root);
|
|
89
|
+
const exists = existsSync(path);
|
|
90
|
+
if (!exists && !create) {
|
|
91
|
+
throw new RagError('store-not-initialized', 'el registro del perfil no existe', { details: { root } });
|
|
92
|
+
}
|
|
93
|
+
if (create) mkdirSync(dirname(path), { recursive: true });
|
|
94
|
+
|
|
95
|
+
const db = new DatabaseSync(path);
|
|
96
|
+
try {
|
|
97
|
+
db.exec('PRAGMA foreign_keys = ON');
|
|
98
|
+
db.exec('PRAGMA busy_timeout = 5000');
|
|
99
|
+
db.exec('PRAGMA journal_mode = WAL');
|
|
100
|
+
db.exec('PRAGMA synchronous = FULL');
|
|
101
|
+
|
|
102
|
+
const fresh = registryTables(db).length === 0;
|
|
103
|
+
if (fresh) {
|
|
104
|
+
if (!create) throw new RagError('store-not-initialized', 'el registro del perfil está vacío');
|
|
105
|
+
initializeRegistry(db, { root, now });
|
|
106
|
+
} else {
|
|
107
|
+
// Un registro de una versión anterior se migra de forma ADITIVA antes de validarlo: sólo se
|
|
108
|
+
// crean estructuras nuevas (v1 → v2 añade `pa_selection`), ninguna fila existente se toca.
|
|
109
|
+
migrateRegistry(db, { root });
|
|
110
|
+
assertRegistry(db, { root });
|
|
111
|
+
}
|
|
112
|
+
return { db, path, root };
|
|
113
|
+
} catch (error) {
|
|
114
|
+
db.close();
|
|
115
|
+
throw error;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function initializeRegistry(db, { root, now }) {
|
|
120
|
+
db.exec('BEGIN IMMEDIATE');
|
|
121
|
+
try {
|
|
122
|
+
for (const statement of REGISTRY_DDL) db.exec(statement);
|
|
123
|
+
db.exec(`PRAGMA application_id = ${REGISTRY_APPLICATION_ID}`);
|
|
124
|
+
db.exec(`PRAGMA user_version = ${REGISTRY_VERSION}`);
|
|
125
|
+
const meta = db.prepare('INSERT INTO meta (key, value) VALUES (?, ?)');
|
|
126
|
+
meta.run('registry_version', String(REGISTRY_VERSION));
|
|
127
|
+
meta.run('created_at', String(now));
|
|
128
|
+
meta.run('profile_root', root);
|
|
129
|
+
meta.run('audit_head_seq', '0');
|
|
130
|
+
meta.run('audit_head_hash', '');
|
|
131
|
+
db.exec('COMMIT');
|
|
132
|
+
} catch (error) {
|
|
133
|
+
db.exec('ROLLBACK');
|
|
134
|
+
throw new RagError('internal', `no se pudo crear el registro: ${error.message}`, { cause: error });
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Lleva el registro a `REGISTRY_VERSION` con migraciones aditivas, o no hace nada si ya está al día.
|
|
140
|
+
*
|
|
141
|
+
* Se ejecuta dentro de `BEGIN IMMEDIATE` y vuelve a leer la versión dentro de la transacción: dos
|
|
142
|
+
* procesos del mismo perfil (host y CLI) pueden abrir a la vez, y sólo uno migra; el otro encuentra
|
|
143
|
+
* el registro ya migrado y sigue. Una versión superior a la soportada no se toca: la rechaza
|
|
144
|
+
* `assertRegistry` con `store-version-unsupported`.
|
|
145
|
+
*/
|
|
146
|
+
function migrateRegistry(db, { root }) {
|
|
147
|
+
const from = Number(db.prepare('PRAGMA user_version').get().user_version);
|
|
148
|
+
if (!Number.isInteger(from) || from < 1 || from >= REGISTRY_VERSION) return;
|
|
149
|
+
db.exec('BEGIN IMMEDIATE');
|
|
150
|
+
try {
|
|
151
|
+
const current = Number(db.prepare('PRAGMA user_version').get().user_version);
|
|
152
|
+
if (current >= REGISTRY_VERSION) {
|
|
153
|
+
db.exec('COMMIT');
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
for (let target = current + 1; target <= REGISTRY_VERSION; target += 1) {
|
|
157
|
+
for (const statement of REGISTRY_MIGRATIONS[target] ?? []) db.exec(statement);
|
|
158
|
+
}
|
|
159
|
+
db.exec(`PRAGMA user_version = ${REGISTRY_VERSION}`);
|
|
160
|
+
db.prepare(`INSERT INTO meta (key, value) VALUES ('registry_version', ?)
|
|
161
|
+
ON CONFLICT(key) DO UPDATE SET value = excluded.value`).run(String(REGISTRY_VERSION));
|
|
162
|
+
db.exec('COMMIT');
|
|
163
|
+
} catch (error) {
|
|
164
|
+
try { db.exec('ROLLBACK'); } catch { /* la transacción ya no estaba abierta */ }
|
|
165
|
+
throw new RagError('registry-corrupt', 'no se pudo migrar el registro del perfil', {
|
|
166
|
+
details: { root, from, to: REGISTRY_VERSION },
|
|
167
|
+
cause: error,
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function assertRegistry(db, { root }) {
|
|
173
|
+
const appId = Number(db.prepare('PRAGMA application_id').get().application_id);
|
|
174
|
+
if (appId !== REGISTRY_APPLICATION_ID) {
|
|
175
|
+
throw new RagError('registry-corrupt', 'el fichero de registro no es de LifeCode RAG', { details: { root } });
|
|
176
|
+
}
|
|
177
|
+
const version = Number(db.prepare('PRAGMA user_version').get().user_version);
|
|
178
|
+
if (!Number.isInteger(version) || version < 1) {
|
|
179
|
+
throw new RagError('registry-corrupt', 'versión de registro inválida', { details: { version } });
|
|
180
|
+
}
|
|
181
|
+
if (version > REGISTRY_VERSION) {
|
|
182
|
+
throw new RagError('store-version-unsupported', 'el registro fue escrito por una versión más nueva', {
|
|
183
|
+
details: { found: version, supported: REGISTRY_VERSION },
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
const tables = new Set(registryTables(db));
|
|
187
|
+
const missing = REGISTRY_TABLES.filter((name) => !tables.has(name));
|
|
188
|
+
if (missing.length > 0) {
|
|
189
|
+
throw new RagError('registry-corrupt', 'al registro le faltan tablas', { details: { missing } });
|
|
190
|
+
}
|
|
191
|
+
const check = db.prepare('PRAGMA quick_check').all();
|
|
192
|
+
if (check.length !== 1 || check[0].quick_check !== 'ok') {
|
|
193
|
+
throw new RagError('registry-corrupt', 'quick_check del registro falló', { details: { check } });
|
|
194
|
+
}
|
|
195
|
+
const chain = verifyRegistryAudit(db);
|
|
196
|
+
if (!chain.ok) {
|
|
197
|
+
throw new RagError('registry-corrupt', 'la cadena de auditoría del registro no verifica', { details: chain });
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export function closeRegistry(db) {
|
|
202
|
+
try {
|
|
203
|
+
db.close();
|
|
204
|
+
} catch {
|
|
205
|
+
// cerrar dos veces no es un fallo
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function requireName(name) {
|
|
210
|
+
if (typeof name !== 'string' || name.trim() === '' || name.trim().length > 120) {
|
|
211
|
+
throw new RagError('invalid-argument', 'el nombre debe tener entre 1 y 120 caracteres');
|
|
212
|
+
}
|
|
213
|
+
return name.trim();
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export function getMeta(db, key) {
|
|
217
|
+
const row = db.prepare('SELECT value FROM meta WHERE key = ?').get(key);
|
|
218
|
+
return row ? row.value : null;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
export function setMeta(db, key, value) {
|
|
222
|
+
db.prepare(`INSERT INTO meta (key, value) VALUES (?, ?)
|
|
223
|
+
ON CONFLICT(key) DO UPDATE SET value = excluded.value`).run(key, String(value));
|
|
224
|
+
return value;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
export function createProject(db, { name, now = Date.now() } = {}) {
|
|
228
|
+
const id = newId('prj_', now);
|
|
229
|
+
db.prepare(`INSERT INTO projects (id, name, status, created_at, updated_at) VALUES (?, ?, 'active', ?, ?)`)
|
|
230
|
+
.run(id, requireName(name), now, now);
|
|
231
|
+
return { id, name: name.trim(), createdAt: now };
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export function createLibrary(db, { name, now = Date.now() } = {}) {
|
|
235
|
+
const id = newId('lib_', now);
|
|
236
|
+
db.prepare(`INSERT INTO libraries (id, name, status, created_at, updated_at) VALUES (?, ?, 'active', ?, ?)`)
|
|
237
|
+
.run(id, requireName(name), now, now);
|
|
238
|
+
return { id, name: name.trim(), createdAt: now };
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Añade una raíz autorizada. La ruta debe ser absoluta y existir; la pertenencia al proyecto o
|
|
243
|
+
* biblioteca la valida el disparador del esquema.
|
|
244
|
+
*/
|
|
245
|
+
/**
|
|
246
|
+
* Añade una raíz autorizada. Desde PA4 la estructura se valida **antes** de escribir: la ruta debe
|
|
247
|
+
* existir, ser un directorio real (no enlace/junction/reparse) y no solaparse con ninguna raíz ya
|
|
248
|
+
* registrada, ni duplicarla. La pertenencia al proyecto o biblioteca la valida el disparador.
|
|
249
|
+
*/
|
|
250
|
+
export function addRoot(db, {
|
|
251
|
+
scopeKind, scopeId, path, addedBy = 'human', now = Date.now(), allowNested = false,
|
|
252
|
+
} = {}) {
|
|
253
|
+
if (!['prj', 'lib'].includes(scopeKind)) throw new RagError('invalid-argument', 'scopeKind inválido');
|
|
254
|
+
if (typeof scopeId !== 'string' || !scopeId.startsWith(scopeKind === 'prj' ? 'prj_' : 'lib_')) {
|
|
255
|
+
throw new RagError('invalid-argument', 'scopeId no corresponde al tipo de ámbito');
|
|
256
|
+
}
|
|
257
|
+
if (!['human', 'host'].includes(addedBy)) {
|
|
258
|
+
throw new RagError('invalid-argument', 'sólo una persona o el host pueden autorizar raíces');
|
|
259
|
+
}
|
|
260
|
+
if (typeof path !== 'string' || path.trim() === '' || !isAbsolute(path)) {
|
|
261
|
+
throw new RagError('invalid-argument', 'la raíz debe ser una ruta absoluta');
|
|
262
|
+
}
|
|
263
|
+
const info = assertRootStructure(inspectRoot(path));
|
|
264
|
+
const existing = listRoots(db);
|
|
265
|
+
const verdict = classifyRootRegistration({ key: info.key, path: info.canonical }, existing, { allowNested });
|
|
266
|
+
if (!verdict.ok) {
|
|
267
|
+
throw new RagError(verdict.code, verdict.message, {
|
|
268
|
+
details: {
|
|
269
|
+
path: info.canonical,
|
|
270
|
+
relation: verdict.conflict.relation,
|
|
271
|
+
conflictsWith: {
|
|
272
|
+
scopeKind: verdict.conflict.root.scope_kind,
|
|
273
|
+
scopeId: verdict.conflict.root.scope_id,
|
|
274
|
+
path: verdict.conflict.root.path,
|
|
275
|
+
},
|
|
276
|
+
},
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
const id = newId('rt_', now);
|
|
281
|
+
try {
|
|
282
|
+
db.prepare(`INSERT INTO roots (id, scope_kind, scope_id, path, path_key, state, added_at, added_by)
|
|
283
|
+
VALUES (?, ?, ?, ?, ?, 'authorized', ?, ?)`)
|
|
284
|
+
.run(id, scopeKind, scopeId, info.canonical, info.key, now, addedBy);
|
|
285
|
+
} catch (error) {
|
|
286
|
+
if (String(error.message).includes('UNIQUE') || String(error.message).includes('unique')) {
|
|
287
|
+
throw new RagError('invalid-argument', 'esa ruta ya está registrada en este perfil', {
|
|
288
|
+
details: { path: info.canonical },
|
|
289
|
+
cause: error,
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
throw error;
|
|
293
|
+
}
|
|
294
|
+
return { id, scopeKind, scopeId, path: info.canonical, pathKey: info.key };
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
export function getProject(db, id) {
|
|
298
|
+
return db.prepare('SELECT * FROM projects WHERE id = ?').get(id) ?? null;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
export function listRoots(db, { scopeKind, scopeId } = {}) {
|
|
302
|
+
if (scopeKind && scopeId) {
|
|
303
|
+
return db.prepare('SELECT * FROM roots WHERE scope_kind = ? AND scope_id = ? ORDER BY path').all(scopeKind, scopeId);
|
|
304
|
+
}
|
|
305
|
+
return db.prepare('SELECT * FROM roots ORDER BY path').all();
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/* ------------------------------------------------------------------ administración de proyectos
|
|
309
|
+
*
|
|
310
|
+
* ACP-07 F1. Las cinco operaciones son de **registro**, no de contenido: ninguna abre el almacén de
|
|
311
|
+
* ámbito (`scopes/<id>/rag.sqlite3`), así que archivar o quitar una raíz no puede tocar fuentes ni
|
|
312
|
+
* ficheros del usuario.
|
|
313
|
+
*
|
|
314
|
+
* Todas escriben dentro de una transacción `IMMEDIATE` (o reutilizan la del llamador, igual que
|
|
315
|
+
* `appendRegistryAudit`) y dejan su entrada en la cadena de auditoría del registro.
|
|
316
|
+
*/
|
|
317
|
+
|
|
318
|
+
/** Ejecuta `work` en una transacción sólo si el llamador no está ya dentro de una. */
|
|
319
|
+
function transactional(db, work) {
|
|
320
|
+
return db.isTransaction ? work() : withTransaction(db, work, { immediate: true });
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function requireActor(actor) {
|
|
324
|
+
if (!['human', 'host'].includes(actor)) {
|
|
325
|
+
throw new RagError('invalid-argument', 'sólo una persona o el host pueden administrar proyectos');
|
|
326
|
+
}
|
|
327
|
+
return actor;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/** Fila del proyecto o `project-not-found` (404). */
|
|
331
|
+
function requireProjectRow(db, id) {
|
|
332
|
+
if (typeof id !== 'string' || !id.startsWith('prj_')) {
|
|
333
|
+
throw new RagError('invalid-argument', 'id no es un identificador de proyecto', {
|
|
334
|
+
details: { reason: 'invalid-field', field: 'project' },
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
const row = db.prepare('SELECT * FROM projects WHERE id = ?').get(id);
|
|
338
|
+
if (!row) {
|
|
339
|
+
throw new RagError('project-not-found', 'el proyecto no existe en este perfil', { details: { project: id } });
|
|
340
|
+
}
|
|
341
|
+
return row;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
function projectRow(db, id) {
|
|
345
|
+
const row = db.prepare('SELECT * FROM projects WHERE id = ?').get(id);
|
|
346
|
+
return row
|
|
347
|
+
? {
|
|
348
|
+
id: row.id,
|
|
349
|
+
name: row.name,
|
|
350
|
+
status: row.status,
|
|
351
|
+
createdAt: Number(row.created_at),
|
|
352
|
+
updatedAt: Number(row.updated_at),
|
|
353
|
+
archivedAt: row.archived_at === null ? null : Number(row.archived_at),
|
|
354
|
+
}
|
|
355
|
+
: null;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/** Cambia el nombre de un proyecto. No toca raíces, selección ni almacenes. */
|
|
359
|
+
export function updateProject(db, { id, name, now = Date.now(), actor = 'human' } = {}) {
|
|
360
|
+
requireActor(actor);
|
|
361
|
+
const nextName = requireName(name);
|
|
362
|
+
return transactional(db, () => {
|
|
363
|
+
const before = requireProjectRow(db, id);
|
|
364
|
+
if (before.name === nextName) {
|
|
365
|
+
return { changed: false, project: projectRow(db, id) };
|
|
366
|
+
}
|
|
367
|
+
db.prepare('UPDATE projects SET name = ?, updated_at = ? WHERE id = ?').run(nextName, now, id);
|
|
368
|
+
appendRegistryAudit(db, {
|
|
369
|
+
at: now,
|
|
370
|
+
actor,
|
|
371
|
+
sessionId: null,
|
|
372
|
+
action: 'project.update',
|
|
373
|
+
target: id,
|
|
374
|
+
outcome: 'ok',
|
|
375
|
+
detail: { before: { name: before.name }, after: { name: nextName } },
|
|
376
|
+
});
|
|
377
|
+
return { changed: true, project: projectRow(db, id) };
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* Archiva un proyecto (eliminación lógica). No borra la fila, ni las raíces, ni el almacén del ámbito:
|
|
383
|
+
* sólo cambia `status` y `archived_at`, que el esquema obliga a mantener coherentes.
|
|
384
|
+
*
|
|
385
|
+
* Se niega si la selección del perfil apunta a este proyecto: mover o limpiar la selección es
|
|
386
|
+
* responsabilidad de `archiveProjectWithSelection` (lib/selection.mjs), que hace ambas cosas en una
|
|
387
|
+
* sola transacción. Así no puede quedar una selección colgando por llamar a la función suelta.
|
|
388
|
+
*/
|
|
389
|
+
export function archiveProject(db, { id, now = Date.now(), actor = 'human' } = {}) {
|
|
390
|
+
requireActor(actor);
|
|
391
|
+
return transactional(db, () => {
|
|
392
|
+
const row = requireProjectRow(db, id);
|
|
393
|
+
if (row.status === 'archived') {
|
|
394
|
+
return { changed: false, project: projectRow(db, id) };
|
|
395
|
+
}
|
|
396
|
+
const selected = db.prepare('SELECT project_id FROM pa_selection WHERE selection_key = ?').get('profile');
|
|
397
|
+
if (selected && selected.project_id === id) {
|
|
398
|
+
throw new RagError('invalid-argument', 'el proyecto está seleccionado: usa archiveProjectWithSelection', {
|
|
399
|
+
details: { reason: 'selection-attached', project: id },
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
db.prepare("UPDATE projects SET status = 'archived', archived_at = ?, updated_at = ? WHERE id = ?")
|
|
403
|
+
.run(now, now, id);
|
|
404
|
+
appendRegistryAudit(db, {
|
|
405
|
+
at: now,
|
|
406
|
+
actor,
|
|
407
|
+
sessionId: null,
|
|
408
|
+
action: 'project.archive',
|
|
409
|
+
target: id,
|
|
410
|
+
outcome: 'ok',
|
|
411
|
+
detail: { name: row.name, roots: db.prepare("SELECT COUNT(*) AS n FROM roots WHERE scope_kind='prj' AND scope_id = ?").get(id).n },
|
|
412
|
+
});
|
|
413
|
+
return { changed: true, project: projectRow(db, id) };
|
|
414
|
+
});
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/** Devuelve un proyecto archivado a `active`. Conserva identidad, raíces y referencias RAG. */
|
|
418
|
+
export function restoreProject(db, { id, now = Date.now(), actor = 'human' } = {}) {
|
|
419
|
+
requireActor(actor);
|
|
420
|
+
return transactional(db, () => {
|
|
421
|
+
const row = requireProjectRow(db, id);
|
|
422
|
+
if (row.status === 'active') {
|
|
423
|
+
return { changed: false, project: projectRow(db, id) };
|
|
424
|
+
}
|
|
425
|
+
db.prepare("UPDATE projects SET status = 'active', archived_at = NULL, updated_at = ? WHERE id = ?")
|
|
426
|
+
.run(now, id);
|
|
427
|
+
appendRegistryAudit(db, {
|
|
428
|
+
at: now,
|
|
429
|
+
actor,
|
|
430
|
+
sessionId: null,
|
|
431
|
+
action: 'project.restore',
|
|
432
|
+
target: id,
|
|
433
|
+
outcome: 'ok',
|
|
434
|
+
detail: { name: row.name, archivedAt: row.archived_at === null ? null : Number(row.archived_at) },
|
|
435
|
+
});
|
|
436
|
+
return { changed: true, project: projectRow(db, id) };
|
|
437
|
+
});
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/**
|
|
441
|
+
* Quita una raíz del registro. Sólo borra la fila: no toca ficheros del usuario ni fuentes RAG.
|
|
442
|
+
*
|
|
443
|
+
* Guarda: no deja un proyecto activo sin ninguna raíz salvo `allowEmpty`, porque a partir de ahí sus
|
|
444
|
+
* herramientas dejarían de resolver sin un motivo evidente.
|
|
445
|
+
*/
|
|
446
|
+
export function removeRoot(db, { rootId, allowEmpty = false, now = Date.now(), actor = 'human' } = {}) {
|
|
447
|
+
requireActor(actor);
|
|
448
|
+
return transactional(db, () => {
|
|
449
|
+
const row = typeof rootId === 'string'
|
|
450
|
+
? db.prepare('SELECT * FROM roots WHERE id = ?').get(rootId)
|
|
451
|
+
: null;
|
|
452
|
+
if (!row) {
|
|
453
|
+
throw new RagError('source-not-found', 'la raíz no existe en este perfil', {
|
|
454
|
+
details: { root: typeof rootId === 'string' ? rootId : null },
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
const siblings = db.prepare('SELECT COUNT(*) AS n FROM roots WHERE scope_kind = ? AND scope_id = ?')
|
|
458
|
+
.get(row.scope_kind, row.scope_id).n;
|
|
459
|
+
if (siblings <= 1 && !allowEmpty) {
|
|
460
|
+
throw new RagError('invalid-argument', 'es la última raíz del ámbito: pide allowEmpty para dejarlo sin raíces', {
|
|
461
|
+
details: { reason: 'last-root', scopeId: row.scope_id, path: row.path },
|
|
462
|
+
});
|
|
463
|
+
}
|
|
464
|
+
db.prepare('DELETE FROM roots WHERE id = ?').run(row.id);
|
|
465
|
+
appendRegistryAudit(db, {
|
|
466
|
+
at: now,
|
|
467
|
+
actor,
|
|
468
|
+
sessionId: null,
|
|
469
|
+
action: 'root.remove',
|
|
470
|
+
target: row.id,
|
|
471
|
+
outcome: 'ok',
|
|
472
|
+
detail: { scopeKind: row.scope_kind, scopeId: row.scope_id, path: row.path },
|
|
473
|
+
});
|
|
474
|
+
return { removed: { id: row.id, scopeKind: row.scope_kind, scopeId: row.scope_id, path: row.path } };
|
|
475
|
+
});
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/**
|
|
479
|
+
* Listado de proyectos con su estado y el recuento de raíces. Es la consulta que comparten la CLI y
|
|
480
|
+
* la API del panel; no depende del descubrimiento, así que un proyecto registrado sigue apareciendo
|
|
481
|
+
* aunque su carpeta ya no se descubra.
|
|
482
|
+
*/
|
|
483
|
+
export function listProjects(db, { status = 'active' } = {}) {
|
|
484
|
+
if (status !== 'active' && status !== 'archived' && status !== 'all') {
|
|
485
|
+
throw new RagError('invalid-argument', 'status debe ser active, archived o all', { details: { status } });
|
|
486
|
+
}
|
|
487
|
+
const rows = status === 'all'
|
|
488
|
+
? db.prepare('SELECT * FROM projects ORDER BY created_at, id').all()
|
|
489
|
+
: db.prepare('SELECT * FROM projects WHERE status = ? ORDER BY created_at, id').all(status);
|
|
490
|
+
const counts = new Map(
|
|
491
|
+
db.prepare(`SELECT scope_id, COUNT(*) AS total, SUM(state = 'authorized') AS authorized
|
|
492
|
+
FROM roots WHERE scope_kind = 'prj' GROUP BY scope_id`).all()
|
|
493
|
+
.map((row) => [row.scope_id, { total: Number(row.total), authorized: Number(row.authorized ?? 0) }]),
|
|
494
|
+
);
|
|
495
|
+
return {
|
|
496
|
+
projects: rows.map((row) => ({
|
|
497
|
+
id: row.id,
|
|
498
|
+
name: row.name,
|
|
499
|
+
status: row.status,
|
|
500
|
+
createdAt: Number(row.created_at),
|
|
501
|
+
updatedAt: Number(row.updated_at),
|
|
502
|
+
archivedAt: row.archived_at === null ? null : Number(row.archived_at),
|
|
503
|
+
roots: counts.get(row.id) ?? { total: 0, authorized: 0 },
|
|
504
|
+
})),
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
function registryAuditPayload(entry) {
|
|
509
|
+
return {
|
|
510
|
+
at: Number(entry.at),
|
|
511
|
+
actor: entry.actor,
|
|
512
|
+
sessionId: entry.sessionId ?? null,
|
|
513
|
+
action: entry.action,
|
|
514
|
+
target: entry.target,
|
|
515
|
+
outcome: entry.outcome,
|
|
516
|
+
detail: normalizeDetail(entry.detail),
|
|
517
|
+
};
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
/**
|
|
521
|
+
* El detalle se guarda siempre como texto JSON: así el hash es estable y no depende de que cada
|
|
522
|
+
* llamador se acuerde de serializar (un objeto pasado crudo rompía el enlace de SQLite).
|
|
523
|
+
*/
|
|
524
|
+
function normalizeDetail(detail) {
|
|
525
|
+
if (detail === undefined || detail === null) return null;
|
|
526
|
+
return typeof detail === 'string' ? detail : JSON.stringify(detail);
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
export function registryAuditHash(prevHash, entry) {
|
|
530
|
+
return createHash('sha256').update(`${prevHash}\n${canonicalJson(registryAuditPayload(entry))}`, 'utf8').digest('hex');
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
/**
|
|
534
|
+
* Añade una entrada a la cadena de auditoría del registro.
|
|
535
|
+
*
|
|
536
|
+
* La lectura de la cabeza, el cálculo del hash, el `INSERT` y la actualización de `meta` van en la
|
|
537
|
+
* MISMA transacción `IMMEDIATE`: dos conexiones del perfil (host y CLI, por ejemplo) se serializan y
|
|
538
|
+
* la cadena no puede quedar con un `prev_hash` que no cuadre —lo que dejaría el perfil entero
|
|
539
|
+
* inservible, porque `assertRegistry` verifica la cadena al abrir—. Si el llamador ya está en una
|
|
540
|
+
* transacción se reutiliza esa: abrir otra dentro fallaría.
|
|
541
|
+
*/
|
|
542
|
+
export function appendRegistryAudit(db, entry) {
|
|
543
|
+
const append = () => {
|
|
544
|
+
const head = Number(db.prepare(`SELECT value FROM meta WHERE key='audit_head_seq'`).get()?.value ?? '0');
|
|
545
|
+
let prevHash = '0'.repeat(64);
|
|
546
|
+
if (head > 0) {
|
|
547
|
+
const row = db.prepare('SELECT hash FROM audit_registry WHERE seq = ?').get(head);
|
|
548
|
+
if (!row) throw new RagError('registry-corrupt', `falta la entrada de auditoría del registro ${head}`);
|
|
549
|
+
prevHash = row.hash;
|
|
550
|
+
}
|
|
551
|
+
const payload = registryAuditPayload(entry);
|
|
552
|
+
const hash = registryAuditHash(prevHash, payload);
|
|
553
|
+
const info = db.prepare(`INSERT INTO audit_registry (at, actor, session_id, action, target, outcome, detail, prev_hash, hash)
|
|
554
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(
|
|
555
|
+
payload.at, payload.actor, payload.sessionId, payload.action, payload.target,
|
|
556
|
+
payload.outcome, payload.detail, prevHash, hash,
|
|
557
|
+
);
|
|
558
|
+
const seq = Number(info.lastInsertRowid);
|
|
559
|
+
db.prepare(`UPDATE meta SET value=? WHERE key='audit_head_seq'`).run(String(seq));
|
|
560
|
+
db.prepare(`UPDATE meta SET value=? WHERE key='audit_head_hash'`).run(hash);
|
|
561
|
+
return { seq, hash };
|
|
562
|
+
};
|
|
563
|
+
return db.isTransaction ? append() : withTransaction(db, append, { immediate: true });
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
export function verifyRegistryAudit(db) {
|
|
567
|
+
const rows = db.prepare(`SELECT seq, at, actor, session_id, action, target, outcome, detail, prev_hash, hash
|
|
568
|
+
FROM audit_registry ORDER BY seq ASC`).all();
|
|
569
|
+
let prevHash = '0'.repeat(64);
|
|
570
|
+
for (const row of rows) {
|
|
571
|
+
if (row.prev_hash !== prevHash) return { ok: false, brokenAt: row.seq, reason: 'prev-hash' };
|
|
572
|
+
const expected = registryAuditHash(prevHash, {
|
|
573
|
+
at: row.at,
|
|
574
|
+
actor: row.actor,
|
|
575
|
+
sessionId: row.session_id,
|
|
576
|
+
action: row.action,
|
|
577
|
+
target: row.target,
|
|
578
|
+
outcome: row.outcome,
|
|
579
|
+
detail: row.detail,
|
|
580
|
+
});
|
|
581
|
+
if (expected !== row.hash) return { ok: false, brokenAt: row.seq, reason: 'hash' };
|
|
582
|
+
prevHash = row.hash;
|
|
583
|
+
}
|
|
584
|
+
const head = Number(db.prepare(`SELECT value FROM meta WHERE key='audit_head_seq'`).get()?.value ?? '0');
|
|
585
|
+
if (head !== rows.length) return { ok: false, brokenAt: head, reason: 'head' };
|
|
586
|
+
return { ok: true, count: rows.length };
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
/** Comprobación de integridad completa (usada por el informe y las pruebas). */
|
|
590
|
+
export function registryIntegrity(db) {
|
|
591
|
+
const foreign = db.prepare('PRAGMA foreign_key_check').all();
|
|
592
|
+
const roots = listRoots(db);
|
|
593
|
+
const rootConflicts = findRootConflicts(roots);
|
|
594
|
+
return {
|
|
595
|
+
quickCheck: db.prepare('PRAGMA quick_check').all().map((row) => row.quick_check).join(','),
|
|
596
|
+
foreignKeys: foreign.length,
|
|
597
|
+
tables: registryTables(db).length,
|
|
598
|
+
roots: roots.length,
|
|
599
|
+
rootConflicts: rootConflicts.map(({ left, right, relation }) => ({
|
|
600
|
+
relation,
|
|
601
|
+
left: { scopeKind: left.scope_kind, scopeId: left.scope_id, path: left.path },
|
|
602
|
+
right: { scopeKind: right.scope_kind, scopeId: right.scope_id, path: right.path },
|
|
603
|
+
})),
|
|
604
|
+
audit: verifyRegistryAudit(db),
|
|
605
|
+
};
|
|
606
|
+
}
|