@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/pa-api.mjs
ADDED
|
@@ -0,0 +1,946 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* LE-RAG-10 · API PA del panel.
|
|
3
|
+
*
|
|
4
|
+
* Núcleo puro: no importa nada del harness. `index.js` la conecta a `webServer`.
|
|
5
|
+
* Rutas de lectura: `/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
|
+
* ACP-07 F3 · administración de proyectos (§6.12): `/projects` (POST crear, PATCH actualizar),
|
|
11
|
+
* `/projects/archive`, `/projects/restore`, `/roots`, `/roots/remove`, `/projects/register` y
|
|
12
|
+
* `/candidates` (GET). Sólo se atienden con la compuerta del host resuelta: sin ella la
|
|
13
|
+
* administración no existe (503), porque estas rutas no son herramientas del modelo.
|
|
14
|
+
*
|
|
15
|
+
* LE-RAG-11 (D-01): una sola forma de llamar a cada ruta. `/search` y `/context` con GET devuelven
|
|
16
|
+
* 405; no se conservan dos contratos para la misma operación.
|
|
17
|
+
*/
|
|
18
|
+
import {
|
|
19
|
+
addRoot, appendRegistryAudit, createProject, getProject, listProjects, listRoots,
|
|
20
|
+
openRegistry, pathKeyFor, removeRoot, restoreProject, updateProject, verifyRegistryAudit,
|
|
21
|
+
} from './registry.mjs';
|
|
22
|
+
import { withTransaction } from './db.mjs';
|
|
23
|
+
import { openScopeStore } from './scope-stores.mjs';
|
|
24
|
+
import { search } from './search.mjs';
|
|
25
|
+
import { assembleContextAsync } from './context.mjs';
|
|
26
|
+
import { resolveConfig } from './config-resolve.mjs';
|
|
27
|
+
import { DEFAULT_DIM, LOCAL_PROVIDER, embedText } from './embed.mjs';
|
|
28
|
+
import { RagError, httpStatusFor } from './errors.mjs';
|
|
29
|
+
import { applySelection, archiveProjectWithSelection, readSelection } from './selection.mjs';
|
|
30
|
+
import { registerDiscoveredProject, scanWorkspace } from './discovery.mjs';
|
|
31
|
+
import { trustedRootFor } from './trusted-roots.mjs';
|
|
32
|
+
import { verifyAuditChain } from './audit.mjs';
|
|
33
|
+
|
|
34
|
+
export const PA_PREFIX = '/lifecode-rag/pa';
|
|
35
|
+
export const PA_VERSION = 'pa/1.3.0';
|
|
36
|
+
const MAX_BODY = 1_000_000;
|
|
37
|
+
const MAX_LIMIT = 200;
|
|
38
|
+
const MAX_SEARCH = 50;
|
|
39
|
+
const MAX_NAME = 120;
|
|
40
|
+
const MAX_PATH = 4096;
|
|
41
|
+
/** Contrato §8: la consulta se limita a 512 caracteres; por encima se rechaza, nunca se recorta. */
|
|
42
|
+
const MAX_QUERY = 512;
|
|
43
|
+
const GET_ROUTES = {
|
|
44
|
+
'/': ['project', 'limit', 'cursor'],
|
|
45
|
+
'/snapshot': ['project', 'limit', 'cursor'],
|
|
46
|
+
'/history': ['project', 'limit', 'cursor'],
|
|
47
|
+
};
|
|
48
|
+
const POST_FIELDS = {
|
|
49
|
+
'/search': ['query', 'limit'],
|
|
50
|
+
'/context': ['query', 'budgetTokens'],
|
|
51
|
+
'/selection': ['projectId', 'expectedRevision'],
|
|
52
|
+
};
|
|
53
|
+
/** En POST el proyecto viaja por query string: la cabecera de sesión del contrato está BLOCKED (PA01). */
|
|
54
|
+
const POST_PARAMS = ['project'];
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Administración de proyectos (ACP-07 F3, contrato §6.12).
|
|
58
|
+
*
|
|
59
|
+
* `fields` es por método y es la lista **exacta** de campos aceptados: lo no declarado se rechaza
|
|
60
|
+
* (`unknown-field`), como en el resto de la API. Ninguna de estas rutas es una herramienta del
|
|
61
|
+
* modelo: sin compuerta del host no se atienden (ver `adminGate`).
|
|
62
|
+
*/
|
|
63
|
+
const ADMIN_ROUTES = Object.freeze({
|
|
64
|
+
'/projects': {
|
|
65
|
+
methods: ['POST', 'PATCH'],
|
|
66
|
+
fields: { POST: ['name', 'path'], PATCH: ['id', 'name'] },
|
|
67
|
+
},
|
|
68
|
+
'/projects/archive': { methods: ['POST'], fields: { POST: ['id'] } },
|
|
69
|
+
'/projects/restore': { methods: ['POST'], fields: { POST: ['id'] } },
|
|
70
|
+
'/roots': { methods: ['POST'], fields: { POST: ['projectId', 'path'] } },
|
|
71
|
+
'/roots/remove': { methods: ['POST'], fields: { POST: ['rootId', 'projectId', 'path', 'allowEmpty'] } },
|
|
72
|
+
'/projects/register': { methods: ['POST'], fields: { POST: ['path', 'name'] } },
|
|
73
|
+
'/candidates': { methods: ['GET', 'HEAD'], fields: {}, query: ['project', 'path', 'maxDepth'] },
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
const localEmbedder = {
|
|
77
|
+
model: LOCAL_PROVIDER,
|
|
78
|
+
dim: DEFAULT_DIM,
|
|
79
|
+
embed: async (texts) => texts.map((text) => embedText(text)),
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
/** Escribe el sobre contractual (§5): {ok:true,data} o {ok:false,error}. Un cuerpo que supera el tope no se
|
|
83
|
+
* sirve: se responde 500 con el código público response-too-large, nunca un 200 con error dentro. */
|
|
84
|
+
function writeJson(res, status, body, limit) {
|
|
85
|
+
const text = JSON.stringify(body);
|
|
86
|
+
res.setHeader('content-type', 'application/json; charset=utf-8');
|
|
87
|
+
res.setHeader('cache-control', 'no-store');
|
|
88
|
+
res.setHeader('x-content-type-options', 'nosniff');
|
|
89
|
+
if (text.length > limit) {
|
|
90
|
+
res.statusCode = 500;
|
|
91
|
+
res.end(JSON.stringify({ ok: false, error: { code: 'response-too-large', message: 'la respuesta supera el tamaño máximo permitido', details: { limit } } }));
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
res.statusCode = status;
|
|
95
|
+
res.end(text);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Rechaza parámetros de query no declarados por la ruta (contrato §5: no se ignora nada en silencio). */
|
|
99
|
+
function queryParams(url, allowed, route) {
|
|
100
|
+
const unknown = [...new Set([...url.searchParams.keys()].filter((key) => !allowed.includes(key)))];
|
|
101
|
+
if (unknown.length > 0) {
|
|
102
|
+
throw new RagError('invalid-argument', `${route}: parámetro no declarado`, { details: { reason: 'unknown-parameter', parameters: unknown } });
|
|
103
|
+
}
|
|
104
|
+
const q = url.searchParams;
|
|
105
|
+
const limitRaw = q.get('limit');
|
|
106
|
+
const limit = limitRaw === null ? null : Number(limitRaw);
|
|
107
|
+
if (limit !== null && (!Number.isInteger(limit) || limit < 1)) {
|
|
108
|
+
throw new RagError('invalid-argument', 'limit inválido', { details: { reason: 'invalid-field', field: 'limit' } });
|
|
109
|
+
} if (limit !== null && limit > MAX_LIMIT) {
|
|
110
|
+
throw new RagError('invalid-argument', 'limit supera ' + MAX_LIMIT, { details: { reason: 'limit-too-large', field: 'limit', max: MAX_LIMIT } });
|
|
111
|
+
}
|
|
112
|
+
return {
|
|
113
|
+
project: q.get('project') || null,
|
|
114
|
+
limit,
|
|
115
|
+
cursor: q.get('cursor') || null,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Lee el cuerpo JSON de un POST: tamaño acotado, objeto plano y un error propio por cada caso. */
|
|
120
|
+
async function readJsonBody(req, limit = MAX_BODY) {
|
|
121
|
+
const chunks = [];
|
|
122
|
+
let size = 0;
|
|
123
|
+
if (req && typeof req[Symbol.asyncIterator] === 'function') {
|
|
124
|
+
for await (const chunk of req) {
|
|
125
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
|
|
126
|
+
size += buffer.length;
|
|
127
|
+
if (size > limit) throw new RagError('too-large', 'cuerpo de la petición demasiado grande', { details: { limit } });
|
|
128
|
+
chunks.push(buffer);
|
|
129
|
+
}
|
|
130
|
+
} else if (req && req.body !== undefined && req.body !== null) {
|
|
131
|
+
const raw = typeof req.body === 'string' ? req.body : JSON.stringify(req.body);
|
|
132
|
+
if (raw.length > limit) throw new RagError('too-large', 'cuerpo de la petición demasiado grande', { details: { limit } });
|
|
133
|
+
chunks.push(Buffer.from(raw));
|
|
134
|
+
}
|
|
135
|
+
const raw = Buffer.concat(chunks).toString('utf8').trim();
|
|
136
|
+
if (raw === '') throw new RagError('invalid-argument', 'cuerpo JSON obligatorio', { details: { reason: 'missing-body' } });
|
|
137
|
+
let data;
|
|
138
|
+
try {
|
|
139
|
+
data = JSON.parse(raw);
|
|
140
|
+
} catch {
|
|
141
|
+
throw new RagError('invalid-argument', 'cuerpo JSON inválido', { details: { reason: 'invalid-json' } });
|
|
142
|
+
}
|
|
143
|
+
if (data === null || typeof data !== 'object' || Array.isArray(data)) {
|
|
144
|
+
throw new RagError('invalid-argument', 'el cuerpo debe ser un objeto JSON', { details: { reason: 'invalid-body' } });
|
|
145
|
+
}
|
|
146
|
+
return data;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function assertKnownFields(body, allowed, route) {
|
|
150
|
+
const unknown = Object.keys(body).filter((key) => !allowed.includes(key));
|
|
151
|
+
if (unknown.length > 0) {
|
|
152
|
+
throw new RagError('invalid-argument', `${route}: campo no declarado`, { details: { reason: 'unknown-field', fields: unknown } });
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function requireQuery(body, route) {
|
|
157
|
+
if (!Object.prototype.hasOwnProperty.call(body, 'query')) {
|
|
158
|
+
throw new RagError('invalid-argument', `${route}: falta query`, { details: { reason: 'missing-field', field: 'query' } });
|
|
159
|
+
}
|
|
160
|
+
if (typeof body.query !== 'string') {
|
|
161
|
+
throw new RagError('invalid-argument', `${route}: query debe ser texto`, { details: { reason: 'invalid-field', field: 'query' } });
|
|
162
|
+
}
|
|
163
|
+
const query = body.query.trim();
|
|
164
|
+
if (query === '') {
|
|
165
|
+
throw new RagError('invalid-argument', `${route}: query vacío`, { details: { reason: 'invalid-field', field: 'query' } });
|
|
166
|
+
}
|
|
167
|
+
if (query.length > MAX_QUERY) {
|
|
168
|
+
throw new RagError('invalid-argument', `${route}: query supera ${MAX_QUERY} caracteres`, { details: { reason: 'query-too-long', field: 'query', max: MAX_QUERY } });
|
|
169
|
+
}
|
|
170
|
+
return query;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function searchPayload(body, config) {
|
|
174
|
+
assertKnownFields(body, POST_FIELDS['/search'], '/search');
|
|
175
|
+
const query = requireQuery(body, '/search');
|
|
176
|
+
const fallback = Number.isInteger(config?.search?.limit) ? config.search.limit : 8;
|
|
177
|
+
let limit = Math.min(fallback, MAX_SEARCH);
|
|
178
|
+
if (body.limit !== undefined) {
|
|
179
|
+
if (!Number.isInteger(body.limit) || body.limit < 1) {
|
|
180
|
+
throw new RagError('invalid-argument', '/search: limit inválido', { details: { reason: 'invalid-field', field: 'limit' } });
|
|
181
|
+
}
|
|
182
|
+
if (body.limit > MAX_SEARCH) {
|
|
183
|
+
throw new RagError('invalid-argument', `/search: limit supera ${MAX_SEARCH}`, { details: { reason: 'limit-too-large', field: 'limit', max: MAX_SEARCH } });
|
|
184
|
+
}
|
|
185
|
+
limit = body.limit;
|
|
186
|
+
}
|
|
187
|
+
return { query, limit };
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function contextPayload(body, config) {
|
|
191
|
+
assertKnownFields(body, POST_FIELDS['/context'], '/context');
|
|
192
|
+
const query = requireQuery(body, '/context');
|
|
193
|
+
const fallback = Number.isInteger(config?.context?.budgetTokens) ? config.context.budgetTokens : 2000;
|
|
194
|
+
let budgetTokens = fallback;
|
|
195
|
+
if (body.budgetTokens !== undefined) {
|
|
196
|
+
if (!Number.isInteger(body.budgetTokens) || body.budgetTokens < 1) {
|
|
197
|
+
throw new RagError('invalid-argument', '/context: budgetTokens inválido', { details: { reason: 'invalid-field', field: 'budgetTokens' } });
|
|
198
|
+
}
|
|
199
|
+
budgetTokens = body.budgetTokens;
|
|
200
|
+
}
|
|
201
|
+
return { query, budgetTokens };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** CR-1 (§6.2): el cuerpo declara el proyecto y la revisión que el cliente cree vigente. */
|
|
205
|
+
function selectionPayload(body) {
|
|
206
|
+
assertKnownFields(body, POST_FIELDS['/selection'], '/selection');
|
|
207
|
+
if (!Object.prototype.hasOwnProperty.call(body, 'projectId')) {
|
|
208
|
+
throw new RagError('invalid-argument', '/selection: falta projectId', { details: { reason: 'missing-field', field: 'projectId' } });
|
|
209
|
+
}
|
|
210
|
+
if (typeof body.projectId !== 'string' || !body.projectId.startsWith('prj_')) {
|
|
211
|
+
throw new RagError('invalid-argument', '/selection: projectId debe ser un identificador de proyecto', { details: { reason: 'invalid-field', field: 'projectId' } });
|
|
212
|
+
}
|
|
213
|
+
return { projectId: body.projectId, expectedRevision: body.expectedRevision };
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Proyecto efectivo de la petición, en este orden: el que pide el cliente, la selección persistida
|
|
218
|
+
* del perfil (CR-1) y, si sólo hay uno, ese. Con varios proyectos y sin selección se responde
|
|
219
|
+
* `scope-ambiguous`: nunca se elige uno «por defecto» a la callada.
|
|
220
|
+
*/
|
|
221
|
+
function projectView(db, requested, selection = null) {
|
|
222
|
+
// Sólo proyectos ACTIVOS: un proyecto archivado no es seleccionable ni consultable como activo,
|
|
223
|
+
// aunque alguien pida su id (aparece en `archived` del snapshot, que es donde se restaura).
|
|
224
|
+
const projects = db.prepare(`select id, name from projects where status='active' order by created_at`).all();
|
|
225
|
+
if (projects.length === 0) throw new RagError('project-not-authorized', 'el perfil no tiene proyectos');
|
|
226
|
+
let project = null;
|
|
227
|
+
if (requested) {
|
|
228
|
+
project = projects.find((p) => p.id === requested) ?? null;
|
|
229
|
+
if (!project) throw new RagError('project-not-authorized', 'proyecto desconocido o no autorizado', { details: { project: requested } });
|
|
230
|
+
} else if (selection) {
|
|
231
|
+
project = projects.find((p) => p.id === selection.projectId) ?? null;
|
|
232
|
+
// Una selección que apunta a un proyecto desaparecido o archivado no se usa en silencio: se
|
|
233
|
+
// ignora y se resuelve como si no hubiera selección.
|
|
234
|
+
}
|
|
235
|
+
if (!project) {
|
|
236
|
+
if (projects.length === 1) project = projects[0];
|
|
237
|
+
else throw new RagError('scope-ambiguous', 'varios proyectos: especifica project', { details: { candidates: projects.map((p) => p.id) } });
|
|
238
|
+
}
|
|
239
|
+
const roots = listRoots(db, { scopeKind: 'prj', scopeId: project.id });
|
|
240
|
+
const authorized = roots.filter((r) => r.state === 'authorized');
|
|
241
|
+
if (authorized.length === 0) throw new RagError('project-not-authorized', 'el proyecto no tiene raíces autorizadas', { details: { project: project.id } });
|
|
242
|
+
return { project, roots, authorized };
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function openStore(profileRoot, profileKey, scopeId) {
|
|
246
|
+
const store = openScopeStore({ profileRoot, profileKey, scope: { kind: 'prj', id: scopeId }, create: false });
|
|
247
|
+
if (!store) throw new RagError('store-not-initialized', 'el proyecto no tiene almacén', { details: { project: scopeId } });
|
|
248
|
+
return store;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function relUri(uri, roots) {
|
|
252
|
+
const norm = (v) => String(v).split(String.fromCharCode(92)).join('/').toLowerCase();
|
|
253
|
+
const target = norm(uri);
|
|
254
|
+
for (const root of roots) {
|
|
255
|
+
const base = norm(root.path);
|
|
256
|
+
if (target === base) return '.';
|
|
257
|
+
if (target.startsWith(base + '/')) return String(uri).slice(root.path.length + 1);
|
|
258
|
+
}
|
|
259
|
+
const parts = String(uri).split(String.fromCharCode(92)).join('/').split('/');
|
|
260
|
+
return parts[parts.length - 1] ?? String(uri);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function sourcesPage(db, { limit, cursor, roots = [] }) {
|
|
264
|
+
const take = Math.min(limit ?? 50, MAX_LIMIT);
|
|
265
|
+
const offset = cursor ? Number(cursor) : 0;
|
|
266
|
+
if (!Number.isInteger(offset) || offset < 0) throw new RagError('invalid-argument', 'cursor inválido');
|
|
267
|
+
const total = db.prepare('select count(*) n from sources').get().n;
|
|
268
|
+
const rows = db.prepare(`select s.id, s.uri, s.title, s.mime, s.bytes, s.indexed_at,
|
|
269
|
+
(select count(*) from chunks c where c.source_id = s.id) as chunk_count
|
|
270
|
+
from sources s order by s.uri limit ? offset ?`).all(take, offset);
|
|
271
|
+
return {
|
|
272
|
+
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 })),
|
|
273
|
+
total,
|
|
274
|
+
nextCursor: offset + rows.length < total ? String(offset + rows.length) : null,
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function auditHead(db) {
|
|
279
|
+
const row = db.prepare('select max(seq) seq from audit').get();
|
|
280
|
+
return { head: row?.seq ?? 0 };
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* Proyectos seleccionables del perfil: id, nombre y raíces autorizadas. Es lo que el panel necesita
|
|
285
|
+
* para ofrecer el cambio de proyecto (CR-1); sin esta lista el selector sólo podía mostrar el activo.
|
|
286
|
+
*
|
|
287
|
+
* F3 añade claves, no las cambia: `roots`/`authorized` siguen siendo el número de raíces autorizadas
|
|
288
|
+
* y la lista sigue conteniendo sólo proyectos activos. Lo nuevo es `status`, `total` (raíces
|
|
289
|
+
* registradas) y `selectable`, que ya tiene en cuenta si el proyecto puede usarse.
|
|
290
|
+
*/
|
|
291
|
+
function projectsIndex(db, currentId) {
|
|
292
|
+
const rows = db.prepare(`select p.id, p.name, p.status,
|
|
293
|
+
(select count(*) from roots r where r.scope_kind='prj' and r.scope_id=p.id) as total,
|
|
294
|
+
(select count(*) from roots r where r.scope_kind='prj' and r.scope_id=p.id and r.state='authorized') as roots
|
|
295
|
+
from projects p where p.status='active' order by p.created_at`).all();
|
|
296
|
+
return rows.map((row) => ({
|
|
297
|
+
id: row.id,
|
|
298
|
+
name: row.name,
|
|
299
|
+
status: row.status,
|
|
300
|
+
roots: Number(row.roots),
|
|
301
|
+
authorized: Number(row.roots),
|
|
302
|
+
total: Number(row.total),
|
|
303
|
+
current: row.id === currentId,
|
|
304
|
+
selectable: Number(row.roots) > 0,
|
|
305
|
+
}));
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** Proyectos archivados: no son seleccionables, pero el panel debe poder restaurarlos (F4). */
|
|
309
|
+
function archivedIndex(db) {
|
|
310
|
+
const rows = db.prepare(`select p.id, p.name, p.archived_at,
|
|
311
|
+
(select count(*) from roots r where r.scope_kind='prj' and r.scope_id=p.id) as total,
|
|
312
|
+
(select count(*) from roots r where r.scope_kind='prj' and r.scope_id=p.id and r.state='authorized') as roots
|
|
313
|
+
from projects p where p.status='archived' order by p.archived_at, p.id`).all();
|
|
314
|
+
return rows.map((row) => ({
|
|
315
|
+
id: row.id,
|
|
316
|
+
name: row.name,
|
|
317
|
+
status: 'archived',
|
|
318
|
+
roots: Number(row.roots),
|
|
319
|
+
total: Number(row.total),
|
|
320
|
+
archivedAt: row.archived_at === null ? null : Number(row.archived_at),
|
|
321
|
+
current: false,
|
|
322
|
+
selectable: false,
|
|
323
|
+
}));
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** Lo que esta versión de la API ofrece a la interfaz (F4). Es informativo y aditivo. */
|
|
327
|
+
function adminCapabilities() {
|
|
328
|
+
return {
|
|
329
|
+
projects: ['create', 'update', 'archive', 'restore'],
|
|
330
|
+
roots: ['add', 'remove'],
|
|
331
|
+
discovery: ['candidates', 'register'],
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* Raíces de los proyectos con su ruta. El recuento no basta para la interfaz: para retirar una raíz
|
|
337
|
+
* concreta hay que conocer su id y su ruta (ACP-07 F4). Es aditivo en `pa/1.3.0`.
|
|
338
|
+
*/
|
|
339
|
+
function rootsIndex(db) {
|
|
340
|
+
return listRoots(db)
|
|
341
|
+
.filter((row) => row.scope_kind === 'prj')
|
|
342
|
+
.map((row) => ({ scopeId: row.scope_id, id: row.id, path: row.path, state: row.state }));
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/** Vista resumida de un proyecto para las respuestas de administración. */
|
|
346
|
+
function projectAdminView(db, projectId) {
|
|
347
|
+
const project = getProject(db, projectId);
|
|
348
|
+
if (!project) throw new RagError('project-not-found', 'el proyecto no existe en este perfil', { details: { project: projectId } });
|
|
349
|
+
const roots = listRoots(db, { scopeKind: 'prj', scopeId: projectId });
|
|
350
|
+
return {
|
|
351
|
+
id: project.id,
|
|
352
|
+
name: project.name,
|
|
353
|
+
status: project.status,
|
|
354
|
+
createdAt: Number(project.created_at),
|
|
355
|
+
updatedAt: Number(project.updated_at),
|
|
356
|
+
archivedAt: project.archived_at === null ? null : Number(project.archived_at),
|
|
357
|
+
roots: {
|
|
358
|
+
total: roots.length,
|
|
359
|
+
authorized: roots.filter((r) => r.state === 'authorized').length,
|
|
360
|
+
},
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/**
|
|
365
|
+
* Claves de `audit.details` que se publican. El resto se descarta: los detalles pueden llevar rutas
|
|
366
|
+
* absolutas, ids de otros ámbitos o mensajes de error con trayectorias, y el historial es de lectura.
|
|
367
|
+
*/
|
|
368
|
+
const HISTORY_DETAIL_KEYS = Object.freeze(['sourceId', 'chunks', 'bytes', 'code', 'revision', 'replace', 'embedding', 'skipped']);
|
|
369
|
+
|
|
370
|
+
function safeDetails(raw) {
|
|
371
|
+
if (raw === null || raw === undefined) return null;
|
|
372
|
+
let parsed;
|
|
373
|
+
try { parsed = typeof raw === 'string' ? JSON.parse(raw) : raw; } catch { return null; }
|
|
374
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
|
|
375
|
+
const out = {};
|
|
376
|
+
for (const key of HISTORY_DETAIL_KEYS) {
|
|
377
|
+
if (Object.prototype.hasOwnProperty.call(parsed, key)) out[key] = parsed[key];
|
|
378
|
+
}
|
|
379
|
+
return Object.keys(out).length > 0 ? out : null;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/**
|
|
383
|
+
* Historial del proyecto ACTIVO, leído de SU almacén (`audit`), que es la cadena encadenada por hash.
|
|
384
|
+
* No hay forma de ver el historial de otro proyecto por esta ruta: cada proyecto tiene su propio
|
|
385
|
+
* fichero y sus propias filas, así que el filtro de ámbito es estructural, no un `where` que se pueda
|
|
386
|
+
* olvidar. `details` se filtra por lista blanca y `target` se relativiza a las raíces autorizadas.
|
|
387
|
+
*/
|
|
388
|
+
function historyPage(db, { limit, cursor, roots, scope }) {
|
|
389
|
+
const take = Math.min(limit ?? 50, MAX_LIMIT);
|
|
390
|
+
const before = cursor ? Number(cursor) : null;
|
|
391
|
+
if (before !== null && (!Number.isInteger(before) || before < 0)) {
|
|
392
|
+
throw new RagError('invalid-argument', 'cursor inválido', { details: { reason: 'invalid-field', field: 'cursor' } });
|
|
393
|
+
}
|
|
394
|
+
const total = db.prepare('select count(*) n from audit').get().n;
|
|
395
|
+
const rows = before === null
|
|
396
|
+
? db.prepare(`select seq, at, actor, tool, action, target, outcome, details, hash
|
|
397
|
+
from audit order by seq desc limit ?`).all(take)
|
|
398
|
+
: db.prepare(`select seq, at, actor, tool, action, target, outcome, details, hash
|
|
399
|
+
from audit where seq < ? order by seq desc limit ?`).all(before, take);
|
|
400
|
+
const entries = rows.map((row) => ({
|
|
401
|
+
seq: row.seq,
|
|
402
|
+
at: Number(row.at),
|
|
403
|
+
actor: row.actor,
|
|
404
|
+
tool: row.tool,
|
|
405
|
+
action: row.action,
|
|
406
|
+
target: row.target === null ? null : relUri(row.target, roots),
|
|
407
|
+
outcome: row.outcome,
|
|
408
|
+
hash: String(row.hash).slice(0, 16),
|
|
409
|
+
details: safeDetails(row.details),
|
|
410
|
+
}));
|
|
411
|
+
const oldest = entries.length > 0 ? entries[entries.length - 1].seq : null;
|
|
412
|
+
return {
|
|
413
|
+
scope,
|
|
414
|
+
total,
|
|
415
|
+
entries,
|
|
416
|
+
nextCursor: oldest !== null && oldest > 1 ? String(oldest) : null,
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/** Campos de administración: texto obligatorio u opcional, con tope y sin recortes silenciosos. */
|
|
421
|
+
function adminField(body, field, { route, max = MAX_NAME, required = true } = {}) {
|
|
422
|
+
const value = body ? body[field] : undefined;
|
|
423
|
+
if (value === undefined || value === null) {
|
|
424
|
+
if (!required) return null;
|
|
425
|
+
throw new RagError('invalid-argument', `${route}: falta el campo ${field}`, { details: { reason: 'missing-field', field } });
|
|
426
|
+
}
|
|
427
|
+
if (typeof value !== 'string') {
|
|
428
|
+
throw new RagError('invalid-argument', `${route}: ${field} debe ser texto`, { details: { reason: 'invalid-field', field } });
|
|
429
|
+
}
|
|
430
|
+
const text = value.trim();
|
|
431
|
+
if (text === '') {
|
|
432
|
+
throw new RagError('invalid-argument', `${route}: ${field} no puede estar vacío`, { details: { reason: 'invalid-field', field } });
|
|
433
|
+
}
|
|
434
|
+
if (text.length > max) {
|
|
435
|
+
throw new RagError('invalid-argument', `${route}: ${field} supera ${max} caracteres`, { details: { reason: 'field-too-long', field, max } });
|
|
436
|
+
}
|
|
437
|
+
return text;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
function adminProject(db, projectId) {
|
|
441
|
+
const project = getProject(db, projectId);
|
|
442
|
+
if (!project) {
|
|
443
|
+
throw new RagError('project-not-found', 'el proyecto no existe en este perfil', { details: { project: projectId } });
|
|
444
|
+
}
|
|
445
|
+
return project;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/**
|
|
449
|
+
* Toda escritura de administración deja su entrada en la cadena del registro. `addRoot` y
|
|
450
|
+
* `createProject` son operaciones de dominio que no auditan por sí solas: la ruta las envuelve en
|
|
451
|
+
* una transacción y añade el asiento, de modo que no existe escritura sin rastro.
|
|
452
|
+
*/
|
|
453
|
+
function auditedWrite(db, { action, detail, now, work }) {
|
|
454
|
+
return withTransaction(db, () => {
|
|
455
|
+
const result = work();
|
|
456
|
+
appendRegistryAudit(db, {
|
|
457
|
+
at: now, actor: 'human', sessionId: null, action, target: result.id, outcome: 'ok',
|
|
458
|
+
detail: typeof detail === 'function' ? detail(result) : detail,
|
|
459
|
+
});
|
|
460
|
+
return result;
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/**
|
|
465
|
+
* Descubrimiento de candidatos: lee el disco y **no escribe nada** (decisión D-02 y D-05). Exige una
|
|
466
|
+
* raíz autorizada para lectura, porque recorrer un árbol es leerlo.
|
|
467
|
+
*/
|
|
468
|
+
function candidateRootPath(db, { project: projectParam, path: pathParam }) {
|
|
469
|
+
if (pathParam) return pathParam;
|
|
470
|
+
const rows = projectParam
|
|
471
|
+
? db.prepare(`select path from roots where scope_kind='prj' and scope_id=? and state='authorized' order by path`).all(projectParam)
|
|
472
|
+
: db.prepare(`select path from roots where scope_kind='prj' and state='authorized' order by path`).all();
|
|
473
|
+
if (rows.length === 1) return rows[0].path;
|
|
474
|
+
throw new RagError('invalid-argument', 'indica path: hay varias raíces autorizadas', {
|
|
475
|
+
details: { reason: 'path-required', roots: rows.map((row) => row.path) },
|
|
476
|
+
});
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
function assertReadableRoot(db, path) {
|
|
480
|
+
if (typeof path !== 'string' || path.trim() === '') {
|
|
481
|
+
throw new RagError('invalid-argument', 'la ruta es obligatoria', { details: { reason: 'missing-field', field: 'path' } });
|
|
482
|
+
}
|
|
483
|
+
const trust = trustedRootFor(db, pathKeyFor(path));
|
|
484
|
+
if (!trust || trust.readAuthorization !== true) {
|
|
485
|
+
throw new RagError('scope-unresolved', 'la raíz no está autorizada para lectura', {
|
|
486
|
+
details: {
|
|
487
|
+
reason: 'project-not-authorized',
|
|
488
|
+
path,
|
|
489
|
+
command: `node bin/lifecode-rag.mjs trust add --path "${path}"`,
|
|
490
|
+
},
|
|
491
|
+
});
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
/**
|
|
496
|
+
* Despacho de la administración de proyectos (F3). Recibe el registro ya abierto y devuelve
|
|
497
|
+
* `{status, data}`; no escribe nada fuera de las operaciones de F1/F2 ni abre almacenes de ámbito:
|
|
498
|
+
* archivar, restaurar, renombrar y quitar una raíz no tocan `scopes/<id>/rag.sqlite3`.
|
|
499
|
+
*/
|
|
500
|
+
async function adminDispatch(db, { route, method, body, url, principal, now, profileRoot }) {
|
|
501
|
+
const integrity = () => verifyRegistryAudit(db);
|
|
502
|
+
|
|
503
|
+
if (route === '/projects' && method === 'POST') {
|
|
504
|
+
const name = adminField(body, 'name', { route });
|
|
505
|
+
const path = adminField(body, 'path', { route, max: MAX_PATH, required: false });
|
|
506
|
+
if (!path) {
|
|
507
|
+
// Proyecto sin raíz: existe en el registro y se le añaden raíces después. No es seleccionable
|
|
508
|
+
// hasta que tenga al menos una (lo refleja `selectable`).
|
|
509
|
+
const created = auditedWrite(db, {
|
|
510
|
+
action: 'project.create', detail: { name, path: null }, now,
|
|
511
|
+
work: () => createProject(db, { name, now }),
|
|
512
|
+
});
|
|
513
|
+
return {
|
|
514
|
+
status: 201,
|
|
515
|
+
data: { created: true, project: projectAdminView(db, created.id), integrity: integrity() },
|
|
516
|
+
};
|
|
517
|
+
}
|
|
518
|
+
const outcome = withTransaction(db, () => {
|
|
519
|
+
const existing = db.prepare(`select scope_id from roots where scope_kind='prj' and path_key=? limit 1`).get(pathKeyFor(path));
|
|
520
|
+
if (existing) return { created: false, projectId: existing.scope_id };
|
|
521
|
+
const project = createProject(db, { name, now });
|
|
522
|
+
const root = addRoot(db, { scopeKind: 'prj', scopeId: project.id, path, addedBy: 'human', now });
|
|
523
|
+
appendRegistryAudit(db, {
|
|
524
|
+
at: now, actor: 'human', sessionId: null, action: 'project.create', target: project.id,
|
|
525
|
+
outcome: 'ok', detail: { name: project.name, path: root.path, rootId: root.id },
|
|
526
|
+
});
|
|
527
|
+
return { created: true, projectId: project.id };
|
|
528
|
+
});
|
|
529
|
+
return {
|
|
530
|
+
status: outcome.created ? 201 : 200,
|
|
531
|
+
data: {
|
|
532
|
+
created: outcome.created,
|
|
533
|
+
project: projectAdminView(db, outcome.projectId),
|
|
534
|
+
integrity: integrity(),
|
|
535
|
+
},
|
|
536
|
+
};
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
if (route === '/projects' && method === 'PATCH') {
|
|
540
|
+
const id = adminField(body, 'id', { route });
|
|
541
|
+
const name = adminField(body, 'name', { route });
|
|
542
|
+
adminProject(db, id);
|
|
543
|
+
const result = updateProject(db, { id, name, now, actor: 'human' });
|
|
544
|
+
return {
|
|
545
|
+
status: 200,
|
|
546
|
+
data: { changed: result.changed, project: projectAdminView(db, id), integrity: integrity() },
|
|
547
|
+
};
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
if (route === '/projects/archive') {
|
|
551
|
+
const id = adminField(body, 'id', { route });
|
|
552
|
+
adminProject(db, id);
|
|
553
|
+
// Archivar el proyecto seleccionado mueve o retira la selección en la MISMA transacción (F1).
|
|
554
|
+
const result = archiveProjectWithSelection(db, {
|
|
555
|
+
projectId: id, now, actor: 'human', principal: principal ?? 'owner',
|
|
556
|
+
});
|
|
557
|
+
return {
|
|
558
|
+
status: 200,
|
|
559
|
+
data: {
|
|
560
|
+
changed: result.changed,
|
|
561
|
+
project: projectAdminView(db, id),
|
|
562
|
+
selection: result.selection,
|
|
563
|
+
selectionChange: result.selectionChange,
|
|
564
|
+
integrity: integrity(),
|
|
565
|
+
},
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
if (route === '/projects/restore') {
|
|
570
|
+
const id = adminField(body, 'id', { route });
|
|
571
|
+
adminProject(db, id);
|
|
572
|
+
const result = restoreProject(db, { id, now, actor: 'human' });
|
|
573
|
+
return {
|
|
574
|
+
status: 200,
|
|
575
|
+
data: { changed: result.changed, project: projectAdminView(db, id), integrity: integrity() },
|
|
576
|
+
};
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
if (route === '/roots') {
|
|
580
|
+
const projectId = adminField(body, 'projectId', { route });
|
|
581
|
+
adminProject(db, projectId);
|
|
582
|
+
const path = adminField(body, 'path', { route, max: MAX_PATH });
|
|
583
|
+
const root = auditedWrite(db, {
|
|
584
|
+
action: 'root.add', detail: { scopeId: projectId, path }, now,
|
|
585
|
+
work: () => addRoot(db, { scopeKind: 'prj', scopeId: projectId, path, addedBy: 'human', now }),
|
|
586
|
+
});
|
|
587
|
+
return {
|
|
588
|
+
status: 201,
|
|
589
|
+
data: {
|
|
590
|
+
root: { id: root.id, path: root.path, state: 'authorized' },
|
|
591
|
+
project: projectAdminView(db, projectId),
|
|
592
|
+
integrity: integrity(),
|
|
593
|
+
},
|
|
594
|
+
};
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
if (route === '/roots/remove') {
|
|
598
|
+
const rootId = adminField(body, 'rootId', { route, required: false });
|
|
599
|
+
const projectId = adminField(body, 'projectId', { route, required: false });
|
|
600
|
+
const path = adminField(body, 'path', { route, max: MAX_PATH, required: false });
|
|
601
|
+
if (body && body.allowEmpty !== undefined && typeof body.allowEmpty !== 'boolean') {
|
|
602
|
+
throw new RagError('invalid-argument', '/roots/remove: allowEmpty debe ser booleano', { details: { reason: 'invalid-field', field: 'allowEmpty' } });
|
|
603
|
+
}
|
|
604
|
+
let target = rootId;
|
|
605
|
+
if (!target) {
|
|
606
|
+
if (!projectId || !path) {
|
|
607
|
+
throw new RagError('invalid-argument', '/roots/remove: indica rootId o projectId y path', {
|
|
608
|
+
details: { reason: 'missing-field', fields: ['rootId', 'projectId+path'] },
|
|
609
|
+
});
|
|
610
|
+
}
|
|
611
|
+
const row = db.prepare(`select id from roots where scope_kind='prj' and scope_id=? and path_key=?`)
|
|
612
|
+
.get(projectId, pathKeyFor(path));
|
|
613
|
+
if (!row) throw new RagError('source-not-found', 'la raíz no existe en este proyecto', { details: { project: projectId, path } });
|
|
614
|
+
target = row.id;
|
|
615
|
+
}
|
|
616
|
+
const result = removeRoot(db, { rootId: target, allowEmpty: body?.allowEmpty === true, now, actor: 'human' });
|
|
617
|
+
return {
|
|
618
|
+
status: 200,
|
|
619
|
+
data: {
|
|
620
|
+
removed: result.removed,
|
|
621
|
+
project: projectAdminView(db, result.removed.scopeId),
|
|
622
|
+
integrity: integrity(),
|
|
623
|
+
},
|
|
624
|
+
};
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
if (route === '/candidates') {
|
|
628
|
+
const path = candidateRootPath(db, {
|
|
629
|
+
project: url.searchParams.get('project'),
|
|
630
|
+
path: url.searchParams.get('path'),
|
|
631
|
+
});
|
|
632
|
+
assertReadableRoot(db, path);
|
|
633
|
+
const maxDepthRaw = url.searchParams.get('maxDepth');
|
|
634
|
+
const maxDepth = maxDepthRaw === null ? undefined : Number(maxDepthRaw);
|
|
635
|
+
if (maxDepth !== undefined && (!Number.isInteger(maxDepth) || maxDepth < 0 || maxDepth > 8)) {
|
|
636
|
+
throw new RagError('invalid-argument', 'maxDepth debe ser un entero entre 0 y 8', { details: { reason: 'invalid-field', field: 'maxDepth', max: 8 } });
|
|
637
|
+
}
|
|
638
|
+
const scan = scanWorkspace(path, maxDepth === undefined ? {} : { maxDepth });
|
|
639
|
+
const registered = new Set(db.prepare(`select path_key from roots where scope_kind='prj'`).all().map((row) => row.path_key));
|
|
640
|
+
return {
|
|
641
|
+
status: 200,
|
|
642
|
+
data: {
|
|
643
|
+
root: scan.root,
|
|
644
|
+
total: scan.projects.length,
|
|
645
|
+
truncated: scan.truncated,
|
|
646
|
+
candidates: scan.projects.map((row) => ({
|
|
647
|
+
path: row.path,
|
|
648
|
+
name: row.name,
|
|
649
|
+
manifestName: row.manifestName ?? null,
|
|
650
|
+
type: row.type,
|
|
651
|
+
indicators: row.indicators,
|
|
652
|
+
depth: row.depth,
|
|
653
|
+
registered: registered.has(row.pathKey),
|
|
654
|
+
action: registered.has(row.pathKey) ? null : 'register-project',
|
|
655
|
+
})),
|
|
656
|
+
skipped: scan.skipped,
|
|
657
|
+
},
|
|
658
|
+
};
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
if (route === '/projects/register') {
|
|
662
|
+
const path = adminField(body, 'path', { route, max: MAX_PATH });
|
|
663
|
+
const name = adminField(body, 'name', { route, required: false });
|
|
664
|
+
assertReadableRoot(db, path);
|
|
665
|
+
// Registrar es un acto explícito y separado del descubrimiento: es la persona quien lo pide.
|
|
666
|
+
const result = registerDiscoveredProject(db, {
|
|
667
|
+
path, ...(name ? { name } : {}), type: 'unknown', source: 'api', now,
|
|
668
|
+
});
|
|
669
|
+
return {
|
|
670
|
+
status: result.created ? 201 : 200,
|
|
671
|
+
data: {
|
|
672
|
+
created: result.created,
|
|
673
|
+
registeredRoot: result.registeredRoot ?? null,
|
|
674
|
+
error: result.error ?? null,
|
|
675
|
+
project: projectAdminView(db, result.projectId),
|
|
676
|
+
integrity: integrity(),
|
|
677
|
+
},
|
|
678
|
+
};
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
return failDispatch(route);
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
function failDispatch(route) {
|
|
685
|
+
throw new RagError('not-found', `ruta PA desconocida: ${route}`);
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
/**
|
|
689
|
+
* @param {{profileRoot: string, profileKey?: string, env?: object, now?: () => number,
|
|
690
|
+
* maxBody?: number, authorize?: (request: {headers: object, method: string, url: URL}) =>
|
|
691
|
+
* Promise<{ok: boolean, peer?: {id?: string, principal?: {kind?: string}}, status?: number,
|
|
692
|
+
* code?: string, message?: string}> | {ok: boolean, peer?: object}} options
|
|
693
|
+
*
|
|
694
|
+
* `authorize` es la compuerta del anfitrión (PA01). Sin ella el núcleo sigue sirviendo tal cual —es
|
|
695
|
+
* su contrato de independencia—, pero el adaptador de DSH **siempre** pasa una, y cuando el host no
|
|
696
|
+
* ofrece servicio de conexión pasa una que niega: la ausencia de compuerta no se degrada a «abierto».
|
|
697
|
+
*
|
|
698
|
+
* ACP-07 F3: `authorize` es además lo que habilita la administración. Sin compuerta, las rutas
|
|
699
|
+
* `/projects*`, `/roots*` y `/candidates` responden 503 `authorization-unavailable`: no existe
|
|
700
|
+
* una versión «abierta» de la administración para un host que no identifica a nadie.
|
|
701
|
+
*/
|
|
702
|
+
export function createPaHandler({
|
|
703
|
+
profileRoot, profileKey = 'desktop', env = process.env, now = () => Date.now(),
|
|
704
|
+
maxBody = MAX_BODY, authorize = null,
|
|
705
|
+
} = {}) {
|
|
706
|
+
// Respondedores ligados al tope de esta instancia: la sobrecarga se mide por respuesta.
|
|
707
|
+
const respond = (res, status, payload) => writeJson(res, status, { ok: true, data: payload }, maxBody);
|
|
708
|
+
const failWith = (res, status, code, message, details) => writeJson(res, status, { ok: false, error: { code, message, ...(details ? { details } : {}) } }, maxBody);
|
|
709
|
+
const methodNotAllowed = (res, allowed, message) => failWith(res, 405, 'method-not-allowed', message, { reason: 'method-not-allowed', allow: allowed });
|
|
710
|
+
|
|
711
|
+
if (typeof profileRoot !== 'string' || !profileRoot) throw new TypeError('profileRoot obligatorio');
|
|
712
|
+
|
|
713
|
+
return async function paHandler(req, res) {
|
|
714
|
+
const started = now();
|
|
715
|
+
try {
|
|
716
|
+
const url = new URL(req.url, 'http://localhost');
|
|
717
|
+
if (!url.pathname.startsWith(PA_PREFIX)) return failWith(res, 404, 'not-found', 'ruta fuera de la API PA');
|
|
718
|
+
const route = url.pathname.slice(PA_PREFIX.length).replace(/\/+$/, '') || '/';
|
|
719
|
+
const method = (req.method || 'GET').toUpperCase();
|
|
720
|
+
|
|
721
|
+
// PA01: la compuerta va ANTES de resolver la ruta. Sin credencial del host no se distingue una
|
|
722
|
+
// ruta existente de una inventada: 401/403 y nada más.
|
|
723
|
+
let peer = null;
|
|
724
|
+
if (authorize) {
|
|
725
|
+
let decision;
|
|
726
|
+
try {
|
|
727
|
+
decision = await authorize({ headers: req.headers ?? {}, method, url });
|
|
728
|
+
} catch {
|
|
729
|
+
return failWith(res, 503, 'authorization-unavailable', 'la compuerta de autenticación del host falló');
|
|
730
|
+
}
|
|
731
|
+
if (!decision || decision.ok !== true) {
|
|
732
|
+
const status = decision?.status === 401 ? 401 : (decision?.status ?? 403);
|
|
733
|
+
const code = decision?.code ?? (status === 401 ? 'unauthenticated' : 'authorization-unavailable');
|
|
734
|
+
return failWith(res, status, code, decision?.message ?? 'la petición no está autenticada por el host');
|
|
735
|
+
}
|
|
736
|
+
peer = decision.peer ?? null;
|
|
737
|
+
}
|
|
738
|
+
const principal = peer && peer.principal && peer.principal.kind ? String(peer.principal.kind) : null;
|
|
739
|
+
|
|
740
|
+
const { config } = resolveConfig({ dataRoot: profileRoot, profileKey });
|
|
741
|
+
|
|
742
|
+
// /config no depende de proyecto: se responde antes de abrir el registro.
|
|
743
|
+
if (route === '/config') {
|
|
744
|
+
if (method !== 'GET' && method !== 'HEAD') return methodNotAllowed(res, ['GET', 'HEAD'], 'la configuración se lee con GET');
|
|
745
|
+
queryParams(url, [], route);
|
|
746
|
+
return respond(res, 200, { mode: 'api', service: 'ok', version: PA_VERSION, config, profile: { key: profileKey } });
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
if (route === '/actions') {
|
|
750
|
+
return failWith(res, 403, 'approval-required', 'las operaciones de escritura requieren aprobación del host', {
|
|
751
|
+
tools: ['lifecode_rag_ingest', 'lifecode_rag_forget', 'lifecode_rag_reindex'],
|
|
752
|
+
});
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
let params;
|
|
756
|
+
let payload = null;
|
|
757
|
+
const adminSpec = Object.prototype.hasOwnProperty.call(ADMIN_ROUTES, route) ? ADMIN_ROUTES[route] : null;
|
|
758
|
+
let adminBody = null;
|
|
759
|
+
if (adminSpec) {
|
|
760
|
+
// Administración (F3): métodos declarados, sin campos de más y con la compuerta del host ya
|
|
761
|
+
// resuelta. Si el host no ofrece compuerta, la administración no existe (503).
|
|
762
|
+
if (!adminSpec.methods.includes(method)) {
|
|
763
|
+
return methodNotAllowed(res, adminSpec.methods, `${route} se llama con ${adminSpec.methods.join(' o ')}`);
|
|
764
|
+
}
|
|
765
|
+
if (!authorize) {
|
|
766
|
+
return failWith(res, 503, 'authorization-unavailable',
|
|
767
|
+
'la administración de proyectos exige la compuerta del host');
|
|
768
|
+
}
|
|
769
|
+
params = queryParams(url, adminSpec.query ?? [], route);
|
|
770
|
+
if (method !== 'GET' && method !== 'HEAD') {
|
|
771
|
+
adminBody = await readJsonBody(req, maxBody);
|
|
772
|
+
assertKnownFields(adminBody, adminSpec.fields[method] ?? [], route);
|
|
773
|
+
}
|
|
774
|
+
} else if (Object.prototype.hasOwnProperty.call(POST_FIELDS, route)) {
|
|
775
|
+
// LE-RAG-11: /search y /context son POST con cuerpo JSON. GET sobre ellas se rechaza: una
|
|
776
|
+
// sola forma de llamar a cada ruta (D-01).
|
|
777
|
+
if (method !== 'POST') return methodNotAllowed(res, ['POST'], `${route} se consulta con POST y cuerpo JSON`);
|
|
778
|
+
params = queryParams(url, POST_PARAMS, route);
|
|
779
|
+
const body = await readJsonBody(req, maxBody);
|
|
780
|
+
payload = route === '/search' ? searchPayload(body, config)
|
|
781
|
+
: route === '/context' ? contextPayload(body, config)
|
|
782
|
+
: selectionPayload(body);
|
|
783
|
+
} else if (Object.prototype.hasOwnProperty.call(GET_ROUTES, route)) {
|
|
784
|
+
if (method !== 'GET' && method !== 'HEAD') return methodNotAllowed(res, ['GET', 'HEAD'], 'la API PA es de solo lectura');
|
|
785
|
+
params = queryParams(url, GET_ROUTES[route], route);
|
|
786
|
+
} else {
|
|
787
|
+
return failWith(res, 404, 'not-found', `ruta PA desconocida: ${route}`);
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
let registry;
|
|
791
|
+
try {
|
|
792
|
+
registry = openRegistry({ root: profileRoot, create: false, now: now() });
|
|
793
|
+
} catch (error) {
|
|
794
|
+
if (error instanceof RagError && error.code === 'store-not-initialized') {
|
|
795
|
+
return failWith(res, 503, 'registry-unavailable', 'el perfil no tiene registro Project-Aware');
|
|
796
|
+
}
|
|
797
|
+
throw error;
|
|
798
|
+
}
|
|
799
|
+
const db = registry.db ?? registry;
|
|
800
|
+
try {
|
|
801
|
+
// ACP-07 F3: la administración no depende del proyecto activo (crear, archivar, restaurar o
|
|
802
|
+
// descubrir candidatos funcionan aunque no haya selección o el proyecto esté archivado).
|
|
803
|
+
if (adminSpec) {
|
|
804
|
+
const result = await adminDispatch(db, {
|
|
805
|
+
route, method, body: adminBody, url, principal: principal ?? 'owner', now: now(), profileRoot,
|
|
806
|
+
});
|
|
807
|
+
return respond(res, result.status, result.data);
|
|
808
|
+
}
|
|
809
|
+
// CR-1: la selección se escribe en el registro del perfil, con CAS sobre la revisión.
|
|
810
|
+
if (route === '/selection') {
|
|
811
|
+
const applied = applySelection(db, {
|
|
812
|
+
projectId: payload.projectId,
|
|
813
|
+
expectedRevision: payload.expectedRevision,
|
|
814
|
+
selectedBy: 'human',
|
|
815
|
+
source: 'explicit',
|
|
816
|
+
principal: principal ?? 'owner',
|
|
817
|
+
now: now(),
|
|
818
|
+
});
|
|
819
|
+
const selected = db.prepare('select id, name from projects where id = ?').get(applied.selection.projectId);
|
|
820
|
+
return respond(res, 200, {
|
|
821
|
+
changed: applied.changed,
|
|
822
|
+
selection: applied.selection,
|
|
823
|
+
project: selected ? { id: selected.id, name: selected.name } : null,
|
|
824
|
+
});
|
|
825
|
+
}
|
|
826
|
+
const selection = readSelection(db);
|
|
827
|
+
// El snapshot es el único sitio que puede responder con un perfil *sin* proyecto activo: es
|
|
828
|
+
// el retrato que el panel necesita para ofrecer restaurar o registrar. El resto de rutas
|
|
829
|
+
// siguen exigiendo un proyecto resoluble, igual que antes.
|
|
830
|
+
let view = null;
|
|
831
|
+
try {
|
|
832
|
+
view = projectView(db, params.project, selection);
|
|
833
|
+
} catch (error) {
|
|
834
|
+
const emptyProfile = route === '/' || route === '/snapshot';
|
|
835
|
+
const recoverable = error instanceof RagError
|
|
836
|
+
&& (error.code === 'project-not-authorized' || error.code === 'scope-ambiguous');
|
|
837
|
+
const anyActive = listProjects(db, { status: 'active' }).projects.length > 0;
|
|
838
|
+
if (!emptyProfile || !recoverable || anyActive) throw error;
|
|
839
|
+
}
|
|
840
|
+
if (!view) {
|
|
841
|
+
return respond(res, 200, {
|
|
842
|
+
mode: 'api', service: 'ok', asOf: started, version: PA_VERSION,
|
|
843
|
+
project: null,
|
|
844
|
+
selection,
|
|
845
|
+
projects: projectsIndex(db, null),
|
|
846
|
+
archived: archivedIndex(db),
|
|
847
|
+
roots: rootsIndex(db),
|
|
848
|
+
auth: peer ? { principal: principal ?? 'owner' } : null,
|
|
849
|
+
scopes: [],
|
|
850
|
+
libraries: [],
|
|
851
|
+
sources: { rows: [], total: 0, nextCursor: null },
|
|
852
|
+
audit: { head: 0 },
|
|
853
|
+
config: { strategy: config.search.strategy, limit: config.search.limit, diversity: config.search.diversity },
|
|
854
|
+
capabilities: adminCapabilities(),
|
|
855
|
+
});
|
|
856
|
+
}
|
|
857
|
+
const { project, roots, authorized } = view;
|
|
858
|
+
const store = openStore(profileRoot, profileKey, project.id);
|
|
859
|
+
const sdb = store.db ?? store;
|
|
860
|
+
const scope = { id: project.id, kind: 'prj', name: project.name };
|
|
861
|
+
try {
|
|
862
|
+
if (route === '/history') {
|
|
863
|
+
// Historial del proyecto activo: sale de SU almacén (no de otro), con la cadena verificada.
|
|
864
|
+
const page = historyPage(sdb, { limit: params.limit, cursor: params.cursor, roots: authorized, scope });
|
|
865
|
+
return respond(res, 200, { mode: 'api', ...page, integrity: verifyAuditChain(sdb) });
|
|
866
|
+
}
|
|
867
|
+
if (route === '/' || route === '/snapshot') {
|
|
868
|
+
return respond(res, 200, {
|
|
869
|
+
mode: 'api', service: 'ok', asOf: started, version: PA_VERSION,
|
|
870
|
+
project: { id: project.id, name: project.name },
|
|
871
|
+
selection,
|
|
872
|
+
projects: projectsIndex(db, project.id),
|
|
873
|
+
archived: archivedIndex(db),
|
|
874
|
+
roots: rootsIndex(db),
|
|
875
|
+
auth: peer ? { principal: principal ?? 'owner' } : null,
|
|
876
|
+
scopes: [{ kind: 'prj', id: project.id, name: project.name, roots: roots.length, authorized: authorized.length }],
|
|
877
|
+
libraries: [],
|
|
878
|
+
sources: sourcesPage(sdb, { limit: params.limit, cursor: params.cursor, roots: authorized }),
|
|
879
|
+
audit: auditHead(sdb),
|
|
880
|
+
config: { strategy: config.search.strategy, limit: config.search.limit, diversity: config.search.diversity },
|
|
881
|
+
capabilities: adminCapabilities(),
|
|
882
|
+
});
|
|
883
|
+
}
|
|
884
|
+
if (route === '/search') {
|
|
885
|
+
const result = await search(sdb, {
|
|
886
|
+
query: payload.query, limit: payload.limit, config, embedder: localEmbedder,
|
|
887
|
+
strategy: config.search.strategy, diversity: config.search.diversity, record: false, now: now(),
|
|
888
|
+
});
|
|
889
|
+
const rows = result.results ?? [];
|
|
890
|
+
return respond(res, 200, {
|
|
891
|
+
mode: config.search.strategy,
|
|
892
|
+
elapsedMs: result.elapsedMs ?? null,
|
|
893
|
+
results: rows.map((r) => ({
|
|
894
|
+
chunkKey: r.chunkKey,
|
|
895
|
+
sourceId: r.sourceId,
|
|
896
|
+
uri: relUri(r.uri, authorized),
|
|
897
|
+
title: r.title,
|
|
898
|
+
heading: r.heading ?? null,
|
|
899
|
+
ordinal: r.ordinal,
|
|
900
|
+
rrf: r.rrf ?? null,
|
|
901
|
+
score: r.score ?? null,
|
|
902
|
+
snippet: r.snippet ?? null,
|
|
903
|
+
scopeId: scope.id,
|
|
904
|
+
scopeKind: scope.kind,
|
|
905
|
+
scopeName: scope.name,
|
|
906
|
+
})),
|
|
907
|
+
scopes: [{ ...scope, results: rows.length }],
|
|
908
|
+
});
|
|
909
|
+
}
|
|
910
|
+
if (route === '/context') {
|
|
911
|
+
const result = await search(sdb, {
|
|
912
|
+
query: payload.query, limit: Math.min(config.search.limit * 2, MAX_SEARCH), config,
|
|
913
|
+
embedder: localEmbedder, strategy: config.search.strategy, record: false, now: now(),
|
|
914
|
+
});
|
|
915
|
+
const assembled = await assembleContextAsync({
|
|
916
|
+
results: result.results ?? [], config, embedder: localEmbedder, maxTokens: payload.budgetTokens,
|
|
917
|
+
});
|
|
918
|
+
const citations = (assembled.citations ?? []).map((citation) => ({ ...citation, uri: relUri(citation.uri, authorized) }));
|
|
919
|
+
return respond(res, 200, {
|
|
920
|
+
mode: config.search.strategy,
|
|
921
|
+
elapsedMs: result.elapsedMs ?? null,
|
|
922
|
+
text: assembled.text ?? '',
|
|
923
|
+
citations,
|
|
924
|
+
tokens: assembled.tokens ?? null,
|
|
925
|
+
truncated: assembled.truncated ?? null,
|
|
926
|
+
considered: assembled.considered ?? null,
|
|
927
|
+
scopes: [{ ...scope, results: citations.length }],
|
|
928
|
+
});
|
|
929
|
+
}
|
|
930
|
+
return failWith(res, 404, 'not-found', `ruta PA desconocida: ${route}`);
|
|
931
|
+
} finally {
|
|
932
|
+
store.close?.();
|
|
933
|
+
}
|
|
934
|
+
} finally {
|
|
935
|
+
(db.close ?? (() => {})).call(db);
|
|
936
|
+
}
|
|
937
|
+
} catch (error) {
|
|
938
|
+
if (error instanceof RagError) {
|
|
939
|
+
// Un solo mapa (lib/errors.mjs): un código de autorización no puede acabar en 500 por no estar
|
|
940
|
+
// en una tabla local. El status sale de HTTP_STATUS; lo no clasificado cae a 500 explícitamente.
|
|
941
|
+
return failWith(res, httpStatusFor(error.code), error.code, error.message, error.details);
|
|
942
|
+
}
|
|
943
|
+
return failWith(res, 500, 'internal-error', 'error interno del transporte PA');
|
|
944
|
+
}
|
|
945
|
+
};
|
|
946
|
+
}
|