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,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,342 @@
1
+ /**
2
+ * vector-cortex/topology/query.ts — topology query + router invalidation (VC3C).
3
+ *
4
+ * Owns `RouterKeyV2` (the structured router key) and `TopologyQueryV1` (the
5
+ * generation query/index surface that serves graphs and invalidates stale
6
+ * generations). This is the degradation seam of the sprint's failure triad:
7
+ *
8
+ * A = topology index at current generation (serve the active graph);
9
+ * B = fresh linear scan forced when a key targets a STALE generation;
10
+ * C = authority sequence scan forced when the derived store is unavailable.
11
+ *
12
+ * Key encoding is length-delimited with unsigned-byte (prefix) ordering and a
13
+ * FIXED five-field arity, so no field value can ambiguously prefix another and
14
+ * two sessions `a` / `aa` can never prefix-collide at the key level
15
+ * (M6-KEY-001). Invalidation matches the exact `(session,generation)` identity
16
+ * bytes — never a string-prefix — and a query whose key carries a generation
17
+ * older than the session's active one is rejected with `TOP_GENERATION_STALE`
18
+ * (M6-STALE-002), which forces mode B.
19
+ *
20
+ * Pure src/ logic over an injected `TopologyQueryHost` (the source of graphs +
21
+ * linear/authority scans) and an optional `TopologyQueryEmit`. Deterministic,
22
+ * pi-agnostic, no console, no network (PREVENT-PI-004), no `any`
23
+ * (PREVENT-011). The caller owns durability; every store write on the caller
24
+ * side is best-effort and never breaks the agent loop.
25
+ */
26
+ import { createHash } from "node:crypto";
27
+ /** Query rejected: the key's generation is stale relative to the active one. */
28
+ export const TOP_GENERATION_STALE = "TOP_GENERATION_STALE";
29
+ /** Query rejected: a key could not be decoded (malformed length-delimited bytes). */
30
+ export const TOP_KEY_DECODE_FAILED = "TOP_KEY_DECODE_FAILED";
31
+ /** Query rejected: the derived store is unavailable and no authority scan is possible. */
32
+ export const TOP_AUTHORITY_UNAVAILABLE = "TOP_AUTHORITY_UNAVAILABLE";
33
+ /** Frozen router key schema version carried in every encoded key. */
34
+ export const ROUTER_KEY_VERSION = 2;
35
+ /**
36
+ * Create the query surface. `emit` is optional and flag-gated (the caller passes
37
+ * a reporter produced by the same pattern VC3A/VC3B use — zero emissions when
38
+ * `MEGACOMPACT_VC3C=0`, byte-identical to the predecessor). Pure in-memory index
39
+ * over the injected host; durability of invalidation is the caller's job.
40
+ */
41
+ export function createTopologyQuery(host, emit) {
42
+ // session -> Set of indexed generation strings (exact, byte-identity).
43
+ const generations = new Map();
44
+ const fire = (event, fields) => {
45
+ if (!emit)
46
+ return;
47
+ try {
48
+ emit(event, fields);
49
+ }
50
+ catch {
51
+ /* non-fatal observability — never break the agent loop */
52
+ }
53
+ };
54
+ const query = (key) => {
55
+ const active = host.activeGeneration(key.session);
56
+ // Mode C: derived store unavailable -> authority sequence scan.
57
+ if (!host.derivedAvailable(key.session)) {
58
+ const cDigest = host.authorityScan(key.session, key.sourceStart, key.sourceEnd);
59
+ if (cDigest === undefined) {
60
+ return { ok: false, code: TOP_AUTHORITY_UNAVAILABLE, mode: "C" };
61
+ }
62
+ fire("vector_cortex_topology_query_demoted", {
63
+ session: key.session,
64
+ generation: key.generation.toString(),
65
+ code: "DERIVED_UNAVAILABLE",
66
+ toMode: "C",
67
+ });
68
+ return {
69
+ ok: true,
70
+ mode: "C",
71
+ session: key.session,
72
+ generation: key.generation,
73
+ algorithm: key.algorithm,
74
+ matchedKey: encodeRouterKeyV2(key),
75
+ digest: cDigest.digest,
76
+ };
77
+ }
78
+ // A key is stale when its generation is below the active one (or the active
79
+ // generation is unset and the requested generation is non-zero).
80
+ const stale = active === undefined
81
+ ? key.generation !== 0n
82
+ : key.generation < active;
83
+ if (stale) {
84
+ // Mode B: fresh linear scan forced by a stale A key.
85
+ const bDigest = host.linearScan(key.session, key.sourceStart, key.sourceEnd);
86
+ fire("vector_cortex_topology_query_demoted", {
87
+ session: key.session,
88
+ generation: key.generation.toString(),
89
+ activeGeneration: active === undefined ? null : active.toString(),
90
+ code: "STALE_GENERATION",
91
+ toMode: "B",
92
+ });
93
+ return {
94
+ ok: true,
95
+ mode: "B",
96
+ session: key.session,
97
+ generation: key.generation,
98
+ algorithm: key.algorithm,
99
+ matchedKey: encodeRouterKeyV2(key),
100
+ digest: bDigest.digest,
101
+ };
102
+ }
103
+ // Mode A: topology index at the current generation. If the derived store is
104
+ // up but has not indexed this exact (generation, algorithm) yet, that is a
105
+ // mode-A miss (no graph to serve) — force the fresh linear scan rather than
106
+ // fabricate a graph or report a false staleness (Q03: the index cannot be
107
+ // trusted to hold every current generation; B recomputes from source).
108
+ const graph = host.graphAt(key.session, key.generation, key.algorithm);
109
+ if (graph === undefined) {
110
+ const bDigest = host.linearScan(key.session, key.sourceStart, key.sourceEnd);
111
+ fire("vector_cortex_topology_query_demoted", {
112
+ session: key.session,
113
+ generation: key.generation.toString(),
114
+ code: "GENERATION_MISS",
115
+ toMode: "B",
116
+ });
117
+ return {
118
+ ok: true,
119
+ mode: "B",
120
+ session: key.session,
121
+ generation: key.generation,
122
+ algorithm: key.algorithm,
123
+ matchedKey: encodeRouterKeyV2(key),
124
+ digest: bDigest.digest,
125
+ };
126
+ }
127
+ return {
128
+ ok: true,
129
+ mode: "A",
130
+ session: key.session,
131
+ generation: key.generation,
132
+ algorithm: key.algorithm,
133
+ matchedKey: encodeRouterKeyV2(key),
134
+ digest: graph.digest,
135
+ };
136
+ };
137
+ const invalidate = (session, generation) => {
138
+ const invalidationIdentity = invalidationKey(session, generation);
139
+ const set = generations.get(session);
140
+ if (set)
141
+ set.delete(invalidationIdentity);
142
+ fire("vector_cortex_router_generation_invalidated", {
143
+ session,
144
+ generation: generation.toString(),
145
+ key: invalidationIdentity,
146
+ });
147
+ };
148
+ const generationalCount = (session) => {
149
+ return generations.get(session)?.size ?? 0;
150
+ };
151
+ return { query, invalidate, generationalCount };
152
+ }
153
+ // ---------------------------------------------------------------------------
154
+ // Length-delimited, unsigned-byte-ordered key encoding (M6-KEY-001)
155
+ // ---------------------------------------------------------------------------
156
+ /**
157
+ * Encode one field: `u32BE(byteLength) || bytes`. Non-negative numbers are
158
+ * encoded as their unsigned big-endian byte form (leading zeros trimmed). This
159
+ * is the standard big-endian length-prefixed encoding: two fields compare in
160
+ * unsigned-byte order exactly as their values do, and no value is an ambiguous
161
+ * prefix of another.
162
+ */
163
+ function encodeLengthDelimited(bytes) {
164
+ const out = new Uint8Array(4 + bytes.length);
165
+ const view = new DataView(out.buffer);
166
+ view.setUint32(0, bytes.length, false);
167
+ out.set(bytes, 4);
168
+ return out;
169
+ }
170
+ /** Big-endian unsigned bytes of a non-negative bigint (length-prefixed below). */
171
+ function bigintBytes(n) {
172
+ let v = n;
173
+ const out = [];
174
+ if (v === 0n)
175
+ return new Uint8Array([0]);
176
+ while (v > 0n) {
177
+ out.unshift(Number(v & 0xffn));
178
+ v >>= 8n;
179
+ }
180
+ return Uint8Array.from(out);
181
+ }
182
+ /** UTF-8 bytes of a string. */
183
+ function strBytes(s) {
184
+ return new TextEncoder().encode(s);
185
+ }
186
+ function concat(parts) {
187
+ let len = 0;
188
+ for (const p of parts)
189
+ len += p.length;
190
+ const out = new Uint8Array(len);
191
+ let off = 0;
192
+ for (const p of parts) {
193
+ out.set(p, off);
194
+ off += p.length;
195
+ }
196
+ return out;
197
+ }
198
+ /**
199
+ * Encode a RouterKeyV2 into its canonical, length-delimited, unsigned-byte-ordered
200
+ * byte form. Version-prefixed (1 byte) + five length-delimited fields in fixed
201
+ * order (session, sourceStart, sourceEnd, generation, algorithm). Fixed arity +
202
+ * length-delimiting means no key is a strict prefix of another and sessions `a`
203
+ * and `aa` never collide (M6-KEY-001).
204
+ */
205
+ export function encodeRouterKeyV2(key) {
206
+ const version = Uint8Array.of(ROUTER_KEY_VERSION);
207
+ const session = encodeLengthDelimited(strBytes(key.session));
208
+ const sourceStart = encodeLengthDelimited(bigintBytes(key.sourceStart));
209
+ const sourceEnd = encodeLengthDelimited(bigintBytes(key.sourceEnd));
210
+ const generation = encodeLengthDelimited(bigintBytes(key.generation));
211
+ const algorithm = encodeLengthDelimited(strBytes(key.algorithm));
212
+ return "rk2:" + Buffer.from(concat([version, session, sourceStart, sourceEnd, generation, algorithm])).toString("hex");
213
+ }
214
+ /**
215
+ * Decode a RouterKeyV2 from its canonical byte form. Returns
216
+ * TOP_KEY_DECODE_FAILED on malformed bytes (bad version, truncated length, or
217
+ * trailing garbage). Never parses by string prefix.
218
+ */
219
+ export function decodeRouterKeyV2(encoded) {
220
+ if (!encoded.startsWith("rk2:"))
221
+ return { ok: false, code: "TOP_KEY_DECODE_FAILED" };
222
+ const hex = encoded.slice(4);
223
+ if (!/^[0-9a-f]*$/.test(hex) || hex.length % 2 !== 0) {
224
+ return { ok: false, code: "TOP_KEY_DECODE_FAILED" };
225
+ }
226
+ const buf = Buffer.from(hex, "hex");
227
+ const bytes = new Uint8Array(buf);
228
+ const reader = new Reader(bytes);
229
+ const version = reader.u8();
230
+ if (version !== ROUTER_KEY_VERSION)
231
+ return { ok: false, code: "TOP_KEY_DECODE_FAILED" };
232
+ const sessionBytes = reader.lenPrefixed();
233
+ const ssBytes = reader.lenPrefixed();
234
+ const seBytes = reader.lenPrefixed();
235
+ const genBytes = reader.lenPrefixed();
236
+ const algoBytes = reader.lenPrefixed();
237
+ if (reader.remaining() !== 0)
238
+ return { ok: false, code: "TOP_KEY_DECODE_FAILED" };
239
+ if (sessionBytes === null || ssBytes === null || seBytes === null || genBytes === null || algoBytes === null) {
240
+ return { ok: false, code: "TOP_KEY_DECODE_FAILED" };
241
+ }
242
+ const session = new TextDecoder().decode(sessionBytes);
243
+ const sourceStart = bytesToBigint(ssBytes);
244
+ const sourceEnd = bytesToBigint(seBytes);
245
+ const generation = bytesToBigint(genBytes);
246
+ const algorithm = new TextDecoder().decode(algoBytes);
247
+ return { ok: true, key: { session, sourceStart, sourceEnd, generation, algorithm } };
248
+ }
249
+ /** Sequential length-delimited byte reader. */
250
+ class Reader {
251
+ bytes;
252
+ off = 0;
253
+ constructor(bytes) {
254
+ this.bytes = bytes;
255
+ }
256
+ u8() {
257
+ const v = this.bytes[this.off];
258
+ this.off += 1;
259
+ return v;
260
+ }
261
+ lenPrefixed() {
262
+ if (this.off + 4 > this.bytes.length)
263
+ return null;
264
+ const view = new DataView(this.bytes.buffer, this.bytes.byteOffset + this.off, 4);
265
+ const len = view.getUint32(0, false);
266
+ this.off += 4;
267
+ if (this.off + len > this.bytes.length)
268
+ return null;
269
+ const out = this.bytes.slice(this.off, this.off + len);
270
+ this.off += len;
271
+ return out;
272
+ }
273
+ remaining() {
274
+ return this.bytes.length - this.off;
275
+ }
276
+ }
277
+ /** Non-negative bigint from its unsigned big-endian bytes. */
278
+ function bytesToBigint(bytes) {
279
+ let n = 0n;
280
+ for (const b of bytes)
281
+ n = (n << 8n) | BigInt(b);
282
+ return n;
283
+ }
284
+ /**
285
+ * Canonical invalidation identity for an exact (session,generation) pair, using
286
+ * the SAME length-delimited scheme so two pairs can only match by exact byte
287
+ * equality (never by string prefix — `a` never matches `aa`). Returned as hex
288
+ * for use as a registry key.
289
+ */
290
+ export function invalidationKey(session, generation) {
291
+ const sessionF = encodeLengthDelimited(strBytes(session));
292
+ const genF = encodeLengthDelimited(bigintBytes(generation));
293
+ return "inv:" + Buffer.from(concat([sessionF, genF])).toString("hex");
294
+ }
295
+ /** One deterministic SHA-256 (hex) digest over the canonical key bytes. */
296
+ export function keyDigest(key) {
297
+ return `sha256:${createHash("sha256").update(Buffer.from(encodeRouterKeyV2(key).slice(4), "hex")).digest("hex")}`;
298
+ }
299
+ /**
300
+ * Shared invalidation-capability seam (narrow delegate, no routing rewrite).
301
+ * Records the EXACT (session,generation) identity and, when `enabled`, best-effort
302
+ * emits `vector_cortex_router_generation_invalidated`. Falsy `enabled` (flag OFF)
303
+ * is a strict no-op so the predecessor keying is byte-identical to pre-sprint.
304
+ * Exactness is enforced by `invalidationKey` (length-delimited, never a string
305
+ * prefix — `a` never matches `aa`), the same identity M6 validates.
306
+ */
307
+ export function routerGenerationInvalidationSeam(key, enabled, emit) {
308
+ if (!enabled)
309
+ return;
310
+ const identity = invalidationKey(key.session, key.generation);
311
+ if (emit) {
312
+ try {
313
+ emit("vector_cortex_router_generation_invalidated", {
314
+ session: key.session,
315
+ generation: key.generation.toString(),
316
+ key: identity,
317
+ });
318
+ }
319
+ catch {
320
+ /* non-fatal observability — never break the agent loop */
321
+ }
322
+ }
323
+ }
324
+ /** Registered TOP query conformance ID range (TOP-021..030). */
325
+ export const TOP_QUERY_IDS = [
326
+ "TOP-021",
327
+ "TOP-022",
328
+ "TOP-023",
329
+ "TOP-024",
330
+ "TOP-025",
331
+ "TOP-026",
332
+ "TOP-027",
333
+ "TOP-028",
334
+ "TOP-029",
335
+ "TOP-030",
336
+ ];
337
+ /** Registered named TOP-query conformance IDs. */
338
+ export const TOP_QUERY_NAMED_IDS = [
339
+ "TOP-QUERY-003",
340
+ "M6-KEY-001",
341
+ "M6-STALE-002",
342
+ ];
@@ -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
+ }