pi-mega-compact 0.19.1 → 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 (75) hide show
  1. package/dist/config/vector-cortex.js +9 -0
  2. package/dist/config.js +1 -1
  3. package/dist/extensions/dashboard-server/routes-rag-settings-helpers.js +1 -0
  4. package/dist/extensions/dashboard-server/routes-vector-cortex-topology.js +145 -5
  5. package/dist/src/config/vector-cortex.js +9 -0
  6. package/dist/src/config.js +1 -1
  7. package/dist/src/vector-cortex/topology/build.js +232 -0
  8. package/dist/src/vector-cortex/topology/index.js +113 -0
  9. package/dist/src/vector-cortex/topology/types.js +54 -0
  10. package/dist/src/vector-cortex/vc3b-support.js +125 -0
  11. package/dist/vector-cortex/topology/build.js +232 -0
  12. package/dist/vector-cortex/topology/index.js +113 -0
  13. package/dist/vector-cortex/topology/types.js +54 -0
  14. package/dist/vector-cortex/vc3b-support.js +125 -0
  15. package/extensions/dashboard-client/dist/assets/{AreaChart-B9KYKrUE.js → AreaChart-CSaJZXru.js} +2 -2
  16. package/extensions/dashboard-client/dist/assets/{AreaChart-B9KYKrUE.js.map → AreaChart-CSaJZXru.js.map} +1 -1
  17. package/extensions/dashboard-client/dist/assets/{BarChart-D1sWkR6j.js → BarChart-CQouNj1g.js} +2 -2
  18. package/extensions/dashboard-client/dist/assets/{BarChart-D1sWkR6j.js.map → BarChart-CQouNj1g.js.map} +1 -1
  19. package/extensions/dashboard-client/dist/assets/{CacheTab-BR8MYcJq.js → CacheTab-m_eiCYoL.js} +2 -2
  20. package/extensions/dashboard-client/dist/assets/{CacheTab-BR8MYcJq.js.map → CacheTab-m_eiCYoL.js.map} +1 -1
  21. package/extensions/dashboard-client/dist/assets/{EventsTab-BRNpDMvP.js → EventsTab-DRyOwjYN.js} +2 -2
  22. package/extensions/dashboard-client/dist/assets/{EventsTab-BRNpDMvP.js.map → EventsTab-DRyOwjYN.js.map} +1 -1
  23. package/extensions/dashboard-client/dist/assets/{HealthTab-rr5nXpjq.js → HealthTab-Dj9k40TJ.js} +2 -2
  24. package/extensions/dashboard-client/dist/assets/{HealthTab-rr5nXpjq.js.map → HealthTab-Dj9k40TJ.js.map} +1 -1
  25. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-CtjPWnzN.js → MaintenanceTab-Bk9mhYfD.js} +2 -2
  26. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-CtjPWnzN.js.map → MaintenanceTab-Bk9mhYfD.js.map} +1 -1
  27. package/extensions/dashboard-client/dist/assets/{MemoryMapTab-5SnFDIYc.js → MemoryMapTab-C7ve49VG.js} +2 -2
  28. package/extensions/dashboard-client/dist/assets/{MemoryMapTab-5SnFDIYc.js.map → MemoryMapTab-C7ve49VG.js.map} +1 -1
  29. package/extensions/dashboard-client/dist/assets/{MetricsTab-4MZfwRhq.js → MetricsTab-DzjhqZA9.js} +2 -2
  30. package/extensions/dashboard-client/dist/assets/{MetricsTab-4MZfwRhq.js.map → MetricsTab-DzjhqZA9.js.map} +1 -1
  31. package/extensions/dashboard-client/dist/assets/{OverviewTab-BAKENnbk.js → OverviewTab-CFQdfIm_.js} +2 -2
  32. package/extensions/dashboard-client/dist/assets/{OverviewTab-BAKENnbk.js.map → OverviewTab-CFQdfIm_.js.map} +1 -1
  33. package/extensions/dashboard-client/dist/assets/{ReposTab-7-z_OmZo.js → ReposTab-DyjwEFUr.js} +2 -2
  34. package/extensions/dashboard-client/dist/assets/{ReposTab-7-z_OmZo.js.map → ReposTab-DyjwEFUr.js.map} +1 -1
  35. package/extensions/dashboard-client/dist/assets/{SessionsTab-D_r2ki0y.js → SessionsTab-njLIy7ab.js} +2 -2
  36. package/extensions/dashboard-client/dist/assets/{SessionsTab-D_r2ki0y.js.map → SessionsTab-njLIy7ab.js.map} +1 -1
  37. package/extensions/dashboard-client/dist/assets/{SetupTab-DPujtYgv.js → SetupTab-UHIs8-Lh.js} +2 -2
  38. package/extensions/dashboard-client/dist/assets/{SetupTab-DPujtYgv.js.map → SetupTab-UHIs8-Lh.js.map} +1 -1
  39. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-CLHy30t6.js → TimeSavedCard-inWHjCxg.js} +2 -2
  40. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-CLHy30t6.js.map → TimeSavedCard-inWHjCxg.js.map} +1 -1
  41. package/extensions/dashboard-client/dist/assets/{TurnsTab-Coul6CHc.js → TurnsTab-CXJYugBu.js} +2 -2
  42. package/extensions/dashboard-client/dist/assets/{TurnsTab-Coul6CHc.js.map → TurnsTab-CXJYugBu.js.map} +1 -1
  43. package/extensions/dashboard-client/dist/assets/VectorCortexTab-DkS0Azx9.js +2 -0
  44. package/extensions/dashboard-client/dist/assets/VectorCortexTab-DkS0Azx9.js.map +1 -0
  45. package/extensions/dashboard-client/dist/assets/{WikiTab-hryG5oyY.js → WikiTab-BJ4A2oi9.js} +2 -2
  46. package/extensions/dashboard-client/dist/assets/{WikiTab-hryG5oyY.js.map → WikiTab-BJ4A2oi9.js.map} +1 -1
  47. package/extensions/dashboard-client/dist/assets/{button-Dxo95lRI.js → button-BWl-moyn.js} +2 -2
  48. package/extensions/dashboard-client/dist/assets/{button-Dxo95lRI.js.map → button-BWl-moyn.js.map} +1 -1
  49. package/extensions/dashboard-client/dist/assets/{card-FXwhLF_u.js → card-C58RVPOk.js} +2 -2
  50. package/extensions/dashboard-client/dist/assets/{card-FXwhLF_u.js.map → card-C58RVPOk.js.map} +1 -1
  51. package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-M-GeRM8U.js → generateCategoricalChart-vgeOQU3L.js} +2 -2
  52. package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-M-GeRM8U.js.map → generateCategoricalChart-vgeOQU3L.js.map} +1 -1
  53. package/extensions/dashboard-client/dist/assets/{index-BIZZXvoy.js → index-lVrWQjpu.js} +3 -3
  54. package/extensions/dashboard-client/dist/assets/{index-BIZZXvoy.js.map → index-lVrWQjpu.js.map} +1 -1
  55. package/extensions/dashboard-client/dist/assets/{switch-C-d4tkN1.js → switch-CSeplFQT.js} +2 -2
  56. package/extensions/dashboard-client/dist/assets/{switch-C-d4tkN1.js.map → switch-CSeplFQT.js.map} +1 -1
  57. package/extensions/dashboard-client/dist/assets/{toggle-Bfmucdcl.js → toggle-CQRxgVRi.js} +2 -2
  58. package/extensions/dashboard-client/dist/assets/{toggle-Bfmucdcl.js.map → toggle-CQRxgVRi.js.map} +1 -1
  59. package/extensions/dashboard-client/dist/assets/{useSSE-CxK_wdmk.js → useSSE-BUz6IOI-.js} +2 -2
  60. package/extensions/dashboard-client/dist/assets/{useSSE-CxK_wdmk.js.map → useSSE-BUz6IOI-.js.map} +1 -1
  61. package/extensions/dashboard-client/dist/index.html +1 -1
  62. package/extensions/dashboard-client/src/tabs/VectorCortexTab.tsx +55 -0
  63. package/extensions/dashboard-client/src/types/vector-cortex.ts +13 -0
  64. package/extensions/dashboard-server/api-contracts/vector-cortex.ts +18 -0
  65. package/extensions/dashboard-server/routes-rag-settings-helpers.ts +6 -0
  66. package/extensions/dashboard-server/routes-vector-cortex-topology.ts +166 -5
  67. package/package.json +1 -1
  68. package/src/config/vector-cortex.ts +10 -0
  69. package/src/config.ts +1 -0
  70. package/src/vector-cortex/topology/build.ts +259 -0
  71. package/src/vector-cortex/topology/index.ts +143 -0
  72. package/src/vector-cortex/topology/types.ts +156 -0
  73. package/src/vector-cortex/vc3b-support.ts +142 -0
  74. package/extensions/dashboard-client/dist/assets/VectorCortexTab-rqBpWc7A.js +0 -2
  75. package/extensions/dashboard-client/dist/assets/VectorCortexTab-rqBpWc7A.js.map +0 -1
@@ -101,6 +101,15 @@ export const VC2C_ENABLED = () => sprintFlag("MEGACOMPACT_VC2C");
101
101
  * cortex rebuild/admin seam and the reader-only topology summary seam.
102
102
  */
103
103
  export const VC3A_ENABLED = () => sprintFlag("MEGACOMPACT_VC3A");
104
+ /**
105
+ * VC3B — deterministic cortical topology (TopologyV1 / EdgeV1).
106
+ * Default ON. `MEGACOMPACT_VC3B=0` disables and is byte-identical to the
107
+ * predecessor (mode C: no topology graph is built or emitted, the dashboard
108
+ * topology view returns the VC3A-precise aggregation shape with no node/edge
109
+ * arrays, zero `vector_cortex_topology_*` emissions). The real consumers are
110
+ * the topology build seam (build.ts) and the dashboard topology node/edge view.
111
+ */
112
+ export const VC3B_ENABLED = () => sprintFlag("MEGACOMPACT_VC3B");
104
113
  // ---------------------------------------------------------------------------
105
114
  // Breaker state machine constants (TRIAD_RESILIENCE.md §breaker).
106
115
  // Rolled numbers for one 60s window; VC0C consumes these at its breaker seam.
package/dist/config.js CHANGED
@@ -114,4 +114,4 @@ export const NEW_UI = () => ragEnabled("MEGACOMPACT_NEW_UI");
114
114
  // default ON, `=0`/`_DISABLED` off. Re-exported from src/config/vector-cortex.ts
115
115
  // so root consumers share one source of truth.
116
116
  // ---------------------------------------------------------------------------
117
- export { VC0A_ENABLED, VC0B_ENABLED, VC1A_ENABLED, VC0C_ENABLED, VC1B_ENABLED, VC1C_ENABLED, VC2A_ENABLED, VC2B_ENABLED, VC2C_ENABLED, VC3A_ENABLED, BREAKER_WINDOW_MS, BREAKER_MIN_ATTEMPTS, BREAKER_PERF_FAILURES, BREAKER_PERF_FAILURE_RATE, BREAKER_CORRECTNESS_FAILURES, BREAKER_COOLDOWN_MS, BREAKER_PROBE_COUNT, BREAKER_RETRY_BASE_MS, BREAKER_RETRY_CAP_MS, BREAKER_RETRY_JITTER, BREAKER_HYSTERESIS_FAILURE_RATE, BREAKER_HYSTERESIS_BUDGET_P95_MS, BREAKER_MIN_HEALTHY_RESIDENCE_MS, } from "./config/vector-cortex.js";
117
+ export { VC0A_ENABLED, VC0B_ENABLED, VC1A_ENABLED, VC0C_ENABLED, VC1B_ENABLED, VC1C_ENABLED, VC2A_ENABLED, VC2B_ENABLED, VC2C_ENABLED, VC3A_ENABLED, VC3B_ENABLED, BREAKER_WINDOW_MS, BREAKER_MIN_ATTEMPTS, BREAKER_PERF_FAILURES, BREAKER_PERF_FAILURE_RATE, BREAKER_CORRECTNESS_FAILURES, BREAKER_COOLDOWN_MS, BREAKER_PROBE_COUNT, BREAKER_RETRY_BASE_MS, BREAKER_RETRY_CAP_MS, BREAKER_RETRY_JITTER, BREAKER_HYSTERESIS_FAILURE_RATE, BREAKER_HYSTERESIS_BUDGET_P95_MS, BREAKER_MIN_HEALTHY_RESIDENCE_MS, } from "./config/vector-cortex.js";
@@ -144,6 +144,7 @@ export const SETTINGS = [
144
144
  boolDirect("MEGACOMPACT_VC2B", "VC2B Multi-Head Encoder", "VectorSetV1 five L2-normalized heads (384/128/128/64/32) with head-calibration draft + asset-free trigram B (512d) and lexical C fallbacks, plus the per-head emit seam. OFF = mode C, no per-head vectors emitted, byte-identical predecessor.", true),
145
145
  boolDirect("MEGACOMPACT_VC2C", "VC2C Encoder Qualification + Calibration", "QualifiedEncoderV1/CalibrationV1: calibration fit on the calibration split only (held-out labels prohibited) + atomic selection across MODEL_ASSET and per-head EVALUATION thresholds (any field failure demotes all of A). OFF = mode C, no qualification/calibration selection, byte-identical predecessor.", true),
146
146
  boolDirect("MEGACOMPACT_VC3A", "VC3A Cortex Store", "Capability-gated derived cortex store (CortexReader/Writer/Admin + CortexRecordV1): additive, keyed (sourceHighWater, algorithmVersion, id), immutable records, deterministic generation rebuild + one root digest. OFF = mode C, no cortex records written, byte-identical predecessor.", true),
147
+ boolDirect("MEGACOMPACT_VC3B", "VC3B Deterministic Topology", "Deterministic cortical topology (TopologyV1/EdgeV1): per-(source,head) top-k=16/head calibrated-threshold edges, stable score-desc/then-target-ID sort, dependency directed + contradiction symmetric paired records, one stable generation digest. OFF = mode C, no topology graph built/emitted, predecessor-precise topology view, byte-identical predecessor.", true),
147
148
  ],
148
149
  },
149
150
  {
@@ -1,6 +1,6 @@
1
1
  /**
2
- * dashboard-server/routes-vector-cortex-topology.ts — VC3A vector-cortex topology
3
- * dashboard route.
2
+ * dashboard-server/routes-vector-cortex-topology.ts — VC3A/VC3B vector-cortex
3
+ * topology dashboard route.
4
4
  *
5
5
  * Reader-only GET /api/vector-cortex/topology built ENTIRELY on the CortexReader
6
6
  * capability: opens the isolated cortex DB for this repo's state dir and returns
@@ -10,14 +10,26 @@
10
10
  * (no writer/admin leakage). Non-fatal: a missing or corrupt cortex DB degrades
11
11
  * to `enabled:false`.
12
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
+ *
13
21
  * Guardrails: PREVENT-PI-004 (local filesystem read only), PREVENT-011 (no
14
22
  * `any`), reader-only aggregate.
15
23
  */
16
- import { VC3A_ENABLED } from "../../src/config.js";
24
+ import { VC3A_ENABLED, VC3B_ENABLED } from "../../src/config.js";
25
+ import { Logger } from "../../src/log.js";
17
26
  import { createCortexStore } from "../../src/vector-cortex/cortex/store.js";
27
+ import { buildTopologyGraph } from "../../src/vector-cortex/topology/index.js";
18
28
  import { sendJson } from "./routes-vector-cortex-shared.js";
29
+ /** Well-known cortex record kind that carries a canonical candidate payload. */
30
+ const TOPOLOGY_RECORD_KIND = "topology";
19
31
  /**
20
- * Reader-only GET /api/vector-cortex/topology (VC3A).
32
+ * Reader-only GET /api/vector-cortex/topology (VC3A + VC3B node/edge shapes).
21
33
  */
22
34
  export function handleVectorCortexTopology(req, res, ctx) {
23
35
  const url = req.url ?? "";
@@ -30,13 +42,18 @@ export function handleVectorCortexTopology(req, res, ctx) {
30
42
  return true;
31
43
  }
32
44
  const enabled = VC3A_ENABLED();
45
+ const topologyEnabled = VC3B_ENABLED();
33
46
  let active = enabled;
34
47
  let summary = { generationId: null, rootDigest: null, sourceHighWater: "0", recordCount: 0, ordinal: null };
48
+ let nodes;
49
+ let edges;
50
+ let generationDigest;
35
51
  if (enabled) {
36
52
  try {
37
53
  const store = createCortexStore({ stateDir: ctx.stateDir });
38
54
  try {
39
- const s = store.reader().topologySummary();
55
+ const reader = store.reader();
56
+ const s = reader.topologySummary();
40
57
  summary = {
41
58
  generationId: s.generationId,
42
59
  rootDigest: s.rootDigest,
@@ -44,6 +61,12 @@ export function handleVectorCortexTopology(req, res, ctx) {
44
61
  recordCount: s.recordCount,
45
62
  ordinal: s.ordinal,
46
63
  };
64
+ if (topologyEnabled) {
65
+ const built = buildFromRecords(reader.readRecords());
66
+ nodes = built.nodes;
67
+ edges = built.edges;
68
+ generationDigest = built.generationDigest;
69
+ }
47
70
  }
48
71
  finally {
49
72
  store.close();
@@ -61,8 +84,125 @@ export function handleVectorCortexTopology(req, res, ctx) {
61
84
  sourceHighWater: summary.sourceHighWater,
62
85
  recordCount: summary.recordCount,
63
86
  ordinal: summary.ordinal,
87
+ ...(topologyEnabled
88
+ ? { nodes, edges, generationDigest }
89
+ : {}),
64
90
  updatedAt: new Date().toISOString(),
65
91
  };
66
92
  sendJson(res, 200, body);
67
93
  return true;
68
94
  }
95
+ /**
96
+ * Reconstruct the deterministic topology graph from the accepted derived records
97
+ * (reader-only, best-effort). Only records of kind "topology" whose payload is a
98
+ * canonical TopologyCandidate JSON are consumed; everything else is ignored.
99
+ * Returns empty arrays + null digest when no valid candidates are stored.
100
+ *
101
+ * The build seam is invoked with a logger-derived emit so the VC3B observability
102
+ * events (`vector_cortex_topology_built` / `vector_cortex_topology_edge_rejected`)
103
+ * fire on this production path — not just under unit tests. Best-effort and
104
+ * non-fatal: a failing emitter never breaks the agent loop.
105
+ *
106
+ * Q04 — DIVERGENCE RISK (documented, currently latent): the build is invoked
107
+ * with a hardcoded `threshold: 0` (plus `sessionId: "dashboard"` and
108
+ * `sourceHighWater: 0n`). This reflects the VC3B state where no production
109
+ * writer emits calibrated-threshold candidates yet, so retaining ALL stored
110
+ * "topology" records is correct for now. Once a real calibrated-threshold
111
+ * producer lands (VC3C), this dashboard digest will NOT derive from the
112
+ * authoritative threshold and can diverge from the canonical build for the same
113
+ * stored candidate set. The calibrated threshold must then be threaded through
114
+ * (e.g. sourced from the authority/config, not zero) before this route is treated
115
+ * as authoritative. Until then the route is explicitly best-effort display only.
116
+ */
117
+ function buildFromRecords(records) {
118
+ const candidates = [];
119
+ for (const r of records) {
120
+ if (r.kind !== TOPOLOGY_RECORD_KIND)
121
+ continue;
122
+ const parsed = parseCandidatePayload(r);
123
+ if (parsed)
124
+ candidates.push(parsed);
125
+ }
126
+ const result = buildTopologyGraph({ sessionId: "dashboard", sourceHighWater: 0n, threshold: 0, candidates }, topologyEmit);
127
+ if (!result.ok)
128
+ return { nodes: [], edges: [], generationDigest: null };
129
+ return {
130
+ nodes: result.topology.nodes.map((n) => ({ id: n.id, kind: n.kind })),
131
+ edges: result.topology.edges.map((e) => ({
132
+ source: e.source,
133
+ target: e.target,
134
+ head: e.head,
135
+ score: e.score,
136
+ direction: e.direction,
137
+ })),
138
+ generationDigest: result.topology.generationDigest,
139
+ };
140
+ }
141
+ /**
142
+ * Logger-derived default emitter for the VC3B topology events. Mirrors the
143
+ * cortex store's `defaultEmitFor()` convention: a REAL structured-log producer so
144
+ * a caller that invokes the build seam without injecting an emitter still yields
145
+ * telemetry (best-effort, non-fatal). This is the production invoke point that
146
+ * makes the task-5 emission capable live (not dead under unit tests only).
147
+ */
148
+ const topologyEmit = (event, fields) => {
149
+ new Logger().info(event, fields);
150
+ };
151
+ /**
152
+ * PREVENT-001: parse + shape-check a candidate payload before use. Returns
153
+ * undefined on any malformed/non-object input (best-effort, non-fatal).
154
+ *
155
+ * Q04 — FRAMING HARDENING: the canonical digest serialization in index.ts uses
156
+ * `|` (FIELD_SEP) and `~` (RECORD_SEP) as unambiguous delimiters between node
157
+ * ids/kinds and edge fields. That framing is collision-free only while id values
158
+ * (source/target/head) contain neither byte. Today ids are project-controlled, so
159
+ * this is latent, but a stored topology record could in principle carry a
160
+ * content-derived id containing those bytes, making the digest ambiguous
161
+ * (distinct graphs could collide) or the serialization injection-prone. To keep
162
+ * the digest well-defined for ANY input, reject candidates whose source/target/
163
+ * head contain the field/record separators; such a record is skipped (non-fatal)
164
+ * rather than fed into the digest.
165
+ */
166
+ function parseCandidatePayload(r) {
167
+ let text;
168
+ try {
169
+ text = new TextDecoder().decode(r.payloadBytes);
170
+ }
171
+ catch {
172
+ return undefined;
173
+ }
174
+ try {
175
+ const v = JSON.parse(text);
176
+ if (v === null ||
177
+ typeof v !== "object" ||
178
+ Array.isArray(v)) {
179
+ return undefined;
180
+ }
181
+ const o = v;
182
+ if (typeof o.source !== "string" ||
183
+ typeof o.target !== "string" ||
184
+ typeof o.head !== "string" ||
185
+ typeof o.score !== "number" ||
186
+ (o.kind !== "dependency" && o.kind !== "contradiction")) {
187
+ return undefined;
188
+ }
189
+ // Q04: reject any id that would corrupt the `|`/`~` digest framing.
190
+ if (FRAMING_SEP.test(o.source) ||
191
+ FRAMING_SEP.test(o.target) ||
192
+ FRAMING_SEP.test(o.head)) {
193
+ return undefined;
194
+ }
195
+ return {
196
+ source: o.source,
197
+ target: o.target,
198
+ head: o.head,
199
+ score: o.score,
200
+ kind: o.kind,
201
+ };
202
+ }
203
+ catch {
204
+ return undefined;
205
+ }
206
+ }
207
+ /** Field (`|`) and record (`~`) separators used by the canonical digest framing. */
208
+ const FRAMING_SEP = /[|~]/;
@@ -101,6 +101,15 @@ export const VC2C_ENABLED = () => sprintFlag("MEGACOMPACT_VC2C");
101
101
  * cortex rebuild/admin seam and the reader-only topology summary seam.
102
102
  */
103
103
  export const VC3A_ENABLED = () => sprintFlag("MEGACOMPACT_VC3A");
104
+ /**
105
+ * VC3B — deterministic cortical topology (TopologyV1 / EdgeV1).
106
+ * Default ON. `MEGACOMPACT_VC3B=0` disables and is byte-identical to the
107
+ * predecessor (mode C: no topology graph is built or emitted, the dashboard
108
+ * topology view returns the VC3A-precise aggregation shape with no node/edge
109
+ * arrays, zero `vector_cortex_topology_*` emissions). The real consumers are
110
+ * the topology build seam (build.ts) and the dashboard topology node/edge view.
111
+ */
112
+ export const VC3B_ENABLED = () => sprintFlag("MEGACOMPACT_VC3B");
104
113
  // ---------------------------------------------------------------------------
105
114
  // Breaker state machine constants (TRIAD_RESILIENCE.md §breaker).
106
115
  // Rolled numbers for one 60s window; VC0C consumes these at its breaker seam.
@@ -114,4 +114,4 @@ export const NEW_UI = () => ragEnabled("MEGACOMPACT_NEW_UI");
114
114
  // default ON, `=0`/`_DISABLED` off. Re-exported from src/config/vector-cortex.ts
115
115
  // so root consumers share one source of truth.
116
116
  // ---------------------------------------------------------------------------
117
- export { VC0A_ENABLED, VC0B_ENABLED, VC1A_ENABLED, VC0C_ENABLED, VC1B_ENABLED, VC1C_ENABLED, VC2A_ENABLED, VC2B_ENABLED, VC2C_ENABLED, VC3A_ENABLED, BREAKER_WINDOW_MS, BREAKER_MIN_ATTEMPTS, BREAKER_PERF_FAILURES, BREAKER_PERF_FAILURE_RATE, BREAKER_CORRECTNESS_FAILURES, BREAKER_COOLDOWN_MS, BREAKER_PROBE_COUNT, BREAKER_RETRY_BASE_MS, BREAKER_RETRY_CAP_MS, BREAKER_RETRY_JITTER, BREAKER_HYSTERESIS_FAILURE_RATE, BREAKER_HYSTERESIS_BUDGET_P95_MS, BREAKER_MIN_HEALTHY_RESIDENCE_MS, } from "./config/vector-cortex.js";
117
+ export { VC0A_ENABLED, VC0B_ENABLED, VC1A_ENABLED, VC0C_ENABLED, VC1B_ENABLED, VC1C_ENABLED, VC2A_ENABLED, VC2B_ENABLED, VC2C_ENABLED, VC3A_ENABLED, VC3B_ENABLED, BREAKER_WINDOW_MS, BREAKER_MIN_ATTEMPTS, BREAKER_PERF_FAILURES, BREAKER_PERF_FAILURE_RATE, BREAKER_CORRECTNESS_FAILURES, BREAKER_COOLDOWN_MS, BREAKER_PROBE_COUNT, BREAKER_RETRY_BASE_MS, BREAKER_RETRY_CAP_MS, BREAKER_RETRY_JITTER, BREAKER_HYSTERESIS_FAILURE_RATE, BREAKER_HYSTERESIS_BUDGET_P95_MS, BREAKER_MIN_HEALTHY_RESIDENCE_MS, } from "./config/vector-cortex.js";
@@ -0,0 +1,232 @@
1
+ /**
2
+ * vector-cortex/topology/build.ts — deterministic cortical topology builder (VC3B).
3
+ *
4
+ * Implements the deterministic graph construction (tasks 2–4):
5
+ * - For each (source, head) retain only candidates whose score is strictly
6
+ * above the calibrated threshold.
7
+ * - Stable-sort winning candidates by score DESCENDING, then by unsigned
8
+ * target-ID bytes ASCENDING (TOP-TIE-002 — equal scores sort by target ID).
9
+ * - Cap each (source, head) at top-k=16; the seventeenth eligible neighbor is
10
+ * excluded (TOP-K-001).
11
+ * - Remove self edges (source === target); reject them as TOP_SELF_EDGE.
12
+ * - Reject non-finite scores as TOP_SCORE_NONFINITE — a single bad head's NaN
13
+ * rejects only its own edge and never poisons other heads.
14
+ * - Encode dependency edges as single directed records; contradiction edges as
15
+ * symmetric PAIRED records (source→target and target→source) (TOP-KIND-003).
16
+ *
17
+ * This is the mode-A producer in the sprint triad: a multi-head topology index.
18
+ * The other two modes (B linear VectorSet scan, C source-seq/keyword) must yield
19
+ * the same threshold/tie/cap invariants and the same graph digest. Pure
20
+ * deterministic function — no I/O, no console, no network (PREVENT-PI-004),
21
+ * no `any` (PREVENT-011).
22
+ */
23
+ import { TOP_K, } from "./types.js";
24
+ /**
25
+ * Field (`|`) and record (`~`) separators used by the canonical digest framing in
26
+ * index.ts. Id values (source/target/head) carrying either byte would corrupt the
27
+ * framing and make distinct graphs collide on an identical digest, so the build
28
+ * rejects such candidates with TOP_FRAMING_SEP (Q04, mirrors the dashboard's
29
+ * parseCandidatePayload guard) — enforced at this pure seam, not only at one caller.
30
+ */
31
+ const FRAMING_SEP = /[|~]/;
32
+ /**
33
+ * Build the deterministic topology graph from calibrated-threshold candidates.
34
+ * Order-independent across any permutation of `input.candidates`.
35
+ */
36
+ export function buildTopology(input) {
37
+ const { sessionId, sourceHighWater, threshold } = input;
38
+ // Group winning candidates by (source, head), stable-sorting each group by
39
+ // score desc then unsigned target-ID bytes, capping at top-k.
40
+ const byGroup = new Map();
41
+ const rejections = [];
42
+ for (const c of input.candidates) {
43
+ // Q04 — framing hardening: the canonical digest serialization in index.ts uses
44
+ // `|` (FIELD_SEP) and `~` (RECORD_SEP) as unambiguous delimiters. Those are
45
+ // collision-free only while id values (source/target/head) contain neither
46
+ // byte; a content-derived id carrying either would make two distinct graphs
47
+ // hash to an identical digest. Enforce the no-separator-in-id constraint at
48
+ // this pure build seam (not only at the dashboard caller) by rejecting such a
49
+ // candidate in isolation with TOP_FRAMING_SEP — the digest stays well-defined
50
+ // for ANY input.
51
+ if (FRAMING_SEP.test(c.source) || FRAMING_SEP.test(c.target) || FRAMING_SEP.test(c.head)) {
52
+ rejections.push(reject(c, "TOP_FRAMING_SEP"));
53
+ continue;
54
+ }
55
+ // Non-finite score: reject this candidate in isolation (never poison others).
56
+ if (!Number.isFinite(c.score)) {
57
+ rejections.push(reject(c, "TOP_SCORE_NONFINITE"));
58
+ continue;
59
+ }
60
+ if (c.source === c.target) {
61
+ rejections.push(reject(c, "TOP_SELF_EDGE"));
62
+ continue;
63
+ }
64
+ if (c.score <= threshold)
65
+ continue; // below calibrated threshold
66
+ const key = groupKey(c.source, c.head);
67
+ const group = byGroup.get(key);
68
+ if (group)
69
+ group.push(c);
70
+ else
71
+ byGroup.set(key, [c]);
72
+ }
73
+ // Stable sort each (source, head) group: score desc, then unsigned target-ID
74
+ // bytes asc. Keep exactly the top-k=16 (the 17th eligible neighbor is excluded).
75
+ const selected = [];
76
+ for (const group of byGroup.values()) {
77
+ group.sort(compareCandidates);
78
+ for (let i = 0; i < Math.min(group.length, TOP_K); i++) {
79
+ selected.push(group[i]);
80
+ }
81
+ }
82
+ // Encode dependency edges as directed records; contradiction edges as
83
+ // symmetric PAIRED records. Duplicate (source,target,head) contradictions
84
+ // collapse: the same symmetric pair is emitted once per direction — dedupe to
85
+ // keep the paired graph well-formed and the digest stable.
86
+ //
87
+ // IMPORTANT: `selected` is first ordered by a canonical global comparator so
88
+ // every dedup decision (which head represents a collapsed contradiction pair,
89
+ // which identical directed edge is kept) is deterministic and INDEPENDENT of
90
+ // the incoming candidate order. Without this, reversing the input order could
91
+ // flip which head represents a symmetric pair and change the digest.
92
+ //
93
+ // The comparator sorts by SCORE DESCENDING FIRST, so first-writer-wins dedup
94
+ // keeps the MAXIMUM score per collapsed relation. Two candidates emitting the
95
+ // same directed edge (same source,target,head) with different scores keep the
96
+ // higher one; a contradiction pair a↔b with different scores is claimed by the
97
+ // higher-scoring candidate regardless of which end is "source". A downstream
98
+ // consumer (VC3C receives TopologyV1) therefore gets the strongest score for a
99
+ // collapsed relation, never the weakest, and the winner is decided by score —
100
+ // not by source-ID byte order. (Score ties fall through to bytewise keys so
101
+ // the total order stays deterministic.)
102
+ selected.sort(compareSelected);
103
+ const edges = new Map();
104
+ const nodes = new Map();
105
+ for (const c of selected) {
106
+ nodes.set(c.source, nodeKind(c));
107
+ nodes.set(c.target, nodeKind(c));
108
+ if (c.kind === "contradiction") {
109
+ // Symmetric pair: emit source→target and target→source exactly once, keyed
110
+ // so that a reversed duplicate from another candidate collapses to one pair.
111
+ const fwd = pairKey(c.source, c.target);
112
+ const rev = pairKey(c.target, c.source);
113
+ const hasFwd = edges.has(fwd) || edges.has(rev);
114
+ if (!hasFwd) {
115
+ edges.set(fwd, { source: c.source, target: c.target, head: c.head, score: c.score, direction: "contradiction" });
116
+ edges.set(rev, { source: c.target, target: c.source, head: c.head, score: c.score, direction: "contradiction" });
117
+ }
118
+ continue;
119
+ }
120
+ // Directed dependency: distinct per (source, target, head).
121
+ const depKey = dirKey(c.source, c.target, c.head, "dependency");
122
+ if (!edges.has(depKey)) {
123
+ edges.set(depKey, { source: c.source, target: c.target, head: c.head, score: c.score, direction: "dependency" });
124
+ }
125
+ }
126
+ const nodeList = [...nodes.entries()]
127
+ .map(([id, kind]) => ({ id, kind }))
128
+ .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
129
+ const edgeList = [...edges.values()].sort(compareEdges);
130
+ const graph = {
131
+ schema: "topology-v1",
132
+ sessionId,
133
+ sourceHighWater,
134
+ threshold,
135
+ nodeCount: nodeList.length,
136
+ edgeCount: edgeList.length,
137
+ generationDigest: "",
138
+ nodes: nodeList,
139
+ edges: edgeList,
140
+ };
141
+ return { ok: true, topology: graph, rejected: rejections };
142
+ }
143
+ function reject(c, code) {
144
+ return { source: c.source, target: c.target, head: c.head, score: c.score, code };
145
+ }
146
+ function groupKey(source, head) {
147
+ return JSON.stringify([source, head]);
148
+ }
149
+ function pairKey(a, b) {
150
+ return JSON.stringify([a, b, " "]);
151
+ }
152
+ function dirKey(a, b, head, direction) {
153
+ return JSON.stringify([a, b, head, direction]);
154
+ }
155
+ function compareCandidates(a, b) {
156
+ if (a.score !== b.score)
157
+ return a.score > b.score ? -1 : 1;
158
+ // Equal scores: sort by unsigned target-ID bytes ascending (TOP-TIE-002).
159
+ const byTarget = unsignedBytesCompare(a.target, b.target);
160
+ if (byTarget !== 0)
161
+ return byTarget;
162
+ // Equal score + target: break the tie by kind bytes so the within-group sort is
163
+ // a TOTAL order, independent of input order (Q01). Without this, two tied
164
+ // candidates of differing kind that land exactly at the top-k=16 boundary would
165
+ // fall back to JS stable order = candidate input order, flipping which edge
166
+ // survives and changing the graph digest. Mirrors compareSelected's `kind` key.
167
+ return unsignedBytesCompare(a.kind, b.kind);
168
+ }
169
+ /**
170
+ * Total, deterministic order over selected candidates used to drive dedup before
171
+ * encoding. Independent of the incoming input order so a collapsed contradiction
172
+ * pair always picks the same representing head and identical directed edges keep
173
+ * the same winner.
174
+ *
175
+ * SCORE DESCENDING IS THE PRIMARY KEY: first-writer-wins dedup on this order
176
+ * retains the highest score for every collapsed relation (Q01). Only after
177
+ * scores are equal do we fall through to bytewise source/target/head/kind keys,
178
+ * which keeps a sound deterministic tie-break (a score tie collapses to the
179
+ * same representing head regardless of input order).
180
+ */
181
+ function compareSelected(a, b) {
182
+ return ((a.score < b.score ? 1 : a.score > b.score ? -1 : 0) ||
183
+ unsignedBytesCompare(a.source, b.source) ||
184
+ unsignedBytesCompare(a.target, b.target) ||
185
+ unsignedBytesCompare(a.head, b.head) ||
186
+ unsignedBytesCompare(a.kind, b.kind));
187
+ }
188
+ function compareEdges(a, b) {
189
+ return (unsignedBytesCompare(a.source, b.source) ||
190
+ unsignedBytesCompare(a.target, b.target) ||
191
+ unsignedBytesCompare(a.head, b.head) ||
192
+ unsignedBytesCompare(a.direction, b.direction) ||
193
+ (a.score < b.score ? -1 : a.score > b.score ? 1 : 0));
194
+ }
195
+ /**
196
+ * Unsigned bytewise comparison over UTF-8 bytes of two strings. String
197
+ * `<`/`>` in JS is UTF-16 code-unit order, which equals UTF-8 byte order for
198
+ * the ASCII identifiers used (and for our domain); we implement an explicit
199
+ * unsigned-byte comparator so ordering is defined by spec, not JS internals.
200
+ */
201
+ function unsignedBytesCompare(a, b) {
202
+ const ba = Buffer.from(a, "utf8");
203
+ const bb = Buffer.from(b, "utf8");
204
+ const n = Math.min(ba.length, bb.length);
205
+ for (let i = 0; i < n; i++) {
206
+ if (ba[i] !== bb[i])
207
+ return ba[i] < bb[i] ? -1 : 1;
208
+ }
209
+ return ba.length < bb.length ? -1 : ba.length > bb.length ? 1 : 0;
210
+ }
211
+ /**
212
+ * Node kind for a retained edge: a node is marked by the record kind it is
213
+ * derived from. A contradiction candidate marks both endpoints "contradiction";
214
+ * a dependency candidate marks both endpoints "dependency" (Q02) — the node
215
+ * kind matches the producing record kind, never a synthetic placeholder.
216
+ *
217
+ * NODE-KIND SEMANTICS (documented, Q03): a node participates in the kind of
218
+ * whichever retained edge LABELLED it LAST during the linear pass over `selected`.
219
+ * Because `selected` is sorted SCORE-DESCENDING first, the last label a node
220
+ * receives comes from its LOWEST-scoring retained edge — i.e. when a node is
221
+ * touched by both a dependency and a contradiction edge (of equal or lower
222
+ * score), the WEAKEST relation's kind wins the node's `kind` field, not the
223
+ * strongest. This is deliberate and DETERMINISTIC (the total compareSelected
224
+ * order, with the Q01 `kind` tie-break, fixes the pass order independent of
225
+ * input order), and mode B reproduces it exactly. A downstream VC3C consumer
226
+ * must read node.kind as "the relation kind of the weakest retained edge
227
+ * incident to this node", not "the dominant/strongest relation". Per-edge
228
+ * direction + kind are authoritative on the edges themselves.
229
+ */
230
+ function nodeKind(c) {
231
+ return c.kind === "contradiction" ? "contradiction" : "dependency";
232
+ }
@@ -0,0 +1,113 @@
1
+ /**
2
+ * vector-cortex/topology/index.ts — topology barrel + stable graph digest (VC3B).
3
+ *
4
+ * Typical role: a thin barrel + a few derived helpers. The build algorithm lives
5
+ * in build.ts; this file:
6
+ * - re-exports the TopologyV1 / EdgeV1 contracts;
7
+ * - computes ONE deterministic graph digest over the canonical, order-
8
+ * independent serialization of nodes + edges (task 4);
9
+ * - compose `buildTopologyGraph` = build + digest + emit on one seam.
10
+ *
11
+ * Ordinal-order independence: the digest is computed over nodes sorted by id
12
+ * bytes and edges sorted by (source, target, head, direction) then score, so
13
+ * any permutation of the build input yields an identical digest (verified by the
14
+ * acceptance consumer across 1,000 distinct input orderings — Q02).
15
+ *
16
+ * Pure deterministic helpers: no I/O, no console, no network (PREVENT-PI-004),
17
+ * no `any` (PREVENT-011).
18
+ */
19
+ import { createHash } from "node:crypto";
20
+ import { buildTopology } from "./build.js";
21
+ export { TOP_IDS, TOP_NAMED_IDS, TOP_K } from "./types.js";
22
+ export { buildTopology } from "./build.js";
23
+ /**
24
+ * Deterministic topological-construction seam (task 5). Runs the build, fills
25
+ * the stable generationDigest, and optionally emits:
26
+ * - `vector_cortex_topology_built` — once, when a graph is produced;
27
+ * - `vector_cortex_topology_edge_rejected`— once per rejected edge with code.
28
+ * Emission is best-effort and non-fatal (never breaks the agent loop).
29
+ */
30
+ export function buildTopologyGraph(input, emit) {
31
+ const result = buildTopology(input);
32
+ if (!result.ok)
33
+ return result;
34
+ const topology = {
35
+ ...result.topology,
36
+ generationDigest: graphDigest(result.topology),
37
+ };
38
+ const out = { ok: true, topology, rejected: result.rejected };
39
+ if (emit) {
40
+ try {
41
+ emit("vector_cortex_topology_built", {
42
+ sessionId: topology.sessionId,
43
+ sourceHighWater: topology.sourceHighWater.toString(),
44
+ nodeCount: topology.nodeCount,
45
+ edgeCount: topology.edgeCount,
46
+ generationDigest: topology.generationDigest,
47
+ });
48
+ for (const r of result.rejected) {
49
+ emit("vector_cortex_topology_edge_rejected", {
50
+ sessionId: topology.sessionId,
51
+ source: r.source,
52
+ target: r.target,
53
+ head: r.head,
54
+ code: r.code,
55
+ });
56
+ }
57
+ }
58
+ catch {
59
+ /* non-fatal observability — never break the agent loop */
60
+ }
61
+ }
62
+ return out;
63
+ }
64
+ /**
65
+ * ONE deterministic SHA-256 (hex) over the canonical serialization of the graph.
66
+ * Canonical form is a compact stream: `topology-v1|` + sorted nodes + `|` +
67
+ * sorted edges, where nodes are sorted by id bytes and edges by
68
+ * (source, target, head, direction) then score. Order-independence is achieved
69
+ * by that canonical sort, never by input order.
70
+ *
71
+ * Printable framing (no control bytes): FIELD_SEP (`|`) separates fields and
72
+ * RECORD_SEP (`~`) separates records. The project-controlled field values (ids,
73
+ * kinds, heads, directions, scores) contain neither `|` nor `~`, so the framing
74
+ * never collides, and keeping the file control-byte-free lets git treat this
75
+ * core sprint file as text (prevents a spurious "binary file" classification).
76
+ */
77
+ // Printable, unambiguous framing delimiters for the canonical serialization.
78
+ const FIELD_SEP = "|";
79
+ const RECORD_SEP = "~";
80
+ export function graphDigest(topology) {
81
+ const nodes = canonicalNodes(topology.nodes);
82
+ const edges = canonicalEdges(topology.edges);
83
+ const hash = createHash("sha256");
84
+ hash.update(`topology-v1${FIELD_SEP}`);
85
+ hash.update(nodes);
86
+ hash.update(FIELD_SEP);
87
+ hash.update(edges);
88
+ return `sha256:${hash.digest("hex")}`;
89
+ }
90
+ function canonicalNodes(nodes) {
91
+ const sorted = [...nodes]
92
+ .map((n) => `${n.id}${FIELD_SEP}${n.kind}`)
93
+ .sort(unsignedBytesCompare)
94
+ .join(RECORD_SEP);
95
+ return Buffer.from(sorted, "utf8");
96
+ }
97
+ function canonicalEdges(edges) {
98
+ const parts = edges
99
+ .map((e) => `${e.source}${FIELD_SEP}${e.target}${FIELD_SEP}${e.head}${FIELD_SEP}${e.direction}${FIELD_SEP}${e.score}`)
100
+ .sort(unsignedBytesCompare)
101
+ .join(RECORD_SEP);
102
+ return Buffer.from(parts, "utf8");
103
+ }
104
+ function unsignedBytesCompare(a, b) {
105
+ const ba = Buffer.from(a, "utf8");
106
+ const bb = Buffer.from(b, "utf8");
107
+ const n = Math.min(ba.length, bb.length);
108
+ for (let i = 0; i < n; i++) {
109
+ if (ba[i] !== bb[i])
110
+ return ba[i] < bb[i] ? -1 : 1;
111
+ }
112
+ return ba.length < bb.length ? -1 : ba.length > bb.length ? 1 : 0;
113
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * vector-cortex/topology/types.ts — deterministic cortical topology contract (VC3B).
3
+ *
4
+ * Owns `TopologyV1` / `EdgeV1` / `TopologyNodeV1` — the pure graph produced by
5
+ * the deterministic build (build.ts). The build is the mode-A multi-head
6
+ * topology index: for each (source, head) it retains only calibrated-threshold
7
+ * edges, stable-sorts by score descending then unsigned target-ID bytes, and
8
+ * caps each source/head at top-k=16. Dependency edges are directed records;
9
+ * contradiction edges are emitted as symmetric PAIRED records (source→target
10
+ * and target→source) so the encoded graph is directional even though the
11
+ * relation is symmetric.
12
+ *
13
+ * Consumes only reviewer-accepted predecessor contracts (VC3A CortexRecordV1
14
+ * aggregates, VC2B heads) and the [common contracts](../../../../docs/vector-cortex/CONTRACTS.md).
15
+ * Pure types/schema + small predicates: no storage, no console, no network,
16
+ * no side effects (PREVENT-PI-004 / PREVENT-011). The acceptance contract and
17
+ * conformance IDs (TOP-001..020 + named TOP-K/TIE/KIND) live here.
18
+ */
19
+ /**
20
+ * Registered TOP conformance ID range (TOP-001..020). The acceptance test reads
21
+ * these rows from the v2 manifest and asserts each returns its manifest
22
+ * `ok`/code. The three NAMED assertions (TOP-K-001 / TOP-TIE-002 /
23
+ * TOP-KIND-003) live in the acceptance test.
24
+ */
25
+ export const TOP_IDS = [
26
+ "TOP-001",
27
+ "TOP-002",
28
+ "TOP-003",
29
+ "TOP-004",
30
+ "TOP-005",
31
+ "TOP-006",
32
+ "TOP-007",
33
+ "TOP-008",
34
+ "TOP-009",
35
+ "TOP-010",
36
+ "TOP-011",
37
+ "TOP-012",
38
+ "TOP-013",
39
+ "TOP-014",
40
+ "TOP-015",
41
+ "TOP-016",
42
+ "TOP-017",
43
+ "TOP-018",
44
+ "TOP-019",
45
+ "TOP-020",
46
+ ];
47
+ /** Named TOP conformance assertions (spec: TOP-K/TOP-TIE/TOP-KIND). */
48
+ export const TOP_NAMED_IDS = [
49
+ "TOP-K-001",
50
+ "TOP-TIE-002",
51
+ "TOP-KIND-003",
52
+ ];
53
+ /** Deterministic per-source/head edge cap (top-k=16). */
54
+ export const TOP_K = 16;