@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.
Files changed (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +191 -2
  3. package/bin/lifecode-rag.mjs +449 -0
  4. package/client.js +2801 -0
  5. package/cordis.patch.yml +3 -0
  6. package/docs/ARCHITECTURE-v0.2.md +269 -0
  7. package/docs/AUTO-DISCOVERY.md +111 -0
  8. package/docs/AUTOMATION-POLICIES.md +232 -0
  9. package/docs/CONTRATO-v0.1.md +195 -0
  10. package/docs/EMBEDDING-PROVIDERS.md +105 -0
  11. package/docs/OBSERVABILITY.md +241 -0
  12. package/docs/PA-UI-0-API-CONTRACT.md +802 -0
  13. package/docs/PERFORMANCE-BUDGETS.md +118 -0
  14. package/docs/PROJECT-AWARE-ARCHITECTURE.md +580 -0
  15. package/docs/PROJECT-AWARE-DATA-CONTRACT.md +411 -0
  16. package/docs/PROJECT-AWARE-ERROR-CONTRACT.md +112 -0
  17. package/docs/PROJECT-AWARE-SESSION-CONTRACT.md +120 -0
  18. package/docs/WORKSPACE-API.md +239 -0
  19. package/icon.svg +7 -0
  20. package/index.js +198 -0
  21. package/lib/audit-export.mjs +70 -0
  22. package/lib/audit.mjs +120 -0
  23. package/lib/auto-context.mjs +322 -0
  24. package/lib/automation.mjs +214 -0
  25. package/lib/chunk.mjs +100 -0
  26. package/lib/config-resolve.mjs +119 -0
  27. package/lib/context.mjs +150 -0
  28. package/lib/conversation-events.mjs +145 -0
  29. package/lib/db.mjs +309 -0
  30. package/lib/diagnose.mjs +197 -0
  31. package/lib/discovery.mjs +402 -0
  32. package/lib/doctor.mjs +82 -0
  33. package/lib/embed.mjs +96 -0
  34. package/lib/embedders.mjs +103 -0
  35. package/lib/errors.mjs +227 -0
  36. package/lib/exec-context.mjs +238 -0
  37. package/lib/extract.mjs +260 -0
  38. package/lib/harness-workspaces.mjs +85 -0
  39. package/lib/hash.mjs +34 -0
  40. package/lib/ingest.mjs +239 -0
  41. package/lib/inputs.mjs +67 -0
  42. package/lib/library-state.mjs +252 -0
  43. package/lib/maintenance.mjs +113 -0
  44. package/lib/metrics.mjs +164 -0
  45. package/lib/migrate.mjs +373 -0
  46. package/lib/operations.mjs +132 -0
  47. package/lib/pa-api.mjs +517 -0
  48. package/lib/paths.mjs +345 -0
  49. package/lib/policy.mjs +125 -0
  50. package/lib/profile.mjs +128 -0
  51. package/lib/readmodel.mjs +159 -0
  52. package/lib/recovery.mjs +557 -0
  53. package/lib/registry-schema.mjs +206 -0
  54. package/lib/registry.mjs +406 -0
  55. package/lib/resolve.mjs +311 -0
  56. package/lib/retention.mjs +143 -0
  57. package/lib/revocation.mjs +124 -0
  58. package/lib/roots-structure.mjs +224 -0
  59. package/lib/schema.mjs +173 -0
  60. package/lib/scope-ops.mjs +379 -0
  61. package/lib/scope-stores.mjs +128 -0
  62. package/lib/search.mjs +345 -0
  63. package/lib/selection.mjs +150 -0
  64. package/lib/server.mjs +335 -0
  65. package/lib/session-identity.mjs +51 -0
  66. package/lib/sessions.mjs +343 -0
  67. package/lib/sync-scheduler.mjs +354 -0
  68. package/lib/sync.mjs +755 -0
  69. package/lib/tags.mjs +45 -0
  70. package/lib/tools.mjs +364 -0
  71. package/lib/trusted-roots.mjs +149 -0
  72. package/lib/worker-context.mjs +22 -0
  73. package/package.json +67 -5
package/client.js ADDED
@@ -0,0 +1,2801 @@
1
+ /* LifeCode RAG — mitad cliente (pestaña del host).
2
+ *
3
+ * Módulo de cliente Cordis: React llega por el cargador del host, no por imports de
4
+ * `@deepseek-ai/*`. La interfaz no tiene privilegios: no autoriza, no decide y no escribe.
5
+ *
6
+ * K1 (2026-11-19): el panel montado es el Project-Aware en **modo sintético** (fixtures). El código
7
+ * heredado del Workspace v0.2 se conserva en este mismo fichero, pero queda inalcanzable: su capa de
8
+ * red falla cerrada mientras `DATA_MODE` no sea 'live', y 'live' no está habilitado.
9
+ */
10
+
11
+ window.__ModuleLoader__.load({
12
+ id: '@designerbyron/lifecode-rag',
13
+ factory(require) {
14
+ const React = require('react');
15
+ const el = React.createElement;
16
+ const { useCallback, useEffect, useMemo, useRef, useState } = React;
17
+
18
+ const API = '/lifecode-rag/api';
19
+ const PA_API = '/lifecode-rag/pa';
20
+ const REQUEST_TIMEOUT_MS = 8000;
21
+ /** Presupuesto de contexto por defecto del contrato §8 (2000 tokens estimados). */
22
+ const PA_CONTEXT_BUDGET = 2000;
23
+ const PANEL_ID = 'lifecode-rag';
24
+ const SIDEBAR_SLOT = 'sidebar.panellist';
25
+ const MAIN_SLOT = 'main';
26
+ // Modo de datos del panel. 'fixture' = datos sintéticos, sin red. 'live' no está habilitado:
27
+ // habilitarlo exige la integración de sesión que hoy no existe (PA01 BLOCKED). No hay ningún
28
+ // control en la interfaz que cambie este valor.
29
+ // LE-RAG-10: el modo se negocia con el servidor PA. Arranca en 'fixture' (demostración
30
+ // explícita) y solo pasa a 'api' si /snapshot responde mode:'api'. Si el servidor falla,
31
+ // NO se vuelve silenciosamente al fixture: se informa el estado y la razón.
32
+ const panelState = { mode: 'fixture', reason: 'sin negociar', service: null };
33
+ let requestSeq = 0;
34
+ const latestSeq = new Map();
35
+
36
+ /* ------------------------------------------------------------------ API */
37
+
38
+ async function request(path, options = {}) {
39
+ if (panelState.mode !== 'api') {
40
+ const blocked = new Error('fixture-mode: el panel no está conectado a la API PA');
41
+ blocked.code = 'fixture-mode';
42
+ throw blocked;
43
+ }
44
+ const base = options.target === 'legacy' ? API : PA_API;
45
+ const method = options.method || 'GET';
46
+ const headers = { accept: 'application/json' };
47
+ if (options.body !== undefined) {
48
+ headers['content-type'] = 'application/json';
49
+ headers['x-lifecode-rag'] = '1';
50
+ }
51
+ const key = method + ' ' + path;
52
+ const seq = ++requestSeq;
53
+ latestSeq.set(key, seq);
54
+ const controller = new AbortController();
55
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
56
+ if (options.signal) options.signal.addEventListener('abort', function () { controller.abort(); }, { once: true });
57
+ let response;
58
+ try {
59
+ response = await fetch(base + path, {
60
+ method,
61
+ headers,
62
+ body: options.body === undefined ? undefined : JSON.stringify(options.body),
63
+ signal: controller.signal,
64
+ });
65
+ } catch (error) {
66
+ clearTimeout(timer);
67
+ const aborted = error && error.name === 'AbortError';
68
+ const failure = new Error(aborted ? 'tiempo de espera agotado' : 'fallo de transporte');
69
+ failure.code = aborted ? 'timeout' : 'transport-error';
70
+ throw failure;
71
+ }
72
+ clearTimeout(timer);
73
+ if (latestSeq.get(key) !== seq) {
74
+ const stale = new Error('respuesta obsoleta descartada');
75
+ stale.code = 'stale-response';
76
+ throw stale;
77
+ }
78
+ const text = await response.text();
79
+ let data = null;
80
+ try { data = text ? JSON.parse(text) : null; } catch { data = null; }
81
+ if (data === null) {
82
+ const invalid = new Error('respuesta no es JSON válido');
83
+ invalid.code = 'invalid-json';
84
+ invalid.status = response.status;
85
+ throw invalid;
86
+ }
87
+ // LE-RAG-12: sobre contractual (§5) — `{ok:true, data}` en éxito, `{ok:false, error}` en fallo.
88
+ // Un `ok:false` con status 200 también es un fallo: nunca se degrada a datos vacíos.
89
+ if (data.ok === false && data.error) {
90
+ const failure = new Error(data.error.message || 'la operación no se completó');
91
+ failure.code = data.error.code || 'internal';
92
+ failure.status = response.status;
93
+ throw failure;
94
+ }
95
+ if (!response.ok) {
96
+ if (response.status === 404 && !(data && data.error)) {
97
+ const unavailable = new Error('este perfil usa Project-Aware: el panel del almacén v0.2 no está disponible; usa las herramientas lifecode_rag_*');
98
+ unavailable.code = 'panel-unavailable';
99
+ throw unavailable;
100
+ }
101
+ const failure = new Error((data.error && data.error.message) || ('HTTP ' + response.status));
102
+ failure.code = (data.error && data.error.code) || (`http-${response.status}`);
103
+ failure.status = response.status;
104
+ throw failure;
105
+ }
106
+ return data.ok === true && data.data !== undefined ? data.data : data;
107
+ }
108
+
109
+ async function negotiateMode(options) {
110
+ const project = options && options.project ? options.project : null;
111
+ const suffix = project ? ('?project=' + encodeURIComponent(project)) : '';
112
+ try {
113
+ const response = await fetch(PA_API + '/snapshot' + suffix, { headers: { accept: 'application/json' } });
114
+ let data = null;
115
+ try { data = await response.json(); } catch { data = null; }
116
+ // LE-RAG-12: el sobre §5 envuelve el payload en `data`.
117
+ const payload = data && data.ok === true && data.data ? data.data : data;
118
+ if (response.ok && payload && payload.mode === 'api') {
119
+ panelState.mode = 'api';
120
+ panelState.reason = 'api';
121
+ panelState.service = payload.service || 'ok';
122
+ return panelState;
123
+ }
124
+ panelState.mode = 'fixture';
125
+ panelState.reason = (data && data.error && data.error.code) || ('http-' + response.status);
126
+ panelState.service = 'down';
127
+ } catch (error) {
128
+ panelState.mode = 'fixture';
129
+ panelState.reason = (error && error.code) || 'transport-error';
130
+ panelState.service = 'down';
131
+ }
132
+ return panelState;
133
+ }
134
+
135
+ // LE-RAG-10: normalización de las respuestas reales de la API PA a las filas que pintan las
136
+ // vistas. Se usa la URI relativa del snapshot cuando la cita trae un sourceId conocido, para no
137
+ // exponer rutas absolutas del disco en la interfaz.
138
+ function paNormalizeSearch(data, sources, fallbackScope) {
139
+ const rows = Array.isArray(data && data.results) ? data.results : [];
140
+ const byId = new Map((sources || []).map((row) => [row.id, row]));
141
+ return {
142
+ mode: (data && data.mode) || 'api',
143
+ elapsedMs: data && typeof data.elapsedMs === 'number' ? data.elapsedMs : null,
144
+ results: rows.map((row) => {
145
+ const source = byId.get(row.sourceId) || null;
146
+ return {
147
+ chunkKey: row.chunkKey,
148
+ sourceId: row.sourceId,
149
+ uri: source ? source.uri : (row.uri || ''),
150
+ title: row.title || (source ? source.title : ''),
151
+ heading: row.heading || '',
152
+ ordinal: row.ordinal ?? null,
153
+ snippet: row.snippet ?? '',
154
+ score: typeof row.score === 'number' ? row.score : (typeof row.rrf === 'number' ? row.rrf : null),
155
+ scopeKind: row.scopeKind || 'prj',
156
+ scopeName: row.scopeName || fallbackScope || '',
157
+ };
158
+ }),
159
+ };
160
+ }
161
+
162
+ function paNormalizeContext(data, sources) {
163
+ const citations = Array.isArray(data && data.citations) ? data.citations : [];
164
+ const byId = new Map((sources || []).map((row) => [row.id, row]));
165
+ return {
166
+ text: data && typeof data.text === 'string' ? data.text : '',
167
+ tokens: data && typeof data.tokens === 'number' ? data.tokens
168
+ : (data && typeof data.tokensEstimate === 'number' ? data.tokensEstimate : null),
169
+ truncated: data && typeof data.truncated === 'boolean' ? data.truncated : null,
170
+ considered: data && Number.isFinite(data.considered) ? data.considered
171
+ : (data && Array.isArray(data.considered) ? data.considered.length : null),
172
+ citations: citations.map((citation) => {
173
+ const source = byId.get(citation.sourceId) || null;
174
+ return { ...citation, uri: source ? source.uri : (citation.uri || '') };
175
+ }),
176
+ };
177
+ }
178
+
179
+ // `limit=200` es el máximo del contrato (§8): con él la lista cargada coincide con el total en
180
+ // perfiles normales, y si hay más se declara que el listado está acotado.
181
+ const getSnapshot = () => request('/snapshot?limit=200');
182
+ const getSources = (query = '') => request(`/sources${query ? `?${query}` : ''}`);
183
+ const getSource = (id) => request(`/sources/${encodeURIComponent(id)}`);
184
+ const search = (payload) => request('/search', { method: 'POST', body: payload });
185
+ const buildContext = (payload) => request('/context', { method: 'POST', body: payload });
186
+ const action = (payload) => request('/actions', { method: 'POST', body: payload });
187
+ const saveConfig = (patch) => request('/config', { method: 'POST', body: patch });
188
+ const metricSeries = (metric, days = 7) => request(`/metrics/series?metric=${encodeURIComponent(metric)}&days=${days}`);
189
+
190
+ /* --------------------------------------------------------------- helpers */
191
+
192
+ function formatNumber(value) {
193
+ return new Intl.NumberFormat('es-ES').format(value ?? 0);
194
+ }
195
+
196
+ function formatBytes(bytes) {
197
+ if (!Number.isFinite(bytes) || bytes <= 0) return '0 B';
198
+ const units = ['B', 'kB', 'MB', 'GB'];
199
+ const index = Math.min(units.length - 1, Math.floor(Math.log(bytes) / Math.log(1024)));
200
+ return `${(bytes / 1024 ** index).toFixed(index === 0 ? 0 : 1)} ${units[index]}`;
201
+ }
202
+
203
+ function formatTime(value) {
204
+ if (!value) return '—';
205
+ const date = new Date(value);
206
+ if (Number.isNaN(date.getTime())) return String(value);
207
+ return date.toLocaleString('es-ES', { dateStyle: 'short', timeStyle: 'short' });
208
+ }
209
+
210
+ function errorText(error) {
211
+ if (!error) return '';
212
+ if (error.code) return `${error.message} (${error.code})`;
213
+ return error.message || String(error);
214
+ }
215
+
216
+ const TABS = [
217
+ ['resumen', 'Resumen'],
218
+ ['fuentes', 'Fuentes'],
219
+ ['buscar', 'Buscar'],
220
+ ['contexto', 'Contexto'],
221
+ ['metricas', 'Métricas'],
222
+ ['configuracion', 'Configuración'],
223
+ ['salud', 'Salud'],
224
+ ];
225
+
226
+ /* ------------------------------------------------------------------- UI */
227
+
228
+ function Chip({ tone = 'neutral', children }) {
229
+ return el('span', { className: `lcr-chip lcr-chip--${tone}` }, children);
230
+ }
231
+
232
+ function Card({ title, extra, children }) {
233
+ return el(
234
+ 'section',
235
+ { className: 'lcr-card' },
236
+ el('header', { className: 'lcr-card__head' },
237
+ el('h3', { className: 'lcr-card__title' }, title),
238
+ extra || null),
239
+ el('div', { className: 'lcr-card__body' }, children),
240
+ );
241
+ }
242
+
243
+ function Empty({ title, hint }) {
244
+ return el('div', { className: 'lcr-empty' },
245
+ el('p', { className: 'lcr-empty__title' }, title),
246
+ hint ? el('p', { className: 'lcr-empty__hint' }, hint) : null);
247
+ }
248
+
249
+ function ErrorBox({ error, onRetry }) {
250
+ if (!error) return null;
251
+ return el('div', { className: 'lcr-error', role: 'alert' },
252
+ el('span', null, error),
253
+ onRetry ? el('button', { type: 'button', className: 'lcr-btn lcr-btn--ghost', onClick: onRetry }, 'Reintentar') : null);
254
+ }
255
+
256
+ function Confirm({ open, title, body, confirmLabel = 'Confirmar', onCancel, onConfirm }) {
257
+ if (!open) return null;
258
+ return el('div', { className: 'lcr-modal', role: 'dialog', 'aria-modal': 'true', 'aria-label': title },
259
+ el('div', { className: 'lcr-modal__box' },
260
+ el('h3', { className: 'lcr-modal__title' }, title),
261
+ el('p', { className: 'lcr-modal__body' }, body),
262
+ el('div', { className: 'lcr-modal__actions' },
263
+ el('button', { type: 'button', className: 'lcr-btn lcr-btn--ghost', onClick: onCancel }, 'Cancelar'),
264
+ el('button', { type: 'button', className: 'lcr-btn lcr-btn--danger', onClick: onConfirm }, confirmLabel))));
265
+ }
266
+
267
+ function Overview({ snapshot }) {
268
+ const counts = snapshot?.counts || {};
269
+ const health = snapshot?.health || { ok: false, checks: [] };
270
+ const store = snapshot?.store || {};
271
+ const stats = [
272
+ ['Fuentes', counts.sources],
273
+ ['Fragmentos', counts.chunks],
274
+ ['Vectores', counts.vectors],
275
+ ['Etiquetas', counts.tags],
276
+ ['Colecciones', counts.collections],
277
+ ];
278
+ return el('div', { className: 'lcr-stack' },
279
+ el('div', { className: 'lcr-stats' }, stats.map(([label, value]) =>
280
+ el('div', { className: 'lcr-stat', key: label },
281
+ el('span', { className: 'lcr-stat__label' }, label),
282
+ el('strong', { className: 'lcr-stat__value' }, formatNumber(value))))),
283
+ el('div', { className: 'lcr-grid' },
284
+ el(Card, { title: 'Almacén' },
285
+ el('dl', { className: 'lcr-kv' },
286
+ el('dt', null, 'Ruta'), el('dd', { className: 'lcr-mono' }, store.path || '—'),
287
+ el('dt', null, 'Base de datos'), el('dd', null, formatBytes(store.databaseBytes)),
288
+ el('dt', null, 'Auditoría'), el('dd', null, formatBytes(store.auditBytes)),
289
+ el('dt', null, 'Estado'), el('dd', null, store.initialized ? 'inicializado' : 'sin inicializar'))),
290
+ el(Card, { title: 'Salud' },
291
+ health.ok ? el(Chip, { tone: 'ok' }, 'todo en orden') : el(Chip, { tone: 'bad' }, 'revisar'),
292
+ el('ul', { className: 'lcr-checks' }, (health.checks || []).map((check) =>
293
+ el('li', { key: check.name, className: 'lcr-check' },
294
+ el('span', { className: `lcr-dot lcr-dot--${check.status === 'ok' ? 'ok' : check.status === 'warn' ? 'warn' : 'bad'}`, 'aria-hidden': 'true' }),
295
+ el('span', null, check.name),
296
+ el('span', { className: 'lcr-muted' }, check.status))))),
297
+ el(Card, { title: 'Actividad reciente' },
298
+ (snapshot?.activity?.recent || []).length === 0
299
+ ? el(Empty, { title: 'Sin actividad todavía', hint: 'Indexa una fuente para empezar.' })
300
+ : el('ul', { className: 'lcr-activity' },
301
+ (snapshot.activity.recent || []).map((event) =>
302
+ el('li', { key: `${event.seq}-${event.at}` },
303
+ el('span', { className: 'lcr-mono lcr-muted' }, formatTime(event.at)),
304
+ el('span', null, event.action),
305
+ el('span', { className: 'lcr-muted' }, event.target || '')))))));
306
+ }
307
+
308
+ function SourceDetail({ id, onBack, onChanged }) {
309
+ const [detail, setDetail] = useState(null);
310
+ const [error, setError] = useState('');
311
+ const [busy, setBusy] = useState(false);
312
+ const [confirm, setConfirm] = useState(false);
313
+ const [chunks, setChunks] = useState(20);
314
+
315
+ const load = useCallback(async () => {
316
+ setError('');
317
+ try {
318
+ setDetail(await getSource(id));
319
+ } catch (failure) {
320
+ setError(errorText(failure));
321
+ }
322
+ }, [id]);
323
+
324
+ useEffect(() => { void load(); }, [load]);
325
+
326
+ const forget = async () => {
327
+ setBusy(true);
328
+ try {
329
+ await action({ action: 'forget', ref: id, confirm: true });
330
+ setConfirm(false);
331
+ onChanged();
332
+ onBack();
333
+ } catch (failure) {
334
+ setError(errorText(failure));
335
+ } finally {
336
+ setBusy(false);
337
+ }
338
+ };
339
+
340
+ if (error && !detail) return el('div', null, el(ErrorBox, { error, onRetry: load }), el('button', { type: 'button', className: 'lcr-btn lcr-btn--ghost', onClick: onBack }, 'Volver'));
341
+ if (!detail) return el('p', { className: 'lcr-muted' }, 'Cargando fuente…');
342
+
343
+ const source = detail.source || detail;
344
+ return el('div', { className: 'lcr-stack' },
345
+ el('div', { className: 'lcr-row' },
346
+ el('button', { type: 'button', className: 'lcr-btn lcr-btn--ghost', onClick: onBack }, '← Fuentes'),
347
+ el('button', { type: 'button', className: 'lcr-btn lcr-btn--danger', onClick: () => setConfirm(true), disabled: busy }, 'Olvidar fuente')),
348
+ el(Card, { title: source.title || source.id },
349
+ el('dl', { className: 'lcr-kv' },
350
+ el('dt', null, 'Id'), el('dd', { className: 'lcr-mono' }, source.id),
351
+ el('dt', null, 'Ruta'), el('dd', { className: 'lcr-mono' }, source.uri),
352
+ el('dt', null, 'Colección'), el('dd', null, source.collection || '—'),
353
+ el('dt', null, 'Actualizada'), el('dd', null, formatTime(source.updatedAt)),
354
+ el('dt', null, 'Etiquetas'), el('dd', null, (source.tags || []).join(', ') || '—')),
355
+ el(ErrorBox, { error })),
356
+ el(Card, { title: 'Fragmentos' },
357
+ el('ul', { className: 'lcr-chunks' }, (detail.chunks || []).slice(0, chunks).map((chunk) =>
358
+ el('li', { key: chunk.ordinal, className: 'lcr-chunk' },
359
+ el('div', { className: 'lcr-chunk__head' },
360
+ el('span', { className: 'lcr-mono' }, `#${chunk.ordinal}`),
361
+ el('span', { className: 'lcr-muted' }, chunk.heading || '')),
362
+ el('p', { className: 'lcr-chunk__text' }, chunk.text)))),
363
+ (detail.chunks || []).length > chunks
364
+ ? el('button', { type: 'button', className: 'lcr-btn lcr-btn--ghost', onClick: () => setChunks((n) => n + 30 ) }, 'Mostrar más')
365
+ : null),
366
+ el(Confirm, {
367
+ open: confirm,
368
+ title: 'Olvidar fuente',
369
+ body: `Se eliminarán ${formatNumber(source.chunks)} fragmentos y sus vectores. La acción queda auditada y no se puede deshacer.`,
370
+ confirmLabel: busy ? 'Eliminando…' : 'Eliminar',
371
+ onCancel: () => setConfirm(false),
372
+ onConfirm: forget,
373
+ }));
374
+ }
375
+
376
+ function Sources({ onChanged }) {
377
+ const [rows, setRows] = useState(null);
378
+ const [error, setError] = useState('');
379
+ const [selected, setSelected] = useState(null);
380
+ const [path, setPath] = useState('');
381
+ const [collection, setCollection] = useState('');
382
+ const [busy, setBusy] = useState(false);
383
+ const [notice, setNotice] = useState('');
384
+
385
+ const load = useCallback(async () => {
386
+ setError('');
387
+ try {
388
+ const data = await getSources();
389
+ setRows(data.rows || []);
390
+ } catch (failure) {
391
+ setError(errorText(failure));
392
+ }
393
+ }, []);
394
+
395
+ useEffect(() => { void load(); }, [load]);
396
+
397
+ const ingest = async () => {
398
+ if (!path.trim()) {
399
+ setError('Indica una ruta de fichero o carpeta.');
400
+ return;
401
+ }
402
+ setBusy(true);
403
+ setError('');
404
+ setNotice('');
405
+ try {
406
+ const result = await action({ action: 'ingest', paths: [path.trim()], collection: collection.trim() || undefined });
407
+ const failed = (result.errors || []).length;
408
+ setNotice(`Indexados ${result.ingested ?? 0} · omitidos ${result.skipped ?? 0}${failed ? ` · errores ${failed}` : ''}`);
409
+ if (failed) setError(result.errors.map((item) => `${item.path}: ${item.code}`).join('\n'));
410
+ setPath('');
411
+ await load();
412
+ onChanged?.();
413
+ } catch (failure) {
414
+ setError(errorText(failure));
415
+ } finally {
416
+ setBusy(false);
417
+ }
418
+ };
419
+
420
+ if (selected) return el(SourceDetail, { id: selected, onBack: () => setSelected(null), onChanged: load });
421
+
422
+ return el('div', { className: 'lcr-stack' },
423
+ el(Card, { title: 'Añadir fuente' },
424
+ el('div', { className: 'lcr-form' },
425
+ el('label', { className: 'lcr-field' },
426
+ el('span', null, 'Ruta del proyecto'),
427
+ el('input', { className: 'lcr-input lcr-mono', value: path, onChange: (event) => setPath(event.target.value), placeholder: 'docs/ o C:\\\\ruta\\\\a\\\\carpeta' })),
428
+ el('label', { className: 'lcr-field' },
429
+ el('span', null, 'Colección (opcional)'),
430
+ el('input', { className: 'lcr-input', value: collection, onChange: (event) => setCollection(event.target.value), placeholder: 'documentacion' })),
431
+ el('button', { type: 'button', className: 'lcr-btn', onClick: ingest, disabled: busy }, busy ? 'Indexando…' : 'Indexar')),
432
+ el('p', { className: 'lcr-hint' }, 'Se permiten ficheros o carpetas. Los directorios del sistema y las rutas protegidas se rechazan enteras, sin escribir nada.'),
433
+ notice ? el('p', { className: 'lcr-ok' }, notice) : null,
434
+ el(ErrorBox, { error })),
435
+ el(Card, {
436
+ title: 'Fuentes',
437
+ extra: el('button', { type: 'button', className: 'lcr-btn lcr-btn--ghost', onClick: load }, 'Actualizar'),
438
+ },
439
+ rows === null
440
+ ? el('p', { className: 'lcr-muted' }, 'Cargando…')
441
+ : rows.length === 0
442
+ ? el(Empty, { title: 'Sin fuentes', hint: 'Añade una ruta para construir el índice.' })
443
+ : el('table', { className: 'lcr-table' },
444
+ el('thead', null, el('tr', null,
445
+ el('th', { scope: 'col' }, 'Título'),
446
+ el('th', { scope: 'col' }, 'Colección'),
447
+ el('th', { scope: 'col', className: 'lcr-num' }, 'Fragmentos'),
448
+ el('th', { scope: 'col' }, 'Actualizada'))),
449
+ el('tbody', null, rows.map((row) =>
450
+ el('tr', { key: row.id },
451
+ el('td', null,
452
+ el('button', { type: 'button', className: 'lcr-link', onClick: () => setSelected(row.id) }, row.title || row.id),
453
+ el('div', { className: 'lcr-mono lcr-muted lcr-small' }, row.uri)),
454
+ el('td', null, row.collection || '—'),
455
+ el('td', { className: 'lcr-num' }, formatNumber(row.chunks)),
456
+ el('td', null, formatTime(row.updatedAt))))))));
457
+ }
458
+
459
+ function Search({ onContext }) {
460
+ const [query, setQuery] = useState('');
461
+ const [strategy, setStrategy] = useState('hybrid');
462
+ const [limit, setLimit] = useState(8);
463
+ const [result, setResult] = useState(null);
464
+ const [error, setError] = useState('');
465
+ const [busy, setBusy] = useState(false);
466
+
467
+ const run = async () => {
468
+ if (!query.trim()) return;
469
+ setBusy(true);
470
+ setError('');
471
+ try {
472
+ setResult(await search({ query: query.trim(), strategy, limit }));
473
+ } catch (failure) {
474
+ setError(errorText(failure));
475
+ } finally {
476
+ setBusy(false);
477
+ }
478
+ };
479
+
480
+ const rows = result?.results || [];
481
+ return el('div', { className: 'lcr-stack' },
482
+ el(Card, { title: 'Buscar en el conocimiento' },
483
+ el('div', { className: 'lcr-search' },
484
+ el('input', {
485
+ className: 'lcr-input',
486
+ value: query,
487
+ placeholder: '¿Qué necesitas saber?',
488
+ onChange: (event) => setQuery(event.target.value),
489
+ onKeyDown: (event) => { if (event.key === 'Enter') void run(); },
490
+ }),
491
+ el('select', { className: 'lcr-select', value: strategy, onChange: (event) => setStrategy(event.target.value) },
492
+ el('option', { value: 'hybrid' }, 'Híbrida'),
493
+ el('option', { value: 'fts' }, 'Léxica'),
494
+ el('option', { value: 'vector' }, 'Vectorial')),
495
+ el('select', { className: 'lcr-select', value: String(limit), onChange: (event) => setLimit(Number(event.target.value)) },
496
+ [5, 8, 12, 20].map((n) => el('option', { key: n, value: String(n) }, `${n} resultados`))),
497
+ el('button', { type: 'button', className: 'lcr-btn', onClick: run, disabled: busy }, busy ? 'Buscando…' : 'Buscar')),
498
+ el(ErrorBox, { error })),
499
+ result
500
+ ? el(Card, {
501
+ title: `${rows.length} resultado(s)`,
502
+ extra: el('span', { className: 'lcr-muted lcr-small' }, `${result.diagnostics?.strategy || result.mode} · ${result.elapsedMs ?? 0} ms`),
503
+ },
504
+ rows.length === 0
505
+ ? el(Empty, { title: 'Sin resultados', hint: 'Prueba otra formulación o revisa que la fuente esté indexada.' })
506
+ : el('ul', { className: 'lcr-results' }, rows.map((row) =>
507
+ el('li', { key: row.chunkKey, className: 'lcr-result' },
508
+ el('div', { className: 'lcr-result__head' },
509
+ el('strong', null, row.title || row.sourceId),
510
+ row.heading && row.heading !== row.title ? el('span', { className: 'lcr-muted' }, ` › ${row.heading}`) : null,
511
+ el('span', { className: 'lcr-score' }, Number(row.score ?? 0).toFixed(3))),
512
+ el('p', { className: 'lcr-result__text' }, String(row.snippet || '').replace(/[[\]]/g, '').replace(/\*\*/g, '')),
513
+ el('div', { className: 'lcr-row lcr-row--end' },
514
+ el('span', { className: 'lcr-mono lcr-muted lcr-small' }, row.chunkKey),
515
+ el('button', {
516
+ type: 'button',
517
+ className: 'lcr-btn lcr-btn--ghost',
518
+ onClick: () => onContext?.({ query: query.trim(), limit }),
519
+ }, 'Construir contexto con esta consulta'))))))
520
+ : el(Empty, { title: 'Empieza con una consulta', hint: 'La búsqueda usa el mismo motor que las herramientas del modelo.' }));
521
+ }
522
+
523
+ function Context({ seed }) {
524
+ const [query, setQuery] = useState(seed?.query || '');
525
+ const [budget, setBudget] = useState(2000);
526
+ const [result, setResult] = useState(null);
527
+ const [error, setError] = useState('');
528
+ const [busy, setBusy] = useState(false);
529
+
530
+ useEffect(() => { if (seed?.query) setQuery(seed.query); }, [seed]);
531
+
532
+ const run = async () => {
533
+ if (!query.trim()) return;
534
+ setBusy(true);
535
+ setError('');
536
+ try {
537
+ setResult(await buildContext({ query: query.trim(), budgetTokens: budget, maxChunks: 12 }));
538
+ } catch (failure) {
539
+ setError(errorText(failure));
540
+ } finally {
541
+ setBusy(false);
542
+ }
543
+ };
544
+
545
+ return el('div', { className: 'lcr-stack' },
546
+ el(Card, { title: 'Ensamblar contexto' },
547
+ el('div', { className: 'lcr-form lcr-form--inline' },
548
+ el('input', { className: 'lcr-input', value: query, placeholder: 'Consulta', onChange: (event) => setQuery(event.target.value) }),
549
+ el('input', { className: 'lcr-input lcr-input--num', type: 'number', min: 100, max: 8000, step: 100, value: budget, onChange: (event) => setBudget(Number(event.target.value)) }),
550
+ el('button', { type: 'button', className: 'lcr-btn', onClick: run, disabled: busy }, busy ? 'Construyendo…' : 'Construir')),
551
+ el('p', { className: 'lcr-hint' }, 'Presupuesto en tokens estimados. Si el primer fragmento no cabe, se devuelve vacío y marcado como truncado, nunca un fragmento cortado a medias.'),
552
+ el(ErrorBox, { error })),
553
+ result
554
+ ? el('div', { className: 'lcr-grid' },
555
+ el(Card, { title: `Contexto · ${formatNumber(result.tokens)} tokens${result.truncated ? ' · truncado' : ''}` },
556
+ result.text ? el('pre', { className: 'lcr-context' }, result.text) : el(Empty, { title: 'Sin contexto que quepa', hint: 'Reduce los fragmentos o aumenta el presupuesto.' })),
557
+ el(Card, { title: 'Procedencia' },
558
+ el('ol', { className: 'lcr-citations' }, (result.citations || []).map((citation) =>
559
+ el('li', { key: citation.chunkKey },
560
+ el('span', { className: 'lcr-mono' }, `[${citation.n}] ${citation.chunkKey}`),
561
+ el('div', null, citation.title || citation.uri))))))
562
+ : el(Empty, { title: 'Sin contexto todavía', hint: 'Lanza una consulta para ver citas y presupuesto.' }));
563
+ }
564
+
565
+ function Metrics({ snapshot }) {
566
+ const [metric, setMetric] = useState('query.ms');
567
+ const [series, setSeries] = useState(null);
568
+ const [error, setError] = useState('');
569
+
570
+ const load = useCallback(async () => {
571
+ setError('');
572
+ try {
573
+ setSeries(await metricSeries(metric, 7));
574
+ } catch (failure) {
575
+ setError(errorText(failure));
576
+ }
577
+ }, [metric]);
578
+
579
+ useEffect(() => { void load(); }, [load]);
580
+
581
+ const summary = snapshot?.metrics || [];
582
+ const rows = Array.isArray(summary) ? summary : [];
583
+ const points = Array.isArray(series) ? series : (series?.points || []);
584
+ const max = points.reduce((value, point) => Math.max(value, Number(point.value) || 0), 0) || 1;
585
+
586
+ return el('div', { className: 'lcr-stack' },
587
+ el(Card, { title: 'Agregados (últimos 7 días)' },
588
+ rows.length === 0
589
+ ? el(Empty, { title: 'Sin métricas todavía', hint: 'Se registran al buscar, indexar y construir contexto.' })
590
+ : el('table', { className: 'lcr-table' },
591
+ el('thead', null, el('tr', null, el('th', { scope: 'col' }, 'Métrica'), el('th', { scope: 'col' }, 'Dimensión'), el('th', { scope: 'col', className: 'lcr-num' }, 'Total'))),
592
+ el('tbody', null, rows.map((row) =>
593
+ el('tr', { key: `${row.metric}-${row.dim}` },
594
+ el('td', { className: 'lcr-mono' }, row.metric),
595
+ el('td', null, row.dim || '—'),
596
+ el('td', { className: 'lcr-num' }, formatNumber(row.total))))))),
597
+ el(Card, {
598
+ title: 'Serie',
599
+ extra: el('select', { className: 'lcr-select', value: metric, onChange: (event) => setMetric(event.target.value) },
600
+ ['query.ms', 'query.count', 'ingest.documents', 'context.tokens', 'automation.runs'].map((name) =>
601
+ el('option', { key: name, value: name }, name))),
602
+ },
603
+ el(ErrorBox, { error, onRetry: load }),
604
+ points.length === 0
605
+ ? el('p', { className: 'lcr-muted' }, 'Sin datos para esa métrica.')
606
+ : el('div', { className: 'lcr-bars' }, points.map((point) =>
607
+ el('div', { key: point.day, className: 'lcr-bar' },
608
+ el('div', { className: 'lcr-bar__track' },
609
+ el('div', { className: 'lcr-bar__fill', style: { height: `${Math.max(4, (Number(point.value) / max) * 100)}%` } })),
610
+ el('span', { className: 'lcr-muted lcr-small' }, String(point.day).slice(5))))),
611
+ el('p', { className: 'lcr-hint' }, 'Percentiles estimados por histograma; nunca se guardan consultas, prompts ni respuestas.')));
612
+ }
613
+
614
+ function Settings({ snapshot, onSaved }) {
615
+ const config = snapshot?.config || {};
616
+ const [strategy, setStrategy] = useState(config.strategy || 'hybrid');
617
+ const [limit, setLimit] = useState(config.limit ?? 8);
618
+ const [enabled, setEnabled] = useState(Boolean(config.automation?.enabled));
619
+ const [roots, setRoots] = useState((config.automation?.watchRoots || []).join('\n'));
620
+ const [busy, setBusy] = useState(false);
621
+ const [error, setError] = useState('');
622
+ const [notice, setNotice] = useState('');
623
+
624
+ useEffect(() => {
625
+ setStrategy(config.strategy || 'hybrid');
626
+ setLimit(config.limit ?? 8);
627
+ setEnabled(Boolean(config.automation?.enabled));
628
+ setRoots((config.automation?.watchRoots || []).join('\n'));
629
+ }, [config.strategy, config.limit, config.automation?.enabled, config.automation?.watchRoots]);
630
+
631
+ const save = async () => {
632
+ setBusy(true);
633
+ setError('');
634
+ setNotice('');
635
+ try {
636
+ const watchRoots = roots.split('\n').map((line) => line.trim()).filter(Boolean);
637
+ await saveConfig({ search: { strategy, limit }, automation: { enabled, watchRoots } });
638
+ setNotice('Configuración guardada. La automatización se aplica al recargar el plugin.');
639
+ onSaved?.();
640
+ } catch (failure) {
641
+ setError(errorText(failure));
642
+ } finally {
643
+ setBusy(false);
644
+ }
645
+ };
646
+
647
+ return el('div', { className: 'lcr-stack' },
648
+ el(Card, { title: 'Búsqueda' },
649
+ el('div', { className: 'lcr-form' },
650
+ el('label', { className: 'lcr-field' },
651
+ el('span', null, 'Estrategia por defecto'),
652
+ el('select', { className: 'lcr-select', value: strategy, onChange: (event) => setStrategy(event.target.value) },
653
+ el('option', { value: 'hybrid' }, 'Híbrida (léxica + vectorial)'),
654
+ el('option', { value: 'fts' }, 'Sólo léxica'),
655
+ el('option', { value: 'vector' }, 'Sólo vectorial'))),
656
+ el('label', { className: 'lcr-field' },
657
+ el('span', null, 'Resultados por consulta'),
658
+ el('input', { className: 'lcr-input lcr-input--num', type: 'number', min: 1, max: 50, value: limit, onChange: (event) => setLimit(Number(event.target.value)) })),
659
+ el('p', { className: 'lcr-hint' },
660
+ `Embeddings: ${config.embedding?.provider || 'local-hash-v1'} · ${config.embedding?.dim || 256} dims · ${config.embedding?.kind === 'semantic' ? 'semántico' : 'léxico (hash de tokens)'}. La calidad semántica requiere un proveedor neural aprobado.`))),
661
+ el(Card, { title: 'Automatización' },
662
+ el('label', { className: 'lcr-toggle' },
663
+ el('input', { type: 'checkbox', checked: enabled, onChange: (event) => setEnabled(event.target.checked) }),
664
+ el('span', null, 'Indexar automáticamente las carpetas vigiladas')),
665
+ el('label', { className: 'lcr-field' },
666
+ el('span', null, 'Carpetas vigiladas (una por línea, ruta absoluta)'),
667
+ el('textarea', { className: 'lcr-input lcr-mono', rows: 4, value: roots, onChange: (event) => setRoots(event.target.value) })),
668
+ el('p', { className: 'lcr-hint' }, 'La automatización no puede aprobar operaciones sensibles: olvidar fuentes y reindexar siguen exigiendo confirmación explícita.')),
669
+ el('div', { className: 'lcr-row' },
670
+ el('button', { type: 'button', className: 'lcr-btn', onClick: save, disabled: busy }, busy ? 'Guardando…' : 'Guardar configuración')),
671
+ el(ErrorBox, { error }),
672
+ notice ? el('p', { className: 'lcr-ok' }, notice) : null);
673
+ }
674
+
675
+ function Health({ snapshot }) {
676
+ const health = snapshot?.health || { ok: false, checks: [] };
677
+ const store = snapshot?.store || {};
678
+ return el('div', { className: 'lcr-stack' },
679
+ el(Card, { title: 'Comprobaciones' },
680
+ el('ul', { className: 'lcr-checks' }, (health.checks || []).map((check) =>
681
+ el('li', { key: check.name, className: 'lcr-check' },
682
+ el('span', { className: `lcr-dot lcr-dot--${check.status === 'ok' ? 'ok' : check.status === 'warn' ? 'warn' : 'bad'}`, 'aria-hidden': 'true' }),
683
+ el('span', null, check.name),
684
+ el('span', { className: 'lcr-muted' }, check.detail || check.status))))),
685
+ el(Card, { title: 'Diagnóstico' },
686
+ el('dl', { className: 'lcr-kv' },
687
+ el('dt', null, 'Versión de esquema'), el('dd', null, String(store.schemaVersion ?? '—')),
688
+ el('dt', null, 'Base de datos'), el('dd', { className: 'lcr-mono' }, store.path || '—'),
689
+ el('dt', null, 'Tamaño'), el('dd', null, formatBytes(store.databaseBytes)),
690
+ el('dt', null, 'Journal de auditoría'), el('dd', null, formatBytes(store.auditBytes))),
691
+ el('p', { className: 'lcr-hint' }, 'Si algo aparece en rojo, ejecuta el doctor del plugin: `node bin/lifecode-rag.mjs doctor`.')));
692
+ }
693
+
694
+ function Panel(props) {
695
+ const [tab, setTab] = useState('resumen');
696
+ const [snapshot, setSnapshot] = useState(null);
697
+ const [error, setError] = useState('');
698
+ const [seed, setSeed] = useState(null);
699
+ const timer = useRef(null);
700
+
701
+ const load = useCallback(async () => {
702
+ try {
703
+ // LE-RAG-10: negociar modo antes de pedir datos. Solo se pinta el fixture si el
704
+ // servidor PA no confirma 'api'; en ese caso se muestra la razón, nunca una lista vacía.
705
+ if (panelState.mode !== 'api') await negotiateMode();
706
+ if (panelState.mode !== 'api') {
707
+ setSnapshot(null);
708
+ setError('panel sin conexión con la API PA: ' + panelState.reason);
709
+ return;
710
+ }
711
+ setSnapshot(await getSnapshot());
712
+ setError('');
713
+ } catch (failure) {
714
+ const text = errorText(failure);
715
+ setError(text ? text : 'error de transporte');
716
+ }
717
+ }, []);
718
+
719
+ useEffect(() => {
720
+ void load();
721
+ timer.current = setInterval(() => {
722
+ if (document.visibilityState !== 'hidden') void load();
723
+ }, 30_000);
724
+ return () => clearInterval(timer.current);
725
+ }, [load]);
726
+
727
+ const content = useMemo(() => {
728
+ switch (tab) {
729
+ case 'fuentes': return el(Sources, { onChanged: load });
730
+ case 'buscar': return el(Search, { onContext: (payload) => { setSeed(payload); setTab('contexto'); } });
731
+ case 'contexto': return el(Context, { seed });
732
+ case 'metricas': return el(Metrics, { snapshot });
733
+ case 'configuracion': return el(Settings, { snapshot, onSaved: load });
734
+ case 'salud': return el(Health, { snapshot });
735
+ default: return el(Overview, { snapshot });
736
+ }
737
+ }, [tab, snapshot, seed, load]);
738
+
739
+ return el('div', { className: 'lcr-root' },
740
+ el('header', { className: 'lcr-header' },
741
+ el('div', null,
742
+ el('h2', { className: 'lcr-title' }, 'LifeCode RAG'),
743
+ el('p', { className: 'lcr-subtitle' }, 'Conocimiento local, recuperación híbrida y contexto con procedencia.')),
744
+ el('button', { type: 'button', className: 'lcr-btn lcr-btn--ghost', onClick: load, 'aria-label': 'Actualizar datos' }, 'Actualizar')),
745
+ el('nav', { className: 'lcr-tabs', role: 'tablist', 'aria-label': 'Secciones del Workspace' },
746
+ TABS.map(([id, label]) =>
747
+ el('button', {
748
+ key: id,
749
+ type: 'button',
750
+ role: 'tab',
751
+ 'aria-selected': tab === id,
752
+ className: `lcr-tab${tab === id ? ' lcr-tab--active' : ''}`,
753
+ onClick: () => setTab(id),
754
+ }, label))),
755
+ el(ErrorBox, { error, onRetry: load }),
756
+ el('main', { className: 'lcr-main' }, snapshot ? content : el('p', { className: 'lcr-muted' }, 'Cargando Workspace…')));
757
+ }
758
+
759
+ const ICON = (props) => {
760
+ const size = props?.size || 18;
761
+ return el('svg', {
762
+ width: size, height: size, viewBox: '0 0 24 24', fill: 'none',
763
+ stroke: 'currentColor', strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round',
764
+ 'aria-hidden': 'true', focusable: 'false',
765
+ },
766
+ el('path', { d: 'M4 5.5A2.5 2.5 0 0 1 6.5 3H18a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6.5A2.5 2.5 0 0 1 4 18.5z' }),
767
+ el('path', { d: 'M8 7h8M8 11h8M8 15h5' }));
768
+ };
769
+
770
+ const CSS = `
771
+ .lcr-root { display: flex; flex-direction: column; gap: 14px; padding: 18px 20px 28px; color: var(--dsw-alias-label-primary, #e8e8ea); background: var(--dsw-alias-bg-base, #17181c); min-height: 100%; font-size: 13px; line-height: 1.5; }
772
+ .lcr-header { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; }
773
+ .lcr-title { margin: 0; font-size: 20px; font-weight: 650; letter-spacing: -0.01em; }
774
+ .lcr-subtitle { margin: 2px 0 0; color: var(--dsw-alias-label-secondary, #a0a0aa); }
775
+ .lcr-tabs { display: flex; flex-wrap: wrap; gap: 4px; border-bottom: 1px solid var(--dsw-alias-border-l1, #2c2d33); padding-bottom: 6px; }
776
+ .lcr-tab { appearance: none; border: 0; background: transparent; color: var(--dsw-alias-label-secondary, #a0a0aa); padding: 6px 10px; border-radius: 6px; cursor: pointer; font: inherit; }
777
+ .lcr-tab:hover { background: var(--dsw-alias-bg-layer-1, #202127); color: var(--dsw-alias-label-primary, #e8e8ea); }
778
+ .lcr-tab:focus-visible, .lcr-btn:focus-visible, .lcr-input:focus-visible, .lcr-select:focus-visible, .lcr-link:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary, #4f8cff); outline-offset: 2px; }
779
+ .lcr-tab--active { background: color-mix(in oklab, var(--dsw-alias-brand-primary, #4f8cff) 16%, transparent); color: var(--dsw-alias-label-primary, #e8e8ea); font-weight: 600; }
780
+ .lcr-main { display: flex; flex-direction: column; gap: 14px; }
781
+ .lcr-stack { display: flex; flex-direction: column; gap: 14px; }
782
+ .lcr-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 14px; }
783
+ .lcr-card { background: var(--dsw-alias-bg-layer-1, #202127); border: 1px solid var(--dsw-alias-border-l1, #2c2d33); border-radius: 10px; overflow: hidden; }
784
+ .lcr-card__head { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 10px 14px; border-bottom: 1px solid var(--dsw-alias-border-l2, #34353d); }
785
+ .lcr-card__title { margin: 0; font-size: 13px; font-weight: 600; }
786
+ .lcr-card__body { padding: 12px 14px; }
787
+ .lcr-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 10px; }
788
+ .lcr-stat { display: flex; flex-direction: column; gap: 2px; padding: 12px; border-radius: 10px; background: var(--dsw-alias-bg-layer-1, #202127); border: 1px solid var(--dsw-alias-border-l1, #2c2d33); }
789
+ .lcr-stat__label { color: var(--dsw-alias-label-secondary, #a0a0aa); font-size: 12px; }
790
+ .lcr-stat__value { font-size: 22px; font-variant-numeric: tabular-nums; }
791
+ .lcr-kv { display: grid; grid-template-columns: max-content 1fr; gap: 6px 14px; margin: 0; }
792
+ .lcr-kv dt { color: var(--dsw-alias-label-secondary, #a0a0aa); }
793
+ .lcr-kv dd { margin: 0; overflow-wrap: anywhere; }
794
+ .lcr-mono { font-family: ui-monospace, "Cascadia Code", Consolas, monospace; font-size: 12px; }
795
+ .lcr-small { font-size: 11px; }
796
+ .lcr-muted { color: var(--dsw-alias-label-secondary, #a0a0aa); }
797
+ .lcr-hint { margin: 8px 0 0; color: var(--dsw-alias-label-secondary, #a0a0aa); font-size: 12px; }
798
+ .lcr-ok { color: var(--dsw-alias-state-success-primary, #2e9e6b); font-size: 12px; }
799
+ .lcr-error { display: flex; align-items: center; gap: 10px; padding: 10px 12px; border-radius: 8px; background: color-mix(in oklab, var(--dsw-alias-state-error-primary, #e5484d) 12%, transparent); border: 1px solid color-mix(in oklab, var(--dsw-alias-state-error-primary, #e5484d) 40%, transparent); color: var(--dsw-alias-label-primary, #e8e8ea); white-space: pre-wrap; }
800
+ .lcr-chip { display: inline-flex; align-items: center; padding: 1px 8px; border-radius: 999px; font-size: 11px; font-weight: 600; }
801
+ .lcr-chip--ok { background: color-mix(in oklab, var(--dsw-alias-state-success-primary, #2e9e6b) 18%, transparent); color: var(--dsw-alias-state-success-primary, #2e9e6b); }
802
+ .lcr-chip--bad { background: color-mix(in oklab, var(--dsw-alias-state-error-primary, #e5484d) 18%, transparent); color: var(--dsw-alias-state-error-primary, #e5484d); }
803
+ .lcr-chip--neutral { background: var(--dsw-alias-bg-layer-2, #2a2b32); color: var(--dsw-alias-label-secondary, #a0a0aa); }
804
+ .lcr-checks { list-style: none; margin: 10px 0 0; padding: 0; display: flex; flex-direction: column; gap: 6px; }
805
+ .lcr-check { display: grid; grid-template-columns: 10px 1fr max-content; align-items: center; gap: 8px; }
806
+ .lcr-dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; }
807
+ .lcr-dot--ok { background: var(--dsw-alias-state-success-primary, #2e9e6b); }
808
+ .lcr-dot--warn { background: var(--dsw-alias-state-warn-primary, #d68a1f); }
809
+ .lcr-dot--bad { background: var(--dsw-alias-state-error-primary, #e5484d); }
810
+ .lcr-activity { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; }
811
+ .lcr-activity li { display: grid; grid-template-columns: 120px 1fr auto; gap: 10px; padding: 4px 0; border-bottom: 1px solid var(--dsw-alias-border-l2, #34353d); }
812
+ .lcr-form { display: flex; flex-direction: column; gap: 10px; }
813
+ .lcr-form--inline { flex-direction: row; flex-wrap: wrap; align-items: center; }
814
+ .lcr-field { display: flex; flex-direction: column; gap: 4px; font-size: 12px; color: var(--dsw-alias-label-secondary, #a0a0aa); }
815
+ .lcr-input, .lcr-select { background: var(--dsw-alias-bg-base, #17181c); color: var(--dsw-alias-label-primary, #e8e8ea); border: 1px solid var(--dsw-alias-border-l1, #2c2d33); border-radius: 6px; padding: 6px 8px; font: inherit; }
816
+ .lcr-input--num { width: 110px; }
817
+ .lcr-search { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
818
+ .lcr-search .lcr-input { flex: 1 1 260px; }
819
+ .lcr-btn { appearance: none; border: 1px solid var(--dsw-alias-border-l1, #2c2d33); background: var(--dsw-alias-bg-layer-2, #2a2b32); color: var(--dsw-alias-label-primary, #e8e8ea); border-radius: 6px; padding: 6px 12px; font: inherit; cursor: pointer; }
820
+ .lcr-btn:hover:not(:disabled) { border-color: var(--dsw-alias-brand-primary, #4f8cff); }
821
+ .lcr-btn:disabled { opacity: 0.55; cursor: default; }
822
+ .lcr-btn--ghost { background: transparent; }
823
+ .lcr-btn--danger { border-color: color-mix(in oklab, var(--dsw-alias-state-error-primary, #e5484d) 50%, transparent); color: var(--dsw-alias-state-error-primary, #e5484d); }
824
+ .lcr-row { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
825
+ .lcr-row--end { justify-content: flex-end; }
826
+ .lcr-table { width: 100%; border-collapse: collapse; font-size: 12px; }
827
+ .lcr-table th { text-align: left; font-weight: 600; color: var(--dsw-alias-label-secondary, #a0a0aa); padding: 6px 8px; border-bottom: 1px solid var(--dsw-alias-border-l1, #2c2d33); }
828
+ .lcr-table td { padding: 7px 8px; border-bottom: 1px solid var(--dsw-alias-border-l2, #34353d); vertical-align: top; }
829
+ .lcr-num { text-align: right; font-variant-numeric: tabular-nums; }
830
+ .lcr-link { appearance: none; border: 0; background: transparent; color: var(--dsw-alias-brand-primary, #4f8cff); padding: 0; font: inherit; cursor: pointer; text-align: left; }
831
+ .lcr-empty { padding: 18px; text-align: center; border: 1px dashed var(--dsw-alias-border-l1, #2c2d33); border-radius: 8px; }
832
+ .lcr-empty__title { margin: 0; font-weight: 600; }
833
+ .lcr-empty__hint { margin: 4px 0 0; color: var(--dsw-alias-label-secondary, #a0a0aa); font-size: 12px; }
834
+ .lcr-results, .lcr-chunks, .lcr-citations { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 10px; }
835
+ .lcr-result, .lcr-chunk { padding: 10px; border-radius: 8px; background: var(--dsw-alias-bg-base, #17181c); border: 1px solid var(--dsw-alias-border-l2, #34353d); }
836
+ .lcr-result__head, .lcr-chunk__head { display: flex; flex-wrap: wrap; gap: 6px; align-items: baseline; }
837
+ .lcr-score { margin-left: auto; font-variant-numeric: tabular-nums; color: var(--dsw-alias-label-secondary, #a0a0aa); }
838
+ .lcr-result__text, .lcr-chunk__text { margin: 6px 0; color: var(--dsw-alias-label-primary, #e8e8ea); white-space: pre-wrap; }
839
+ .lcr-context { margin: 0; padding: 10px; border-radius: 8px; background: var(--dsw-alias-bg-base, #17181c); border: 1px solid var(--dsw-alias-border-l2, #34353d); white-space: pre-wrap; font-family: inherit; font-size: 12px; max-height: 420px; overflow: auto; }
840
+ .lcr-bars { display: flex; align-items: flex-end; gap: 6px; height: 120px; padding-top: 8px; overflow-x: auto; }
841
+ .lcr-bar { flex: 0 0 48px; display: flex; flex-direction: column; align-items: center; gap: 4px; height: 100%; justify-content: flex-end; }
842
+ .lcr-bar__track { width: 100%; flex: 1; display: flex; align-items: flex-end; background: var(--dsw-alias-bg-base, #17181c); border-radius: 4px; }
843
+ .lcr-bar__fill { width: 100%; background: color-mix(in oklab, var(--dsw-alias-brand-primary, #4f8cff) 55%, transparent); border-radius: 4px 4px 0 0; min-height: 3px; }
844
+ .lcr-toggle { display: flex; align-items: center; gap: 8px; margin-bottom: 10px; }
845
+ .lcr-modal { position: fixed; inset: 0; background: rgba(0, 0, 0, 0.55); display: flex; align-items: center; justify-content: center; z-index: 60; padding: 20px; }
846
+ .lcr-modal__box { background: var(--dsw-alias-bg-layer-1, #202127); border: 1px solid var(--dsw-alias-border-l1, #2c2d33); border-radius: 10px; padding: 18px; max-width: 440px; width: 100%; }
847
+ .lcr-modal__title { margin: 0 0 6px; font-size: 15px; }
848
+ .lcr-modal__body { margin: 0 0 14px; color: var(--dsw-alias-label-secondary, #a0a0aa); }
849
+ .lcr-modal__actions { display: flex; justify-content: flex-end; gap: 8px; }
850
+ @media (prefers-reduced-motion: reduce) { .lcr-root * { transition: none !important; } }
851
+ @media (forced-colors: active) { .lcr-card, .lcr-stat, .lcr-result, .lcr-chunk, .lcr-context { border-color: CanvasText; } }
852
+ `;
853
+
854
+ /* ==========================================================================
855
+ K1 — panel Project-Aware EN MODO SINTÉTICO.
856
+
857
+ Reglas que este bloque respeta:
858
+ - Cero red: los datos salen de fixtures deterministas; las operaciones son simuladas.
859
+ - Cero polling: no hay temporizadores. Si algún día existe 'live', el refresco deberá usar
860
+ `usePanelInfo` (panel activo), no `document.visibilityState`.
861
+ - Cero escritura: nada toca el registro, los almacenes ni el perfil.
862
+ - La UI no decide autorización: sólo pinta el estado que le dan.
863
+ ====================================================================== */
864
+
865
+ const NS = 'lifecode-rag';
866
+ const SYNTHETIC_BANNER = 'SYNTHETIC DATA MODE — DEMO: ESTA VISTA NO LEE EL PROYECTO REAL';
867
+ const PA_BASE_AT = 1763000000000;
868
+ const PA_PAGE_LIMIT = 50;
869
+ const PA_INGEST_PATHS = [
870
+ 'sintetico/nuevo/acta-de-reunion.md',
871
+ 'sintetico/nuevo/decision-de-arquitectura.md',
872
+ 'sintetico/nuevo/guia-de-operacion.md',
873
+ // Caso de error deliberado del fixture: permite ejercitar el estado de error sin tocar nada real.
874
+ 'sintetico/nuevo/informe-escaneado.pdf',
875
+ ];
876
+
877
+ const PA_DICT = {
878
+ es: {
879
+ 'app.title': 'LifeCode RAG',
880
+ 'app.subtitle': 'Proyecto activo, bibliotecas, fuentes y recuperación',
881
+ 'status.client': 'Cliente montado',
882
+ 'status.api': 'API no montada',
883
+ 'status.apiOk': 'API montada',
884
+ 'status.data': 'Demo (fixtures)',
885
+ 'status.dataApi': 'Datos del proyecto',
886
+ 'a11y.status': 'Estado del panel y de la conexión',
887
+ 'app.reset': 'Reiniciar datos sintéticos',
888
+ 'banner.hint': 'Fixture de demostración: no representa el proyecto real. Las herramientas del agente (lifecode_rag_*) sí trabajan con datos reales.',
889
+ 'a11y.tabs': 'Secciones del panel',
890
+ 'a11y.banner': 'Aviso de modo sintético',
891
+ 'nav.project': 'Proyecto',
892
+ 'nav.libraries': 'Bibliotecas',
893
+ 'nav.sources': 'Fuentes',
894
+ 'nav.search': 'Búsqueda',
895
+ 'nav.context': 'Contexto',
896
+ 'nav.operations': 'Operaciones',
897
+ 'nav.diagnostics': 'Diagnóstico',
898
+ 'nav.connection': 'Conexión',
899
+ 'nav.history': 'Historial',
900
+ 'common.none': '—',
901
+ 'common.total': 'Total',
902
+ 'common.previous': 'Anterior',
903
+ 'common.next': 'Siguiente',
904
+ 'common.page': 'Página {page} de {pages}',
905
+ 'common.back': 'Volver',
906
+ 'common.open': 'Abrir',
907
+ 'common.source': 'Fuente',
908
+ 'common.chunks': 'Fragmentos',
909
+ 'common.bytes': 'Bytes',
910
+ 'common.updated': 'Actualizado',
911
+ 'common.indexed': 'Indexado',
912
+ 'common.collection': 'Colección',
913
+ 'common.status': 'Estado',
914
+ 'common.actions': 'Acciones',
915
+ 'common.value': 'Valor',
916
+ 'common.name': 'Nombre',
917
+ 'common.uri': 'URI',
918
+ 'common.store': 'Almacén',
919
+ 'common.roots': 'Raíces',
920
+ 'common.permission': 'Permiso',
921
+ 'common.granted': 'Concedido',
922
+ 'common.simulated': 'Simulado',
923
+ 'common.yes': 'Sí',
924
+ 'common.no': 'No',
925
+ 'common.detail': 'Detalle',
926
+ 'common.first': 'Primera página',
927
+ 'common.last': 'Última página',
928
+ 'common.showing': 'Mostrando {from}–{to} de {total}',
929
+ 'project.title': 'Proyecto activo',
930
+ 'project.candidates': 'Proyectos candidatos',
931
+ 'project.project': 'Proyecto',
932
+ 'project.selection': 'Selección',
933
+ 'project.source': 'Origen',
934
+ 'project.source.explicit': 'explícita',
935
+ 'project.source.cwd': 'directorio de trabajo',
936
+ 'project.revision': 'Revisión',
937
+ 'project.scopes': 'Ámbitos efectivos',
938
+ 'project.service': 'Servicio',
939
+ 'project.current': 'actual',
940
+ 'project.select': 'Seleccionar',
941
+ 'project.selectionCas': 'CR-1: la selección se guarda en el perfil con una revisión; si dos paneles cambian a la vez, el segundo recibe un conflicto y no pisa el cambio del primero.',
942
+ 'libraries.title': 'Bibliotecas autorizadas',
943
+ 'libraries.readonly': 'Sólo lectura: el panel no concede ni revoca bibliotecas.',
944
+ 'libraries.allPresent': 'Todos los almacenes disponibles',
945
+ 'libraries.empty': 'No hay bibliotecas concedidas para este proyecto.',
946
+ 'libraries.gap': 'Una biblioteca revocada desaparece de esta lista; su causa se explica en el proyecto.',
947
+ 'sources.title': 'Fuentes del proyecto',
948
+ 'sources.empty': 'Este proyecto no tiene fuentes indexadas.',
949
+ 'sources.showing': 'Mostrando {shown} de {total}',
950
+ 'sources.capped': 'El listado carga las primeras {loaded} fuentes de {total}; las demás se consultan con las herramientas lifecode_rag_*.',
951
+ 'sources.filter': 'Sólo lectura: la ingesta se hace con las herramientas del agente, nunca desde el panel.',
952
+ 'source.title': 'Detalle de fuente',
953
+ 'source.notFound': 'La fuente ya no está disponible.',
954
+ 'source.chunksShown': 'Se muestran {shown} de {total} fragmentos.',
955
+ 'source.chunksPending': 'La API PA todavía no expone el texto de los fragmentos: aquí sólo se muestran los metadatos de la fuente.',
956
+ 'source.gap05': 'GAP-05: esta versión no pagina fragmentos; el detalle se limita a los primeros.',
957
+ 'source.meta': 'Metadatos',
958
+ 'search.title': 'Búsqueda',
959
+ 'search.placeholder': 'Texto a buscar en el proyecto',
960
+ 'search.run': 'Buscar',
961
+ 'search.running': 'Buscando…',
962
+ 'search.limit': 'Resultados',
963
+ 'search.mode': 'Modo',
964
+ 'search.elapsed': 'Duración',
965
+ 'search.results': 'Resultados con procedencia',
966
+ 'search.scope': 'Ámbito',
967
+ 'search.score': 'Puntuación',
968
+ 'search.noResults': 'Sin resultados para esa consulta.',
969
+ 'search.failed': 'La búsqueda falló',
970
+ 'search.hint': 'La búsqueda se ejecuta sobre datos sintéticos; no consulta el motor.',
971
+ 'search.hintApi': 'La búsqueda consulta el motor del proyecto activo y devuelve procedencia por fuente.',
972
+ 'search.openContext': 'Construir contexto con estos resultados',
973
+ 'context.title': 'Contexto recuperado',
974
+ 'context.build': 'Construir contexto',
975
+ 'context.empty': 'Ejecuta una búsqueda y construye el contexto con sus resultados.',
976
+ 'context.tokens': 'Tokens estimados',
977
+ 'context.truncated': 'Truncado',
978
+ 'context.considered': 'Fragmentos considerados',
979
+ 'context.citations': 'Citas',
980
+ 'context.failed': 'No se pudo construir el contexto',
981
+ 'context.failClosed': 'Con un almacén ilegible, la operación falla en cerrado: no se sirve contexto parcial.',
982
+ 'context.text': 'Texto que se serviría al modelo',
983
+ 'operations.title': 'Operaciones simuladas',
984
+ 'operations.ingest': 'Ingesta simulada',
985
+ 'operations.ingestHint': 'Añade una fuente de ejemplo al fixture. No lee ni escribe ficheros.',
986
+ 'operations.reindex': 'Reindexación simulada',
987
+ 'operations.reindexHint': 'Recorre las fuentes del fixture y cuenta fragmentos. No abre ningún almacén.',
988
+ 'operations.journal': 'Registro de operaciones simuladas',
989
+ 'operations.empty': 'Todavía no se ejecutó ninguna operación simulada.',
990
+ 'operations.noWrite': 'Las operaciones de esta vista no escriben en el RAG ni en el registro de auditoría.',
991
+ 'operations.hostOnly': 'Las operaciones de escritura (ingesta, olvido, reindexación) no se ejecutan desde el panel: la API PA responde 403 y exige aprobación del host. Se lanzan con las herramientas lifecode_rag_*.',
992
+ 'operations.error': 'No se pudo completar la operación simulada',
993
+ 'operations.errorCode': 'Código',
994
+ 'operations.clearError': 'Descartar aviso',
995
+ 'operations.errUnsupported': 'Formato no soportado en el fixture',
996
+ 'operations.errDuplicate': 'URI duplicada',
997
+ 'notice.ingestError': 'La ingesta simulada falló: formato no soportado en el fixture.',
998
+ 'operations.affected': 'Fuentes afectadas',
999
+ 'operations.at': 'Momento',
1000
+ 'operations.kind': 'Tipo',
1001
+ 'diagnostics.title': 'Diagnóstico',
1002
+ 'diagnostics.integrity': 'Integridad',
1003
+ 'diagnostics.registry': 'Registro',
1004
+ 'diagnostics.stores': 'Almacenes',
1005
+ 'diagnostics.auditHead': 'Cabeza de auditoría',
1006
+ 'diagnostics.scopes': 'Ámbitos',
1007
+ 'diagnostics.pendingApi': 'Integridad, auditoría y versiones todavía no se leen de la API PA: esta vista muestra sólo los ámbitos efectivos del proyecto.',
1008
+ 'diagnostics.versions': 'Versiones',
1009
+ 'diagnostics.api': 'API',
1010
+ 'diagnostics.host': 'Anfitrión',
1011
+ 'diagnostics.gap06': 'GAP-06: el diagnóstico multi-ámbito está limitado; se compone por ámbito.',
1012
+ 'diagnostics.gap10': 'GAP-10: no hay detalle por embedding; sólo estado global.',
1013
+ 'diagnostics.gap07': 'GAP-07: las lecturas del panel todavía no se auditan (ui.read no implementado).',
1014
+ 'diagnostics.notAvailable': 'no disponible',
1015
+ 'diagnostics.verified': 'Verificado',
1016
+ 'diagnostics.limitations': 'Limitaciones conocidas',
1017
+ 'diagnostics.fixtureNote': 'Estos valores vienen del fixture sintético: no se leen del anfitrión.',
1018
+ 'diagnostics.storesDetail': '{missing} de {total} almacenes no disponible(s)',
1019
+ 'connection.title': 'Conexión y disponibilidad',
1020
+ 'connection.service': 'Servicio',
1021
+ 'connection.registry': 'Registro',
1022
+ 'connection.storeRoot': 'Raíz de almacenes',
1023
+ 'connection.api': 'API Project-Aware',
1024
+ 'connection.legacy': 'API heredada v0.2',
1025
+ 'connection.notMounted': 'no montada',
1026
+ 'connection.mode': 'Modo de datos',
1027
+ 'connection.notice': 'No hay conexión real: el panel no habla con ninguna API y no puede activarla.',
1028
+ 'connection.noticeLive': 'Conectado a la API del panel: el estado se lee del almacén del perfil y cualquier escritura sigue exigiendo aprobación del host.',
1029
+ 'connection.serviceDetail': 'Servicio degradado: {missing} de {total} almacenes no disponible(s).',
1030
+ 'history.title': 'Historial del proyecto',
1031
+ 'history.unavailable': 'No disponible en esta versión',
1032
+ 'history.why': 'La API no ha devuelto un historial para este proyecto. La vista no inventa entradas.',
1033
+ 'history.route': 'No se inventa una ruta: la vista queda deshabilitada hasta que la API responda.',
1034
+ 'history.simulated': 'Las operaciones de esta sesión se registran en la vista Operaciones, no aquí.',
1035
+ 'history.subtitle': 'Cadena de auditoría del almacén del proyecto activo, de más reciente a más antigua.',
1036
+ 'history.chainOk': 'Cadena verificada ({count} entradas)',
1037
+ 'history.chainBroken': 'Cadena rota en la entrada {at} ({reason})',
1038
+ 'history.empty': 'Este proyecto todavía no tiene operaciones auditadas.',
1039
+ 'history.col.seq': 'N.º',
1040
+ 'history.col.at': 'Fecha',
1041
+ 'history.col.actor': 'Actor',
1042
+ 'history.col.tool': 'Herramienta',
1043
+ 'history.col.action': 'Acción',
1044
+ 'history.col.target': 'Objetivo',
1045
+ 'history.col.outcome': 'Resultado',
1046
+ 'history.col.hash': 'Hash',
1047
+ 'history.page': 'Página {page} de {pages}',
1048
+ 'history.more': 'Cargar más',
1049
+ 'history.total': 'Total',
1050
+ 'history.toOperations': 'Ver operaciones simuladas',
1051
+ 'notice.sameProject': 'Ese proyecto ya está seleccionado; no hubo cambios.',
1052
+ 'notice.selected': 'Selección guardada en el perfil (revisión {revision}).',
1053
+ 'notice.selectedFixture': 'Selección simulada: la revisión subió y el cambio quedó anotado en Operaciones.',
1054
+ 'notice.selectionConflict': 'Otro panel cambió la selección antes: se recargó la revisión vigente y no se sobrescribió nada.',
1055
+ 'notice.selectionFailed': 'No se pudo guardar la selección ({reason}); no se cambió nada.',
1056
+ 'notice.ingest': 'Ingesta simulada completada: una fuente añadida al fixture.',
1057
+ 'notice.reindex': 'Reindexación simulada completada: no se escribió nada.',
1058
+ 'notice.reset': 'Datos sintéticos reiniciados.',
1059
+ 'notice.searchEmpty': 'La búsqueda no devolvió resultados en el fixture.',
1060
+ 'notice.emptyQuery': 'Escribe algo para buscar; no se cambió nada.',
1061
+ 'notice.longQuery': 'La consulta supera el límite de 512 caracteres.',
1062
+ 'notice.duplicateUri': 'Esa URI ya está en el fixture; no se añadió nada.',
1063
+ 'view.errorTitle': 'No se pudo mostrar esta vista',
1064
+ 'view.errorHint': 'El resto del panel sigue disponible. Reintenta o cambia de sección.',
1065
+ 'view.retry': 'Reintentar',
1066
+ },
1067
+ en: {
1068
+ 'app.title': 'LifeCode RAG',
1069
+ 'app.subtitle': 'Active project, libraries, sources and retrieval',
1070
+ 'status.client': 'Client mounted',
1071
+ 'status.api': 'API not mounted',
1072
+ 'status.apiOk': 'API mounted',
1073
+ 'status.data': 'Demo (fixtures)',
1074
+ 'status.dataApi': 'Project data',
1075
+ 'a11y.status': 'Panel and connection status',
1076
+ 'app.reset': 'Reset synthetic data',
1077
+ 'banner.hint': 'Demo fixture: not the real project. Agent tools (lifecode_rag_*) do work with real data.',
1078
+ 'a11y.tabs': 'Panel sections',
1079
+ 'a11y.banner': 'Synthetic mode notice',
1080
+ 'nav.project': 'Project',
1081
+ 'nav.libraries': 'Libraries',
1082
+ 'nav.sources': 'Sources',
1083
+ 'nav.search': 'Search',
1084
+ 'nav.context': 'Context',
1085
+ 'nav.operations': 'Operations',
1086
+ 'nav.diagnostics': 'Diagnostics',
1087
+ 'nav.connection': 'Connection',
1088
+ 'nav.history': 'History',
1089
+ 'common.none': '—',
1090
+ 'common.total': 'Total',
1091
+ 'common.previous': 'Previous',
1092
+ 'common.next': 'Next',
1093
+ 'common.page': 'Page {page} of {pages}',
1094
+ 'common.back': 'Back',
1095
+ 'common.open': 'Open',
1096
+ 'common.source': 'Source',
1097
+ 'common.chunks': 'Chunks',
1098
+ 'common.bytes': 'Bytes',
1099
+ 'common.updated': 'Updated',
1100
+ 'common.indexed': 'Indexed',
1101
+ 'common.collection': 'Collection',
1102
+ 'common.status': 'Status',
1103
+ 'common.actions': 'Actions',
1104
+ 'common.value': 'Value',
1105
+ 'common.name': 'Name',
1106
+ 'common.uri': 'URI',
1107
+ 'common.store': 'Store',
1108
+ 'common.roots': 'Roots',
1109
+ 'common.permission': 'Permission',
1110
+ 'common.granted': 'Granted',
1111
+ 'common.simulated': 'Simulated',
1112
+ 'common.yes': 'Yes',
1113
+ 'common.no': 'No',
1114
+ 'common.detail': 'Detail',
1115
+ 'common.first': 'First page',
1116
+ 'common.last': 'Last page',
1117
+ 'common.showing': 'Showing {from}–{to} of {total}',
1118
+ 'project.title': 'Active project',
1119
+ 'project.candidates': 'Candidate projects',
1120
+ 'project.project': 'Project',
1121
+ 'project.selection': 'Selection',
1122
+ 'project.source': 'Origin',
1123
+ 'project.source.explicit': 'explicit',
1124
+ 'project.source.cwd': 'working directory',
1125
+ 'project.revision': 'Revision',
1126
+ 'project.scopes': 'Effective scopes',
1127
+ 'project.service': 'Service',
1128
+ 'project.current': 'current',
1129
+ 'project.select': 'Select',
1130
+ 'project.selectionCas': 'CR-1: the selection is stored in the profile with a revision; if two panels change it at once, the second gets a conflict and never overwrites the first.',
1131
+ 'libraries.title': 'Authorized libraries',
1132
+ 'libraries.readonly': 'Read-only: the panel neither grants nor revokes libraries.',
1133
+ 'libraries.allPresent': 'All stores available',
1134
+ 'libraries.empty': 'No libraries granted for this project.',
1135
+ 'libraries.gap': 'A revoked library disappears from this list; the cause is explained in the project view.',
1136
+ 'sources.title': 'Project sources',
1137
+ 'sources.empty': 'This project has no indexed sources.',
1138
+ 'sources.showing': 'Showing {shown} of {total}',
1139
+ 'sources.capped': 'The list loads the first {loaded} sources of {total}; the rest are reachable with the lifecode_rag_* tools.',
1140
+ 'sources.filter': 'Read-only: ingestion runs through the agent tools, never from this panel.',
1141
+ 'source.title': 'Source detail',
1142
+ 'source.notFound': 'The source is no longer available.',
1143
+ 'source.chunksShown': 'Showing {shown} of {total} chunks.',
1144
+ 'source.chunksPending': 'The PA API does not expose chunk text yet: only source metadata is shown here.',
1145
+ 'source.gap05': 'GAP-05: this version does not paginate chunks; detail is limited to the first ones.',
1146
+ 'source.meta': 'Metadata',
1147
+ 'search.title': 'Search',
1148
+ 'search.placeholder': 'Text to search in the project',
1149
+ 'search.run': 'Search',
1150
+ 'search.running': 'Searching…',
1151
+ 'search.limit': 'Results',
1152
+ 'search.mode': 'Mode',
1153
+ 'search.elapsed': 'Duration',
1154
+ 'search.results': 'Results with provenance',
1155
+ 'search.scope': 'Scope',
1156
+ 'search.score': 'Score',
1157
+ 'search.noResults': 'No results for that query.',
1158
+ 'search.failed': 'Search failed',
1159
+ 'search.hint': 'Search runs over synthetic data; it does not query the engine.',
1160
+ 'search.hintApi': 'Search queries the active project engine and reports provenance per source.',
1161
+ 'search.openContext': 'Build context from these results',
1162
+ 'context.title': 'Retrieved context',
1163
+ 'context.build': 'Build context',
1164
+ 'context.empty': 'Run a search and build the context from its results.',
1165
+ 'context.tokens': 'Estimated tokens',
1166
+ 'context.truncated': 'Truncated',
1167
+ 'context.considered': 'Chunks considered',
1168
+ 'context.citations': 'Citations',
1169
+ 'context.failed': 'Context could not be built',
1170
+ 'context.failClosed': 'With an unreadable store, the operation fails closed: no partial context is served.',
1171
+ 'context.text': 'Text that would be served to the model',
1172
+ 'operations.title': 'Simulated operations',
1173
+ 'operations.ingest': 'Simulated ingestion',
1174
+ 'operations.ingestHint': 'Adds a sample source to the fixture. It neither reads nor writes files.',
1175
+ 'operations.reindex': 'Simulated reindex',
1176
+ 'operations.reindexHint': 'Walks the fixture sources and counts chunks. It opens no store.',
1177
+ 'operations.journal': 'Simulated operations log',
1178
+ 'operations.empty': 'No simulated operation has run yet.',
1179
+ 'operations.noWrite': 'Operations in this view write neither to the RAG nor to the audit log.',
1180
+ 'operations.hostOnly': 'Write operations (ingest, forget, reindex) never run from this panel: the PA API answers 403 and the host must authorize them. They run through the lifecode_rag_* tools.',
1181
+ 'operations.error': 'The simulated operation could not be completed',
1182
+ 'operations.errorCode': 'Code',
1183
+ 'operations.clearError': 'Dismiss notice',
1184
+ 'operations.errUnsupported': 'Unsupported format in the fixture',
1185
+ 'operations.errDuplicate': 'Duplicate URI',
1186
+ 'notice.ingestError': 'Simulated ingestion failed: unsupported format in the fixture.',
1187
+ 'operations.affected': 'Affected sources',
1188
+ 'operations.at': 'Time',
1189
+ 'operations.kind': 'Type',
1190
+ 'diagnostics.title': 'Diagnostics',
1191
+ 'diagnostics.integrity': 'Integrity',
1192
+ 'diagnostics.registry': 'Registry',
1193
+ 'diagnostics.stores': 'Stores',
1194
+ 'diagnostics.auditHead': 'Audit head',
1195
+ 'diagnostics.scopes': 'Scopes',
1196
+ 'diagnostics.pendingApi': 'Integrity, audit and versions are not read from the PA API yet: this view only shows the effective scopes of the project.',
1197
+ 'diagnostics.versions': 'Versions',
1198
+ 'diagnostics.api': 'API',
1199
+ 'diagnostics.host': 'Host',
1200
+ 'diagnostics.gap06': 'GAP-06: multi-scope diagnostics are limited; they are composed per scope.',
1201
+ 'diagnostics.gap10': 'GAP-10: no per-embedding detail; global state only.',
1202
+ 'diagnostics.gap07': 'GAP-07: panel reads are not audited yet (ui.read not implemented).',
1203
+ 'diagnostics.notAvailable': 'not available',
1204
+ 'diagnostics.verified': 'Verified',
1205
+ 'diagnostics.limitations': 'Known limitations',
1206
+ 'diagnostics.fixtureNote': 'These values come from the synthetic fixture: they are not read from the host.',
1207
+ 'diagnostics.storesDetail': '{missing} of {total} stores unavailable',
1208
+ 'connection.title': 'Connection and availability',
1209
+ 'connection.service': 'Service',
1210
+ 'connection.registry': 'Registry',
1211
+ 'connection.storeRoot': 'Store root',
1212
+ 'connection.api': 'Project-Aware API',
1213
+ 'connection.legacy': 'Legacy v0.2 API',
1214
+ 'connection.notMounted': 'not mounted',
1215
+ 'connection.mode': 'Data mode',
1216
+ 'connection.notice': 'No real connection: the panel talks to no API and cannot enable one.',
1217
+ 'connection.noticeLive': 'Connected to the panel API: state is read from the profile store and every write still needs the host to confirm it.',
1218
+ 'connection.serviceDetail': 'Service degraded: {missing} of {total} stores unavailable.',
1219
+ 'history.title': 'Project history',
1220
+ 'history.unavailable': 'Not available in this version',
1221
+ 'history.why': 'The API returned no history for this project. The view does not invent entries.',
1222
+ 'history.route': 'No route is invented: the view stays disabled until the API answers.',
1223
+ 'history.simulated': 'The operations of this session are logged in the Operations view, not here.',
1224
+ 'history.subtitle': 'Audit chain of the active project store, newest first.',
1225
+ 'history.chainOk': 'Chain verified ({count} entries)',
1226
+ 'history.chainBroken': 'Chain broken at entry {at} ({reason})',
1227
+ 'history.empty': 'This project has no audited operations yet.',
1228
+ 'history.col.seq': 'No.',
1229
+ 'history.col.at': 'Date',
1230
+ 'history.col.actor': 'Actor',
1231
+ 'history.col.tool': 'Tool',
1232
+ 'history.col.action': 'Action',
1233
+ 'history.col.target': 'Target',
1234
+ 'history.col.outcome': 'Outcome',
1235
+ 'history.col.hash': 'Hash',
1236
+ 'history.page': 'Page {page} of {pages}',
1237
+ 'history.more': 'Load more',
1238
+ 'history.total': 'Total',
1239
+ 'history.toOperations': 'View simulated operations',
1240
+ 'notice.sameProject': 'That project is already selected; nothing changed.',
1241
+ 'notice.selected': 'Selection saved to the profile (revision {revision}).',
1242
+ 'notice.selectedFixture': 'Simulated selection: the revision went up and the change was logged in Operations.',
1243
+ 'notice.selectionConflict': 'Another panel changed the selection first: the current revision was reloaded and nothing was overwritten.',
1244
+ 'notice.selectionFailed': 'The selection could not be saved ({reason}); nothing changed.',
1245
+ 'notice.ingest': 'Simulated ingestion complete: one source added to the fixture.',
1246
+ 'notice.reindex': 'Simulated reindex complete: nothing was written.',
1247
+ 'notice.reset': 'Synthetic data reset.',
1248
+ 'notice.searchEmpty': 'The search returned no results in the fixture.',
1249
+ 'notice.emptyQuery': 'Type something to search; nothing changed.',
1250
+ 'notice.longQuery': 'The query exceeds the 512-character limit.',
1251
+ 'notice.duplicateUri': 'That URI is already in the fixture; nothing was added.',
1252
+ 'view.errorTitle': 'This view could not be rendered',
1253
+ 'view.errorHint': 'The rest of the panel is still available. Retry or switch section.',
1254
+ 'view.retry': 'Retry',
1255
+ },
1256
+ };
1257
+
1258
+ function paNormalizeLang(value) {
1259
+ return String(value ?? '').toLowerCase().startsWith('en') ? 'en' : 'es';
1260
+ }
1261
+
1262
+ function paTranslate(lang, key, vars) {
1263
+ const table = PA_DICT[lang] ?? PA_DICT.es;
1264
+ const text = table[key] ?? PA_DICT.es[key] ?? key;
1265
+ if (vars === undefined) return text;
1266
+ return text.replace(/\{(\w+)\}/g, (match, name) => (name in vars ? String(vars[name]) : match));
1267
+ }
1268
+
1269
+ function paReadLanguage(locale) {
1270
+ if (locale === null || locale === undefined) return 'es';
1271
+ try {
1272
+ if (typeof locale.getSnapshot === 'function') {
1273
+ const snapshot = locale.getSnapshot();
1274
+ const value = snapshot?.locale ?? snapshot?.lang ?? snapshot?.id ?? snapshot?.name;
1275
+ if (value !== undefined && value !== null) return paNormalizeLang(value);
1276
+ }
1277
+ if (typeof locale.getLocale === 'function') return paNormalizeLang(locale.getLocale());
1278
+ } catch {
1279
+ /* el locale es presentación: si falla, seguimos en español */
1280
+ }
1281
+ return 'es';
1282
+ }
1283
+
1284
+ /* ----------------------------------------------------------- fixtures */
1285
+
1286
+ function paNum(value) {
1287
+ const text = String(Math.trunc(Number(value) || 0));
1288
+ return text.replace(/\B(?=(\d{3})+(?!\d))/g, '.');
1289
+ }
1290
+
1291
+ function paTime(at) {
1292
+ try {
1293
+ return new Date(at).toISOString().slice(0, 16).replace('T', ' ');
1294
+ } catch {
1295
+ return '—';
1296
+ }
1297
+ }
1298
+
1299
+ function paHash(text) {
1300
+ let hash = 0;
1301
+ for (let i = 0; i < text.length; i += 1) hash = (hash * 31 + text.charCodeAt(i)) % 100000;
1302
+ return hash;
1303
+ }
1304
+
1305
+ function paChunkCount(sourceId) {
1306
+ return 3 + (paHash(sourceId) % 9);
1307
+ }
1308
+
1309
+ function paChunks(source) {
1310
+ const total = source.chunks;
1311
+ const rows = [];
1312
+ for (let ordinal = 0; ordinal < total; ordinal += 1) {
1313
+ rows.push({
1314
+ ordinal,
1315
+ heading: source.title + ' · sección ' + String(ordinal + 1),
1316
+ charStart: ordinal * 1200,
1317
+ charEnd: ordinal * 1200 + 1100,
1318
+ tokenEst: 275,
1319
+ text: 'Fragmento sintético ' + String(ordinal + 1) + ' de «' + source.title + '». Contenido de ejemplo para probar la interfaz: no proviene de ningún documento real ni de ningún almacén.',
1320
+ });
1321
+ }
1322
+ return rows;
1323
+ }
1324
+
1325
+ const PA_DOC_NAMES = {
1326
+ normativa: ['Política de acceso', 'Registro de decisiones', 'Acta de revisión'],
1327
+ producto: ['Manual de producto', 'Guía de producto', 'Plan de pruebas'],
1328
+ operaciones: ['Guía de operación', 'Procedimiento de soporte', 'Contrato de datos'],
1329
+ };
1330
+ const PA_COLLECTIONS = ['normativa', 'producto', 'operaciones'];
1331
+
1332
+ function paBuildSources(count) {
1333
+ const rows = [];
1334
+ for (let i = 1; i <= count; i += 1) {
1335
+ const id = 'src_k1fx_' + String(i).padStart(4, '0');
1336
+ const collection = PA_COLLECTIONS[i % PA_COLLECTIONS.length];
1337
+ const names = PA_DOC_NAMES[collection];
1338
+ const title = names[Math.floor(i / PA_COLLECTIONS.length) % names.length] + ' ' + String(i).padStart(3, '0');
1339
+ rows.push({
1340
+ id,
1341
+ uri: 'sintetico/' + collection + '/doc-' + String(i).padStart(4, '0') + '.md',
1342
+ title,
1343
+ collection,
1344
+ bytes: 800 + ((i * 37) % 4200),
1345
+ chunks: paChunkCount(id),
1346
+ updatedAt: PA_BASE_AT - i * 3600000,
1347
+ indexedAt: PA_BASE_AT - i * 3500000,
1348
+ mime: 'text/markdown',
1349
+ });
1350
+ }
1351
+ return rows;
1352
+ }
1353
+
1354
+ function paFixtures() {
1355
+ const sources = paBuildSources(121);
1356
+ return {
1357
+ session: {
1358
+ api: 'pa-ui/0.1.0-draft',
1359
+ contract: '0.1.0',
1360
+ session: {
1361
+ id: 'session-k1fx-0001',
1362
+ profileKey: 'k1-fixture',
1363
+ state: 'active',
1364
+ invalidReason: null,
1365
+ expiresAt: null,
1366
+ selection: {
1367
+ state: 'active',
1368
+ projectId: 'prj_k1fx_01',
1369
+ projectName: 'Fixture de demostración (no real)',
1370
+ source: 'explicit',
1371
+ revision: 3,
1372
+ selectedBy: 'human',
1373
+ selectedAt: PA_BASE_AT - 3600000,
1374
+ candidates: [],
1375
+ },
1376
+ },
1377
+ project: { id: 'prj_k1fx_01', name: 'Fixture de demostración (no real)', status: 'active' },
1378
+ scopes: [
1379
+ { kind: 'prj', id: 'prj_k1fx_01', name: 'Fixture de demostración (no real)', roots: 2, store: 'present' },
1380
+ { kind: 'lib', id: 'lib_k1fx_01', name: 'Normativa interna', roots: 1, store: 'present', permission: 'read' },
1381
+ { kind: 'lib', id: 'lib_k1fx_02', name: 'Documentación de producto', roots: 1, store: 'missing', permission: 'read' },
1382
+ ],
1383
+ scopeCount: 3,
1384
+ service: { status: 'degraded', registry: 'ok', storeRoot: 'ready' },
1385
+ },
1386
+ projects: [
1387
+ { id: 'prj_k1fx_01', name: 'Fixture de demostración (no real)', current: true, rootCount: 2 },
1388
+ { id: 'prj_k1fx_02', name: 'Biblioteca Compartida Beta', current: false, rootCount: 1 },
1389
+ ],
1390
+ libraries: [
1391
+ { id: 'lib_k1fx_01', name: 'Normativa interna', permission: 'read', grantedAt: PA_BASE_AT - 7200000, grantedBy: 'human', store: 'present', roots: 1 },
1392
+ { id: 'lib_k1fx_02', name: 'Documentación de producto', permission: 'read', grantedAt: PA_BASE_AT - 7100000, grantedBy: 'human', store: 'missing', roots: 1 },
1393
+ ],
1394
+ sources,
1395
+ diagnostics: {
1396
+ session: { id: 'session-k1fx-0001', profileKey: 'k1-fixture', state: 'active' },
1397
+ selection: { projectId: 'prj_k1fx_01', source: 'explicit', revision: 3 },
1398
+ scopes: [
1399
+ { kind: 'prj', id: 'prj_k1fx_01', name: 'Fixture de demostración (no real)', store: 'present', verified: true },
1400
+ { kind: 'lib', id: 'lib_k1fx_01', name: 'Normativa interna', store: 'present', verified: true },
1401
+ { kind: 'lib', id: 'lib_k1fx_02', name: 'Documentación de producto', store: 'missing', verified: false },
1402
+ ],
1403
+ grants: [
1404
+ { libraryId: 'lib_k1fx_01', permission: 'read', grantedAt: PA_BASE_AT - 7200000, state: 'open' },
1405
+ { libraryId: 'lib_k1fx_02', permission: 'read', grantedAt: PA_BASE_AT - 7100000, state: 'open' },
1406
+ ],
1407
+ integrity: { registry: 'ok', stores: 'degraded', auditHead: 42 },
1408
+ versions: { plugin: '1.0.0', contract: '0.1.0', api: 'pa-ui/0.1.0-draft', host: '0.2.2-rc.5' },
1409
+ health: {
1410
+ status: 'degraded',
1411
+ checks: [
1412
+ { id: 'registry', ok: true },
1413
+ { id: 'stores', ok: false },
1414
+ { id: 'audit-chain', ok: true },
1415
+ ],
1416
+ },
1417
+ },
1418
+ health: { api: 'pa-ui/0.1.0-draft', contract: '0.1.0', status: 'degraded', registry: 'ok', legacy: false },
1419
+ };
1420
+ }
1421
+
1422
+ function paInitialState() {
1423
+ const fx = paFixtures();
1424
+ return {
1425
+ view: 'project',
1426
+ mode: 'fixture',
1427
+ session: fx.session,
1428
+ projects: fx.projects,
1429
+ libraries: fx.libraries,
1430
+ sources: fx.sources,
1431
+ sourcePage: { limit: PA_PAGE_LIMIT, offset: 0 },
1432
+ history: { entries: [], total: 0, nextCursor: null, integrity: null, pages: 1, loaded: false, error: null },
1433
+ selectedSourceId: null,
1434
+ query: '',
1435
+ limit: 8,
1436
+ ingestPath: PA_INGEST_PATHS[0],
1437
+ results: null,
1438
+ context: null,
1439
+ diagnostics: fx.diagnostics,
1440
+ health: fx.health,
1441
+ journal: [],
1442
+ clock: 0,
1443
+ opSeq: 0,
1444
+ notice: null,
1445
+ lastError: null,
1446
+ searchInvalid: null,
1447
+ viewEpoch: 0,
1448
+ };
1449
+ }
1450
+
1451
+ /* ------------------------------------------------------------ utilidades */
1452
+
1453
+ function paNormalizeUri(value) {
1454
+ return String(value ?? '')
1455
+ .trim()
1456
+ .replace(/\\/g, '/')
1457
+ .replace(/\/{2,}/g, '/')
1458
+ .toLowerCase();
1459
+ }
1460
+
1461
+ function paPageInfo(state) {
1462
+ const { limit, offset } = state.sourcePage;
1463
+ const total = state.sources.length;
1464
+ const pages = Math.max(1, Math.ceil(total / limit));
1465
+ const page = Math.min(pages, Math.floor(offset / limit) + 1);
1466
+ return {
1467
+ limit,
1468
+ offset: (page - 1) * limit,
1469
+ total,
1470
+ pages,
1471
+ page,
1472
+ from: total === 0 ? 0 : (page - 1) * limit + 1,
1473
+ to: Math.min(total, page * limit),
1474
+ hasPrev: page > 1,
1475
+ hasNext: page < pages,
1476
+ };
1477
+ }
1478
+
1479
+ /* ------------------------------------------------------------ búsqueda */
1480
+
1481
+ function paSearchResults(state, query, limit) {
1482
+ const text = String(query ?? '').trim().toLowerCase();
1483
+ if (text === '') return null;
1484
+ const hits = [];
1485
+ state.sources.forEach((source) => {
1486
+ const haystack = (source.title + ' ' + source.uri + ' ' + source.collection).toLowerCase();
1487
+ if (!haystack.includes(text)) return;
1488
+ hits.push({
1489
+ chunkKey: source.id + ':0',
1490
+ sourceId: source.id,
1491
+ uri: source.uri,
1492
+ title: source.title,
1493
+ heading: 'Introducción',
1494
+ ordinal: 0,
1495
+ rrf: 0.031 - hits.length * 0.001,
1496
+ snippet: 'Coincidencia sintética en «' + source.title + '» para «' + String(query).trim() + '».',
1497
+ scopeId: 'prj_k1fx_01',
1498
+ scopeKind: 'prj',
1499
+ scopeName: 'Fixture de demostración (no real)',
1500
+ });
1501
+ });
1502
+ if (/norm|acces|polit|libr/.test(text) || text.length < 3) {
1503
+ // La procedencia de biblioteca va primero para que se vea aun con el límite por defecto.
1504
+ hits.unshift({
1505
+ chunkKey: 'lib_k1fx_01:0',
1506
+ sourceId: 'src_k1fx_lib_01',
1507
+ uri: 'sintetico/normativa/acceso.md',
1508
+ title: 'Política de acceso (biblioteca)',
1509
+ heading: 'Ámbito de aplicación',
1510
+ ordinal: 0,
1511
+ rrf: 0.019,
1512
+ snippet: 'Resultado sintético de la biblioteca compartida para «' + String(query).trim() + '».',
1513
+ scopeId: 'lib_k1fx_01',
1514
+ scopeKind: 'lib',
1515
+ scopeName: 'Normativa interna',
1516
+ });
1517
+ }
1518
+ const results = hits.slice(0, limit);
1519
+ return {
1520
+ mode: 'hybrid',
1521
+ elapsedMs: 8 + (String(query).length % 11),
1522
+ results,
1523
+ scopes: [
1524
+ { id: 'prj_k1fx_01', kind: 'prj', name: 'Fixture de demostración (no real)', results: results.filter((r) => r.scopeKind === 'prj').length },
1525
+ { id: 'lib_k1fx_01', kind: 'lib', name: 'Normativa interna', results: results.filter((r) => r.scopeKind === 'lib').length },
1526
+ ],
1527
+ };
1528
+ }
1529
+
1530
+ function paBuildContext(state, results) {
1531
+ if (!results || results.length === 0) return null;
1532
+ const chosen = results.slice(0, 3);
1533
+ const lines = chosen.map((row, index) => '[' + String(index + 1) + '] ' + row.title + ' — ' + row.heading + '\n' + row.snippet);
1534
+ const text = lines.join('\n\n');
1535
+ const citations = chosen.map((row, index) => ({
1536
+ n: index + 1,
1537
+ chunkKey: row.chunkKey,
1538
+ sourceId: row.sourceId,
1539
+ uri: row.uri,
1540
+ title: row.title,
1541
+ heading: row.heading,
1542
+ ordinal: row.ordinal,
1543
+ charStart: 0,
1544
+ charEnd: row.snippet.length,
1545
+ }));
1546
+ return {
1547
+ text,
1548
+ citations,
1549
+ tokens: Math.ceil(text.length / 4),
1550
+ truncated: false,
1551
+ considered: results.length,
1552
+ scopes: [
1553
+ { id: 'prj_k1fx_01', kind: 'prj', name: 'Fixture de demostración (no real)' },
1554
+ { id: 'lib_k1fx_01', kind: 'lib', name: 'Normativa interna' },
1555
+ ],
1556
+ elapsedMs: 5,
1557
+ };
1558
+ }
1559
+
1560
+ /* ------------------------------------------------------------- reducer */
1561
+
1562
+ function paJournalEntry(state, kind, detail) {
1563
+ const clock = state.clock + 1;
1564
+ const seq = state.opSeq + 1;
1565
+ const entry = {
1566
+ id: 'op-k1fx-' + String(seq).padStart(3, '0'),
1567
+ at: PA_BASE_AT + clock * 60000,
1568
+ kind,
1569
+ detail,
1570
+ status: 'simulated',
1571
+ };
1572
+ return { clock, seq, journal: [entry, ...state.journal] };
1573
+ }
1574
+
1575
+ function paReduce(state, action) {
1576
+ if (!action || typeof action.type !== 'string') return state;
1577
+ switch (action.type) {
1578
+ case 'hydrate': {
1579
+ const snapshot = action.snapshot || {};
1580
+ const rows = (snapshot.sources && snapshot.sources.rows) || [];
1581
+ // Las filas vienen de la API: se copia lo que la API entrega y nada más. Heredar campos del
1582
+ // fixture (colección, texto de fragmentos) sería inventar datos sobre un proyecto real.
1583
+ const fuentes = rows.map((r) => ({
1584
+ id: r.id,
1585
+ uri: r.uri,
1586
+ title: r.title,
1587
+ mime: r.mime,
1588
+ bytes: Number(r.bytes) || 0,
1589
+ chunks: Number(r.chunks) || 0,
1590
+ collection: r.collection || null,
1591
+ indexedAt: r.indexedAt ?? null,
1592
+ updatedAt: r.updatedAt ?? r.indexedAt ?? null,
1593
+ api: true,
1594
+ }));
1595
+ const scopesRaw = Array.isArray(snapshot.scopes) ? snapshot.scopes : [];
1596
+ const prjScopes = scopesRaw.filter((scope) => (scope.kind || 'prj') === 'prj');
1597
+ // CR-1: la lista de proyectos seleccionables viene del perfil (`snapshot.projects`), no sólo
1598
+ // del proyecto activo; si el servidor no la trae, se conserva la derivación anterior.
1599
+ const proyectos = Array.isArray(snapshot.projects) && snapshot.projects.length > 0
1600
+ ? snapshot.projects.map((row) => ({
1601
+ id: row.id,
1602
+ name: row.name || row.id,
1603
+ current: Boolean(row.current),
1604
+ rootCount: Number(row.roots) || 0,
1605
+ }))
1606
+ : (prjScopes.length > 0
1607
+ ? prjScopes.map((scope) => ({
1608
+ id: scope.id,
1609
+ name: scope.name || scope.id,
1610
+ current: Boolean(snapshot.project) && scope.id === snapshot.project.id,
1611
+ rootCount: Number(scope.roots) || 0,
1612
+ }))
1613
+ : (state.projects || []).map((p, index) => (index === 0 && snapshot.project
1614
+ ? { ...p, id: snapshot.project.id, name: snapshot.project.name } : p)));
1615
+ const totalFuentes = Number(snapshot.sources && snapshot.sources.total);
1616
+ const libraries = (Array.isArray(snapshot.libraries) ? snapshot.libraries : []).map((lib, index) => ({
1617
+ id: lib.id || ('lib_' + index),
1618
+ name: lib.name || lib.id || '—',
1619
+ permission: lib.permission || 'read',
1620
+ grantedAt: Number(lib.grantedAt) || 0,
1621
+ grantedBy: lib.grantedBy || null,
1622
+ store: lib.store || (Number(lib.roots) > 0 ? 'present' : 'missing'),
1623
+ roots: Number(lib.roots) || 0,
1624
+ }));
1625
+ const serviceStatus = snapshot.service || 'ok';
1626
+ const selection = state.session.session.selection;
1627
+ return {
1628
+ ...state,
1629
+ mode: 'api',
1630
+ pending: null,
1631
+ apiVersion: snapshot.version || state.apiVersion || null,
1632
+ error: null,
1633
+ libraries,
1634
+ projects: proyectos,
1635
+ sources: fuentes,
1636
+ sourcesTotal: Number.isFinite(totalFuentes) ? totalFuentes : fuentes.length,
1637
+ sourcePage: { ...(state.sourcePage || {}), offset: 0 },
1638
+ session: {
1639
+ ...state.session,
1640
+ scopeCount: scopesRaw.length,
1641
+ project: snapshot.project
1642
+ ? { ...(state.session.project || {}), id: snapshot.project.id, name: snapshot.project.name, status: 'active' }
1643
+ : state.session.project,
1644
+ service: { ...(state.session.service || {}), status: serviceStatus },
1645
+ session: {
1646
+ ...state.session.session,
1647
+ // CR-1: la revisión que se muestra es la CONFIRMADA por el servidor, no una local.
1648
+ selection: snapshot.selection
1649
+ ? {
1650
+ ...selection,
1651
+ projectId: snapshot.selection.projectId,
1652
+ projectName: snapshot.selection.projectName ?? (snapshot.project ? snapshot.project.name : selection.projectName),
1653
+ state: 'active',
1654
+ source: snapshot.selection.source || 'explicit',
1655
+ selectedBy: snapshot.selection.selectedBy ?? selection.selectedBy,
1656
+ selectedAt: snapshot.selection.selectedAt ?? selection.selectedAt,
1657
+ revision: snapshot.selection.revision,
1658
+ }
1659
+ : (snapshot.project
1660
+ ? { ...selection, projectId: snapshot.project.id, projectName: snapshot.project.name, state: 'active', source: 'explicit' }
1661
+ : selection),
1662
+ },
1663
+ },
1664
+ diagnostics: scopesRaw.length > 0
1665
+ ? { ...state.diagnostics, scopes: scopesRaw.map((scope) => ({
1666
+ kind: scope.kind || 'prj',
1667
+ id: scope.id,
1668
+ name: scope.name || scope.id,
1669
+ store: Number(scope.roots) > 0 ? 'present' : 'missing',
1670
+ verified: true,
1671
+ })) }
1672
+ : state.diagnostics,
1673
+ health: { ...state.health, status: serviceStatus },
1674
+ };
1675
+ }
1676
+ case 'unavailable':
1677
+ return { ...state, mode: 'down', error: action.reason || 'unavailable' };
1678
+ case 'reset':
1679
+ return paInitialState();
1680
+ case 'nav': {
1681
+ const wantsHistory = action.view === 'history' && state.mode === 'api'
1682
+ && !state.history.loaded && state.pending === null;
1683
+ return { ...state, view: action.view, notice: null, ...(wantsHistory ? { pending: 'history' } : {}) };
1684
+ }
1685
+ case 'select-project': {
1686
+ const current = state.session.session.selection;
1687
+ if (!action.projectId || action.projectId === current.projectId) {
1688
+ return { ...state, notice: { code: 'notice.sameProject' } };
1689
+ }
1690
+ const project = state.projects.find((row) => row.id === action.projectId);
1691
+ if (!project) return { ...state, notice: { code: 'notice.sameProject' } };
1692
+ // CR-1: en modo API la selección la confirma el servidor con CAS sobre la revisión. El
1693
+ // panel NO adelanta el cambio: hasta que la respuesta llega, se sigue pintando la última
1694
+ // revisión confirmada.
1695
+ if (state.mode === 'api') {
1696
+ return {
1697
+ ...state,
1698
+ notice: null,
1699
+ pending: 'selection',
1700
+ selectionPending: { projectId: project.id, projectName: project.name, expectedRevision: current.revision },
1701
+ };
1702
+ }
1703
+ const entry = paJournalEntry(state, 'selection', project.name);
1704
+ return {
1705
+ ...state,
1706
+ session: {
1707
+ ...state.session,
1708
+ session: {
1709
+ ...state.session.session,
1710
+ selection: { ...current, projectId: project.id, projectName: project.name, source: 'explicit', revision: current.revision + 1 },
1711
+ },
1712
+ },
1713
+ projects: state.projects.map((row) => ({ ...row, current: row.id === project.id })),
1714
+ clock: entry.clock,
1715
+ opSeq: entry.seq,
1716
+ journal: entry.journal,
1717
+ notice: { code: 'notice.selectedFixture' },
1718
+ };
1719
+ }
1720
+ case 'selection-ok': {
1721
+ const confirmed = action.selection;
1722
+ const project = state.projects.find((row) => row.id === confirmed.projectId);
1723
+ const entry = paJournalEntry(state, 'selection', confirmed.projectName || (project ? project.name : confirmed.projectId));
1724
+ return {
1725
+ ...state,
1726
+ // Las fuentes del proyecto anterior NO valen en el nuevo: se vacían y se pide el snapshot
1727
+ // del proyecto confirmado (si no, se pintarían filas ajenas con el nombre nuevo).
1728
+ pending: 'snapshot',
1729
+ sources: [],
1730
+ sourcesTotal: 0,
1731
+ results: null,
1732
+ context: null,
1733
+ selectedSourceId: null,
1734
+ selectionPending: null,
1735
+ session: {
1736
+ ...state.session,
1737
+ session: {
1738
+ ...state.session.session,
1739
+ selection: {
1740
+ ...state.session.session.selection,
1741
+ projectId: confirmed.projectId,
1742
+ projectName: confirmed.projectName || (project ? project.name : confirmed.projectId),
1743
+ state: 'active',
1744
+ source: confirmed.source || 'explicit',
1745
+ selectedBy: confirmed.selectedBy ?? 'human',
1746
+ selectedAt: confirmed.selectedAt ?? Date.now(),
1747
+ revision: confirmed.revision,
1748
+ },
1749
+ },
1750
+ },
1751
+ projects: state.projects.map((row) => ({ ...row, current: row.id === confirmed.projectId })),
1752
+ clock: entry.clock,
1753
+ opSeq: entry.seq,
1754
+ journal: entry.journal,
1755
+ notice: { code: 'notice.selected', values: { revision: confirmed.revision } },
1756
+ };
1757
+ }
1758
+ case 'selection-error':
1759
+ return {
1760
+ ...state,
1761
+ pending: null,
1762
+ selectionPending: null,
1763
+ notice: {
1764
+ code: action.reason === 'revision-conflict' ? 'notice.selectionConflict' : 'notice.selectionFailed',
1765
+ values: { reason: action.reason || 'transport-error' },
1766
+ },
1767
+ };
1768
+ case 'history-ok': {
1769
+ const page = action.page || {};
1770
+ const entries = Array.isArray(page.entries) ? page.entries : [];
1771
+ const merged = action.append ? [...state.history.entries, ...entries] : entries;
1772
+ const limit = 50;
1773
+ return {
1774
+ ...state,
1775
+ pending: null,
1776
+ history: {
1777
+ entries: merged,
1778
+ total: Number.isFinite(page.total) ? page.total : merged.length,
1779
+ nextCursor: page.nextCursor ?? null,
1780
+ integrity: page.integrity ?? state.history.integrity,
1781
+ pages: Math.max(1, Math.ceil((Number.isFinite(page.total) ? page.total : merged.length) / limit)),
1782
+ loaded: true,
1783
+ error: null,
1784
+ },
1785
+ };
1786
+ }
1787
+ case 'history-error':
1788
+ return {
1789
+ ...state,
1790
+ pending: null,
1791
+ history: { ...state.history, loaded: true, error: action.reason || 'transport-error' },
1792
+ };
1793
+ case 'history-more':
1794
+ if (!state.history.nextCursor || state.pending) return state;
1795
+ return { ...state, pending: 'history' };
1796
+ case 'page': {
1797
+ const maxOffset = Math.max(0, Math.floor((state.sources.length - 1) / state.sourcePage.limit) * state.sourcePage.limit);
1798
+ const offset = Math.min(maxOffset, Math.max(0, Number(action.offset) || 0));
1799
+ return { ...state, sourcePage: { ...state.sourcePage, offset } };
1800
+ }
1801
+ case 'open-source':
1802
+ return { ...state, view: 'source', selectedSourceId: action.id, notice: null };
1803
+ case 'query':
1804
+ return { ...state, query: String(action.value ?? ''), searchInvalid: null };
1805
+ case 'limit':
1806
+ return { ...state, limit: Number(action.value) || 8 };
1807
+ case 'search': {
1808
+ const text = String(state.query ?? '').trim();
1809
+ if (text === '') {
1810
+ return { ...state, view: 'search', searchInvalid: 'empty', notice: { code: 'notice.emptyQuery' } };
1811
+ }
1812
+ if (text.length > 512) {
1813
+ return { ...state, view: 'search', searchInvalid: 'long', notice: { code: 'notice.longQuery' } };
1814
+ }
1815
+ // En modo api la búsqueda va al motor del proyecto: el resultado lo trae el efecto.
1816
+ if (state.mode === 'api') {
1817
+ return { ...state, view: 'search', results: null, context: null, searchInvalid: null, searchError: null, notice: null, pending: 'search' };
1818
+ }
1819
+ const results = paSearchResults(state, text, state.limit);
1820
+ return {
1821
+ ...state,
1822
+ view: 'search',
1823
+ results,
1824
+ context: null,
1825
+ searchInvalid: null,
1826
+ notice: results && results.results.length === 0 ? { code: 'notice.searchEmpty' } : null,
1827
+ };
1828
+ }
1829
+ case 'search-ok':
1830
+ return { ...state, pending: null, searchError: null, view: 'search', results: action.results,
1831
+ notice: action.results && action.results.results.length === 0 ? { code: 'notice.searchEmpty' } : null };
1832
+ case 'search-error':
1833
+ return { ...state, pending: null, results: null, searchError: action.reason || 'transport-error' };
1834
+ case 'retry-view':
1835
+ return { ...state, viewEpoch: (state.viewEpoch ?? 0) + 1, notice: null };
1836
+ case 'context': {
1837
+ if (state.mode === 'api') {
1838
+ return { ...state, view: 'context', contextError: null, pending: 'context' };
1839
+ }
1840
+ const context = state.results && state.results.results.length > 0 ? paBuildContext(state, state.results.results) : null;
1841
+ return { ...state, view: 'context', context, notice: context ? null : { code: 'notice.searchEmpty' } };
1842
+ }
1843
+ case 'context-ok':
1844
+ return { ...state, pending: null, contextError: null, view: 'context', context: action.context, notice: null };
1845
+ case 'context-error':
1846
+ return { ...state, pending: null, context: null, contextError: action.reason || 'transport-error' };
1847
+ case 'ingest-path':
1848
+ return { ...state, ingestPath: String(action.value ?? PA_INGEST_PATHS[0]) };
1849
+ case 'ingest': {
1850
+ const path = String(state.ingestPath ?? '');
1851
+ if (path.toLowerCase().endsWith('.pdf')) {
1852
+ const failed = paJournalEntry(state, 'ingest', path);
1853
+ return {
1854
+ ...state,
1855
+ clock: failed.clock,
1856
+ opSeq: failed.seq,
1857
+ journal: failed.journal,
1858
+ lastError: { code: 'unsupported-format', key: 'operations.errUnsupported', path },
1859
+ notice: { code: 'notice.ingestError' },
1860
+ };
1861
+ }
1862
+ if (state.sources.some((row) => paNormalizeUri(row.uri) === paNormalizeUri(path))) {
1863
+ const rejected = paJournalEntry(state, 'ingest', path);
1864
+ return {
1865
+ ...state,
1866
+ clock: rejected.clock,
1867
+ opSeq: rejected.seq,
1868
+ journal: rejected.journal,
1869
+ lastError: { code: 'duplicate-uri', key: 'operations.errDuplicate', path },
1870
+ notice: { code: 'notice.duplicateUri' },
1871
+ };
1872
+ }
1873
+ const entry = paJournalEntry(state, 'ingest', path);
1874
+ const id = 'src_k1fx_ing_' + String(entry.seq).padStart(2, '0');
1875
+ const source = {
1876
+ id,
1877
+ uri: path,
1878
+ title: 'Documento sintético ' + String(entry.seq).padStart(2, '0'),
1879
+ collection: 'operaciones',
1880
+ bytes: 1024 + entry.seq * 16,
1881
+ chunks: paChunkCount(id),
1882
+ updatedAt: PA_BASE_AT + entry.clock * 60000,
1883
+ indexedAt: PA_BASE_AT + entry.clock * 60000,
1884
+ mime: 'text/markdown',
1885
+ };
1886
+ return {
1887
+ ...state,
1888
+ sources: [source, ...state.sources],
1889
+ clock: entry.clock,
1890
+ opSeq: entry.seq,
1891
+ journal: entry.journal,
1892
+ notice: { code: 'notice.ingest' },
1893
+ };
1894
+ }
1895
+ case 'reindex': {
1896
+ const entry = paJournalEntry(state, 'reindex', String(state.sources.length));
1897
+ return {
1898
+ ...state,
1899
+ clock: entry.clock,
1900
+ opSeq: entry.seq,
1901
+ journal: entry.journal,
1902
+ notice: { code: 'notice.reindex' },
1903
+ };
1904
+ }
1905
+ case 'clear-error':
1906
+ return { ...state, lastError: null, notice: null };
1907
+ default:
1908
+ return state;
1909
+ }
1910
+ }
1911
+
1912
+ /* -------------------------------------------------------------- vistas */
1913
+
1914
+ function paChip(text, tone) {
1915
+ return el('span', { className: 'lcr-pa-chip lcr-pa-chip--' + (tone ?? 'neutral') }, text);
1916
+ }
1917
+
1918
+ function paCard(title, children, extra) {
1919
+ return el('section', { className: 'lcr-pa-card' },
1920
+ el('div', { className: 'lcr-pa-card__head' },
1921
+ el('h2', { className: 'lcr-pa-card__title' }, title),
1922
+ extra ?? null),
1923
+ el('div', { className: 'lcr-pa-card__body' }, children));
1924
+ }
1925
+
1926
+ function paKv(pairs) {
1927
+ const children = [];
1928
+ pairs.forEach((pair, index) => {
1929
+ children.push(el('dt', { key: 'k' + index }, pair[0]));
1930
+ children.push(el('dd', { key: 'v' + index }, pair[1] === null || pair[1] === undefined || pair[1] === '' ? '—' : pair[1]));
1931
+ });
1932
+ return el('dl', { className: 'lcr-pa-kv' }, ...children);
1933
+ }
1934
+
1935
+ function paTable(caption, cols, rows, wrapClass) {
1936
+ return el('div', { className: 'lcr-pa-scroll' + (wrapClass ? ' ' + wrapClass : '') },
1937
+ el('table', { className: 'lcr-pa-table' },
1938
+ el('caption', { className: 'lcr-pa-sr' }, caption),
1939
+ el('thead', null, el('tr', null, ...cols.map((col) => el('th', { key: col, scope: 'col' }, col)))),
1940
+ el('tbody', null, ...rows)));
1941
+ }
1942
+
1943
+ function paEmpty(title, hint) {
1944
+ return el('div', { className: 'lcr-pa-empty' },
1945
+ el('p', { className: 'lcr-pa-empty__title' }, title),
1946
+ hint ? el('p', { className: 'lcr-pa-empty__hint' }, hint) : null);
1947
+ }
1948
+
1949
+ function paNotice(state, t) {
1950
+ if (!state.notice) return null;
1951
+ return el('p', { className: 'lcr-pa-notice' }, t(state.notice.code, state.notice.values));
1952
+ }
1953
+
1954
+ function paKpi(label, value, hint) {
1955
+ return el('div', { className: 'lcr-pa-kpi' },
1956
+ el('span', { className: 'lcr-pa-kpi__label' }, label),
1957
+ el('span', { className: 'lcr-pa-kpi__value' }, value),
1958
+ hint ? el('span', { className: 'lcr-pa-kpi__hint' }, hint) : null);
1959
+ }
1960
+
1961
+ function paViewProject(state, t, dispatch) {
1962
+ const selection = state.session.session.selection;
1963
+ const missingStores = state.diagnostics.scopes.filter((scope) => scope.store !== 'present').length;
1964
+ const missingLibraries = state.libraries.filter((library) => library.store !== 'present').length;
1965
+ const totalFuentes = Number.isFinite(state.sourcesTotal) ? state.sourcesTotal : state.sources.length;
1966
+ const pages = Math.max(1, Math.ceil(state.sources.length / PA_PAGE_LIMIT));
1967
+ const rows = state.projects.map((project) => el('tr', { key: project.id },
1968
+ el('td', null, project.name),
1969
+ el('td', { className: 'lcr-pa-num' }, String(project.rootCount)),
1970
+ el('td', null, project.current ? paChip(t('project.current'), 'ok') : t('common.none')),
1971
+ el('td', null, el('button', {
1972
+ type: 'button',
1973
+ className: 'lcr-pa-btn',
1974
+ disabled: project.current,
1975
+ onClick: () => dispatch({ type: 'select-project', projectId: project.id }),
1976
+ }, t('project.select')))));
1977
+ return el('div', { className: 'lcr-pa-stack' },
1978
+ el('div', { className: 'lcr-pa-kpis' },
1979
+ paKpi(t('project.scopes'), String(state.session.scopeCount), selection.projectName),
1980
+ paKpi(t('nav.libraries'), String(state.libraries.length), missingLibraries > 0
1981
+ ? t('diagnostics.storesDetail', { missing: missingLibraries, total: state.libraries.length })
1982
+ : t('libraries.allPresent')),
1983
+ paKpi(t('nav.sources'), paNum(totalFuentes), t('common.page', { page: 1, pages })),
1984
+ paKpi(t('connection.service'), state.session.service.status,
1985
+ missingStores > 0
1986
+ ? t('connection.serviceDetail', { missing: missingStores, total: state.diagnostics.scopes.length })
1987
+ : t('libraries.allPresent'))),
1988
+ el('div', { className: 'lcr-pa-split' },
1989
+ paCard(t('project.title'), el('div', { className: 'lcr-pa-stack' },
1990
+ paKv([
1991
+ [t('project.project'), selection.projectName],
1992
+ [t('project.selection'), selection.state],
1993
+ [t('project.source'), selection.source === 'explicit' ? t('project.source.explicit') : t('project.source.cwd')],
1994
+ [t('project.revision'), String(selection.revision)],
1995
+ [t('project.scopes'), String(state.session.scopeCount)],
1996
+ [t('project.service'), state.session.service.status],
1997
+ ]),
1998
+ el('p', { className: 'lcr-pa-hint' }, t('project.selectionCas')))),
1999
+ paCard(t('project.candidates'), paTable(t('project.candidates'), [t('project.project'), t('common.roots'), t('common.status'), t('common.actions')], rows))),
2000
+ paNotice(state, t));
2001
+ }
2002
+
2003
+ function paViewLibraries(state, t) {
2004
+ const missingStores = state.libraries.filter((library) => library.store !== 'present').length;
2005
+ const rows = state.libraries.map((library) => el('tr', { key: library.id },
2006
+ el('td', null, library.name),
2007
+ el('td', null, paChip(library.permission, 'lib')),
2008
+ el('td', null, paChip(library.store, library.store === 'present' ? 'ok' : 'warn')),
2009
+ el('td', { className: 'lcr-pa-num' }, String(library.roots)),
2010
+ el('td', null, paTime(library.grantedAt))));
2011
+ return el('div', { className: 'lcr-pa-stack' },
2012
+ paCard(t('libraries.title'),
2013
+ el('div', { className: 'lcr-pa-stack' },
2014
+ el('p', { className: 'lcr-pa-hint' }, t('libraries.readonly')),
2015
+ state.libraries.length === 0
2016
+ ? paEmpty(t('libraries.empty'))
2017
+ : paTable(t('libraries.title'), [t('common.name'), t('common.permission'), t('common.store'), t('common.roots'), t('common.granted')], rows),
2018
+ el('p', { className: 'lcr-pa-hint' }, missingStores > 0
2019
+ ? t('diagnostics.storesDetail', { missing: missingStores, total: state.libraries.length })
2020
+ : t('libraries.allPresent')),
2021
+ el('p', { className: 'lcr-pa-hint' }, t('libraries.gap')))));
2022
+ }
2023
+
2024
+ function paSourcePager(info, t, dispatch) {
2025
+ return el('div', { className: 'lcr-pa-row' },
2026
+ el('span', { className: 'lcr-pa-muted' }, t('common.page', { page: info.page, pages: info.pages })),
2027
+ el('span', { className: 'lcr-pa-row' },
2028
+ el('button', {
2029
+ type: 'button',
2030
+ className: 'lcr-pa-btn lcr-pa-btn--ghost',
2031
+ 'aria-label': t('common.first'),
2032
+ disabled: !info.hasPrev,
2033
+ onClick: () => dispatch({ type: 'page', offset: 0 }),
2034
+ }, '«'),
2035
+ el('button', {
2036
+ type: 'button',
2037
+ className: 'lcr-pa-btn',
2038
+ disabled: !info.hasPrev,
2039
+ onClick: () => dispatch({ type: 'page', offset: info.offset - info.limit }),
2040
+ }, t('common.previous')),
2041
+ el('button', {
2042
+ type: 'button',
2043
+ className: 'lcr-pa-btn',
2044
+ disabled: !info.hasNext,
2045
+ onClick: () => dispatch({ type: 'page', offset: info.offset + info.limit }),
2046
+ }, t('common.next')),
2047
+ el('button', {
2048
+ type: 'button',
2049
+ className: 'lcr-pa-btn lcr-pa-btn--ghost',
2050
+ 'aria-label': t('common.last'),
2051
+ disabled: !info.hasNext,
2052
+ onClick: () => dispatch({ type: 'page', offset: (info.pages - 1) * info.limit }),
2053
+ }, '»')));
2054
+ }
2055
+
2056
+ function paViewSources(state, t, dispatch) {
2057
+ const info = paPageInfo(state);
2058
+ const totalProyecto = Number.isFinite(state.sourcesTotal) ? state.sourcesTotal : info.total;
2059
+ const pageRows = state.sources.slice(info.offset, info.offset + info.limit);
2060
+ const rows = pageRows.map((source) => el('tr', { key: source.id },
2061
+ el('td', null, source.title),
2062
+ el('td', null, el('span', { className: 'lcr-pa-mono lcr-pa-celluri', title: source.uri }, source.uri)),
2063
+ el('td', null, paChip(source.collection || '—', 'lib')),
2064
+ el('td', { className: 'lcr-pa-num' }, String(source.chunks)),
2065
+ el('td', { className: 'lcr-pa-num' }, paNum(source.bytes)),
2066
+ el('td', null, paTime(source.updatedAt)),
2067
+ el('td', null, el('button', {
2068
+ type: 'button',
2069
+ className: 'lcr-pa-btn',
2070
+ onClick: () => dispatch({ type: 'open-source', id: source.id }),
2071
+ }, t('common.open')))));
2072
+ return el('div', { className: 'lcr-pa-stack' },
2073
+ paCard(t('sources.title'),
2074
+ el('div', { className: 'lcr-pa-stack' },
2075
+ el('div', { className: 'lcr-pa-toolbar' },
2076
+ el('span', { className: 'lcr-pa-toolbar__group' },
2077
+ paChip(t('nav.sources') + ': ' + paNum(totalProyecto), 'lib'),
2078
+ el('span', { className: 'lcr-pa-muted' }, t('sources.showing', { shown: pageRows.length, total: totalProyecto })))),
2079
+ el('p', { className: 'lcr-pa-hint' }, t('sources.filter')),
2080
+ totalProyecto > info.total
2081
+ ? el('p', { className: 'lcr-pa-hint' }, t('sources.capped', { loaded: info.total, total: totalProyecto }))
2082
+ : null,
2083
+ info.total === 0
2084
+ ? paEmpty(t('sources.empty'))
2085
+ : paTable(t('sources.title'), [t('common.name'), t('common.uri'), t('common.collection'), t('common.chunks'), t('common.bytes'), t('common.updated'), t('common.actions')], rows, 'lcr-pa-tablewrap')),
2086
+ info.total === 0 ? null : paSourcePager(info, t, dispatch)),
2087
+ paNotice(state, t));
2088
+ }
2089
+
2090
+ function paViewSource(state, t, dispatch) {
2091
+ const source = state.sources.find((row) => row.id === state.selectedSourceId);
2092
+ const back = () => dispatch({ type: 'nav', view: 'sources' });
2093
+ if (!source) {
2094
+ return paCard(t('source.title'), el('div', { className: 'lcr-pa-stack' },
2095
+ paEmpty(t('source.notFound')),
2096
+ el('div', { className: 'lcr-pa-row' },
2097
+ el('button', { type: 'button', className: 'lcr-pa-btn', onClick: back }, t('common.back')))));
2098
+ }
2099
+ // Una fuente hidratada desde la API no trae el texto de los fragmentos: no se inventa.
2100
+ const apiSource = source.api === true;
2101
+ const chunks = apiSource ? [] : paChunks(source);
2102
+ const shown = chunks.slice(0, 8);
2103
+ const rows = shown.map((chunk) => el('tr', { key: chunk.ordinal },
2104
+ el('td', { className: 'lcr-pa-num' }, String(chunk.ordinal)),
2105
+ el('td', null, chunk.heading),
2106
+ el('td', { className: 'lcr-pa-mono' }, chunk.charStart + '..' + chunk.charEnd),
2107
+ el('td', { className: 'lcr-pa-num' }, String(chunk.tokenEst)),
2108
+ el('td', { className: 'lcr-pa-chunk-cell' }, chunk.text)));
2109
+ return el('div', { className: 'lcr-pa-stack' },
2110
+ paCard(source.title, el('div', { className: 'lcr-pa-stack' },
2111
+ el('div', { className: 'lcr-pa-toolbar' },
2112
+ el('button', { type: 'button', className: 'lcr-pa-btn', onClick: back }, t('common.back')),
2113
+ el('span', { className: 'lcr-pa-toolbar__group' },
2114
+ paChip(source.collection || '—', 'lib'),
2115
+ paChip(paNum(source.bytes) + ' B'),
2116
+ paChip(String(source.chunks) + ' ' + t('common.chunks')))),
2117
+ paKv([
2118
+ [t('common.uri'), source.uri],
2119
+ [t('common.collection'), source.collection || '—'],
2120
+ [t('common.bytes'), paNum(source.bytes)],
2121
+ [t('common.chunks'), String(source.chunks)],
2122
+ [t('common.indexed'), paTime(source.indexedAt)],
2123
+ ]),
2124
+ el('h3', { className: 'lcr-pa-subtitle' }, t('common.chunks')),
2125
+ apiSource
2126
+ ? el('p', { className: 'lcr-pa-hint' }, t('source.chunksPending'))
2127
+ : el('div', null,
2128
+ el('p', { className: 'lcr-pa-hint' }, t('source.chunksShown', { shown: shown.length, total: source.chunks })),
2129
+ paTable(t('common.chunks'), ['#', t('common.name'), 'charStart..charEnd', 'tokens', t('common.value')], rows, 'lcr-pa-tablewrap'),
2130
+ el('p', { className: 'lcr-pa-hint' }, t('source.gap05'))))));
2131
+ }
2132
+
2133
+ function paViewSearch(state, t, dispatch) {
2134
+ const results = state.results;
2135
+ const message = state.searchInvalid === 'empty' ? t('notice.emptyQuery')
2136
+ : state.searchInvalid === 'long' ? t('notice.longQuery') : null;
2137
+ const hasResults = Boolean(results && results.results.length > 0);
2138
+ const rows = results
2139
+ ? results.results.map((row, index) => el('tr', { key: row.chunkKey },
2140
+ el('td', { className: 'lcr-pa-num' }, String(index + 1)),
2141
+ el('td', null, row.title),
2142
+ el('td', null, row.heading || row.uri || '—'),
2143
+ el('td', null, row.scopeName ? paChip(row.scopeName + ' · ' + row.scopeKind, row.scopeKind === 'lib' ? 'lib' : 'prj') : '—'),
2144
+ el('td', null, row.snippet || '—'),
2145
+ el('td', { className: 'lcr-pa-num' }, row.score === null || row.score === undefined ? '—' : Number(row.score).toFixed(3))))
2146
+ : [];
2147
+ return el('div', { className: 'lcr-pa-stack' },
2148
+ el('section', { className: 'lcr-pa-hero' },
2149
+ el('h2', { className: 'lcr-pa-card__title' }, t('search.title')),
2150
+ el('div', { className: 'lcr-pa-hero__form' },
2151
+ el('input', {
2152
+ type: 'text',
2153
+ className: 'lcr-pa-input',
2154
+ value: state.query,
2155
+ placeholder: t('search.placeholder'),
2156
+ 'aria-label': t('search.placeholder'),
2157
+ 'aria-invalid': message ? 'true' : 'false',
2158
+ 'aria-describedby': 'lcr-pa-search-msg',
2159
+ 'data-field': 'query',
2160
+ onChange: (event) => dispatch({ type: 'query', value: event.target.value }),
2161
+ }),
2162
+ el('label', { className: 'lcr-pa-field' }, t('search.limit'),
2163
+ el('select', {
2164
+ className: 'lcr-pa-input',
2165
+ value: String(state.limit),
2166
+ 'data-field': 'limit',
2167
+ onChange: (event) => dispatch({ type: 'limit', value: event.target.value }),
2168
+ }, ['8', '20', '50'].map((value) => el('option', { key: value, value }, value)))),
2169
+ el('button', { type: 'button', className: 'lcr-pa-btn lcr-pa-btn--primary', disabled: state.pending === 'search', onClick: () => dispatch({ type: 'search' }) }, state.pending === 'search' ? t('search.running') : t('search.run'))),
2170
+ el('p', { className: 'lcr-pa-hint', id: 'lcr-pa-search-msg' }, message
2171
+ ?? (state.searchError ? t('search.failed') + ' · ' + state.searchError
2172
+ : (state.mode === 'api' ? t('search.hintApi') : t('search.hint'))))),
2173
+ results && results.results.length === 0
2174
+ ? paCard(t('search.results'), paEmpty(t('search.noResults'), t('search.hint')))
2175
+ : null,
2176
+ results && results.results.length > 0
2177
+ ? paCard(t('search.results'), el('div', { className: 'lcr-pa-stack' },
2178
+ el('div', { className: 'lcr-pa-toolbar' },
2179
+ el('span', { className: 'lcr-pa-toolbar__group' },
2180
+ paChip(t('search.mode') + ': ' + results.mode, 'ok'),
2181
+ paChip(String(results.elapsedMs) + ' ms'),
2182
+ paChip(String(results.results.length) + ' / ' + String(state.limit))),
2183
+ el('button', {
2184
+ type: 'button',
2185
+ className: 'lcr-pa-btn lcr-pa-btn--primary',
2186
+ disabled: !hasResults,
2187
+ onClick: () => dispatch({ type: 'context' }),
2188
+ }, t('search.openContext'))),
2189
+ paTable(t('search.results'), ['#', t('common.name'), t('common.value'), t('search.scope'), t('common.detail'), t('search.score')], rows, 'lcr-pa-tablewrap')))
2190
+ : null,
2191
+ paNotice(state, t));
2192
+ }
2193
+
2194
+ function paViewContext(state, t, dispatch) {
2195
+ const context = state.context;
2196
+ const rows = context
2197
+ ? context.citations.map((citation) => el('tr', { key: citation.n },
2198
+ el('td', { className: 'lcr-pa-num' }, String(citation.n)),
2199
+ el('td', null, citation.title),
2200
+ el('td', { className: 'lcr-pa-mono' }, citation.uri),
2201
+ el('td', null, citation.heading),
2202
+ el('td', { className: 'lcr-pa-num' }, String(citation.ordinal)),
2203
+ el('td', { className: 'lcr-pa-mono' }, citation.charStart + '..' + citation.charEnd)))
2204
+ : [];
2205
+ return el('div', { className: 'lcr-pa-stack' },
2206
+ paCard(t('context.title'), el('div', { className: 'lcr-pa-stack' },
2207
+ el('div', { className: 'lcr-pa-row lcr-pa-row--end' },
2208
+ el('button', {
2209
+ type: 'button',
2210
+ className: 'lcr-pa-btn lcr-pa-btn--primary',
2211
+ disabled: state.pending === 'context' || !(state.results && state.results.results.length > 0),
2212
+ onClick: () => dispatch({ type: 'context' }),
2213
+ }, t('context.build'))),
2214
+ state.contextError ? el('p', { className: 'lcr-pa-error__title' }, t('context.failed') + ' · ' + state.contextError) : null,
2215
+ context === null
2216
+ ? paEmpty(t('context.empty'), t('context.failClosed'))
2217
+ : el('div', { className: 'lcr-pa-stack' },
2218
+ el('div', { className: 'lcr-pa-kpis' },
2219
+ context.tokens === null || context.tokens === undefined ? null : paKpi(t('context.tokens'), String(context.tokens)),
2220
+ context.truncated === null || context.truncated === undefined ? null : paKpi(t('context.truncated'), context.truncated ? t('common.yes') : t('common.no')),
2221
+ context.considered === null || context.considered === undefined ? null : paKpi(t('context.considered'), String(context.considered))),
2222
+ el('h3', { className: 'lcr-pa-subtitle' }, t('context.text')),
2223
+ el('pre', { className: 'lcr-pa-context' }, context.text),
2224
+ el('h3', { className: 'lcr-pa-subtitle' }, t('context.citations')),
2225
+ paTable(t('context.citations'), ['#', t('common.name'), t('common.uri'), t('common.value'), 'ordinal', 'offsets'], rows, 'lcr-pa-tablewrap'),
2226
+ el('p', { className: 'lcr-pa-hint' }, t('context.failClosed'))))),
2227
+ paNotice(state, t));
2228
+ }
2229
+
2230
+ function paViewOperations(state, t, dispatch) {
2231
+ // En modo api no hay operaciones simuladas que ofrecer: las de escritura exigen aprobación del
2232
+ // host y responden 403 desde la API. Se declara en vez de fingir botones que no escriben.
2233
+ if (state.mode === 'api') {
2234
+ return el('div', { className: 'lcr-pa-stack' },
2235
+ paCard(t('nav.operations'), el('div', { className: 'lcr-pa-stack' },
2236
+ el('p', { className: 'lcr-pa-hint' }, t('operations.hostOnly')))),
2237
+ paNotice(state, t));
2238
+ }
2239
+ const rows = state.journal.map((entry) => el('tr', { key: entry.id },
2240
+ el('td', { className: 'lcr-pa-mono' }, entry.id),
2241
+ el('td', null, paTime(entry.at)),
2242
+ el('td', null, entry.kind),
2243
+ el('td', null, entry.detail),
2244
+ el('td', null, paChip(t('common.simulated'), 'warn'))));
2245
+ return el('div', { className: 'lcr-pa-stack' },
2246
+ paCard(t('operations.title'), el('div', { className: 'lcr-pa-stack' },
2247
+ el('p', { className: 'lcr-pa-hint' }, t('operations.noWrite')),
2248
+ state.lastError ? el('div', { className: 'lcr-pa-error' },
2249
+ el('p', { className: 'lcr-pa-error__title' }, t(state.lastError.key ?? 'operations.error')),
2250
+ el('p', { className: 'lcr-pa-hint' }, t('operations.errorCode') + ': ' + state.lastError.code + ' · ' + state.lastError.path),
2251
+ el('button', { type: 'button', className: 'lcr-pa-btn', onClick: () => dispatch({ type: 'clear-error' }) }, t('operations.clearError'))) : null,
2252
+ el('div', { className: 'lcr-pa-grid' },
2253
+ paCard(t('operations.ingest'), el('div', { className: 'lcr-pa-stack' },
2254
+ el('p', { className: 'lcr-pa-hint' }, t('operations.ingestHint')),
2255
+ el('label', { className: 'lcr-pa-field' }, t('common.uri'),
2256
+ el('select', {
2257
+ className: 'lcr-pa-input',
2258
+ value: state.ingestPath,
2259
+ 'data-field': 'ingest-path',
2260
+ onChange: (event) => dispatch({ type: 'ingest-path', value: event.target.value }),
2261
+ }, PA_INGEST_PATHS.map((value) => el('option', { key: value, value }, value)))),
2262
+ el('div', { className: 'lcr-pa-row' },
2263
+ el('button', { type: 'button', className: 'lcr-pa-btn lcr-pa-btn--primary', onClick: () => dispatch({ type: 'ingest' }) }, t('operations.ingest')))),
2264
+ paChip(t('common.simulated'), 'warn')),
2265
+ paCard(t('operations.reindex'), el('div', { className: 'lcr-pa-stack' },
2266
+ el('p', { className: 'lcr-pa-hint' }, t('operations.reindexHint')),
2267
+ el('p', { className: 'lcr-pa-hint' }, t('operations.affected') + ': ' + String(state.sources.length)),
2268
+ el('div', { className: 'lcr-pa-row' },
2269
+ el('button', { type: 'button', className: 'lcr-pa-btn lcr-pa-btn--primary', onClick: () => dispatch({ type: 'reindex' }) }, t('operations.reindex')))),
2270
+ paChip(t('common.simulated'), 'warn'))))),
2271
+ paCard(t('operations.journal'),
2272
+ state.journal.length === 0
2273
+ ? paEmpty(t('operations.empty'))
2274
+ : paTable(t('operations.journal'), ['id', t('operations.at'), t('operations.kind'), t('common.detail'), t('common.status')], rows, 'lcr-pa-tablewrap')),
2275
+ paNotice(state, t));
2276
+ }
2277
+
2278
+ function paViewDiagnostics(state, t) {
2279
+ const diagnostics = state.diagnostics;
2280
+ const missingStores = diagnostics.scopes.filter((scope) => scope.store !== 'present').length;
2281
+ const scopeRows = diagnostics.scopes.map((scope) => el('tr', { key: scope.id },
2282
+ el('td', null, scope.kind),
2283
+ el('td', { className: 'lcr-pa-mono' }, scope.id),
2284
+ el('td', null, scope.name),
2285
+ el('td', null, scope.store),
2286
+ el('td', null, scope.verified ? t('common.yes') : t('common.no'))));
2287
+ // En modo api sólo los ámbitos vienen de la API; integridad, auditoría y versiones son del
2288
+ // fixture, así que no se pintan (nada de cifras inventadas bajo un panel conectado).
2289
+ if (state.mode === 'api') {
2290
+ return el('div', { className: 'lcr-pa-stack' },
2291
+ paCard(t('diagnostics.scopes'), paTable(t('diagnostics.scopes'), ['kind', 'id', t('common.name'), t('common.store'), t('diagnostics.verified')], scopeRows, 'lcr-pa-tablewrap')),
2292
+ el('p', { className: 'lcr-pa-hint' }, t('diagnostics.pendingApi')));
2293
+ }
2294
+ const versions = paKv([
2295
+ ['plugin', diagnostics.versions.plugin],
2296
+ ['contract', diagnostics.versions.contract],
2297
+ [t('diagnostics.api'), diagnostics.versions.api],
2298
+ [t('diagnostics.host'), diagnostics.versions.host],
2299
+ ]);
2300
+ return el('div', { className: 'lcr-pa-stack' },
2301
+ el('div', { className: 'lcr-pa-kpis' },
2302
+ paKpi(t('diagnostics.registry'), diagnostics.integrity.registry),
2303
+ paKpi(t('diagnostics.stores'), diagnostics.integrity.stores, t('diagnostics.storesDetail', { missing: missingStores, total: diagnostics.scopes.length })),
2304
+ paKpi(t('diagnostics.auditHead'), String(diagnostics.integrity.auditHead))),
2305
+ el('div', { className: 'lcr-pa-split' },
2306
+ paCard(t('diagnostics.scopes'), paTable(t('diagnostics.scopes'), ['kind', 'id', t('common.name'), t('common.store'), t('diagnostics.verified')], scopeRows, 'lcr-pa-tablewrap')),
2307
+ paCard(t('diagnostics.versions'), el('div', { className: 'lcr-pa-stack' }, versions,
2308
+ el('p', { className: 'lcr-pa-hint' }, t('diagnostics.fixtureNote')),
2309
+ el('h3', { className: 'lcr-pa-subtitle' }, t('diagnostics.limitations')),
2310
+ el('ul', { className: 'lcr-pa-list' },
2311
+ el('li', { className: 'lcr-pa-list__item' }, paChip('GAP-06', 'warn'), el('span', null, t('diagnostics.gap06'))),
2312
+ el('li', { className: 'lcr-pa-list__item' }, paChip('GAP-10', 'warn'), el('span', null, t('diagnostics.gap10'))),
2313
+ el('li', { className: 'lcr-pa-list__item' }, paChip('GAP-07', 'warn'), el('span', null, t('diagnostics.gap07'))))))));
2314
+ }
2315
+
2316
+ function paViewConnection(state, t) {
2317
+ const health = state.health;
2318
+ const mounted = state.mode === 'api';
2319
+ const missingStores = state.diagnostics.scopes.filter((scope) => scope.store !== 'present').length;
2320
+ // En modo api sólo se muestra lo que la API confirma; registry/storeRoot/legacy son del fixture
2321
+ // y no se pintan para no presentar datos inventados como estado real.
2322
+ const pairs = mounted
2323
+ ? [
2324
+ [t('connection.service'), health.status],
2325
+ [t('connection.api'), PA_API + (state.apiVersion ? ' · ' + state.apiVersion : '')],
2326
+ [t('connection.mode'), panelState.mode + (panelState.reason && panelState.reason !== panelState.mode ? ' · ' + panelState.reason : '')],
2327
+ [t('project.project'), state.session.session.selection.projectName],
2328
+ [t('project.scopes'), String(state.session.scopeCount)],
2329
+ ]
2330
+ : [
2331
+ [t('connection.service'), health.status],
2332
+ [t('connection.registry'), health.registry],
2333
+ [t('connection.storeRoot'), state.session.service.storeRoot],
2334
+ [t('connection.api'), t('connection.notMounted')],
2335
+ [t('connection.legacy'), health.legacy ? 'legacy' : 'no'],
2336
+ [t('connection.mode'), panelState.mode + ' · ' + panelState.reason],
2337
+ ];
2338
+ return el('div', { className: 'lcr-pa-stack' },
2339
+ paCard(t('connection.title'), el('div', { className: 'lcr-pa-stack' },
2340
+ el('div', { className: 'lcr-pa-toolbar' },
2341
+ el('span', { className: 'lcr-pa-toolbar__group' },
2342
+ paChip(t('status.client'), 'ok'),
2343
+ paChip(mounted ? t('status.apiOk') : t('status.api'), mounted ? 'ok' : 'warn'),
2344
+ paChip(mounted ? t('status.dataApi') : t('status.data'), mounted ? 'ok' : 'warn'),
2345
+ paChip(t('connection.service') + ': ' + health.status, health.status === 'ok' ? 'ok' : 'warn'))),
2346
+ paKv(pairs),
2347
+ el('p', { className: 'lcr-pa-hint' }, t(mounted ? 'connection.noticeLive' : 'connection.notice')),
2348
+ el('p', { className: 'lcr-pa-hint' }, missingStores > 0
2349
+ ? t('connection.serviceDetail', { missing: missingStores, total: state.diagnostics.scopes.length })
2350
+ : t('libraries.allPresent')))));
2351
+ }
2352
+
2353
+ function paViewHistory(state, t, dispatch) {
2354
+ const history = state.history || { entries: [], total: 0, nextCursor: null, integrity: null, pages: 1, loaded: false, error: null };
2355
+ // Sin historial servible se conserva el estado honesto: no se fabrica ni una fila.
2356
+ if (!history.loaded || history.error !== null || (history.entries.length === 0 && history.integrity === null)) {
2357
+ return paCard(t('history.title'), el('div', { className: 'lcr-pa-stack' },
2358
+ el('div', { className: 'lcr-pa-empty lcr-pa-empty--big' },
2359
+ el('p', { className: 'lcr-pa-empty__title' }, t('history.unavailable')),
2360
+ el('p', { className: 'lcr-pa-empty__hint' }, t('history.why')),
2361
+ el('button', {
2362
+ type: 'button',
2363
+ className: 'lcr-pa-link',
2364
+ onClick: () => dispatch({ type: 'nav', view: 'operations' }),
2365
+ }, t('history.toOperations'))),
2366
+ el('p', { className: 'lcr-pa-hint' }, t('history.route')),
2367
+ el('p', { className: 'lcr-pa-hint' }, t('history.simulated'))));
2368
+ }
2369
+ const integrity = history.integrity || {};
2370
+ const chain = integrity.ok
2371
+ ? paChip(t('history.chainOk', { count: integrity.count ?? history.total }), 'ok')
2372
+ : paChip(t('history.chainBroken', { at: integrity.brokenAt ?? '?', reason: integrity.reason ?? '?' }), 'warn');
2373
+ const rows = history.entries.map((entry) => el('tr', { key: entry.seq },
2374
+ el('td', { className: 'lcr-pa-num' }, String(entry.seq)),
2375
+ el('td', null, paTime(entry.at)),
2376
+ el('td', null, entry.actor),
2377
+ el('td', null, el('span', { className: 'lcr-pa-mono' }, entry.tool)),
2378
+ el('td', null, entry.action),
2379
+ el('td', null, el('span', { className: 'lcr-pa-mono lcr-pa-celluri', title: entry.target || '' }, entry.target || '—')),
2380
+ el('td', null, paChip(entry.outcome, entry.outcome === 'ok' ? 'ok' : 'warn')),
2381
+ el('td', null, el('span', { className: 'lcr-pa-mono' }, entry.hash || '—'))));
2382
+ return paCard(t('history.title'), el('div', { className: 'lcr-pa-stack' },
2383
+ el('div', { className: 'lcr-pa-toolbar' },
2384
+ el('span', { className: 'lcr-pa-toolbar__group' },
2385
+ paChip(t('history.total') + ': ' + paNum(history.total), 'lib'),
2386
+ chain),
2387
+ history.nextCursor
2388
+ ? el('button', { type: 'button', className: 'lcr-pa-btn', onClick: () => dispatch({ type: 'history-more' }) }, t('history.more'))
2389
+ : null),
2390
+ el('p', { className: 'lcr-pa-hint' }, t('history.subtitle')),
2391
+ history.entries.length === 0
2392
+ ? paEmpty(t('history.empty'))
2393
+ : paTable(t('history.title'), [
2394
+ t('history.col.seq'), t('history.col.at'), t('history.col.actor'), t('history.col.tool'),
2395
+ t('history.col.action'), t('history.col.target'), t('history.col.outcome'), t('history.col.hash'),
2396
+ ], rows, 'lcr-pa-tablewrap')));
2397
+ }
2398
+
2399
+ const PA_VIEWS = [
2400
+ { id: 'project', key: 'nav.project' },
2401
+ { id: 'libraries', key: 'nav.libraries' },
2402
+ { id: 'sources', key: 'nav.sources' },
2403
+ { id: 'search', key: 'nav.search' },
2404
+ { id: 'context', key: 'nav.context' },
2405
+ { id: 'operations', key: 'nav.operations' },
2406
+ { id: 'diagnostics', key: 'nav.diagnostics' },
2407
+ { id: 'connection', key: 'nav.connection' },
2408
+ { id: 'history', key: 'nav.history' },
2409
+ ];
2410
+
2411
+ function paRenderView(state, t, dispatch) {
2412
+ switch (state.view) {
2413
+ case 'libraries': return paViewLibraries(state, t);
2414
+ case 'sources': return paViewSources(state, t, dispatch);
2415
+ case 'source': return paViewSource(state, t, dispatch);
2416
+ case 'search': return paViewSearch(state, t, dispatch);
2417
+ case 'context': return paViewContext(state, t, dispatch);
2418
+ case 'operations': return paViewOperations(state, t, dispatch);
2419
+ case 'diagnostics': return paViewDiagnostics(state, t);
2420
+ case 'connection': return paViewConnection(state, t);
2421
+ case 'history': return paViewHistory(state, t, dispatch);
2422
+ default: return paViewProject(state, t, dispatch);
2423
+ }
2424
+ }
2425
+
2426
+ function paRenderViewSafe(state, t, dispatch, render) {
2427
+ const draw = typeof render === 'function' ? render : paRenderView;
2428
+ try {
2429
+ return draw(state, t, dispatch);
2430
+ } catch (error) {
2431
+ return el('section', { className: 'lcr-pa-card', 'data-view-error': state.view },
2432
+ el('div', { className: 'lcr-pa-card__head' },
2433
+ el('h2', { className: 'lcr-pa-card__title' }, t('view.errorTitle'))),
2434
+ el('div', { className: 'lcr-pa-card__body' },
2435
+ el('div', { className: 'lcr-pa-error' },
2436
+ el('p', { className: 'lcr-pa-error__title' }, t('view.errorTitle')),
2437
+ el('p', { className: 'lcr-pa-hint' }, t('view.errorHint')),
2438
+ el('button', {
2439
+ type: 'button',
2440
+ className: 'lcr-pa-btn',
2441
+ onClick: () => dispatch({ type: 'retry-view' }),
2442
+ }, t('view.retry')))));
2443
+ }
2444
+ }
2445
+
2446
+ function paStatusPill(label, tone) {
2447
+ return el('span', { className: 'lcr-pa-status__item' },
2448
+ el('span', { className: 'lcr-pa-dot lcr-pa-dot--' + tone, 'aria-hidden': 'true' }),
2449
+ label);
2450
+ }
2451
+
2452
+ function PaPanel(props) {
2453
+ const [state, setState] = useState(() => paInitialState());
2454
+ const t = props && typeof props.t === 'function' ? props.t : (key, vars) => paTranslate('es', key, vars);
2455
+ const dispatch = (action) => setState((previous) => paReduce(previous, action));
2456
+ // LE-RAG-10: el componente REAL del slot negocia antes de pintar datos. Si el servidor no
2457
+ // confirma 'api', el estado pasa a 'down' con su razón (nunca lista vacía silenciosa).
2458
+ useEffect(() => {
2459
+ let alive = true;
2460
+ (async () => {
2461
+ await negotiateMode();
2462
+ if (!alive) return;
2463
+ if (panelState.mode !== 'api') {
2464
+ dispatch({ type: 'unavailable', reason: panelState.reason });
2465
+ return;
2466
+ }
2467
+ try {
2468
+ const snapshot = await request('/snapshot');
2469
+ if (alive) dispatch({ type: 'hydrate', snapshot });
2470
+ } catch (failure) {
2471
+ if (alive) dispatch({ type: 'unavailable', reason: (failure && failure.code) || 'transport-error' });
2472
+ }
2473
+ })();
2474
+ return () => { alive = false; };
2475
+ }, []);
2476
+ // LE-RAG-10: la red de las vistas vive en un efecto encadenado al estado (no en el manejador del
2477
+ // clic), así el reducer sigue siendo puro y un fallo de transporte se pinta como aviso en lugar
2478
+ // de tumbar el panel.
2479
+ useEffect(() => {
2480
+ const job = state.pending;
2481
+ if (!job) return undefined;
2482
+ let alive = true;
2483
+ (async () => {
2484
+ try {
2485
+ const query = String(state.query ?? '').trim();
2486
+ // El contrato identifica el proyecto por query string en POST (la cabecera de sesión está
2487
+ // BLOCKED). Sin esto, un perfil con más de un proyecto respondería scope-ambiguous.
2488
+ const projectId = state.session.session.selection.projectId;
2489
+ const suffix = projectId ? '?project=' + encodeURIComponent(projectId) : '';
2490
+ if (job === 'search') {
2491
+ const data = await request('/search' + suffix, { method: 'POST', body: { query, limit: state.limit } });
2492
+ if (alive) dispatch({ type: 'search-ok', results: paNormalizeSearch(data, state.sources, state.session.session.selection.projectName) });
2493
+ return;
2494
+ }
2495
+ if (job === 'context') {
2496
+ const data = await request('/context' + suffix, { method: 'POST', body: { query, budgetTokens: PA_CONTEXT_BUDGET } });
2497
+ if (alive) dispatch({ type: 'context-ok', context: paNormalizeContext(data, state.sources) });
2498
+ }
2499
+ if (job === 'history') {
2500
+ // Historial del proyecto activo: la API lo resuelve por la selección persistida.
2501
+ const append = state.history.loaded && Boolean(state.history.nextCursor);
2502
+ const suffixHistory = '?limit=50' + (append ? '&cursor=' + encodeURIComponent(state.history.nextCursor) : '');
2503
+ try {
2504
+ const page = await request('/history' + suffixHistory);
2505
+ if (alive) dispatch({ type: 'history-ok', page, append });
2506
+ } catch (failure) {
2507
+ if (alive) dispatch({ type: 'history-error', reason: (failure && failure.code) || 'transport-error' });
2508
+ }
2509
+ return;
2510
+ }
2511
+ if (job === 'snapshot') {
2512
+ const snapshot = await request('/snapshot?limit=200');
2513
+ if (alive) dispatch({ type: 'hydrate', snapshot });
2514
+ return;
2515
+ }
2516
+ if (job === 'selection') {
2517
+ // CR-1: el cambio sólo se pinta cuando el servidor lo confirma con la revisión nueva.
2518
+ const target = state.selectionPending;
2519
+ if (!target) return;
2520
+ try {
2521
+ const data = await request('/selection', {
2522
+ method: 'POST',
2523
+ body: { projectId: target.projectId, expectedRevision: target.expectedRevision },
2524
+ });
2525
+ if (alive) dispatch({ type: 'selection-ok', selection: data.selection });
2526
+ } catch (failure) {
2527
+ const reason = (failure && failure.code) || 'transport-error';
2528
+ if (reason === 'revision-conflict') {
2529
+ // Otro panel ganó: se recarga la revisión vigente y se avisa; no se reintenta solo.
2530
+ try {
2531
+ const snapshot = await request('/snapshot');
2532
+ if (alive) dispatch({ type: 'hydrate', snapshot });
2533
+ } catch { /* el aviso de conflicto ya es suficiente */ }
2534
+ }
2535
+ if (alive) dispatch({ type: 'selection-error', reason });
2536
+ }
2537
+ }
2538
+ } catch (failure) {
2539
+ if (alive) dispatch({ type: job + '-error', reason: (failure && failure.code) || 'transport-error' });
2540
+ }
2541
+ })();
2542
+ return () => { alive = false; };
2543
+ }, [state.pending]);
2544
+ const activeId = state.view === 'source' ? 'sources' : state.view;
2545
+ const onKeyDown = (event) => {
2546
+ if (!event || (event.key !== 'ArrowRight' && event.key !== 'ArrowLeft')) return;
2547
+ if (typeof event.preventDefault === 'function') event.preventDefault();
2548
+ const ids = PA_VIEWS.map((view) => view.id);
2549
+ const current = ids.indexOf(activeId);
2550
+ const delta = event.key === 'ArrowRight' ? 1 : -1;
2551
+ const next = ids[(current + delta + ids.length) % ids.length];
2552
+ dispatch({ type: 'nav', view: next });
2553
+ };
2554
+ const serviceStatus = state.session.service.status;
2555
+ const mounted = state.mode === 'api';
2556
+ return el('div', { className: 'lcr-pa-root', 'data-data-mode': panelState.mode },
2557
+ (panelState.mode === 'api' && !(typeof window !== 'undefined' && window.location && window.location.search.indexOf('lcrnobanner=1') >= 0)) ? null : el('div', { className: 'lcr-pa-banner', role: 'status', 'aria-atomic': 'true', 'aria-label': t('a11y.banner') },
2558
+ el('strong', null, SYNTHETIC_BANNER),
2559
+ el('span', { className: 'lcr-pa-banner__hint' }, t('banner.hint'))),
2560
+ el('header', { className: 'lcr-pa-head' },
2561
+ el('div', { className: 'lcr-pa-head__main' },
2562
+ el('div', { className: 'lcr-pa-brand' },
2563
+ el('span', { className: 'lcr-pa-mark', 'aria-hidden': 'true' }, 'RAG'),
2564
+ el('div', null,
2565
+ el('h1', { className: 'lcr-pa-head__title' }, t('app.title')),
2566
+ el('p', { className: 'lcr-pa-head__sub' }, t('app.subtitle')))),
2567
+ el('div', { className: 'lcr-pa-status', 'aria-label': t('a11y.status') },
2568
+ paStatusPill(t('status.client'), 'ok'),
2569
+ paStatusPill(mounted ? t('status.apiOk') : t('status.api'), mounted ? 'ok' : 'warn'),
2570
+ paStatusPill(mounted ? t('status.dataApi') : t('status.data'), mounted ? 'ok' : 'warn'),
2571
+ paStatusPill(t('connection.service') + ': ' + serviceStatus, serviceStatus === 'ok' ? 'ok' : 'warn'))),
2572
+ el('div', { className: 'lcr-pa-head__actions' },
2573
+ mounted ? null : el('button', { type: 'button', className: 'lcr-pa-btn', onClick: () => dispatch({ type: 'reset' }) }, t('app.reset')))),
2574
+ el('div', { className: 'lcr-pa-tabs', role: 'tablist', 'aria-label': t('a11y.tabs'), onKeyDown },
2575
+ ...PA_VIEWS.map((view) => el('button', {
2576
+ key: view.id,
2577
+ type: 'button',
2578
+ role: 'tab',
2579
+ id: 'lcr-pa-tab-' + view.id,
2580
+ className: 'lcr-pa-tab' + (activeId === view.id ? ' lcr-pa-tab--active' : ''),
2581
+ 'aria-selected': activeId === view.id ? 'true' : 'false',
2582
+ 'aria-controls': 'lcr-pa-panel-' + view.id,
2583
+ tabIndex: activeId === view.id ? 0 : -1,
2584
+ onClick: () => dispatch({ type: 'nav', view: view.id }),
2585
+ }, t(view.key)))),
2586
+ el('div', {
2587
+ className: 'lcr-pa-body',
2588
+ role: 'tabpanel',
2589
+ id: 'lcr-pa-panel-' + activeId,
2590
+ 'aria-labelledby': 'lcr-pa-tab-' + activeId,
2591
+ 'data-view': state.view,
2592
+ }, paRenderViewSafe(state, t, dispatch)));
2593
+ }
2594
+
2595
+ const CSS_PA = `
2596
+ .lcr-pa-root {
2597
+ --pa-bg: var(--dsw-alias-bg-base, #17181c);
2598
+ --pa-surface: var(--dsw-alias-bg-layer-1, #202127);
2599
+ --pa-surface-2: var(--dsw-alias-bg-layer-2, #2a2b32);
2600
+ --pa-border: var(--dsw-alias-border-l1, #2c2d33);
2601
+ --pa-border-2: var(--dsw-alias-border-l2, #34353d);
2602
+ --pa-text: var(--dsw-alias-label-primary, #e8e8ea);
2603
+ --pa-muted: var(--dsw-alias-label-secondary, #a0a0aa);
2604
+ --pa-accent: var(--dsw-alias-brand-primary, #4f8cff);
2605
+ --pa-ok: var(--dsw-alias-state-success-primary, #2fbf71);
2606
+ --pa-warn: var(--dsw-alias-state-warn-primary, #d6a100);
2607
+ --pa-err: var(--dsw-alias-state-error-primary, #e5484d);
2608
+ --pa-radius: 10px;
2609
+ --pa-radius-sm: 7px;
2610
+ display: flex;
2611
+ flex-direction: column;
2612
+ gap: 14px;
2613
+ min-height: 100%;
2614
+ padding: 18px 20px 32px;
2615
+ overflow: auto;
2616
+ color: var(--pa-text);
2617
+ background: var(--pa-bg);
2618
+ font-family: inherit;
2619
+ font-size: 13px;
2620
+ line-height: 1.5;
2621
+ }
2622
+ .lcr-pa-root *, .lcr-pa-root *::before, .lcr-pa-root *::after { box-sizing: border-box; }
2623
+ /* Los bloques fijos de la cabecera no se comprimen cuando el slot tiene altura fija: sin esto,
2624
+ el navegador reparte la falta de espacio encogiendo la fila de pestañas (su min-height resuelve
2625
+ a 0 por el overflow-x) y la deja reducida a la barra de desplazamiento. */
2626
+ .lcr-pa-banner, .lcr-pa-head, .lcr-pa-tabs { flex: 0 0 auto; }
2627
+ .lcr-pa-body { flex: 1 0 auto; }
2628
+ .lcr-pa-sr { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; }
2629
+ .lcr-pa-banner { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 7px 11px; border: 1px solid color-mix(in oklab, var(--pa-warn) 45%, transparent); border-radius: var(--pa-radius-sm); background: color-mix(in oklab, var(--pa-warn) 10%, transparent); font-size: 11.5px; }
2630
+ .lcr-pa-banner strong { font-size: 11px; letter-spacing: 0.04em; font-weight: 700; }
2631
+ .lcr-pa-banner__hint { color: var(--pa-muted); }
2632
+ .lcr-pa-head { display: flex; flex-wrap: wrap; align-items: flex-start; justify-content: space-between; gap: 14px; }
2633
+ .lcr-pa-head__main { display: flex; flex-direction: column; gap: 10px; min-width: 0; }
2634
+ .lcr-pa-brand { display: flex; align-items: center; gap: 10px; }
2635
+ .lcr-pa-mark { display: inline-flex; align-items: center; justify-content: center; width: 34px; height: 34px; border-radius: 9px; border: 1px solid color-mix(in oklab, var(--pa-accent) 45%, transparent); background: color-mix(in oklab, var(--pa-accent) 14%, transparent); color: var(--pa-accent); font-size: 10px; font-weight: 800; letter-spacing: 0.04em; }
2636
+ .lcr-pa-status { display: flex; flex-wrap: wrap; gap: 6px; }
2637
+ .lcr-pa-status__item { display: inline-flex; align-items: center; gap: 6px; padding: 3px 9px; border: 1px solid var(--pa-border); border-radius: 999px; background: var(--pa-surface); font-size: 11px; color: var(--pa-muted); }
2638
+ .lcr-pa-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--pa-muted); }
2639
+ .lcr-pa-dot--ok { background: var(--pa-ok); }
2640
+ .lcr-pa-dot--warn { background: var(--pa-warn); }
2641
+ .lcr-pa-dot--err { background: var(--pa-err); }
2642
+ .lcr-pa-head__title { margin: 0; font-size: 20px; font-weight: 650; letter-spacing: -0.01em; }
2643
+ .lcr-pa-head__sub { margin: 3px 0 0; color: var(--pa-muted); font-size: 12px; }
2644
+ .lcr-pa-head__actions { display: flex; align-items: center; gap: 8px; }
2645
+ .lcr-pa-tabs { display: flex; gap: 2px; padding: 3px; border: 1px solid var(--pa-border); border-radius: var(--pa-radius-sm); background: var(--pa-surface); overflow-x: auto; scrollbar-width: thin; }
2646
+ .lcr-pa-tab { appearance: none; flex: 0 0 auto; border: 1px solid transparent; border-radius: 6px; background: transparent; color: var(--pa-muted); padding: 6px 11px; font: inherit; font-size: 12px; cursor: pointer; white-space: nowrap; }
2647
+ .lcr-pa-tab:hover { color: var(--pa-text); background: color-mix(in oklab, var(--pa-surface-2) 60%, transparent); }
2648
+ .lcr-pa-tab--active { color: var(--pa-text); background: var(--pa-surface-2); border-color: var(--pa-border-2); font-weight: 600; }
2649
+ .lcr-pa-tab:focus-visible, .lcr-pa-btn:focus-visible, .lcr-pa-input:focus-visible, .lcr-pa-link:focus-visible { outline: 2px solid var(--pa-accent); outline-offset: 2px; }
2650
+ .lcr-pa-body { display: flex; flex-direction: column; gap: 14px; min-width: 0; }
2651
+ .lcr-pa-card { border: 1px solid var(--pa-border); border-radius: var(--pa-radius); background: var(--pa-surface); overflow: hidden; min-width: 0; }
2652
+ .lcr-pa-card__head { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 8px; padding: 9px 14px; border-bottom: 1px solid var(--pa-border); background: color-mix(in oklab, var(--pa-surface-2) 35%, transparent); }
2653
+ .lcr-pa-card__title { margin: 0; font-size: 12.5px; font-weight: 650; letter-spacing: 0.01em; }
2654
+ .lcr-pa-card__body { padding: 12px 14px; min-width: 0; }
2655
+ .lcr-pa-subtitle { margin: 14px 0 6px; font-size: 11px; font-weight: 650; text-transform: uppercase; letter-spacing: 0.05em; color: var(--pa-muted); }
2656
+ .lcr-pa-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 14px; align-items: start; }
2657
+ .lcr-pa-form { display: flex; flex-wrap: wrap; align-items: flex-end; gap: 10px; }
2658
+ .lcr-pa-field { display: flex; flex-direction: column; gap: 4px; font-size: 11px; color: var(--pa-muted); min-width: 0; }
2659
+ .lcr-pa-input { appearance: none; border: 1px solid var(--pa-border); border-radius: 6px; background: var(--pa-bg); color: inherit; padding: 7px 9px; font: inherit; font-size: 12.5px; min-width: 0; }
2660
+ .lcr-pa-input:hover { border-color: var(--pa-border-2); }
2661
+ .lcr-pa-input[aria-invalid="true"] { border-color: var(--pa-err); }
2662
+ .lcr-pa-btn { appearance: none; border: 1px solid var(--pa-border); border-radius: 6px; background: var(--pa-surface-2); color: var(--pa-text); padding: 6px 12px; font: inherit; font-size: 12px; cursor: pointer; white-space: nowrap; }
2663
+ .lcr-pa-btn:hover:not(:disabled) { border-color: var(--pa-accent); }
2664
+ .lcr-pa-btn:disabled { opacity: 0.5; cursor: default; }
2665
+ .lcr-pa-btn--primary { background: color-mix(in oklab, var(--pa-accent) 72%, #000); border-color: color-mix(in oklab, var(--pa-accent) 72%, #000); color: #fff; font-weight: 600; }
2666
+ .lcr-pa-btn--ghost { background: transparent; }
2667
+ .lcr-pa-scroll { overflow: auto; min-width: 0; }
2668
+ .lcr-pa-table { width: 100%; border-collapse: separate; border-spacing: 0; font-size: 12px; }
2669
+ .lcr-pa-table th { position: sticky; top: 0; z-index: 1; text-align: left; font-weight: 600; font-size: 10.5px; text-transform: uppercase; letter-spacing: 0.04em; color: var(--pa-muted); padding: 8px 10px; border-bottom: 1px solid var(--pa-border); background: var(--pa-surface); white-space: nowrap; }
2670
+ .lcr-pa-table td { padding: 8px 10px; border-bottom: 1px solid var(--pa-border-2); vertical-align: top; }
2671
+ .lcr-pa-table tbody tr:hover td { background: color-mix(in oklab, var(--pa-surface-2) 45%, transparent); }
2672
+ .lcr-pa-table tbody tr:last-child td { border-bottom: 0; }
2673
+ .lcr-pa-num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
2674
+ .lcr-pa-mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 11.5px; }
2675
+ .lcr-pa-muted { color: var(--pa-muted); }
2676
+ .lcr-pa-hint { margin: 6px 0 0; color: var(--pa-muted); font-size: 11.5px; }
2677
+ .lcr-pa-kv { display: grid; grid-template-columns: minmax(120px, max-content) 1fr; gap: 6px 16px; margin: 0; }
2678
+ .lcr-pa-kv dt { color: var(--pa-muted); font-size: 11.5px; }
2679
+ .lcr-pa-kv dd { margin: 0; font-size: 12.5px; min-width: 0; overflow-wrap: anywhere; }
2680
+ .lcr-pa-chunk-cell { max-width: 460px; white-space: pre-wrap; overflow-wrap: anywhere; }
2681
+ .lcr-pa-chip { display: inline-flex; align-items: center; gap: 4px; padding: 1px 7px; border-radius: 999px; border: 1px solid var(--pa-border-2); font-size: 10.5px; font-weight: 600; white-space: nowrap; }
2682
+ .lcr-pa-chip--ok { border-color: color-mix(in oklab, var(--pa-ok) 45%, transparent); color: var(--pa-ok); background: color-mix(in oklab, var(--pa-ok) 12%, transparent); }
2683
+ .lcr-pa-chip--warn { border-color: color-mix(in oklab, var(--pa-warn) 45%, transparent); color: var(--pa-warn); background: color-mix(in oklab, var(--pa-warn) 12%, transparent); }
2684
+ .lcr-pa-chip--err { border-color: color-mix(in oklab, var(--pa-err) 45%, transparent); color: var(--pa-err); background: color-mix(in oklab, var(--pa-err) 12%, transparent); }
2685
+ .lcr-pa-chip--lib { border-color: color-mix(in oklab, var(--pa-accent) 45%, transparent); color: var(--pa-accent); background: color-mix(in oklab, var(--pa-accent) 12%, transparent); }
2686
+ .lcr-pa-notice { margin: 0; padding: 8px 11px; border-radius: var(--pa-radius-sm); border: 1px solid var(--pa-border); background: var(--pa-surface); font-size: 12px; }
2687
+ .lcr-pa-error { margin: 0 0 10px; padding: 10px 12px; border-radius: var(--pa-radius-sm); border: 1px solid color-mix(in oklab, var(--pa-err) 45%, transparent); background: color-mix(in oklab, var(--pa-err) 10%, transparent); font-size: 12px; }
2688
+ .lcr-pa-error__title { margin: 0 0 4px; font-weight: 650; }
2689
+ .lcr-pa-empty { display: flex; flex-direction: column; align-items: center; gap: 4px; padding: 24px 16px; border: 1px dashed var(--pa-border-2); border-radius: var(--pa-radius-sm); text-align: center; }
2690
+ .lcr-pa-empty__title { margin: 0; font-weight: 650; font-size: 12.5px; }
2691
+ .lcr-pa-empty__hint { margin: 0; color: var(--pa-muted); font-size: 11.5px; max-width: 60ch; }
2692
+ .lcr-pa-row { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 10px; }
2693
+ .lcr-pa-row--end { justify-content: flex-end; }
2694
+ .lcr-pa-context { margin: 8px 0 0; padding: 12px; border-radius: var(--pa-radius-sm); border: 1px solid var(--pa-border-2); background: var(--pa-bg); white-space: pre-wrap; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 11.5px; max-height: 420px; overflow: auto; }
2695
+ .lcr-pa-stack { display: flex; flex-direction: column; gap: 10px; min-width: 0; }
2696
+ .lcr-pa-kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px; }
2697
+ .lcr-pa-kpi { display: flex; flex-direction: column; gap: 2px; padding: 12px 14px; border: 1px solid var(--pa-border); border-radius: var(--pa-radius); background: var(--pa-surface); min-width: 0; }
2698
+ .lcr-pa-kpi__label { font-size: 10.5px; text-transform: uppercase; letter-spacing: 0.05em; color: var(--pa-muted); }
2699
+ .lcr-pa-kpi__value { font-size: 21px; font-weight: 650; letter-spacing: -0.01em; line-height: 1.2; }
2700
+ .lcr-pa-kpi__hint { font-size: 11px; color: var(--pa-muted); overflow-wrap: anywhere; }
2701
+ .lcr-pa-split { display: grid; grid-template-columns: minmax(0, 1.15fr) minmax(0, 0.85fr); gap: 14px; align-items: start; }
2702
+ .lcr-pa-hero { padding: 16px; border: 1px solid var(--pa-border); border-radius: var(--pa-radius); background: linear-gradient(180deg, color-mix(in oklab, var(--pa-accent) 7%, transparent), transparent 70%), var(--pa-surface); }
2703
+ .lcr-pa-hero__form { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
2704
+ .lcr-pa-hero__form > .lcr-pa-input { flex: 1 1 320px; padding: 10px 12px; font-size: 13.5px; }
2705
+ .lcr-pa-toolbar { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 10px; }
2706
+ .lcr-pa-toolbar__group { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
2707
+ .lcr-pa-list { display: flex; flex-direction: column; gap: 8px; margin: 0; padding: 0; list-style: none; }
2708
+ .lcr-pa-list__item { display: flex; align-items: flex-start; gap: 8px; font-size: 11.5px; color: var(--pa-muted); }
2709
+ .lcr-pa-tablewrap { max-height: 540px; }
2710
+ .lcr-pa-celluri { display: block; max-width: 340px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
2711
+ .lcr-pa-empty--big { padding: 40px 18px; }
2712
+ .lcr-pa-link { appearance: none; border: 0; padding: 0; background: none; color: var(--pa-accent); font: inherit; font-size: 12px; cursor: pointer; text-decoration: underline; text-underline-offset: 2px; }
2713
+ .lcr-pa-banner + .lcr-pa-head { margin-top: 2px; }
2714
+ @media (max-width: 760px) {
2715
+ .lcr-pa-root { padding: 14px 12px 24px; }
2716
+ .lcr-pa-head { flex-direction: column; align-items: stretch; }
2717
+ .lcr-pa-head__actions { justify-content: flex-start; }
2718
+ .lcr-pa-grid { grid-template-columns: 1fr; }
2719
+ .lcr-pa-split { grid-template-columns: 1fr; }
2720
+ .lcr-pa-kpis { grid-template-columns: repeat(2, minmax(0, 1fr)); }
2721
+ .lcr-pa-form { align-items: stretch; }
2722
+ .lcr-pa-form > * { flex: 1 1 100%; }
2723
+ .lcr-pa-hero__form > .lcr-pa-input { flex: 1 1 100%; }
2724
+ .lcr-pa-tab { padding: 5px 9px; font-size: 11.5px; }
2725
+ .lcr-pa-chunk-cell { max-width: 240px; }
2726
+ .lcr-pa-celluri { max-width: 180px; }
2727
+ .lcr-pa-kv { grid-template-columns: 1fr; }
2728
+ .lcr-pa-tablewrap { max-height: none; }
2729
+ }
2730
+ @media (prefers-reduced-motion: reduce) { .lcr-pa-root * { transition: none; } }
2731
+ @media (forced-colors: active) { .lcr-pa-card, .lcr-pa-banner, .lcr-pa-notice, .lcr-pa-empty, .lcr-pa-tabs { border-color: CanvasText; } }
2732
+ `;
2733
+
2734
+ return {
2735
+ inject: ['slots', 'locale'],
2736
+ apply(ctx) {
2737
+ ctx.effect(() => {
2738
+ const style = document.createElement('style');
2739
+ style.id = 'lcr-styles';
2740
+ style.textContent = CSS + CSS_PA;
2741
+ document.head.appendChild(style);
2742
+ return () => { style.remove(); };
2743
+ });
2744
+
2745
+ // Locales: diccionarios inline (ES/EN con paridad de claves). El registro se deshace al
2746
+ // descargar el plugin, no se acumula al remontar.
2747
+ const locale = ctx.locale ?? ctx.get?.('locale') ?? null;
2748
+ if (locale !== null && locale !== undefined && typeof locale.register === 'function') {
2749
+ ctx.effect(() => {
2750
+ const dispose = locale.register(NS, PA_DICT);
2751
+ return typeof dispose === 'function' ? dispose : undefined;
2752
+ });
2753
+ }
2754
+
2755
+ // Slots con la API vigente del anfitrión: `inject(slot, cb)`. El registro vive dentro del
2756
+ // callback y su disposer lo administra el anfitrión; la forma antigua `inject(slot)` +
2757
+ // `.register(...)` devolvía un disposer y reventaba con TypeError.
2758
+ ctx.slots.inject(SIDEBAR_SLOT, () => ctx.slots.register({
2759
+ name: SIDEBAR_SLOT,
2760
+ id: PANEL_ID,
2761
+ order: 35,
2762
+ label: () => paTranslate(paReadLanguage(locale), 'app.title'),
2763
+ locale: NS,
2764
+ }, ICON));
2765
+
2766
+ ctx.slots.inject(MAIN_SLOT, () => ctx.slots.register({
2767
+ name: MAIN_SLOT,
2768
+ key: PANEL_ID,
2769
+ order: 55,
2770
+ locale: NS,
2771
+ }, PaPanel));
2772
+ },
2773
+ // Superficie de pruebas: el anfitrión la ignora. Permite ejercitar el contrato del módulo
2774
+ // (slots, reducer, vistas, guarda de red) sin React y sin host.
2775
+ __test: {
2776
+ panelState,
2777
+ request,
2778
+ negotiateMode,
2779
+ get DATA_MODE() { return panelState.mode; },
2780
+ SYNTHETIC_BANNER,
2781
+ PA_DICT,
2782
+ PA_VIEWS,
2783
+ CSS_PA,
2784
+ CSS,
2785
+ PaPanel,
2786
+ paInitialState,
2787
+ paReduce,
2788
+ paRenderView,
2789
+ paRenderViewSafe,
2790
+ paNormalizeUri,
2791
+ paPageInfo,
2792
+ paFixtures,
2793
+ paTranslate,
2794
+ paReadLanguage,
2795
+ paChunks,
2796
+ paBuildSources,
2797
+ requestLegacy: request,
2798
+ },
2799
+ };
2800
+ },
2801
+ });