@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
|
@@ -0,0 +1,449 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* CLI de LifeCode RAG. No registra herramientas ni habla con el host: sirve para diagnosticar, verificar
|
|
4
|
+
* y recuperar los almacenes antes o después de una operación. Nunca crea un almacén que falte.
|
|
5
|
+
*
|
|
6
|
+
* node bin/lifecode-rag.mjs doctor
|
|
7
|
+
* node bin/lifecode-rag.mjs project create --name <nombre> [--create] | project list
|
|
8
|
+
* node bin/lifecode-rag.mjs root add --project <prj_id> --path <ruta absoluta> [--create] | root list
|
|
9
|
+
* node bin/lifecode-rag.mjs select --session <id> --project <prj_id> [--by human|host]
|
|
10
|
+
* node bin/lifecode-rag.mjs session show --session <id>
|
|
11
|
+
* node bin/lifecode-rag.mjs audit export|verify
|
|
12
|
+
* node bin/lifecode-rag.mjs library status|verify|plan|recover|rollback
|
|
13
|
+
* node bin/lifecode-rag.mjs sync run [--scope <id>] [--dry-run] [--limit n] | sync status
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { auditState, exportAuditJsonl, verifyAuditExport } from '../lib/audit-export.mjs';
|
|
17
|
+
import { closeDatabase, openDatabase } from '../lib/db.mjs';
|
|
18
|
+
import { diagnoseProfile } from '../lib/diagnose.mjs';
|
|
19
|
+
import { runDoctor } from '../lib/doctor.mjs';
|
|
20
|
+
import { loadConfig, ragRoot, storePaths } from '../lib/paths.mjs';
|
|
21
|
+
import { profileKey, profileRoot } from '../lib/profile.mjs';
|
|
22
|
+
import { closeRegistry, openRegistry, addRoot, createProject, getProject, listRoots } from '../lib/registry.mjs';
|
|
23
|
+
import { describeProject, registerDiscoveredProject, scanWorkspace } from '../lib/discovery.mjs';
|
|
24
|
+
import { addTrustedRoot, listTrustedRoots, removeTrustedRoot } from '../lib/trusted-roots.mjs';
|
|
25
|
+
import { getSession, registerSelection } from '../lib/sessions.mjs';
|
|
26
|
+
import {
|
|
27
|
+
listRecoveryArtifacts, planRecovery, recoverScopeStore, rollbackRecovery, scopeHealth,
|
|
28
|
+
} from '../lib/recovery.mjs';
|
|
29
|
+
import { isServable } from '../lib/library-state.mjs';
|
|
30
|
+
import { activeSyncScopes, syncScopes, syncStatus } from '../lib/sync.mjs';
|
|
31
|
+
|
|
32
|
+
const argv = process.argv.slice(2);
|
|
33
|
+
const [command, subcommand] = argv;
|
|
34
|
+
|
|
35
|
+
function fail(message, code = 1) {
|
|
36
|
+
console.error(`✗ ${message}`);
|
|
37
|
+
process.exit(code);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function flag(name, fallback = null) {
|
|
41
|
+
const index = argv.indexOf(`--${name}`);
|
|
42
|
+
if (index < 0) return fallback;
|
|
43
|
+
const value = argv[index + 1];
|
|
44
|
+
return value === undefined || value.startsWith('--') ? true : value;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
if (command === 'doctor') {
|
|
48
|
+
const root = ragRoot(process.env);
|
|
49
|
+
const report = runDoctor({ root });
|
|
50
|
+
console.log(`LifeCode RAG · ${root}`);
|
|
51
|
+
for (const item of report.checks) {
|
|
52
|
+
const icon = item.status === 'ok' ? '✓' : item.status === 'warn' ? '!' : '✗';
|
|
53
|
+
console.log(` ${icon} ${item.name}: ${item.detail}`);
|
|
54
|
+
}
|
|
55
|
+
console.log(` · perfil Project-Aware: ${profileKey(process.env)} (usa \`diagnose\` para el detalle del registro y los almacenes)`);
|
|
56
|
+
process.exit(report.ok ? 0 : 1);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
if (command === 'diagnose') {
|
|
60
|
+
// Diagnóstico del perfil Project-Aware: sólo lectura, sin reparar nada y sin tocar el registro.
|
|
61
|
+
const report = diagnoseProfile({ env: process.env });
|
|
62
|
+
if (flag('json', false)) {
|
|
63
|
+
console.log(JSON.stringify(report, null, 2));
|
|
64
|
+
process.exit(report.ok ? 0 : 1);
|
|
65
|
+
}
|
|
66
|
+
const icon = (value) => (value ? '✓' : '✗');
|
|
67
|
+
console.log(`LifeCode RAG · diagnóstico del perfil ${report.profile.key}`);
|
|
68
|
+
console.log(` ${icon(Boolean(report.profile.config.sha256))} perfil: ${report.profile.root}`);
|
|
69
|
+
const cfg = report.profile.config;
|
|
70
|
+
console.log(
|
|
71
|
+
` ${icon(!cfg.error)} configuración: ${cfg.exists ? `${cfg.bytes} B sha256 ${String(cfg.sha256).slice(0, 12)}…` : 'no existe (valores por defecto)'}` +
|
|
72
|
+
`${cfg.automation ? ` · automation=${cfg.automation.enabled ? 'ON' : 'off'}` : ''}` +
|
|
73
|
+
`${cfg.autoContext ? ` · autoContext=${cfg.autoContext.enabled ? 'ON' : 'off'}` : ''}`,
|
|
74
|
+
);
|
|
75
|
+
const reg = report.registry;
|
|
76
|
+
if (!reg?.exists) {
|
|
77
|
+
console.log(' ✗ registro: no existe en este perfil');
|
|
78
|
+
} else if (reg.error) {
|
|
79
|
+
console.log(` ✗ registro: ${reg.error} (${reg.path})`);
|
|
80
|
+
} else {
|
|
81
|
+
console.log(
|
|
82
|
+
` ${icon(reg.quickCheck === 'ok' && reg.foreignKeys === 0 && reg.audit?.ok)} registro: ${reg.bytes} B · quick_check=${reg.quickCheck} · fk=${reg.foreignKeys} · auditoría=${reg.audit?.count ?? 0}${reg.audit?.ok ? ' ok' : ` ROTA en ${reg.audit?.brokenAt}`} · operaciones sin cerrar=${reg.unfinishedOperations.length}`,
|
|
83
|
+
);
|
|
84
|
+
for (const item of report.scopes) {
|
|
85
|
+
const counts = item.counts && !item.counts.error ? item.counts : null;
|
|
86
|
+
const detail = counts
|
|
87
|
+
? `${counts.sources} fuentes / ${counts.chunks} chunks / ${counts.vectors} vectores · sync ${Object.entries(item.sync ?? {}).map(([k, v]) => `${k}=${v}`).join(' ') || 'sin filas'} · auditoría=${counts.audit?.count ?? 0}${counts.audit?.ok ? '' : ' ROTA'}`
|
|
88
|
+
: item.reason ?? 'sin almacén';
|
|
89
|
+
console.log(` ${isServable(item.state) ? '✓' : '✗'} ${item.kind === 'prj' ? 'proyecto' : 'biblioteca'} ${item.name ?? item.scopeId}: ${item.state}${item.state === 'present' ? '' : ` (${detail})`}${item.state === 'present' ? ` · ${detail}` : ''}`);
|
|
90
|
+
}
|
|
91
|
+
for (const selection of report.selections) {
|
|
92
|
+
console.log(` · sesión ${selection.session_id}: ${selection.state} (${selection.selection_source}/${selection.selected_by}, revisión ${selection.revision})`);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
if (report.problems.length > 0) {
|
|
96
|
+
console.log(' problemas:');
|
|
97
|
+
for (const problem of report.problems) console.log(` ✗ ${problem}`);
|
|
98
|
+
}
|
|
99
|
+
console.log(`RESULTADO: ${report.ok ? 'sin problemas' : `${report.problems.length} problema(s)`}`);
|
|
100
|
+
process.exit(report.ok ? 0 : 1);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
if (command === 'audit' && (subcommand === 'export' || subcommand === 'verify')) {
|
|
104
|
+
const root = ragRoot(process.env);
|
|
105
|
+
loadConfig(root);
|
|
106
|
+
const opened = openDatabase({ root, create: false });
|
|
107
|
+
try {
|
|
108
|
+
const path = storePaths(root).audit;
|
|
109
|
+
if (subcommand === 'export') {
|
|
110
|
+
const result = exportAuditJsonl(opened.db, { path });
|
|
111
|
+
console.log(`✓ auditoría exportada: ${result.entries} entrada(s), ${result.bytes} bytes → ${path}`);
|
|
112
|
+
} else {
|
|
113
|
+
const result = verifyAuditExport(opened.db, { path });
|
|
114
|
+
if (result.ok) {
|
|
115
|
+
console.log(`✓ auditoría coherente: ${result.entries} entrada(s), base y fichero coinciden`);
|
|
116
|
+
} else {
|
|
117
|
+
fail(`auditoría incoherente: ${result.reason}${result.seq ? ` (seq ${result.seq})` : ''}`);
|
|
118
|
+
}
|
|
119
|
+
const state = auditState(opened.db, { path });
|
|
120
|
+
if (!state.ok) fail(`estado de auditoría inválido: ${state.where}/${state.reason}`);
|
|
121
|
+
}
|
|
122
|
+
} finally {
|
|
123
|
+
closeDatabase(opened.db);
|
|
124
|
+
}
|
|
125
|
+
process.exit(0);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Todos los ámbitos del registro con su nombre y estado; sólo lee. */
|
|
129
|
+
function allScopes(registryDb) {
|
|
130
|
+
const projects = registryDb.prepare(`SELECT id, name, status FROM projects ORDER BY name`).all()
|
|
131
|
+
.map((row) => ({ id: row.id, kind: 'prj', name: row.name, status: row.status }));
|
|
132
|
+
const libraries = registryDb.prepare(`SELECT id, name, status FROM libraries ORDER BY name`).all()
|
|
133
|
+
.map((row) => ({ id: row.id, kind: 'lib', name: row.name, status: row.status }));
|
|
134
|
+
return [...projects, ...libraries];
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function findScope(registryDb, id) {
|
|
138
|
+
if (typeof id !== 'string' || id.length === 0) fail('falta --scope <scope_id>', 2);
|
|
139
|
+
const scope = allScopes(registryDb).find((entry) => entry.id === id);
|
|
140
|
+
if (!scope) fail(`no existe el ámbito ${id} en este perfil`, 2);
|
|
141
|
+
return scope;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
if (command === 'library') {
|
|
145
|
+
const env = process.env;
|
|
146
|
+
const root = profileRoot(env);
|
|
147
|
+
const key = profileKey(env);
|
|
148
|
+
const now = Date.now();
|
|
149
|
+
let registry;
|
|
150
|
+
try {
|
|
151
|
+
registry = openRegistry({ root, create: false, now });
|
|
152
|
+
} catch (error) {
|
|
153
|
+
fail(`registro no disponible en ${root}: ${error?.message ?? error}`);
|
|
154
|
+
}
|
|
155
|
+
try {
|
|
156
|
+
if (!subcommand || subcommand === 'status' || subcommand === 'verify') {
|
|
157
|
+
const scopes = allScopes(registry.db);
|
|
158
|
+
const health = scopeHealth({ profileRootPath: root, profileKey: key, scopes });
|
|
159
|
+
console.log(`LifeCode RAG · ${root}`);
|
|
160
|
+
let blocked = 0;
|
|
161
|
+
for (const entry of health) {
|
|
162
|
+
const ok = subcommand === 'verify' ? isServable(entry.state) : true;
|
|
163
|
+
if (!ok) blocked += 1;
|
|
164
|
+
const icon = isServable(entry.state) ? '✓' : '✗';
|
|
165
|
+
const size = entry.bytes ? `, ${entry.bytes} bytes` : '';
|
|
166
|
+
console.log(` ${icon} ${entry.kind} ${entry.scopeId} (${entry.name ?? 'sin nombre'}): ${entry.state}${size}${entry.reason ? ` — ${entry.reason}` : ''}`);
|
|
167
|
+
for (const staging of entry.artifacts.staging) console.log(` ! trabajo de recuperación sin terminar: ${staging}`);
|
|
168
|
+
for (const quarantine of entry.artifacts.quarantine) console.log(` · cuarentena disponible: ${quarantine}`);
|
|
169
|
+
}
|
|
170
|
+
process.exit(subcommand === 'verify' && blocked > 0 ? 1 : 0);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
if (subcommand === 'plan' || subcommand === 'recover') {
|
|
174
|
+
const scope = findScope(registry.db, flag('scope'));
|
|
175
|
+
if (subcommand === 'plan') {
|
|
176
|
+
const plan = planRecovery({ profileRootPath: root, profileKey: key, scope });
|
|
177
|
+
console.log(JSON.stringify(plan, null, 2));
|
|
178
|
+
process.exit(plan.plan === 'blocked' ? 1 : 0);
|
|
179
|
+
}
|
|
180
|
+
const { config } = loadConfig(root);
|
|
181
|
+
const mode = flag('mode', 'auto');
|
|
182
|
+
const result = recoverScopeStore({
|
|
183
|
+
profileRootPath: root,
|
|
184
|
+
profileKey: key,
|
|
185
|
+
scope,
|
|
186
|
+
config,
|
|
187
|
+
mode,
|
|
188
|
+
confirm: flag('confirm') === true,
|
|
189
|
+
now,
|
|
190
|
+
actor: 'human',
|
|
191
|
+
registryDb: registry.db,
|
|
192
|
+
});
|
|
193
|
+
console.log(JSON.stringify(result, null, 2));
|
|
194
|
+
process.exit(0);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
if (subcommand === 'rollback') {
|
|
198
|
+
const scope = findScope(registry.db, flag('scope'));
|
|
199
|
+
const art = listRecoveryArtifacts({ profileRootPath: root, scope });
|
|
200
|
+
const from = flag('from', null);
|
|
201
|
+
const quarantine = from === null ? art.quarantine.at(-1) : String(from);
|
|
202
|
+
if (!quarantine) fail(`no hay cuarentena para ${scope.id}; usa --from <ruta>`, 2);
|
|
203
|
+
const result = rollbackRecovery({ profileRootPath: root, scope, quarantine, now, registryDb: registry.db });
|
|
204
|
+
console.log(JSON.stringify(result, null, 2));
|
|
205
|
+
process.exit(0);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
fail('uso: library status|verify|plan --scope <id>|recover --scope <id> [--mode auto|rebuild|reinit] --confirm|rollback --scope <id> [--from <ruta>]', 2);
|
|
209
|
+
} finally {
|
|
210
|
+
closeRegistry(registry.db);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
if (command === 'sync') {
|
|
215
|
+
const env = process.env;
|
|
216
|
+
const root = profileRoot(env);
|
|
217
|
+
const key = profileKey(env);
|
|
218
|
+
const { config } = loadConfig(root);
|
|
219
|
+
const now = Date.now();
|
|
220
|
+
let registry;
|
|
221
|
+
try {
|
|
222
|
+
registry = openRegistry({ root, create: false, now });
|
|
223
|
+
} catch (error) {
|
|
224
|
+
fail(`registro no disponible en ${root}: ${error?.message ?? error}`);
|
|
225
|
+
}
|
|
226
|
+
try {
|
|
227
|
+
if (!subcommand || subcommand === 'status') {
|
|
228
|
+
const scopes = activeSyncScopes(registry.db);
|
|
229
|
+
console.log(`LifeCode RAG · ${root}`);
|
|
230
|
+
if (scopes.length === 0) console.log(' · ningún ámbito activo con raíz autorizada');
|
|
231
|
+
for (const scope of scopes) {
|
|
232
|
+
const status = syncStatus(registry.db, { scopeKind: scope.kind, scopeId: scope.id });
|
|
233
|
+
const detail = status.length === 0
|
|
234
|
+
? 'sin sincronizar'
|
|
235
|
+
: status.map((entry) => `${entry.status}=${entry.count}`).join(' ');
|
|
236
|
+
console.log(` · ${scope.kind} ${scope.id} (${scope.name}): ${detail}`);
|
|
237
|
+
}
|
|
238
|
+
process.exit(0);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
if (subcommand === 'run') {
|
|
242
|
+
const scopeId = flag('scope', null);
|
|
243
|
+
const scopes = activeSyncScopes(registry.db).filter((scope) => scopeId === null || scope.id === scopeId);
|
|
244
|
+
if (scopes.length === 0) fail('no hay ámbitos activos que sincronizar con ese filtro', 2);
|
|
245
|
+
const limit = flag('limit', null);
|
|
246
|
+
const results = await syncScopes({
|
|
247
|
+
registryDb: registry.db,
|
|
248
|
+
profileRoot: root,
|
|
249
|
+
profileKey: key,
|
|
250
|
+
scopes,
|
|
251
|
+
config,
|
|
252
|
+
now: () => Date.now(),
|
|
253
|
+
limit: limit === null ? null : Number(limit),
|
|
254
|
+
actor: 'human',
|
|
255
|
+
dryRun: flag('dry-run') === true,
|
|
256
|
+
});
|
|
257
|
+
for (const result of results) {
|
|
258
|
+
console.log(`${result.scope_kind} ${result.scope_id}: observados=${result.observed} sin_cambios=${result.unchanged} nuevos=${result.new} modificados=${result.changed} ausentes=${result.missing} ilegibles=${result.unreadable} no_soportados=${result.unsupported} sensibles=${result.sensitive} ingeridos=${result.ingested} fallos=${result.failed}${result.stop_reason ? ` motivo=${result.stop_reason}` : ''}${result.cancelled ? ' CANCELADO' : ''}${result.dry_run ? ' (simulación)' : ''}`);
|
|
259
|
+
for (const error of result.errors.slice(0, 5)) console.log(` ! ${error.code}: ${error.path ?? ''} ${error.message}`);
|
|
260
|
+
}
|
|
261
|
+
const failed = results.some((result) => result.failed > 0 || result.cancelled || result.complete === false);
|
|
262
|
+
process.exit(failed ? 1 : 0);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
if (subcommand === 'report') {
|
|
266
|
+
// Observabilidad sin inspeccionar la base a mano: últimas pasadas y ticks tal como quedaron
|
|
267
|
+
// auditados (M6.7 §7). Sólo agregados; nunca contenido de documentos ni de prompts.
|
|
268
|
+
const limit = Number(flag('limit', 10));
|
|
269
|
+
const rows = registry.db
|
|
270
|
+
.prepare(
|
|
271
|
+
`SELECT seq, at, action, outcome, detail FROM audit_registry
|
|
272
|
+
WHERE action IN ('sync.run', 'sync.tick')
|
|
273
|
+
ORDER BY seq DESC LIMIT ?`,
|
|
274
|
+
)
|
|
275
|
+
.all(Number.isInteger(limit) && limit > 0 ? limit : 10);
|
|
276
|
+
if (rows.length === 0) console.log(' · sin pasadas de sincronización auditadas');
|
|
277
|
+
for (const row of rows) {
|
|
278
|
+
let detail = {};
|
|
279
|
+
try { detail = row.detail ? JSON.parse(row.detail) : {}; } catch { detail = {}; }
|
|
280
|
+
const parts = [
|
|
281
|
+
`scopes=${detail.scopes ?? '?'}`,
|
|
282
|
+
`nuevos=${detail.new ?? 0}`,
|
|
283
|
+
`ingeridos=${detail.ingested ?? 0}`,
|
|
284
|
+
`ausentes=${detail.missing ?? 0}`,
|
|
285
|
+
`fallos=${detail.failed ?? 0}`,
|
|
286
|
+
`no_soportados=${detail.unsupported ?? 0}`,
|
|
287
|
+
`sensibles=${detail.sensitive ?? 0}`,
|
|
288
|
+
`parciales=${detail.partial ?? 0}`,
|
|
289
|
+
`ms=${detail.ms ?? '?'}`,
|
|
290
|
+
detail.budget_ms ? `presupuesto_ms=${detail.budget_ms}` : null,
|
|
291
|
+
detail.stop_reason ? `motivo=${detail.stop_reason}` : null,
|
|
292
|
+
].filter(Boolean);
|
|
293
|
+
console.log(` #${row.seq} ${row.action} ${row.outcome} ${new Date(Number(row.at)).toISOString()} ${parts.join(' ')}`);
|
|
294
|
+
}
|
|
295
|
+
process.exit(0);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
fail('uso: sync run [--scope <id>] [--dry-run] [--limit n] | sync status | sync report [--limit n]', 2);
|
|
299
|
+
} finally {
|
|
300
|
+
closeRegistry(registry.db);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
if (command === 'project' || command === 'root' || command === 'select' || command === 'session'
|
|
305
|
+
|| command === 'trust' || command === 'discover') {
|
|
306
|
+
// Registro del perfil: crear proyecto, autorizar una raíz o fijar la selección de una sesión. No crea
|
|
307
|
+
// el almacén salvo `--create` explícito: la CLI nunca inventa un perfil. Toda salida va por stdout en
|
|
308
|
+
// JSON para que sea verificable; el código de salida es 0 sólo si la operación se completó.
|
|
309
|
+
const env = process.env;
|
|
310
|
+
const root = profileRoot(env);
|
|
311
|
+
const key = profileKey(env);
|
|
312
|
+
const now = Date.now();
|
|
313
|
+
let registry;
|
|
314
|
+
try {
|
|
315
|
+
registry = openRegistry({ root, create: flag('create', false) === true, now });
|
|
316
|
+
} catch (error) {
|
|
317
|
+
fail(`registro no disponible en ${root}: ${error?.message ?? error}`);
|
|
318
|
+
}
|
|
319
|
+
const db = registry.db;
|
|
320
|
+
let status = 0;
|
|
321
|
+
try {
|
|
322
|
+
if (command === 'project' && (!subcommand || subcommand === 'list')) {
|
|
323
|
+
const rows = db.prepare('SELECT id, name, status, created_at FROM projects ORDER BY created_at').all();
|
|
324
|
+
console.log(JSON.stringify({ profile: key, root, projects: rows.length, rows }, null, 1));
|
|
325
|
+
} else if (command === 'project' && (subcommand === 'create' || subcommand === 'add')) {
|
|
326
|
+
const name = flag('name');
|
|
327
|
+
if (name === null || name === true) fail('falta --name <nombre>', 2);
|
|
328
|
+
const project = createProject(db, { name: String(name), now });
|
|
329
|
+
console.log(JSON.stringify({ ok: true, profile: key, project }, null, 1));
|
|
330
|
+
} else if (command === 'project') {
|
|
331
|
+
fail('uso: project create --name <nombre> [--create] | project list', 2);
|
|
332
|
+
} else if (command === 'root' && (!subcommand || subcommand === 'list')) {
|
|
333
|
+
const rows = listRoots(db);
|
|
334
|
+
console.log(JSON.stringify({ profile: key, roots: rows.length, rows }, null, 1));
|
|
335
|
+
} else if (command === 'root' && (subcommand === 'add' || subcommand === 'authorize')) {
|
|
336
|
+
const projectId = flag('project');
|
|
337
|
+
const path = flag('path');
|
|
338
|
+
if (projectId === null || projectId === true) fail('falta --project <prj_id>', 2);
|
|
339
|
+
if (path === null || path === true) fail('falta --path <ruta absoluta>', 2);
|
|
340
|
+
if (!getProject(db, String(projectId))) fail(`no existe el proyecto ${projectId} en este perfil`, 2);
|
|
341
|
+
const row = addRoot(db, { scopeKind: 'prj', scopeId: String(projectId), path: String(path), addedBy: 'human', now });
|
|
342
|
+
console.log(JSON.stringify({ ok: true, profile: key, root: row }, null, 1));
|
|
343
|
+
} else if (command === 'root') {
|
|
344
|
+
fail('uso: root add --project <prj_id> --path <ruta absoluta> [--create] | root list', 2);
|
|
345
|
+
} else if (command === 'select') {
|
|
346
|
+
const session = flag('session');
|
|
347
|
+
const projectId = flag('project');
|
|
348
|
+
if (session === null || session === true) fail('falta --session <id>', 2);
|
|
349
|
+
if (projectId === null || projectId === true) fail('falta --project <prj_id>', 2);
|
|
350
|
+
const result = registerSelection(db, {
|
|
351
|
+
identity: { sessionId: String(session), profileKey: key },
|
|
352
|
+
expectedProfileKey: key,
|
|
353
|
+
projectId: String(projectId),
|
|
354
|
+
selectedBy: flag('by', 'human') === 'host' ? 'host' : 'human',
|
|
355
|
+
source: 'explicit',
|
|
356
|
+
actor: 'human',
|
|
357
|
+
now,
|
|
358
|
+
});
|
|
359
|
+
const selection = result.selection;
|
|
360
|
+
console.log(JSON.stringify({
|
|
361
|
+
ok: true,
|
|
362
|
+
profile: key,
|
|
363
|
+
created: result.created,
|
|
364
|
+
changed: result.changed,
|
|
365
|
+
selection: {
|
|
366
|
+
session: selection.session_id,
|
|
367
|
+
project: selection.project_id,
|
|
368
|
+
source: selection.selection_source,
|
|
369
|
+
by: selection.selected_by,
|
|
370
|
+
state: selection.state,
|
|
371
|
+
revision: selection.revision,
|
|
372
|
+
},
|
|
373
|
+
}, null, 1));
|
|
374
|
+
} else if (command === 'trust' && (!subcommand || subcommand === 'list')) {
|
|
375
|
+
const rows = listTrustedRoots(db);
|
|
376
|
+
console.log(JSON.stringify({
|
|
377
|
+
profile: key, root, trusted: rows.length, rows,
|
|
378
|
+
}, null, 1));
|
|
379
|
+
} else if (command === 'trust' && (subcommand === 'add' || subcommand === 'authorize')) {
|
|
380
|
+
const path = flag('path');
|
|
381
|
+
if (path === null || path === true) fail('falta --path <ruta absoluta del workspace>', 2);
|
|
382
|
+
const result = addTrustedRoot(db, {
|
|
383
|
+
path: String(path),
|
|
384
|
+
readAuthorization: flag('read', 'true') !== 'false',
|
|
385
|
+
addedBy: 'human',
|
|
386
|
+
now,
|
|
387
|
+
});
|
|
388
|
+
console.log(JSON.stringify({
|
|
389
|
+
ok: true, profile: key, created: result.created, changed: result.changed, root: result.root,
|
|
390
|
+
}, null, 1));
|
|
391
|
+
} else if (command === 'trust' && subcommand === 'remove') {
|
|
392
|
+
const path = flag('path');
|
|
393
|
+
if (path === null || path === true) fail('falta --path <ruta absoluta del workspace>', 2);
|
|
394
|
+
const result = removeTrustedRoot(db, { path: String(path), removedBy: 'human', now });
|
|
395
|
+
console.log(JSON.stringify({ ok: true, profile: key, changed: result.changed }, null, 1));
|
|
396
|
+
} else if (command === 'discover' && (subcommand === 'scan' || subcommand === 'register')) {
|
|
397
|
+
const path = flag('path');
|
|
398
|
+
if (path === null || path === true) fail('falta --path <ruta absoluta del workspace confiable>', 2);
|
|
399
|
+
const scan = scanWorkspace(String(path));
|
|
400
|
+
if (subcommand === 'scan') {
|
|
401
|
+
console.log(JSON.stringify({ profile: key, ...scan }, null, 1));
|
|
402
|
+
} else {
|
|
403
|
+
const authorization = flag('read', 'true') !== 'false' ? 'read' : 'discovered';
|
|
404
|
+
const results = scan.projects.map((project) => registerDiscoveredProject(db, {
|
|
405
|
+
path: project.path,
|
|
406
|
+
name: project.name,
|
|
407
|
+
type: project.type,
|
|
408
|
+
indicators: project.indicators,
|
|
409
|
+
source: 'cli',
|
|
410
|
+
authorization,
|
|
411
|
+
now,
|
|
412
|
+
}));
|
|
413
|
+
console.log(JSON.stringify({
|
|
414
|
+
profile: key,
|
|
415
|
+
scanned: scan.projects.length,
|
|
416
|
+
registered: results.filter((row) => row.created).length,
|
|
417
|
+
reused: results.filter((row) => !row.created).length,
|
|
418
|
+
skipped: scan.skipped,
|
|
419
|
+
results,
|
|
420
|
+
}, null, 1));
|
|
421
|
+
}
|
|
422
|
+
} else if (command === 'discover' && subcommand === 'show') {
|
|
423
|
+
const projectId = flag('project');
|
|
424
|
+
if (projectId === null || projectId === true) fail('falta --project <prj_id>', 2);
|
|
425
|
+
console.log(JSON.stringify({ profile: key, project: describeProject(db, String(projectId)) }, null, 1));
|
|
426
|
+
} else if (command === 'discover') {
|
|
427
|
+
fail('uso: discover scan|register --path <ruta> [--read true|false] | discover show --project <id>', 2);
|
|
428
|
+
} else if (command === 'trust') {
|
|
429
|
+
fail('uso: trust add --path <ruta> [--read true|false] | trust list | trust remove --path <ruta>', 2);
|
|
430
|
+
} else if (command === 'session' && subcommand === 'show') {
|
|
431
|
+
const session = flag('session');
|
|
432
|
+
if (session === null || session === true) fail('falta --session <id>', 2);
|
|
433
|
+
const row = getSession(db, String(session));
|
|
434
|
+
console.log(JSON.stringify({ profile: key, session: row ?? null }, null, 1));
|
|
435
|
+
if (!row) status = 1;
|
|
436
|
+
} else {
|
|
437
|
+
fail('uso: session show --session <id>', 2);
|
|
438
|
+
}
|
|
439
|
+
} catch (error) {
|
|
440
|
+
// Un error de dominio (proyecto inexistente, raíz no autorizable) no puede tumbar la CLI con traza.
|
|
441
|
+
console.error(`✗ ${error?.message ?? error}`);
|
|
442
|
+
status = 1;
|
|
443
|
+
} finally {
|
|
444
|
+
closeRegistry(db);
|
|
445
|
+
}
|
|
446
|
+
process.exit(status);
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
fail('uso: lifecode-rag.mjs doctor | diagnose | audit export | audit verify | project create|list | root add|list | select | session show | library status|verify|plan|recover|rollback | sync run|status|report', 2);
|