@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/sessions.mjs
ADDED
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Selección de ámbitos por sesión (PA2.2/PA2.3/PA2.5) sobre `session_scope` del registro PA1.
|
|
3
|
+
*
|
|
4
|
+
* Reglas que este módulo mantiene:
|
|
5
|
+
* - Una fila de `session_scope` **es** una selección explícita; su ausencia es una sesión sin
|
|
6
|
+
* selección (no un error). El contrato de sesión prohíbe inventar un proyecto por defecto.
|
|
7
|
+
* - Las sesiones terminales (`expired`, `invalidated`) no se reactivan: volver a seleccionar en
|
|
8
|
+
* ellas falla en cerrado.
|
|
9
|
+
* - Los grants los crea una persona o el host (`granted_by`), nunca el modelo; el límite de
|
|
10
|
+
* siete bibliotecas (ocho ámbitos con el proyecto) se comprueba antes de insertar.
|
|
11
|
+
* - Toda escritura se audita en la cadena del registro, en la misma transacción.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { RagError } from './errors.mjs';
|
|
15
|
+
import { appendRegistryAudit } from './registry.mjs';
|
|
16
|
+
import { assertProfile, assertSessionId } from './session-identity.mjs';
|
|
17
|
+
|
|
18
|
+
export const MAX_LIBRARIES_PER_PROJECT = 7;
|
|
19
|
+
export const MAX_SCOPES_PER_SELECTION = 8;
|
|
20
|
+
|
|
21
|
+
const SESSION_STATES = Object.freeze(['active', 'expired', 'invalidated']);
|
|
22
|
+
const INVALID_REASONS = Object.freeze([
|
|
23
|
+
'project-archived', 'grant-revoked', 'root-revoked', 'profile-changed', 'admin', 'session-cloned',
|
|
24
|
+
]);
|
|
25
|
+
|
|
26
|
+
function audit(db, entry) {
|
|
27
|
+
return appendRegistryAudit(db, {
|
|
28
|
+
at: entry.now,
|
|
29
|
+
actor: entry.actor ?? 'host',
|
|
30
|
+
sessionId: entry.sessionId ?? null,
|
|
31
|
+
action: entry.action,
|
|
32
|
+
target: entry.target,
|
|
33
|
+
outcome: entry.outcome ?? 'ok',
|
|
34
|
+
detail: entry.detail === undefined ? null : JSON.stringify(entry.detail),
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function getSession(db, sessionId) {
|
|
39
|
+
assertSessionId(sessionId);
|
|
40
|
+
return db.prepare('SELECT * FROM session_scope WHERE session_id = ?').get(sessionId) ?? null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function listSessions(db, { state } = {}) {
|
|
44
|
+
if (state !== undefined && !SESSION_STATES.includes(state)) {
|
|
45
|
+
throw new RagError('invalid-argument', 'estado de sesión inválido', { details: { state } });
|
|
46
|
+
}
|
|
47
|
+
return state
|
|
48
|
+
? db.prepare('SELECT * FROM session_scope WHERE state = ? ORDER BY session_id').all(state)
|
|
49
|
+
: db.prepare('SELECT * FROM session_scope ORDER BY session_id').all();
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function requireProject(db, projectId) {
|
|
53
|
+
const project = db.prepare('SELECT * FROM projects WHERE id = ?').get(projectId);
|
|
54
|
+
if (!project) throw new RagError('scope-forbidden', 'el proyecto no existe en este perfil', {
|
|
55
|
+
details: { reason: 'project-missing', project_id: projectId },
|
|
56
|
+
});
|
|
57
|
+
if (project.status !== 'active') throw new RagError('scope-forbidden', 'el proyecto está archivado', {
|
|
58
|
+
details: { reason: 'project-archived', project_id: projectId },
|
|
59
|
+
});
|
|
60
|
+
return project;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Registra la selección explícita de una sesión. Es idempotente: repetir la misma selección no
|
|
65
|
+
* crea una revisión nueva ni reescribe la marca de tiempo.
|
|
66
|
+
*/
|
|
67
|
+
export function registerSelection(db, {
|
|
68
|
+
identity,
|
|
69
|
+
expectedProfileKey,
|
|
70
|
+
projectId,
|
|
71
|
+
selectedBy = 'human',
|
|
72
|
+
source = 'explicit',
|
|
73
|
+
cwd = null,
|
|
74
|
+
cloneOf = null,
|
|
75
|
+
actor = null,
|
|
76
|
+
now = Date.now(),
|
|
77
|
+
} = {}) {
|
|
78
|
+
const sessionId = assertProfile(identity, expectedProfileKey);
|
|
79
|
+
if (!['human', 'host'].includes(selectedBy)) {
|
|
80
|
+
throw new RagError('invalid-argument', 'sólo una persona o el host pueden seleccionar proyecto');
|
|
81
|
+
}
|
|
82
|
+
if (!['explicit', 'cwd'].includes(source)) {
|
|
83
|
+
throw new RagError('invalid-argument', 'origen de selección inválido', { details: { source } });
|
|
84
|
+
}
|
|
85
|
+
if (typeof projectId !== 'string' || !projectId.startsWith('prj_')) {
|
|
86
|
+
throw new RagError('invalid-argument', 'projectId no es un identificador de proyecto');
|
|
87
|
+
}
|
|
88
|
+
requireProject(db, projectId);
|
|
89
|
+
|
|
90
|
+
const existing = getSession(db, sessionId);
|
|
91
|
+
if (existing) {
|
|
92
|
+
if (existing.state === 'expired') {
|
|
93
|
+
throw new RagError('session-expired', 'la sesión está terminada', {
|
|
94
|
+
details: { session_id: sessionId, expires_at: existing.expires_at },
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
if (existing.state === 'invalidated') {
|
|
98
|
+
throw new RagError('scope-forbidden', 'la selección de la sesión fue invalidada', {
|
|
99
|
+
details: { session_id: sessionId, reason: existing.invalid_reason },
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
if (existing && existing.project_id === projectId && existing.selection_source === source) {
|
|
105
|
+
return {
|
|
106
|
+
created: false, changed: false, selection: existing,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const write = actor ?? selectedBy;
|
|
111
|
+
db.exec('BEGIN IMMEDIATE');
|
|
112
|
+
try {
|
|
113
|
+
let selection;
|
|
114
|
+
if (existing) {
|
|
115
|
+
db.prepare(`UPDATE session_scope
|
|
116
|
+
SET project_id=?, selection_source=?, selected_by=?, updated_at=?, cwd=?, revision=revision+1
|
|
117
|
+
WHERE session_id=?`)
|
|
118
|
+
.run(projectId, source, selectedBy, now, cwd, sessionId);
|
|
119
|
+
selection = getSession(db, sessionId);
|
|
120
|
+
audit(db, {
|
|
121
|
+
now, actor: write, sessionId, action: 'session.reselect', target: projectId,
|
|
122
|
+
detail: { project_id: projectId, revision: selection.revision },
|
|
123
|
+
});
|
|
124
|
+
} else {
|
|
125
|
+
db.prepare(`INSERT INTO session_scope
|
|
126
|
+
(session_id, project_id, state, selection_source, selected_by, selected_at, updated_at, cwd, clone_of, revision)
|
|
127
|
+
VALUES (?, ?, 'active', ?, ?, ?, ?, ?, ?, 1)`)
|
|
128
|
+
.run(sessionId, projectId, source, selectedBy, now, now, cwd, cloneOf);
|
|
129
|
+
selection = getSession(db, sessionId);
|
|
130
|
+
audit(db, {
|
|
131
|
+
now, actor: write, sessionId, action: 'session.select', target: projectId,
|
|
132
|
+
detail: { project_id: projectId, revision: 1, clone_of: cloneOf ?? null },
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
db.exec('COMMIT');
|
|
136
|
+
return { created: !existing, changed: true, selection };
|
|
137
|
+
} catch (error) {
|
|
138
|
+
db.exec('ROLLBACK');
|
|
139
|
+
throw error;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Terminación normal: conserva la fila para auditoría y prohíbe reactivarla. */
|
|
144
|
+
export function expireSession(db, { identity, expectedProfileKey, actor = 'host', now = Date.now() } = {}) {
|
|
145
|
+
const sessionId = assertProfile(identity, expectedProfileKey);
|
|
146
|
+
const existing = getSession(db, sessionId);
|
|
147
|
+
if (!existing) return { changed: false };
|
|
148
|
+
if (existing.state !== 'active') return { changed: false, state: existing.state };
|
|
149
|
+
db.exec('BEGIN IMMEDIATE');
|
|
150
|
+
try {
|
|
151
|
+
db.prepare(`UPDATE session_scope SET state='expired', expires_at=?, updated_at=? WHERE session_id=?`)
|
|
152
|
+
.run(now, now, sessionId);
|
|
153
|
+
audit(db, { now, actor, sessionId, action: 'session.terminate', target: sessionId, detail: { state: 'expired' } });
|
|
154
|
+
db.exec('COMMIT');
|
|
155
|
+
return { changed: true, state: 'expired' };
|
|
156
|
+
} catch (error) {
|
|
157
|
+
db.exec('ROLLBACK');
|
|
158
|
+
throw error;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Invalida una selección por una causa del contrato; nunca la reutiliza. */
|
|
163
|
+
export function invalidateSession(db, {
|
|
164
|
+
identity, expectedProfileKey, reason, actor = 'host', now = Date.now(),
|
|
165
|
+
} = {}) {
|
|
166
|
+
const sessionId = assertProfile(identity, expectedProfileKey);
|
|
167
|
+
if (!INVALID_REASONS.includes(reason)) {
|
|
168
|
+
throw new RagError('invalid-argument', 'motivo de invalidación inválido', { details: { reason } });
|
|
169
|
+
}
|
|
170
|
+
const existing = getSession(db, sessionId);
|
|
171
|
+
if (!existing) return { changed: false };
|
|
172
|
+
if (existing.state !== 'active') return { changed: false, state: existing.state };
|
|
173
|
+
db.exec('BEGIN IMMEDIATE');
|
|
174
|
+
try {
|
|
175
|
+
db.prepare(`UPDATE session_scope
|
|
176
|
+
SET state='invalidated', invalidated_at=?, invalid_reason=?, updated_at=? WHERE session_id=?`)
|
|
177
|
+
.run(now, reason, now, sessionId);
|
|
178
|
+
audit(db, {
|
|
179
|
+
now, actor, sessionId, action: 'session.invalidate', target: sessionId,
|
|
180
|
+
detail: { reason },
|
|
181
|
+
});
|
|
182
|
+
db.exec('COMMIT');
|
|
183
|
+
return { changed: true, state: 'invalidated', reason };
|
|
184
|
+
} catch (error) {
|
|
185
|
+
db.exec('ROLLBACK');
|
|
186
|
+
throw error;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Sesiones huérfanas: filas activas cuyo `SessionId` ya no está entre las sesiones vivas del host.
|
|
192
|
+
* Se terminan (no se invalidan): la causa es la desaparición de la sesión, no un permiso revocado.
|
|
193
|
+
*/
|
|
194
|
+
export function markOrphans(db, { activeSessionIds, now = Date.now() } = {}) {
|
|
195
|
+
if (!Array.isArray(activeSessionIds)) {
|
|
196
|
+
throw new RagError('invalid-argument', 'activeSessionIds debe ser una lista');
|
|
197
|
+
}
|
|
198
|
+
const active = new Set(activeSessionIds);
|
|
199
|
+
const rows = db.prepare(`SELECT session_id FROM session_scope WHERE state='active' ORDER BY session_id`).all();
|
|
200
|
+
const orphans = rows.map((row) => row.session_id).filter((id) => !active.has(id));
|
|
201
|
+
let changed = 0;
|
|
202
|
+
for (const sessionId of orphans) {
|
|
203
|
+
db.exec('BEGIN IMMEDIATE');
|
|
204
|
+
try {
|
|
205
|
+
db.prepare(`UPDATE session_scope SET state='expired', expires_at=?, updated_at=? WHERE session_id=? AND state='active'`)
|
|
206
|
+
.run(now, now, sessionId);
|
|
207
|
+
audit(db, {
|
|
208
|
+
now, actor: 'host', sessionId, action: 'session.orphan', target: sessionId,
|
|
209
|
+
detail: { state: 'expired' },
|
|
210
|
+
});
|
|
211
|
+
db.exec('COMMIT');
|
|
212
|
+
changed += 1;
|
|
213
|
+
} catch (error) {
|
|
214
|
+
db.exec('ROLLBACK');
|
|
215
|
+
throw error;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
return { changed, orphans };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
export function grantLibrary(db, {
|
|
222
|
+
projectId, libraryId, grantedBy = 'human', actor = null, now = Date.now(),
|
|
223
|
+
} = {}) {
|
|
224
|
+
if (!['human', 'host'].includes(grantedBy)) {
|
|
225
|
+
throw new RagError('invalid-argument', 'sólo una persona o el host pueden conceder bibliotecas');
|
|
226
|
+
}
|
|
227
|
+
requireProject(db, projectId);
|
|
228
|
+
const library = db.prepare('SELECT * FROM libraries WHERE id = ?').get(libraryId);
|
|
229
|
+
if (!library) throw new RagError('scope-forbidden', 'la biblioteca no existe en este perfil', {
|
|
230
|
+
details: { reason: 'library-missing', library_id: libraryId },
|
|
231
|
+
});
|
|
232
|
+
if (library.status !== 'active') throw new RagError('scope-forbidden', 'la biblioteca está archivada', {
|
|
233
|
+
details: { reason: 'library-archived', library_id: libraryId },
|
|
234
|
+
});
|
|
235
|
+
const open = db.prepare('SELECT * FROM grants WHERE project_id=? AND library_id=? AND revoked_at IS NULL')
|
|
236
|
+
.get(projectId, libraryId);
|
|
237
|
+
if (open) return { created: false, grant: open };
|
|
238
|
+
const count = Number(db.prepare('SELECT COUNT(*) AS n FROM grants WHERE project_id=? AND revoked_at IS NULL')
|
|
239
|
+
.get(projectId).n);
|
|
240
|
+
if (count >= MAX_LIBRARIES_PER_PROJECT) {
|
|
241
|
+
throw new RagError('scope-too-many', 'el proyecto ya tiene el máximo de bibliotecas concedidas', {
|
|
242
|
+
details: {
|
|
243
|
+
project_id: projectId, libraries: count, limit: MAX_LIBRARIES_PER_PROJECT, scopes_limit: MAX_SCOPES_PER_SELECTION,
|
|
244
|
+
},
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
db.exec('BEGIN IMMEDIATE');
|
|
248
|
+
try {
|
|
249
|
+
const info = db.prepare(`INSERT INTO grants (project_id, library_id, permission, granted_at, granted_by)
|
|
250
|
+
VALUES (?, ?, 'read', ?, ?)`).run(projectId, libraryId, now, grantedBy);
|
|
251
|
+
const grantId = Number(info.lastInsertRowid);
|
|
252
|
+
audit(db, {
|
|
253
|
+
now, actor: actor ?? grantedBy, action: 'grant.create', target: libraryId,
|
|
254
|
+
detail: { project_id: projectId, library_id: libraryId, grant_id: grantId },
|
|
255
|
+
});
|
|
256
|
+
db.exec('COMMIT');
|
|
257
|
+
return { created: true, grant: { id: grantId, project_id: projectId, library_id: libraryId } };
|
|
258
|
+
} catch (error) {
|
|
259
|
+
db.exec('ROLLBACK');
|
|
260
|
+
throw error;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
export function revokeGrant(db, {
|
|
265
|
+
projectId, libraryId, revokedBy = 'human', actor = null, now = Date.now(),
|
|
266
|
+
} = {}) {
|
|
267
|
+
if (!['human', 'host'].includes(revokedBy)) {
|
|
268
|
+
throw new RagError('invalid-argument', 'sólo una persona o el host pueden revocar bibliotecas');
|
|
269
|
+
}
|
|
270
|
+
const open = db.prepare('SELECT * FROM grants WHERE project_id=? AND library_id=? AND revoked_at IS NULL')
|
|
271
|
+
.get(projectId, libraryId);
|
|
272
|
+
if (!open) return { changed: false };
|
|
273
|
+
db.exec('BEGIN IMMEDIATE');
|
|
274
|
+
try {
|
|
275
|
+
db.prepare('UPDATE grants SET revoked_at=?, revoked_by=? WHERE id=?').run(now, revokedBy, open.id);
|
|
276
|
+
audit(db, {
|
|
277
|
+
now, actor: actor ?? revokedBy, action: 'grant.revoke', target: libraryId,
|
|
278
|
+
detail: { project_id: projectId, library_id: libraryId, grant_id: open.id },
|
|
279
|
+
});
|
|
280
|
+
db.exec('COMMIT');
|
|
281
|
+
return { changed: true };
|
|
282
|
+
} catch (error) {
|
|
283
|
+
db.exec('ROLLBACK');
|
|
284
|
+
throw error;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* Ámbitos efectivos de una selección activa: el proyecto y sus bibliotecas concedidas y activas.
|
|
290
|
+
* Aplica el límite de ocho ámbitos sin truncar: si se supera, falla.
|
|
291
|
+
*/
|
|
292
|
+
export function effectiveScopes(db, { identity, expectedProfileKey } = {}) {
|
|
293
|
+
const sessionId = assertProfile(identity, expectedProfileKey);
|
|
294
|
+
const session = getSession(db, sessionId);
|
|
295
|
+
if (!session) {
|
|
296
|
+
throw new RagError('scope-unresolved', 'la sesión no tiene selección', {
|
|
297
|
+
details: { session_id: sessionId },
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
if (session.state === 'expired') {
|
|
301
|
+
throw new RagError('session-expired', 'la sesión está terminada', {
|
|
302
|
+
details: { session_id: sessionId },
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
if (session.state === 'invalidated') {
|
|
306
|
+
throw new RagError('scope-forbidden', 'la selección de la sesión fue invalidada', {
|
|
307
|
+
details: { session_id: sessionId, reason: session.invalid_reason },
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
const project = requireProject(db, session.project_id);
|
|
311
|
+
const libraries = db.prepare(`SELECT l.* FROM grants g
|
|
312
|
+
JOIN libraries l ON l.id = g.library_id
|
|
313
|
+
WHERE g.project_id = ? AND g.revoked_at IS NULL AND l.status = 'active'
|
|
314
|
+
ORDER BY l.name, l.id`).all(project.id);
|
|
315
|
+
if (libraries.length > MAX_LIBRARIES_PER_PROJECT) {
|
|
316
|
+
throw new RagError('scope-too-many', 'la selección supera el máximo de bibliotecas', {
|
|
317
|
+
details: {
|
|
318
|
+
project_id: project.id,
|
|
319
|
+
libraries: libraries.map((library) => library.id),
|
|
320
|
+
limit: MAX_LIBRARIES_PER_PROJECT,
|
|
321
|
+
},
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const rootsOf = (scopeKind, scopeId) => db.prepare(
|
|
326
|
+
`SELECT id, path, path_key FROM roots WHERE scope_kind=? AND scope_id=? AND state='authorized' ORDER BY path`,
|
|
327
|
+
).all(scopeKind, scopeId);
|
|
328
|
+
|
|
329
|
+
const projectRoots = rootsOf('prj', project.id);
|
|
330
|
+
const scopes = [
|
|
331
|
+
{ kind: 'prj', id: project.id, name: project.name, roots: projectRoots },
|
|
332
|
+
...libraries.map((library) => ({
|
|
333
|
+
kind: 'lib', id: library.id, name: library.name, roots: rootsOf('lib', library.id),
|
|
334
|
+
})),
|
|
335
|
+
];
|
|
336
|
+
const scopeCount = scopes.length;
|
|
337
|
+
if (scopeCount > MAX_SCOPES_PER_SELECTION) {
|
|
338
|
+
throw new RagError('scope-too-many', 'la selección supera el máximo de ámbitos', {
|
|
339
|
+
details: { project_id: project.id, scopes: scopes.map((scope) => scope.id), limit: MAX_SCOPES_PER_SELECTION },
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
return { session, project, scopes, scopeCount };
|
|
343
|
+
}
|
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Programación de la sincronización (PA5 · endurecido en M6.7).
|
|
3
|
+
*
|
|
4
|
+
* El motor (`syncScope`) no sabe nada de relojes; este módulo sólo lo llama. La programación se
|
|
5
|
+
* inyecta: el host pasa `ctx.timer.interval` (devuelve un disposer y muere con el plugin) y fuera del
|
|
6
|
+
* host se usa `setInterval` de Node. Dentro del host NO se cae al temporizador global: si el servicio
|
|
7
|
+
* no está, el programador se declara no iniciado (`no-timer`) en vez de crear un intervalo invisible
|
|
8
|
+
* que nadie va a poder cerrar.
|
|
9
|
+
*
|
|
10
|
+
* Garantías (verificadas en `tests/sync-scheduler.test.mjs`):
|
|
11
|
+
* - Activación única: `start()` dos veces no crea un segundo temporizador.
|
|
12
|
+
* - Una pasada nunca se solapa con otra (`running`); los ticks que llegan durante una pasada se
|
|
13
|
+
* cuentan (`skippedTicks`) y no se encolan, así que no hay trabajo pendiente ilimitado.
|
|
14
|
+
* - Cada tick lleva presupuesto de tiempo y límite de ficheros; una pasada que los alcanza termina
|
|
15
|
+
* como parcial (no como fallo) y el resto queda para el tick siguiente.
|
|
16
|
+
* - Un fallo no detiene el temporizador ni propaga al host: se registra, se audita y se reintenta con
|
|
17
|
+
* espera creciente (factor 1, 2, 4, 8 como máximo).
|
|
18
|
+
* - `stop()` cierra el disposer y aborta la pasada en curso: el teardown del plugin no deja trabajo
|
|
19
|
+
* escribiendo por detrás, y no se aceptan ticks después del cierre.
|
|
20
|
+
* - Sin registro Project-Aware no hay nada que sincronizar: el tick se salta sin ruido y sin error.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import { existsSync } from 'node:fs';
|
|
24
|
+
import { workerConfig } from './worker-context.mjs';
|
|
25
|
+
import { loadConfig } from './paths.mjs';
|
|
26
|
+
import { profileKey, profileRoot, registryPath } from './profile.mjs';
|
|
27
|
+
import { appendRegistryAudit, closeRegistry, openRegistry } from './registry.mjs';
|
|
28
|
+
import { activeSyncScopes, syncScopes } from './sync.mjs';
|
|
29
|
+
|
|
30
|
+
const state = new WeakMap();
|
|
31
|
+
const MAX_BACKOFF_FACTOR = 8;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Enumeración de ámbitos sincronizables: proyectos activos y bibliotecas activas, cada uno con sus
|
|
35
|
+
* raíces autorizadas. Un ámbito sin raíces no se sincroniza (y no es un error: puede estar vacío).
|
|
36
|
+
*/
|
|
37
|
+
export function listSyncScopes(registryDb) {
|
|
38
|
+
return activeSyncScopes(registryDb);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Temporizador por defecto: el de Node. Devuelve un disposer, igual que `ctx.timer.interval`.
|
|
43
|
+
*/
|
|
44
|
+
function nodeInterval(callback, delay) {
|
|
45
|
+
const handle = setInterval(callback, delay);
|
|
46
|
+
handle.unref?.();
|
|
47
|
+
return () => clearInterval(handle);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* @param {object} [options]
|
|
52
|
+
* @param {(callback: () => void, delay: number) => (() => void)} [options.interval]
|
|
53
|
+
* Temporizador del host (`ctx.timer.interval`). Si no se pasa, se usa el de Node.
|
|
54
|
+
*/
|
|
55
|
+
export function createSyncScheduler({
|
|
56
|
+
env = process.env,
|
|
57
|
+
root = profileRoot(env),
|
|
58
|
+
now = () => Date.now(),
|
|
59
|
+
monotonic = null,
|
|
60
|
+
logger = console,
|
|
61
|
+
embedder = null,
|
|
62
|
+
interval = null,
|
|
63
|
+
config = null,
|
|
64
|
+
dataRoot = null,
|
|
65
|
+
} = {}) {
|
|
66
|
+
const schedule = typeof interval === 'function' ? interval : nodeInterval;
|
|
67
|
+
const usingHostTimer = typeof interval === 'function';
|
|
68
|
+
const registryFile = registryPath(root);
|
|
69
|
+
let disposeTimer = null;
|
|
70
|
+
let controller = null;
|
|
71
|
+
let running = false;
|
|
72
|
+
let nextAttemptAt = 0;
|
|
73
|
+
const status = {
|
|
74
|
+
enabled: false,
|
|
75
|
+
running: false,
|
|
76
|
+
lastTickAt: null,
|
|
77
|
+
lastRunAt: null,
|
|
78
|
+
lastResult: null,
|
|
79
|
+
lastError: null,
|
|
80
|
+
consecutiveFailures: 0,
|
|
81
|
+
intervalMs: null,
|
|
82
|
+
// Diagnóstico del ciclo de vida (M6.7 §7): cuántas veces se pidió una pasada, cuántas no cabía y
|
|
83
|
+
// cuántas veces se ha (re)programado el temporizador.
|
|
84
|
+
ticks: 0,
|
|
85
|
+
skippedTicks: 0,
|
|
86
|
+
lastSkippedAt: null,
|
|
87
|
+
lastSkipReason: null,
|
|
88
|
+
starts: 0,
|
|
89
|
+
stops: 0,
|
|
90
|
+
timerType: usingHostTimer ? 'host' : 'node',
|
|
91
|
+
effective: null,
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
function currentConfig() {
|
|
95
|
+
return workerConfig({ config, dataRoot, root, env }).config;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function effectivePolicy(config) {
|
|
99
|
+
return {
|
|
100
|
+
intervalMs: config?.automation?.intervalMs ?? null,
|
|
101
|
+
maxFilesPerRun: config?.automation?.maxFilesPerRun ?? null,
|
|
102
|
+
tickBudgetMs: config?.automation?.tickBudgetMs ?? null,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function statusSnapshot() {
|
|
107
|
+
// Una configuración inválida no puede hacer que el diagnóstico (el panel) reviente: se devuelve el
|
|
108
|
+
// error como dato, que es justo cuando más falta hace verlo.
|
|
109
|
+
let config = null;
|
|
110
|
+
let configError = null;
|
|
111
|
+
try {
|
|
112
|
+
config = currentConfig();
|
|
113
|
+
} catch (error) {
|
|
114
|
+
configError = { code: error?.code ?? 'invalid-config', message: error?.message ?? 'configuración inválida' };
|
|
115
|
+
}
|
|
116
|
+
const intervalMs = config?.automation?.intervalMs ?? status.intervalMs;
|
|
117
|
+
const nextTickAt = status.enabled && intervalMs && status.lastTickAt !== null ? status.lastTickAt + intervalMs : null;
|
|
118
|
+
// Backoff observable (M6.8, R-08): un operador tiene que poder ver cuánto falta para el próximo
|
|
119
|
+
// intento y en qué factor va, sin abrir el proceso ni leer auditoría.
|
|
120
|
+
const backoffFactor =
|
|
121
|
+
status.consecutiveFailures > 0 ? Math.min(2 ** (status.consecutiveFailures - 1), MAX_BACKOFF_FACTOR) : 0;
|
|
122
|
+
return {
|
|
123
|
+
...status,
|
|
124
|
+
enabled: disposeTimer !== null,
|
|
125
|
+
configured: config?.automation?.enabled ?? null,
|
|
126
|
+
intervalMs,
|
|
127
|
+
nextTickAt,
|
|
128
|
+
nextAttemptAt: nextAttemptAt > 0 ? nextAttemptAt : null,
|
|
129
|
+
backoffFactor,
|
|
130
|
+
backoffRemainingMs: nextAttemptAt > 0 ? Math.max(0, nextAttemptAt - now()) : 0,
|
|
131
|
+
effective: config ? effectivePolicy(config) : status.effective,
|
|
132
|
+
timer: usingHostTimer ? 'host:ctx.timer.interval' : 'node:setInterval',
|
|
133
|
+
note: usingHostTimer
|
|
134
|
+
? 'temporizador del host (ctx.timer.interval); su ciclo de vida lo cierra el contexto del plugin'
|
|
135
|
+
: 'temporizador de Node; dentro del host PA6 inyecta ctx.timer.interval',
|
|
136
|
+
...(configError ? { configError } : {}),
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Una pasada completa sobre todos los ámbitos activos.
|
|
142
|
+
* @returns {Promise<{at:number, scopes:number, results:Array, ms:number, skipped?:boolean, reason?:string}>}
|
|
143
|
+
*/
|
|
144
|
+
async function runOnce({ signal = undefined, scopeId = null, dryRun = false } = {}) {
|
|
145
|
+
if (running) return { skipped: true, reason: 'already-running' };
|
|
146
|
+
const config = currentConfig();
|
|
147
|
+
if (!config.automation.enabled && !dryRun) return { skipped: true, reason: 'disabled' };
|
|
148
|
+
if (!existsSync(registryFile)) return { skipped: true, reason: 'no-registry' };
|
|
149
|
+
|
|
150
|
+
running = true;
|
|
151
|
+
status.running = true;
|
|
152
|
+
const started = now();
|
|
153
|
+
status.lastTickAt = started;
|
|
154
|
+
status.ticks += 1;
|
|
155
|
+
status.effective = effectivePolicy(config);
|
|
156
|
+
let registry = null;
|
|
157
|
+
try {
|
|
158
|
+
registry = openRegistry({ root, create: false, now: started });
|
|
159
|
+
const scopes = activeSyncScopes(registry.db).filter((scope) => scopeId === null || scope.id === scopeId);
|
|
160
|
+
const results = await syncScopes({
|
|
161
|
+
registryDb: registry.db,
|
|
162
|
+
profileRoot: root,
|
|
163
|
+
profileKey: profileKey(env),
|
|
164
|
+
scopes,
|
|
165
|
+
config,
|
|
166
|
+
embedder,
|
|
167
|
+
now,
|
|
168
|
+
signal,
|
|
169
|
+
// Política efectiva del tick: límite de ficheros y presupuesto de tiempo vienen de la config
|
|
170
|
+
// (M6.7 §4). El motor los aplica entre fichero y fichero y nunca a mitad de una transacción.
|
|
171
|
+
limit: config.automation.maxFilesPerRun,
|
|
172
|
+
budgetMs: config.automation.tickBudgetMs,
|
|
173
|
+
monotonic,
|
|
174
|
+
actor: 'automation',
|
|
175
|
+
dryRun,
|
|
176
|
+
});
|
|
177
|
+
const finished = now();
|
|
178
|
+
const outcome = {
|
|
179
|
+
at: finished,
|
|
180
|
+
scopes: results.length,
|
|
181
|
+
results,
|
|
182
|
+
ingested: results.reduce((total, item) => total + item.ingested, 0),
|
|
183
|
+
missing: results.reduce((total, item) => total + item.missing, 0),
|
|
184
|
+
failed: results.reduce((total, item) => total + item.failed, 0),
|
|
185
|
+
unsupported: results.reduce((total, item) => total + item.unsupported, 0),
|
|
186
|
+
sensitive: results.reduce((total, item) => total + (item.sensitive ?? 0), 0),
|
|
187
|
+
partial: results.filter((item) => item.outcome === 'partial').length,
|
|
188
|
+
budgetExhausted: results.filter((item) => item.budget_exhausted === true).length,
|
|
189
|
+
cancelled: results.some((item) => item.cancelled),
|
|
190
|
+
ms: finished - started,
|
|
191
|
+
};
|
|
192
|
+
if (!dryRun) {
|
|
193
|
+
try {
|
|
194
|
+
appendRegistryAudit(registry.db, {
|
|
195
|
+
at: finished,
|
|
196
|
+
actor: 'automation',
|
|
197
|
+
action: 'sync.tick',
|
|
198
|
+
target: 'all',
|
|
199
|
+
outcome: outcome.cancelled ? 'skipped' : outcome.failed > 0 ? 'failed' : 'ok',
|
|
200
|
+
detail: {
|
|
201
|
+
scopes: outcome.scopes,
|
|
202
|
+
ingested: outcome.ingested,
|
|
203
|
+
missing: outcome.missing,
|
|
204
|
+
failed: outcome.failed,
|
|
205
|
+
unsupported: outcome.unsupported,
|
|
206
|
+
sensitive: outcome.sensitive,
|
|
207
|
+
partial: outcome.partial,
|
|
208
|
+
budget_exhausted: outcome.budgetExhausted,
|
|
209
|
+
ms: outcome.ms,
|
|
210
|
+
budget_ms: config.automation.tickBudgetMs,
|
|
211
|
+
max_files: config.automation.maxFilesPerRun,
|
|
212
|
+
},
|
|
213
|
+
});
|
|
214
|
+
} catch (error) {
|
|
215
|
+
logger.warn?.(`lifecode-rag sincronización: no se pudo auditar la pasada: ${error.message}`);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
status.lastRunAt = finished;
|
|
219
|
+
status.lastResult = outcome;
|
|
220
|
+
return outcome;
|
|
221
|
+
} finally {
|
|
222
|
+
if (registry) closeRegistry(registry.db);
|
|
223
|
+
running = false;
|
|
224
|
+
status.running = false;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Tick del temporizador: nunca propaga y deja constancia de los fallos consecutivos. */
|
|
229
|
+
async function tick() {
|
|
230
|
+
// Después de `stop()` el temporizador ya no existe; un callback rezagado no debe ejecutar nada.
|
|
231
|
+
if (!disposeTimer) return;
|
|
232
|
+
if (running) {
|
|
233
|
+
status.skippedTicks += 1;
|
|
234
|
+
status.lastSkippedAt = now();
|
|
235
|
+
status.lastSkipReason = 'already-running';
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
// Desactivar mientras se espera un reintento tiene que surtir efecto YA: si el operador apaga la
|
|
239
|
+
// automatización, el tick no debe seguir contando backoff (ni arrastrarlo si vuelve a activarla).
|
|
240
|
+
let configured = null;
|
|
241
|
+
try {
|
|
242
|
+
configured = currentConfig()?.automation?.enabled ?? null;
|
|
243
|
+
} catch {
|
|
244
|
+
// Configuración inválida: se deja que `runOnce` la reporte como fallo y cuente el backoff.
|
|
245
|
+
configured = null;
|
|
246
|
+
}
|
|
247
|
+
if (configured === false) {
|
|
248
|
+
status.skippedTicks += 1;
|
|
249
|
+
status.lastSkippedAt = now();
|
|
250
|
+
status.lastSkipReason = 'disabled';
|
|
251
|
+
status.consecutiveFailures = 0;
|
|
252
|
+
status.lastError = null;
|
|
253
|
+
nextAttemptAt = 0;
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
if (now() < nextAttemptAt) {
|
|
257
|
+
status.skippedTicks += 1;
|
|
258
|
+
status.lastSkippedAt = now();
|
|
259
|
+
status.lastSkipReason = 'backoff';
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
try {
|
|
263
|
+
const result = await runOnce({ signal: controller?.signal });
|
|
264
|
+
if (!result?.skipped) {
|
|
265
|
+
status.consecutiveFailures = 0;
|
|
266
|
+
status.lastError = null;
|
|
267
|
+
nextAttemptAt = 0;
|
|
268
|
+
} else {
|
|
269
|
+
status.skippedTicks += 1;
|
|
270
|
+
status.lastSkippedAt = now();
|
|
271
|
+
status.lastSkipReason = result.reason ?? 'skipped';
|
|
272
|
+
}
|
|
273
|
+
} catch (error) {
|
|
274
|
+
status.consecutiveFailures += 1;
|
|
275
|
+
status.lastError = {
|
|
276
|
+
at: now(),
|
|
277
|
+
code: error?.code ?? 'internal',
|
|
278
|
+
message: error?.message ?? 'fallo de sincronización',
|
|
279
|
+
};
|
|
280
|
+
const base = status.intervalMs ?? 60_000;
|
|
281
|
+
const factor = Math.min(2 ** (status.consecutiveFailures - 1), MAX_BACKOFF_FACTOR);
|
|
282
|
+
nextAttemptAt = now() + base * factor;
|
|
283
|
+
logger.warn?.(
|
|
284
|
+
`lifecode-rag sincronización: ${error?.message ?? 'fallo'} (intento ${status.consecutiveFailures}; espera ${factor}×)`,
|
|
285
|
+
);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function start() {
|
|
290
|
+
const config = currentConfig();
|
|
291
|
+
if (!config.automation.enabled) {
|
|
292
|
+
status.enabled = false;
|
|
293
|
+
return { started: false, reason: 'disabled' };
|
|
294
|
+
}
|
|
295
|
+
if (disposeTimer) return { started: true, already: true };
|
|
296
|
+
status.intervalMs = config.automation.intervalMs;
|
|
297
|
+
status.effective = effectivePolicy(config);
|
|
298
|
+
controller = new AbortController();
|
|
299
|
+
// Programar primero y declarar `enabled` después: si el temporizador del host lanza (por ejemplo,
|
|
300
|
+
// porque el servicio no existe), `status()` no puede decir que la sincronización está activa.
|
|
301
|
+
let dispose;
|
|
302
|
+
try {
|
|
303
|
+
dispose = schedule(() => {
|
|
304
|
+
tick().catch((error) => logger.warn?.(`lifecode-rag sincronización: ${error?.message ?? 'fallo'}`));
|
|
305
|
+
}, config.automation.intervalMs);
|
|
306
|
+
} catch (error) {
|
|
307
|
+
controller = null;
|
|
308
|
+
status.lastError = { at: now(), code: 'no-timer', message: error?.message ?? 'sin temporizador' };
|
|
309
|
+
return { started: false, reason: 'no-timer', message: status.lastError.message };
|
|
310
|
+
}
|
|
311
|
+
disposeTimer = dispose;
|
|
312
|
+
status.enabled = true;
|
|
313
|
+
status.starts += 1;
|
|
314
|
+
return {
|
|
315
|
+
started: true,
|
|
316
|
+
intervalMs: config.automation.intervalMs,
|
|
317
|
+
timer: usingHostTimer ? 'host' : 'node',
|
|
318
|
+
budgetMs: config.automation.tickBudgetMs,
|
|
319
|
+
maxFilesPerRun: config.automation.maxFilesPerRun,
|
|
320
|
+
scopes: 0,
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function stop() {
|
|
325
|
+
if (disposeTimer) disposeTimer();
|
|
326
|
+
disposeTimer = null;
|
|
327
|
+
status.enabled = false;
|
|
328
|
+
status.stops += 1;
|
|
329
|
+
// Un programador detenido no tiene reintentos pendientes: el backoff se descarta para que un
|
|
330
|
+
// rearranque no herede una espera de hasta ocho intervalos.
|
|
331
|
+
nextAttemptAt = 0;
|
|
332
|
+
status.consecutiveFailures = 0;
|
|
333
|
+
status.lastError = null;
|
|
334
|
+
// Abortar la pasada en curso: el teardown no debe dejar una sincronización escribiendo por detrás.
|
|
335
|
+
if (controller) {
|
|
336
|
+
try {
|
|
337
|
+
controller.abort('scheduler-stopped');
|
|
338
|
+
} catch {
|
|
339
|
+
/* abortar dos veces no es un fallo */
|
|
340
|
+
}
|
|
341
|
+
controller = null;
|
|
342
|
+
}
|
|
343
|
+
return { stopped: true };
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
return { start, stop, runOnce, status: statusSnapshot, tick };
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
export function syncSchedulerFor(deps) {
|
|
350
|
+
if (state.has(deps)) return state.get(deps);
|
|
351
|
+
const scheduler = createSyncScheduler(deps);
|
|
352
|
+
state.set(deps, scheduler);
|
|
353
|
+
return scheduler;
|
|
354
|
+
}
|