@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/tags.mjs
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Etiquetas normalizadas (resolución v2.1 §2): minúsculas, recortadas y con forma estable.
|
|
3
|
+
* Se validan antes de tocar el almacén para que una etiqueta inválida no deje media ingesta.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { RagError } from './errors.mjs';
|
|
7
|
+
|
|
8
|
+
export const TAG_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
|
9
|
+
export const MAX_TAGS_PER_SOURCE = 20;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* @param {unknown} raw
|
|
13
|
+
* @returns {string}
|
|
14
|
+
*/
|
|
15
|
+
export function normalizeTag(raw) {
|
|
16
|
+
if (typeof raw !== 'string') throw new RagError('invalid-tag', 'la etiqueta debe ser texto');
|
|
17
|
+
const tag = raw.trim().toLowerCase();
|
|
18
|
+
if (!TAG_PATTERN.test(tag)) {
|
|
19
|
+
throw new RagError('invalid-tag', `etiqueta inválida: ${JSON.stringify(raw)}`, {
|
|
20
|
+
details: { tag: raw, pattern: TAG_PATTERN.source },
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
return tag;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* @param {unknown} raw
|
|
28
|
+
* @param {{max?:number}=} options
|
|
29
|
+
* @returns {string[]}
|
|
30
|
+
*/
|
|
31
|
+
export function normalizeTags(raw, { max = MAX_TAGS_PER_SOURCE } = {}) {
|
|
32
|
+
if (raw === undefined || raw === null) return [];
|
|
33
|
+
const list = Array.isArray(raw) ? raw : [raw];
|
|
34
|
+
const tags = [];
|
|
35
|
+
for (const item of list) {
|
|
36
|
+
const tag = normalizeTag(item);
|
|
37
|
+
if (!tags.includes(tag)) tags.push(tag);
|
|
38
|
+
}
|
|
39
|
+
if (tags.length > max) {
|
|
40
|
+
throw new RagError('invalid-tag', `demasiadas etiquetas: ${tags.length} (máximo ${max})`, {
|
|
41
|
+
details: { count: tags.length, max },
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
return tags;
|
|
45
|
+
}
|
package/lib/tools.mjs
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Herramientas públicas `lifecode_rag_*` (M5 + PA3).
|
|
3
|
+
*
|
|
4
|
+
* Este módulo es núcleo puro: no importa nada del harness. Recibe los servicios que necesita
|
|
5
|
+
* (`approval`, `workingDirectory`, `env`) y devuelve definiciones listas para `ctx.tools.register`.
|
|
6
|
+
*
|
|
7
|
+
* PA3: ninguna herramienta abre un almacén por su cuenta. Todas pasan por
|
|
8
|
+
* `withAuthorizedContext`, que valida identidad, perfil, selección, grants y ámbitos antes de
|
|
9
|
+
* entregar conexiones ya autorizadas. El contrato público v0.1 no cambia: mismos nombres,
|
|
10
|
+
* parámetros y campos de salida.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { RagError } from './errors.mjs';
|
|
14
|
+
import { createEmbedder } from './embedders.mjs';
|
|
15
|
+
import { effectiveConfig } from './config-resolve.mjs';
|
|
16
|
+
import { withAuthorizedContext } from './exec-context.mjs';
|
|
17
|
+
import {
|
|
18
|
+
contextScopes, forgetInProject, getAcross, listProject, planIngest, reindexProject, runIngest, searchScopes,
|
|
19
|
+
} from './scope-ops.mjs';
|
|
20
|
+
|
|
21
|
+
const NAMESPACE = 'lifecode_rag_';
|
|
22
|
+
|
|
23
|
+
/** Esquema de objeto laxo: el pipeline valida el valor devuelto contra esto. */
|
|
24
|
+
const OBJECT = Object.freeze({ type: 'object' });
|
|
25
|
+
|
|
26
|
+
function textBlock(text) {
|
|
27
|
+
return [{ type: 'text', text }];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function jsonBlock(value) {
|
|
31
|
+
return textBlock(JSON.stringify(value));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** aprueba una operación sensible o falla en cerrado. Sólo `allowed-once` es un permiso. */
|
|
35
|
+
async function requireApproval(services, exec, toolName, reason, deniedCode = 'approval-required') {
|
|
36
|
+
const approval = services.approval;
|
|
37
|
+
if (!approval || typeof approval.request !== 'function') {
|
|
38
|
+
throw new RagError('approval-unavailable', 'el host no ofrece aprobaciones; la operación se rechaza', {
|
|
39
|
+
details: { tool: toolName },
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
const outcome = await approval.request({
|
|
43
|
+
agent: exec.agent,
|
|
44
|
+
toolName,
|
|
45
|
+
callId: exec.callId,
|
|
46
|
+
reason,
|
|
47
|
+
displayReason: { en: reason },
|
|
48
|
+
signal: exec.signal,
|
|
49
|
+
});
|
|
50
|
+
if (outcome !== 'allowed-once') {
|
|
51
|
+
throw new RagError(deniedCode, 'la operación necesita aprobación humana', {
|
|
52
|
+
details: { tool: toolName, outcome },
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Egress: un proveedor remoto envía texto del usuario a un tercero. Sólo se permite con aprobación por
|
|
59
|
+
* llamada; si el host no ofrece aprobaciones, la operación se rechaza (fail closed).
|
|
60
|
+
*/
|
|
61
|
+
async function requireEgress(services, exec, toolName, embedder) {
|
|
62
|
+
if (embedder.kind !== 'semantic') return false;
|
|
63
|
+
await requireApproval(services, exec, toolName,
|
|
64
|
+
`Enviar texto a un proveedor remoto de embeddings (${embedder.model}); la aprobación vale sólo para esta llamada`,
|
|
65
|
+
'egress-denied');
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function embedderFor(services, config) {
|
|
70
|
+
return services.embedder ?? createEmbedder(config, { fetchImpl: services.fetch, credential: services.credential });
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function sessionCwd(services, exec) {
|
|
74
|
+
const directory = services.workingDirectory;
|
|
75
|
+
if (!directory || typeof directory.ensure !== 'function') return null;
|
|
76
|
+
try {
|
|
77
|
+
return await directory.ensure(exec.agent, exec.signal);
|
|
78
|
+
} catch {
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function normalizePaths(value) {
|
|
84
|
+
const list = Array.isArray(value) ? value : [value];
|
|
85
|
+
const paths = list.map((item) => String(item ?? '').trim()).filter((item) => item !== '');
|
|
86
|
+
if (paths.length === 0) throw new RagError('invalid-argument', 'indica al menos una ruta');
|
|
87
|
+
return paths;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function scopeLabel(scope) {
|
|
91
|
+
return `${scope.kind === 'prj' ? 'proyecto' : 'biblioteca'} ${scope.name} (${scope.id})`;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Construye las siete definiciones.
|
|
96
|
+
* @param {{config: object, root?: string, services: object}} options
|
|
97
|
+
*/
|
|
98
|
+
export function createToolDefinitions({ config = effectiveConfig().config, services = {} } = {}) {
|
|
99
|
+
const now = () => (typeof services.now === 'function' ? services.now() : Date.now());
|
|
100
|
+
const definitions = [];
|
|
101
|
+
// Número de chunks del último `forget`, para el texto de respuesta: el valor devuelto respeta el
|
|
102
|
+
// contrato v0.1 y no expone `chunks`.
|
|
103
|
+
let renderForget = null;
|
|
104
|
+
|
|
105
|
+
definitions.push({
|
|
106
|
+
name: `${NAMESPACE}ingest`,
|
|
107
|
+
description: 'Indexa ficheros de texto locales en la base de conocimiento de LifeCode RAG. Acepta ficheros o directorios del proyecto actual (omite .git, node_modules, dist, build y coverage); fuera del proyecto exige aprobación humana. Formatos: md, txt, html, json, jsonl, csv, tsv, yaml, xml, logs y código.',
|
|
108
|
+
parameters: {
|
|
109
|
+
type: 'object',
|
|
110
|
+
properties: {
|
|
111
|
+
paths: { oneOf: [{ type: 'string' }, { type: 'array', items: { type: 'string' } }] },
|
|
112
|
+
collection: { type: 'string' },
|
|
113
|
+
tags: { type: 'array', items: { type: 'string' } },
|
|
114
|
+
force: { type: 'boolean' },
|
|
115
|
+
},
|
|
116
|
+
required: ['paths'],
|
|
117
|
+
additionalProperties: false,
|
|
118
|
+
},
|
|
119
|
+
async execute(args, exec) {
|
|
120
|
+
const requested = normalizePaths(args.paths);
|
|
121
|
+
return withAuthorizedContext({ services, exec }, async (ctx) => {
|
|
122
|
+
// expandir y clasificar antes de abrir el almacén del proyecto: una ruta protegida o un
|
|
123
|
+
// enlace duro rechazan la llamada entera sin efectos.
|
|
124
|
+
const cwd = ctx.cwd ?? await sessionCwd(services, exec);
|
|
125
|
+
const { scope, classified } = planIngest(ctx, { requested, cwd, config });
|
|
126
|
+
const outside = classified.filter((item) => item.outsideRoots).map((item) => item.realPath);
|
|
127
|
+
if (outside.length > 0) {
|
|
128
|
+
await requireApproval(services, exec, `${NAMESPACE}ingest`,
|
|
129
|
+
`Indexar ${outside.length} ruta(s) fuera de ${scopeLabel(scope)}: ${outside.join(', ')}`, 'path-not-allowed');
|
|
130
|
+
}
|
|
131
|
+
const embedder = embedderFor(services, config);
|
|
132
|
+
await requireEgress(services, exec, `${NAMESPACE}ingest`, embedder);
|
|
133
|
+
const result = await runIngest(ctx, {
|
|
134
|
+
scope,
|
|
135
|
+
files: classified.map((item) => item.realPath),
|
|
136
|
+
collection: args.collection ?? 'default',
|
|
137
|
+
tags: Array.isArray(args.tags) ? args.tags.map(String) : [],
|
|
138
|
+
force: args.force === true,
|
|
139
|
+
now: now(),
|
|
140
|
+
config,
|
|
141
|
+
embedder,
|
|
142
|
+
actor: 'model',
|
|
143
|
+
});
|
|
144
|
+
return { ...result, approvedOutside: outside.length > 0 };
|
|
145
|
+
});
|
|
146
|
+
},
|
|
147
|
+
output: {
|
|
148
|
+
schema: OBJECT,
|
|
149
|
+
render(args, value) {
|
|
150
|
+
const lines = [
|
|
151
|
+
`ingeridos: ${value.ingested.length}, omitidos: ${value.skipped.length}, errores: ${value.errors.length}`,
|
|
152
|
+
...value.ingested.map((item) => `+ ${item.uri} (${item.chunks} chunks)`),
|
|
153
|
+
...value.errors.map((item) => `! ${item.path}: ${item.code} — ${item.message}`),
|
|
154
|
+
];
|
|
155
|
+
return textBlock(lines.join('\n'));
|
|
156
|
+
},
|
|
157
|
+
},
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
definitions.push({
|
|
161
|
+
name: `${NAMESPACE}search`,
|
|
162
|
+
description: 'Busca en la base de conocimiento local (híbrido léxico + vectores) y devuelve fragmentos compactos con su fuente y posición. Usa lifecode_rag_context para obtener el contexto listo para citar.',
|
|
163
|
+
parameters: {
|
|
164
|
+
type: 'object',
|
|
165
|
+
properties: {
|
|
166
|
+
query: { type: 'string' },
|
|
167
|
+
limit: { type: 'number' },
|
|
168
|
+
collection: { type: 'string' },
|
|
169
|
+
tags: { type: 'array', items: { type: 'string' } },
|
|
170
|
+
tagMode: { type: 'string', enum: ['any', 'all'] },
|
|
171
|
+
},
|
|
172
|
+
required: ['query'],
|
|
173
|
+
additionalProperties: false,
|
|
174
|
+
},
|
|
175
|
+
async execute(args, exec) {
|
|
176
|
+
return withAuthorizedContext({ services, exec }, async (ctx) => {
|
|
177
|
+
const embedder = embedderFor(services, config);
|
|
178
|
+
await requireEgress(services, exec, `${NAMESPACE}search`, embedder);
|
|
179
|
+
const result = await searchScopes(ctx, {
|
|
180
|
+
query: args.query,
|
|
181
|
+
limit: args.limit,
|
|
182
|
+
collection: args.collection,
|
|
183
|
+
tags: Array.isArray(args.tags) ? args.tags.map(String) : undefined,
|
|
184
|
+
tagMode: args.tagMode ?? 'any',
|
|
185
|
+
// Único punto donde la configuración llega a la herramienta; `context` no pasa este valor.
|
|
186
|
+
diversity: config.search.diversity,
|
|
187
|
+
config,
|
|
188
|
+
embedder,
|
|
189
|
+
now: now(),
|
|
190
|
+
});
|
|
191
|
+
return {
|
|
192
|
+
results: result.results.map((row) => ({
|
|
193
|
+
chunkKey: row.chunkKey,
|
|
194
|
+
sourceId: row.sourceId,
|
|
195
|
+
uri: row.uri,
|
|
196
|
+
title: row.sourceTitle || row.title,
|
|
197
|
+
heading: row.heading,
|
|
198
|
+
ordinal: row.ordinal,
|
|
199
|
+
rrf: row.rrf,
|
|
200
|
+
snippet: row.snippet,
|
|
201
|
+
})),
|
|
202
|
+
mode: result.mode,
|
|
203
|
+
elapsedMs: result.elapsedMs,
|
|
204
|
+
};
|
|
205
|
+
});
|
|
206
|
+
},
|
|
207
|
+
output: { schema: OBJECT, render: (args, value) => jsonBlock(value) },
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
definitions.push({
|
|
211
|
+
name: `${NAMESPACE}context`,
|
|
212
|
+
description: 'Ensambla contexto listo para el modelo: fragmentos diversificados (MMR), dentro de un presupuesto de tokens, con citas numeradas verificables. Consulta el proyecto y las bibliotecas autorizadas.',
|
|
213
|
+
parameters: {
|
|
214
|
+
type: 'object',
|
|
215
|
+
properties: {
|
|
216
|
+
query: { type: 'string' },
|
|
217
|
+
budgetTokens: { type: 'number' },
|
|
218
|
+
maxChunks: { type: 'number' },
|
|
219
|
+
collection: { type: 'string' },
|
|
220
|
+
tags: { type: 'array', items: { type: 'string' } },
|
|
221
|
+
},
|
|
222
|
+
required: ['query'],
|
|
223
|
+
additionalProperties: false,
|
|
224
|
+
},
|
|
225
|
+
async execute(args, exec) {
|
|
226
|
+
return withAuthorizedContext({ services, exec }, async (ctx) => {
|
|
227
|
+
const embedder = embedderFor(services, config);
|
|
228
|
+
await requireEgress(services, exec, `${NAMESPACE}context`, embedder);
|
|
229
|
+
const assembled = await contextScopes(ctx, {
|
|
230
|
+
query: args.query,
|
|
231
|
+
budgetTokens: args.budgetTokens,
|
|
232
|
+
maxChunks: args.maxChunks,
|
|
233
|
+
collection: args.collection,
|
|
234
|
+
tags: Array.isArray(args.tags) ? args.tags.map(String) : undefined,
|
|
235
|
+
config,
|
|
236
|
+
embedder,
|
|
237
|
+
now: now(),
|
|
238
|
+
});
|
|
239
|
+
// Proyección al contrato v0.1: cinco campos y citas sin metadatos internos de ámbito.
|
|
240
|
+
return {
|
|
241
|
+
text: assembled.text,
|
|
242
|
+
citations: assembled.citations.map((citation) => ({
|
|
243
|
+
n: citation.n,
|
|
244
|
+
chunkKey: citation.chunkKey,
|
|
245
|
+
sourceId: citation.sourceId,
|
|
246
|
+
uri: citation.uri,
|
|
247
|
+
title: citation.title,
|
|
248
|
+
heading: citation.heading,
|
|
249
|
+
ordinal: citation.ordinal,
|
|
250
|
+
charStart: citation.charStart,
|
|
251
|
+
charEnd: citation.charEnd,
|
|
252
|
+
})),
|
|
253
|
+
tokens: assembled.tokens,
|
|
254
|
+
truncated: assembled.truncated,
|
|
255
|
+
considered: assembled.considered,
|
|
256
|
+
};
|
|
257
|
+
});
|
|
258
|
+
},
|
|
259
|
+
output: {
|
|
260
|
+
schema: OBJECT,
|
|
261
|
+
render(args, value) {
|
|
262
|
+
if (value.text === '') return textBlock('Sin resultados para el presupuesto solicitado.');
|
|
263
|
+
const sources = value.citations.map((citation) => `[${citation.n}] ${citation.uri}${citation.heading ? ` › ${citation.heading}` : ''} (${citation.chunkKey})`);
|
|
264
|
+
return textBlock(`${value.text}\n\nFuentes:\n${sources.join('\n')}`);
|
|
265
|
+
},
|
|
266
|
+
},
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
definitions.push({
|
|
270
|
+
name: `${NAMESPACE}get`,
|
|
271
|
+
description: 'Lee una fuente indexada y sus fragmentos completos, para verificar una cita o revisar el original normalizado. La referencia debe ser inequívoca dentro de los ámbitos autorizados.',
|
|
272
|
+
parameters: {
|
|
273
|
+
type: 'object',
|
|
274
|
+
properties: {
|
|
275
|
+
ref: { type: 'string' },
|
|
276
|
+
limit: { type: 'number' },
|
|
277
|
+
},
|
|
278
|
+
required: ['ref'],
|
|
279
|
+
additionalProperties: false,
|
|
280
|
+
},
|
|
281
|
+
async execute(args, exec) {
|
|
282
|
+
return withAuthorizedContext({ services, exec }, (ctx) => {
|
|
283
|
+
const found = getAcross(ctx, { ref: args.ref, limit: args.limit });
|
|
284
|
+
return { source: found.source, chunks: found.chunks };
|
|
285
|
+
});
|
|
286
|
+
},
|
|
287
|
+
output: { schema: OBJECT, render: (args, value) => jsonBlock(value) },
|
|
288
|
+
});
|
|
289
|
+
|
|
290
|
+
definitions.push({
|
|
291
|
+
name: `${NAMESPACE}list`,
|
|
292
|
+
description: 'Lista las fuentes indexadas del proyecto actual con filtros por colección o etiqueta y paginación.',
|
|
293
|
+
parameters: {
|
|
294
|
+
type: 'object',
|
|
295
|
+
properties: {
|
|
296
|
+
collection: { type: 'string' },
|
|
297
|
+
tag: { type: 'string' },
|
|
298
|
+
limit: { type: 'number' },
|
|
299
|
+
offset: { type: 'number' },
|
|
300
|
+
},
|
|
301
|
+
additionalProperties: false,
|
|
302
|
+
},
|
|
303
|
+
async execute(args, exec) {
|
|
304
|
+
return withAuthorizedContext({ services, exec }, (ctx) => listProject(ctx, {
|
|
305
|
+
collection: args.collection,
|
|
306
|
+
tag: args.tag,
|
|
307
|
+
limit: args.limit,
|
|
308
|
+
offset: args.offset,
|
|
309
|
+
}));
|
|
310
|
+
},
|
|
311
|
+
output: { schema: OBJECT, render: (args, value) => jsonBlock(value) },
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
definitions.push({
|
|
315
|
+
name: `${NAMESPACE}forget`,
|
|
316
|
+
description: 'Elimina una fuente del proyecto actual y todo lo indexado de ella. Operación destructiva: exige aprobación humana con el objetivo exacto y nunca borra una fuente de una biblioteca.',
|
|
317
|
+
parameters: {
|
|
318
|
+
type: 'object',
|
|
319
|
+
properties: { ref: { type: 'string' } },
|
|
320
|
+
required: ['ref'],
|
|
321
|
+
additionalProperties: false,
|
|
322
|
+
},
|
|
323
|
+
async execute(args, exec) {
|
|
324
|
+
return withAuthorizedContext({ services, exec }, async (ctx) => {
|
|
325
|
+
const pending = forgetInProject(ctx, { ref: args.ref, exec, now: now() });
|
|
326
|
+
await requireApproval(services, exec, `${NAMESPACE}forget`,
|
|
327
|
+
`Eliminar la fuente ${pending.preview.id} (${pending.preview.uri}) de ${scopeLabel(pending.scope)} y todo su índice`);
|
|
328
|
+
const removed = await pending.run();
|
|
329
|
+
// Proyección al contrato v0.1; `chunks` es útil pero no forma parte del contrato público, así
|
|
330
|
+
// que el render no puede leerlo del valor devuelto: se guarda sólo para el texto de respuesta.
|
|
331
|
+
renderForget = Number(removed.chunks ?? 0);
|
|
332
|
+
return { forgotten: true, sourceId: removed.sourceId, uri: removed.uri };
|
|
333
|
+
});
|
|
334
|
+
},
|
|
335
|
+
output: { schema: OBJECT, render: (args, value) => textBlock(`eliminada ${value.uri} (${renderForget ?? 0} chunks)`) },
|
|
336
|
+
});
|
|
337
|
+
|
|
338
|
+
definitions.push({
|
|
339
|
+
name: `${NAMESPACE}reindex`,
|
|
340
|
+
description: 'Reconstruye el índice de texto, los vectores o ambos del proyecto actual. Exige aprobación humana porque recalcula el índice completo; no reindexa bibliotecas ajenas.',
|
|
341
|
+
parameters: {
|
|
342
|
+
type: 'object',
|
|
343
|
+
properties: { operation: { type: 'string', enum: ['fts', 'vectors', 'all'] } },
|
|
344
|
+
required: ['operation'],
|
|
345
|
+
additionalProperties: false,
|
|
346
|
+
},
|
|
347
|
+
async execute(args, exec) {
|
|
348
|
+
return withAuthorizedContext({ services, exec }, async (ctx) => {
|
|
349
|
+
const pending = reindexProject(ctx, { operation: args.operation, config, now: now(), exec });
|
|
350
|
+
await requireApproval(services, exec, `${NAMESPACE}reindex`,
|
|
351
|
+
`Reindexar (${args.operation}) ${scopeLabel(pending.scope)}`);
|
|
352
|
+
const result = await pending.run();
|
|
353
|
+
return {
|
|
354
|
+
operation: result.operation,
|
|
355
|
+
...(result.fts ? { rebuiltChunks: result.fts.rebuiltChunks } : {}),
|
|
356
|
+
...(result.vectors ? { rebuiltSources: result.vectors.sources } : {}),
|
|
357
|
+
};
|
|
358
|
+
});
|
|
359
|
+
},
|
|
360
|
+
output: { schema: OBJECT, render: (args, value) => jsonBlock(value) },
|
|
361
|
+
});
|
|
362
|
+
|
|
363
|
+
return definitions;
|
|
364
|
+
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Trusted Workspace Roots (auto-discovery 01).
|
|
3
|
+
*
|
|
4
|
+
* Un *workspace confiable* es una carpeta que una persona autoriza una sola vez para que
|
|
5
|
+
* LifeCode RAG descubra los proyectos que contiene. La confianza y la autorización de lectura
|
|
6
|
+
* son decisiones separadas y explícitas:
|
|
7
|
+
*
|
|
8
|
+
* - `state: 'trusted'` → se puede escanear (descubrir) dentro de la raíz.
|
|
9
|
+
* - `readAuthorization` → los proyectos descubiertos pueden registrarse como ámbitos de
|
|
10
|
+
* lectura (raíz `authorized`) sin una segunda aprobación.
|
|
11
|
+
*
|
|
12
|
+
* Descubrir NUNCA es indexar ni leer documentos: el escaneo sólo comprueba la existencia de
|
|
13
|
+
* indicadores y, como mucho, lee `package.json` para clasificar el tipo de proyecto.
|
|
14
|
+
*
|
|
15
|
+
* La confianza se guarda en la tabla `meta` del registro (clave `trusted_roots`), en orden
|
|
16
|
+
* estable y sin tocar el esquema. Es idempotente por `pathKey`.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { RagError } from './errors.mjs';
|
|
20
|
+
import { appendRegistryAudit, getMeta, setMeta } from './registry.mjs';
|
|
21
|
+
import { assertRootStructure, inspectRoot } from './roots-structure.mjs';
|
|
22
|
+
|
|
23
|
+
export const TRUST_META_KEY = 'trusted_roots';
|
|
24
|
+
const MAX_TRUSTED_ROOTS = 32;
|
|
25
|
+
|
|
26
|
+
function normalizeTrust(entry) {
|
|
27
|
+
return {
|
|
28
|
+
path: entry.path,
|
|
29
|
+
pathKey: entry.pathKey,
|
|
30
|
+
state: entry.state === 'revoked' ? 'revoked' : 'trusted',
|
|
31
|
+
readAuthorization: entry.readAuthorization === true,
|
|
32
|
+
addedAt: Number(entry.addedAt) || 0,
|
|
33
|
+
addedBy: entry.addedBy === 'host' ? 'host' : 'human',
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function listTrustedRoots(db) {
|
|
38
|
+
const raw = getMeta(db, TRUST_META_KEY);
|
|
39
|
+
if (!raw) return [];
|
|
40
|
+
let parsed;
|
|
41
|
+
try {
|
|
42
|
+
parsed = JSON.parse(raw);
|
|
43
|
+
} catch {
|
|
44
|
+
return [];
|
|
45
|
+
}
|
|
46
|
+
if (!Array.isArray(parsed)) return [];
|
|
47
|
+
return parsed.map(normalizeTrust).filter((entry) => typeof entry.pathKey === 'string' && entry.pathKey !== '');
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function writeTrustedRoots(db, roots) {
|
|
51
|
+
const ordered = [...roots]
|
|
52
|
+
.sort((left, right) => left.pathKey.localeCompare(right.pathKey))
|
|
53
|
+
.map(normalizeTrust);
|
|
54
|
+
setMeta(db, TRUST_META_KEY, JSON.stringify(ordered));
|
|
55
|
+
return ordered;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function audit(db, { at, actor, action, target, outcome = 'ok', detail }) {
|
|
59
|
+
try {
|
|
60
|
+
appendRegistryAudit(db, {
|
|
61
|
+
at,
|
|
62
|
+
actor: actor === 'host' ? 'host' : 'human',
|
|
63
|
+
sessionId: null,
|
|
64
|
+
action,
|
|
65
|
+
target,
|
|
66
|
+
outcome,
|
|
67
|
+
detail: JSON.stringify(detail ?? {}),
|
|
68
|
+
});
|
|
69
|
+
} catch {
|
|
70
|
+
// La auditoría del registro no debe convertir una operación válida en un fallo silencioso;
|
|
71
|
+
// los rechazos de autorización sí se auditan en resolve/exec-context.
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Añade (o actualiza) un workspace confiable. Idempotente: repetir la misma ruta no duplica,
|
|
77
|
+
* no cambia `addedAt` y devuelve `created: false`.
|
|
78
|
+
*/
|
|
79
|
+
export function addTrustedRoot(db, {
|
|
80
|
+
path, readAuthorization = true, addedBy = 'human', now = Date.now(),
|
|
81
|
+
} = {}) {
|
|
82
|
+
if (addedBy !== 'human' && addedBy !== 'host') {
|
|
83
|
+
throw new RagError('invalid-argument', 'sólo una persona o el host pueden confiar un workspace');
|
|
84
|
+
}
|
|
85
|
+
const info = assertRootStructure(inspectRoot(path));
|
|
86
|
+
const roots = listTrustedRoots(db);
|
|
87
|
+
const existing = roots.find((entry) => entry.pathKey === info.key);
|
|
88
|
+
if (existing) {
|
|
89
|
+
if (existing.state === 'trusted' && existing.readAuthorization === (readAuthorization === true)) {
|
|
90
|
+
return { created: false, changed: false, root: existing };
|
|
91
|
+
}
|
|
92
|
+
const updated = roots.map((entry) => (entry.pathKey === info.key
|
|
93
|
+
? { ...entry, state: 'trusted', readAuthorization: readAuthorization === true }
|
|
94
|
+
: entry));
|
|
95
|
+
const [root] = writeTrustedRoots(db, updated).filter((entry) => entry.pathKey === info.key);
|
|
96
|
+
audit(db, {
|
|
97
|
+
at: now, actor: addedBy, action: 'trust.update', target: info.key,
|
|
98
|
+
detail: { path: info.canonical, readAuthorization: readAuthorization === true },
|
|
99
|
+
});
|
|
100
|
+
return { created: false, changed: true, root };
|
|
101
|
+
}
|
|
102
|
+
if (roots.length >= MAX_TRUSTED_ROOTS) {
|
|
103
|
+
throw new RagError('invalid-argument', 'demasiados workspaces confiables', {
|
|
104
|
+
details: { limit: MAX_TRUSTED_ROOTS },
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
const record = normalizeTrust({
|
|
108
|
+
path: info.canonical,
|
|
109
|
+
pathKey: info.key,
|
|
110
|
+
state: 'trusted',
|
|
111
|
+
readAuthorization: readAuthorization === true,
|
|
112
|
+
addedAt: now,
|
|
113
|
+
addedBy,
|
|
114
|
+
});
|
|
115
|
+
writeTrustedRoots(db, [...roots, record]);
|
|
116
|
+
audit(db, {
|
|
117
|
+
at: now, actor: addedBy, action: 'trust.add', target: info.key,
|
|
118
|
+
detail: { path: info.canonical, readAuthorization: record.readAuthorization },
|
|
119
|
+
});
|
|
120
|
+
return { created: true, changed: true, root: record };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Revoca la confianza sin tocar los proyectos ya registrados ni sus almacenes. */
|
|
124
|
+
export function removeTrustedRoot(db, { path, removedBy = 'human', now = Date.now() } = {}) {
|
|
125
|
+
const info = inspectRoot(path);
|
|
126
|
+
const roots = listTrustedRoots(db);
|
|
127
|
+
const existing = roots.find((entry) => entry.pathKey === info.key);
|
|
128
|
+
if (!existing) return { changed: false, root: null };
|
|
129
|
+
const updated = roots.map((entry) => (entry.pathKey === info.key ? { ...entry, state: 'revoked' } : entry));
|
|
130
|
+
writeTrustedRoots(db, updated);
|
|
131
|
+
audit(db, {
|
|
132
|
+
at: now, actor: removedBy, action: 'trust.remove', target: info.key,
|
|
133
|
+
detail: { path: info.canonical },
|
|
134
|
+
});
|
|
135
|
+
return { changed: true, root: { ...existing, state: 'revoked' } };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** El workspace confiable activo más específico que contiene la clave dada. */
|
|
139
|
+
export function trustedRootFor(db, key) {
|
|
140
|
+
if (!key) return null;
|
|
141
|
+
let best = null;
|
|
142
|
+
for (const entry of listTrustedRoots(db)) {
|
|
143
|
+
if (entry.state !== 'trusted') continue;
|
|
144
|
+
const inside = key === entry.pathKey || key.startsWith(`${entry.pathKey}/`);
|
|
145
|
+
if (!inside) continue;
|
|
146
|
+
if (!best || entry.pathKey.length > best.pathKey.length) best = entry;
|
|
147
|
+
}
|
|
148
|
+
return best;
|
|
149
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* LE-RAG-03 · Contexto de configuración de los trabajadores (scheduler, automatización).
|
|
3
|
+
*
|
|
4
|
+
* Resolución en tres niveles, sin romper contratos existentes:
|
|
5
|
+
* 1. `config` explícita inyectada por el anfitrión (la que ya resolvió el plugin).
|
|
6
|
+
* 2. `dataRoot` + `profileKey` explícitos → resolvedor único (perfil > global > defaults).
|
|
7
|
+
* 3. compatibilidad histórica: el `config.json` del `root` que recibe el trabajador.
|
|
8
|
+
*
|
|
9
|
+
* El nivel 3 se conserva a propósito: hay consumidores legacy que operan sobre un almacén con su
|
|
10
|
+
* propia configuración y no deben heredar la del perfil.
|
|
11
|
+
*/
|
|
12
|
+
import { loadConfig } from './paths.mjs';
|
|
13
|
+
import { resolveConfig, resolveProfileKey } from './config-resolve.mjs';
|
|
14
|
+
|
|
15
|
+
export function workerConfig({ config = null, dataRoot = null, profileKey = null, root = null, env = process.env } = {}) {
|
|
16
|
+
if (config) return { config, source: 'injected' };
|
|
17
|
+
if (dataRoot) {
|
|
18
|
+
return { config: resolveConfig({ dataRoot, profileKey: profileKey ?? resolveProfileKey(env) }).config, source: 'resolver' };
|
|
19
|
+
}
|
|
20
|
+
if (!root) throw new TypeError('workerConfig necesita config, dataRoot o root');
|
|
21
|
+
return { config: loadConfig(root, env).config, source: 'root' };
|
|
22
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,68 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
"
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@designerbyron/lifecode-rag",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"main": "index.js",
|
|
6
|
+
"description": "Recuperación local, independiente y auditable para el ecosistema LifeCode (plugin de DeepSeek Harness)",
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"author": "Byron Vanegas (designerbyron)",
|
|
9
|
+
"keywords": ["lifecode", "rag", "retrieval", "deepseek-harness", "dsh-plugin", "sqlite", "local-first"],
|
|
10
|
+
"engines": {
|
|
11
|
+
"node": "\u003e=22.5.0",
|
|
12
|
+
"dsh": "\u003e=0.2.2-rc.3 \u003c0.3.0"
|
|
13
|
+
},
|
|
14
|
+
"dsh": {
|
|
15
|
+
"manifestVersion": 1,
|
|
16
|
+
"bundle": {
|
|
17
|
+
"patch": "./cordis.patch.yml"
|
|
18
|
+
},
|
|
19
|
+
"client": {
|
|
20
|
+
"platform": "web",
|
|
21
|
+
"immediately": true
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"icon": "./icon.svg",
|
|
25
|
+
"files": [
|
|
26
|
+
"index.js",
|
|
27
|
+
"client.js",
|
|
28
|
+
"lib/",
|
|
29
|
+
"bin/",
|
|
30
|
+
"icon.svg",
|
|
31
|
+
"cordis.patch.yml",
|
|
32
|
+
"README.md",
|
|
33
|
+
"LICENSE",
|
|
34
|
+
"docs/CONTRATO-v0.1.md",
|
|
35
|
+
"docs/ARCHITECTURE-v0.2.md",
|
|
36
|
+
"docs/PROJECT-AWARE-ARCHITECTURE.md",
|
|
37
|
+
"docs/PROJECT-AWARE-DATA-CONTRACT.md",
|
|
38
|
+
"docs/PROJECT-AWARE-ERROR-CONTRACT.md",
|
|
39
|
+
"docs/PROJECT-AWARE-SESSION-CONTRACT.md",
|
|
40
|
+
"docs/PA-UI-0-API-CONTRACT.md",
|
|
41
|
+
"docs/AUTO-DISCOVERY.md",
|
|
42
|
+
"docs/AUTOMATION-POLICIES.md",
|
|
43
|
+
"docs/EMBEDDING-PROVIDERS.md",
|
|
44
|
+
"docs/OBSERVABILITY.md",
|
|
45
|
+
"docs/PERFORMANCE-BUDGETS.md",
|
|
46
|
+
"docs/WORKSPACE-API.md"
|
|
47
|
+
],
|
|
48
|
+
"publishConfig": {
|
|
49
|
+
"access": "public"
|
|
50
|
+
},
|
|
51
|
+
"exports": {
|
|
52
|
+
".": "./index.js",
|
|
53
|
+
"./client": "./client.js",
|
|
54
|
+
"./package.json": "./package.json",
|
|
55
|
+
"./lib/*.mjs": "./lib/*.mjs",
|
|
56
|
+
"./lib/*": "./lib/*.mjs"
|
|
57
|
+
},
|
|
58
|
+
"scripts": {
|
|
59
|
+
"test": "node --test --test-concurrency=1",
|
|
60
|
+
"test:hermetic": "node tools/hermetic.mjs",
|
|
61
|
+
"check": "node tools/check.mjs",
|
|
62
|
+
"bench": "node tools/benchmark.mjs",
|
|
63
|
+
"bench:harness": "node tools/harness.mjs",
|
|
64
|
+
"demo": "node demo/server.mjs",
|
|
65
|
+
"screenshots": "node tools/screenshots.mjs"
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|