pi-mega-compact 0.19.2 → 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 (78) hide show
  1. package/dist/config/vector-cortex.js +12 -0
  2. package/dist/config.js +1 -1
  3. package/dist/extensions/dashboard-server/routes-rag-settings-helpers.js +1 -0
  4. package/dist/extensions/dashboard-server/routes-vector-cortex-query.js +46 -0
  5. package/dist/extensions/dashboard-server/routes-vector-cortex.js +1 -0
  6. package/dist/extensions/dashboard-server/routes.js +1 -1
  7. package/dist/extensions/dashboard-server/server.js +3 -1
  8. package/dist/src/config/vector-cortex.js +12 -0
  9. package/dist/src/config.js +1 -1
  10. package/dist/src/tieredRouter.js +8 -0
  11. package/dist/src/vector-cortex/migrations/router-generation-v2.js +252 -0
  12. package/dist/src/vector-cortex/topology/query.js +342 -0
  13. package/dist/vector-cortex/migrations/router-generation-v2.js +252 -0
  14. package/dist/vector-cortex/topology/query.js +342 -0
  15. package/extensions/dashboard-client/dist/assets/{AreaChart-CSaJZXru.js → AreaChart-DqiFSnDx.js} +2 -2
  16. package/extensions/dashboard-client/dist/assets/{AreaChart-CSaJZXru.js.map → AreaChart-DqiFSnDx.js.map} +1 -1
  17. package/extensions/dashboard-client/dist/assets/{BarChart-CQouNj1g.js → BarChart-Cqg-PQMK.js} +2 -2
  18. package/extensions/dashboard-client/dist/assets/{BarChart-CQouNj1g.js.map → BarChart-Cqg-PQMK.js.map} +1 -1
  19. package/extensions/dashboard-client/dist/assets/{CacheTab-m_eiCYoL.js → CacheTab-BPNs0xIF.js} +2 -2
  20. package/extensions/dashboard-client/dist/assets/{CacheTab-m_eiCYoL.js.map → CacheTab-BPNs0xIF.js.map} +1 -1
  21. package/extensions/dashboard-client/dist/assets/{EventsTab-DRyOwjYN.js → EventsTab-BQf7OGkf.js} +2 -2
  22. package/extensions/dashboard-client/dist/assets/{EventsTab-DRyOwjYN.js.map → EventsTab-BQf7OGkf.js.map} +1 -1
  23. package/extensions/dashboard-client/dist/assets/{HealthTab-Dj9k40TJ.js → HealthTab-B14TaSPN.js} +2 -2
  24. package/extensions/dashboard-client/dist/assets/{HealthTab-Dj9k40TJ.js.map → HealthTab-B14TaSPN.js.map} +1 -1
  25. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-Bk9mhYfD.js → MaintenanceTab-D8lkRoa1.js} +2 -2
  26. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-Bk9mhYfD.js.map → MaintenanceTab-D8lkRoa1.js.map} +1 -1
  27. package/extensions/dashboard-client/dist/assets/{MemoryMapTab-C7ve49VG.js → MemoryMapTab-BOWtGfpx.js} +2 -2
  28. package/extensions/dashboard-client/dist/assets/{MemoryMapTab-C7ve49VG.js.map → MemoryMapTab-BOWtGfpx.js.map} +1 -1
  29. package/extensions/dashboard-client/dist/assets/{MetricsTab-DzjhqZA9.js → MetricsTab-7XI9cWaX.js} +2 -2
  30. package/extensions/dashboard-client/dist/assets/{MetricsTab-DzjhqZA9.js.map → MetricsTab-7XI9cWaX.js.map} +1 -1
  31. package/extensions/dashboard-client/dist/assets/{OverviewTab-CFQdfIm_.js → OverviewTab-C9KaGYvh.js} +2 -2
  32. package/extensions/dashboard-client/dist/assets/{OverviewTab-CFQdfIm_.js.map → OverviewTab-C9KaGYvh.js.map} +1 -1
  33. package/extensions/dashboard-client/dist/assets/{ReposTab-DyjwEFUr.js → ReposTab-BwESNhox.js} +2 -2
  34. package/extensions/dashboard-client/dist/assets/{ReposTab-DyjwEFUr.js.map → ReposTab-BwESNhox.js.map} +1 -1
  35. package/extensions/dashboard-client/dist/assets/{SessionsTab-njLIy7ab.js → SessionsTab-DKH55Rda.js} +2 -2
  36. package/extensions/dashboard-client/dist/assets/{SessionsTab-njLIy7ab.js.map → SessionsTab-DKH55Rda.js.map} +1 -1
  37. package/extensions/dashboard-client/dist/assets/{SetupTab-UHIs8-Lh.js → SetupTab-zDxf-nJd.js} +2 -2
  38. package/extensions/dashboard-client/dist/assets/{SetupTab-UHIs8-Lh.js.map → SetupTab-zDxf-nJd.js.map} +1 -1
  39. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-inWHjCxg.js → TimeSavedCard-C9isog4L.js} +2 -2
  40. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-inWHjCxg.js.map → TimeSavedCard-C9isog4L.js.map} +1 -1
  41. package/extensions/dashboard-client/dist/assets/{TurnsTab-CXJYugBu.js → TurnsTab-ciI6ydvj.js} +2 -2
  42. package/extensions/dashboard-client/dist/assets/{TurnsTab-CXJYugBu.js.map → TurnsTab-ciI6ydvj.js.map} +1 -1
  43. package/extensions/dashboard-client/dist/assets/VectorCortexTab-qTZ7NWng.js +2 -0
  44. package/extensions/dashboard-client/dist/assets/VectorCortexTab-qTZ7NWng.js.map +1 -0
  45. package/extensions/dashboard-client/dist/assets/{WikiTab-BJ4A2oi9.js → WikiTab-DcYHc734.js} +2 -2
  46. package/extensions/dashboard-client/dist/assets/{WikiTab-BJ4A2oi9.js.map → WikiTab-DcYHc734.js.map} +1 -1
  47. package/extensions/dashboard-client/dist/assets/{button-BWl-moyn.js → button-DF8lx4bt.js} +2 -2
  48. package/extensions/dashboard-client/dist/assets/{button-BWl-moyn.js.map → button-DF8lx4bt.js.map} +1 -1
  49. package/extensions/dashboard-client/dist/assets/{card-C58RVPOk.js → card-DIoDheSZ.js} +2 -2
  50. package/extensions/dashboard-client/dist/assets/{card-C58RVPOk.js.map → card-DIoDheSZ.js.map} +1 -1
  51. package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-vgeOQU3L.js → generateCategoricalChart-BFRzeYX3.js} +2 -2
  52. package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-vgeOQU3L.js.map → generateCategoricalChart-BFRzeYX3.js.map} +1 -1
  53. package/extensions/dashboard-client/dist/assets/{index-lVrWQjpu.js → index-DSZON0Yi.js} +3 -3
  54. package/extensions/dashboard-client/dist/assets/{index-lVrWQjpu.js.map → index-DSZON0Yi.js.map} +1 -1
  55. package/extensions/dashboard-client/dist/assets/{switch-CSeplFQT.js → switch-l4qo22mU.js} +2 -2
  56. package/extensions/dashboard-client/dist/assets/{switch-CSeplFQT.js.map → switch-l4qo22mU.js.map} +1 -1
  57. package/extensions/dashboard-client/dist/assets/{toggle-CQRxgVRi.js → toggle-DPn6td1_.js} +2 -2
  58. package/extensions/dashboard-client/dist/assets/{toggle-CQRxgVRi.js.map → toggle-DPn6td1_.js.map} +1 -1
  59. package/extensions/dashboard-client/dist/assets/{useSSE-BUz6IOI-.js → useSSE-BLmolqTJ.js} +2 -2
  60. package/extensions/dashboard-client/dist/assets/{useSSE-BUz6IOI-.js.map → useSSE-BLmolqTJ.js.map} +1 -1
  61. package/extensions/dashboard-client/dist/index.html +1 -1
  62. package/extensions/dashboard-client/src/api/vector-cortex.ts +9 -0
  63. package/extensions/dashboard-client/src/tabs/VectorCortexTab.tsx +27 -0
  64. package/extensions/dashboard-client/src/types/vector-cortex.ts +12 -0
  65. package/extensions/dashboard-server/api-contracts/vector-cortex.ts +17 -0
  66. package/extensions/dashboard-server/routes-rag-settings-helpers.ts +6 -0
  67. package/extensions/dashboard-server/routes-vector-cortex-query.ts +54 -0
  68. package/extensions/dashboard-server/routes-vector-cortex.ts +1 -0
  69. package/extensions/dashboard-server/routes.ts +1 -0
  70. package/extensions/dashboard-server/server.ts +2 -0
  71. package/package.json +1 -1
  72. package/src/config/vector-cortex.ts +13 -0
  73. package/src/config.ts +1 -0
  74. package/src/tieredRouter.ts +9 -0
  75. package/src/vector-cortex/migrations/router-generation-v2.ts +317 -0
  76. package/src/vector-cortex/topology/query.ts +485 -0
  77. package/extensions/dashboard-client/dist/assets/VectorCortexTab-DkS0Azx9.js +0 -2
  78. package/extensions/dashboard-client/dist/assets/VectorCortexTab-DkS0Azx9.js.map +0 -1
@@ -0,0 +1,54 @@
1
+ /**
2
+ * dashboard-server/routes-vector-cortex-query.ts — VC3C vector-cortex query-layer
3
+ * diagnostics dashboard route.
4
+ *
5
+ * Reader-only GET /api/vector-cortex/query. Purely a flag-status + structural
6
+ * diagnostic: the VC3C query index is in-memory (not durable), so this route
7
+ * reports whether the VC3C flag is enabled, the router-generation v2 version
8
+ * constant, and a snapshot timestamp. It NEVER exposes payloads or prompts.
9
+ * Non-fatal: a missing state dir (or any internal error) degrades to
10
+ * `enabled:false`.
11
+ *
12
+ * Guardrails: PREVENT-PI-004 (local flag/config read only, no network),
13
+ * PREVENT-011 (no `any`), reader-only aggregate (never payloads/prompts).
14
+ */
15
+
16
+ import type { IncomingMessage, ServerResponse } from "node:http";
17
+ import type { RouteContext } from "./routes-core.js";
18
+ import { VC3C_ENABLED } from "../../src/config.js";
19
+ import { ROUTER_KEY_VERSION } from "../../src/vector-cortex/topology/query.js";
20
+ import { sendJson } from "./routes-vector-cortex-shared.js";
21
+ import type { VectorCortexQueryView } from "./api-contracts/vector-cortex.js";
22
+
23
+ /**
24
+ * Reader-only GET /api/vector-cortex/query (VC3C query-layer diagnostics).
25
+ */
26
+ export function handleVectorCortexQuery(
27
+ req: IncomingMessage,
28
+ res: ServerResponse,
29
+ _ctx: RouteContext,
30
+ ): boolean {
31
+ const url = req.url ?? "";
32
+ const path = url.split("?")[0] ?? url;
33
+ if (path !== "/api/vector-cortex/query") return false;
34
+ if (req.method !== "GET") {
35
+ // Reader-only path: no mutation endpoint lives at /query.
36
+ sendJson(res, 405, { error: "method_not_allowed" });
37
+ return true;
38
+ }
39
+
40
+ let enabled = false;
41
+ try {
42
+ enabled = VC3C_ENABLED();
43
+ } catch {
44
+ // Non-fatal: a missing/unavailable flag degrades to `enabled:false`.
45
+ enabled = false;
46
+ }
47
+ const body: VectorCortexQueryView = {
48
+ enabled,
49
+ routerVersion: ROUTER_KEY_VERSION,
50
+ updatedAt: new Date().toISOString(),
51
+ };
52
+ sendJson(res, 200, body);
53
+ return true;
54
+ }
@@ -18,3 +18,4 @@ export { handleVectorCortexEvaluation } from "./routes-vector-cortex-eval.js";
18
18
  export { handleVectorCortexHealth, handleVectorCortexBreakersReset } from "./routes-vector-cortex-health.js";
19
19
  export { handleVectorCortexLedger } from "./routes-vector-cortex-ledger.js";
20
20
  export { handleVectorCortexTopology } from "./routes-vector-cortex-topology.js";
21
+ export { handleVectorCortexQuery } from "./routes-vector-cortex-query.js";
@@ -46,4 +46,5 @@ export {
46
46
  handleVectorCortexBreakersReset,
47
47
  handleVectorCortexLedger,
48
48
  handleVectorCortexTopology,
49
+ handleVectorCortexQuery,
49
50
  } from "./routes-vector-cortex.js";
@@ -61,6 +61,7 @@ import {
61
61
  handleVectorCortexBreakersReset,
62
62
  handleVectorCortexLedger,
63
63
  handleVectorCortexTopology,
64
+ handleVectorCortexQuery,
64
65
  handleStatic,
65
66
  } from "./routes.js";
66
67
 
@@ -285,6 +286,7 @@ export async function launchDashboardServer(
285
286
  if (handleVectorCortexBreakersReset(req, res, ctx)) return;
286
287
  if (handleVectorCortexLedger(req, res, ctx)) return;
287
288
  if (handleVectorCortexTopology(req, res, ctx)) return;
289
+ if (handleVectorCortexQuery(req, res, ctx)) return;
288
290
  handleStatic(req, res, ctx);
289
291
  });
290
292
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-mega-compact",
3
- "version": "0.19.2",
3
+ "version": "0.19.3",
4
4
  "description": "Layered, local, vector-backed context compressor for pi — supersede/collapse/cluster compaction with deduped inline recall.",
5
5
  "type": "module",
6
6
  "license": "BSD-3-Clause",
@@ -121,6 +121,19 @@ export const VC3A_ENABLED = (): boolean => sprintFlag("MEGACOMPACT_VC3A");
121
121
  */
122
122
  export const VC3B_ENABLED = (): boolean => sprintFlag("MEGACOMPACT_VC3B");
123
123
 
124
+ /**
125
+ * VC3C — topology query + router invalidation (TopologyQueryV1 / RouterKeyV2,
126
+ * M6 router-generation-v2 migration).
127
+ * Default ON. `MEGACOMPACT_VC3C=0` disables and is byte-identical to the
128
+ * predecessor (mode C: no length-delimited router key, no generation
129
+ * invalidation, zero `vector_cortex_router_generation_invalidated` /
130
+ * `vector_cortex_topology_query_demoted` emissions; the predecessor tiered
131
+ * router keying is unchanged). The real consumers are the topology query seam
132
+ * (query.ts), the M6 router-generation-v2 migration seam, and the reader-only
133
+ * dashboard topology query diagnostic view.
134
+ */
135
+ export const VC3C_ENABLED = (): boolean => sprintFlag("MEGACOMPACT_VC3C");
136
+
124
137
  // ---------------------------------------------------------------------------
125
138
  // Breaker state machine constants (TRIAD_RESILIENCE.md §breaker).
126
139
  // Rolled numbers for one 60s window; VC0C consumes these at its breaker seam.
package/src/config.ts CHANGED
@@ -162,6 +162,7 @@ export {
162
162
  VC2C_ENABLED,
163
163
  VC3A_ENABLED,
164
164
  VC3B_ENABLED,
165
+ VC3C_ENABLED,
165
166
  BREAKER_WINDOW_MS,
166
167
  BREAKER_MIN_ATTEMPTS,
167
168
  BREAKER_PERF_FAILURES,
@@ -16,6 +16,9 @@
16
16
  import { createHash } from "node:crypto";
17
17
  import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
18
18
  import { dirname, join } from "node:path";
19
+ import { VC3C_ENABLED } from "./config.js";
20
+ import { Logger } from "./log.js";
21
+ import { routerGenerationInvalidationSeam, type RouterKeyV2 } from "./vector-cortex/topology/query.js";
19
22
  import { openStore } from "./store/sqlite/utils.js";
20
23
  import { fts5SearchScoped } from "./store/sqlite/fts5-search.js";
21
24
  import { listCheckpoints } from "./store/sqlite.js";
@@ -343,6 +346,12 @@ export class TieredRouter {
343
346
  this.embeddingCache.clear();
344
347
  }
345
348
 
349
+ /** VC3C narrow delegate: exact (session,generation) RouterKeyV2 invalidation.
350
+ * No routing rewrite; `MEGACOMPACT_VC3C=0` is a strict no-op, byte-identical. */
351
+ invalidateGeneration(key: RouterKeyV2): void {
352
+ routerGenerationInvalidationSeam(key, VC3C_ENABLED(), (e, f) => new Logger().info(e, f));
353
+ }
354
+
346
355
  /** Snapshot of current metrics for dashboard / logging. */
347
356
  getMetrics(): TieredRouterMetrics {
348
357
  const q = Math.max(this.totalQueries, 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
+ }