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,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;
@@ -0,0 +1,125 @@
1
+ /**
2
+ * vector-cortex/vc3b-support.ts — VC3B acceptance test support (mode-B reference
3
+ * scan + shared helper producers).
4
+ *
5
+ * Exact-algorithm sibling to the acceptance aggregator (vc3b-acceptance.test.ts).
6
+ * Splitting the mode-B linear VectorSet scan into its own file keeps the
7
+ * aggregator under its headroom limits (Q03) while preserving the forced-triad
8
+ * A/B digest agreement check: build.ts is mode A (multi-head index), this
9
+ * linear scan is mode B (same thresholds/cap/encoding), and they must agree on
10
+ * the graph digest for the same eligible candidate set.
11
+ *
12
+ * The scan mirrors build.ts semantics deliberately — including keeping the
13
+ * MAXIMUM score across a collapsed relation (contradiction pair or duplicate
14
+ * directed edge) so a real calibrated-threshold builder and the reference scan
15
+ * agree even when duplicate candidates carry different scores (Q01).
16
+ *
17
+ * Test-support only: no production code imports this module, no console, no
18
+ * network (PREVENT-PI-004), no `any` (PREVENT-011).
19
+ */
20
+ import { graphDigest, TOP_K } from "./topology/index.js";
21
+ export function candidates(rows) {
22
+ return rows.map(([source, target, head, score, kind]) => ({
23
+ source,
24
+ target,
25
+ head,
26
+ score,
27
+ kind,
28
+ }));
29
+ }
30
+ /**
31
+ * Reference mode-B linear VectorSet scan: same calibrated threshold and cap as
32
+ * THE documented builder. For each (source, head) it scans ALL records, keeps
33
+ * those strictly above threshold, sorts by score descending then target bytes,
34
+ * keeps the top-k, and encodes dependency/contradiction directions. It is a
35
+ * separate linear implementation from build.ts's grouped byGroup path, so the
36
+ * two independent implementations must agree on the digest.
37
+ */
38
+ export function linearScan(input) {
39
+ const groups = new Map();
40
+ for (const c of input.candidates) {
41
+ if (!Number.isFinite(c.score))
42
+ continue;
43
+ if (c.source === c.target)
44
+ continue;
45
+ if (c.score <= input.threshold)
46
+ continue;
47
+ const key = `${c.source}::${c.head}`;
48
+ const g = groups.get(key);
49
+ if (g)
50
+ g.push(c);
51
+ else
52
+ groups.set(key, [c]);
53
+ }
54
+ const selected = [];
55
+ for (const g of groups.values()) {
56
+ g.sort((x, y) => x.score !== y.score ? (x.score > y.score ? -1 : 1) :
57
+ x.target < y.target ? -1 : x.target > y.target ? 1 :
58
+ // Equal score + target: break the tie by kind bytes so the within-group sort
59
+ // is a TOTAL order independent of input order (Q01) — mirrors build.ts's
60
+ // compareCandidates and keeps the A/B reference-faithfulness claim at the
61
+ // top-k boundary.
62
+ x.kind < y.kind ? -1 : x.kind > y.kind ? 1 : 0);
63
+ for (let i = 0; i < Math.min(g.length, TOP_K); i++)
64
+ selected.push(g[i]);
65
+ }
66
+ // Sort score DESCENDING first so dedup keeps the MAXIMUM score per collapsed
67
+ // relation, mirroring build.ts (Q01). Score ties fall through to bytewise
68
+ // source/target/head/kind keys — INCLUDING `kind` as the final tie-break — so
69
+ // the total order is exactly compareSelected in build.ts (mode A). Without the
70
+ // `kind` tie-break, two equal-(score,source,target,head) candidates of
71
+ // differing kind would fall back to stable input order, which depends on input
72
+ // ordering: the deterministic last-writer for a node's kind (and hence the
73
+ // graph digest) would diverge from mode A whenever such a pair produces the
74
+ // node-kind map entry. Adding `kind` keeps mode B reference-faithful to mode A
75
+ // (Q01: 'contradiction' sorts before 'dependency', bytewise).
76
+ selected.sort((x, y) => x.score !== y.score ? (x.score > y.score ? -1 : 1) :
77
+ x.source < y.source ? -1 : x.source > y.source ? 1 :
78
+ x.target < y.target ? -1 : x.target > y.target ? 1 :
79
+ x.head < y.head ? -1 : x.head > y.head ? 1 :
80
+ x.kind < y.kind ? -1 : x.kind > y.kind ? 1 : 0);
81
+ const nodes = new Map();
82
+ const edges = [];
83
+ const seen = new Set();
84
+ for (const c of selected) {
85
+ const kind = c.kind === "contradiction" ? "contradiction" : "dependency";
86
+ nodes.set(c.source, kind);
87
+ nodes.set(c.target, kind);
88
+ if (c.kind === "contradiction") {
89
+ const fwd = `${c.source}::${c.target}`;
90
+ const rev = `${c.target}::${c.source}`;
91
+ if (!seen.has(fwd) && !seen.has(rev)) {
92
+ seen.add(fwd);
93
+ seen.add(rev);
94
+ edges.push({ source: c.source, target: c.target, head: c.head, score: c.score, direction: "contradiction" });
95
+ edges.push({ source: c.target, target: c.source, head: c.head, score: c.score, direction: "contradiction" });
96
+ }
97
+ continue;
98
+ }
99
+ const depKey = `${c.source}::${c.target}::${c.head}::dependency`;
100
+ if (!seen.has(depKey)) {
101
+ seen.add(depKey);
102
+ edges.push({ source: c.source, target: c.target, head: c.head, score: c.score, direction: "dependency" });
103
+ }
104
+ }
105
+ const nodeList = [...nodes.entries()]
106
+ .map(([id, kind]) => ({ id, kind }))
107
+ .sort((x, y) => (x.id < y.id ? -1 : x.id > y.id ? 1 : 0));
108
+ const edgeList = [...edges].sort((x, y) => x.source < y.source ? -1 : x.source > y.source ? 1 :
109
+ x.target < y.target ? -1 : x.target > y.target ? 1 :
110
+ x.head < y.head ? -1 : x.head > y.head ? 1 :
111
+ x.direction < y.direction ? -1 : x.direction > y.direction ? 1 :
112
+ x.score < y.score ? -1 : x.score > y.score ? 1 : 0);
113
+ const digest = graphDigest({
114
+ schema: "topology-v1",
115
+ sessionId: input.sessionId,
116
+ sourceHighWater: input.sourceHighWater,
117
+ threshold: input.threshold,
118
+ nodeCount: nodeList.length,
119
+ edgeCount: edgeList.length,
120
+ generationDigest: "",
121
+ nodes: nodeList,
122
+ edges: edgeList,
123
+ });
124
+ return { nodes: nodeList, edges: edgeList, digest };
125
+ }
@@ -0,0 +1,252 @@
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
+ import { createHash } from "node:crypto";
28
+ import { encodeRouterKeyV2, decodeRouterKeyV2, } from "../topology/query.js";
29
+ /** The active-version value the v2 router generation pointer is switched to. */
30
+ export const ROUTER_GEN_V2_VERSION = 2;
31
+ /** The legacy (predecessor) active-version value before any verified switch. */
32
+ export const ROUTER_GEN_LEGACY_VERSION = 1;
33
+ /** M6 failure codes. */
34
+ export const M6_FAIL = {
35
+ VERSION_MISMATCH: "M6_VERSION_MISMATCH",
36
+ COPY_PARTIAL: "M6_COPY_PARTIAL",
37
+ COUNT_MISMATCH: "M6_COUNT_MISMATCH",
38
+ DIGEST_MISMATCH: "M6_DIGEST_MISMATCH",
39
+ BAD_OLD_KEY: "M6_BAD_OLD_KEY",
40
+ CROSS_SESSION_EVICTION: "M6_CROSS_SESSION_EVICTION",
41
+ SWITCH_PRECONDITION: "M6_SWITCH_PRECONDITION",
42
+ };
43
+ /** Derive one v2 row from an old key (authoritative bytes). */
44
+ export function deriveRouterGenRow(host, session, oldKey) {
45
+ const parsed = host.parseOldKey(session, oldKey);
46
+ if (!parsed.ok)
47
+ return { ok: false, session, oldKey };
48
+ const key = parsed.key;
49
+ // Cross-session guard at COPY time: the structured key's session must equal
50
+ // the slot session. A key that claims a different session is never copied.
51
+ if (key.session !== session)
52
+ return { ok: false, session, oldKey };
53
+ const encoded = encodeRouterKeyV2(key);
54
+ return {
55
+ ok: true,
56
+ row: {
57
+ session,
58
+ generation: key.generation,
59
+ sourceStart: key.sourceStart,
60
+ sourceEnd: key.sourceEnd,
61
+ algorithm: key.algorithm,
62
+ key: encoded,
63
+ digest: sha256Hex(Buffer.from(encoded.slice(4), "hex")),
64
+ },
65
+ };
66
+ }
67
+ function sha256Hex(bytes) {
68
+ return createHash("sha256").update(bytes).digest("hex");
69
+ }
70
+ /**
71
+ * Copy the full old query set into v2 rows (resumable): rows already persisted
72
+ * with a matching canonical key + digest are left untouched (no duplicates);
73
+ * absent or corrupt (wrong session / wrong key / stale digest / bad old key)
74
+ * slots are (re)written from the authoritative derivation. Returns the delta
75
+ * written this call. The active pointer stays at the legacy version until a
76
+ * verified switch.
77
+ */
78
+ export function m6Copy(host) {
79
+ const existing = new Map(host.existingV2().map((r) => [`${r.session}::${r.key}`, r]));
80
+ const wanted = [];
81
+ for (const session of host.sessions()) {
82
+ for (const oldKey of host.oldKeysOf(session)) {
83
+ const derived = deriveRouterGenRow(host, session, oldKey);
84
+ if (!derived.ok)
85
+ continue; // bad old key surfaced by verify, not lost silently
86
+ const stored = existing.get(`${session}::${derived.row.key}`);
87
+ if (stored !== undefined && rowMatches(stored, derived.row))
88
+ continue; // healthy
89
+ wanted.push(derived.row);
90
+ }
91
+ }
92
+ if (wanted.length > 0)
93
+ host.putV2(wanted);
94
+ return { written: wanted, all: [...host.existingV2()] };
95
+ }
96
+ /** True when a persisted row already matches the authoritative derivation. */
97
+ function rowMatches(stored, fresh) {
98
+ return (stored.session === fresh.session &&
99
+ stored.generation === fresh.generation &&
100
+ stored.sourceStart === fresh.sourceStart &&
101
+ stored.sourceEnd === fresh.sourceEnd &&
102
+ stored.algorithm === fresh.algorithm &&
103
+ stored.key === fresh.key &&
104
+ stored.digest === fresh.digest);
105
+ }
106
+ /**
107
+ * Verify the migrated query set: every old query key across every session has a
108
+ * v2 row (exact-once), every row's key is canonical + re-hashes, and the new set
109
+ * is partition-preserving — every row's session is exactly the session of the
110
+ * old key it was derived from (rejects cross-session eviction). Never mutates.
111
+ *
112
+ * Comparison of old/new query sets is exact-by-identity (structured key bytes),
113
+ * never by string prefix.
114
+ */
115
+ export function m6Verify(host) {
116
+ const codes = [];
117
+ const stored = host.existingV2();
118
+ // Expected slot inventory: (session, canonical key) for every derivable old key.
119
+ const expectedSlots = [];
120
+ const badOldKeys = [];
121
+ for (const session of host.sessions()) {
122
+ for (const oldKey of host.oldKeysOf(session)) {
123
+ const parsed = host.parseOldKey(session, oldKey);
124
+ if (!parsed.ok) {
125
+ badOldKeys.push({ session, oldKey });
126
+ continue;
127
+ }
128
+ if (parsed.key.session !== session) {
129
+ // A structured key that claims a different session is a cross-session
130
+ // eviction attempt — never migrated, never evicted.
131
+ codes.push(M6_FAIL.CROSS_SESSION_EVICTION);
132
+ continue;
133
+ }
134
+ expectedSlots.push({ session, oldKey });
135
+ }
136
+ }
137
+ if (badOldKeys.length > 0)
138
+ codes.push(M6_FAIL.BAD_OLD_KEY);
139
+ // Map stored rows by their (session,key) identity.
140
+ const byIdentity = new Map();
141
+ const duplicateCheck = new Map();
142
+ for (const r of stored) {
143
+ const ident = `${r.session}::${r.key}`;
144
+ byIdentity.set(ident, r);
145
+ duplicateCheck.set(ident, (duplicateCheck.get(ident) ?? 0) + 1);
146
+ }
147
+ // Each expected slot must be present exactly once, with a healthy row.
148
+ for (const slot of expectedSlots) {
149
+ const parsed = host.parseOldKey(slot.session, slot.oldKey);
150
+ if (!parsed.ok)
151
+ continue;
152
+ const expectedKey = encodeRouterKeyV2(parsed.key);
153
+ const ident = `${slot.session}::${expectedKey}`;
154
+ const count = duplicateCheck.get(ident) ?? 0;
155
+ if (count === 0)
156
+ codes.push(M6_FAIL.COPY_PARTIAL);
157
+ if (count > 1)
158
+ codes.push(M6_FAIL.COUNT_MISMATCH);
159
+ }
160
+ // Row health: digest re-hashes + session partition-preserving.
161
+ for (const r of stored) {
162
+ if (!r.key.startsWith("rk2:"))
163
+ codes.push(M6_FAIL.DIGEST_MISMATCH);
164
+ const expectedDigest = sha256Hex(Buffer.from(r.key.slice(4), "hex"));
165
+ if (r.digest !== expectedDigest)
166
+ codes.push(M6_FAIL.DIGEST_MISMATCH);
167
+ // The row's own structured key must decode and agree with its declared fields.
168
+ const dec = decodeRow(r);
169
+ if (!dec)
170
+ codes.push(M6_FAIL.DIGEST_MISMATCH);
171
+ }
172
+ // No stored row may be an orphan (no corresponding old key anywhere).
173
+ const expectedIdentities = new Set();
174
+ for (const slot of expectedSlots) {
175
+ const parsed = host.parseOldKey(slot.session, slot.oldKey);
176
+ if (!parsed.ok)
177
+ continue;
178
+ expectedIdentities.add(`${slot.session}::${encodeRouterKeyV2(parsed.key)}`);
179
+ }
180
+ for (const ident of byIdentity.keys()) {
181
+ if (!expectedIdentities.has(ident))
182
+ codes.push(M6_FAIL.COUNT_MISMATCH);
183
+ }
184
+ const ok = codes.length === 0;
185
+ return { ok, codes: dedupe(codes) };
186
+ }
187
+ /**
188
+ * Self-consistent decode of a stored row: its canonical key decodes to a
189
+ * RouterKeyV2 whose five fields equal the row's declared fields. A row whose key
190
+ * doesn't round-trip against its own declared session/generation/range/algorithm
191
+ * is corrupt (cannot be trusted as the query set's identity).
192
+ */
193
+ function decodeRow(r) {
194
+ if (!r.key.startsWith("rk2:"))
195
+ return false;
196
+ const hex = r.key.slice(4);
197
+ if (!/^[0-9a-f]+$/.test(hex) || hex.length % 2 !== 0)
198
+ return false;
199
+ const dec = decodeRouterKeyV2(r.key);
200
+ if (!dec.ok)
201
+ return false;
202
+ return (dec.key.session === r.session &&
203
+ dec.key.generation === r.generation &&
204
+ dec.key.sourceStart === r.sourceStart &&
205
+ dec.key.sourceEnd === r.sourceEnd &&
206
+ dec.key.algorithm === r.algorithm);
207
+ }
208
+ /**
209
+ * Switch the active version to 2. Only call after `m6Verify` reports ok; a
210
+ * crash/return before switch leaves the legacy pointer active (interruption
211
+ * keeps old authority, resumable idempotently).
212
+ */
213
+ export function m6Switch(host) {
214
+ if (host.activeVersion() !== ROUTER_GEN_LEGACY_VERSION)
215
+ return;
216
+ host.switchToV2();
217
+ }
218
+ /** Full M6 lifecycle: copy -> verify -> switch; returns the verify result. */
219
+ export function migrateRouterGenerationV2(host) {
220
+ m6Copy(host);
221
+ const v = m6Verify(host);
222
+ if (v.ok)
223
+ m6Switch(host);
224
+ return v;
225
+ }
226
+ /** Registered M6 conformance ID range (M6-001..012). */
227
+ export const M6_IDS = [
228
+ "M6-001",
229
+ "M6-002",
230
+ "M6-003",
231
+ "M6-004",
232
+ "M6-005",
233
+ "M6-006",
234
+ "M6-007",
235
+ "M6-008",
236
+ "M6-009",
237
+ "M6-010",
238
+ "M6-011",
239
+ "M6-012",
240
+ ];
241
+ /** Registered named M6 conformance IDs. */
242
+ export const M6_NAMED_IDS = [
243
+ "M6-KEY-001",
244
+ "M6-STALE-002",
245
+ ];
246
+ function dedupe(codes) {
247
+ const out = [];
248
+ for (const c of codes)
249
+ if (!out.includes(c))
250
+ out.push(c);
251
+ return out;
252
+ }
@@ -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
+ }