pi-mega-compact 0.19.1 → 0.19.3

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 (92) hide show
  1. package/dist/config/vector-cortex.js +21 -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-query.js +46 -0
  5. package/dist/extensions/dashboard-server/routes-vector-cortex-topology.js +145 -5
  6. package/dist/extensions/dashboard-server/routes-vector-cortex.js +1 -0
  7. package/dist/extensions/dashboard-server/routes.js +1 -1
  8. package/dist/extensions/dashboard-server/server.js +3 -1
  9. package/dist/src/config/vector-cortex.js +21 -0
  10. package/dist/src/config.js +1 -1
  11. package/dist/src/tieredRouter.js +8 -0
  12. package/dist/src/vector-cortex/migrations/router-generation-v2.js +252 -0
  13. package/dist/src/vector-cortex/topology/build.js +232 -0
  14. package/dist/src/vector-cortex/topology/index.js +113 -0
  15. package/dist/src/vector-cortex/topology/query.js +342 -0
  16. package/dist/src/vector-cortex/topology/types.js +54 -0
  17. package/dist/src/vector-cortex/vc3b-support.js +125 -0
  18. package/dist/vector-cortex/migrations/router-generation-v2.js +252 -0
  19. package/dist/vector-cortex/topology/build.js +232 -0
  20. package/dist/vector-cortex/topology/index.js +113 -0
  21. package/dist/vector-cortex/topology/query.js +342 -0
  22. package/dist/vector-cortex/topology/types.js +54 -0
  23. package/dist/vector-cortex/vc3b-support.js +125 -0
  24. package/extensions/dashboard-client/dist/assets/{AreaChart-B9KYKrUE.js → AreaChart-DqiFSnDx.js} +2 -2
  25. package/extensions/dashboard-client/dist/assets/{AreaChart-B9KYKrUE.js.map → AreaChart-DqiFSnDx.js.map} +1 -1
  26. package/extensions/dashboard-client/dist/assets/{BarChart-D1sWkR6j.js → BarChart-Cqg-PQMK.js} +2 -2
  27. package/extensions/dashboard-client/dist/assets/{BarChart-D1sWkR6j.js.map → BarChart-Cqg-PQMK.js.map} +1 -1
  28. package/extensions/dashboard-client/dist/assets/{CacheTab-BR8MYcJq.js → CacheTab-BPNs0xIF.js} +2 -2
  29. package/extensions/dashboard-client/dist/assets/{CacheTab-BR8MYcJq.js.map → CacheTab-BPNs0xIF.js.map} +1 -1
  30. package/extensions/dashboard-client/dist/assets/{EventsTab-BRNpDMvP.js → EventsTab-BQf7OGkf.js} +2 -2
  31. package/extensions/dashboard-client/dist/assets/{EventsTab-BRNpDMvP.js.map → EventsTab-BQf7OGkf.js.map} +1 -1
  32. package/extensions/dashboard-client/dist/assets/{HealthTab-rr5nXpjq.js → HealthTab-B14TaSPN.js} +2 -2
  33. package/extensions/dashboard-client/dist/assets/{HealthTab-rr5nXpjq.js.map → HealthTab-B14TaSPN.js.map} +1 -1
  34. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-CtjPWnzN.js → MaintenanceTab-D8lkRoa1.js} +2 -2
  35. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-CtjPWnzN.js.map → MaintenanceTab-D8lkRoa1.js.map} +1 -1
  36. package/extensions/dashboard-client/dist/assets/{MemoryMapTab-5SnFDIYc.js → MemoryMapTab-BOWtGfpx.js} +2 -2
  37. package/extensions/dashboard-client/dist/assets/{MemoryMapTab-5SnFDIYc.js.map → MemoryMapTab-BOWtGfpx.js.map} +1 -1
  38. package/extensions/dashboard-client/dist/assets/{MetricsTab-4MZfwRhq.js → MetricsTab-7XI9cWaX.js} +2 -2
  39. package/extensions/dashboard-client/dist/assets/{MetricsTab-4MZfwRhq.js.map → MetricsTab-7XI9cWaX.js.map} +1 -1
  40. package/extensions/dashboard-client/dist/assets/{OverviewTab-BAKENnbk.js → OverviewTab-C9KaGYvh.js} +2 -2
  41. package/extensions/dashboard-client/dist/assets/{OverviewTab-BAKENnbk.js.map → OverviewTab-C9KaGYvh.js.map} +1 -1
  42. package/extensions/dashboard-client/dist/assets/{ReposTab-7-z_OmZo.js → ReposTab-BwESNhox.js} +2 -2
  43. package/extensions/dashboard-client/dist/assets/{ReposTab-7-z_OmZo.js.map → ReposTab-BwESNhox.js.map} +1 -1
  44. package/extensions/dashboard-client/dist/assets/{SessionsTab-D_r2ki0y.js → SessionsTab-DKH55Rda.js} +2 -2
  45. package/extensions/dashboard-client/dist/assets/{SessionsTab-D_r2ki0y.js.map → SessionsTab-DKH55Rda.js.map} +1 -1
  46. package/extensions/dashboard-client/dist/assets/{SetupTab-DPujtYgv.js → SetupTab-zDxf-nJd.js} +2 -2
  47. package/extensions/dashboard-client/dist/assets/{SetupTab-DPujtYgv.js.map → SetupTab-zDxf-nJd.js.map} +1 -1
  48. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-CLHy30t6.js → TimeSavedCard-C9isog4L.js} +2 -2
  49. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-CLHy30t6.js.map → TimeSavedCard-C9isog4L.js.map} +1 -1
  50. package/extensions/dashboard-client/dist/assets/{TurnsTab-Coul6CHc.js → TurnsTab-ciI6ydvj.js} +2 -2
  51. package/extensions/dashboard-client/dist/assets/{TurnsTab-Coul6CHc.js.map → TurnsTab-ciI6ydvj.js.map} +1 -1
  52. package/extensions/dashboard-client/dist/assets/VectorCortexTab-qTZ7NWng.js +2 -0
  53. package/extensions/dashboard-client/dist/assets/VectorCortexTab-qTZ7NWng.js.map +1 -0
  54. package/extensions/dashboard-client/dist/assets/{WikiTab-hryG5oyY.js → WikiTab-DcYHc734.js} +2 -2
  55. package/extensions/dashboard-client/dist/assets/{WikiTab-hryG5oyY.js.map → WikiTab-DcYHc734.js.map} +1 -1
  56. package/extensions/dashboard-client/dist/assets/{button-Dxo95lRI.js → button-DF8lx4bt.js} +2 -2
  57. package/extensions/dashboard-client/dist/assets/{button-Dxo95lRI.js.map → button-DF8lx4bt.js.map} +1 -1
  58. package/extensions/dashboard-client/dist/assets/{card-FXwhLF_u.js → card-DIoDheSZ.js} +2 -2
  59. package/extensions/dashboard-client/dist/assets/{card-FXwhLF_u.js.map → card-DIoDheSZ.js.map} +1 -1
  60. package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-M-GeRM8U.js → generateCategoricalChart-BFRzeYX3.js} +2 -2
  61. package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-M-GeRM8U.js.map → generateCategoricalChart-BFRzeYX3.js.map} +1 -1
  62. package/extensions/dashboard-client/dist/assets/{index-BIZZXvoy.js → index-DSZON0Yi.js} +3 -3
  63. package/extensions/dashboard-client/dist/assets/{index-BIZZXvoy.js.map → index-DSZON0Yi.js.map} +1 -1
  64. package/extensions/dashboard-client/dist/assets/{switch-C-d4tkN1.js → switch-l4qo22mU.js} +2 -2
  65. package/extensions/dashboard-client/dist/assets/{switch-C-d4tkN1.js.map → switch-l4qo22mU.js.map} +1 -1
  66. package/extensions/dashboard-client/dist/assets/{toggle-Bfmucdcl.js → toggle-DPn6td1_.js} +2 -2
  67. package/extensions/dashboard-client/dist/assets/{toggle-Bfmucdcl.js.map → toggle-DPn6td1_.js.map} +1 -1
  68. package/extensions/dashboard-client/dist/assets/{useSSE-CxK_wdmk.js → useSSE-BLmolqTJ.js} +2 -2
  69. package/extensions/dashboard-client/dist/assets/{useSSE-CxK_wdmk.js.map → useSSE-BLmolqTJ.js.map} +1 -1
  70. package/extensions/dashboard-client/dist/index.html +1 -1
  71. package/extensions/dashboard-client/src/api/vector-cortex.ts +9 -0
  72. package/extensions/dashboard-client/src/tabs/VectorCortexTab.tsx +82 -0
  73. package/extensions/dashboard-client/src/types/vector-cortex.ts +25 -0
  74. package/extensions/dashboard-server/api-contracts/vector-cortex.ts +35 -0
  75. package/extensions/dashboard-server/routes-rag-settings-helpers.ts +12 -0
  76. package/extensions/dashboard-server/routes-vector-cortex-query.ts +54 -0
  77. package/extensions/dashboard-server/routes-vector-cortex-topology.ts +166 -5
  78. package/extensions/dashboard-server/routes-vector-cortex.ts +1 -0
  79. package/extensions/dashboard-server/routes.ts +1 -0
  80. package/extensions/dashboard-server/server.ts +2 -0
  81. package/package.json +1 -1
  82. package/src/config/vector-cortex.ts +23 -0
  83. package/src/config.ts +2 -0
  84. package/src/tieredRouter.ts +9 -0
  85. package/src/vector-cortex/migrations/router-generation-v2.ts +317 -0
  86. package/src/vector-cortex/topology/build.ts +259 -0
  87. package/src/vector-cortex/topology/index.ts +143 -0
  88. package/src/vector-cortex/topology/query.ts +485 -0
  89. package/src/vector-cortex/topology/types.ts +156 -0
  90. package/src/vector-cortex/vc3b-support.ts +142 -0
  91. package/extensions/dashboard-client/dist/assets/VectorCortexTab-rqBpWc7A.js +0 -2
  92. package/extensions/dashboard-client/dist/assets/VectorCortexTab-rqBpWc7A.js.map +0 -1
@@ -0,0 +1,317 @@
1
+ /**
2
+ * vector-cortex/migrations/router-generation-v2.ts — M6 copy/validate/switch
3
+ * migration (VC3C).
4
+ *
5
+ * M6 versions the tiered router's query set: the predecessor routed on ad-hoc
6
+ * per-session keys (no generation identity); VC3C routes on the structured,
7
+ * length-delimited `RouterKeyV2`. M6 copies the old per-session query set into
8
+ * v2 `RouterGenV2Row`s BESIDE the legacy state, validates, and only then
9
+ * atomically switches the active version pointer — the same copy/validate/
10
+ * switch + resume contract as M4.
11
+ *
12
+ * - copy: resumable per (session, old key) — an interrupted run resumes
13
+ * without duplicate rows or active-pointer drift.
14
+ * - validate: every old query key has exactly one v2 row, every row's key is
15
+ * canonical + re-hashes, and — the VC3C-specific invariant — the new query
16
+ * set is partition-preserving: a row derived from an old key of session S
17
+ * MUST carry session S. A row whose session differs is rejected as
18
+ * cross-session eviction (`M6_CROSS_SESSION_EVICTION`): one session may
19
+ * never lose or steal another session's query identity.
20
+ * - switch: atomically flips the ACTIVE VERSION pointer from 1 (legacy) to 2
21
+ * (router-generation-v2) only after a verified copy; interruption keeps the
22
+ * old active pointer.
23
+ *
24
+ * Pure logic over an injected M6Host (deterministic + testable; no console).
25
+ * PREVENT-002/011/PI-004 honored.
26
+ */
27
+
28
+ import { createHash } from "node:crypto";
29
+ import {
30
+ encodeRouterKeyV2,
31
+ decodeRouterKeyV2,
32
+ type RouterKeyV2,
33
+ } from "../topology/query.js";
34
+
35
+ /** The active-version value the v2 router generation pointer is switched to. */
36
+ export const ROUTER_GEN_V2_VERSION = 2;
37
+ /** The legacy (predecessor) active-version value before any verified switch. */
38
+ export const ROUTER_GEN_LEGACY_VERSION = 1;
39
+
40
+ /** M6 failure codes. */
41
+ export const M6_FAIL = {
42
+ VERSION_MISMATCH: "M6_VERSION_MISMATCH",
43
+ COPY_PARTIAL: "M6_COPY_PARTIAL",
44
+ COUNT_MISMATCH: "M6_COUNT_MISMATCH",
45
+ DIGEST_MISMATCH: "M6_DIGEST_MISMATCH",
46
+ BAD_OLD_KEY: "M6_BAD_OLD_KEY",
47
+ CROSS_SESSION_EVICTION: "M6_CROSS_SESSION_EVICTION",
48
+ SWITCH_PRECONDITION: "M6_SWITCH_PRECONDITION",
49
+ } as const;
50
+ export type M6MigrationCode = (typeof M6_FAIL)[keyof typeof M6_FAIL];
51
+
52
+ /**
53
+ * A v2 router-generation row derived from one predecessor query key. Identity is
54
+ * exact: `session` + the canonical length-delimited `key` (all five structured
55
+ * fields). `digest` is the authoritative sha256 over the canonical key bytes.
56
+ */
57
+ export interface RouterGenV2Row {
58
+ readonly session: string;
59
+ readonly generation: bigint;
60
+ readonly sourceStart: bigint;
61
+ readonly sourceEnd: bigint;
62
+ readonly algorithm: string;
63
+ /** Canonical `rk2:` hex encoding of the full structured key. */
64
+ readonly key: string;
65
+ /** Authoritative sha256 hex over the canonical key bytes. */
66
+ readonly digest: string;
67
+ }
68
+
69
+ /** The host the migration reads from / writes to (capability-shaped). */
70
+ export interface M6Host {
71
+ /** Every session whose query set is being migrated. */
72
+ readonly sessions: () => readonly string[];
73
+ /** The predecessor (legacy) query keys for one session. */
74
+ readonly oldKeysOf: (session: string) => readonly string[];
75
+ /**
76
+ * Decode one predecessor query key into the structured RouterKeyV2 it maps to,
77
+ * or a `M6_BAD_OLD_KEY` rejection when the legacy key cannot be interpreted.
78
+ */
79
+ readonly parseOldKey: (
80
+ session: string,
81
+ oldKey: string,
82
+ ) => { ok: true; key: RouterKeyV2 } | { ok: false };
83
+ /** Persisted v2 rows already written (for resume + active pointer). */
84
+ readonly existingV2: () => readonly RouterGenV2Row[];
85
+ /** Idempotent write of v2 rows (never mutates legacy rows). */
86
+ readonly putV2: (rows: readonly RouterGenV2Row[]) => void;
87
+ /** The currently ACTIVE version (1 = legacy until a verified switch). */
88
+ readonly activeVersion: () => number;
89
+ /** Atomically switch the active version pointer to 2. */
90
+ readonly switchToV2: () => void;
91
+ }
92
+
93
+ /** An M6 migration validation result. */
94
+ export interface M6ValidateResult {
95
+ readonly ok: boolean;
96
+ readonly codes: readonly M6MigrationCode[];
97
+ }
98
+
99
+ /** The identity of a query-set slot, for copy/resume dedup. */
100
+ interface SlotId {
101
+ readonly session: string;
102
+ readonly oldKey: string;
103
+ }
104
+
105
+ /** Derive one v2 row from an old key (authoritative bytes). */
106
+ export function deriveRouterGenRow(
107
+ host: M6Host,
108
+ session: string,
109
+ oldKey: string,
110
+ ): { ok: true; row: RouterGenV2Row } | { ok: false; session: string; oldKey: string } {
111
+ const parsed = host.parseOldKey(session, oldKey);
112
+ if (!parsed.ok) return { ok: false, session, oldKey };
113
+ const key = parsed.key;
114
+ // Cross-session guard at COPY time: the structured key's session must equal
115
+ // the slot session. A key that claims a different session is never copied.
116
+ if (key.session !== session) return { ok: false, session, oldKey };
117
+ const encoded = encodeRouterKeyV2(key);
118
+ return {
119
+ ok: true,
120
+ row: {
121
+ session,
122
+ generation: key.generation,
123
+ sourceStart: key.sourceStart,
124
+ sourceEnd: key.sourceEnd,
125
+ algorithm: key.algorithm,
126
+ key: encoded,
127
+ digest: sha256Hex(Buffer.from(encoded.slice(4), "hex")),
128
+ },
129
+ };
130
+ }
131
+
132
+ function sha256Hex(bytes: Buffer): string {
133
+ return createHash("sha256").update(bytes).digest("hex");
134
+ }
135
+
136
+ /**
137
+ * Copy the full old query set into v2 rows (resumable): rows already persisted
138
+ * with a matching canonical key + digest are left untouched (no duplicates);
139
+ * absent or corrupt (wrong session / wrong key / stale digest / bad old key)
140
+ * slots are (re)written from the authoritative derivation. Returns the delta
141
+ * written this call. The active pointer stays at the legacy version until a
142
+ * verified switch.
143
+ */
144
+ export function m6Copy(host: M6Host): { readonly written: RouterGenV2Row[]; readonly all: RouterGenV2Row[] } {
145
+ const existing = new Map(host.existingV2().map((r) => [`${r.session}::${r.key}`, r]));
146
+ const wanted: RouterGenV2Row[] = [];
147
+ for (const session of host.sessions()) {
148
+ for (const oldKey of host.oldKeysOf(session)) {
149
+ const derived = deriveRouterGenRow(host, session, oldKey);
150
+ if (!derived.ok) continue; // bad old key surfaced by verify, not lost silently
151
+ const stored = existing.get(`${session}::${derived.row.key}`);
152
+ if (stored !== undefined && rowMatches(stored, derived.row)) continue; // healthy
153
+ wanted.push(derived.row);
154
+ }
155
+ }
156
+ if (wanted.length > 0) host.putV2(wanted);
157
+ return { written: wanted, all: [...host.existingV2()] };
158
+ }
159
+
160
+ /** True when a persisted row already matches the authoritative derivation. */
161
+ function rowMatches(stored: RouterGenV2Row, fresh: RouterGenV2Row): boolean {
162
+ return (
163
+ stored.session === fresh.session &&
164
+ stored.generation === fresh.generation &&
165
+ stored.sourceStart === fresh.sourceStart &&
166
+ stored.sourceEnd === fresh.sourceEnd &&
167
+ stored.algorithm === fresh.algorithm &&
168
+ stored.key === fresh.key &&
169
+ stored.digest === fresh.digest
170
+ );
171
+ }
172
+
173
+ /**
174
+ * Verify the migrated query set: every old query key across every session has a
175
+ * v2 row (exact-once), every row's key is canonical + re-hashes, and the new set
176
+ * is partition-preserving — every row's session is exactly the session of the
177
+ * old key it was derived from (rejects cross-session eviction). Never mutates.
178
+ *
179
+ * Comparison of old/new query sets is exact-by-identity (structured key bytes),
180
+ * never by string prefix.
181
+ */
182
+ export function m6Verify(host: M6Host): M6ValidateResult {
183
+ const codes: M6MigrationCode[] = [];
184
+ const stored = host.existingV2();
185
+
186
+ // Expected slot inventory: (session, canonical key) for every derivable old key.
187
+ const expectedSlots: SlotId[] = [];
188
+ const badOldKeys: SlotId[] = [];
189
+ for (const session of host.sessions()) {
190
+ for (const oldKey of host.oldKeysOf(session)) {
191
+ const parsed = host.parseOldKey(session, oldKey);
192
+ if (!parsed.ok) {
193
+ badOldKeys.push({ session, oldKey });
194
+ continue;
195
+ }
196
+ if (parsed.key.session !== session) {
197
+ // A structured key that claims a different session is a cross-session
198
+ // eviction attempt — never migrated, never evicted.
199
+ codes.push(M6_FAIL.CROSS_SESSION_EVICTION);
200
+ continue;
201
+ }
202
+ expectedSlots.push({ session, oldKey });
203
+ }
204
+ }
205
+ if (badOldKeys.length > 0) codes.push(M6_FAIL.BAD_OLD_KEY);
206
+
207
+ // Map stored rows by their (session,key) identity.
208
+ const byIdentity = new Map<string, RouterGenV2Row>();
209
+ const duplicateCheck = new Map<string, number>();
210
+ for (const r of stored) {
211
+ const ident = `${r.session}::${r.key}`;
212
+ byIdentity.set(ident, r);
213
+ duplicateCheck.set(ident, (duplicateCheck.get(ident) ?? 0) + 1);
214
+ }
215
+
216
+ // Each expected slot must be present exactly once, with a healthy row.
217
+ for (const slot of expectedSlots) {
218
+ const parsed = host.parseOldKey(slot.session, slot.oldKey);
219
+ if (!parsed.ok) continue;
220
+ const expectedKey = encodeRouterKeyV2(parsed.key);
221
+ const ident = `${slot.session}::${expectedKey}`;
222
+ const count = duplicateCheck.get(ident) ?? 0;
223
+ if (count === 0) codes.push(M6_FAIL.COPY_PARTIAL);
224
+ if (count > 1) codes.push(M6_FAIL.COUNT_MISMATCH);
225
+ }
226
+
227
+ // Row health: digest re-hashes + session partition-preserving.
228
+ for (const r of stored) {
229
+ if (!r.key.startsWith("rk2:")) codes.push(M6_FAIL.DIGEST_MISMATCH);
230
+ const expectedDigest = sha256Hex(Buffer.from(r.key.slice(4), "hex"));
231
+ if (r.digest !== expectedDigest) codes.push(M6_FAIL.DIGEST_MISMATCH);
232
+ // The row's own structured key must decode and agree with its declared fields.
233
+ const dec = decodeRow(r);
234
+ if (!dec) codes.push(M6_FAIL.DIGEST_MISMATCH);
235
+ }
236
+
237
+ // No stored row may be an orphan (no corresponding old key anywhere).
238
+ const expectedIdentities = new Set<string>();
239
+ for (const slot of expectedSlots) {
240
+ const parsed = host.parseOldKey(slot.session, slot.oldKey);
241
+ if (!parsed.ok) continue;
242
+ expectedIdentities.add(`${slot.session}::${encodeRouterKeyV2(parsed.key)}`);
243
+ }
244
+ for (const ident of byIdentity.keys()) {
245
+ if (!expectedIdentities.has(ident)) codes.push(M6_FAIL.COUNT_MISMATCH);
246
+ }
247
+
248
+ const ok = codes.length === 0;
249
+ return { ok, codes: dedupe(codes) };
250
+ }
251
+
252
+ /**
253
+ * Self-consistent decode of a stored row: its canonical key decodes to a
254
+ * RouterKeyV2 whose five fields equal the row's declared fields. A row whose key
255
+ * doesn't round-trip against its own declared session/generation/range/algorithm
256
+ * is corrupt (cannot be trusted as the query set's identity).
257
+ */
258
+ function decodeRow(r: RouterGenV2Row): boolean {
259
+ if (!r.key.startsWith("rk2:")) return false;
260
+ const hex = r.key.slice(4);
261
+ if (!/^[0-9a-f]+$/.test(hex) || hex.length % 2 !== 0) return false;
262
+ const dec = decodeRouterKeyV2(r.key);
263
+ if (!dec.ok) return false;
264
+ return (
265
+ dec.key.session === r.session &&
266
+ dec.key.generation === r.generation &&
267
+ dec.key.sourceStart === r.sourceStart &&
268
+ dec.key.sourceEnd === r.sourceEnd &&
269
+ dec.key.algorithm === r.algorithm
270
+ );
271
+ }
272
+
273
+ /**
274
+ * Switch the active version to 2. Only call after `m6Verify` reports ok; a
275
+ * crash/return before switch leaves the legacy pointer active (interruption
276
+ * keeps old authority, resumable idempotently).
277
+ */
278
+ export function m6Switch(host: M6Host): void {
279
+ if (host.activeVersion() !== ROUTER_GEN_LEGACY_VERSION) return;
280
+ host.switchToV2();
281
+ }
282
+
283
+ /** Full M6 lifecycle: copy -> verify -> switch; returns the verify result. */
284
+ export function migrateRouterGenerationV2(host: M6Host): M6ValidateResult {
285
+ m6Copy(host);
286
+ const v = m6Verify(host);
287
+ if (v.ok) m6Switch(host);
288
+ return v;
289
+ }
290
+
291
+ /** Registered M6 conformance ID range (M6-001..012). */
292
+ export const M6_IDS = [
293
+ "M6-001",
294
+ "M6-002",
295
+ "M6-003",
296
+ "M6-004",
297
+ "M6-005",
298
+ "M6-006",
299
+ "M6-007",
300
+ "M6-008",
301
+ "M6-009",
302
+ "M6-010",
303
+ "M6-011",
304
+ "M6-012",
305
+ ] as const;
306
+
307
+ /** Registered named M6 conformance IDs. */
308
+ export const M6_NAMED_IDS = [
309
+ "M6-KEY-001",
310
+ "M6-STALE-002",
311
+ ] as const;
312
+
313
+ function dedupe(codes: readonly M6MigrationCode[]): M6MigrationCode[] {
314
+ const out: M6MigrationCode[] = [];
315
+ for (const c of codes) if (!out.includes(c)) out.push(c);
316
+ return out;
317
+ }
@@ -0,0 +1,259 @@
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 {
24
+ TOP_K,
25
+ type TopologyBuildResult,
26
+ type TopologyCandidate,
27
+ type TopologyEdgeV1,
28
+ type TopologyInput,
29
+ type TopologyNodeV1,
30
+ type TopologyRejection,
31
+ type TopologyV1,
32
+ } from "./types.js";
33
+
34
+ /**
35
+ * Field (`|`) and record (`~`) separators used by the canonical digest framing in
36
+ * index.ts. Id values (source/target/head) carrying either byte would corrupt the
37
+ * framing and make distinct graphs collide on an identical digest, so the build
38
+ * rejects such candidates with TOP_FRAMING_SEP (Q04, mirrors the dashboard's
39
+ * parseCandidatePayload guard) — enforced at this pure seam, not only at one caller.
40
+ */
41
+ const FRAMING_SEP = /[|~]/;
42
+
43
+ /**
44
+ * Build the deterministic topology graph from calibrated-threshold candidates.
45
+ * Order-independent across any permutation of `input.candidates`.
46
+ */
47
+ export function buildTopology(input: TopologyInput): TopologyBuildResult {
48
+ const { sessionId, sourceHighWater, threshold } = input;
49
+
50
+ // Group winning candidates by (source, head), stable-sorting each group by
51
+ // score desc then unsigned target-ID bytes, capping at top-k.
52
+ const byGroup = new Map<string, TopologyCandidate[]>();
53
+ const rejections: TopologyRejection[] = [];
54
+
55
+ for (const c of input.candidates) {
56
+ // Q04 — framing hardening: the canonical digest serialization in index.ts uses
57
+ // `|` (FIELD_SEP) and `~` (RECORD_SEP) as unambiguous delimiters. Those are
58
+ // collision-free only while id values (source/target/head) contain neither
59
+ // byte; a content-derived id carrying either would make two distinct graphs
60
+ // hash to an identical digest. Enforce the no-separator-in-id constraint at
61
+ // this pure build seam (not only at the dashboard caller) by rejecting such a
62
+ // candidate in isolation with TOP_FRAMING_SEP — the digest stays well-defined
63
+ // for ANY input.
64
+ if (FRAMING_SEP.test(c.source) || FRAMING_SEP.test(c.target) || FRAMING_SEP.test(c.head)) {
65
+ rejections.push(reject(c, "TOP_FRAMING_SEP"));
66
+ continue;
67
+ }
68
+ // Non-finite score: reject this candidate in isolation (never poison others).
69
+ if (!Number.isFinite(c.score)) {
70
+ rejections.push(reject(c, "TOP_SCORE_NONFINITE"));
71
+ continue;
72
+ }
73
+ if (c.source === c.target) {
74
+ rejections.push(reject(c, "TOP_SELF_EDGE"));
75
+ continue;
76
+ }
77
+ if (c.score <= threshold) continue; // below calibrated threshold
78
+ const key = groupKey(c.source, c.head);
79
+ const group = byGroup.get(key);
80
+ if (group) group.push(c);
81
+ else byGroup.set(key, [c]);
82
+ }
83
+
84
+ // Stable sort each (source, head) group: score desc, then unsigned target-ID
85
+ // bytes asc. Keep exactly the top-k=16 (the 17th eligible neighbor is excluded).
86
+ const selected: TopologyCandidate[] = [];
87
+ for (const group of byGroup.values()) {
88
+ group.sort(compareCandidates);
89
+ for (let i = 0; i < Math.min(group.length, TOP_K); i++) {
90
+ selected.push(group[i]);
91
+ }
92
+ }
93
+
94
+ // Encode dependency edges as directed records; contradiction edges as
95
+ // symmetric PAIRED records. Duplicate (source,target,head) contradictions
96
+ // collapse: the same symmetric pair is emitted once per direction — dedupe to
97
+ // keep the paired graph well-formed and the digest stable.
98
+ //
99
+ // IMPORTANT: `selected` is first ordered by a canonical global comparator so
100
+ // every dedup decision (which head represents a collapsed contradiction pair,
101
+ // which identical directed edge is kept) is deterministic and INDEPENDENT of
102
+ // the incoming candidate order. Without this, reversing the input order could
103
+ // flip which head represents a symmetric pair and change the digest.
104
+ //
105
+ // The comparator sorts by SCORE DESCENDING FIRST, so first-writer-wins dedup
106
+ // keeps the MAXIMUM score per collapsed relation. Two candidates emitting the
107
+ // same directed edge (same source,target,head) with different scores keep the
108
+ // higher one; a contradiction pair a↔b with different scores is claimed by the
109
+ // higher-scoring candidate regardless of which end is "source". A downstream
110
+ // consumer (VC3C receives TopologyV1) therefore gets the strongest score for a
111
+ // collapsed relation, never the weakest, and the winner is decided by score —
112
+ // not by source-ID byte order. (Score ties fall through to bytewise keys so
113
+ // the total order stays deterministic.)
114
+ selected.sort(compareSelected);
115
+ const edges: Map<string, TopologyEdgeV1> = new Map();
116
+ const nodes = new Map<string, TopologyNodeKind>();
117
+ for (const c of selected) {
118
+ nodes.set(c.source, nodeKind(c));
119
+ nodes.set(c.target, nodeKind(c));
120
+ if (c.kind === "contradiction") {
121
+ // Symmetric pair: emit source→target and target→source exactly once, keyed
122
+ // so that a reversed duplicate from another candidate collapses to one pair.
123
+ const fwd = pairKey(c.source, c.target);
124
+ const rev = pairKey(c.target, c.source);
125
+ const hasFwd = edges.has(fwd) || edges.has(rev);
126
+ if (!hasFwd) {
127
+ edges.set(fwd, { source: c.source, target: c.target, head: c.head, score: c.score, direction: "contradiction" });
128
+ edges.set(rev, { source: c.target, target: c.source, head: c.head, score: c.score, direction: "contradiction" });
129
+ }
130
+ continue;
131
+ }
132
+ // Directed dependency: distinct per (source, target, head).
133
+ const depKey = dirKey(c.source, c.target, c.head, "dependency");
134
+ if (!edges.has(depKey)) {
135
+ edges.set(depKey, { source: c.source, target: c.target, head: c.head, score: c.score, direction: "dependency" });
136
+ }
137
+ }
138
+
139
+ const nodeList: TopologyNodeV1[] = [...nodes.entries()]
140
+ .map(([id, kind]) => ({ id, kind }))
141
+ .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
142
+ const edgeList = [...edges.values()].sort(compareEdges);
143
+
144
+ const graph: TopologyV1 = {
145
+ schema: "topology-v1",
146
+ sessionId,
147
+ sourceHighWater,
148
+ threshold,
149
+ nodeCount: nodeList.length,
150
+ edgeCount: edgeList.length,
151
+ generationDigest: "",
152
+ nodes: nodeList,
153
+ edges: edgeList,
154
+ };
155
+
156
+ return { ok: true, topology: graph, rejected: rejections };
157
+ }
158
+
159
+ function reject(c: TopologyCandidate, code: TopologyRejection["code"]): TopologyRejection {
160
+ return { source: c.source, target: c.target, head: c.head, score: c.score, code };
161
+ }
162
+
163
+ function groupKey(source: string, head: string): string {
164
+ return JSON.stringify([source, head]);
165
+ }
166
+
167
+ function pairKey(a: string, b: string): string {
168
+ return JSON.stringify([a, b, " "]);
169
+ }
170
+
171
+ function dirKey(a: string, b: string, head: string, direction: string): string {
172
+ return JSON.stringify([a, b, head, direction]);
173
+ }
174
+
175
+ function compareCandidates(a: TopologyCandidate, b: TopologyCandidate): number {
176
+ if (a.score !== b.score) return a.score > b.score ? -1 : 1;
177
+ // Equal scores: sort by unsigned target-ID bytes ascending (TOP-TIE-002).
178
+ const byTarget = unsignedBytesCompare(a.target, b.target);
179
+ if (byTarget !== 0) return byTarget;
180
+ // Equal score + target: break the tie by kind bytes so the within-group sort is
181
+ // a TOTAL order, independent of input order (Q01). Without this, two tied
182
+ // candidates of differing kind that land exactly at the top-k=16 boundary would
183
+ // fall back to JS stable order = candidate input order, flipping which edge
184
+ // survives and changing the graph digest. Mirrors compareSelected's `kind` key.
185
+ return unsignedBytesCompare(a.kind, b.kind);
186
+ }
187
+
188
+ /**
189
+ * Total, deterministic order over selected candidates used to drive dedup before
190
+ * encoding. Independent of the incoming input order so a collapsed contradiction
191
+ * pair always picks the same representing head and identical directed edges keep
192
+ * the same winner.
193
+ *
194
+ * SCORE DESCENDING IS THE PRIMARY KEY: first-writer-wins dedup on this order
195
+ * retains the highest score for every collapsed relation (Q01). Only after
196
+ * scores are equal do we fall through to bytewise source/target/head/kind keys,
197
+ * which keeps a sound deterministic tie-break (a score tie collapses to the
198
+ * same representing head regardless of input order).
199
+ */
200
+ function compareSelected(a: TopologyCandidate, b: TopologyCandidate): number {
201
+ return (
202
+ (a.score < b.score ? 1 : a.score > b.score ? -1 : 0) ||
203
+ unsignedBytesCompare(a.source, b.source) ||
204
+ unsignedBytesCompare(a.target, b.target) ||
205
+ unsignedBytesCompare(a.head, b.head) ||
206
+ unsignedBytesCompare(a.kind, b.kind)
207
+ );
208
+ }
209
+
210
+ function compareEdges(a: TopologyEdgeV1, b: TopologyEdgeV1): number {
211
+ return (
212
+ unsignedBytesCompare(a.source, b.source) ||
213
+ unsignedBytesCompare(a.target, b.target) ||
214
+ unsignedBytesCompare(a.head, b.head) ||
215
+ unsignedBytesCompare(a.direction, b.direction) ||
216
+ (a.score < b.score ? -1 : a.score > b.score ? 1 : 0)
217
+ );
218
+ }
219
+
220
+ /**
221
+ * Unsigned bytewise comparison over UTF-8 bytes of two strings. String
222
+ * `<`/`>` in JS is UTF-16 code-unit order, which equals UTF-8 byte order for
223
+ * the ASCII identifiers used (and for our domain); we implement an explicit
224
+ * unsigned-byte comparator so ordering is defined by spec, not JS internals.
225
+ */
226
+ function unsignedBytesCompare(a: string, b: string): number {
227
+ const ba = Buffer.from(a, "utf8");
228
+ const bb = Buffer.from(b, "utf8");
229
+ const n = Math.min(ba.length, bb.length);
230
+ for (let i = 0; i < n; i++) {
231
+ if (ba[i] !== bb[i]) return ba[i] < bb[i] ? -1 : 1;
232
+ }
233
+ return ba.length < bb.length ? -1 : ba.length > bb.length ? 1 : 0;
234
+ }
235
+
236
+ /**
237
+ * Node kind for a retained edge: a node is marked by the record kind it is
238
+ * derived from. A contradiction candidate marks both endpoints "contradiction";
239
+ * a dependency candidate marks both endpoints "dependency" (Q02) — the node
240
+ * kind matches the producing record kind, never a synthetic placeholder.
241
+ *
242
+ * NODE-KIND SEMANTICS (documented, Q03): a node participates in the kind of
243
+ * whichever retained edge LABELLED it LAST during the linear pass over `selected`.
244
+ * Because `selected` is sorted SCORE-DESCENDING first, the last label a node
245
+ * receives comes from its LOWEST-scoring retained edge — i.e. when a node is
246
+ * touched by both a dependency and a contradiction edge (of equal or lower
247
+ * score), the WEAKEST relation's kind wins the node's `kind` field, not the
248
+ * strongest. This is deliberate and DETERMINISTIC (the total compareSelected
249
+ * order, with the Q01 `kind` tie-break, fixes the pass order independent of
250
+ * input order), and mode B reproduces it exactly. A downstream VC3C consumer
251
+ * must read node.kind as "the relation kind of the weakest retained edge
252
+ * incident to this node", not "the dominant/strongest relation". Per-edge
253
+ * direction + kind are authoritative on the edges themselves.
254
+ */
255
+ function nodeKind(c: TopologyCandidate): TopologyNodeKind {
256
+ return c.kind === "contradiction" ? "contradiction" : "dependency";
257
+ }
258
+
259
+ type TopologyNodeKind = "semantic" | "dependency" | "contradiction" | "synthetic";