@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/paths.mjs
ADDED
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rutas y configuración de LifeCode RAG.
|
|
3
|
+
*
|
|
4
|
+
* El almacén es **propio y separado**: por defecto `$DSH_HOME/lifecode-rag`, o lo que diga
|
|
5
|
+
* `LIFECODE_RAG_ROOT`. Nunca se deriva del directorio de trabajo ni del almacén del Skill Center.
|
|
6
|
+
* La configuración es un fichero opcional; si falta, se usan los valores por defecto **sin escribir**.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { existsSync, mkdirSync, openSync, closeSync, fsyncSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
10
|
+
import { homedir } from 'node:os';
|
|
11
|
+
import { isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
12
|
+
|
|
13
|
+
import { RagError } from './errors.mjs';
|
|
14
|
+
|
|
15
|
+
/** Configuración por defecto. Cambiarla exige revisar los límites de las pruebas de aceptación. */
|
|
16
|
+
export const DEFAULT_CONFIG = Object.freeze({
|
|
17
|
+
maxFileBytes: 2_000_000,
|
|
18
|
+
maxFilesPerIngest: 200,
|
|
19
|
+
chunk: Object.freeze({ targetChars: 1_200, maxChars: 2_000, overlapChars: 120 }),
|
|
20
|
+
context: Object.freeze({ budgetTokens: 2_000, maxChunks: 12, mmrLambda: 0.7 }),
|
|
21
|
+
search: Object.freeze({
|
|
22
|
+
limit: 8,
|
|
23
|
+
maxLimit: 50,
|
|
24
|
+
maxVectorScan: 20_000,
|
|
25
|
+
strategy: 'hybrid',
|
|
26
|
+
rrfK: 60,
|
|
27
|
+
// Con el proveedor léxico (local-hash-v1) la lista "semántica" aporta ruido;
|
|
28
|
+
// a 10.000 chunks, 1:1 baja Recall@5 a 0,692 mientras 3:1 la mantiene en 1,000.
|
|
29
|
+
// Con un proveedor neural aprobado, el operador debe medir y ajustar (1:1 como punto de partida).
|
|
30
|
+
weights: Object.freeze({ lexical: 3, semantic: 1 }),
|
|
31
|
+
minScore: 0,
|
|
32
|
+
maxPerSource: 0,
|
|
33
|
+
diversity: 'fragment',
|
|
34
|
+
}),
|
|
35
|
+
embedding: Object.freeze({ provider: 'local-hash-v1', dim: 256, remote: null }),
|
|
36
|
+
audit: Object.freeze({ exportJsonl: true }),
|
|
37
|
+
roots: Object.freeze({ extra: Object.freeze([]) }),
|
|
38
|
+
metrics: Object.freeze({ enabled: true, retentionDays: 90 }),
|
|
39
|
+
automation: Object.freeze({
|
|
40
|
+
enabled: false,
|
|
41
|
+
intervalMs: 60_000,
|
|
42
|
+
watchRoots: Object.freeze([]),
|
|
43
|
+
maxFilesPerRun: 50,
|
|
44
|
+
// Presupuesto de tiempo por tick (M6.7). El tick corre dentro del proceso del host: si una pasada
|
|
45
|
+
// se alarga, compite con las herramientas del usuario y retrasa la respuesta. Se corta de forma
|
|
46
|
+
// cooperativa entre fichero y fichero (lo ya confirmado no se revierte) y el resto queda para el
|
|
47
|
+
// tick siguiente. 2 000 ms es el valor por defecto acordado en M6.7 §4.
|
|
48
|
+
tickBudgetMs: 2_000,
|
|
49
|
+
collections: Object.freeze({}),
|
|
50
|
+
}),
|
|
51
|
+
// PA6: contexto recuperado antes de cada respuesta. Desactivado por defecto: activarlo cambia lo que
|
|
52
|
+
// el modelo ve en cada petición y consume tokens, así que es una decisión explícita del operador.
|
|
53
|
+
autoContext: Object.freeze({
|
|
54
|
+
enabled: false,
|
|
55
|
+
maxChars: 1_600,
|
|
56
|
+
maxChunks: 4,
|
|
57
|
+
budgetTokens: 600,
|
|
58
|
+
// Presupuesto del hook: el `agent/pre-step` corre en el camino crítico del turno, así que la
|
|
59
|
+
// recuperación se abandona al vencer en vez de retrasar la respuesta (D-PA6-08).
|
|
60
|
+
timeoutMs: 2_000,
|
|
61
|
+
}),
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
const CONFIG_KEYS = new Set([
|
|
65
|
+
'maxFileBytes', 'maxFilesPerIngest', 'chunk', 'context', 'search', 'embedding', 'audit', 'roots', 'metrics', 'automation',
|
|
66
|
+
'autoContext',
|
|
67
|
+
]);
|
|
68
|
+
|
|
69
|
+
/** Una clave desconocida en cualquier nivel es un error: una errata no puede pasar muda. */
|
|
70
|
+
function onlyKeys(object, allowed, label) {
|
|
71
|
+
for (const key of Object.keys(object)) {
|
|
72
|
+
if (!allowed.includes(key)) failConfig(`clave desconocida en ${label}: ${key}`, { key, label });
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** ¿Es una ruta absoluta? Se exige para la raíz: una relativa dependería del cwd de cada sesión. */
|
|
77
|
+
export function absoluteRoot(value, label = 'LIFECODE_RAG_ROOT') {
|
|
78
|
+
if (typeof value !== 'string' || value.trim() === '') {
|
|
79
|
+
throw new RagError('invalid-config', `${label} está vacío`);
|
|
80
|
+
}
|
|
81
|
+
if (!isAbsolute(value)) {
|
|
82
|
+
throw new RagError('invalid-config', `${label} debe ser una ruta absoluta`, { details: { value } });
|
|
83
|
+
}
|
|
84
|
+
return resolve(value);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Raíz del almacén. `LIFECODE_RAG_ROOT` manda; si no, `$DSH_HOME/lifecode-rag` y, en su defecto,
|
|
89
|
+
* `~/.dsh/lifecode-rag`. El Harness expone `DSH_PROFILE_DIR`, pero no se usa: el perfil puede cambiar
|
|
90
|
+
* de nombre y el almacén no debe depender de ello.
|
|
91
|
+
*/
|
|
92
|
+
export function ragRoot(env = process.env) {
|
|
93
|
+
const explicit = env.LIFECODE_RAG_ROOT;
|
|
94
|
+
if (typeof explicit === 'string') {
|
|
95
|
+
// Presente pero vacía no significa «usa el defecto»: significa que algo se configuró mal. Caer al
|
|
96
|
+
// almacén por defecto indexaría en otro sitio sin decirlo.
|
|
97
|
+
if (explicit.trim() === '') throw new RagError('invalid-config', 'LIFECODE_RAG_ROOT está vacío');
|
|
98
|
+
return absoluteRoot(explicit);
|
|
99
|
+
}
|
|
100
|
+
const home = typeof env.DSH_HOME === 'string'
|
|
101
|
+
? absoluteRoot(env.DSH_HOME, 'DSH_HOME')
|
|
102
|
+
: join(homedir(), '.dsh');
|
|
103
|
+
return join(home, 'lifecode-rag');
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Rutas derivadas de la raíz. No crean nada. */
|
|
107
|
+
export function storePaths(root) {
|
|
108
|
+
const base = absoluteRoot(root, 'root');
|
|
109
|
+
return Object.freeze({
|
|
110
|
+
root: base,
|
|
111
|
+
database: join(base, 'rag.sqlite3'),
|
|
112
|
+
audit: join(base, 'audit.jsonl'),
|
|
113
|
+
backups: join(base, 'backups'),
|
|
114
|
+
config: join(base, 'config.json'),
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* ¿`child` está dentro de `parent` (o es `parent`)? Comparación por ruta resuelta y, en Windows, sin
|
|
120
|
+
* distinguir mayúsculas: el mismo directorio no puede considerarse «fuera» por una mayúscula.
|
|
121
|
+
*/
|
|
122
|
+
export function isWithin(parent, child, platform = process.platform) {
|
|
123
|
+
const base = resolve(parent);
|
|
124
|
+
const target = resolve(child);
|
|
125
|
+
const fold = (value) => (platform === 'win32' ? value.toLowerCase() : value);
|
|
126
|
+
const left = fold(base);
|
|
127
|
+
const right = fold(target);
|
|
128
|
+
if (left === right) return true;
|
|
129
|
+
const rel = relative(left, right);
|
|
130
|
+
return rel !== '' && rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function failConfig(message, details = {}) {
|
|
134
|
+
throw new RagError('invalid-config', message, { details });
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function checkInteger(value, key, min, max) {
|
|
138
|
+
if (!Number.isInteger(value) || value < min || value > max) {
|
|
139
|
+
failConfig(`${key} debe ser un entero entre ${min} y ${max}`, { key, value });
|
|
140
|
+
}
|
|
141
|
+
return value;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Valida una configuración ya parseada. Rechaza claves desconocidas: una errata no puede pasar muda. */
|
|
145
|
+
export function validateConfig(raw) {
|
|
146
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
147
|
+
failConfig('config.json debe ser un objeto');
|
|
148
|
+
}
|
|
149
|
+
for (const key of Object.keys(raw)) {
|
|
150
|
+
if (!CONFIG_KEYS.has(key)) failConfig(`clave de configuración desconocida: ${key}`, { key });
|
|
151
|
+
}
|
|
152
|
+
onlyKeys(raw.chunk ?? {}, ['targetChars', 'maxChars', 'overlapChars'], 'chunk');
|
|
153
|
+
onlyKeys(raw.context ?? {}, ['budgetTokens', 'maxChunks', 'mmrLambda'], 'context');
|
|
154
|
+
onlyKeys(raw.search ?? {}, ['limit', 'maxLimit', 'maxVectorScan', 'strategy', 'rrfK', 'weights', 'minScore', 'maxPerSource', 'diversity'], 'search');
|
|
155
|
+
onlyKeys(raw.embedding ?? {}, ['provider', 'dim', 'remote'], 'embedding');
|
|
156
|
+
onlyKeys(raw.audit ?? {}, ['exportJsonl'], 'audit');
|
|
157
|
+
onlyKeys(raw.roots ?? {}, ['extra'], 'roots');
|
|
158
|
+
onlyKeys(raw.metrics ?? {}, ['enabled', 'retentionDays'], 'metrics');
|
|
159
|
+
onlyKeys(raw.automation ?? {}, ['enabled', 'intervalMs', 'watchRoots', 'maxFilesPerRun', 'tickBudgetMs', 'collections'], 'automation');
|
|
160
|
+
onlyKeys(raw.autoContext ?? {}, ['enabled', 'maxChars', 'maxChunks', 'budgetTokens', 'timeoutMs'], 'autoContext');
|
|
161
|
+
|
|
162
|
+
const merged = {
|
|
163
|
+
maxFileBytes: raw.maxFileBytes ?? DEFAULT_CONFIG.maxFileBytes,
|
|
164
|
+
maxFilesPerIngest: raw.maxFilesPerIngest ?? DEFAULT_CONFIG.maxFilesPerIngest,
|
|
165
|
+
chunk: { ...DEFAULT_CONFIG.chunk, ...(raw.chunk ?? {}) },
|
|
166
|
+
context: { ...DEFAULT_CONFIG.context, ...(raw.context ?? {}) },
|
|
167
|
+
search: {
|
|
168
|
+
...DEFAULT_CONFIG.search,
|
|
169
|
+
...(raw.search ?? {}),
|
|
170
|
+
weights: { ...DEFAULT_CONFIG.search.weights, ...(raw.search?.weights ?? {}) },
|
|
171
|
+
},
|
|
172
|
+
embedding: { ...DEFAULT_CONFIG.embedding, ...(raw.embedding ?? {}) },
|
|
173
|
+
audit: { ...DEFAULT_CONFIG.audit, ...(raw.audit ?? {}) },
|
|
174
|
+
roots: { ...DEFAULT_CONFIG.roots, ...(raw.roots ?? {}) },
|
|
175
|
+
metrics: { ...DEFAULT_CONFIG.metrics, ...(raw.metrics ?? {}) },
|
|
176
|
+
automation: {
|
|
177
|
+
...DEFAULT_CONFIG.automation,
|
|
178
|
+
...(raw.automation ?? {}),
|
|
179
|
+
collections: { ...DEFAULT_CONFIG.automation.collections, ...(raw.automation?.collections ?? {}) },
|
|
180
|
+
},
|
|
181
|
+
autoContext: { ...DEFAULT_CONFIG.autoContext, ...(raw.autoContext ?? {}) },
|
|
182
|
+
};
|
|
183
|
+
checkInteger(merged.maxFileBytes, 'maxFileBytes', 1_024, 64 * 1024 * 1024);
|
|
184
|
+
checkInteger(merged.maxFilesPerIngest, 'maxFilesPerIngest', 1, 10_000);
|
|
185
|
+
checkInteger(merged.chunk.targetChars, 'chunk.targetChars', 128, 8_000);
|
|
186
|
+
checkInteger(merged.chunk.maxChars, 'chunk.maxChars', merged.chunk.targetChars, 16_000);
|
|
187
|
+
checkInteger(merged.chunk.overlapChars, 'chunk.overlapChars', 0, merged.chunk.targetChars);
|
|
188
|
+
checkInteger(merged.context.budgetTokens, 'context.budgetTokens', 128, 200_000);
|
|
189
|
+
checkInteger(merged.context.maxChunks, 'context.maxChunks', 1, 100);
|
|
190
|
+
if (typeof merged.context.mmrLambda !== 'number' || merged.context.mmrLambda < 0 || merged.context.mmrLambda > 1) {
|
|
191
|
+
failConfig('context.mmrLambda debe estar entre 0 y 1', { value: merged.context.mmrLambda });
|
|
192
|
+
}
|
|
193
|
+
checkInteger(merged.search.limit, 'search.limit', 1, 100);
|
|
194
|
+
checkInteger(merged.search.maxLimit, 'search.maxLimit', merged.search.limit, 200);
|
|
195
|
+
checkInteger(merged.search.maxVectorScan, 'search.maxVectorScan', 100, 1_000_000);
|
|
196
|
+
if (!['hybrid', 'fts', 'vector'].includes(merged.search.strategy)) {
|
|
197
|
+
failConfig('search.strategy debe ser hybrid, fts o vector', { value: merged.search.strategy });
|
|
198
|
+
}
|
|
199
|
+
checkInteger(merged.search.rrfK, 'search.rrfK', 1, 1_000);
|
|
200
|
+
for (const side of ['lexical', 'semantic']) {
|
|
201
|
+
const weight = merged.search.weights[side];
|
|
202
|
+
if (typeof weight !== 'number' || !Number.isFinite(weight) || weight < 0 || weight > 10) {
|
|
203
|
+
failConfig(`search.weights.${side} debe estar entre 0 y 10`, { value: weight });
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
if (merged.search.weights.lexical + merged.search.weights.semantic <= 0) {
|
|
207
|
+
failConfig('search.weights debe tener algún peso mayor que cero');
|
|
208
|
+
}
|
|
209
|
+
if (typeof merged.search.minScore !== 'number' || merged.search.minScore < 0 || merged.search.minScore > 1) {
|
|
210
|
+
failConfig('search.minScore debe estar entre 0 y 1', { value: merged.search.minScore });
|
|
211
|
+
}
|
|
212
|
+
checkInteger(merged.search.maxPerSource, 'search.maxPerSource', 0, 100);
|
|
213
|
+
if (!['fragment', 'source'].includes(merged.search.diversity)) {
|
|
214
|
+
failConfig('search.diversity debe ser "fragment" o "source"', { value: merged.search.diversity });
|
|
215
|
+
}
|
|
216
|
+
if (!Array.isArray(merged.roots.extra)) failConfig('roots.extra debe ser una lista');
|
|
217
|
+
merged.roots.extra.forEach((root, index) => {
|
|
218
|
+
if (typeof root !== 'string' || !isAbsolute(root)) {
|
|
219
|
+
failConfig(`roots.extra[${index}] debe ser una ruta absoluta`, { value: root });
|
|
220
|
+
}
|
|
221
|
+
});
|
|
222
|
+
merged.roots = Object.freeze({ extra: Object.freeze([...merged.roots.extra]) });
|
|
223
|
+
|
|
224
|
+
if (!['local-hash-v1', 'remote'].includes(merged.embedding.provider)) {
|
|
225
|
+
failConfig('embedding.provider debe ser local-hash-v1 o remote', { value: merged.embedding.provider });
|
|
226
|
+
}
|
|
227
|
+
checkInteger(merged.embedding.dim, 'embedding.dim', 64, 4_096);
|
|
228
|
+
if (merged.embedding.provider === 'remote') {
|
|
229
|
+
const remote = merged.embedding.remote;
|
|
230
|
+
if (remote === null || typeof remote !== 'object' || Array.isArray(remote)) {
|
|
231
|
+
failConfig('embedding.remote es obligatorio cuando provider es remote');
|
|
232
|
+
}
|
|
233
|
+
onlyKeys(remote, ['endpoint', 'model', 'batchSize', 'timeoutMs', 'credentialRef'], 'embedding.remote');
|
|
234
|
+
if (typeof remote.endpoint !== 'string' || !/^https?:\/\/[^\s]+$/i.test(remote.endpoint)) {
|
|
235
|
+
failConfig('embedding.remote.endpoint debe ser una URL http(s)');
|
|
236
|
+
}
|
|
237
|
+
if (typeof remote.model !== 'string' || remote.model.trim() === '' || remote.model.length > 120) {
|
|
238
|
+
failConfig('embedding.remote.model debe ser un identificador no vacío');
|
|
239
|
+
}
|
|
240
|
+
checkInteger(remote.batchSize ?? 16, 'embedding.remote.batchSize', 1, 256);
|
|
241
|
+
checkInteger(remote.timeoutMs ?? 20_000, 'embedding.remote.timeoutMs', 500, 120_000);
|
|
242
|
+
if (remote.credentialRef !== undefined && (typeof remote.credentialRef !== 'string' || remote.credentialRef === '')) {
|
|
243
|
+
failConfig('embedding.remote.credentialRef debe ser una referencia no vacía');
|
|
244
|
+
}
|
|
245
|
+
merged.embedding.remote = Object.freeze({
|
|
246
|
+
endpoint: remote.endpoint,
|
|
247
|
+
model: remote.model,
|
|
248
|
+
batchSize: remote.batchSize ?? 16,
|
|
249
|
+
timeoutMs: remote.timeoutMs ?? 20_000,
|
|
250
|
+
credentialRef: remote.credentialRef ?? null,
|
|
251
|
+
});
|
|
252
|
+
} else if (merged.embedding.remote !== null) {
|
|
253
|
+
failConfig('embedding.remote sólo se admite con provider remote');
|
|
254
|
+
}
|
|
255
|
+
if (merged.audit.exportJsonl !== true && merged.audit.exportJsonl !== false) {
|
|
256
|
+
failConfig('audit.exportJsonl debe ser booleano');
|
|
257
|
+
}
|
|
258
|
+
if (typeof merged.metrics.enabled !== 'boolean') failConfig('metrics.enabled debe ser booleano');
|
|
259
|
+
checkInteger(merged.metrics.retentionDays, 'metrics.retentionDays', 1, 3_650);
|
|
260
|
+
if (typeof merged.automation.enabled !== 'boolean') failConfig('automation.enabled debe ser booleano');
|
|
261
|
+
checkInteger(merged.automation.intervalMs, 'automation.intervalMs', 5_000, 3_600_000);
|
|
262
|
+
checkInteger(merged.automation.maxFilesPerRun, 'automation.maxFilesPerRun', 1, 1_000);
|
|
263
|
+
checkInteger(merged.automation.tickBudgetMs, 'automation.tickBudgetMs', 250, 120_000);
|
|
264
|
+
if (!Array.isArray(merged.automation.watchRoots)) failConfig('automation.watchRoots debe ser una lista');
|
|
265
|
+
merged.automation.watchRoots.forEach((watch, index) => {
|
|
266
|
+
if (typeof watch !== 'string' || !isAbsolute(watch)) {
|
|
267
|
+
failConfig(`automation.watchRoots[${index}] debe ser una ruta absoluta`, { value: watch });
|
|
268
|
+
}
|
|
269
|
+
});
|
|
270
|
+
if (merged.automation.collections === null || typeof merged.automation.collections !== 'object' || Array.isArray(merged.automation.collections)) {
|
|
271
|
+
failConfig('automation.collections debe ser un objeto ruta→colección');
|
|
272
|
+
}
|
|
273
|
+
for (const [key, value] of Object.entries(merged.automation.collections)) {
|
|
274
|
+
if (typeof value !== 'string' || value.trim() === '') failConfig(`automation.collections[${key}] debe ser texto`);
|
|
275
|
+
}
|
|
276
|
+
merged.automation = Object.freeze({
|
|
277
|
+
enabled: merged.automation.enabled,
|
|
278
|
+
intervalMs: merged.automation.intervalMs,
|
|
279
|
+
watchRoots: Object.freeze([...merged.automation.watchRoots]),
|
|
280
|
+
maxFilesPerRun: merged.automation.maxFilesPerRun,
|
|
281
|
+
tickBudgetMs: merged.automation.tickBudgetMs,
|
|
282
|
+
collections: Object.freeze({ ...merged.automation.collections }),
|
|
283
|
+
});
|
|
284
|
+
merged.metrics = Object.freeze({ enabled: merged.metrics.enabled, retentionDays: merged.metrics.retentionDays });
|
|
285
|
+
if (typeof merged.autoContext.enabled !== 'boolean') failConfig('autoContext.enabled debe ser booleano');
|
|
286
|
+
checkInteger(merged.autoContext.maxChars, 'autoContext.maxChars', 200, 20_000);
|
|
287
|
+
checkInteger(merged.autoContext.maxChunks, 'autoContext.maxChunks', 1, 20);
|
|
288
|
+
checkInteger(merged.autoContext.budgetTokens, 'autoContext.budgetTokens', 64, 8_000);
|
|
289
|
+
checkInteger(merged.autoContext.timeoutMs, 'autoContext.timeoutMs', 100, 15_000);
|
|
290
|
+
if (merged.autoContext.budgetTokens > merged.context.budgetTokens) {
|
|
291
|
+
failConfig('autoContext.budgetTokens no puede superar context.budgetTokens');
|
|
292
|
+
}
|
|
293
|
+
merged.autoContext = Object.freeze({
|
|
294
|
+
enabled: merged.autoContext.enabled,
|
|
295
|
+
maxChars: merged.autoContext.maxChars,
|
|
296
|
+
maxChunks: merged.autoContext.maxChunks,
|
|
297
|
+
budgetTokens: merged.autoContext.budgetTokens,
|
|
298
|
+
timeoutMs: merged.autoContext.timeoutMs,
|
|
299
|
+
});
|
|
300
|
+
merged.search = Object.freeze({ ...merged.search, weights: Object.freeze({ ...merged.search.weights }) });
|
|
301
|
+
return Object.freeze(merged);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* Lee `config.json` si existe. Ausente ⇒ defaults sin escribir; ilegible o inválido ⇒ `invalid-config`
|
|
306
|
+
* (fail closed: un almacén con configuración ambigua no se usa).
|
|
307
|
+
*/
|
|
308
|
+
export function loadConfig(root) {
|
|
309
|
+
const paths = storePaths(root);
|
|
310
|
+
if (!existsSync(paths.config)) return { config: validateConfig({}), source: 'defaults', path: paths.config };
|
|
311
|
+
let text;
|
|
312
|
+
try {
|
|
313
|
+
text = readFileSync(paths.config, 'utf8');
|
|
314
|
+
} catch (error) {
|
|
315
|
+
throw new RagError('invalid-config', 'no se pudo leer config.json', { details: { path: paths.config }, cause: error });
|
|
316
|
+
}
|
|
317
|
+
let parsed;
|
|
318
|
+
try {
|
|
319
|
+
parsed = JSON.parse(text);
|
|
320
|
+
} catch (error) {
|
|
321
|
+
throw new RagError('invalid-config', 'config.json no es JSON válido', { details: { path: paths.config }, cause: error });
|
|
322
|
+
}
|
|
323
|
+
return { config: validateConfig(parsed), source: 'file', path: paths.config };
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* Escribe `config.json` de forma atómica: se valida antes, se escribe en temporal, `fsync` y
|
|
328
|
+
* `rename`. Un fallo a mitad deja la configuración anterior intacta. La escritura la decide una
|
|
329
|
+
* persona desde el Workspace o la CLI; nunca se escribe un fichero por el simple hecho de leer.
|
|
330
|
+
*/
|
|
331
|
+
export function writeConfig(root, raw, { now = Date.now() } = {}) {
|
|
332
|
+
const config = validateConfig(raw);
|
|
333
|
+
const paths = storePaths(root);
|
|
334
|
+
mkdirSync(paths.root, { recursive: true });
|
|
335
|
+
const tmp = `${paths.config}.tmp-${process.pid}-${now}`;
|
|
336
|
+
const handle = openSync(tmp, 'w');
|
|
337
|
+
try {
|
|
338
|
+
writeFileSync(handle, `${JSON.stringify(config, null, 2)}\n`, 'utf8');
|
|
339
|
+
fsyncSync(handle);
|
|
340
|
+
} finally {
|
|
341
|
+
closeSync(handle);
|
|
342
|
+
}
|
|
343
|
+
renameSync(tmp, paths.config);
|
|
344
|
+
return { config, path: paths.config };
|
|
345
|
+
}
|
package/lib/policy.mjs
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Política de rutas (M5, P0.4/P1.9): qué se puede leer para indexar y qué nunca.
|
|
3
|
+
*
|
|
4
|
+
* La exclusión del Skill Center es **incondicional**: no depende de que exista, de que esté dentro del
|
|
5
|
+
* cwd ni de una lista de raíces permitidas. Se comprueba por segmento de ruta *y* por ruta canónica,
|
|
6
|
+
* porque las tres ubicaciones reales (repo, estado en `$DSH_HOME`, copia instalada en el perfil) no
|
|
7
|
+
* comparten un prefijo único y ninguna es un enlace.
|
|
8
|
+
*
|
|
9
|
+
* La canonicalización con `realpath` resuelve symlinks y junctions de Windows antes de decidir, así que
|
|
10
|
+
* un acceso directo dentro del cwd no puede apuntar al almacén protegido.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { lstatSync, realpathSync, statSync } from 'node:fs';
|
|
14
|
+
import { basename, resolve } from 'node:path';
|
|
15
|
+
|
|
16
|
+
import { RagError } from './errors.mjs';
|
|
17
|
+
import { isWithin } from './paths.mjs';
|
|
18
|
+
|
|
19
|
+
/** Nombres de producto que nunca se indexan. En minúsculas; se comparan por segmento. */
|
|
20
|
+
export const PROTECTED_SEGMENTS = Object.freeze(['lifecode-skill-center']);
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Nombres de fichero que la sincronización periódica excluye por PATRÓN (M6.7 §5.1).
|
|
24
|
+
*
|
|
25
|
+
* Es una defensa en profundidad barata: el índice nunca debe contener credenciales, y una pasada
|
|
26
|
+
* automática no tiene a nadie mirando cada fichero nuevo. La lista es deliberadamente corta y por
|
|
27
|
+
* nombre exacto o extensión, para no excluir documentación legítima (p. ej. `environment.md` NO cae,
|
|
28
|
+
* `id_rsa` sí). No es un gestor de secretos: un secreto con nombre inocente y dentro de la raíz
|
|
29
|
+
* autorizada sigue siendo indexable, y por eso el contrato dice «sin secretos en la raíz».
|
|
30
|
+
*
|
|
31
|
+
* Se compara el nombre en minúsculas. `*.example`/`*.sample` sí se excluyen: son plantillas con la
|
|
32
|
+
* misma forma que el fichero real y el valor diferencial es cero.
|
|
33
|
+
*/
|
|
34
|
+
export const SENSITIVE_NAME_PATTERNS = Object.freeze([
|
|
35
|
+
/^\.env(\..+)?$/,
|
|
36
|
+
/^\.npmrc$/,
|
|
37
|
+
/^\.netrc$/,
|
|
38
|
+
/^\.pgpass$/,
|
|
39
|
+
/^id_(rsa|dsa|ecdsa|ed25519)(\.pub)?$/,
|
|
40
|
+
/^.*\.(pem|key|pfx|p12|keystore|jks)$/,
|
|
41
|
+
/^.*\.(env|secrets?|credentials?)(\.(local|production|development|test))?$/,
|
|
42
|
+
/^(.*[-_.])?(secrets?|credentials?)([-_.].*)?\.(json|ya?ml|toml|ini)$/,
|
|
43
|
+
]);
|
|
44
|
+
|
|
45
|
+
/** ¿El nombre del fichero (sin ruta) parece un secreto por su forma? */
|
|
46
|
+
export function isSensitiveName(name) {
|
|
47
|
+
const lower = String(name ?? '').toLowerCase().trim();
|
|
48
|
+
if (lower === '') return false;
|
|
49
|
+
return SENSITIVE_NAME_PATTERNS.some((pattern) => pattern.test(lower));
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const WINDOWS_DEVICES = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;
|
|
53
|
+
|
|
54
|
+
/** ¿La ruta cae en un producto protegido? Comparación por segmento, insensible a mayúsculas. */
|
|
55
|
+
export function isProtectedPath(filePath) {
|
|
56
|
+
const segments = String(filePath).split(/[\\/]+/).filter(Boolean).map((segment) => segment.toLowerCase());
|
|
57
|
+
return segments.some((segment) => PROTECTED_SEGMENTS.includes(segment));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Valida y canonicaliza una ruta de lectura.
|
|
62
|
+
* @returns {{realPath:string, outsideRoots:boolean, directory?:boolean}}
|
|
63
|
+
*/
|
|
64
|
+
export function classifyPath(filePath, { cwd, roots = [], ragRootPath = null, allowDirectory = false } = {}) {
|
|
65
|
+
if (typeof filePath !== 'string' || filePath.trim() === '') {
|
|
66
|
+
throw new RagError('invalid-argument', 'ruta vacía');
|
|
67
|
+
}
|
|
68
|
+
if (typeof cwd !== 'string' || cwd.trim() === '') {
|
|
69
|
+
throw new RagError('invalid-argument', 'no se pudo determinar el directorio de trabajo de la sesión');
|
|
70
|
+
}
|
|
71
|
+
const requested = resolve(cwd, filePath);
|
|
72
|
+
const name = basename(requested);
|
|
73
|
+
if (name.includes(':') || WINDOWS_DEVICES.test(name)) {
|
|
74
|
+
throw new RagError('path-unsupported', `nombre de fichero no admitido: ${name}`, { details: { path: requested } });
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// §14: no se sigue un symlink/junction/reparse point. Se rechaza por su propio nombre antes de
|
|
78
|
+
// resolver, para que un enlace a una ruta protegida no se convierta en una lectura de esa ruta.
|
|
79
|
+
let linkStats;
|
|
80
|
+
try {
|
|
81
|
+
linkStats = lstatSync(requested);
|
|
82
|
+
} catch (cause) {
|
|
83
|
+
throw new RagError('source-unreadable', 'la ruta no existe o no se puede resolver', { cause, details: { path: requested } });
|
|
84
|
+
}
|
|
85
|
+
if (linkStats.isSymbolicLink()) {
|
|
86
|
+
throw new RagError('path-escape', 'la ruta es un enlace simbólico o junction y no se sigue', { details: { path: requested } });
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
let realPath;
|
|
90
|
+
try {
|
|
91
|
+
realPath = realpathSync.native(requested);
|
|
92
|
+
} catch (cause) {
|
|
93
|
+
throw new RagError('source-unreadable', 'la ruta no existe o no se puede resolver', { cause, details: { path: requested } });
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
if (isProtectedPath(realPath) || isProtectedPath(requested)) {
|
|
97
|
+
throw new RagError('path-denied', 'la ruta pertenece a un producto protegido y no se indexa', { details: { path: realPath } });
|
|
98
|
+
}
|
|
99
|
+
if (ragRootPath && isWithin(ragRootPath, realPath)) {
|
|
100
|
+
throw new RagError('path-denied', 'la ruta pertenece al propio almacén de LifeCode RAG', { details: { path: realPath } });
|
|
101
|
+
}
|
|
102
|
+
for (const root of roots) {
|
|
103
|
+
if (isProtectedPath(root)) throw new RagError('invalid-config', `raíz permitida protegida: ${root}`);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// A8: un enlace duro puede dar acceso a un fichero protegido con otro nombre. Se rechaza.
|
|
107
|
+
let stats;
|
|
108
|
+
try {
|
|
109
|
+
stats = statSync(realPath);
|
|
110
|
+
} catch (cause) {
|
|
111
|
+
throw new RagError('source-unreadable', 'no se puede leer la ruta', { cause, details: { path: realPath } });
|
|
112
|
+
}
|
|
113
|
+
// `cwd` puede faltar: el host no siempre puede resolverlo (o la sesión se resolvió por selección
|
|
114
|
+
// explícita). Sin cwd sólo cuentan las raíces; `resolve(null)` reventaría con TypeError.
|
|
115
|
+
const allowed = [cwd, ...roots].filter((root) => typeof root === 'string' && root.length > 0);
|
|
116
|
+
const outsideRoots = !allowed.some((root) => isWithin(resolve(root), realPath));
|
|
117
|
+
if (stats.isDirectory()) {
|
|
118
|
+
if (!allowDirectory) throw new RagError('path-unsupported', 'no es un fichero regular', { details: { path: realPath } });
|
|
119
|
+
return { realPath, outsideRoots, directory: true };
|
|
120
|
+
}
|
|
121
|
+
if (!stats.isFile()) throw new RagError('path-unsupported', 'no es un fichero regular', { details: { path: realPath } });
|
|
122
|
+
if (stats.nlink > 1) throw new RagError('hardlink-refused', 'el fichero tiene enlaces duros', { details: { path: realPath, nlink: stats.nlink } });
|
|
123
|
+
|
|
124
|
+
return { realPath, outsideRoots };
|
|
125
|
+
}
|
package/lib/profile.mjs
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resolución de rutas Project-Aware (PA1).
|
|
3
|
+
*
|
|
4
|
+
* El registro es **uno por perfil**. Para que dos perfiles de DeepSeek Harness no compartan
|
|
5
|
+
* conocimiento, la raíz de datos se deriva del perfil activo y no de una ruta fija:
|
|
6
|
+
*
|
|
7
|
+
* 1. `LIFECODE_RAG_ROOT` (anulación explícita, útil en pruebas y desarrollo).
|
|
8
|
+
* 2. `$DSH_HOME/lifecode-rag/profiles/<profileKey>/`.
|
|
9
|
+
*
|
|
10
|
+
* `profileKey` es el nombre del perfil (`DSH_PROFILE`) o, si no está, el nombre del directorio del
|
|
11
|
+
* perfil (`DSH_PROFILE_DIR`) o, si tampoco está, el directorio de perfil con el que el host arrancó
|
|
12
|
+
* (`<...>/profiles/<nombre>` en `process.argv`). El host de escritorio recibe el perfil como
|
|
13
|
+
* argumento y no siempre lo publica en el entorno; sin este último paso el plugin dentro de la app
|
|
14
|
+
* resolvía `default` mientras el perfil real era `desktop`. Nunca se inventa una ruta: si no hay
|
|
15
|
+
* ninguna señal se usa `default`.
|
|
16
|
+
*
|
|
17
|
+
* El almacén v0.2 anterior vivía en `$DSH_HOME/lifecode-rag/rag.sqlite3`; esa ruta se conserva como
|
|
18
|
+
* origen de migración y **no** se reutiliza como raíz de perfil.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { createHash } from 'node:crypto';
|
|
22
|
+
import { statSync } from 'node:fs';
|
|
23
|
+
import { homedir } from 'node:os';
|
|
24
|
+
import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
|
|
25
|
+
|
|
26
|
+
import { RagError } from './errors.mjs';
|
|
27
|
+
|
|
28
|
+
function nonBlank(value, name) {
|
|
29
|
+
if (value === undefined || value === null) return null;
|
|
30
|
+
if (typeof value !== 'string') throw new RagError('invalid-config', `${name} debe ser una cadena`);
|
|
31
|
+
if (value.trim() === '') {
|
|
32
|
+
throw new RagError('invalid-config', `${name} está definida pero vacía (fail-closed)`);
|
|
33
|
+
}
|
|
34
|
+
return value.trim();
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function dshHome(env = process.env) {
|
|
38
|
+
const home = nonBlank(env.DSH_HOME, 'DSH_HOME');
|
|
39
|
+
return home ? resolve(home) : join(homedir(), '.dsh');
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Nombre estable del perfil activo, saneado para usarse como segmento de ruta.
|
|
44
|
+
*
|
|
45
|
+
* El saneado es con pérdida: `Pruebas` y `pruebas`, o `a b` y `a-b`, colapsan al mismo nombre. Como
|
|
46
|
+
* esta clave separa registros y almacenes, dos perfiles distintos compartirían conocimiento y
|
|
47
|
+
* auditoría. Cuando el saneado cambia el valor original se añade un sufijo derivado del nombre crudo,
|
|
48
|
+
* de modo que la identidad sigue siendo determinista pero inyectiva. Los nombres que ya son válidos
|
|
49
|
+
* (`desktop`, `headless`) no cambian: no hay migración de rutas para los perfiles existentes.
|
|
50
|
+
*/
|
|
51
|
+
export function profileKey(env = process.env, argv = process.argv) {
|
|
52
|
+
const name = nonBlank(env.DSH_PROFILE, 'DSH_PROFILE');
|
|
53
|
+
const dir = nonBlank(env.DSH_PROFILE_DIR, 'DSH_PROFILE_DIR');
|
|
54
|
+
const fromEnv = name ?? (dir ? basename(dir) : '');
|
|
55
|
+
const raw = fromEnv || profileNameFromArgv(argv) || '';
|
|
56
|
+
if (raw === '') return 'default';
|
|
57
|
+
const clean = raw.toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '');
|
|
58
|
+
if (clean === '') return `default-${suffixOf(raw)}`;
|
|
59
|
+
const truncated = clean.slice(0, 64);
|
|
60
|
+
if (truncated === raw && clean === raw) return truncated;
|
|
61
|
+
// Sólo cuando hubo pérdida se desambigua; el resultado cabe en el límite de 64 caracteres.
|
|
62
|
+
return `${truncated.slice(0, 55)}-${suffixOf(raw)}`;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Sufijo estable (8 hex) de la identidad cruda del perfil. */
|
|
66
|
+
function suffixOf(raw) {
|
|
67
|
+
return createHash('sha256').update(raw, 'utf8').digest('hex').slice(0, 8);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Nombre del perfil a partir del argumento con el que arrancó el host.
|
|
72
|
+
*
|
|
73
|
+
* El host de escritorio se lanza como `<exe> .../dsh-desktop-host/lib/index.js <dsh> <profileDir>
|
|
74
|
+
* <runtime> ...` y no exporta `DSH_PROFILE` en su propio entorno (esas variables se inyectan a los
|
|
75
|
+
* procesos hijos). Buscar aquí un directorio real `.../profiles/<nombre>` evita que el plugin dentro
|
|
76
|
+
* de la app resuelva `default` y no encuentre el registro del perfil activo. Sólo cuenta una ruta
|
|
77
|
+
* absoluta existente cuyo padre se llame `profiles`; cualquier otra cosa se ignora.
|
|
78
|
+
*/
|
|
79
|
+
function profileNameFromArgv(argv) {
|
|
80
|
+
for (const arg of Array.isArray(argv) ? argv : []) {
|
|
81
|
+
if (typeof arg !== 'string' || !isAbsolute(arg)) continue;
|
|
82
|
+
if (basename(dirname(arg)) !== 'profiles') continue;
|
|
83
|
+
try {
|
|
84
|
+
if (statSync(arg).isDirectory()) return basename(arg);
|
|
85
|
+
} catch {
|
|
86
|
+
// Ruta desaparecida o inaccesible: no es una señal de identidad.
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return '';
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Raíz de datos del perfil: contiene `registry.sqlite3` y `scopes/`. */
|
|
93
|
+
export function profileRoot(env = process.env, argv = process.argv) {
|
|
94
|
+
const override = nonBlank(env.LIFECODE_RAG_ROOT, 'LIFECODE_RAG_ROOT');
|
|
95
|
+
if (override) {
|
|
96
|
+
if (!isAbsolute(override)) {
|
|
97
|
+
throw new RagError('invalid-config', 'LIFECODE_RAG_ROOT debe ser una ruta absoluta');
|
|
98
|
+
}
|
|
99
|
+
return resolve(override);
|
|
100
|
+
}
|
|
101
|
+
return join(dshHome(env), 'lifecode-rag', 'profiles', profileKey(env, argv));
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Almacén único de v0.2, origen de la migración y dueño de la API heredada.
|
|
106
|
+
*
|
|
107
|
+
* Con `LIFECODE_RAG_ROOT` (pruebas y desarrollo) la raíz legada es ese mismo directorio: toda la
|
|
108
|
+
* instalación queda confinada ahí y una prueba nunca puede tocar el `$DSH_HOME` real. Sin anulación
|
|
109
|
+
* es `$DSH_HOME/lifecode-rag`, que es donde vivía v0.2.
|
|
110
|
+
*/
|
|
111
|
+
export function legacyRagRoot(env = process.env) {
|
|
112
|
+
const override = nonBlank(env.LIFECODE_RAG_ROOT, 'LIFECODE_RAG_ROOT');
|
|
113
|
+
if (override) {
|
|
114
|
+
if (!isAbsolute(override)) {
|
|
115
|
+
throw new RagError('invalid-config', 'LIFECODE_RAG_ROOT debe ser una ruta absoluta');
|
|
116
|
+
}
|
|
117
|
+
return resolve(override);
|
|
118
|
+
}
|
|
119
|
+
return join(dshHome(env), 'lifecode-rag');
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function registryPath(root) {
|
|
123
|
+
return join(root, 'registry.sqlite3');
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function scopeRoot(root, scopeId) {
|
|
127
|
+
return join(root, 'scopes', scopeId);
|
|
128
|
+
}
|