@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/pa-api.mjs
ADDED
|
@@ -0,0 +1,517 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* LE-RAG-10 · API PA (solo lectura) para el panel.
|
|
3
|
+
*
|
|
4
|
+
* Núcleo puro: no importa nada del harness. `index.js` la conecta a `webServer`.
|
|
5
|
+
* Rutas: `/snapshot` y `/config` por GET; `/search` y `/context` por POST con cuerpo JSON
|
|
6
|
+
* (contrato `PA-UI-0-API-CONTRACT.md` §6.7 y §6.8); `/actions` responde SIEMPRE 403
|
|
7
|
+
* `approval-required`: ninguna ruta HTTP puede ejecutar ingest/forget/reindex sin la aprobación
|
|
8
|
+
* del host.
|
|
9
|
+
*
|
|
10
|
+
* LE-RAG-11 (D-01): una sola forma de llamar a cada ruta. `/search` y `/context` con GET devuelven
|
|
11
|
+
* 405; no se conservan dos contratos para la misma operación.
|
|
12
|
+
*/
|
|
13
|
+
import { openRegistry, listRoots } from './registry.mjs';
|
|
14
|
+
import { openScopeStore } from './scope-stores.mjs';
|
|
15
|
+
import { search } from './search.mjs';
|
|
16
|
+
import { assembleContextAsync } from './context.mjs';
|
|
17
|
+
import { resolveConfig } from './config-resolve.mjs';
|
|
18
|
+
import { DEFAULT_DIM, LOCAL_PROVIDER, embedText } from './embed.mjs';
|
|
19
|
+
import { RagError, httpStatusFor } from './errors.mjs';
|
|
20
|
+
import { applySelection, readSelection } from './selection.mjs';
|
|
21
|
+
import { verifyAuditChain } from './audit.mjs';
|
|
22
|
+
|
|
23
|
+
export const PA_PREFIX = '/lifecode-rag/pa';
|
|
24
|
+
export const PA_VERSION = 'pa/1.2.0';
|
|
25
|
+
const MAX_BODY = 1_000_000;
|
|
26
|
+
const MAX_LIMIT = 200;
|
|
27
|
+
const MAX_SEARCH = 50;
|
|
28
|
+
/** Contrato §8: la consulta se limita a 512 caracteres; por encima se rechaza, nunca se recorta. */
|
|
29
|
+
const MAX_QUERY = 512;
|
|
30
|
+
const GET_ROUTES = {
|
|
31
|
+
'/': ['project', 'limit', 'cursor'],
|
|
32
|
+
'/snapshot': ['project', 'limit', 'cursor'],
|
|
33
|
+
'/history': ['project', 'limit', 'cursor'],
|
|
34
|
+
};
|
|
35
|
+
const POST_FIELDS = {
|
|
36
|
+
'/search': ['query', 'limit'],
|
|
37
|
+
'/context': ['query', 'budgetTokens'],
|
|
38
|
+
'/selection': ['projectId', 'expectedRevision'],
|
|
39
|
+
};
|
|
40
|
+
/** En POST el proyecto viaja por query string: la cabecera de sesión del contrato está BLOCKED (PA01). */
|
|
41
|
+
const POST_PARAMS = ['project'];
|
|
42
|
+
|
|
43
|
+
const localEmbedder = {
|
|
44
|
+
model: LOCAL_PROVIDER,
|
|
45
|
+
dim: DEFAULT_DIM,
|
|
46
|
+
embed: async (texts) => texts.map((text) => embedText(text)),
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
/** Escribe el sobre contractual (§5): {ok:true,data} o {ok:false,error}. Un cuerpo que supera el tope no se
|
|
50
|
+
* sirve: se responde 500 con el código público response-too-large, nunca un 200 con error dentro. */
|
|
51
|
+
function writeJson(res, status, body, limit) {
|
|
52
|
+
const text = JSON.stringify(body);
|
|
53
|
+
res.setHeader('content-type', 'application/json; charset=utf-8');
|
|
54
|
+
res.setHeader('cache-control', 'no-store');
|
|
55
|
+
res.setHeader('x-content-type-options', 'nosniff');
|
|
56
|
+
if (text.length > limit) {
|
|
57
|
+
res.statusCode = 500;
|
|
58
|
+
res.end(JSON.stringify({ ok: false, error: { code: 'response-too-large', message: 'la respuesta supera el tamaño máximo permitido', details: { limit } } }));
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
res.statusCode = status;
|
|
62
|
+
res.end(text);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Rechaza parámetros de query no declarados por la ruta (contrato §5: no se ignora nada en silencio). */
|
|
66
|
+
function queryParams(url, allowed, route) {
|
|
67
|
+
const unknown = [...new Set([...url.searchParams.keys()].filter((key) => !allowed.includes(key)))];
|
|
68
|
+
if (unknown.length > 0) {
|
|
69
|
+
throw new RagError('invalid-argument', `${route}: parámetro no declarado`, { details: { reason: 'unknown-parameter', parameters: unknown } });
|
|
70
|
+
}
|
|
71
|
+
const q = url.searchParams;
|
|
72
|
+
const limitRaw = q.get('limit');
|
|
73
|
+
const limit = limitRaw === null ? null : Number(limitRaw);
|
|
74
|
+
if (limit !== null && (!Number.isInteger(limit) || limit < 1)) {
|
|
75
|
+
throw new RagError('invalid-argument', 'limit inválido', { details: { reason: 'invalid-field', field: 'limit' } });
|
|
76
|
+
} if (limit !== null && limit > MAX_LIMIT) {
|
|
77
|
+
throw new RagError('invalid-argument', 'limit supera ' + MAX_LIMIT, { details: { reason: 'limit-too-large', field: 'limit', max: MAX_LIMIT } });
|
|
78
|
+
}
|
|
79
|
+
return {
|
|
80
|
+
project: q.get('project') || null,
|
|
81
|
+
limit,
|
|
82
|
+
cursor: q.get('cursor') || null,
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Lee el cuerpo JSON de un POST: tamaño acotado, objeto plano y un error propio por cada caso. */
|
|
87
|
+
async function readJsonBody(req, limit = MAX_BODY) {
|
|
88
|
+
const chunks = [];
|
|
89
|
+
let size = 0;
|
|
90
|
+
if (req && typeof req[Symbol.asyncIterator] === 'function') {
|
|
91
|
+
for await (const chunk of req) {
|
|
92
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
|
|
93
|
+
size += buffer.length;
|
|
94
|
+
if (size > limit) throw new RagError('too-large', 'cuerpo de la petición demasiado grande', { details: { limit } });
|
|
95
|
+
chunks.push(buffer);
|
|
96
|
+
}
|
|
97
|
+
} else if (req && req.body !== undefined && req.body !== null) {
|
|
98
|
+
const raw = typeof req.body === 'string' ? req.body : JSON.stringify(req.body);
|
|
99
|
+
if (raw.length > limit) throw new RagError('too-large', 'cuerpo de la petición demasiado grande', { details: { limit } });
|
|
100
|
+
chunks.push(Buffer.from(raw));
|
|
101
|
+
}
|
|
102
|
+
const raw = Buffer.concat(chunks).toString('utf8').trim();
|
|
103
|
+
if (raw === '') throw new RagError('invalid-argument', 'cuerpo JSON obligatorio', { details: { reason: 'missing-body' } });
|
|
104
|
+
let data;
|
|
105
|
+
try {
|
|
106
|
+
data = JSON.parse(raw);
|
|
107
|
+
} catch {
|
|
108
|
+
throw new RagError('invalid-argument', 'cuerpo JSON inválido', { details: { reason: 'invalid-json' } });
|
|
109
|
+
}
|
|
110
|
+
if (data === null || typeof data !== 'object' || Array.isArray(data)) {
|
|
111
|
+
throw new RagError('invalid-argument', 'el cuerpo debe ser un objeto JSON', { details: { reason: 'invalid-body' } });
|
|
112
|
+
}
|
|
113
|
+
return data;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function assertKnownFields(body, allowed, route) {
|
|
117
|
+
const unknown = Object.keys(body).filter((key) => !allowed.includes(key));
|
|
118
|
+
if (unknown.length > 0) {
|
|
119
|
+
throw new RagError('invalid-argument', `${route}: campo no declarado`, { details: { reason: 'unknown-field', fields: unknown } });
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function requireQuery(body, route) {
|
|
124
|
+
if (!Object.prototype.hasOwnProperty.call(body, 'query')) {
|
|
125
|
+
throw new RagError('invalid-argument', `${route}: falta query`, { details: { reason: 'missing-field', field: 'query' } });
|
|
126
|
+
}
|
|
127
|
+
if (typeof body.query !== 'string') {
|
|
128
|
+
throw new RagError('invalid-argument', `${route}: query debe ser texto`, { details: { reason: 'invalid-field', field: 'query' } });
|
|
129
|
+
}
|
|
130
|
+
const query = body.query.trim();
|
|
131
|
+
if (query === '') {
|
|
132
|
+
throw new RagError('invalid-argument', `${route}: query vacío`, { details: { reason: 'invalid-field', field: 'query' } });
|
|
133
|
+
}
|
|
134
|
+
if (query.length > MAX_QUERY) {
|
|
135
|
+
throw new RagError('invalid-argument', `${route}: query supera ${MAX_QUERY} caracteres`, { details: { reason: 'query-too-long', field: 'query', max: MAX_QUERY } });
|
|
136
|
+
}
|
|
137
|
+
return query;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function searchPayload(body, config) {
|
|
141
|
+
assertKnownFields(body, POST_FIELDS['/search'], '/search');
|
|
142
|
+
const query = requireQuery(body, '/search');
|
|
143
|
+
const fallback = Number.isInteger(config?.search?.limit) ? config.search.limit : 8;
|
|
144
|
+
let limit = Math.min(fallback, MAX_SEARCH);
|
|
145
|
+
if (body.limit !== undefined) {
|
|
146
|
+
if (!Number.isInteger(body.limit) || body.limit < 1) {
|
|
147
|
+
throw new RagError('invalid-argument', '/search: limit inválido', { details: { reason: 'invalid-field', field: 'limit' } });
|
|
148
|
+
}
|
|
149
|
+
if (body.limit > MAX_SEARCH) {
|
|
150
|
+
throw new RagError('invalid-argument', `/search: limit supera ${MAX_SEARCH}`, { details: { reason: 'limit-too-large', field: 'limit', max: MAX_SEARCH } });
|
|
151
|
+
}
|
|
152
|
+
limit = body.limit;
|
|
153
|
+
}
|
|
154
|
+
return { query, limit };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function contextPayload(body, config) {
|
|
158
|
+
assertKnownFields(body, POST_FIELDS['/context'], '/context');
|
|
159
|
+
const query = requireQuery(body, '/context');
|
|
160
|
+
const fallback = Number.isInteger(config?.context?.budgetTokens) ? config.context.budgetTokens : 2000;
|
|
161
|
+
let budgetTokens = fallback;
|
|
162
|
+
if (body.budgetTokens !== undefined) {
|
|
163
|
+
if (!Number.isInteger(body.budgetTokens) || body.budgetTokens < 1) {
|
|
164
|
+
throw new RagError('invalid-argument', '/context: budgetTokens inválido', { details: { reason: 'invalid-field', field: 'budgetTokens' } });
|
|
165
|
+
}
|
|
166
|
+
budgetTokens = body.budgetTokens;
|
|
167
|
+
}
|
|
168
|
+
return { query, budgetTokens };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** CR-1 (§6.2): el cuerpo declara el proyecto y la revisión que el cliente cree vigente. */
|
|
172
|
+
function selectionPayload(body) {
|
|
173
|
+
assertKnownFields(body, POST_FIELDS['/selection'], '/selection');
|
|
174
|
+
if (!Object.prototype.hasOwnProperty.call(body, 'projectId')) {
|
|
175
|
+
throw new RagError('invalid-argument', '/selection: falta projectId', { details: { reason: 'missing-field', field: 'projectId' } });
|
|
176
|
+
}
|
|
177
|
+
if (typeof body.projectId !== 'string' || !body.projectId.startsWith('prj_')) {
|
|
178
|
+
throw new RagError('invalid-argument', '/selection: projectId debe ser un identificador de proyecto', { details: { reason: 'invalid-field', field: 'projectId' } });
|
|
179
|
+
}
|
|
180
|
+
return { projectId: body.projectId, expectedRevision: body.expectedRevision };
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Proyecto efectivo de la petición, en este orden: el que pide el cliente, la selección persistida
|
|
185
|
+
* del perfil (CR-1) y, si sólo hay uno, ese. Con varios proyectos y sin selección se responde
|
|
186
|
+
* `scope-ambiguous`: nunca se elige uno «por defecto» a la callada.
|
|
187
|
+
*/
|
|
188
|
+
function projectView(db, requested, selection = null) {
|
|
189
|
+
const projects = db.prepare('select id, name from projects order by created_at').all();
|
|
190
|
+
if (projects.length === 0) throw new RagError('project-not-authorized', 'el perfil no tiene proyectos');
|
|
191
|
+
let project = null;
|
|
192
|
+
if (requested) {
|
|
193
|
+
project = projects.find((p) => p.id === requested) ?? null;
|
|
194
|
+
if (!project) throw new RagError('project-not-authorized', 'proyecto desconocido o no autorizado', { details: { project: requested } });
|
|
195
|
+
} else if (selection) {
|
|
196
|
+
project = projects.find((p) => p.id === selection.projectId) ?? null;
|
|
197
|
+
// Una selección que apunta a un proyecto desaparecido o archivado no se usa en silencio: se
|
|
198
|
+
// ignora y se resuelve como si no hubiera selección.
|
|
199
|
+
}
|
|
200
|
+
if (!project) {
|
|
201
|
+
if (projects.length === 1) project = projects[0];
|
|
202
|
+
else throw new RagError('scope-ambiguous', 'varios proyectos: especifica project', { details: { candidates: projects.map((p) => p.id) } });
|
|
203
|
+
}
|
|
204
|
+
const roots = listRoots(db, { scopeKind: 'prj', scopeId: project.id });
|
|
205
|
+
const authorized = roots.filter((r) => r.state === 'authorized');
|
|
206
|
+
if (authorized.length === 0) throw new RagError('project-not-authorized', 'el proyecto no tiene raíces autorizadas', { details: { project: project.id } });
|
|
207
|
+
return { project, roots, authorized };
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function openStore(profileRoot, profileKey, scopeId) {
|
|
211
|
+
const store = openScopeStore({ profileRoot, profileKey, scope: { kind: 'prj', id: scopeId }, create: false });
|
|
212
|
+
if (!store) throw new RagError('store-not-initialized', 'el proyecto no tiene almacén', { details: { project: scopeId } });
|
|
213
|
+
return store;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function relUri(uri, roots) {
|
|
217
|
+
const norm = (v) => String(v).split(String.fromCharCode(92)).join('/').toLowerCase();
|
|
218
|
+
const target = norm(uri);
|
|
219
|
+
for (const root of roots) {
|
|
220
|
+
const base = norm(root.path);
|
|
221
|
+
if (target === base) return '.';
|
|
222
|
+
if (target.startsWith(base + '/')) return String(uri).slice(root.path.length + 1);
|
|
223
|
+
}
|
|
224
|
+
const parts = String(uri).split(String.fromCharCode(92)).join('/').split('/');
|
|
225
|
+
return parts[parts.length - 1] ?? String(uri);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function sourcesPage(db, { limit, cursor, roots = [] }) {
|
|
229
|
+
const take = Math.min(limit ?? 50, MAX_LIMIT);
|
|
230
|
+
const offset = cursor ? Number(cursor) : 0;
|
|
231
|
+
if (!Number.isInteger(offset) || offset < 0) throw new RagError('invalid-argument', 'cursor inválido');
|
|
232
|
+
const total = db.prepare('select count(*) n from sources').get().n;
|
|
233
|
+
const rows = db.prepare(`select s.id, s.uri, s.title, s.mime, s.bytes, s.indexed_at,
|
|
234
|
+
(select count(*) from chunks c where c.source_id = s.id) as chunk_count
|
|
235
|
+
from sources s order by s.uri limit ? offset ?`).all(take, offset);
|
|
236
|
+
return {
|
|
237
|
+
rows: rows.map((r) => ({ id: r.id, uri: relUri(r.uri, roots), title: r.title, mime: r.mime, bytes: r.bytes, chunks: r.chunk_count, indexedAt: r.indexed_at })),
|
|
238
|
+
total,
|
|
239
|
+
nextCursor: offset + rows.length < total ? String(offset + rows.length) : null,
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function auditHead(db) {
|
|
244
|
+
const row = db.prepare('select max(seq) seq from audit').get();
|
|
245
|
+
return { head: row?.seq ?? 0 };
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Proyectos seleccionables del perfil: id, nombre y raíces autorizadas. Es lo que el panel necesita
|
|
250
|
+
* para ofrecer el cambio de proyecto (CR-1); sin esta lista el selector sólo podía mostrar el activo.
|
|
251
|
+
*/
|
|
252
|
+
function projectsIndex(db, currentId) {
|
|
253
|
+
const rows = db.prepare(`select p.id, p.name, p.status,
|
|
254
|
+
(select count(*) from roots r where r.scope_kind='prj' and r.scope_id=p.id and r.state='authorized') as roots
|
|
255
|
+
from projects p where p.status='active' order by p.created_at`).all();
|
|
256
|
+
return rows.map((row) => ({
|
|
257
|
+
id: row.id,
|
|
258
|
+
name: row.name,
|
|
259
|
+
roots: Number(row.roots),
|
|
260
|
+
authorized: Number(row.roots),
|
|
261
|
+
current: row.id === currentId,
|
|
262
|
+
}));
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Claves de `audit.details` que se publican. El resto se descarta: los detalles pueden llevar rutas
|
|
267
|
+
* absolutas, ids de otros ámbitos o mensajes de error con trayectorias, y el historial es de lectura.
|
|
268
|
+
*/
|
|
269
|
+
const HISTORY_DETAIL_KEYS = Object.freeze(['sourceId', 'chunks', 'bytes', 'code', 'revision', 'replace', 'embedding', 'skipped']);
|
|
270
|
+
|
|
271
|
+
function safeDetails(raw) {
|
|
272
|
+
if (raw === null || raw === undefined) return null;
|
|
273
|
+
let parsed;
|
|
274
|
+
try { parsed = typeof raw === 'string' ? JSON.parse(raw) : raw; } catch { return null; }
|
|
275
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
|
|
276
|
+
const out = {};
|
|
277
|
+
for (const key of HISTORY_DETAIL_KEYS) {
|
|
278
|
+
if (Object.prototype.hasOwnProperty.call(parsed, key)) out[key] = parsed[key];
|
|
279
|
+
}
|
|
280
|
+
return Object.keys(out).length > 0 ? out : null;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* Historial del proyecto ACTIVO, leído de SU almacén (`audit`), que es la cadena encadenada por hash.
|
|
285
|
+
* No hay forma de ver el historial de otro proyecto por esta ruta: cada proyecto tiene su propio
|
|
286
|
+
* fichero y sus propias filas, así que el filtro de ámbito es estructural, no un `where` que se pueda
|
|
287
|
+
* olvidar. `details` se filtra por lista blanca y `target` se relativiza a las raíces autorizadas.
|
|
288
|
+
*/
|
|
289
|
+
function historyPage(db, { limit, cursor, roots, scope }) {
|
|
290
|
+
const take = Math.min(limit ?? 50, MAX_LIMIT);
|
|
291
|
+
const before = cursor ? Number(cursor) : null;
|
|
292
|
+
if (before !== null && (!Number.isInteger(before) || before < 0)) {
|
|
293
|
+
throw new RagError('invalid-argument', 'cursor inválido', { details: { reason: 'invalid-field', field: 'cursor' } });
|
|
294
|
+
}
|
|
295
|
+
const total = db.prepare('select count(*) n from audit').get().n;
|
|
296
|
+
const rows = before === null
|
|
297
|
+
? db.prepare(`select seq, at, actor, tool, action, target, outcome, details, hash
|
|
298
|
+
from audit order by seq desc limit ?`).all(take)
|
|
299
|
+
: db.prepare(`select seq, at, actor, tool, action, target, outcome, details, hash
|
|
300
|
+
from audit where seq < ? order by seq desc limit ?`).all(before, take);
|
|
301
|
+
const entries = rows.map((row) => ({
|
|
302
|
+
seq: row.seq,
|
|
303
|
+
at: Number(row.at),
|
|
304
|
+
actor: row.actor,
|
|
305
|
+
tool: row.tool,
|
|
306
|
+
action: row.action,
|
|
307
|
+
target: row.target === null ? null : relUri(row.target, roots),
|
|
308
|
+
outcome: row.outcome,
|
|
309
|
+
hash: String(row.hash).slice(0, 16),
|
|
310
|
+
details: safeDetails(row.details),
|
|
311
|
+
}));
|
|
312
|
+
const oldest = entries.length > 0 ? entries[entries.length - 1].seq : null;
|
|
313
|
+
return {
|
|
314
|
+
scope,
|
|
315
|
+
total,
|
|
316
|
+
entries,
|
|
317
|
+
nextCursor: oldest !== null && oldest > 1 ? String(oldest) : null,
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* @param {{profileRoot: string, profileKey?: string, env?: object, now?: () => number,
|
|
323
|
+
* maxBody?: number, authorize?: (request: {headers: object, method: string, url: URL}) =>
|
|
324
|
+
* Promise<{ok: boolean, peer?: {id?: string, principal?: {kind?: string}}, status?: number,
|
|
325
|
+
* code?: string, message?: string}> | {ok: boolean, peer?: object}} options
|
|
326
|
+
*
|
|
327
|
+
* `authorize` es la compuerta del anfitrión (PA01). Sin ella el núcleo sigue sirviendo tal cual —es
|
|
328
|
+
* su contrato de independencia—, pero el adaptador de DSH **siempre** pasa una, y cuando el host no
|
|
329
|
+
* ofrece servicio de conexión pasa una que niega: la ausencia de compuerta no se degrada a «abierto».
|
|
330
|
+
*/
|
|
331
|
+
export function createPaHandler({
|
|
332
|
+
profileRoot, profileKey = 'desktop', env = process.env, now = () => Date.now(),
|
|
333
|
+
maxBody = MAX_BODY, authorize = null,
|
|
334
|
+
} = {}) {
|
|
335
|
+
// Respondedores ligados al tope de esta instancia: la sobrecarga se mide por respuesta.
|
|
336
|
+
const respond = (res, status, payload) => writeJson(res, status, { ok: true, data: payload }, maxBody);
|
|
337
|
+
const failWith = (res, status, code, message, details) => writeJson(res, status, { ok: false, error: { code, message, ...(details ? { details } : {}) } }, maxBody);
|
|
338
|
+
const methodNotAllowed = (res, allowed, message) => failWith(res, 405, 'method-not-allowed', message, { reason: 'method-not-allowed', allow: allowed });
|
|
339
|
+
|
|
340
|
+
if (typeof profileRoot !== 'string' || !profileRoot) throw new TypeError('profileRoot obligatorio');
|
|
341
|
+
|
|
342
|
+
return async function paHandler(req, res) {
|
|
343
|
+
const started = now();
|
|
344
|
+
try {
|
|
345
|
+
const url = new URL(req.url, 'http://localhost');
|
|
346
|
+
if (!url.pathname.startsWith(PA_PREFIX)) return failWith(res, 404, 'not-found', 'ruta fuera de la API PA');
|
|
347
|
+
const route = url.pathname.slice(PA_PREFIX.length).replace(/\/+$/, '') || '/';
|
|
348
|
+
const method = (req.method || 'GET').toUpperCase();
|
|
349
|
+
|
|
350
|
+
// PA01: la compuerta va ANTES de resolver la ruta. Sin credencial del host no se distingue una
|
|
351
|
+
// ruta existente de una inventada: 401/403 y nada más.
|
|
352
|
+
let peer = null;
|
|
353
|
+
if (authorize) {
|
|
354
|
+
let decision;
|
|
355
|
+
try {
|
|
356
|
+
decision = await authorize({ headers: req.headers ?? {}, method, url });
|
|
357
|
+
} catch {
|
|
358
|
+
return failWith(res, 503, 'authorization-unavailable', 'la compuerta de autenticación del host falló');
|
|
359
|
+
}
|
|
360
|
+
if (!decision || decision.ok !== true) {
|
|
361
|
+
const status = decision?.status === 401 ? 401 : (decision?.status ?? 403);
|
|
362
|
+
const code = decision?.code ?? (status === 401 ? 'unauthenticated' : 'authorization-unavailable');
|
|
363
|
+
return failWith(res, status, code, decision?.message ?? 'la petición no está autenticada por el host');
|
|
364
|
+
}
|
|
365
|
+
peer = decision.peer ?? null;
|
|
366
|
+
}
|
|
367
|
+
const principal = peer && peer.principal && peer.principal.kind ? String(peer.principal.kind) : null;
|
|
368
|
+
|
|
369
|
+
const { config } = resolveConfig({ dataRoot: profileRoot, profileKey });
|
|
370
|
+
|
|
371
|
+
// /config no depende de proyecto: se responde antes de abrir el registro.
|
|
372
|
+
if (route === '/config') {
|
|
373
|
+
if (method !== 'GET' && method !== 'HEAD') return methodNotAllowed(res, ['GET', 'HEAD'], 'la configuración se lee con GET');
|
|
374
|
+
queryParams(url, [], route);
|
|
375
|
+
return respond(res, 200, { mode: 'api', service: 'ok', version: PA_VERSION, config, profile: { key: profileKey } });
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
if (route === '/actions') {
|
|
379
|
+
return failWith(res, 403, 'approval-required', 'las operaciones de escritura requieren aprobación del host', {
|
|
380
|
+
tools: ['lifecode_rag_ingest', 'lifecode_rag_forget', 'lifecode_rag_reindex'],
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
let params;
|
|
385
|
+
let payload = null;
|
|
386
|
+
if (Object.prototype.hasOwnProperty.call(POST_FIELDS, route)) {
|
|
387
|
+
// LE-RAG-11: /search y /context son POST con cuerpo JSON. GET sobre ellas se rechaza: una
|
|
388
|
+
// sola forma de llamar a cada ruta (D-01).
|
|
389
|
+
if (method !== 'POST') return methodNotAllowed(res, ['POST'], `${route} se consulta con POST y cuerpo JSON`);
|
|
390
|
+
params = queryParams(url, POST_PARAMS, route);
|
|
391
|
+
const body = await readJsonBody(req, maxBody);
|
|
392
|
+
payload = route === '/search' ? searchPayload(body, config)
|
|
393
|
+
: route === '/context' ? contextPayload(body, config)
|
|
394
|
+
: selectionPayload(body);
|
|
395
|
+
} else if (Object.prototype.hasOwnProperty.call(GET_ROUTES, route)) {
|
|
396
|
+
if (method !== 'GET' && method !== 'HEAD') return methodNotAllowed(res, ['GET', 'HEAD'], 'la API PA es de solo lectura');
|
|
397
|
+
params = queryParams(url, GET_ROUTES[route], route);
|
|
398
|
+
} else {
|
|
399
|
+
return failWith(res, 404, 'not-found', `ruta PA desconocida: ${route}`);
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
let registry;
|
|
403
|
+
try {
|
|
404
|
+
registry = openRegistry({ root: profileRoot, create: false, now: now() });
|
|
405
|
+
} catch (error) {
|
|
406
|
+
if (error instanceof RagError && error.code === 'store-not-initialized') {
|
|
407
|
+
return failWith(res, 503, 'registry-unavailable', 'el perfil no tiene registro Project-Aware');
|
|
408
|
+
}
|
|
409
|
+
throw error;
|
|
410
|
+
}
|
|
411
|
+
const db = registry.db ?? registry;
|
|
412
|
+
try {
|
|
413
|
+
// CR-1: la selección se escribe en el registro del perfil, con CAS sobre la revisión.
|
|
414
|
+
if (route === '/selection') {
|
|
415
|
+
const applied = applySelection(db, {
|
|
416
|
+
projectId: payload.projectId,
|
|
417
|
+
expectedRevision: payload.expectedRevision,
|
|
418
|
+
selectedBy: 'human',
|
|
419
|
+
source: 'explicit',
|
|
420
|
+
principal: principal ?? 'owner',
|
|
421
|
+
now: now(),
|
|
422
|
+
});
|
|
423
|
+
const selected = db.prepare('select id, name from projects where id = ?').get(applied.selection.projectId);
|
|
424
|
+
return respond(res, 200, {
|
|
425
|
+
changed: applied.changed,
|
|
426
|
+
selection: applied.selection,
|
|
427
|
+
project: selected ? { id: selected.id, name: selected.name } : null,
|
|
428
|
+
});
|
|
429
|
+
}
|
|
430
|
+
const selection = readSelection(db);
|
|
431
|
+
const { project, roots, authorized } = projectView(db, params.project, selection);
|
|
432
|
+
const store = openStore(profileRoot, profileKey, project.id);
|
|
433
|
+
const sdb = store.db ?? store;
|
|
434
|
+
const scope = { id: project.id, kind: 'prj', name: project.name };
|
|
435
|
+
try {
|
|
436
|
+
if (route === '/history') {
|
|
437
|
+
// Historial del proyecto activo: sale de SU almacén (no de otro), con la cadena verificada.
|
|
438
|
+
const page = historyPage(sdb, { limit: params.limit, cursor: params.cursor, roots: authorized, scope });
|
|
439
|
+
return respond(res, 200, { mode: 'api', ...page, integrity: verifyAuditChain(sdb) });
|
|
440
|
+
}
|
|
441
|
+
if (route === '/' || route === '/snapshot') {
|
|
442
|
+
return respond(res, 200, {
|
|
443
|
+
mode: 'api', service: 'ok', asOf: started, version: PA_VERSION,
|
|
444
|
+
project: { id: project.id, name: project.name },
|
|
445
|
+
selection,
|
|
446
|
+
projects: projectsIndex(db, project.id),
|
|
447
|
+
auth: peer ? { principal: principal ?? 'owner' } : null,
|
|
448
|
+
scopes: [{ kind: 'prj', id: project.id, name: project.name, roots: roots.length, authorized: authorized.length }],
|
|
449
|
+
libraries: [],
|
|
450
|
+
sources: sourcesPage(sdb, { limit: params.limit, cursor: params.cursor, roots: authorized }),
|
|
451
|
+
audit: auditHead(sdb),
|
|
452
|
+
config: { strategy: config.search.strategy, limit: config.search.limit, diversity: config.search.diversity },
|
|
453
|
+
});
|
|
454
|
+
}
|
|
455
|
+
if (route === '/search') {
|
|
456
|
+
const result = await search(sdb, {
|
|
457
|
+
query: payload.query, limit: payload.limit, config, embedder: localEmbedder,
|
|
458
|
+
strategy: config.search.strategy, diversity: config.search.diversity, record: false, now: now(),
|
|
459
|
+
});
|
|
460
|
+
const rows = result.results ?? [];
|
|
461
|
+
return respond(res, 200, {
|
|
462
|
+
mode: config.search.strategy,
|
|
463
|
+
elapsedMs: result.elapsedMs ?? null,
|
|
464
|
+
results: rows.map((r) => ({
|
|
465
|
+
chunkKey: r.chunkKey,
|
|
466
|
+
sourceId: r.sourceId,
|
|
467
|
+
uri: relUri(r.uri, authorized),
|
|
468
|
+
title: r.title,
|
|
469
|
+
heading: r.heading ?? null,
|
|
470
|
+
ordinal: r.ordinal,
|
|
471
|
+
rrf: r.rrf ?? null,
|
|
472
|
+
score: r.score ?? null,
|
|
473
|
+
snippet: r.snippet ?? null,
|
|
474
|
+
scopeId: scope.id,
|
|
475
|
+
scopeKind: scope.kind,
|
|
476
|
+
scopeName: scope.name,
|
|
477
|
+
})),
|
|
478
|
+
scopes: [{ ...scope, results: rows.length }],
|
|
479
|
+
});
|
|
480
|
+
}
|
|
481
|
+
if (route === '/context') {
|
|
482
|
+
const result = await search(sdb, {
|
|
483
|
+
query: payload.query, limit: Math.min(config.search.limit * 2, MAX_SEARCH), config,
|
|
484
|
+
embedder: localEmbedder, strategy: config.search.strategy, record: false, now: now(),
|
|
485
|
+
});
|
|
486
|
+
const assembled = await assembleContextAsync({
|
|
487
|
+
results: result.results ?? [], config, embedder: localEmbedder, maxTokens: payload.budgetTokens,
|
|
488
|
+
});
|
|
489
|
+
const citations = (assembled.citations ?? []).map((citation) => ({ ...citation, uri: relUri(citation.uri, authorized) }));
|
|
490
|
+
return respond(res, 200, {
|
|
491
|
+
mode: config.search.strategy,
|
|
492
|
+
elapsedMs: result.elapsedMs ?? null,
|
|
493
|
+
text: assembled.text ?? '',
|
|
494
|
+
citations,
|
|
495
|
+
tokens: assembled.tokens ?? null,
|
|
496
|
+
truncated: assembled.truncated ?? null,
|
|
497
|
+
considered: assembled.considered ?? null,
|
|
498
|
+
scopes: [{ ...scope, results: citations.length }],
|
|
499
|
+
});
|
|
500
|
+
}
|
|
501
|
+
return failWith(res, 404, 'not-found', `ruta PA desconocida: ${route}`);
|
|
502
|
+
} finally {
|
|
503
|
+
store.close?.();
|
|
504
|
+
}
|
|
505
|
+
} finally {
|
|
506
|
+
(db.close ?? (() => {})).call(db);
|
|
507
|
+
}
|
|
508
|
+
} catch (error) {
|
|
509
|
+
if (error instanceof RagError) {
|
|
510
|
+
// Un solo mapa (lib/errors.mjs): un código de autorización no puede acabar en 500 por no estar
|
|
511
|
+
// en una tabla local. El status sale de HTTP_STATUS; lo no clasificado cae a 500 explícitamente.
|
|
512
|
+
return failWith(res, httpStatusFor(error.code), error.code, error.message, error.details);
|
|
513
|
+
}
|
|
514
|
+
return failWith(res, 500, 'internal-error', 'error interno del transporte PA');
|
|
515
|
+
}
|
|
516
|
+
};
|
|
517
|
+
}
|