pi-mega-compact 0.16.3 → 0.17.1
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.
- package/dist/config/vector-cortex.js +91 -0
- package/dist/dedup/digest.js +30 -0
- package/dist/dedup/l1-lsh-v2.js +60 -0
- package/dist/dedup/l1-lsh.js +52 -0
- package/dist/dedup/l1-minhash-v2.js +193 -0
- package/dist/dedup/l1-minhash.js +91 -0
- package/dist/dedup/l1-verify.js +54 -0
- package/dist/dedup/mmr.js +45 -0
- package/dist/dedup/normalize.js +39 -0
- package/dist/dedup/raptor/buildHistory.js +164 -0
- package/dist/dedup/raptor/guardrails.js +83 -0
- package/dist/dedup/raptor/incremental.js +304 -0
- package/dist/dedup/raptor/index.js +190 -0
- package/dist/dedup/raptor/kmeans.js +152 -0
- package/dist/dedup/raptor/multilevel.js +184 -0
- package/dist/dedup/raptor/retrieval.js +93 -0
- package/dist/dedup/raptor/summarizer.js +86 -0
- package/dist/dedup/raptor/tree.js +202 -0
- package/dist/dedup/topk.js +60 -0
- package/dist/extensions/dashboard-server/api-contracts/endpoints/registry-ext.js +30 -0
- package/dist/extensions/dashboard-server/api-contracts/endpoints/registry.js +4 -14
- package/dist/extensions/dashboard-server/api-contracts/vector-cortex.js +12 -0
- package/dist/extensions/dashboard-server/routes-rag-settings-helpers.js +11 -0
- package/dist/extensions/dashboard-server/routes-vector-cortex.js +292 -0
- package/dist/extensions/dashboard-server/routes.js +1 -0
- package/dist/extensions/dashboard-server/server.js +9 -1
- package/dist/extensions/mega-events/context-handler.js +11 -0
- package/dist/extensions/mega-runtime/vector-cortex-ledger.js +131 -0
- package/dist/extensions/mega-runtime/vector-cortex-safety.js +100 -0
- package/dist/src/config/vector-cortex.js +91 -0
- package/dist/src/config.js +6 -0
- package/dist/src/dedup/l1-lsh-v2.js +60 -0
- package/dist/src/dedup/l1-minhash-v2.js +193 -0
- package/dist/src/dedup/normalize.js +1 -1
- package/dist/src/vector-cortex/conformance/emit.js +46 -0
- package/dist/src/vector-cortex/conformance/manifest.js +235 -0
- package/dist/src/vector-cortex/conformance/runner.js +111 -0
- package/dist/src/vector-cortex/conformance/triadB-reader.js +95 -0
- package/dist/src/vector-cortex/eval/annotations.js +41 -0
- package/dist/src/vector-cortex/eval/metrics.js +86 -0
- package/dist/src/vector-cortex/eval/observer.js +61 -0
- package/dist/src/vector-cortex/eval/persist.js +67 -0
- package/dist/src/vector-cortex/eval/reader.js +29 -0
- package/dist/src/vector-cortex/eval/types.js +33 -0
- package/dist/src/vector-cortex/ledger/adapter.js +55 -0
- package/dist/src/vector-cortex/ledger/compat-journal.js +206 -0
- package/dist/src/vector-cortex/ledger/emit.js +53 -0
- package/dist/src/vector-cortex/ledger/event-codec.js +72 -0
- package/dist/src/vector-cortex/ledger/event-codecB.js +76 -0
- package/dist/src/vector-cortex/ledger/sqlite.js +200 -0
- package/dist/src/vector-cortex/ledger/store.js +184 -0
- package/dist/src/vector-cortex/ledger/types.js +52 -0
- package/dist/src/vector-cortex/ledger/validator.js +117 -0
- package/dist/src/vector-cortex/migrations/effective-cut-v2.js +103 -0
- package/dist/src/vector-cortex/migrations/minhash-v2.js +209 -0
- package/dist/src/vector-cortex/migrations/occurrence-v2.js +139 -0
- package/dist/src/vector-cortex/replay/cut.js +123 -0
- package/dist/src/vector-cortex/replay/emit.js +58 -0
- package/dist/src/vector-cortex/replay/replay.js +260 -0
- package/dist/src/vector-cortex/replay/replayB.js +73 -0
- package/dist/src/vector-cortex/replay/types.js +52 -0
- package/dist/src/vector-cortex/resilience/breaker-core.js +359 -0
- package/dist/src/vector-cortex/resilience/breaker.js +12 -0
- package/dist/src/vector-cortex/resilience/emit.js +56 -0
- package/dist/src/vector-cortex/resilience/spool-core.js +347 -0
- package/dist/src/vector-cortex/resilience/spool.js +12 -0
- package/dist/src/vector-cortex/resilience/types.js +32 -0
- package/dist/vector-cortex/conformance/emit.js +46 -0
- package/dist/vector-cortex/conformance/manifest.js +235 -0
- package/dist/vector-cortex/conformance/runner.js +111 -0
- package/dist/vector-cortex/conformance/triadB-reader.js +95 -0
- package/dist/vector-cortex/eval/annotations.js +41 -0
- package/dist/vector-cortex/eval/metrics.js +86 -0
- package/dist/vector-cortex/eval/observer.js +61 -0
- package/dist/vector-cortex/eval/persist.js +67 -0
- package/dist/vector-cortex/eval/reader.js +29 -0
- package/dist/vector-cortex/eval/types.js +33 -0
- package/dist/vector-cortex/ledger/adapter.js +55 -0
- package/dist/vector-cortex/ledger/compat-journal.js +206 -0
- package/dist/vector-cortex/ledger/emit.js +53 -0
- package/dist/vector-cortex/ledger/event-codec.js +72 -0
- package/dist/vector-cortex/ledger/event-codecB.js +76 -0
- package/dist/vector-cortex/ledger/sqlite.js +200 -0
- package/dist/vector-cortex/ledger/store.js +184 -0
- package/dist/vector-cortex/ledger/types.js +52 -0
- package/dist/vector-cortex/ledger/validator.js +117 -0
- package/dist/vector-cortex/migrations/effective-cut-v2.js +103 -0
- package/dist/vector-cortex/migrations/minhash-v2.js +209 -0
- package/dist/vector-cortex/migrations/occurrence-v2.js +139 -0
- package/dist/vector-cortex/replay/cut.js +123 -0
- package/dist/vector-cortex/replay/emit.js +58 -0
- package/dist/vector-cortex/replay/replay.js +260 -0
- package/dist/vector-cortex/replay/replayB.js +73 -0
- package/dist/vector-cortex/replay/types.js +52 -0
- package/dist/vector-cortex/resilience/breaker-core.js +359 -0
- package/dist/vector-cortex/resilience/breaker.js +12 -0
- package/dist/vector-cortex/resilience/emit.js +56 -0
- package/dist/vector-cortex/resilience/spool-core.js +347 -0
- package/dist/vector-cortex/resilience/spool.js +12 -0
- package/dist/vector-cortex/resilience/types.js +32 -0
- package/extensions/dashboard-client/dist/assets/{AreaChart-Y_X0Bbjd.js → AreaChart-BQXFF7UI.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{AreaChart-Y_X0Bbjd.js.map → AreaChart-BQXFF7UI.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{BarChart-B9XDb-Ob.js → BarChart-BVtoz9Eg.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{BarChart-B9XDb-Ob.js.map → BarChart-BVtoz9Eg.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{CacheTab-BUGVb1G1.js → CacheTab-trI2TIGy.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{CacheTab-BUGVb1G1.js.map → CacheTab-trI2TIGy.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{EventsTab-dOqLYTsy.js → EventsTab-CNUbk9__.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{EventsTab-dOqLYTsy.js.map → EventsTab-CNUbk9__.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{HealthTab-c2vezKg1.js → HealthTab-K-bd_CM-.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{HealthTab-c2vezKg1.js.map → HealthTab-K-bd_CM-.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{MaintenanceTab-bQYHIcdx.js → MaintenanceTab-CoEioKzx.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{MaintenanceTab-bQYHIcdx.js.map → MaintenanceTab-CoEioKzx.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{MemoryMapTab-2L8pH6y2.js → MemoryMapTab-CJo24ulv.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{MemoryMapTab-2L8pH6y2.js.map → MemoryMapTab-CJo24ulv.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{MetricsTab-CzUx1jpo.js → MetricsTab-DCNlQWWP.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{MetricsTab-CzUx1jpo.js.map → MetricsTab-DCNlQWWP.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{OverviewTab-eCNoaclv.js → OverviewTab-CQQlyIQ6.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{OverviewTab-eCNoaclv.js.map → OverviewTab-CQQlyIQ6.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{ReposTab-tb0IW3NF.js → ReposTab-Cqm82_yn.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{ReposTab-tb0IW3NF.js.map → ReposTab-Cqm82_yn.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{SessionsTab-C-IoLw5h.js → SessionsTab-A8xTAdET.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{SessionsTab-C-IoLw5h.js.map → SessionsTab-A8xTAdET.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{SetupTab-BvmFi8gf.js → SetupTab-CqaSgaZl.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{SetupTab-BvmFi8gf.js.map → SetupTab-CqaSgaZl.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{TimeSavedCard-DBH-cOlA.js → TimeSavedCard-C_f3q8GR.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{TimeSavedCard-DBH-cOlA.js.map → TimeSavedCard-C_f3q8GR.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{TurnsTab-DBMgmvnX.js → TurnsTab-BEsafACo.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{TurnsTab-DBMgmvnX.js.map → TurnsTab-BEsafACo.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/VectorCortexTab-DD1CMK80.js +2 -0
- package/extensions/dashboard-client/dist/assets/VectorCortexTab-DD1CMK80.js.map +1 -0
- package/extensions/dashboard-client/dist/assets/{WikiTab-1LcQrXk3.js → WikiTab-Bf01M2_Z.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{WikiTab-1LcQrXk3.js.map → WikiTab-Bf01M2_Z.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{button-DtEsZTUE.js → button-BEJPTk_E.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{button-DtEsZTUE.js.map → button-BEJPTk_E.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{card-DcfTmw-4.js → card-DK1V382s.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{card-DcfTmw-4.js.map → card-DK1V382s.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-BsIxUDyw.js → generateCategoricalChart-CRtaPphL.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-BsIxUDyw.js.map → generateCategoricalChart-CRtaPphL.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{index-B93cewiX.js → index-CB6BslE4.js} +34 -29
- package/extensions/dashboard-client/dist/assets/index-CB6BslE4.js.map +1 -0
- package/extensions/dashboard-client/dist/assets/index-CfvziyBi.css +1 -0
- package/extensions/dashboard-client/dist/assets/{switch-Bowd7jCD.js → switch-C4FV6B9k.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{switch-Bowd7jCD.js.map → switch-C4FV6B9k.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{toggle-Bo7kJZ4u.js → toggle-GBmeENMd.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{toggle-Bo7kJZ4u.js.map → toggle-GBmeENMd.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{useSSE-zNhb0c3u.js → useSSE-BOKZGSn1.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{useSSE-zNhb0c3u.js.map → useSSE-BOKZGSn1.js.map} +1 -1
- package/extensions/dashboard-client/dist/index.html +2 -2
- package/extensions/dashboard-client/src/App.tsx +2 -0
- package/extensions/dashboard-client/src/api/vector-cortex.ts +54 -0
- package/extensions/dashboard-client/src/tabs/VectorCortexTab.tsx +272 -0
- package/extensions/dashboard-client/src/tabs/registry.ts +4 -1
- package/extensions/dashboard-client/src/types/vector-cortex.ts +84 -0
- package/extensions/dashboard-client/tsconfig.json +1 -1
- package/extensions/dashboard-server/api-contracts/endpoints/registry-ext.ts +67 -0
- package/extensions/dashboard-server/api-contracts/endpoints/registry.ts +4 -21
- package/extensions/dashboard-server/api-contracts/index.ts +3 -0
- package/extensions/dashboard-server/api-contracts/vector-cortex.ts +136 -0
- package/extensions/dashboard-server/routes-rag-settings-helpers.ts +41 -0
- package/extensions/dashboard-server/routes-vector-cortex.ts +332 -0
- package/extensions/dashboard-server/routes.ts +6 -0
- package/extensions/dashboard-server/server.ts +8 -0
- package/extensions/mega-events/context-handler.ts +16 -0
- package/extensions/mega-runtime/vector-cortex-ledger.ts +165 -0
- package/extensions/mega-runtime/vector-cortex-safety.ts +181 -0
- package/package.json +2 -1
- package/src/config/vector-cortex.ts +98 -0
- package/src/config.ts +28 -0
- package/src/dedup/l1-lsh-v2.ts +78 -0
- package/src/dedup/l1-minhash-v2.ts +221 -0
- package/src/dedup/normalize.ts +1 -1
- package/src/store/sqlite/game-scores.ts +2 -1
- package/src/vector-cortex/conformance/emit.ts +56 -0
- package/src/vector-cortex/conformance/manifest.ts +298 -0
- package/src/vector-cortex/conformance/runner.ts +165 -0
- package/src/vector-cortex/conformance/triadB-reader.ts +110 -0
- package/src/vector-cortex/eval/annotations.ts +70 -0
- package/src/vector-cortex/eval/metrics.ts +113 -0
- package/src/vector-cortex/eval/observer.ts +86 -0
- package/src/vector-cortex/eval/persist.ts +73 -0
- package/src/vector-cortex/eval/reader.ts +45 -0
- package/src/vector-cortex/eval/types.ts +89 -0
- package/src/vector-cortex/ledger/adapter.ts +71 -0
- package/src/vector-cortex/ledger/compat-journal.ts +234 -0
- package/src/vector-cortex/ledger/emit.ts +86 -0
- package/src/vector-cortex/ledger/event-codec.ts +79 -0
- package/src/vector-cortex/ledger/event-codecB.ts +87 -0
- package/src/vector-cortex/ledger/sqlite.ts +265 -0
- package/src/vector-cortex/ledger/store.ts +380 -0
- package/src/vector-cortex/ledger/types.ts +141 -0
- package/src/vector-cortex/ledger/validator.ts +124 -0
- package/src/vector-cortex/migrations/effective-cut-v2.ts +149 -0
- package/src/vector-cortex/migrations/minhash-v2.ts +263 -0
- package/src/vector-cortex/migrations/occurrence-v2.ts +192 -0
- package/src/vector-cortex/replay/cut.ts +169 -0
- package/src/vector-cortex/replay/emit.ts +89 -0
- package/src/vector-cortex/replay/replay.ts +308 -0
- package/src/vector-cortex/replay/replayB.ts +97 -0
- package/src/vector-cortex/replay/types.ts +145 -0
- package/src/vector-cortex/resilience/breaker-core.ts +444 -0
- package/src/vector-cortex/resilience/breaker.ts +22 -0
- package/src/vector-cortex/resilience/emit.ts +99 -0
- package/src/vector-cortex/resilience/spool-core.ts +411 -0
- package/src/vector-cortex/resilience/spool.ts +22 -0
- package/src/vector-cortex/resilience/types.ts +158 -0
- package/extensions/dashboard-client/dist/assets/index-B93cewiX.js.map +0 -1
- package/extensions/dashboard-client/dist/assets/index-C_tCbOI0.css +0 -1
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* vector-cortex/ledger/types.ts — EventV2 / EventCodec byte-authority contract
|
|
3
|
+
* types, validation result codes, and the registered EVT conformance ID range.
|
|
4
|
+
*
|
|
5
|
+
* Owned by VC1A (canonical byte events). Consumes only reviewer-accepted
|
|
6
|
+
* predecessor contracts and [common contracts](../../CONTRACTS.md §EventV2),
|
|
7
|
+
* which are NORMATIVE here. `originalBytes` and its SHA-256 digest are the byte
|
|
8
|
+
* authority; strict UTF-8 classification is never lossy; `canonicalNfc` is a
|
|
9
|
+
* DERIVED comparison/search key only (never identity, digest, or reconstruction).
|
|
10
|
+
*
|
|
11
|
+
* Pure type/schema definitions + a short pure digest/classify predicate runtime
|
|
12
|
+
* (validator codes). No network, no side effects (PREVENT-PI-004 / PREVENT-011).
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/** SHA-256 digest over the authoritative `originalBytes`, `sha256:<hex>`. */
|
|
16
|
+
export type BytesDigest = `sha256:${string}`;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* EventV2 — the neutral byte-authority ledger occurrence. `schema:"event-v2"`
|
|
20
|
+
* is the discriminant tag of the union. Two events whose bytes differ by NFC
|
|
21
|
+
* normalization are DISTINCT identities (different `originalBytes`, different
|
|
22
|
+
* `bytesDigest`); their `canonicalNfc` (derived) may coincide but never drives
|
|
23
|
+
* equality, hashing, or byte reconstruction.
|
|
24
|
+
*/
|
|
25
|
+
export interface EventV2 {
|
|
26
|
+
schema: "event-v2";
|
|
27
|
+
sessionId: string;
|
|
28
|
+
seq: bigint;
|
|
29
|
+
eventId: string;
|
|
30
|
+
role: "policy" | "user" | "assistant" | "tool";
|
|
31
|
+
kind: string;
|
|
32
|
+
/** Authoritative original event bytes (byte authority). */
|
|
33
|
+
originalBytes: Uint8Array;
|
|
34
|
+
/** DigitalObjectIdentifier over originalBytes (authoritative digest). */
|
|
35
|
+
bytesDigest: BytesDigest;
|
|
36
|
+
/**
|
|
37
|
+
* Strict UTF-8 classification (NO lossy replacement). Invalid input is
|
|
38
|
+
* represented only as `{valid:false, base64}`.
|
|
39
|
+
*/
|
|
40
|
+
utf8: { valid: true; text: string } | { valid: false; base64: string };
|
|
41
|
+
/** DERIVED NFC comparison/search key, valid UTF-8 only. Never identity. */
|
|
42
|
+
canonicalNfc?: string;
|
|
43
|
+
/** On a tool RESULT, references exactly one earlier CALL in this session. */
|
|
44
|
+
toolCallId?: string;
|
|
45
|
+
/** Wall-clock occurrence timestamp (monotonic for ordering; not the sort key). */
|
|
46
|
+
occurredAtMs: bigint;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Inputs to the byte-authority encoder. `bytes` is the sole byte source. */
|
|
50
|
+
export interface EventEncodeInput {
|
|
51
|
+
sessionId: string;
|
|
52
|
+
seq: bigint;
|
|
53
|
+
eventId: string;
|
|
54
|
+
role: "policy" | "user" | "assistant" | "tool";
|
|
55
|
+
kind: string;
|
|
56
|
+
bytes: Uint8Array;
|
|
57
|
+
toolCallId?: string;
|
|
58
|
+
occurredAtMs: bigint;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* EventCodec — byte-authority contract (normative, [CONTRACTS §EventV2]).
|
|
63
|
+
* `encode` computes the SHA-256 digest + strict UTF-8 classification + derived
|
|
64
|
+
* NFC; `decode` returns the authoritative `originalBytes` unchanged. Decoding
|
|
65
|
+
* never reconstructs bytes from normalized text — only from originalBytes.
|
|
66
|
+
*/
|
|
67
|
+
export interface EventCodec {
|
|
68
|
+
encode(input: EventEncodeInput): EventV2;
|
|
69
|
+
decode(event: EventV2): Uint8Array;
|
|
70
|
+
/**
|
|
71
|
+
* Strict UTF-8 classification: `fatal` decode succeeds, or the raw bytes are
|
|
72
|
+
* reported as `{valid:false, base64}` — never replacement-decode to U+FFFD.
|
|
73
|
+
*/
|
|
74
|
+
classifyUtf8(bytes: Uint8Array): { valid: true; text: string } | { valid: false; base64: string };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Canonical validator failure codes (VC1A). */
|
|
78
|
+
export type ValidationCode =
|
|
79
|
+
/** sha256(originalBytes) !== bytesDigest (authority corruption). */
|
|
80
|
+
| "EVT_DIGEST_MISMATCH"
|
|
81
|
+
/** The stored `utf8` discriminant contradicts a strict re-classification. */
|
|
82
|
+
| "EVT_UTF8_TAG_INVALID"
|
|
83
|
+
/** Duplicate (sessionId, seq, eventId) occurrence. */
|
|
84
|
+
| "EVT_DUPLICATE_ID";
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Deterministic validation result. `ok:false` carries the deduplicated failure
|
|
88
|
+
* codes (fixed priority order) AND the per-occurrence `issues` with real
|
|
89
|
+
* locators (sessionId/seq/eventId) so consumers can identify WHICH event failed.
|
|
90
|
+
*/
|
|
91
|
+
export type ValidationResult =
|
|
92
|
+
| { ok: true; ordered: readonly EventV2[] }
|
|
93
|
+
| { ok: false; codes: readonly ValidationCode[]; issues: readonly ValidationIssue[] };
|
|
94
|
+
|
|
95
|
+
/** A single flagged validation issue (code + the offending occurrence locator). */
|
|
96
|
+
export interface ValidationIssue {
|
|
97
|
+
readonly code: ValidationCode;
|
|
98
|
+
readonly sessionId: string;
|
|
99
|
+
readonly seq: bigint;
|
|
100
|
+
readonly eventId: string;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Registered EVT conformance ID range (EVT-001..030). The acceptance test reads
|
|
105
|
+
* these rows from the v2 manifest and asserts each returns its manifest bytes or
|
|
106
|
+
* exactly its listed failure code. Mirrors CUT_IDS / M3_IDS in replay/types.ts.
|
|
107
|
+
* EVT-001..015 are owned by VC1A (codec/validator); EVT-016..030 are owned by
|
|
108
|
+
* VC1B (occurrence ledger, see ledger/store.ts).
|
|
109
|
+
*/
|
|
110
|
+
export const EVT_IDS = [
|
|
111
|
+
"EVT-001",
|
|
112
|
+
"EVT-002",
|
|
113
|
+
"EVT-003",
|
|
114
|
+
"EVT-004",
|
|
115
|
+
"EVT-005",
|
|
116
|
+
"EVT-006",
|
|
117
|
+
"EVT-007",
|
|
118
|
+
"EVT-008",
|
|
119
|
+
"EVT-009",
|
|
120
|
+
"EVT-010",
|
|
121
|
+
"EVT-011",
|
|
122
|
+
"EVT-012",
|
|
123
|
+
"EVT-013",
|
|
124
|
+
"EVT-014",
|
|
125
|
+
"EVT-015",
|
|
126
|
+
"EVT-016",
|
|
127
|
+
"EVT-017",
|
|
128
|
+
"EVT-018",
|
|
129
|
+
"EVT-019",
|
|
130
|
+
"EVT-020",
|
|
131
|
+
"EVT-021",
|
|
132
|
+
"EVT-022",
|
|
133
|
+
"EVT-023",
|
|
134
|
+
"EVT-024",
|
|
135
|
+
"EVT-025",
|
|
136
|
+
"EVT-026",
|
|
137
|
+
"EVT-027",
|
|
138
|
+
"EVT-028",
|
|
139
|
+
"EVT-029",
|
|
140
|
+
"EVT-030",
|
|
141
|
+
] as const;
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* vector-cortex/ledger/validator.ts — EventV2 canonical validation (VC1A).
|
|
3
|
+
*
|
|
4
|
+
* Canonical ordering is `(sessionId, seq, eventId bytewise UTF-8)`: the sort is
|
|
5
|
+
* by the eventId's UTF-8 BYTES (unsigned) — NOT by JS string code-unit order —
|
|
6
|
+
* so multi-byte eventIds sort bytewise. Deterministic failure detection with a
|
|
7
|
+
* fixed priority order:
|
|
8
|
+
* 1. EVT_DIGEST_MISMATCH — sha256(originalBytes) !== bytesDigest
|
|
9
|
+
* 2. EVT_UTF8_TAG_INVALID — stored `utf8` discriminant contradicting a strict
|
|
10
|
+
* fatal re-classification of originalBytes
|
|
11
|
+
* 3. EVT_DUPLICATE_ID — duplicate (sessionId, seq, eventId) occurrence
|
|
12
|
+
*
|
|
13
|
+
* The unique failure injection requirement: flip ONE stored byte while retaining
|
|
14
|
+
* the SHA-256 signature — the digest recomputation diverges and the validator
|
|
15
|
+
* returns EVT_DIGEST_MISMATCH (never a lossy replacement text, which is not
|
|
16
|
+
* produced anywhere in this module).
|
|
17
|
+
*
|
|
18
|
+
* Pure/deterministic — no console, no network, no side effects (PREVENT-PI-004).
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import nodeCrypto from "node:crypto";
|
|
22
|
+
import { classifyUtf8 } from "./event-codec.js";
|
|
23
|
+
import type { BytesDigest, EventV2, ValidationCode, ValidationIssue, ValidationResult } from "./types.js";
|
|
24
|
+
|
|
25
|
+
/** Mode-A digest recompute (validator uses the codec's canonical digest rule). */
|
|
26
|
+
function digestOf(bytes: Uint8Array): BytesDigest {
|
|
27
|
+
const hex = nodeCrypto.createHash("sha256").update(bytes).digest("hex");
|
|
28
|
+
return `sha256:${hex}`;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Bytewise UTF-8 comparator for eventId tiebreak (unsigned bytes, not code units). */
|
|
32
|
+
function compareEventIdBytes(a: string, b: string): number {
|
|
33
|
+
const ab = Buffer.from(a, "utf8");
|
|
34
|
+
const bb = Buffer.from(b, "utf8");
|
|
35
|
+
const n = Math.min(ab.length, bb.length);
|
|
36
|
+
for (let i = 0; i < n; i++) {
|
|
37
|
+
if (ab[i] !== bb[i]) return ab[i] < bb[i] ? -1 : 1;
|
|
38
|
+
}
|
|
39
|
+
if (ab.length !== bb.length) return ab.length < bb.length ? -1 : 1;
|
|
40
|
+
return 0;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Comparator: `(sessionId, seq, eventId bytewise UTF-8)`. */
|
|
44
|
+
export function compareEvents(a: EventV2, b: EventV2): number {
|
|
45
|
+
if (a.sessionId !== b.sessionId) return a.sessionId < b.sessionId ? -1 : 1;
|
|
46
|
+
if (a.seq !== b.seq) return a.seq < b.seq ? -1 : 1;
|
|
47
|
+
return compareEventIdBytes(a.eventId, b.eventId);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Ascending (sessionId, seq, eventId-bytes) sort. Returns a new array. */
|
|
51
|
+
export function sortEvents(events: readonly EventV2[]): EventV2[] {
|
|
52
|
+
return [...events].sort(compareEvents);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Recompute the digest and compare to the stored one (authority corruption). */
|
|
56
|
+
function digestMismatch(event: EventV2): boolean {
|
|
57
|
+
return digestOf(event.originalBytes) !== event.bytesDigest;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The stored utf8 discriminant must match a strict fatal re-classification. */
|
|
61
|
+
function utf8TagMismatch(event: EventV2): boolean {
|
|
62
|
+
const cls = classifyUtf8(event.originalBytes);
|
|
63
|
+
const stored = event.utf8;
|
|
64
|
+
if (stored.valid !== cls.valid) return true;
|
|
65
|
+
if (!stored.valid) {
|
|
66
|
+
// Both invalid: never compare decoded text; only the (valid, base64) shape.
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
if (!cls.valid) return true; // unreachable given `stored.valid === cls.valid`
|
|
70
|
+
// Both valid: compare the strict-decoded TEXT (no NFC — the tag stores raw text).
|
|
71
|
+
return stored.text !== cls.text;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Validate a batch of events. Returns `{ok:true, ordered}` when every event
|
|
76
|
+
* passes digest + UTF-8-tag consistency and no duplicate occurrence exists;
|
|
77
|
+
* otherwise `{ok:false, codes}` with the failure codes in fixed priority order,
|
|
78
|
+
* deduplicated, and an explicit issue list for diagnostics.
|
|
79
|
+
*/
|
|
80
|
+
export function validateEvents(events: readonly EventV2[]): ValidationResult {
|
|
81
|
+
const issues: ValidationIssue[] = [];
|
|
82
|
+
|
|
83
|
+
// Fixed priority order: DIGEST_MISMATCH, UTF8_TAG_INVALID, DUPLICATE_ID.
|
|
84
|
+
for (const e of events) {
|
|
85
|
+
if (digestMismatch(e)) {
|
|
86
|
+
issues.push({ code: "EVT_DIGEST_MISMATCH", sessionId: e.sessionId, seq: e.seq, eventId: e.eventId });
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
for (const e of events) {
|
|
90
|
+
if (utf8TagMismatch(e)) {
|
|
91
|
+
issues.push({ code: "EVT_UTF8_TAG_INVALID", sessionId: e.sessionId, seq: e.seq, eventId: e.eventId });
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Unambiguous (sessionId, seq, eventId) occurrence key (seq stringified — a
|
|
96
|
+
// bigint cannot be JSON-serialized directly).
|
|
97
|
+
const key = (e: EventV2): string => JSON.stringify([e.sessionId, e.seq.toString(), e.eventId]);
|
|
98
|
+
const seen = new Set<string>();
|
|
99
|
+
for (const e of sortEvents(events)) {
|
|
100
|
+
const k = key(e);
|
|
101
|
+
if (seen.has(k)) {
|
|
102
|
+
issues.push({ code: "EVT_DUPLICATE_ID", sessionId: e.sessionId, seq: e.seq, eventId: e.eventId });
|
|
103
|
+
}
|
|
104
|
+
seen.add(k);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
if (issues.length === 0) {
|
|
108
|
+
return { ok: true, ordered: sortEvents(events) };
|
|
109
|
+
}
|
|
110
|
+
// Surface the per-occurrence issues (real locators) alongside the deduped
|
|
111
|
+
// codes so the adapter/observability feed can name WHICH event failed.
|
|
112
|
+
return { ok: false, codes: dedupe(issues.map((i) => i.code)), issues };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function dedupe(codes: ValidationCode[]): ValidationCode[] {
|
|
116
|
+
const out: ValidationCode[] = [];
|
|
117
|
+
for (const c of codes) {
|
|
118
|
+
if (!out.includes(c)) out.push(c);
|
|
119
|
+
}
|
|
120
|
+
return out;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Export the canonical ordering comparator for consumers (replay etc.). */
|
|
124
|
+
export { compareEventIdBytes };
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* vector-cortex/migrations/effective-cut-v2.ts — M3 copy/validate/switch
|
|
3
|
+
* migration (VC0B).
|
|
4
|
+
*
|
|
5
|
+
* Freezes the v2 effective replay cut: `min(boundarySafeSeq, committedSeq,
|
|
6
|
+
* capturedHighWater)` with pair retreat and anchor floor. The migration copies
|
|
7
|
+
* the candidate into the staged slot, validates the STAGED pointer against the
|
|
8
|
+
* minima and pair/anchor invariants (plus copy-match), and ONLY THEN atomically
|
|
9
|
+
* switches the active pointer. The three phases are exposed separately so a
|
|
10
|
+
* crash between validate and switch retains the OLD pointer and a restart
|
|
11
|
+
* resumes idempotently (the unique failure-injection contract).
|
|
12
|
+
*
|
|
13
|
+
* This is an internal developer seam: no dashboard/API change is necessary. It
|
|
14
|
+
* operates against the EXISTING host state via an injected M3Host interface —
|
|
15
|
+
* the future v2 compat-journal is owned by VC1B and is not introduced here.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { computeEffectiveCutV2 } from "../replay/cut.js";
|
|
19
|
+
import type { ReplayToolPair, ReplayRetreatCode } from "../replay/types.js";
|
|
20
|
+
|
|
21
|
+
/** Migration failure codes (registered in M3-001..010 as conformance rows). */
|
|
22
|
+
export const M3_FAIL = {
|
|
23
|
+
MISSING_HOST: "M3_HOST_MISSING",
|
|
24
|
+
INVALID_MINIMA: "M3_MINIMA_VIOLATED",
|
|
25
|
+
PAIR_SPLIT: "M3_PAIR_SPLIT",
|
|
26
|
+
ANCHOR_CROSSED: "M3_ANCHOR_CROSSED",
|
|
27
|
+
COPY_MISMATCH: "M3_COPY_MISMATCH",
|
|
28
|
+
} as const;
|
|
29
|
+
export type M3FailureCode = (typeof M3_FAIL)[keyof typeof M3_FAIL];
|
|
30
|
+
|
|
31
|
+
/** Live seq inputs that parameterize the effective cut. */
|
|
32
|
+
export interface M3CutInput {
|
|
33
|
+
readonly requestedSeq: bigint;
|
|
34
|
+
readonly boundarySafeSeq: bigint;
|
|
35
|
+
readonly committedSeq: bigint;
|
|
36
|
+
readonly capturedHighWater: bigint;
|
|
37
|
+
readonly anchorFloor: bigint;
|
|
38
|
+
readonly pairs: readonly ReplayToolPair[];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Host state the migration reads/writes. copy/validate are read-only over host;
|
|
43
|
+
* switch is the only mutating step (atomically activates the staged pointer).
|
|
44
|
+
*/
|
|
45
|
+
export interface M3Host {
|
|
46
|
+
/** Actively used cut pointer (legacy prior). Never changes before switch. */
|
|
47
|
+
readonly oldPointer: bigint | null;
|
|
48
|
+
/** Persist the staged (new) cut pointer WITHOUT activating it. */
|
|
49
|
+
writeStaged(pointer: bigint): void;
|
|
50
|
+
/** The currently staged (new) pointer, persisted across restarts. */
|
|
51
|
+
stagedPointer(): bigint | null;
|
|
52
|
+
/** Contiguous durable authority high-water (min source). */
|
|
53
|
+
committedSeq(): bigint;
|
|
54
|
+
/** Atomic switch: activate the staged pointer and freeze the prior one. */
|
|
55
|
+
switchPointer(pointer: bigint): void;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface M3ValidateResult {
|
|
59
|
+
readonly ok: boolean;
|
|
60
|
+
readonly codes: readonly M3FailureCode[];
|
|
61
|
+
readonly retreats: readonly { code: ReplayRetreatCode; fromSeq: bigint; toSeq: bigint }[];
|
|
62
|
+
readonly effectiveSeq: bigint;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Pure effective-cut computation (min-of-three + retreat + floor). */
|
|
66
|
+
export function m3Compute(input: M3CutInput): bigint {
|
|
67
|
+
return computeEffectiveCutV2(input).cut.effectiveSeq;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Phase 1 — copy: compute the candidate effective cut and stage it via the host
|
|
72
|
+
* (without activating). Returns the staged seq.
|
|
73
|
+
*/
|
|
74
|
+
export function m3Copy(host: M3Host, input: M3CutInput): bigint {
|
|
75
|
+
const effective = m3Compute(input);
|
|
76
|
+
host.writeStaged(effective);
|
|
77
|
+
return effective;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Phase 2 — validate: the host's STAGED pointer must equal the freshly computed
|
|
82
|
+
* effective cut (copy-match), respect the minima, not split a pair, and never
|
|
83
|
+
* fall below the anchor floor. Failure codes:
|
|
84
|
+
* M3_HOST_MISSING — no staged pointer at all
|
|
85
|
+
* M3_COPY_MISMATCH — staged != freshly computed effective
|
|
86
|
+
* M3_MINIMA_VIOLATED — effective exceeds a source minimum (or requested)
|
|
87
|
+
* M3_PAIR_SPLIT — effective splits a tool call/result pair
|
|
88
|
+
* M3_ANCHOR_CROSSED — effective is below the anchor floor
|
|
89
|
+
*/
|
|
90
|
+
export function m3Validate(host: M3Host, input: M3CutInput): M3ValidateResult {
|
|
91
|
+
const codes: M3FailureCode[] = [];
|
|
92
|
+
const { cut, retreats } = computeEffectiveCutV2(input);
|
|
93
|
+
const expected = cut.effectiveSeq;
|
|
94
|
+
|
|
95
|
+
const staged = host.stagedPointer();
|
|
96
|
+
if (staged === null) {
|
|
97
|
+
codes.push(M3_FAIL.MISSING_HOST);
|
|
98
|
+
} else {
|
|
99
|
+
if (staged !== expected) codes.push(M3_FAIL.COPY_MISMATCH);
|
|
100
|
+
if (
|
|
101
|
+
staged > input.boundarySafeSeq ||
|
|
102
|
+
staged > host.committedSeq() ||
|
|
103
|
+
staged > input.capturedHighWater ||
|
|
104
|
+
staged > input.requestedSeq
|
|
105
|
+
) {
|
|
106
|
+
codes.push(M3_FAIL.INVALID_MINIMA);
|
|
107
|
+
}
|
|
108
|
+
for (const p of input.pairs) {
|
|
109
|
+
if (p.callSeq <= staged && staged < p.resultSeq) {
|
|
110
|
+
codes.push(M3_FAIL.PAIR_SPLIT);
|
|
111
|
+
break;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
if (staged < input.anchorFloor) codes.push(M3_FAIL.ANCHOR_CROSSED);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
return {
|
|
118
|
+
ok: codes.length === 0,
|
|
119
|
+
codes,
|
|
120
|
+
retreats,
|
|
121
|
+
effectiveSeq: expected,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Phase 3 — switch: atomic activation of the staged pointer. Only call after
|
|
127
|
+
* m3Validate reports ok; the host performs the durable pointer flip.
|
|
128
|
+
*/
|
|
129
|
+
export function m3Switch(host: M3Host, input: M3CutInput): bigint {
|
|
130
|
+
const effective = m3Compute(input);
|
|
131
|
+
host.switchPointer(effective);
|
|
132
|
+
return effective;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Run the full copy-validate-switch migration against a host. On validation
|
|
137
|
+
* failure the switch is NOT performed and the host retains its previous pointer
|
|
138
|
+
* (crash-safety / copy-validate-switch).
|
|
139
|
+
*/
|
|
140
|
+
export function migrateEffectiveCutV2(
|
|
141
|
+
host: M3Host,
|
|
142
|
+
input: M3CutInput,
|
|
143
|
+
): { ok: boolean; codes: readonly M3FailureCode[]; effectiveSeq: bigint } {
|
|
144
|
+
m3Copy(host, input);
|
|
145
|
+
const v = m3Validate(host, input);
|
|
146
|
+
if (!v.ok) return { ok: false, codes: v.codes, effectiveSeq: v.effectiveSeq };
|
|
147
|
+
m3Switch(host, input);
|
|
148
|
+
return { ok: true, codes: [], effectiveSeq: v.effectiveSeq };
|
|
149
|
+
}
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* vector-cortex/migrations/minhash-v2.ts — M4 MinHashV2 copy/validate/switch
|
|
3
|
+
* migration (VC1C).
|
|
4
|
+
*
|
|
5
|
+
* M4 versions the L1 dedup signature store: v2 signatures/buckets are written
|
|
6
|
+
* BESIDE v1, backfilled by checkpoint id, verified, and only then switched as
|
|
7
|
+
* the active version. It follows the same copy/validate/switch + resume
|
|
8
|
+
* contract as M2 but for the minhash index:
|
|
9
|
+
*
|
|
10
|
+
* - batch: writes v2 signatures + buckets for a set of checkpoint IDs, each
|
|
11
|
+
* tagged with the frozen version 2; never touches v1 rows.
|
|
12
|
+
* - backfill: resumable by checkpoint id — an interrupted run resumes without
|
|
13
|
+
* duplicate v2 signatures or active-pointer drift.
|
|
14
|
+
* - verify: counts per checkpoint match v1 and every v2 digest re-hashes.
|
|
15
|
+
* - switch: atomically flips the ACTIVE VERSION pointer from v1 to v2; until
|
|
16
|
+
* a verified switch, v1 remains active (interruption keeps old authority).
|
|
17
|
+
*
|
|
18
|
+
* Cross-version compare is REJECTED: a mixed v1-v2 similarity/bucket query
|
|
19
|
+
* returns `MINHASH_VERSION_MISMATCH` (never compares v1/v2 signatures).
|
|
20
|
+
*
|
|
21
|
+
* Pure logic over an injected M4Host (deterministic + testable; no console).
|
|
22
|
+
* PREVENT-002/011/PI-004 honored.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import { createHash } from "node:crypto";
|
|
26
|
+
import {
|
|
27
|
+
MINHASH_VERSION,
|
|
28
|
+
minhashV2Signature,
|
|
29
|
+
encodeSignatureV2,
|
|
30
|
+
} from "../../dedup/l1-minhash-v2.js";
|
|
31
|
+
import {
|
|
32
|
+
lshBandsV2,
|
|
33
|
+
BANDS_V2,
|
|
34
|
+
SIGNATURE_BYTES_EXPECTED_V2,
|
|
35
|
+
} from "../../dedup/l1-lsh-v2.js";
|
|
36
|
+
import {
|
|
37
|
+
createConformanceReporter,
|
|
38
|
+
type ConformanceReporter,
|
|
39
|
+
} from "../conformance/emit.js";
|
|
40
|
+
|
|
41
|
+
/** M4 failure codes. */
|
|
42
|
+
export const M4_FAIL = {
|
|
43
|
+
VERSION_MISMATCH: "MINHASH_VERSION_MISMATCH",
|
|
44
|
+
BACKFILL_PARTIAL: "M4_BACKFILL_PARTIAL",
|
|
45
|
+
COUNT_MISMATCH: "M4_COUNT_MISMATCH",
|
|
46
|
+
DIGEST_MISMATCH: "M4_DIGEST_MISMATCH",
|
|
47
|
+
} as const;
|
|
48
|
+
export type M4MigrationCode = (typeof M4_FAIL)[keyof typeof M4_FAIL];
|
|
49
|
+
|
|
50
|
+
/** A v2 signature row stored beside v1 (keyed by checkpoint id). */
|
|
51
|
+
export interface V2SignatureRow {
|
|
52
|
+
readonly checkpointId: string;
|
|
53
|
+
readonly sessionId: string;
|
|
54
|
+
readonly version: number; // MINHASH_VERSION
|
|
55
|
+
readonly signatureBytes: Uint8Array; // 2048 LE bytes
|
|
56
|
+
readonly digest: string; // sha256: over signatureBytes
|
|
57
|
+
readonly buckets: readonly string[]; // 64 band keys
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The host the migration reads from / writes to (capability-shaped). */
|
|
61
|
+
export interface M4Host {
|
|
62
|
+
/** Full set of v1 checkpoint ids the index should cover. */
|
|
63
|
+
readonly v1CheckpointIds: () => readonly string[];
|
|
64
|
+
/** Session id a checkpoint belongs to (for bucket scoping). */
|
|
65
|
+
readonly sessionOf: (checkpointId: string) => string;
|
|
66
|
+
/** The raw source text for a checkpoint (to recompute a v2 signature). */
|
|
67
|
+
readonly sourceOf: (checkpointId: string) => string;
|
|
68
|
+
/** Persisted v2 rows already written (for resume/dedup + active pointer). */
|
|
69
|
+
readonly storedV2: () => readonly V2SignatureRow[];
|
|
70
|
+
/** The currently ACTIVE version (1 until a verified switch). */
|
|
71
|
+
readonly activeVersion: () => number;
|
|
72
|
+
/** Idempotent write of v2 rows (never mutates v1 rows). */
|
|
73
|
+
readonly putV2: (rows: readonly V2SignatureRow[]) => void;
|
|
74
|
+
/** Atomically switch the active version pointer to v2. */
|
|
75
|
+
readonly switchToV2: () => void;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** An M4 migration failure result. */
|
|
79
|
+
export interface M4ValidateResult {
|
|
80
|
+
readonly ok: boolean;
|
|
81
|
+
readonly codes: readonly M4MigrationCode[];
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Reject a cross-version compare. Returns the frozen mismatch code. */
|
|
85
|
+
export function crossVersionError(): M4MigrationCode {
|
|
86
|
+
return M4_FAIL.VERSION_MISMATCH;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Compute v2 signature + buckets for one checkpoint (the authoritative bytes).
|
|
91
|
+
* Pure and cross-language deterministic.
|
|
92
|
+
*/
|
|
93
|
+
export function computeV2Row(host: M4Host, checkpointId: string): V2SignatureRow {
|
|
94
|
+
const sessionId = host.sessionOf(checkpointId);
|
|
95
|
+
const source = host.sourceOf(checkpointId);
|
|
96
|
+
const sig = minhashV2Signature(source);
|
|
97
|
+
const bytes = encodeSignatureV2(sig);
|
|
98
|
+
const buckets = lshBandsV2(new Uint8Array(bytes), sessionId);
|
|
99
|
+
return {
|
|
100
|
+
checkpointId,
|
|
101
|
+
sessionId,
|
|
102
|
+
version: MINHASH_VERSION,
|
|
103
|
+
signatureBytes: new Uint8Array(bytes),
|
|
104
|
+
digest: `sha256:${sha256Hex(bytes)}`,
|
|
105
|
+
buckets,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function sha256Hex(bytes: Uint8Array): string {
|
|
110
|
+
return createHash("sha256").update(bytes).digest("hex");
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Backfill v2 signatures/buckets for all v1 checkpoint ids (resumable): rows
|
|
115
|
+
* already persisted with matching v2 digest/version are left untouched (no
|
|
116
|
+
* duplicates), and the active pointer stays at v1 until a verified switch.
|
|
117
|
+
* Returns the rows written this call (delta), never duplicates.
|
|
118
|
+
*
|
|
119
|
+
* An EXISTING row is re-computed and digest-verified before it is skipped; if
|
|
120
|
+
* the persisted row is corrupt (wrong version, wrong length, or a digest that
|
|
121
|
+
* no longer re-hashes its signatureBytes — e.g. a crash mid-write that left a
|
|
122
|
+
* truncated/bad row for an already-present id), it is recomputed and rewritten
|
|
123
|
+
* so corruption self-heals instead of being frozen by a later `m4Verify` failure.
|
|
124
|
+
*/
|
|
125
|
+
export function m4Backfill(
|
|
126
|
+
host: M4Host,
|
|
127
|
+
reporter: ConformanceReporter = createConformanceReporter(),
|
|
128
|
+
): readonly V2SignatureRow[] {
|
|
129
|
+
const wanted = host.v1CheckpointIds();
|
|
130
|
+
const existing = new Map(host.storedV2().map((r) => [r.checkpointId, r]));
|
|
131
|
+
const writes: V2SignatureRow[] = [];
|
|
132
|
+
for (const id of wanted) {
|
|
133
|
+
const row = computeV2Row(host, id);
|
|
134
|
+
const stored = existing.get(id);
|
|
135
|
+
if (stored !== undefined && v2RowMatches(stored, row)) continue; // healthy, no dup
|
|
136
|
+
writes.push(row); // absent, or stored row is corrupt -> (re)compute authoritative bytes
|
|
137
|
+
}
|
|
138
|
+
if (writes.length > 0) {
|
|
139
|
+
host.putV2(writes);
|
|
140
|
+
reporter.backfilled({
|
|
141
|
+
written: writes.length,
|
|
142
|
+
checkpointIds: writes.map((r) => r.checkpointId),
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
return writes;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** True when a persisted row already matches the authoritative recompute. */
|
|
149
|
+
function v2RowMatches(stored: V2SignatureRow, fresh: V2SignatureRow): boolean {
|
|
150
|
+
return (
|
|
151
|
+
stored.version === MINHASH_VERSION &&
|
|
152
|
+
stored.checkpointId === fresh.checkpointId &&
|
|
153
|
+
stored.sessionId === fresh.sessionId &&
|
|
154
|
+
stored.signatureBytes.length === fresh.signatureBytes.length &&
|
|
155
|
+
stored.digest === fresh.digest &&
|
|
156
|
+
bucketsMatch(stored)
|
|
157
|
+
);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Re-derive the 64 bucket keys from the row's signatureBytes + sessionId and
|
|
162
|
+
* compare every value to the stored buckets. This closes a defensive
|
|
163
|
+
* verification gap: a persisted row whose signatureBytes + digest are correct
|
|
164
|
+
* but whose bucket VALUES were written wrong (a writer defect, or a partial
|
|
165
|
+
* bucket write that still held 64 entries) would otherwise pass digest+count
|
|
166
|
+
* checks and be treated as healthy — yet the buckets are exactly the data the
|
|
167
|
+
* live LSH-dedup path queries. Buckets are deterministic from sigBytes +
|
|
168
|
+
* sessionId, so a mismatch is always a real storage/author defect.
|
|
169
|
+
*/
|
|
170
|
+
function bucketsMatch(row: V2SignatureRow): boolean {
|
|
171
|
+
// A wrong-length signature can't be banded (lshBandsV2 throws); the caller
|
|
172
|
+
// already reports it as a count/version mismatch, so fail closed here too.
|
|
173
|
+
if (row.signatureBytes.length !== SIGNATURE_BYTES_EXPECTED_V2) return false;
|
|
174
|
+
if (row.buckets.length !== BANDS_V2) return false;
|
|
175
|
+
const expected = lshBandsV2(new Uint8Array(row.signatureBytes), row.sessionId);
|
|
176
|
+
for (let i = 0; i < BANDS_V2; i++) {
|
|
177
|
+
if ((expected[i] as string) !== (row.buckets[i] as string)) return false;
|
|
178
|
+
}
|
|
179
|
+
return true;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Verify the backfilled v2 index: every v1 checkpoint has exactly one v2 row
|
|
184
|
+
* (reset -> resumable partial counts), each stored row's digest re-hashes, and
|
|
185
|
+
* each row has all 64 buckets. Never mutates.
|
|
186
|
+
*/
|
|
187
|
+
export function m4Verify(host: M4Host): M4ValidateResult {
|
|
188
|
+
const codes: M4MigrationCode[] = [];
|
|
189
|
+
const wanted = new Set(host.v1CheckpointIds());
|
|
190
|
+
const stored = host.storedV2();
|
|
191
|
+
const counts = new Map<string, number>();
|
|
192
|
+
for (const r of stored) {
|
|
193
|
+
counts.set(r.checkpointId, (counts.get(r.checkpointId) ?? 0) + 1);
|
|
194
|
+
if (r.version !== MINHASH_VERSION) codes.push(M4_FAIL.VERSION_MISMATCH);
|
|
195
|
+
if (r.signatureBytes.length !== 2048) codes.push(M4_FAIL.COUNT_MISMATCH);
|
|
196
|
+
if (r.buckets.length !== BANDS_V2) codes.push(M4_FAIL.COUNT_MISMATCH);
|
|
197
|
+
if (r.digest !== `sha256:${sha256Hex(r.signatureBytes)}`) {
|
|
198
|
+
codes.push(M4_FAIL.DIGEST_MISMATCH);
|
|
199
|
+
}
|
|
200
|
+
// Bucket VALUE verification: re-derive all 64 keys from signatureBytes +
|
|
201
|
+
// sessionId and compare them. Digest + count alone would let a row with
|
|
202
|
+
// correct sigBytes/digest but wrong bucket values pass; the buckets are the
|
|
203
|
+
// data the live LSH-dedup path queries, so a drifts here is a real defect.
|
|
204
|
+
if (!bucketsMatch(r)) codes.push(M4_FAIL.COUNT_MISMATCH);
|
|
205
|
+
}
|
|
206
|
+
// Every v1 checkpoint backfilled exactly once (count parity, no dup rows).
|
|
207
|
+
for (const id of wanted) {
|
|
208
|
+
const c = counts.get(id) ?? 0;
|
|
209
|
+
if (c === 0) codes.push(M4_FAIL.BACKFILL_PARTIAL);
|
|
210
|
+
if (c > 1) codes.push(M4_FAIL.COUNT_MISMATCH);
|
|
211
|
+
}
|
|
212
|
+
// No orphan v2 rows without a v1 checkpoint.
|
|
213
|
+
for (const id of counts.keys()) {
|
|
214
|
+
if (!wanted.has(id)) codes.push(M4_FAIL.COUNT_MISMATCH);
|
|
215
|
+
}
|
|
216
|
+
const ok = codes.length === 0;
|
|
217
|
+
return { ok, codes: dedupe(codes) };
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Switch the active version to v2. Only call after `m4Verify` reports ok; a
|
|
222
|
+
* crash/return before switch leaves v1 active (interruption keeps old
|
|
223
|
+
* authority, resumable idempotently).
|
|
224
|
+
*/
|
|
225
|
+
export function m4Switch(host: M4Host): void {
|
|
226
|
+
host.switchToV2();
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** Full M4 lifecycle: backfill -> verify -> switch; returns verify result. */
|
|
230
|
+
export function migrateMinhashV2(
|
|
231
|
+
host: M4Host,
|
|
232
|
+
reporter: ConformanceReporter = createConformanceReporter(),
|
|
233
|
+
): M4ValidateResult {
|
|
234
|
+
m4Backfill(host, reporter);
|
|
235
|
+
const v = m4Verify(host);
|
|
236
|
+
if (v.ok) m4Switch(host);
|
|
237
|
+
return v;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** Registered M4 conformance ID range (M4-001..008 + named M4-*). */
|
|
241
|
+
export const M4_IDS = [
|
|
242
|
+
"M4-001",
|
|
243
|
+
"M4-002",
|
|
244
|
+
"M4-003",
|
|
245
|
+
"M4-004",
|
|
246
|
+
"M4-005",
|
|
247
|
+
"M4-006",
|
|
248
|
+
"M4-007",
|
|
249
|
+
"M4-008",
|
|
250
|
+
] as const;
|
|
251
|
+
|
|
252
|
+
/** Registered named M4 conformance IDs. */
|
|
253
|
+
export const M4_NAMED = [
|
|
254
|
+
"M4-HIGHBIT-001",
|
|
255
|
+
"M4-VERSION-002",
|
|
256
|
+
"M4-RESUME-003",
|
|
257
|
+
] as const;
|
|
258
|
+
|
|
259
|
+
function dedupe(codes: M4MigrationCode[]): M4MigrationCode[] {
|
|
260
|
+
const out: M4MigrationCode[] = [];
|
|
261
|
+
for (const c of codes) if (!out.includes(c)) out.push(c);
|
|
262
|
+
return out;
|
|
263
|
+
}
|