pi-mega-compact 0.19.0 → 0.19.2

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 (101) hide show
  1. package/dist/config/vector-cortex.js +19 -0
  2. package/dist/config.js +1 -1
  3. package/dist/extensions/dashboard-server/routes-rag-settings-helpers.js +2 -0
  4. package/dist/extensions/dashboard-server/routes-vector-cortex-eval.js +49 -0
  5. package/dist/extensions/dashboard-server/routes-vector-cortex-health.js +233 -0
  6. package/dist/extensions/dashboard-server/routes-vector-cortex-ledger.js +82 -0
  7. package/dist/extensions/dashboard-server/routes-vector-cortex-shared.js +46 -0
  8. package/dist/extensions/dashboard-server/routes-vector-cortex-topology.js +208 -0
  9. package/dist/extensions/dashboard-server/routes-vector-cortex.js +12 -373
  10. package/dist/extensions/dashboard-server/routes.js +1 -1
  11. package/dist/extensions/dashboard-server/server.js +3 -1
  12. package/dist/src/config/vector-cortex.js +19 -0
  13. package/dist/src/config.js +1 -1
  14. package/dist/src/vector-cortex/cortex/sqlite.js +393 -0
  15. package/dist/src/vector-cortex/cortex/store.js +139 -0
  16. package/dist/src/vector-cortex/cortex/types.js +44 -0
  17. package/dist/src/vector-cortex/topology/build.js +232 -0
  18. package/dist/src/vector-cortex/topology/index.js +113 -0
  19. package/dist/src/vector-cortex/topology/types.js +54 -0
  20. package/dist/src/vector-cortex/vc3b-support.js +125 -0
  21. package/dist/vector-cortex/cortex/sqlite.js +393 -0
  22. package/dist/vector-cortex/cortex/store.js +139 -0
  23. package/dist/vector-cortex/cortex/types.js +44 -0
  24. package/dist/vector-cortex/topology/build.js +232 -0
  25. package/dist/vector-cortex/topology/index.js +113 -0
  26. package/dist/vector-cortex/topology/types.js +54 -0
  27. package/dist/vector-cortex/vc3b-support.js +125 -0
  28. package/extensions/dashboard-client/dist/assets/{AreaChart-DywU5SSt.js → AreaChart-CSaJZXru.js} +2 -2
  29. package/extensions/dashboard-client/dist/assets/{AreaChart-DywU5SSt.js.map → AreaChart-CSaJZXru.js.map} +1 -1
  30. package/extensions/dashboard-client/dist/assets/{BarChart-But7WN6K.js → BarChart-CQouNj1g.js} +2 -2
  31. package/extensions/dashboard-client/dist/assets/{BarChart-But7WN6K.js.map → BarChart-CQouNj1g.js.map} +1 -1
  32. package/extensions/dashboard-client/dist/assets/{CacheTab-7aZWa1DR.js → CacheTab-m_eiCYoL.js} +2 -2
  33. package/extensions/dashboard-client/dist/assets/{CacheTab-7aZWa1DR.js.map → CacheTab-m_eiCYoL.js.map} +1 -1
  34. package/extensions/dashboard-client/dist/assets/{EventsTab-Bf_boNG2.js → EventsTab-DRyOwjYN.js} +2 -2
  35. package/extensions/dashboard-client/dist/assets/{EventsTab-Bf_boNG2.js.map → EventsTab-DRyOwjYN.js.map} +1 -1
  36. package/extensions/dashboard-client/dist/assets/{HealthTab-AbGc1nXP.js → HealthTab-Dj9k40TJ.js} +2 -2
  37. package/extensions/dashboard-client/dist/assets/{HealthTab-AbGc1nXP.js.map → HealthTab-Dj9k40TJ.js.map} +1 -1
  38. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-BfHHhn5F.js → MaintenanceTab-Bk9mhYfD.js} +2 -2
  39. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-BfHHhn5F.js.map → MaintenanceTab-Bk9mhYfD.js.map} +1 -1
  40. package/extensions/dashboard-client/dist/assets/{MemoryMapTab-DrcWti0-.js → MemoryMapTab-C7ve49VG.js} +2 -2
  41. package/extensions/dashboard-client/dist/assets/{MemoryMapTab-DrcWti0-.js.map → MemoryMapTab-C7ve49VG.js.map} +1 -1
  42. package/extensions/dashboard-client/dist/assets/{MetricsTab-ALiglXQq.js → MetricsTab-DzjhqZA9.js} +2 -2
  43. package/extensions/dashboard-client/dist/assets/{MetricsTab-ALiglXQq.js.map → MetricsTab-DzjhqZA9.js.map} +1 -1
  44. package/extensions/dashboard-client/dist/assets/{OverviewTab-nnaJdNyR.js → OverviewTab-CFQdfIm_.js} +2 -2
  45. package/extensions/dashboard-client/dist/assets/{OverviewTab-nnaJdNyR.js.map → OverviewTab-CFQdfIm_.js.map} +1 -1
  46. package/extensions/dashboard-client/dist/assets/{ReposTab-BTK0nofM.js → ReposTab-DyjwEFUr.js} +2 -2
  47. package/extensions/dashboard-client/dist/assets/{ReposTab-BTK0nofM.js.map → ReposTab-DyjwEFUr.js.map} +1 -1
  48. package/extensions/dashboard-client/dist/assets/{SessionsTab-RXPNqO6x.js → SessionsTab-njLIy7ab.js} +2 -2
  49. package/extensions/dashboard-client/dist/assets/{SessionsTab-RXPNqO6x.js.map → SessionsTab-njLIy7ab.js.map} +1 -1
  50. package/extensions/dashboard-client/dist/assets/{SetupTab-Dab0AVfs.js → SetupTab-UHIs8-Lh.js} +2 -2
  51. package/extensions/dashboard-client/dist/assets/{SetupTab-Dab0AVfs.js.map → SetupTab-UHIs8-Lh.js.map} +1 -1
  52. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-DIVG8hdt.js → TimeSavedCard-inWHjCxg.js} +2 -2
  53. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-DIVG8hdt.js.map → TimeSavedCard-inWHjCxg.js.map} +1 -1
  54. package/extensions/dashboard-client/dist/assets/{TurnsTab-9uz2fBwx.js → TurnsTab-CXJYugBu.js} +2 -2
  55. package/extensions/dashboard-client/dist/assets/{TurnsTab-9uz2fBwx.js.map → TurnsTab-CXJYugBu.js.map} +1 -1
  56. package/extensions/dashboard-client/dist/assets/VectorCortexTab-DkS0Azx9.js +2 -0
  57. package/extensions/dashboard-client/dist/assets/VectorCortexTab-DkS0Azx9.js.map +1 -0
  58. package/extensions/dashboard-client/dist/assets/{WikiTab-CpcgaggS.js → WikiTab-BJ4A2oi9.js} +2 -2
  59. package/extensions/dashboard-client/dist/assets/{WikiTab-CpcgaggS.js.map → WikiTab-BJ4A2oi9.js.map} +1 -1
  60. package/extensions/dashboard-client/dist/assets/{button-B0Q2fuKY.js → button-BWl-moyn.js} +2 -2
  61. package/extensions/dashboard-client/dist/assets/{button-B0Q2fuKY.js.map → button-BWl-moyn.js.map} +1 -1
  62. package/extensions/dashboard-client/dist/assets/{card-Cnik3TFr.js → card-C58RVPOk.js} +2 -2
  63. package/extensions/dashboard-client/dist/assets/{card-Cnik3TFr.js.map → card-C58RVPOk.js.map} +1 -1
  64. package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-DrSwgn1V.js → generateCategoricalChart-vgeOQU3L.js} +2 -2
  65. package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-DrSwgn1V.js.map → generateCategoricalChart-vgeOQU3L.js.map} +1 -1
  66. package/extensions/dashboard-client/dist/assets/index-CYpzq9Lm.css +1 -0
  67. package/extensions/dashboard-client/dist/assets/{index-DraytcOY.js → index-lVrWQjpu.js} +3 -3
  68. package/extensions/dashboard-client/dist/assets/{index-DraytcOY.js.map → index-lVrWQjpu.js.map} +1 -1
  69. package/extensions/dashboard-client/dist/assets/{switch-DVQ1aB9b.js → switch-CSeplFQT.js} +2 -2
  70. package/extensions/dashboard-client/dist/assets/{switch-DVQ1aB9b.js.map → switch-CSeplFQT.js.map} +1 -1
  71. package/extensions/dashboard-client/dist/assets/{toggle-Dkppx-49.js → toggle-CQRxgVRi.js} +2 -2
  72. package/extensions/dashboard-client/dist/assets/{toggle-Dkppx-49.js.map → toggle-CQRxgVRi.js.map} +1 -1
  73. package/extensions/dashboard-client/dist/assets/{useSSE-CPkjU4Gx.js → useSSE-BUz6IOI-.js} +2 -2
  74. package/extensions/dashboard-client/dist/assets/{useSSE-CPkjU4Gx.js.map → useSSE-BUz6IOI-.js.map} +1 -1
  75. package/extensions/dashboard-client/dist/index.html +2 -2
  76. package/extensions/dashboard-client/src/api/vector-cortex.ts +9 -0
  77. package/extensions/dashboard-client/src/tabs/VectorCortexTab.tsx +89 -0
  78. package/extensions/dashboard-client/src/types/vector-cortex.ts +28 -0
  79. package/extensions/dashboard-server/api-contracts/vector-cortex.ts +41 -0
  80. package/extensions/dashboard-server/routes-rag-settings-helpers.ts +12 -0
  81. package/extensions/dashboard-server/routes-vector-cortex-eval.ts +59 -0
  82. package/extensions/dashboard-server/routes-vector-cortex-health.ts +273 -0
  83. package/extensions/dashboard-server/routes-vector-cortex-ledger.ts +92 -0
  84. package/extensions/dashboard-server/routes-vector-cortex-shared.ts +53 -0
  85. package/extensions/dashboard-server/routes-vector-cortex-topology.ts +244 -0
  86. package/extensions/dashboard-server/routes-vector-cortex.ts +12 -431
  87. package/extensions/dashboard-server/routes.ts +1 -0
  88. package/extensions/dashboard-server/server.ts +2 -0
  89. package/package.json +1 -1
  90. package/src/config/vector-cortex.ts +21 -0
  91. package/src/config.ts +2 -0
  92. package/src/vector-cortex/cortex/sqlite.ts +489 -0
  93. package/src/vector-cortex/cortex/store.ts +202 -0
  94. package/src/vector-cortex/cortex/types.ts +194 -0
  95. package/src/vector-cortex/topology/build.ts +259 -0
  96. package/src/vector-cortex/topology/index.ts +143 -0
  97. package/src/vector-cortex/topology/types.ts +156 -0
  98. package/src/vector-cortex/vc3b-support.ts +142 -0
  99. package/extensions/dashboard-client/dist/assets/VectorCortexTab-DnKY61EJ.js +0 -2
  100. package/extensions/dashboard-client/dist/assets/VectorCortexTab-DnKY61EJ.js.map +0 -1
  101. package/extensions/dashboard-client/dist/assets/index-CfvziyBi.css +0 -1
@@ -0,0 +1,244 @@
1
+ /**
2
+ * dashboard-server/routes-vector-cortex-topology.ts — VC3A/VC3B vector-cortex
3
+ * topology dashboard route.
4
+ *
5
+ * Reader-only GET /api/vector-cortex/topology built ENTIRELY on the CortexReader
6
+ * capability: opens the isolated cortex DB for this repo's state dir and returns
7
+ * the topology summary (enabled, active generation identity, one root digest,
8
+ * derived frontier, record count, ordinal). It is query-only — never
9
+ * append/rebuild/switch. No writer or admin capability is reachable on this path
10
+ * (no writer/admin leakage). Non-fatal: a missing or corrupt cortex DB degrades
11
+ * to `enabled:false`.
12
+ *
13
+ * VC3B adds the deterministic node/edge shapes (TopologyV1) when both VC3A and
14
+ * VC3B are enabled: the accepted derived records of kind "topology" that carry a
15
+ * canonical TopologyCandidate JSON payload are fed through the deterministic
16
+ * build (buildTopologyGraph), whose stable generation digest + sorted node/edge
17
+ * arrays are returned. Bad/unparseable records are skipped (PREVENT-001), and
18
+ * with VC3B off the node/edge fields are omitted entirely — byte-identical to
19
+ * the VC3A predecessor view.
20
+ *
21
+ * Guardrails: PREVENT-PI-004 (local filesystem read only), PREVENT-011 (no
22
+ * `any`), reader-only aggregate.
23
+ */
24
+
25
+ import type { IncomingMessage, ServerResponse } from "node:http";
26
+ import type { RouteContext } from "./routes-core.js";
27
+ import { VC3A_ENABLED, VC3B_ENABLED } from "../../src/config.js";
28
+ import { Logger } from "../../src/log.js";
29
+ import { createCortexStore } from "../../src/vector-cortex/cortex/store.js";
30
+ import { buildTopologyGraph } from "../../src/vector-cortex/topology/index.js";
31
+ import type { TopologyCandidate, TopologyEmit } from "../../src/vector-cortex/topology/index.js";
32
+ import type { CortexRecordV1 } from "../../src/vector-cortex/cortex/types.js";
33
+ import { sendJson } from "./routes-vector-cortex-shared.js";
34
+ import type { VectorCortexTopologyView } from "./api-contracts/vector-cortex.js";
35
+
36
+ /** Well-known cortex record kind that carries a canonical candidate payload. */
37
+ const TOPOLOGY_RECORD_KIND = "topology";
38
+
39
+ /**
40
+ * Reader-only GET /api/vector-cortex/topology (VC3A + VC3B node/edge shapes).
41
+ */
42
+ export function handleVectorCortexTopology(
43
+ req: IncomingMessage,
44
+ res: ServerResponse,
45
+ ctx: RouteContext,
46
+ ): boolean {
47
+ const url = req.url ?? "";
48
+ const path = url.split("?")[0] ?? url;
49
+ if (path !== "/api/vector-cortex/topology") return false;
50
+ if (req.method !== "GET") {
51
+ // Reader-only path: no mutation endpoint lives at /topology.
52
+ sendJson(res, 405, { error: "method_not_allowed" });
53
+ return true;
54
+ }
55
+
56
+ const enabled = VC3A_ENABLED();
57
+ const topologyEnabled = VC3B_ENABLED();
58
+ let active = enabled;
59
+ let summary: {
60
+ generationId: string | null;
61
+ rootDigest: string | null;
62
+ sourceHighWater: string;
63
+ recordCount: number;
64
+ ordinal: string | null;
65
+ } = { generationId: null, rootDigest: null, sourceHighWater: "0", recordCount: 0, ordinal: null };
66
+ let nodes: { id: string; kind: string }[] | undefined;
67
+ let edges: {
68
+ source: string;
69
+ target: string;
70
+ head: string;
71
+ score: number;
72
+ direction: string;
73
+ }[] | undefined;
74
+ let generationDigest: string | null | undefined;
75
+
76
+ if (enabled) {
77
+ try {
78
+ const store = createCortexStore({ stateDir: ctx.stateDir });
79
+ try {
80
+ const reader = store.reader();
81
+ const s = reader.topologySummary();
82
+ summary = {
83
+ generationId: s.generationId,
84
+ rootDigest: s.rootDigest,
85
+ sourceHighWater: s.sourceHighWater,
86
+ recordCount: s.recordCount,
87
+ ordinal: s.ordinal,
88
+ };
89
+ if (topologyEnabled) {
90
+ const built = buildFromRecords(reader.readRecords());
91
+ nodes = built.nodes;
92
+ edges = built.edges;
93
+ generationDigest = built.generationDigest;
94
+ }
95
+ } finally {
96
+ store.close();
97
+ }
98
+ } catch {
99
+ // Non-fatal: a missing/corrupt cortex DB degrades to `enabled:false`.
100
+ active = false;
101
+ }
102
+ }
103
+
104
+ const body: VectorCortexTopologyView = {
105
+ enabled: active,
106
+ generationId: summary.generationId,
107
+ rootDigest: summary.rootDigest,
108
+ sourceHighWater: summary.sourceHighWater,
109
+ recordCount: summary.recordCount,
110
+ ordinal: summary.ordinal,
111
+ ...(topologyEnabled
112
+ ? { nodes, edges, generationDigest }
113
+ : {}),
114
+ updatedAt: new Date().toISOString(),
115
+ };
116
+ sendJson(res, 200, body);
117
+ return true;
118
+ }
119
+
120
+ /**
121
+ * Reconstruct the deterministic topology graph from the accepted derived records
122
+ * (reader-only, best-effort). Only records of kind "topology" whose payload is a
123
+ * canonical TopologyCandidate JSON are consumed; everything else is ignored.
124
+ * Returns empty arrays + null digest when no valid candidates are stored.
125
+ *
126
+ * The build seam is invoked with a logger-derived emit so the VC3B observability
127
+ * events (`vector_cortex_topology_built` / `vector_cortex_topology_edge_rejected`)
128
+ * fire on this production path — not just under unit tests. Best-effort and
129
+ * non-fatal: a failing emitter never breaks the agent loop.
130
+ *
131
+ * Q04 — DIVERGENCE RISK (documented, currently latent): the build is invoked
132
+ * with a hardcoded `threshold: 0` (plus `sessionId: "dashboard"` and
133
+ * `sourceHighWater: 0n`). This reflects the VC3B state where no production
134
+ * writer emits calibrated-threshold candidates yet, so retaining ALL stored
135
+ * "topology" records is correct for now. Once a real calibrated-threshold
136
+ * producer lands (VC3C), this dashboard digest will NOT derive from the
137
+ * authoritative threshold and can diverge from the canonical build for the same
138
+ * stored candidate set. The calibrated threshold must then be threaded through
139
+ * (e.g. sourced from the authority/config, not zero) before this route is treated
140
+ * as authoritative. Until then the route is explicitly best-effort display only.
141
+ */
142
+ function buildFromRecords(records: readonly CortexRecordV1[]): {
143
+ nodes: { id: string; kind: string }[];
144
+ edges: { source: string; target: string; head: string; score: number; direction: string }[];
145
+ generationDigest: string | null;
146
+ } {
147
+ const candidates: TopologyCandidate[] = [];
148
+ for (const r of records) {
149
+ if (r.kind !== TOPOLOGY_RECORD_KIND) continue;
150
+ const parsed = parseCandidatePayload(r);
151
+ if (parsed) candidates.push(parsed);
152
+ }
153
+ const result = buildTopologyGraph(
154
+ { sessionId: "dashboard", sourceHighWater: 0n, threshold: 0, candidates },
155
+ topologyEmit,
156
+ );
157
+ if (!result.ok) return { nodes: [], edges: [], generationDigest: null };
158
+ return {
159
+ nodes: result.topology.nodes.map((n) => ({ id: n.id, kind: n.kind })),
160
+ edges: result.topology.edges.map((e) => ({
161
+ source: e.source,
162
+ target: e.target,
163
+ head: e.head,
164
+ score: e.score,
165
+ direction: e.direction,
166
+ })),
167
+ generationDigest: result.topology.generationDigest,
168
+ };
169
+ }
170
+
171
+ /**
172
+ * Logger-derived default emitter for the VC3B topology events. Mirrors the
173
+ * cortex store's `defaultEmitFor()` convention: a REAL structured-log producer so
174
+ * a caller that invokes the build seam without injecting an emitter still yields
175
+ * telemetry (best-effort, non-fatal). This is the production invoke point that
176
+ * makes the task-5 emission capable live (not dead under unit tests only).
177
+ */
178
+ const topologyEmit: TopologyEmit = (event, fields) => {
179
+ new Logger().info(event, fields);
180
+ };
181
+
182
+ /**
183
+ * PREVENT-001: parse + shape-check a candidate payload before use. Returns
184
+ * undefined on any malformed/non-object input (best-effort, non-fatal).
185
+ *
186
+ * Q04 — FRAMING HARDENING: the canonical digest serialization in index.ts uses
187
+ * `|` (FIELD_SEP) and `~` (RECORD_SEP) as unambiguous delimiters between node
188
+ * ids/kinds and edge fields. That framing is collision-free only while id values
189
+ * (source/target/head) contain neither byte. Today ids are project-controlled, so
190
+ * this is latent, but a stored topology record could in principle carry a
191
+ * content-derived id containing those bytes, making the digest ambiguous
192
+ * (distinct graphs could collide) or the serialization injection-prone. To keep
193
+ * the digest well-defined for ANY input, reject candidates whose source/target/
194
+ * head contain the field/record separators; such a record is skipped (non-fatal)
195
+ * rather than fed into the digest.
196
+ */
197
+ function parseCandidatePayload(r: CortexRecordV1): TopologyCandidate | undefined {
198
+ let text: string;
199
+ try {
200
+ text = new TextDecoder().decode(r.payloadBytes);
201
+ } catch {
202
+ return undefined;
203
+ }
204
+ try {
205
+ const v: unknown = JSON.parse(text);
206
+ if (
207
+ v === null ||
208
+ typeof v !== "object" ||
209
+ Array.isArray(v)
210
+ ) {
211
+ return undefined;
212
+ }
213
+ const o = v as Record<string, unknown>;
214
+ if (
215
+ typeof o.source !== "string" ||
216
+ typeof o.target !== "string" ||
217
+ typeof o.head !== "string" ||
218
+ typeof o.score !== "number" ||
219
+ (o.kind !== "dependency" && o.kind !== "contradiction")
220
+ ) {
221
+ return undefined;
222
+ }
223
+ // Q04: reject any id that would corrupt the `|`/`~` digest framing.
224
+ if (
225
+ FRAMING_SEP.test(o.source) ||
226
+ FRAMING_SEP.test(o.target) ||
227
+ FRAMING_SEP.test(o.head)
228
+ ) {
229
+ return undefined;
230
+ }
231
+ return {
232
+ source: o.source,
233
+ target: o.target,
234
+ head: o.head,
235
+ score: o.score,
236
+ kind: o.kind,
237
+ };
238
+ } catch {
239
+ return undefined;
240
+ }
241
+ }
242
+
243
+ /** Field (`|`) and record (`~`) separators used by the canonical digest framing. */
244
+ const FRAMING_SEP = /[|~]/;
@@ -1,439 +1,20 @@
1
1
  /**
2
2
  * dashboard-server/routes-vector-cortex.ts — vector-cortex dashboard routes.
3
3
  *
4
- * VC0A ships a single reader-only GET /api/vector-cortex/evaluation that
5
- * aggregates redacted evaluation rows (persisted JSONL under the state dir)
6
- * via the reader. No writable capability — no reset/mutation here; VC0C adds
7
- * breaker health + reset endpoints into this same file, keeping it additive
8
- * and within extension limits.
4
+ * Delegate shell: each VC feature owns a focused handler module below the
5
+ * extension line limit, and this file re-exports them unchanged so the existing
6
+ * registration (`routes.ts`, `server.ts`) keeps working without modification.
9
7
  *
10
- * VC0C (task 5) adds:
11
- * GET /api/vector-cortex/health reader-only aggregate health card
12
- * POST /api/vector-cortex/breakers/reset — explicit admin capability
8
+ * VC0A evaluation -> routes-vector-cortex-eval.ts (GET /evaluation)
9
+ * VC0C health/reset-> routes-vector-cortex-health.ts(GET /health, POST /breakers/reset)
10
+ * VC1B ledger -> routes-vector-cortex-ledger.ts (GET /ledger)
11
+ * VC3A topology -> routes-vector-cortex-topology.ts(GET /topology)
13
12
  *
14
13
  * Guardrails: PREVENT-PI-004 (local filesystem read only), PREVENT-011 (no
15
- * `any`), reader-only aggregate (never payloads/prompts/ledger — EVAL-REDACT-002).
14
+ * `any`), reader-only aggregates (never payloads/prompts/ledger text).
16
15
  */
17
16
 
18
- import type { IncomingMessage, ServerResponse } from "node:http";
19
- import type { RouteContext } from "./routes-core.js";
20
- import { createHash } from "node:crypto";
21
- import { readFileSync, statSync } from "node:fs";
22
- import { join, dirname } from "node:path";
23
- import { fileURLToPath } from "node:url";
24
- import { VC0A_ENABLED, VC0C_ENABLED, VC1B_ENABLED, VC2C_ENABLED } from "../../src/config.js";
25
- import { readEvalRows } from "../../src/vector-cortex/eval/persist.js";
26
- import { summarizeEvalRows } from "../../src/vector-cortex/eval/reader.js";
27
- import { createVectorCortexSafety } from "../mega-runtime/vector-cortex-safety.js";
28
- import { createLedgerStore } from "../../src/vector-cortex/ledger/store.js";
29
- import { readEncoderManifest, verifyEncoderAsset, detectPlatform } from "../../src/vector-cortex/encoder/asset.js";
30
- import type {
31
- VectorCortexEvaluationSummary,
32
- VectorCortexHealthCard,
33
- VectorCortexLedgerView,
34
- VectorCortexResetResult,
35
- } from "./api-contracts/vector-cortex.js";
36
-
37
- /** Admin capability: an actor-supplied subsystem selector for breaker reset. */
38
- function readJsonBody(
39
- req: IncomingMessage,
40
- cb: (
41
- result: { ok: true; value: Record<string, unknown> } | { ok: false; error: string },
42
- ) => void,
43
- ): void {
44
- let body = "";
45
- let tooBig = false;
46
- req.on("data", (chunk: Buffer) => {
47
- if (body.length > 65536) {
48
- tooBig = true;
49
- return;
50
- }
51
- body += chunk.toString();
52
- });
53
- req.on("end", () => {
54
- if (tooBig) return cb({ ok: false, error: "body_too_large" });
55
- try {
56
- const v = body ? JSON.parse(body) : {};
57
- if (typeof v !== "object" || v === null || Array.isArray(v)) {
58
- return cb({ ok: false, error: "invalid_object" });
59
- }
60
- cb({ ok: true, value: v as Record<string, unknown> });
61
- } catch {
62
- cb({ ok: false, error: "invalid_json" });
63
- }
64
- });
65
- }
66
-
67
- function sendJson(res: ServerResponse, status: number, body: unknown): void {
68
- // guardrails-allow PREVENT-PI-004: loopback dashboard response (local)
69
- res.writeHead(status, { "Content-Type": "application/json" });
70
- res.end(JSON.stringify(body));
71
- }
72
-
73
- /** Resolve the committed encoder-v1 asset dir by walking up to the repo root. */
74
- function encoderAssetDir(): string | null {
75
- let dir = dirname(fileURLToPath(import.meta.url));
76
- const rel = join("assets", "vector-cortex", "encoder-v1");
77
- for (let i = 0; i < 8; i++) {
78
- const candidate = join(dir, rel);
79
- try {
80
- // guardrails-allow PREVENT-PI-004: local asset filesystem read (loopback)
81
- readFileSync(join(candidate, "manifest.json"));
82
- return candidate;
83
- } catch {
84
- /* keep walking */
85
- }
86
- const next = dirname(dir);
87
- if (next === dir) break;
88
- dir = next;
89
- }
90
- return null;
91
- }
92
-
93
- /**
94
- * VC2C encoder health facts (task 5): the SHA-256 of the committed qualified
95
- * manifest (asset digest) and the encoder triad mode. Reader-only aggregate
96
- * (digest prefix, no bytes). Gated on MEGACOMPACT_VC2C: when the flag is OFF
97
- * (rollback), the card reports mode C with an absent digest — consistent with
98
- * the rest of the card, whose enabled/mode fields reflect active (flag-gated)
99
- * state. When ON: "A" when the committed asset verifies on this host, "B" when
100
- * present but not verified (demotion), "C" when absent.
101
- *
102
- * The verification hashes the full ONNX + tokenizer bytes, which is expensive
103
- * on a periodically-polled endpoint as the shipped asset grows. The result is
104
- * memoized against a cheap key (manifest bytes + file sizes/mtimes + platform);
105
- * any on-disk mutation invalidates the key, so the cache never goes stale while
106
- * avoiding the repeated large-file hashing. A failed digest read returns null
107
- * (an absent digest), never a misleading zero-sentinel.
108
- */
109
- type EncoderHealthFacts = { assetDigest: string | null; mode: "A" | "B" | "C" };
110
-
111
- interface HealthFactCache {
112
- key: string;
113
- facts: EncoderHealthFacts;
114
- }
115
-
116
- let healthCache: HealthFactCache | null = null;
117
-
118
- /** Stable cache key: manifest bytes + (size,mtime) of the asset files + platform. */
119
- function healthFactCacheKey(dir: string, manifestPath: string): string | null {
120
- const platform = detectPlatform();
121
- if (!platform) return null;
122
- const parts: string[] = [platform];
123
- try {
124
- for (const p of [manifestPath, join(dir, "model.onnx"), join(dir, "tokenizer.json")]) {
125
- const s = statSync(p);
126
- parts.push(`${s.size}:${s.mtimeMs}`);
127
- }
128
- // guardrails-allow PREVENT-PI-004: local manifest filesystem read (loopback)
129
- parts.push(createHash("sha256").update(readFileSync(manifestPath)).digest("hex"));
130
- } catch {
131
- return null;
132
- }
133
- return parts.join("|");
134
- }
135
-
136
- function computeEncoderHealthFacts(dir: string): EncoderHealthFacts | null {
137
- const manifest = readEncoderManifest(dir);
138
- if (manifest === null) return { assetDigest: null, mode: "C" };
139
- const manifestPath = join(dir, "manifest.json");
140
- const key = healthFactCacheKey(dir, manifestPath);
141
- if (key === null) return null;
142
- if (healthCache !== null && healthCache.key === key) return healthCache.facts;
143
- let digest: string;
144
- try {
145
- // guardrails-allow PREVENT-PI-004: local manifest filesystem read (loopback)
146
- digest = createHash("sha256").update(readFileSync(manifestPath)).digest("hex");
147
- } catch {
148
- return { assetDigest: null, mode: "B" };
149
- }
150
- const verify = verifyEncoderAsset(dir, manifest, detectPlatform());
151
- const facts: EncoderHealthFacts = { assetDigest: digest, mode: verify.ok ? "A" : "B" };
152
- healthCache = { key, facts };
153
- return facts;
154
- }
155
-
156
- function encoderHealthFacts(): EncoderHealthFacts {
157
- if (!VC2C_ENABLED()) {
158
- // Rollback: MEGACOMPACT_VC2C=0 selects C — report the inactive (flag-gated)
159
- // mode with no asset digest rather than an on-disk-computed A/B.
160
- return { assetDigest: null, mode: "C" };
161
- }
162
- const dir = encoderAssetDir();
163
- if (dir === null) return { assetDigest: null, mode: "C" };
164
- const facts = computeEncoderHealthFacts(dir);
165
- if (facts === null) return { assetDigest: null, mode: "C" };
166
- return facts;
167
- }
168
-
169
- /** Reader-only aggregate GET /api/vector-cortex/evaluation. */
170
- export function handleVectorCortexEvaluation(
171
- req: IncomingMessage,
172
- res: ServerResponse,
173
- ctx: RouteContext,
174
- ): boolean {
175
- const url = req.url ?? "";
176
- if (url !== "/api/vector-cortex/evaluation") return false;
177
- if (req.method !== "GET") {
178
- // Reader-only: no mutation endpoints exist on this path.
179
- // guardrails-allow PREVENT-PI-004: loopback dashboard response (local)
180
- res.writeHead(405, { "Content-Type": "application/json" });
181
- res.end(JSON.stringify({ error: "method_not_allowed" }));
182
- return true;
183
- }
184
-
185
- const enabled = VC0A_ENABLED();
186
- const rows = enabled ? readEvalRows(ctx.stateDir) : [];
187
- const summary = summarizeEvalRows(rows);
188
-
189
- const body: VectorCortexEvaluationSummary = {
190
- enabled,
191
- mode: enabled ? "A" : "C",
192
- samples: summary.samples,
193
- byMode: {
194
- A: summary.byMode.A,
195
- B: summary.byMode.B,
196
- C: summary.byMode.C,
197
- },
198
- histogram: {
199
- edges: [...summary.histogram.edges],
200
- cells: [...summary.histogram.cells],
201
- overflow: summary.histogram.overflow,
202
- total: summary.histogram.total,
203
- },
204
- rejects: [], // VC0C wires live breaker/reject telemetry here
205
- updatedAt: new Date().toISOString(),
206
- };
207
- sendJson(res, 200, body);
208
- return true;
209
- }
210
-
211
- /**
212
- * Reader-only GET /api/vector-cortex/health (VC0C).
213
- *
214
- * Aggregate health card: breaker state (window/probe/backoff), durable spool
215
- * frontier/authority/lag, and a worst-state aggregate. Constructs the safety
216
- * adapter over the state dir — durable spool state (frontier-frozen, lag) is
217
- * read from disk, so it reflects restart. Purely read: no mutation, never
218
- * payloads/prompts/ledger.
219
- */
220
- export function handleVectorCortexHealth(
221
- req: IncomingMessage,
222
- res: ServerResponse,
223
- ctx: RouteContext,
224
- ): boolean {
225
- const url = req.url ?? "";
226
- if (url !== "/api/vector-cortex/health") return false;
227
- if (req.method !== "GET") {
228
- // Reader-only path: no mutation endpoint lives at /health.
229
- sendJson(res, 405, { error: "method_not_allowed" });
230
- return true;
231
- }
232
-
233
- const enabled = VC0C_ENABLED();
234
- const safety = enabled ? createVectorCortexSafety({ stateDir: ctx.stateDir }) : null;
235
- const card = safety ? safety.health() : null;
236
-
237
- const enc = encoderHealthFacts();
238
-
239
- const fallback: VectorCortexHealthCard = {
240
- enabled: false,
241
- mode: "C",
242
- state: "CLOSED_A",
243
- subsystem: "provider",
244
- sinceMs: 0,
245
- windowMs: 0,
246
- probeCount: 0,
247
- backoffDelayMs: 0,
248
- frontierFrozen: false,
249
- authorityOutage: false,
250
- spoolLag: 0,
251
- attempts: 0,
252
- failures: 0,
253
- p95Ms: 0,
254
- failureRate: 0,
255
- updatedAt: new Date().toISOString(),
256
- aggregate: "CLOSED_A",
257
- stateSource: "ephemeral",
258
- encoderAssetDigest: enc.assetDigest,
259
- encoderMode: enc.mode,
260
- };
261
- if (!card) {
262
- sendJson(res, 200, fallback);
263
- return true;
264
- }
265
-
266
- const mode: "A" | "B" | "C" =
267
- card.state === "CLOSED_A" ? "A" : card.state === "MANUAL_HALT" ? "C" : "B";
268
- const aggregate =
269
- card.state === "MANUAL_HALT"
270
- ? "MANUAL_HALT"
271
- : card.state === "OPEN_C"
272
- ? "OPEN_C"
273
- : card.state === "OPEN_B"
274
- ? "OPEN_B"
275
- : card.state === "PROBE_B" || card.state === "PROBE_A"
276
- ? "PROBE"
277
- : "CLOSED_A";
278
-
279
- const body: VectorCortexHealthCard = {
280
- enabled,
281
- mode,
282
- state: card.state,
283
- subsystem: card.subsystem,
284
- sinceMs: card.sinceMs,
285
- reason: card.reason,
286
- windowMs: card.windowMs,
287
- probeCount: card.probeCount,
288
- backoffDelayMs: card.backoffDelayMs,
289
- frontierFrozen: card.frontierFrozen,
290
- authorityOutage: card.authorityOutage,
291
- spoolLag: card.spoolLag,
292
- attempts: card.attempts,
293
- failures: card.failures,
294
- p95Ms: card.p95Ms,
295
- failureRate: card.failureRate,
296
- updatedAt: new Date().toISOString(),
297
- aggregate,
298
- stateSource: card.stateSource,
299
- encoderAssetDigest: enc.assetDigest,
300
- encoderMode: enc.mode,
301
- };
302
- sendJson(res, 200, body);
303
- return true;
304
- }
305
-
306
- /**
307
- * Admin POST /api/vector-cortex/breakers/reset (VC0C).
308
- *
309
- * Explicit admin capability (separate from the reader GET). Clears a breaker's
310
- * cooldown — or unwires a MANUAL_HALT — but NEVER evidence (attempts/failures
311
- * are retained, per TRIAD_RESILIENCE). The subsystem is actor-supplied via the
312
- * JSON body `{ subsystem }`. Every reset is documented in the returned record
313
- * (state, retained evidence, updatedAt) — an auditable mutation surface; the
314
- * GET path can never mutate.
315
- */
316
- export function handleVectorCortexBreakersReset(
317
- req: IncomingMessage,
318
- res: ServerResponse,
319
- ctx: RouteContext,
320
- ): boolean {
321
- const url = req.url ?? "";
322
- if (url !== "/api/vector-cortex/breakers/reset") return false;
323
- if (req.method !== "POST") {
324
- sendJson(res, 405, { error: "method_not_allowed" });
325
- return true;
326
- }
327
- if (!VC0C_ENABLED()) {
328
- sendJson(res, 409, { error: "vco_c_disabled" });
329
- return true;
330
- }
331
-
332
- readJsonBody(req, (parsed) => {
333
- if (!parsed.ok) {
334
- sendJson(res, 400, { error: parsed.error });
335
- return;
336
- }
337
- const subsystem = parsed.value.subsystem;
338
- if (typeof subsystem !== "string" || subsystem.length === 0) {
339
- sendJson(res, 400, { error: "subsystem_required" });
340
- return;
341
- }
342
- try {
343
- const safety = createVectorCortexSafety({ stateDir: ctx.stateDir });
344
- const rec = safety.reset(subsystem);
345
- const body: VectorCortexResetResult = {
346
- subsystem: rec.subsystem,
347
- state: rec.state,
348
- cooldownCleared: true,
349
- attempts: rec.attempts,
350
- failures: rec.failures,
351
- probeCount: rec.probeCount,
352
- manualReason: rec.manualReason,
353
- updatedAt: rec.updatedAt,
354
- };
355
- sendJson(res, 200, body);
356
- } catch {
357
- sendJson(res, 500, { error: "reset_failed" });
358
- }
359
- });
360
- return true;
361
- }
362
-
363
- /**
364
- * Reader-only GET /api/vector-cortex/ledger (VC1B).
365
- *
366
- * Built on the LedgerReader capability: opens the occurrence-v2 ledger for this
367
- * repo's state dir and returns the session's occurrence IDENTITY rows
368
- * (seq/eventId/kind/digest/toolCallId) plus high-water/count. NEVER ships
369
- * sourceBytes or prompt text (reader-only no-ledger-text rule). Optional
370
- * `?session=<id>` query selects the session (default "default").
371
- */
372
- export function handleVectorCortexLedger(
373
- req: IncomingMessage,
374
- res: ServerResponse,
375
- ctx: RouteContext,
376
- ): boolean {
377
- const url = req.url ?? "";
378
- const path = url.split("?")[0] ?? url;
379
- if (path !== "/api/vector-cortex/ledger") return false;
380
- if (req.method !== "GET") {
381
- // Reader-only path: no mutation endpoint lives at /ledger.
382
- sendJson(res, 405, { error: "method_not_allowed" });
383
- return true;
384
- }
385
-
386
- // Parse the optional session query parameter.
387
- let session = "default";
388
- const qs = url.split("?")[1];
389
- if (qs !== undefined) {
390
- for (const pair of qs.split("&")) {
391
- const [k, v] = pair.split("=");
392
- if (k === "session" && v !== undefined && v.length > 0) {
393
- session = decodeURIComponent(v);
394
- }
395
- }
396
- }
397
-
398
- const enabled = VC1B_ENABLED();
399
- let active = enabled;
400
- let highWater = "0";
401
- let count = 0;
402
- let occurrences: VectorCortexLedgerView["occurrences"] = [];
403
-
404
- if (enabled) {
405
- try {
406
- const store = createLedgerStore({ stateDir: ctx.stateDir });
407
- try {
408
- const reader = store.reader();
409
- highWater = reader.highWater(session).toString();
410
- const rows = reader.readSession(session);
411
- count = rows.length;
412
- // Identity only: never sourceBytes or prompt text (reader-only rule).
413
- occurrences = rows.slice(-500).map((occ) => ({
414
- seq: occ.seq.toString(),
415
- eventId: occ.eventId,
416
- kind: occ.kind,
417
- digest: occ.digest,
418
- ...(occ.toolCallId !== undefined ? { toolCallId: occ.toolCallId } : {}),
419
- }));
420
- } finally {
421
- store.close();
422
- }
423
- } catch {
424
- // Non-fatal: a missing/corrupt ledger DB degrades to `enabled:false`.
425
- active = false;
426
- }
427
- }
428
-
429
- const body: VectorCortexLedgerView = {
430
- enabled: active,
431
- session,
432
- highWater,
433
- count,
434
- occurrences,
435
- updatedAt: new Date().toISOString(),
436
- };
437
- sendJson(res, 200, body);
438
- return true;
439
- }
17
+ export { handleVectorCortexEvaluation } from "./routes-vector-cortex-eval.js";
18
+ export { handleVectorCortexHealth, handleVectorCortexBreakersReset } from "./routes-vector-cortex-health.js";
19
+ export { handleVectorCortexLedger } from "./routes-vector-cortex-ledger.js";
20
+ export { handleVectorCortexTopology } from "./routes-vector-cortex-topology.js";