pi-mega-compact 0.19.2 → 0.20.0

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 (98) hide show
  1. package/dist/config/vector-cortex.js +24 -0
  2. package/dist/config.js +1 -1
  3. package/dist/extensions/dashboard-server/routes-cache.test/_helpers.js +2 -0
  4. package/dist/extensions/dashboard-server/routes-rag-settings-helpers.js +2 -0
  5. package/dist/extensions/dashboard-server/routes-vector-cortex-helpers.js +100 -0
  6. package/dist/extensions/dashboard-server/routes-vector-cortex-query.js +46 -0
  7. package/dist/extensions/dashboard-server/routes-vector-cortex-shards.js +48 -0
  8. package/dist/extensions/dashboard-server/routes-vector-cortex.js +2 -0
  9. package/dist/extensions/dashboard-server/routes.js +1 -1
  10. package/dist/extensions/dashboard-server/server.js +41 -16
  11. package/dist/extensions/dashboard-server/tailscale.js +32 -0
  12. package/dist/src/config/vector-cortex.js +24 -0
  13. package/dist/src/config.js +1 -1
  14. package/dist/src/tieredRouter.js +8 -0
  15. package/dist/src/vector-cortex/migrations/router-generation-v2.js +252 -0
  16. package/dist/src/vector-cortex/shards/exact.js +134 -0
  17. package/dist/src/vector-cortex/shards/manifest.js +237 -0
  18. package/dist/src/vector-cortex/shards/semantic.js +137 -0
  19. package/dist/src/vector-cortex/shards/types.js +51 -0
  20. package/dist/src/vector-cortex/topology/query.js +342 -0
  21. package/dist/vector-cortex/migrations/router-generation-v2.js +252 -0
  22. package/dist/vector-cortex/shards/exact.js +134 -0
  23. package/dist/vector-cortex/shards/manifest.js +237 -0
  24. package/dist/vector-cortex/shards/semantic.js +137 -0
  25. package/dist/vector-cortex/shards/types.js +51 -0
  26. package/dist/vector-cortex/topology/query.js +342 -0
  27. package/extensions/dashboard-client/dist/assets/{AreaChart-CSaJZXru.js → AreaChart-n4z5w9Ox.js} +2 -2
  28. package/extensions/dashboard-client/dist/assets/{AreaChart-CSaJZXru.js.map → AreaChart-n4z5w9Ox.js.map} +1 -1
  29. package/extensions/dashboard-client/dist/assets/{BarChart-CQouNj1g.js → BarChart-BLGjWWBr.js} +2 -2
  30. package/extensions/dashboard-client/dist/assets/{BarChart-CQouNj1g.js.map → BarChart-BLGjWWBr.js.map} +1 -1
  31. package/extensions/dashboard-client/dist/assets/{CacheTab-m_eiCYoL.js → CacheTab-CAnrKKVK.js} +2 -2
  32. package/extensions/dashboard-client/dist/assets/{CacheTab-m_eiCYoL.js.map → CacheTab-CAnrKKVK.js.map} +1 -1
  33. package/extensions/dashboard-client/dist/assets/{EventsTab-DRyOwjYN.js → EventsTab-D-GL7Ngq.js} +2 -2
  34. package/extensions/dashboard-client/dist/assets/{EventsTab-DRyOwjYN.js.map → EventsTab-D-GL7Ngq.js.map} +1 -1
  35. package/extensions/dashboard-client/dist/assets/{HealthTab-Dj9k40TJ.js → HealthTab-C4x5qQ8s.js} +2 -2
  36. package/extensions/dashboard-client/dist/assets/{HealthTab-Dj9k40TJ.js.map → HealthTab-C4x5qQ8s.js.map} +1 -1
  37. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-Bk9mhYfD.js → MaintenanceTab-BSPs0eq5.js} +2 -2
  38. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-Bk9mhYfD.js.map → MaintenanceTab-BSPs0eq5.js.map} +1 -1
  39. package/extensions/dashboard-client/dist/assets/{MemoryMapTab-C7ve49VG.js → MemoryMapTab-BWEUtTSu.js} +2 -2
  40. package/extensions/dashboard-client/dist/assets/{MemoryMapTab-C7ve49VG.js.map → MemoryMapTab-BWEUtTSu.js.map} +1 -1
  41. package/extensions/dashboard-client/dist/assets/{MetricsTab-DzjhqZA9.js → MetricsTab-Dhm1c3Cx.js} +2 -2
  42. package/extensions/dashboard-client/dist/assets/{MetricsTab-DzjhqZA9.js.map → MetricsTab-Dhm1c3Cx.js.map} +1 -1
  43. package/extensions/dashboard-client/dist/assets/{OverviewTab-CFQdfIm_.js → OverviewTab-Cm6cySiQ.js} +2 -2
  44. package/extensions/dashboard-client/dist/assets/{OverviewTab-CFQdfIm_.js.map → OverviewTab-Cm6cySiQ.js.map} +1 -1
  45. package/extensions/dashboard-client/dist/assets/{ReposTab-DyjwEFUr.js → ReposTab-DxLN1N4K.js} +2 -2
  46. package/extensions/dashboard-client/dist/assets/{ReposTab-DyjwEFUr.js.map → ReposTab-DxLN1N4K.js.map} +1 -1
  47. package/extensions/dashboard-client/dist/assets/{SessionsTab-njLIy7ab.js → SessionsTab-CZuI4ISW.js} +2 -2
  48. package/extensions/dashboard-client/dist/assets/{SessionsTab-njLIy7ab.js.map → SessionsTab-CZuI4ISW.js.map} +1 -1
  49. package/extensions/dashboard-client/dist/assets/{SetupTab-UHIs8-Lh.js → SetupTab-C_0VOomm.js} +2 -2
  50. package/extensions/dashboard-client/dist/assets/{SetupTab-UHIs8-Lh.js.map → SetupTab-C_0VOomm.js.map} +1 -1
  51. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-inWHjCxg.js → TimeSavedCard-BhbaRLmi.js} +2 -2
  52. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-inWHjCxg.js.map → TimeSavedCard-BhbaRLmi.js.map} +1 -1
  53. package/extensions/dashboard-client/dist/assets/{TurnsTab-CXJYugBu.js → TurnsTab-CXJmbjje.js} +2 -2
  54. package/extensions/dashboard-client/dist/assets/{TurnsTab-CXJYugBu.js.map → TurnsTab-CXJmbjje.js.map} +1 -1
  55. package/extensions/dashboard-client/dist/assets/VectorCortexTab-BGe9hu3r.js +2 -0
  56. package/extensions/dashboard-client/dist/assets/VectorCortexTab-BGe9hu3r.js.map +1 -0
  57. package/extensions/dashboard-client/dist/assets/{WikiTab-BJ4A2oi9.js → WikiTab-C5uvMCzp.js} +2 -2
  58. package/extensions/dashboard-client/dist/assets/{WikiTab-BJ4A2oi9.js.map → WikiTab-C5uvMCzp.js.map} +1 -1
  59. package/extensions/dashboard-client/dist/assets/{button-BWl-moyn.js → button-Cl_fxJcg.js} +2 -2
  60. package/extensions/dashboard-client/dist/assets/{button-BWl-moyn.js.map → button-Cl_fxJcg.js.map} +1 -1
  61. package/extensions/dashboard-client/dist/assets/{card-C58RVPOk.js → card-BH8Le5YM.js} +2 -2
  62. package/extensions/dashboard-client/dist/assets/{card-C58RVPOk.js.map → card-BH8Le5YM.js.map} +1 -1
  63. package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-vgeOQU3L.js → generateCategoricalChart-sZ6ZNtBi.js} +2 -2
  64. package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-vgeOQU3L.js.map → generateCategoricalChart-sZ6ZNtBi.js.map} +1 -1
  65. package/extensions/dashboard-client/dist/assets/{index-lVrWQjpu.js → index-CX9zv8cJ.js} +3 -3
  66. package/extensions/dashboard-client/dist/assets/{index-lVrWQjpu.js.map → index-CX9zv8cJ.js.map} +1 -1
  67. package/extensions/dashboard-client/dist/assets/{switch-CSeplFQT.js → switch-CXJhcjhM.js} +2 -2
  68. package/extensions/dashboard-client/dist/assets/{switch-CSeplFQT.js.map → switch-CXJhcjhM.js.map} +1 -1
  69. package/extensions/dashboard-client/dist/assets/{toggle-CQRxgVRi.js → toggle-CoLtIc6y.js} +2 -2
  70. package/extensions/dashboard-client/dist/assets/{toggle-CQRxgVRi.js.map → toggle-CoLtIc6y.js.map} +1 -1
  71. package/extensions/dashboard-client/dist/assets/{useSSE-BUz6IOI-.js → useSSE-fSXho606.js} +2 -2
  72. package/extensions/dashboard-client/dist/assets/{useSSE-BUz6IOI-.js.map → useSSE-fSXho606.js.map} +1 -1
  73. package/extensions/dashboard-client/dist/index.html +1 -1
  74. package/extensions/dashboard-client/src/api/vector-cortex.ts +18 -0
  75. package/extensions/dashboard-client/src/tabs/VectorCortexTab.tsx +62 -0
  76. package/extensions/dashboard-client/src/types/vector-cortex.ts +25 -0
  77. package/extensions/dashboard-server/api-contracts/vector-cortex.ts +41 -0
  78. package/extensions/dashboard-server/routes-cache.test/_helpers.ts +2 -0
  79. package/extensions/dashboard-server/routes-rag-settings-helpers.ts +12 -0
  80. package/extensions/dashboard-server/routes-vector-cortex-helpers.ts +110 -0
  81. package/extensions/dashboard-server/routes-vector-cortex-query.ts +54 -0
  82. package/extensions/dashboard-server/routes-vector-cortex-shards.ts +57 -0
  83. package/extensions/dashboard-server/routes-vector-cortex.ts +2 -0
  84. package/extensions/dashboard-server/routes.ts +2 -0
  85. package/extensions/dashboard-server/server.ts +46 -17
  86. package/extensions/dashboard-server/tailscale.ts +32 -0
  87. package/package.json +1 -1
  88. package/src/config/vector-cortex.ts +26 -0
  89. package/src/config.ts +2 -0
  90. package/src/tieredRouter.ts +9 -0
  91. package/src/vector-cortex/migrations/router-generation-v2.ts +317 -0
  92. package/src/vector-cortex/shards/exact.ts +141 -0
  93. package/src/vector-cortex/shards/manifest.ts +276 -0
  94. package/src/vector-cortex/shards/semantic.ts +156 -0
  95. package/src/vector-cortex/shards/types.ts +212 -0
  96. package/src/vector-cortex/topology/query.ts +485 -0
  97. package/extensions/dashboard-client/dist/assets/VectorCortexTab-DkS0Azx9.js +0 -2
  98. package/extensions/dashboard-client/dist/assets/VectorCortexTab-DkS0Azx9.js.map +0 -1
@@ -0,0 +1,276 @@
1
+ /**
2
+ * vector-cortex/shards/manifest.ts — shard manifest assembly + validation (VC4A).
3
+ *
4
+ * Owns `assembleShardManifest` (the deterministic build) and
5
+ * `validateShardManifest` (task 4). The builder takes the already-partitioned
6
+ * semantic + exact tiers plus the protected spans and emits a `ShardManifestV1`
7
+ * whose ranges are disjoint and sorted by `(seqStart, byteStart)`. The validator
8
+ * enforces the two structural rules the sprint acceptance pins:
9
+ *
10
+ * - SHD_RANGE_OVERLAP — any two manifest shard ranges (semantic or exact)
11
+ * overlap in the session byte stream;
12
+ * - SHD_PROTECTED_GAP — the exact shards do not cover every protected byte
13
+ * exactly once (a protected span is unterminated by an exact shard, or an
14
+ * exact shard covers a byte no protected span claims).
15
+ *
16
+ * Emits `vector_cortex_shard_manifest_built` on a successful assembly and
17
+ * `vector_cortex_protected_span_rejected` when validation fails, via the same
18
+ * flag-gated reporter pattern VC3A/VC3B/VC3C use (`MEGACOMPACT_VC4A=0` emits
19
+ * nothing — byte-identical predecessor).
20
+ *
21
+ * Pure/deterministic: hashes + range math only, no storage, no console, no
22
+ * network (PREVENT-PI-004 / PREVENT-011).
23
+ */
24
+ import { createHash } from "node:crypto";
25
+ import { VC4A_ENABLED } from "../../config/vector-cortex.js";
26
+ import type {
27
+ ExactShardV1,
28
+ SemanticShardV1,
29
+ ShardEmitter,
30
+ ShardManifestFailureCode,
31
+ ShardManifestV1,
32
+ ShardManifestValidation,
33
+ ShardRange,
34
+ ShardReporter,
35
+ } from "./types.js";
36
+
37
+ /** A bare byte interval (used for the range math below). */
38
+ interface Interval {
39
+ readonly start: number;
40
+ readonly end: number;
41
+ }
42
+
43
+ /** A manifest shard's range, normalized for sorting / digest purposes. */
44
+ function rangeKey(r: ShardRange): string {
45
+ return `${r.seqStart.toString()},${r.byteStart}`;
46
+ }
47
+
48
+ /**
49
+ * Merge byte intervals into disjoint, sorted intervals (half-open). Overlapping
50
+ * AND touching intervals merge into one — this produces the "union" used for
51
+ * coverage math, never used to hide an overlap (overlap is checked separately in
52
+ * `hasOverlap` before any merging).
53
+ */
54
+ function mergeIntervals(ranges: readonly ShardRange[]): Interval[] {
55
+ const sorted = [...ranges]
56
+ .map((r) => ({ start: r.byteStart, end: r.byteEnd }))
57
+ .sort((a, b) => (a.start !== b.start ? a.start - b.start : a.end - b.end));
58
+ const out: Interval[] = [];
59
+ for (const iv of sorted) {
60
+ const last = out[out.length - 1];
61
+ if (last !== undefined && iv.start <= last.end) {
62
+ out[out.length - 1] = { start: last.start, end: Math.max(last.end, iv.end) };
63
+ continue;
64
+ }
65
+ out.push(iv);
66
+ }
67
+ return out;
68
+ }
69
+
70
+ /** Difference: the bytes of `base` intervals NOT covered by `cover` intervals. */
71
+ function subtractCover(base: Interval[], cover: Interval[]): Interval[] {
72
+ const ordered = cover
73
+ .slice()
74
+ .sort((a, b) => (a.start !== b.start ? a.start - b.start : a.end - b.end));
75
+ const gaps: Interval[] = [];
76
+ for (const iv of base) {
77
+ let cursor = iv.start;
78
+ for (const c of ordered) {
79
+ if (c.end <= cursor) continue;
80
+ if (c.start > cursor) {
81
+ gaps.push({ start: cursor, end: Math.min(c.start, iv.end) });
82
+ if (c.start >= iv.end) break;
83
+ }
84
+ cursor = Math.max(cursor, c.end);
85
+ if (cursor >= iv.end) break;
86
+ }
87
+ if (cursor < iv.end) gaps.push({ start: cursor, end: iv.end });
88
+ }
89
+ return gaps;
90
+ }
91
+
92
+ /** True when any two ranges overlap (share at least one byte). */
93
+ function hasOverlap(ranges: readonly ShardRange[]): boolean {
94
+ const sorted = [...ranges].sort((a, b) => (a.byteStart !== b.byteStart ? a.byteStart - b.byteStart : a.byteEnd - b.byteEnd));
95
+ for (let i = 1; i < sorted.length; i++) {
96
+ const prev = sorted[i - 1];
97
+ const cur = sorted[i];
98
+ if (cur.byteStart < prev.byteEnd) return true;
99
+ }
100
+ return false;
101
+ }
102
+
103
+ /**
104
+ * Validate a manifest (task 4). Disjointness is a PER-TIER property: semantic
105
+ * shard ranges must be pairwise disjoint among themselves, and exact shard
106
+ * ranges pairwise disjoint among themselves (else `SHD_RANGE_OVERLAP`). The two
107
+ * tiers are NOT disjoint from each other — exact shards are a verbatim SUBSET of
108
+ * the semantic stream's bytes (a protected tool-pair's bytes are part of the
109
+ * semantic content), so a semantic range and an exact range overlapping is
110
+ * expected and correct. The cross-tier property is complete protected-span
111
+ * coverage: the exact shards must tile every protected span byte exactly once,
112
+ * no gap and no extra coverage (else `SHD_PROTECTED_GAP`). A manifest missing
113
+ * protected spans is malformed (`SHD_PROTECTED_GAP`). `generationDigest` is NOT
114
+ * verified here (it is a deterministic projection; the caller verifies it
115
+ * against the rebuilt digest).
116
+ */
117
+ export function validateShardManifest(manifest: ShardManifestV1): ShardManifestValidation {
118
+ // Disjointness is enforced within each tier separately. An exact shard sitting
119
+ // inside a semantic shard is legitimate (exact ⊂ semantic).
120
+ if (hasOverlap(manifest.semantic.map((s) => s.range))) {
121
+ return { ok: false, code: "SHD_RANGE_OVERLAP" };
122
+ }
123
+ if (hasOverlap(manifest.exact.map((s) => s.range))) {
124
+ return { ok: false, code: "SHD_RANGE_OVERLAP" };
125
+ }
126
+
127
+ const protectedUnion = mergeIntervals(manifest.protectedSpans);
128
+ const exactUnion = mergeIntervals(manifest.exact.map((s) => s.range));
129
+
130
+ // Every protected byte must be covered by at least one exact shard (no gap),
131
+ // and no exact byte may fall outside the protected union (no extra coverage).
132
+ const gaps = subtractCover(protectedUnion, exactUnion);
133
+ const extras = subtractCover(exactUnion, protectedUnion);
134
+ if (gaps.length > 0 || extras.length > 0) {
135
+ return { ok: false, code: "SHD_PROTECTED_GAP" };
136
+ }
137
+ return { ok: true };
138
+ }
139
+
140
+ /**
141
+ * Deterministic manifest digest over a shard set — order-independent because it
142
+ * hashes the shards sorted by `(kind, seqStart, byteStart, digest)` (never input
143
+ * order). One SHA-256 over the canonical parts; the caller compares it against
144
+ * the stored `generationDigest`.
145
+ */
146
+ export function shardManifestDigest(
147
+ sessionId: string,
148
+ sourceHighWater: bigint,
149
+ semantic: readonly { range: ShardRange; digest: string }[],
150
+ exact: readonly { range: ShardRange; digest: string }[],
151
+ ): string {
152
+ const rows: Array<[string, ShardRange, string]> = [
153
+ ...semantic.map((s) => ["semantic", s.range, s.digest] as [string, ShardRange, string]),
154
+ ...exact.map((s) => ["exact", s.range, s.digest] as [string, ShardRange, string]),
155
+ ].sort((a, b) => {
156
+ if (a[0] !== b[0]) return a[0] < b[0] ? -1 : 1;
157
+ const rk = rangeKey(a[1]);
158
+ const rk2 = rangeKey(b[1]);
159
+ return rk !== rk2 ? (rk < rk2 ? -1 : 1) : a[2] < b[2] ? -1 : a[2] > b[2] ? 1 : 0;
160
+ });
161
+ const h = createHash("sha256");
162
+ h.update(`shard-manifest-v1|${sessionId}|${sourceHighWater.toString()}|`);
163
+ for (const [kind, r, digest] of rows) {
164
+ h.update(`${kind}|${r.seqStart.toString()}|${r.seqEnd.toString()}|${r.byteStart}|${r.byteEnd}|${digest}~`);
165
+ }
166
+ return `sha256:${h.digest("hex")}`;
167
+ }
168
+
169
+ /** Inputs to assemble a manifest. */
170
+ export interface AssembleManifestInput {
171
+ readonly sessionId: string;
172
+ readonly sourceHighWater: bigint;
173
+ readonly semantic: readonly SemanticShardV1[];
174
+ readonly exact: readonly ExactShardV1[];
175
+ readonly protectedSpans: readonly ShardRange[];
176
+ }
177
+
178
+ /**
179
+ * Assemble a `ShardManifestV1` from already-partitioned tiers (deterministic).
180
+ * Shards are sorted by `(seqStart, byteStart)`; `generationDigest`, `byteTotal`
181
+ * and `shardCount` are computed from the sorted set. The caller typically runs
182
+ * this through `assembleAndValidate` so the structural rules are enforced too.
183
+ */
184
+ export function buildShardManifest(input: AssembleManifestInput): ShardManifestV1 {
185
+ const cmp = (a: SemanticShardV1 | ExactShardV1, b: SemanticShardV1 | ExactShardV1): number => {
186
+ if (a.range.seqStart !== b.range.seqStart) {
187
+ return a.range.seqStart < b.range.seqStart ? -1 : 1;
188
+ }
189
+ return a.range.byteStart !== b.range.byteStart
190
+ ? a.range.byteStart < b.range.byteStart ? -1 : 1
191
+ : 0;
192
+ };
193
+ const semantic = [...input.semantic].sort(cmp);
194
+ const exact = [...input.exact].sort(cmp);
195
+ const byteTotal =
196
+ semantic.reduce((n, s) => n + s.byteCount, 0) +
197
+ exact.reduce((n, s) => n + s.byteCount, 0);
198
+ const generationDigest = shardManifestDigest(input.sessionId, input.sourceHighWater, semantic, exact);
199
+ return {
200
+ schema: "shard-manifest-v1",
201
+ sessionId: input.sessionId,
202
+ sourceHighWater: input.sourceHighWater,
203
+ semantic,
204
+ exact,
205
+ protectedSpans: [...input.protectedSpans],
206
+ byteTotal,
207
+ shardCount: semantic.length + exact.length,
208
+ generationDigest,
209
+ };
210
+ }
211
+
212
+ /**
213
+ * Assembly + validation seam (task 5). Builds the manifest, validates it, and
214
+ * emits `vector_cortex_shard_manifest_built` on success or
215
+ * `vector_cortex_protected_span_rejected` on failure (flag-gated). Non-fatal:
216
+ * a validation failure returns `{ok:false, code}` and NEVER throws into the host.
217
+ */
218
+ export function assembleAndValidate(
219
+ input: AssembleManifestInput,
220
+ emit?: ShardEmitter,
221
+ ): { ok: true; manifest: ShardManifestV1 } | { ok: false; code: ShardManifestFailureCode } {
222
+ const manifest = buildShardManifest(input);
223
+ const validation = validateShardManifest(manifest);
224
+ const reporter = createShardReporter(emit);
225
+ if (!validation.ok) {
226
+ reporter.protectedSpanRejected({
227
+ sessionId: input.sessionId,
228
+ code: validation.code,
229
+ });
230
+ return { ok: false, code: validation.code };
231
+ }
232
+ reporter.manifestBuilt({
233
+ sessionId: input.sessionId,
234
+ sourceHighWater: input.sourceHighWater.toString(),
235
+ shardCount: manifest.shardCount,
236
+ byteTotal: manifest.byteTotal,
237
+ generationDigest: manifest.generationDigest,
238
+ });
239
+ return { ok: true, manifest };
240
+ }
241
+
242
+ /**
243
+ * Whether each tier's ranges are internally sorted by (seqStart, byteStart).
244
+ * The two tiers are NOT globally ordered against each other (exact shards are a
245
+ * subset of the semantic stream, so an exact range always sits inside some
246
+ * semantic range); the guarantee the builder provides is per-tier ordering.
247
+ */
248
+ export function manifestSorted(m: ShardManifestV1): boolean {
249
+ const key = (r: ShardRange): string => `${r.seqStart.toString()},${r.byteStart}`;
250
+ const sorted = (rows: readonly { range: ShardRange }[]): boolean =>
251
+ rows.every((r, i) => i === 0 || key(rows[i - 1]!.range) <= key(r.range));
252
+ return sorted(m.semantic) && sorted(m.exact);
253
+ }
254
+
255
+ /** Build the flag-gated typed reporter (mirrors ledger/topology reporters). */
256
+ function createShardReporter(emit?: ShardEmitter): ShardReporter {
257
+ const fire = (event: Parameters<ShardEmitter>[0], fields: Record<string, unknown>): void => {
258
+ if (!VC4A_ENABLED()) return;
259
+ if (!emit) return;
260
+ try {
261
+ emit(event, fields);
262
+ } catch {
263
+ /* non-fatal observability — never break the agent loop */
264
+ }
265
+ };
266
+ return {
267
+ manifestBuilt(fields) {
268
+ fire("vector_cortex_shard_manifest_built", fields);
269
+ },
270
+ protectedSpanRejected(fields) {
271
+ fire("vector_cortex_protected_span_rejected", fields);
272
+ },
273
+ };
274
+ }
275
+
276
+ export { createShardReporter };
@@ -0,0 +1,156 @@
1
+ /**
2
+ * vector-cortex/shards/semantic.ts — semantic tier partition (VC4A, mode A/B).
3
+ *
4
+ * Partitions a session's canonical EventV2 stream into `SemanticShardV1`
5
+ * chunks, cutting ONLY at complete record boundaries. Every shard's `range`
6
+ * names the exact inclusive seq span and the half-open source byte window it
7
+ * covers in canonical stream order; a shard NEVER splits a record (or a tool
8
+ * call/result pair). Semantic shards carry DERIVED aggregate content (a
9
+ * deterministic digest + token estimate + byte/event counts) and never
10
+ * reproduce exact text — exact bytes are the exact tier's job.
11
+ *
12
+ * The partition is deterministic and size-bounded: it walks the sorted events,
13
+ * accrues each record's bytes, and closes a shard the moment adding the next
14
+ * complete record would exceed `targetSize`. A single record that is already
15
+ * over the budget gets its own shard (a shard is always at least one complete
16
+ * record, so over-budget records are never split).
17
+ *
18
+ * Triad: A = this semantic tier plus exact shards; B = the same range shape
19
+ * derived from extractive heads with the semantic encoder disabled (the caller
20
+ * may substitute the derived payload, since the range+digest contract is
21
+ * identical); C = exact anchors/current transcript only (no semantic shards at
22
+ * all, handled by the exact tier alone).
23
+ *
24
+ * Pure/deterministic: hashes + array walking only, no storage, no console, no
25
+ * network (PREVENT-PI-004 / PREVENT-011).
26
+ */
27
+ import { createHash } from "node:crypto";
28
+ import type { EventV2 } from "../ledger/types.js";
29
+ import type { SemanticPartitionInput, SemanticPartitionResult, SemanticShardV1 } from "./types.js";
30
+
31
+ /** A full-stream byte offset map: cumulative end offset per ascending seq. */
32
+ export interface ByteOffsets {
33
+ /** For an EventV2 at `seq`, its half-open [byteStart, byteEnd) in stream order. */
34
+ readonly of: (seq: bigint) => { byteStart: number; byteEnd: number } | undefined;
35
+ /** Total canonical stream length (sum of every record's bytes). */
36
+ readonly total: number;
37
+ }
38
+
39
+ /**
40
+ * Compute the canonical per-record byte offsets for a session's sorted events.
41
+ * Events are sorted by seq (ascending) defensively; the byte stream is the
42
+ * concatenation of each event's `originalBytes` in that order. A shared pure
43
+ * helper so semantic + exact tiers agree on source ranges (the two partitioning
44
+ * algorithms remain otherwise independent). Returns `undefined`-guarding lookup
45
+ * plus the total length; empty input yields an empty map with total 0.
46
+ */
47
+ export function cumulativeOffsets(events: readonly EventV2[]): ByteOffsets {
48
+ const map = new Map<string, { byteStart: number; byteEnd: number }>();
49
+ let off = 0;
50
+ const sorted = [...events].sort((a, b) => (a.seq < b.seq ? -1 : a.seq > b.seq ? 1 : 0));
51
+ for (const e of sorted) {
52
+ const len = e.originalBytes.length;
53
+ map.set(e.seq.toString(), { byteStart: off, byteEnd: off + len });
54
+ off += len;
55
+ }
56
+ return {
57
+ of: (seq: bigint) => map.get(seq.toString()),
58
+ total: off,
59
+ };
60
+ }
61
+
62
+ /** Approximate token count for a valid UTF-8 text (whitespace-separated runs). */
63
+ function approxTokens(text: string): number {
64
+ if (text.length === 0) return 0;
65
+ const runs = text.match(/\S+/g);
66
+ return runs ? runs.length : 0;
67
+ }
68
+
69
+ /** Deterministic SHARD digest over a semantic shard's derived payload. */
70
+ function sealedSemanticDigest(
71
+ sessionId: string,
72
+ events: readonly EventV2[],
73
+ range: { byteStart: number; byteEnd: number; seqStart: bigint; seqEnd: bigint },
74
+ tokenEstimate: number,
75
+ ): string {
76
+ const h = createHash("sha256");
77
+ h.update(`semantic-shard-v1|${sessionId}|`);
78
+ h.update(`${range.seqStart.toString()}|${range.seqEnd.toString()}|`);
79
+ h.update(`${range.byteStart}|${range.byteEnd}|`);
80
+ h.update(`${tokenEstimate}|`);
81
+ // One `~`-joined run of the covered records' authoritative byte digests in
82
+ // seq order, so the shard digest depends on exactly which records it covers.
83
+ for (const e of [...events].sort((a, b) => (a.seq < b.seq ? -1 : a.seq > b.seq ? 1 : 0))) {
84
+ h.update(`${e.seq.toString()}:${e.bytesDigest}~`);
85
+ }
86
+ return `sha256:${h.digest("hex")}`;
87
+ }
88
+
89
+ /**
90
+ * Partition the semantic tier (task 2). Returns `ok:true` with a list of
91
+ * `SemanticShardV1` whose (sorted) ranges are contiguous, non-overlapping and
92
+ * jointly cover every event exactly once. Failures are defensive: a non-positive
93
+ * or non-finite `targetSize` rejects with `SHD_INVALID_TARGET_SIZE`; mixed-session
94
+ * events reject with `SHD_CROSS_SESSION`.
95
+ */
96
+ export function partitionSemantic(input: SemanticPartitionInput): SemanticPartitionResult {
97
+ const { sessionId, events, targetSize } = input;
98
+ if (!Number.isFinite(targetSize) || targetSize <= 0) {
99
+ return { ok: false, code: "SHD_INVALID_TARGET_SIZE" };
100
+ }
101
+ if (events.some((e) => e.sessionId !== sessionId)) {
102
+ return { ok: false, code: "SHD_CROSS_SESSION" };
103
+ }
104
+ const offsets = cumulativeOffsets(events);
105
+ const sorted = [...events].sort((a, b) => (a.seq < b.seq ? -1 : a.seq > b.seq ? 1 : 0));
106
+ if (sorted.length === 0) return { ok: true, shards: [] };
107
+
108
+ const shards: SemanticShardV1[] = [];
109
+ let batch: EventV2[] = [];
110
+ let batchBytes = 0;
111
+ let batchTokens = 0;
112
+
113
+ const flush = (): void => {
114
+ if (batch.length === 0) return;
115
+ const first = batch[0];
116
+ const last = batch[batch.length - 1];
117
+ const start = offsets.of(first.seq);
118
+ const end = offsets.of(last.seq);
119
+ const byteStart = start ? start.byteStart : 0;
120
+ const byteEnd = end ? end.byteEnd : byteStart;
121
+ const tokenEstimate = batchTokens;
122
+ shards.push({
123
+ schema: "semantic-shard-v1",
124
+ sessionId,
125
+ range: {
126
+ sessionId,
127
+ seqStart: first.seq,
128
+ seqEnd: last.seq,
129
+ byteStart,
130
+ byteEnd,
131
+ },
132
+ kind: "semantic",
133
+ digest: sealedSemanticDigest(sessionId, batch, { seqStart: first.seq, seqEnd: last.seq, byteStart, byteEnd }, tokenEstimate),
134
+ byteCount: batchBytes,
135
+ eventCount: batch.length,
136
+ tokenEstimate,
137
+ });
138
+ batch = [];
139
+ batchBytes = 0;
140
+ batchTokens = 0;
141
+ };
142
+
143
+ for (const e of sorted) {
144
+ const len = e.originalBytes.length;
145
+ const tokens = e.utf8.valid ? approxTokens(e.utf8.text) : Math.ceil(len / 4);
146
+ // A batch that already has a complete record and would exceed the budget
147
+ // (and the next record itself fits, or it doesn't) closes at a boundary.
148
+ if (batch.length > 0 && batchBytes + len > targetSize) flush();
149
+ batch.push(e);
150
+ batchBytes += len;
151
+ batchTokens += tokens;
152
+ }
153
+ flush();
154
+
155
+ return { ok: true, shards };
156
+ }
@@ -0,0 +1,212 @@
1
+ /**
2
+ * vector-cortex/shards/types.ts — dual-tier shard contract (VC4A).
3
+ *
4
+ * Owns `SemanticShardV1` / `ExactShardV1` / `ShardManifestV1` — the shared
5
+ * partition contract of the sprint failure triad:
6
+ *
7
+ * A = semantic + exact shards (normal path);
8
+ * B = extractive + exact shards with the semantic encoder disabled;
9
+ * C = exact anchors/current transcript only.
10
+ *
11
+ * A session's canonical byte stream is partitioned ONLY at complete EventV2
12
+ * record boundaries (VC1A byte authority — an EventV2's `originalBytes` + its
13
+ * SHA-256 `bytesDigest` are authoritative, invalid UTF-8 is never normalized).
14
+ * A `ShardRange` names a contiguous run of complete records by inclusive
15
+ * seq `[seqStart..seqEnd]` and by the half-open source byte range
16
+ * `[byteStart, byteEnd)` they occupy in canonical stream order (record `seq`
17
+ * carries every byte from `offset(seq)` to `offset(seq)+len(seq)`).
18
+ *
19
+ * Semantic shards carry derived aggregate vectors/token estimates and NEVER
20
+ * reproduce exact text (the RESIDUAL_CODEC / exact-payload shards own exact
21
+ * bytes). Exact shards carry the EXACT original bytes, unchanged, for the
22
+ * protected spans: every tool call/result pair, every anchor, and every invalid
23
+ * UTF-8 event (SHD-UTF8-002 — invalid bytes are exact-only and never
24
+ * normalized/re-encoded). A tool call/result pair that straddles a target-size
25
+ * boundary stays in ONE exact shard (SHD-PAIR-001).
26
+ *
27
+ * Consumes only reviewer-accepted predecessor contracts (VC1A EventV2) and the
28
+ * [common contracts](../../../../docs/vector-cortex/CONTRACTS.md). Pure
29
+ * types/schema + small predicates: no storage, no console, no network
30
+ * (PREVENT-PI-004 / PREVENT-011). The acceptance contract and the conformance
31
+ * IDs (SHD-001..020 + named SHD-PAIR-001 / SHD-UTF8-002 / SHD-RANGE-003) live
32
+ * here.
33
+ */
34
+
35
+ import type { EventV2 } from "../ledger/types.js";
36
+
37
+ /**
38
+ * A contiguous covered byte+seq window over ONE session's canonical EventV2
39
+ * stream. `seqStart`/`seqEnd` are inclusive record sequence bounds; `byteStart`/
40
+ * `byteEnd` are half-open byte offsets in canonical stream order. Every recorded
41
+ * boundary is a COMPLETE EventV2 record boundary — a shard never splits a record
42
+ * or a tool call/result pair.
43
+ */
44
+ export interface ShardRange {
45
+ readonly sessionId: string;
46
+ readonly seqStart: bigint;
47
+ readonly seqEnd: bigint;
48
+ readonly byteStart: number;
49
+ readonly byteEnd: number;
50
+ }
51
+
52
+ /** What an exact shard protects (why its bytes must survive verbatim). */
53
+ export type ExactShardCase =
54
+ | "tool-pair"
55
+ | "anchor"
56
+ | "invalid-utf8"
57
+ | "anchor+invalid";
58
+
59
+ /**
60
+ * A semantic shard — a deterministic partition of complete, valid EventV2
61
+ * records into sub-target-size chunks. It carries DERIVED aggregate content
62
+ * (head vectors + token estimate + a deterministic content digest) and
63
+ * explicitly not the raw record bytes; exact restoration of those bytes is the
64
+ * exact tier's job (RESIDUAL_CODEC / exact payload shards).
65
+ */
66
+ export interface SemanticShardV1 {
67
+ readonly schema: "semantic-shard-v1";
68
+ readonly sessionId: string;
69
+ /** Source metadata: which complete records and byte span this shard covers. */
70
+ readonly range: ShardRange;
71
+ readonly kind: "semantic";
72
+ /** Deterministic SHA-256 over the shard's derived payload bytes. */
73
+ readonly digest: string;
74
+ /** Sum of the covered records' original byte lengths. */
75
+ readonly byteCount: number;
76
+ /** Number of complete events covered. */
77
+ readonly eventCount: number;
78
+ /** Deterministic token estimate for the covered text (aggregate). */
79
+ readonly tokenEstimate: number;
80
+ }
81
+
82
+ /**
83
+ * An exact shard — the ORIGINAL bytes of a protected span, preserved verbatim
84
+ * including invalid UTF-8 (never normalized/re-encoded). `originalBytes` is the
85
+ * concatenation, in seq order, of every covered record's `originalBytes`; the
86
+ * byte range equals that concatenation exactly. `case` records why the span is
87
+ * protected. No semantic loss is ever claimed for exact bytes.
88
+ */
89
+ export interface ExactShardV1 {
90
+ readonly schema: "exact-shard-v1";
91
+ readonly sessionId: string;
92
+ readonly range: ShardRange;
93
+ readonly kind: "exact";
94
+ /** Exact original bytes, unchanged (authoritative). */
95
+ readonly originalBytes: Uint8Array;
96
+ /** SHA-256 of `originalBytes`. */
97
+ readonly digest: string;
98
+ readonly byteCount: number;
99
+ readonly case: ExactShardCase;
100
+ }
101
+
102
+ /**
103
+ * The assembled shard manifest. `changes` mirror the sprint failure triad:
104
+ * A / B — semantic + exact tiers both present (B may derive the semantic tier
105
+ * from extractive heads when the semantic encoder is disabled);
106
+ * C — exact anchors/current transcript ONLY (zero semantic shards).
107
+ * `generationDigest` is ONE deterministic SHA-256 over the canonical
108
+ * serialization of every shard's range + kind + digest. `protectedSpans`
109
+ * enumerate every span that must exist as exact bytes; the validator requires
110
+ * the exact shards to cover them exactly once (no gap, no overlap).
111
+ */
112
+ export interface ShardManifestV1 {
113
+ readonly schema: "shard-manifest-v1";
114
+ readonly sessionId: string;
115
+ /** Contiguous durable authority high-water the manifest is built AT. */
116
+ readonly sourceHighWater: bigint;
117
+ readonly semantic: readonly SemanticShardV1[];
118
+ readonly exact: readonly ExactShardV1[];
119
+ /** Deterministic manifest digest (order-independent over the shard set). */
120
+ readonly generationDigest: string;
121
+ /** The protected spans that must be exactly covered (tools/anchors/invalid). */
122
+ readonly protectedSpans: readonly ShardRange[];
123
+ /** Sum of every semantic + exact shard's covered bytes. */
124
+ readonly byteTotal: number;
125
+ /** Total number of shards (semantic + exact). */
126
+ readonly shardCount: number;
127
+ }
128
+
129
+ /** Input to a semantic partition: the sorted events + a target max byte size. */
130
+ export interface SemanticPartitionInput {
131
+ readonly sessionId: string;
132
+ /** Complete EventV2 records in ascending seq order (source of truth). */
133
+ readonly events: readonly EventV2[];
134
+ /** Per-shard byte budget; a single over-budget record gets its own shard. */
135
+ readonly targetSize: number;
136
+ }
137
+
138
+ /** Result of partitioning the semantic tier (A/B). */
139
+ export type SemanticPartitionResult =
140
+ | { ok: true; shards: readonly SemanticShardV1[] }
141
+ | { ok: false; code: string };
142
+
143
+ /** One protected input span to carve into exact shards. */
144
+ export interface ProtectedSpan {
145
+ /** The events to preserve verbatim, in ascending seq order. */
146
+ readonly events: readonly EventV2[];
147
+ /** Why this span is protected (used for the exact shard `case`). */
148
+ readonly case: ExactShardCase;
149
+ }
150
+
151
+ /**
152
+ * Input to an exact partition. `events` is the FULL canonical session stream
153
+ * (used to derive the true stream byte offsets); `protectedSpans` are the atomic
154
+ * groups to preserve verbatim (a tool call+result pair is ONE span so it can
155
+ * never be split across exact shards — SHD-PAIR-001); `targetSize` is the
156
+ * per-shard byte budget (a single over-budget pair still occupies one shard).
157
+ */
158
+ export interface ExactPartitionInput {
159
+ readonly sessionId: string;
160
+ readonly events: readonly EventV2[];
161
+ readonly protectedSpans: readonly ProtectedSpan[];
162
+ readonly targetSize: number;
163
+ }
164
+
165
+ /** Result of partitioning the exact tier. */
166
+ export type ExactPartitionResult =
167
+ | { ok: true; shards: readonly ExactShardV1[] }
168
+ | { ok: false; code: string };
169
+
170
+ /** Manifest validation failure codes. */
171
+ export type ShardManifestFailureCode = "SHD_RANGE_OVERLAP" | "SHD_PROTECTED_GAP";
172
+
173
+ /** Validation of a manifest vs the pairwise-disjoint + protected-span rules. */
174
+ export type ShardManifestValidation =
175
+ | { ok: true }
176
+ | { ok: false; code: ShardManifestFailureCode };
177
+
178
+ /** The two structured events the VC4A reporter emits. */
179
+ export type ShardEventName =
180
+ | "vector_cortex_shard_manifest_built"
181
+ | "vector_cortex_protected_span_rejected";
182
+
183
+ /** Injected emit callback — same (event, fields) shape as the other VC seams. */
184
+ export type ShardEmitter = (event: ShardEventName, fields: Record<string, unknown>) => void;
185
+
186
+ /** Typed, best-effort reporter bound to the two shard event names. */
187
+ export interface ShardReporter {
188
+ readonly manifestBuilt: (fields: Record<string, unknown>) => void;
189
+ readonly protectedSpanRejected: (fields: Record<string, unknown>) => void;
190
+ }
191
+
192
+ /**
193
+ * Registered SHD conformance ID range (SHD-001..020). The acceptance test reads
194
+ * these rows from the v2 manifest and asserts each returns its manifest
195
+ * `ok`/`code`. The named assertions (SHD-PAIR-001 / SHD-UTF8-002 /
196
+ * SHD-RANGE-003) live in the acceptance test.
197
+ */
198
+ export const SHD_IDS = [
199
+ "SHD-001", "SHD-002", "SHD-003", "SHD-004", "SHD-005",
200
+ "SHD-006", "SHD-007", "SHD-008", "SHD-009", "SHD-010",
201
+ "SHD-011", "SHD-012", "SHD-013", "SHD-014", "SHD-015",
202
+ "SHD-016", "SHD-017", "SHD-018", "SHD-019", "SHD-020",
203
+ ] as const;
204
+
205
+ /** Named SHD conformance assertions. */
206
+ export const SHD_NAMED_IDS = [
207
+ "SHD-PAIR-001",
208
+ "SHD-UTF8-002",
209
+ "SHD-RANGE-003",
210
+ ] as const;
211
+
212
+ export type { EventV2 };