@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
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
# LifeCode RAG — Workspace API v1
|
|
2
|
+
|
|
3
|
+
**Fecha:** 2026-11-17 · **Estado:** contrato propuesto (no implementado)
|
|
4
|
+
**Transporte:** `ctx.webServer.register({ kind: 'prefix', path: '/lifecode-rag/api/v1', handler })`
|
|
5
|
+
**Ámbito:** solo `127.0.0.1` (el host sirve la UI en loopback)
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## 1. Reglas generales
|
|
10
|
+
|
|
11
|
+
- JSON UTF-8, `Content-Type: application/json; charset=utf-8`.
|
|
12
|
+
- Respuesta de error uniforme:
|
|
13
|
+
|
|
14
|
+
```json
|
|
15
|
+
{ "error": { "code": "invalid-argument", "message": "limit debe ser un entero entre 1 y 100", "details": { "field": "limit" } } }
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
- Códigos HTTP: `200` éxito, `400` entrada inválida, `404` recurso inexistente, `405` método no permitido,
|
|
19
|
+
`409` conflicto de estado (p. ej. reindex en curso), `423` almacén bloqueado, `500` fallo interno con
|
|
20
|
+
código `internal` (nunca stack ni rutas absolutas).
|
|
21
|
+
- **Sin autenticación de red**: la defensa es el bind de loopback del host. Aun así:
|
|
22
|
+
- solo se aceptan peticiones con `Host` de loopback (`127.0.0.1`, `localhost`, `[::1]`);
|
|
23
|
+
- los `POST` exigen `Content-Type: application/json` y la cabecera `x-lifecode-rag: 1`
|
|
24
|
+
(un formulario cross-origin no puede enviar cabeceras personalizadas sin preflight);
|
|
25
|
+
- no hay CORS: el navegador no recibe `Access-Control-Allow-Origin`;
|
|
26
|
+
- la API no acepta cookies ni tokens en query.
|
|
27
|
+
- Límites: cuerpo ≤ 64 KiB; `limit` ≤ 100 (por defecto 50); profundidad de filtros fija.
|
|
28
|
+
- Sin paginación implícita: toda lista trae `{ items, total, limit, offset, hasMore }`.
|
|
29
|
+
- `ETag` en `GET /snapshot`, `GET /sources`, `GET /health`; `If-None-Match` → `304`.
|
|
30
|
+
- Cada respuesta incluye `x-lifecode-rag-version` (semver del plugin) y `x-lifecode-rag-api: v1`.
|
|
31
|
+
|
|
32
|
+
## 2. Superficie
|
|
33
|
+
|
|
34
|
+
| Método | Ruta | Propósito | Escritura |
|
|
35
|
+
|---|---|---|---|
|
|
36
|
+
| GET | `/health` | Liveness + versión + modo | no |
|
|
37
|
+
| GET | `/capabilities` | Handshake: rutas, límites, capacidades | no |
|
|
38
|
+
| GET | `/snapshot` | Agregado para Resumen y cabecera | no |
|
|
39
|
+
| GET | `/sources` | Lista paginada de fuentes | no |
|
|
40
|
+
| GET | `/sources/:id` | Detalle de fuente + chunks paginados | no |
|
|
41
|
+
| GET | `/sources/:id/chunks/:ordinal` | Un chunk (texto bajo demanda) | no |
|
|
42
|
+
| GET | `/metrics/summary?from&to` | Cifras del periodo | no |
|
|
43
|
+
| GET | `/metrics/series?metric&from&to&bucket` | Serie temporal | no |
|
|
44
|
+
| GET | `/activity?limit&before` | Actividad reciente | no |
|
|
45
|
+
| GET | `/config` | Configuración efectiva (sin secretos) | no |
|
|
46
|
+
| GET | `/health/checks` | Diagnóstico detallado | no |
|
|
47
|
+
| POST | `/retrieval` | Consulta del Laboratorio (no persiste texto) | no |
|
|
48
|
+
| POST | `/actions` | Acción con política/aprobación | sí |
|
|
49
|
+
| POST | `/config` | Cambio de configuración validado | sí |
|
|
50
|
+
|
|
51
|
+
No existe endpoint de SQL, de exportación masiva ni de lectura de `audit.jsonl` por HTTP.
|
|
52
|
+
|
|
53
|
+
## 3. Esquemas
|
|
54
|
+
|
|
55
|
+
### 3.1 `GET /snapshot`
|
|
56
|
+
|
|
57
|
+
```json
|
|
58
|
+
{
|
|
59
|
+
"generatedAt": "2026-11-17T18:00:00.000Z",
|
|
60
|
+
"engine": { "state": "operational", "reason": null, "version": "0.2.0", "schemaVersion": 2 },
|
|
61
|
+
"counts": { "sources": 38, "chunks": 1240, "vectors": 1240, "collections": 4, "tags": 11 },
|
|
62
|
+
"lastIndexedAt": "2026-11-17T17:42:11.000Z",
|
|
63
|
+
"embedders": [{ "id": "local-hash-v1", "dim": 256, "kind": "local", "coverage": 1 }],
|
|
64
|
+
"window": { "from": "2026-11-10T00:00:00.000Z", "to": "2026-11-17T18:00:00.000Z" },
|
|
65
|
+
"usage": { "agentQueries": 42, "contexts": 12, "zeroResults": 3 },
|
|
66
|
+
"context": { "tokensServed": 18450, "corpusTokens": 141300, "savingRatio": 0.869, "method": "estimate:ceil(chars/4)" },
|
|
67
|
+
"activity": [
|
|
68
|
+
{ "at": "2026-11-17T17:42:11.000Z", "eventId": "e7", "action": "ingest", "target": "src_ab12", "outcome": "ok" }
|
|
69
|
+
],
|
|
70
|
+
"checks": { "sqlite": "ok", "fts": "ok", "vectors": "ok", "audit": "ok" }
|
|
71
|
+
}
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
`engine.state` ∈ `operational | degraded | not-initialized | error`. `counts` son medidos; `context` es
|
|
75
|
+
estimado y lo declara. `activity` máx. 8.
|
|
76
|
+
|
|
77
|
+
### 3.2 `GET /sources`
|
|
78
|
+
|
|
79
|
+
Query: `collection`, `tag`, `q` (título/URI), `limit` (1–100), `offset`, `sort` ∈ `indexedAt|title|chunks`.
|
|
80
|
+
|
|
81
|
+
```json
|
|
82
|
+
{
|
|
83
|
+
"items": [{
|
|
84
|
+
"sourceId": "src_ab12", "uri": "file:///C:/proyecto/docs/a.md", "title": "a.md",
|
|
85
|
+
"collection": "default", "tags": ["docs"], "chunks": 12, "bytes": 20480,
|
|
86
|
+
"indexedAt": "2026-11-17T17:42:11.000Z", "digest": "9f2c1d4e"
|
|
87
|
+
}],
|
|
88
|
+
"total": 38, "limit": 50, "offset": 0, "hasMore": false
|
|
89
|
+
}
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
### 3.3 `GET /sources/:id`
|
|
93
|
+
|
|
94
|
+
Metadatos completos + `chunks: [{ordinal, heading, charStart, charEnd, tokenEst}]` paginados.
|
|
95
|
+
El texto **no** viaja aquí; se pide a `/sources/:id/chunks/:ordinal`.
|
|
96
|
+
|
|
97
|
+
### 3.4 `POST /retrieval`
|
|
98
|
+
|
|
99
|
+
```json
|
|
100
|
+
{ "query": "cómo se aprueba un plan", "strategy": "hybrid", "limit": 8,
|
|
101
|
+
"collection": null, "tags": [], "tagMode": "any", "includeContext": true, "budgetTokens": 2000 }
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
Respuesta:
|
|
105
|
+
|
|
106
|
+
```json
|
|
107
|
+
{
|
|
108
|
+
"mode": "hybrid", "elapsedMs": 1.4, "truncated": false,
|
|
109
|
+
"vectors": { "scanned": 1240, "truncated": false },
|
|
110
|
+
"results": [{ "rank": 1, "chunkKey": "src_ab12#3", "sourceId": "src_ab12", "uri": "…",
|
|
111
|
+
"title": "a.md", "heading": "Aprobación", "ordinal": 3,
|
|
112
|
+
"snippet": "…", "bm25": -1.2, "cosine": 0.71, "rrf": 0.032 }],
|
|
113
|
+
"context": { "text": "…", "tokens": 1702, "truncated": false,
|
|
114
|
+
"citations": [{ "n": 1, "chunkKey": "src_ab12#3", "uri": "…", "charStart": 0, "charEnd": 1200 }] }
|
|
115
|
+
}
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
Reglas: `strategy` ∈ `fts|vector|hybrid`; el Laboratorio no escribe métricas de uso de agente (solo
|
|
119
|
+
contadores `labQueries`, separados); el texto de la consulta **no** se persiste.
|
|
120
|
+
|
|
121
|
+
### 3.5 `POST /actions`
|
|
122
|
+
|
|
123
|
+
Envelope único:
|
|
124
|
+
|
|
125
|
+
```json
|
|
126
|
+
{ "action": "reindex", "payload": { "operation": "fts" } }
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
| Acción | Payload | Política |
|
|
130
|
+
|---|---|---|
|
|
131
|
+
| `reindex` | `{operation: "fts"\|"vectors"\|"all"}` | confirmación + aprobación si `all`/vectores |
|
|
132
|
+
| `forget` | `{ref}` | aprobación humana obligatoria |
|
|
133
|
+
| `ingestPaths` | `{paths, collection?, tags?, force?}` | igual que la tool (aprobación si fuera de raíz) |
|
|
134
|
+
| `doctor` | `{full?: true}` | automático |
|
|
135
|
+
| `exportAudit` | `{}` | automático (solo escribe `audit.jsonl` derivado) |
|
|
136
|
+
|
|
137
|
+
Respuesta `200` con el resultado de la operación; `409` si hay otra operación de mantenimiento en curso;
|
|
138
|
+
`403`/`approval-required` si la política exige aprobación y no se concedió. La UI **no** aprueba: muestra
|
|
139
|
+
«requiere aprobación en el host» y refresca cuando el host resuelve.
|
|
140
|
+
|
|
141
|
+
### 3.6 `POST /config`
|
|
142
|
+
|
|
143
|
+
```json
|
|
144
|
+
{ "patch": { "search": { "limit": 8 }, "context": { "budgetTokens": 2400 } }, "expectedVersion": 7 }
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
Validación con `validateConfig` (mismas reglas que el motor); `expectedVersion` implementa concurrencia
|
|
148
|
+
optimista (`409` si cambió). Cambios de proveedor/raíces exigen confirmación; `localOnly` no se puede
|
|
149
|
+
desactivar desde la UI si el host fijó `LIFECODE_RAG_LOCAL_ONLY=1`.
|
|
150
|
+
|
|
151
|
+
## 4. Modelo de lectura y rendimiento
|
|
152
|
+
|
|
153
|
+
`lib/query.mjs` es el único módulo que consulta para la UI. Reutiliza la conexión abierta por el plugin
|
|
154
|
+
(sin abrir una segunda conexión: en Windows, dos `DatabaseSync` sobre el mismo fichero pueden bloquearse).
|
|
155
|
+
|
|
156
|
+
Presupuestos por endpoint (objetivo a medir en M3, no medido aún):
|
|
157
|
+
|
|
158
|
+
| Endpoint | p95 objetivo | Notas |
|
|
159
|
+
|---|---|---|
|
|
160
|
+
| `/snapshot` | ≤ 60 ms con 10 000 chunks | agregados con índices; sin `COUNT(*)` sobre texto |
|
|
161
|
+
| `/sources` | ≤ 40 ms | índice `sources_collection`, paginación real |
|
|
162
|
+
| `/sources/:id` | ≤ 25 ms | chunks por `chunks_source` |
|
|
163
|
+
| `/retrieval` | ≤ 250 ms | FTS + scan vectorial acotado |
|
|
164
|
+
| `/metrics/*` | ≤ 50 ms | tablas agregadas, no cálculo sobre eventos crudos |
|
|
165
|
+
|
|
166
|
+
Si se supera, la respuesta incluye `partial: true` y la UI lo dice; no se recorta en silencio.
|
|
167
|
+
|
|
168
|
+
## 5. Modelo de seguridad
|
|
169
|
+
|
|
170
|
+
### 5.1 Qué protege y qué no
|
|
171
|
+
|
|
172
|
+
La API **no autentica procesos locales**. Cualquier proceso que corra bajo el mismo usuario Windows puede
|
|
173
|
+
abrir `http://127.0.0.1:<puerto>/lifecode-rag/api/v1/…` y llamarla. Eso es aceptable solo si se declara:
|
|
174
|
+
|
|
175
|
+
- **Sí protege** frente a páginas web de terceros (CSRF), DNS rebinding y formularios cross-origin.
|
|
176
|
+
- **No protege** frente a malware o a otro proceso del mismo usuario; para eso no hay mecanismo en el host
|
|
177
|
+
y no se va a inventar uno en v0.2.
|
|
178
|
+
- La cabecera `x-lifecode-rag: 1` **no autentica**: solo obliga a preflight y descarta formularios simples.
|
|
179
|
+
Se documenta así para no vender una seguridad que no existe.
|
|
180
|
+
|
|
181
|
+
### 5.2 Modelo de amenazas
|
|
182
|
+
|
|
183
|
+
| Amenaza | Vector | Mitigación | Límite |
|
|
184
|
+
|---|---|---|---|
|
|
185
|
+
| CSRF desde una web | `POST` con formulario cross-origin | JSON + cabecera personalizada (preflight) + `Origin` exacto | no aplica a procesos locales |
|
|
186
|
+
| DNS rebinding | dominio atacante resuelto a 127.0.0.1 | `Host` debe ser **exactamente** el origen del host (`getOrigin()`), no «cualquier loopback» | — |
|
|
187
|
+
| Fuga de contenido | `GET /sources/:id/chunks/:ordinal` | solo `sourceId` validado; sin rutas del almacén | un proceso local ya puede leer los ficheros originales |
|
|
188
|
+
| Escritura no autorizada | `POST /config`, `/actions` | validación + `expectedVersion` + política/aprobación + auditoría | la aprobación la da el host, no la UI |
|
|
189
|
+
| DoS local | cuerpo gigante, consultas caras | 64 KiB, límites, `AbortSignal`, 429 por concurrencia | un proceso local puede saturar igual |
|
|
190
|
+
| Fuga por errores | stack, SQL, rutas | códigos públicos; log interno | — |
|
|
191
|
+
|
|
192
|
+
### 5.3 Respuestas a las preguntas de la orden
|
|
193
|
+
|
|
194
|
+
1. **¿Todo proceso local es confiable?** No. Se trata como *no autenticado*; la frontera real es la
|
|
195
|
+
aprobación del host para acciones sensibles y la validación de configuración.
|
|
196
|
+
2. **¿Qué puede hacer un proceso local?** Leer metadatos y chunks (que ya están en disco), lanzar
|
|
197
|
+
`GET`, y pedir acciones. Las sensibles quedan en `approval-required` hasta que la persona apruebe en el
|
|
198
|
+
host; no puede aprobar por HTTP.
|
|
199
|
+
3. **¿Cómo se protegen las escrituras de configuración?** Esquema cerrado (`validateConfig`), rangos,
|
|
200
|
+
`expectedVersion` (409 si cambió), auditoría con antes/después, y confirmación explícita para
|
|
201
|
+
proveedor/raíces/analítica.
|
|
202
|
+
4. **¿Qué exige confirmación o aprobación aunque venga de la UI?** `forget`, `purgeMetrics` total,
|
|
203
|
+
`ingestPaths` fuera de raíz, cambio de raíces/proveedor, egress y cualquier operación destructiva. La
|
|
204
|
+
UI nunca llama a `approval.request`; devuelve el estado y espera.
|
|
205
|
+
5. **¿CSRF y DNS rebinding?** Sin CORS, `Content-Type: application/json` obligatorio, cabecera
|
|
206
|
+
personalizada, `Origin` (si existe) igual al origen del host, y `Host` **exacto** al `host:port` del
|
|
207
|
+
host. Un `OPTIONS` no devuelve cabeceras CORS.
|
|
208
|
+
6. **¿Cómo se valida `Host`/`Origin`?** `Host` se compara con `new URL(ctx.webServer.getOrigin()).host`;
|
|
209
|
+
`Origin`, cuando llega, con el origen completo; discrepancias → `403 host-not-allowed`. No se acepta
|
|
210
|
+
`localhost` comodín ni puertos distintos.
|
|
211
|
+
7. **¿Rutas de solo lectura?** `GET /health`, `/capabilities`, `/snapshot`, `/sources*`, `/metrics/*`,
|
|
212
|
+
`/activity`, `/config`, `/health/checks`. `POST /retrieval` tampoco escribe contenido (solo contadores
|
|
213
|
+
de laboratorio). Las únicas escrituras son `/actions` y `/config`.
|
|
214
|
+
|
|
215
|
+
### 5.4 Pruebas de seguridad reproducibles
|
|
216
|
+
|
|
217
|
+
1. `Host: evil.example` → `403 host-not-allowed`, sin cuerpo de datos.
|
|
218
|
+
2. `POST /actions` sin `x-lifecode-rag` → `403` y **cero** mutaciones (verificar auditoría y filas).
|
|
219
|
+
3. `POST /config` con `Origin: https://evil.example` → `403`.
|
|
220
|
+
4. `OPTIONS /actions` → `405`/`204` sin `Access-Control-Allow-*`.
|
|
221
|
+
5. Cuerpo > 64 KiB → `413`, conexión cerrada sin leer el resto.
|
|
222
|
+
6. `POST /config` con `expectedVersion` viejo → `409`, configuración intacta.
|
|
223
|
+
7. `POST /actions {action:'forget'}` sin aprobación → `403 approval-required`, fuente sigue existiendo.
|
|
224
|
+
8. `GET /sources/:id/chunks/:ordinal` con id inventado → `404`, sin filtrar rutas.
|
|
225
|
+
9. `GET /sources` con `limit=1000` → `400 invalid-argument`.
|
|
226
|
+
10. Tras todas las pruebas, `audit` no contiene cuerpos ni rutas absolutas.
|
|
227
|
+
|
|
228
|
+
### 5.5 Por qué no se añade autenticación ahora
|
|
229
|
+
|
|
230
|
+
Un token en `localStorage` no protege de otro proceso local (puede leerlo o llamar igual), añade estado y
|
|
231
|
+
complica el arranque. Un socket con nombre/OS auth exigiría capacidad del host no verificada. Se declara
|
|
232
|
+
como limitación y, si se necesita, se decide en una orden aparte con coste y compatibilidad.
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
## 6. Versionado
|
|
236
|
+
|
|
237
|
+
- `v1` en la ruta; cambios incompatibles ⇒ `v2`, con `v1` servida durante al menos una versión menor.
|
|
238
|
+
- `capabilities` declara `{api: "v1", tools: "0.1.0", features: ["workspace","metrics","policies"]}`.
|
|
239
|
+
- El cliente exige `api: "v1"`; si no coincide, muestra una tarjeta de incompatibilidad y no rompe.
|
package/icon.svg
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="LifeCode RAG">
|
|
2
|
+
<rect width="64" height="64" rx="14" fill="#0f172a"/>
|
|
3
|
+
<path d="M18 20h20a8 8 0 0 1 8 8v18" fill="none" stroke="#38bdf8" stroke-width="4" stroke-linecap="round"/>
|
|
4
|
+
<circle cx="18" cy="20" r="5" fill="#38bdf8"/>
|
|
5
|
+
<circle cx="46" cy="46" r="5" fill="#a78bfa"/>
|
|
6
|
+
<path d="M26 30h8a6 6 0 0 1 6 6v4" fill="none" stroke="#a78bfa" stroke-width="3" stroke-linecap="round"/>
|
|
7
|
+
</svg>
|
package/index.js
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Adaptador Cordis de LifeCode RAG.
|
|
3
|
+
*
|
|
4
|
+
* Deliberadamente mínimo: no importa nada de `@deepseek-ai/*` ni conoce el esquema de herramientas del
|
|
5
|
+
* host. Todo lo que decide vive en `lib/` y se prueba con `node --test`; aquí sólo se conecta `ctx`.
|
|
6
|
+
*
|
|
7
|
+
* Registro: las herramientas, la ruta HTTP y el hook de contexto se dan de alta en el contexto que
|
|
8
|
+
* llama a `apply`, así que su vida va atada al plugin (efecto del contexto), no a un estado global.
|
|
9
|
+
*
|
|
10
|
+
* PA6 fija tres piezas contra el host real (ver `eval/pa6/PA6-REPORT.md`):
|
|
11
|
+
* - contexto por `agent/pre-step` (el host no activa el bridge de hooks Claude-Code aquí);
|
|
12
|
+
* - sincronización con `ctx.timer.interval`, que devuelve disposer y muere con el plugin;
|
|
13
|
+
* - la automatización v0.2 (`createAutomation`) queda sólo para perfiles que ya tienen el almacén
|
|
14
|
+
* legado, para no crear uno nuevo en perfiles Project-Aware.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { existsSync } from 'node:fs';
|
|
18
|
+
import { legacyRagRoot, profileRoot } from './lib/profile.mjs';
|
|
19
|
+
import { ragRoot, storePaths } from './lib/paths.mjs';
|
|
20
|
+
import { resolveConfig, resolveDataRoot, resolveProfileKey } from './lib/config-resolve.mjs';
|
|
21
|
+
import { createToolDefinitions } from './lib/tools.mjs';
|
|
22
|
+
import { API_PREFIX, createApiHandler } from './lib/server.mjs';
|
|
23
|
+
import { PA_PREFIX, createPaHandler } from './lib/pa-api.mjs';
|
|
24
|
+
import { createAutomation } from './lib/automation.mjs';
|
|
25
|
+
import { createSyncScheduler } from './lib/sync-scheduler.mjs';
|
|
26
|
+
import { createAutoContext } from './lib/auto-context.mjs';
|
|
27
|
+
|
|
28
|
+
export const name = 'lifecode-rag';
|
|
29
|
+
|
|
30
|
+
/** Servicios del host que el plugin necesita: herramientas, servidor web y, para PA01, la compuerta de
|
|
31
|
+
* autenticación (`connection`). El cargador del host 0.2.2-rc.5 no aplica la forma `{required, optional}`
|
|
32
|
+
* (medido: el plugin no se carga y su prefijo responde 404), así que se declaran los tres como requeridos:
|
|
33
|
+
* un perfil sin servidor web no tiene panel que proteger y no carga el plugin igual que antes. */
|
|
34
|
+
export const inject = ['tools', 'webServer', 'connection'];
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* PA01 · compuerta de autenticación del host para la API PA.
|
|
38
|
+
*
|
|
39
|
+
* El host autentica el navegador con una cookie firmada (token de lanzamiento en `GET /`) y aplica
|
|
40
|
+
* la compuerta a `/` y `/api`, **no** a los prefijos que monta un plugin. Aquí se reutiliza su
|
|
41
|
+
* mecanismo: `requestRejection` (trust + auth: 401/403) y `admit` (Peer vivo) sobre cada petición.
|
|
42
|
+
*
|
|
43
|
+
* - Sin `ctx.connection` no hay compuerta posible: se NIEGA (fail closed), nunca se abre.
|
|
44
|
+
* - La identidad la fija el host; ninguna cabecera del renderer se interpreta como identidad.
|
|
45
|
+
*/
|
|
46
|
+
function hostGate(ctx, logger) {
|
|
47
|
+
const connection = ctx.get('connection');
|
|
48
|
+
const usable = connection
|
|
49
|
+
&& typeof connection.requestRejection === 'function'
|
|
50
|
+
&& typeof connection.admit === 'function';
|
|
51
|
+
if (!usable) {
|
|
52
|
+
logger.warn?.('lifecode-rag PA: el host no ofrece ctx.connection; la API PA queda cerrada');
|
|
53
|
+
return async () => ({
|
|
54
|
+
ok: false, status: 503, code: 'authorization-unavailable',
|
|
55
|
+
message: 'el host no ofrece autenticación: la API PA está cerrada',
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
return async ({ headers }) => {
|
|
59
|
+
let rejection = null;
|
|
60
|
+
try {
|
|
61
|
+
rejection = await connection.requestRejection({ headers });
|
|
62
|
+
} catch {
|
|
63
|
+
return { ok: false, status: 503, code: 'authorization-unavailable', message: 'la compuerta del host falló' };
|
|
64
|
+
}
|
|
65
|
+
if (rejection) {
|
|
66
|
+
const status = typeof rejection === 'number' ? rejection
|
|
67
|
+
: (Number(rejection.status) || 401);
|
|
68
|
+
return {
|
|
69
|
+
ok: false,
|
|
70
|
+
status: status === 403 ? 403 : 401,
|
|
71
|
+
code: status === 403 ? 'forbidden' : 'unauthenticated',
|
|
72
|
+
message: 'la petición no está autenticada por el host',
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
let admitted = null;
|
|
76
|
+
try {
|
|
77
|
+
admitted = await connection.admit({ headers });
|
|
78
|
+
} catch {
|
|
79
|
+
return { ok: false, status: 503, code: 'authorization-unavailable', message: 'la compuerta del host falló' };
|
|
80
|
+
}
|
|
81
|
+
if (!admitted || !admitted.peer) {
|
|
82
|
+
const status = admitted && admitted.rejection && Number(admitted.rejection.status) === 403 ? 403 : 401;
|
|
83
|
+
return {
|
|
84
|
+
ok: false,
|
|
85
|
+
status,
|
|
86
|
+
code: status === 403 ? 'forbidden' : 'unauthenticated',
|
|
87
|
+
message: 'la petición no está autenticada por el host',
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
return { ok: true, peer: admitted.peer };
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function apply(ctx) {
|
|
95
|
+
// Dos raíces con propósitos distintos: `ragRoot` sólo guarda la configuración heredada (global al
|
|
96
|
+
// home, no por perfil) y `profileRoot` los datos Project-Aware de ESTE perfil (registro + scopes).
|
|
97
|
+
// Configuración efectiva (LE-RAG-01): perfil > global > defaults. `LIFECODE_RAG_DATA` y
|
|
98
|
+
// `LIFECODE_RAG_PROFILE` permiten un despliegue sin Harness; sin ellos se conserva la raíz histórica.
|
|
99
|
+
const { config } = resolveConfig({
|
|
100
|
+
dataRoot: resolveDataRoot(process.env),
|
|
101
|
+
profileKey: resolveProfileKey(process.env),
|
|
102
|
+
});
|
|
103
|
+
const profile = profileRoot(process.env);
|
|
104
|
+
const legacy = legacyRagRoot(process.env);
|
|
105
|
+
const logger = ctx.logger ?? console;
|
|
106
|
+
// Los servicios opcionales se resuelven en el momento de uso: `ctx.get` dentro de `apply` puede
|
|
107
|
+
// devolver `undefined` si Cordis todavía no cargó `approval`/`workingDirectory` (el plugin sólo
|
|
108
|
+
// inyecta `tools`). Congelarlos aquí convertía una carrera de arranque en un fallo permanente
|
|
109
|
+
// (`approval-unavailable` en cada escritura, sin directorio de trabajo → sin resolución).
|
|
110
|
+
const services = {
|
|
111
|
+
get approval() { return ctx.get('approval'); },
|
|
112
|
+
get workingDirectory() { return ctx.get('workingDirectory'); },
|
|
113
|
+
// Proyectos abiertos en Harness: vista de sólo lectura del registro durable de workspaces.
|
|
114
|
+
// Opcional: sin el servicio, la resolución sigue por `cwd` como antes.
|
|
115
|
+
get workspaces() {
|
|
116
|
+
const registry = ctx.get('workspaceRegistry');
|
|
117
|
+
return registry && typeof registry.list === 'function'
|
|
118
|
+
? { list: () => registry.list() }
|
|
119
|
+
: null;
|
|
120
|
+
},
|
|
121
|
+
env: process.env,
|
|
122
|
+
};
|
|
123
|
+
for (const definition of createToolDefinitions({ config, root: profile, services })) {
|
|
124
|
+
ctx.tools.register(definition);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// API del Workspace v0.2 (almacén único). En un perfil Project-Aware no hay `rag.sqlite3` legado:
|
|
128
|
+
// exponerla allí mostraría un almacén distinto del que consultan las herramientas, así que sólo se
|
|
129
|
+
// registra cuando el almacén legado existe de verdad.
|
|
130
|
+
const legacyStoreExists = existsSync(storePaths(legacy).database);
|
|
131
|
+
const webServer = ctx.get('webServer');
|
|
132
|
+
if (webServer) {
|
|
133
|
+
// LE-RAG-10: el panel lee el almacén del PERFIL (no el legacy). Solo lectura.
|
|
134
|
+
// PA01: toda la API PA pasa por la compuerta de autenticación del host antes de tocar el almacén.
|
|
135
|
+
const authorize = hostGate(ctx, logger);
|
|
136
|
+
const paHandler = createPaHandler({
|
|
137
|
+
profileRoot: profile, profileKey: resolveProfileKey(process.env), env: process.env, authorize,
|
|
138
|
+
});
|
|
139
|
+
ctx.effect(() => webServer.register({ kind: 'prefix', path: PA_PREFIX, handler: paHandler }));
|
|
140
|
+
}
|
|
141
|
+
if (webServer && legacyStoreExists) {
|
|
142
|
+
const handler = createApiHandler({ root: legacy, env: process.env });
|
|
143
|
+
ctx.effect(() => webServer.register({ kind: 'prefix', path: API_PREFIX, handler }));
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// Contexto antes de responder: sólo el primer paso de un turno y sólo con prompt humano. Si el
|
|
147
|
+
// contexto no se puede recuperar (sin registro, sin proyecto, revocado), el turno sigue sin él.
|
|
148
|
+
const autoContext = createAutoContext({ services, config, logger });
|
|
149
|
+
// `on` existe en cualquier Context de Cordis; el guarda sólo cubre dobles de prueba mínimos.
|
|
150
|
+
if (typeof ctx.on === 'function') {
|
|
151
|
+
ctx.on('agent/pre-step', async (payload, next) => {
|
|
152
|
+
const decision = await next();
|
|
153
|
+
if (!decision || decision.kind !== 'enter') return decision;
|
|
154
|
+
try {
|
|
155
|
+
const extra = await autoContext.messageFor(payload, decision.messages ?? []);
|
|
156
|
+
if (!extra) return decision;
|
|
157
|
+
return { ...decision, messages: [...(decision.messages ?? []), extra] };
|
|
158
|
+
} catch (error) {
|
|
159
|
+
logger.warn?.(`lifecode-rag contexto: ${error?.message ?? error}`);
|
|
160
|
+
return decision;
|
|
161
|
+
}
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// Sincronización Project-Aware (PA5) programada con el temporizador del host: su disposer cierra el
|
|
166
|
+
// intervalo cuando el plugin se descarga o el contexto se libera. La raíz es la del PERFIL: el
|
|
167
|
+
// registro Project-Aware vive ahí, no en la raíz legada (pasarla mal dejaba la automatización en un
|
|
168
|
+
// `no-registry` silencioso en cada tick).
|
|
169
|
+
//
|
|
170
|
+
// M6.7 §3.1: dentro del host NO se cae a `setInterval` global. Si `ctx.timer` no está en el momento
|
|
171
|
+
// de programar, se lanza y `start()` devuelve `no-timer`; el motivo queda en `status()`. Un intervalo
|
|
172
|
+
// global creado aquí sería invisible para el teardown del plugin y sobreviviría a la descarga.
|
|
173
|
+
const interval = (callback, delay) => {
|
|
174
|
+
const current = ctx.get('timer');
|
|
175
|
+
if (!current || typeof current.interval !== 'function') {
|
|
176
|
+
throw new Error('el host no ofrece ctx.timer.interval');
|
|
177
|
+
}
|
|
178
|
+
return current.interval(callback, delay);
|
|
179
|
+
};
|
|
180
|
+
const scheduler = createSyncScheduler({ env: process.env, root: profile, logger, interval });
|
|
181
|
+
ctx.effect(() => {
|
|
182
|
+
const started = scheduler.start();
|
|
183
|
+
if (started?.started === false && started.reason) {
|
|
184
|
+
logger.debug?.(`lifecode-rag sincronización: no arranca (${started.reason})`);
|
|
185
|
+
}
|
|
186
|
+
return () => scheduler.stop();
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
// Automatización v0.2: sólo si este perfil ya tenía un almacén legado. En un perfil Project-Aware no
|
|
190
|
+
// se crea nada nuevo (D-PA6-04).
|
|
191
|
+
if (legacyStoreExists) {
|
|
192
|
+
const automation = createAutomation({ root: legacy, env: process.env });
|
|
193
|
+
ctx.effect(() => {
|
|
194
|
+
automation.start();
|
|
195
|
+
return () => automation.stop();
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Exportación derivada de la auditoría (AC10/AC18).
|
|
3
|
+
*
|
|
4
|
+
* La tabla `audit` es la fuente de verdad. El fichero JSONL se escribe a un temporal, se sincroniza a disco
|
|
5
|
+
* y se renombra: un corte deja o el fichero anterior o el nuevo, nunca un híbrido. `meta.audit_exported_seq`
|
|
6
|
+
* registra hasta dónde llega la exportación, de modo que una caída entre el rename y la marca se resuelve
|
|
7
|
+
* regenerando (la exportación es idempotente).
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { closeSync, existsSync, fsyncSync, openSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
11
|
+
|
|
12
|
+
import { auditLine, verifyAuditChain } from './audit.mjs';
|
|
13
|
+
import { writeMeta } from './db.mjs';
|
|
14
|
+
|
|
15
|
+
const COLUMNS = 'seq, at, actor, session_id, call_id, tool, action, target, outcome, details, prev_hash, hash';
|
|
16
|
+
|
|
17
|
+
/** Escribe (o regenera) el JSONL completo desde la tabla. */
|
|
18
|
+
export function exportAuditJsonl(db, { path, tmpPath = `${path}.tmp` }) {
|
|
19
|
+
const rows = db.prepare(`SELECT ${COLUMNS} FROM audit ORDER BY seq ASC`).all();
|
|
20
|
+
const body = rows.map(auditLine).join('\n') + (rows.length > 0 ? '\n' : '');
|
|
21
|
+
writeFileSync(tmpPath, body, 'utf8');
|
|
22
|
+
const fd = openSync(tmpPath, 'r+');
|
|
23
|
+
try {
|
|
24
|
+
fsyncSync(fd);
|
|
25
|
+
} finally {
|
|
26
|
+
closeSync(fd);
|
|
27
|
+
}
|
|
28
|
+
renameSync(tmpPath, path);
|
|
29
|
+
const lastSeq = rows.length > 0 ? rows[rows.length - 1].seq : 0;
|
|
30
|
+
writeMeta(db, 'audit_exported_seq', String(lastSeq));
|
|
31
|
+
return { entries: rows.length, lastSeq, bytes: Buffer.byteLength(body, 'utf8') };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Compara el fichero con la base: detecta truncación, líneas extra, ediciones y corrupción.
|
|
36
|
+
* @returns {{ok:boolean, reason?:string, entries?:number, missing?:number[], seq?:number, line?:number}}
|
|
37
|
+
*/
|
|
38
|
+
export function verifyAuditExport(db, { path }) {
|
|
39
|
+
if (!existsSync(path)) return { ok: false, reason: 'missing' };
|
|
40
|
+
const lines = readFileSync(path, 'utf8').split('\n').filter((line) => line.trim() !== '');
|
|
41
|
+
const rows = db.prepare(`SELECT ${COLUMNS} FROM audit ORDER BY seq ASC`).all();
|
|
42
|
+
const expected = new Map(rows.map((row) => [row.seq, auditLine(row)]));
|
|
43
|
+
const seen = new Set();
|
|
44
|
+
for (let index = 0; index < lines.length; index += 1) {
|
|
45
|
+
let parsed;
|
|
46
|
+
try {
|
|
47
|
+
parsed = JSON.parse(lines[index]);
|
|
48
|
+
} catch {
|
|
49
|
+
return { ok: false, reason: 'invalid-line', line: index + 1 };
|
|
50
|
+
}
|
|
51
|
+
if (!Number.isInteger(parsed.seq) || !expected.has(parsed.seq)) {
|
|
52
|
+
return { ok: false, reason: 'extra', seq: parsed.seq, line: index + 1 };
|
|
53
|
+
}
|
|
54
|
+
if (seen.has(parsed.seq)) return { ok: false, reason: 'duplicate', seq: parsed.seq, line: index + 1 };
|
|
55
|
+
if (expected.get(parsed.seq) !== lines[index]) return { ok: false, reason: 'mismatch', seq: parsed.seq, line: index + 1 };
|
|
56
|
+
seen.add(parsed.seq);
|
|
57
|
+
}
|
|
58
|
+
const missing = rows.filter((row) => !seen.has(row.seq)).map((row) => row.seq);
|
|
59
|
+
if (missing.length > 0) return { ok: false, reason: 'truncated', missing: missing.slice(0, 5), missingCount: missing.length };
|
|
60
|
+
return { ok: true, entries: lines.length };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Estado conjunto: cadena de la base + coherencia del fichero. */
|
|
64
|
+
export function auditState(db, { path }) {
|
|
65
|
+
const chain = verifyAuditChain(db);
|
|
66
|
+
if (!chain.ok) return { ok: false, where: 'database', ...chain };
|
|
67
|
+
const file = verifyAuditExport(db, { path });
|
|
68
|
+
if (!file.ok) return { ok: false, where: 'file', ...file };
|
|
69
|
+
return { ok: true, entries: chain.count };
|
|
70
|
+
}
|
package/lib/audit.mjs
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Auditoría transaccional (M5, adelantada porque la ingesta la necesita).
|
|
3
|
+
*
|
|
4
|
+
* La tabla `audit` es la fuente de verdad; `audit.jsonl` es una **exportación derivada** que se puede
|
|
5
|
+
* regenerar. Cada fila encadena `prev_hash` y `hash`, y `meta.audit_head_seq` fija la cabeza: si la
|
|
6
|
+
* cabeza declarada no coincide con la última fila, el almacén se considera corrupto y no se abre.
|
|
7
|
+
*
|
|
8
|
+
* Límite conocido (A9): sin un ancla externa, truncar las últimas filas *junto con* `audit_head_seq`
|
|
9
|
+
* es indistinguible de un estado legítimo anterior. La cadena detecta ediciones y borrados internos,
|
|
10
|
+
* no una reescritura completa y coherente del fichero.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { createHash } from 'node:crypto';
|
|
14
|
+
|
|
15
|
+
import { RagError } from './errors.mjs';
|
|
16
|
+
import { readMeta, writeMeta } from './db.mjs';
|
|
17
|
+
|
|
18
|
+
export const GENESIS_HASH = '0'.repeat(64);
|
|
19
|
+
|
|
20
|
+
/** JSON canónico: claves ordenadas, sin espacios, para que el hash no dependa del orden de inserción. */
|
|
21
|
+
export function canonicalJson(value) {
|
|
22
|
+
if (value === null || typeof value !== 'object') return JSON.stringify(value ?? null);
|
|
23
|
+
if (Array.isArray(value)) return `[${value.map((item) => canonicalJson(item)).join(',')}]`;
|
|
24
|
+
const entries = Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`);
|
|
25
|
+
return `{${entries.join(',')}}`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Campos que entran en el hash; `details` es texto canónico, no un objeto suelto. */
|
|
29
|
+
function auditPayload(entry) {
|
|
30
|
+
return {
|
|
31
|
+
at: Number(entry.at),
|
|
32
|
+
actor: entry.actor ?? 'model',
|
|
33
|
+
sessionId: entry.sessionId ?? null,
|
|
34
|
+
callId: entry.callId ?? null,
|
|
35
|
+
tool: entry.tool,
|
|
36
|
+
action: entry.action,
|
|
37
|
+
target: entry.target ?? null,
|
|
38
|
+
outcome: entry.outcome,
|
|
39
|
+
details: entry.details ?? null,
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Hash de una entrada encadenada a la anterior. */
|
|
44
|
+
export function auditHash(prevHash, entry) {
|
|
45
|
+
return createHash('sha256').update(`${prevHash}\n${canonicalJson(auditPayload(entry))}`, 'utf8').digest('hex');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Añade una entrada a la cadena. Debe llamarse **dentro** de la transacción de la mutación que audita.
|
|
50
|
+
* @returns {{seq:number, hash:string}}
|
|
51
|
+
*/
|
|
52
|
+
export function appendAudit(db, entry) {
|
|
53
|
+
const head = Number(readMeta(db, 'audit_head_seq') ?? '0');
|
|
54
|
+
let prevHash = GENESIS_HASH;
|
|
55
|
+
if (head > 0) {
|
|
56
|
+
const row = db.prepare('SELECT hash FROM audit WHERE seq = ?').get(head);
|
|
57
|
+
if (!row) throw new RagError('store-corrupt', `falta la entrada de auditoría ${head}`);
|
|
58
|
+
prevHash = row.hash;
|
|
59
|
+
}
|
|
60
|
+
if (typeof entry.tool !== 'string' || entry.tool === '') throw new RagError('internal', 'auditoría sin herramienta');
|
|
61
|
+
if (typeof entry.action !== 'string' || entry.action === '') throw new RagError('internal', 'auditoría sin acción');
|
|
62
|
+
if (!['ok', 'failed', 'denied', 'skipped'].includes(entry.outcome)) {
|
|
63
|
+
throw new RagError('internal', `resultado de auditoría inválido: ${entry.outcome}`);
|
|
64
|
+
}
|
|
65
|
+
const payload = auditPayload(entry);
|
|
66
|
+
const hash = auditHash(prevHash, payload);
|
|
67
|
+
const info = db.prepare(`INSERT INTO audit (at, actor, session_id, call_id, tool, action, target, outcome, details, prev_hash, hash)
|
|
68
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(
|
|
69
|
+
payload.at, payload.actor, payload.sessionId, payload.callId, payload.tool, payload.action,
|
|
70
|
+
payload.target, payload.outcome, canonicalJson(payload.details), prevHash, hash,
|
|
71
|
+
);
|
|
72
|
+
const seq = Number(info.lastInsertRowid);
|
|
73
|
+
writeMeta(db, 'audit_head_seq', String(seq));
|
|
74
|
+
writeMeta(db, 'audit_head_hash', hash);
|
|
75
|
+
return { seq, hash };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Recorre la cadena y devuelve el primer punto roto, si lo hay. */
|
|
79
|
+
export function verifyAuditChain(db) {
|
|
80
|
+
const rows = db.prepare(`SELECT seq, at, actor, session_id, call_id, tool, action, target, outcome, details, prev_hash, hash
|
|
81
|
+
FROM audit ORDER BY seq ASC`).all();
|
|
82
|
+
let prevHash = GENESIS_HASH;
|
|
83
|
+
for (const row of rows) {
|
|
84
|
+
if (row.prev_hash !== prevHash) return { ok: false, brokenAt: row.seq, reason: 'prev-hash' };
|
|
85
|
+
const expected = auditHash(prevHash, {
|
|
86
|
+
at: row.at,
|
|
87
|
+
actor: row.actor,
|
|
88
|
+
sessionId: row.session_id ?? null,
|
|
89
|
+
callId: row.call_id ?? null,
|
|
90
|
+
tool: row.tool,
|
|
91
|
+
action: row.action,
|
|
92
|
+
target: row.target ?? null,
|
|
93
|
+
outcome: row.outcome,
|
|
94
|
+
details: row.details === null ? null : JSON.parse(row.details),
|
|
95
|
+
});
|
|
96
|
+
if (expected !== row.hash) return { ok: false, brokenAt: row.seq, reason: 'hash' };
|
|
97
|
+
prevHash = row.hash;
|
|
98
|
+
}
|
|
99
|
+
const head = Number(readMeta(db, 'audit_head_seq') ?? '0');
|
|
100
|
+
if (head !== rows.length) return { ok: false, brokenAt: head, reason: 'head' };
|
|
101
|
+
return { ok: true, count: rows.length };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Entrada de auditoría legible para la exportación JSONL (una línea por fila). */
|
|
105
|
+
export function auditLine(row) {
|
|
106
|
+
return JSON.stringify({
|
|
107
|
+
seq: row.seq,
|
|
108
|
+
at: row.at,
|
|
109
|
+
actor: row.actor,
|
|
110
|
+
sessionId: row.session_id ?? null,
|
|
111
|
+
callId: row.call_id ?? null,
|
|
112
|
+
tool: row.tool,
|
|
113
|
+
action: row.action,
|
|
114
|
+
target: row.target ?? null,
|
|
115
|
+
outcome: row.outcome,
|
|
116
|
+
details: row.details === null ? null : JSON.parse(row.details),
|
|
117
|
+
prevHash: row.prev_hash,
|
|
118
|
+
hash: row.hash,
|
|
119
|
+
});
|
|
120
|
+
}
|