pi-mega-compact 0.20.0 → 0.20.2

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 (111) hide show
  1. package/dist/config/vector-cortex.js +25 -0
  2. package/dist/config.js +1 -1
  3. package/dist/extensions/dashboard-server/routes-rag-settings-helpers.js +2 -0
  4. package/dist/extensions/dashboard-server/routes-vector-cortex-reconstruct.js +33 -0
  5. package/dist/extensions/dashboard-server/routes-vector-cortex-residual.js +51 -0
  6. package/dist/extensions/dashboard-server/routes-vector-cortex.js +2 -0
  7. package/dist/extensions/dashboard-server/routes.js +1 -1
  8. package/dist/extensions/dashboard-server/server.js +5 -1
  9. package/dist/src/config/vector-cortex.js +25 -0
  10. package/dist/src/config.js +1 -1
  11. package/dist/src/vector-cortex/reconstruct/_acceptance-helpers.js +365 -0
  12. package/dist/src/vector-cortex/reconstruct/assemble.js +137 -0
  13. package/dist/src/vector-cortex/reconstruct/closure.js +268 -0
  14. package/dist/src/vector-cortex/reconstruct/types.js +46 -0
  15. package/dist/src/vector-cortex/reconstruct/validate.js +152 -0
  16. package/dist/src/vector-cortex/residual/codec.js +224 -0
  17. package/dist/src/vector-cortex/residual/dct.js +158 -0
  18. package/dist/src/vector-cortex/residual/fixture-payload.js +77 -0
  19. package/dist/src/vector-cortex/residual/gf256.js +182 -0
  20. package/dist/src/vector-cortex/residual/parity.js +245 -0
  21. package/dist/src/vector-cortex/residual/quantize.js +200 -0
  22. package/dist/src/vector-cortex/residual/stream.js +124 -0
  23. package/dist/src/vector-cortex/residual/types.js +55 -0
  24. package/dist/vector-cortex/reconstruct/_acceptance-helpers.js +365 -0
  25. package/dist/vector-cortex/reconstruct/assemble.js +137 -0
  26. package/dist/vector-cortex/reconstruct/closure.js +268 -0
  27. package/dist/vector-cortex/reconstruct/types.js +46 -0
  28. package/dist/vector-cortex/reconstruct/validate.js +152 -0
  29. package/dist/vector-cortex/residual/codec.js +224 -0
  30. package/dist/vector-cortex/residual/dct.js +158 -0
  31. package/dist/vector-cortex/residual/fixture-payload.js +77 -0
  32. package/dist/vector-cortex/residual/gf256.js +182 -0
  33. package/dist/vector-cortex/residual/parity.js +245 -0
  34. package/dist/vector-cortex/residual/quantize.js +200 -0
  35. package/dist/vector-cortex/residual/stream.js +124 -0
  36. package/dist/vector-cortex/residual/types.js +55 -0
  37. package/extensions/dashboard-client/dist/assets/{AreaChart-n4z5w9Ox.js → AreaChart-XF3jPpvn.js} +2 -2
  38. package/extensions/dashboard-client/dist/assets/{AreaChart-n4z5w9Ox.js.map → AreaChart-XF3jPpvn.js.map} +1 -1
  39. package/extensions/dashboard-client/dist/assets/{BarChart-BLGjWWBr.js → BarChart-DnYYn0GF.js} +2 -2
  40. package/extensions/dashboard-client/dist/assets/{BarChart-BLGjWWBr.js.map → BarChart-DnYYn0GF.js.map} +1 -1
  41. package/extensions/dashboard-client/dist/assets/{CacheTab-CAnrKKVK.js → CacheTab-D3bVskCL.js} +2 -2
  42. package/extensions/dashboard-client/dist/assets/{CacheTab-CAnrKKVK.js.map → CacheTab-D3bVskCL.js.map} +1 -1
  43. package/extensions/dashboard-client/dist/assets/{EventsTab-D-GL7Ngq.js → EventsTab-CX_8myfc.js} +2 -2
  44. package/extensions/dashboard-client/dist/assets/{EventsTab-D-GL7Ngq.js.map → EventsTab-CX_8myfc.js.map} +1 -1
  45. package/extensions/dashboard-client/dist/assets/{HealthTab-C4x5qQ8s.js → HealthTab-CnVzBQvN.js} +2 -2
  46. package/extensions/dashboard-client/dist/assets/{HealthTab-C4x5qQ8s.js.map → HealthTab-CnVzBQvN.js.map} +1 -1
  47. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-BSPs0eq5.js → MaintenanceTab-Cao--dtV.js} +2 -2
  48. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-BSPs0eq5.js.map → MaintenanceTab-Cao--dtV.js.map} +1 -1
  49. package/extensions/dashboard-client/dist/assets/{MemoryMapTab-BWEUtTSu.js → MemoryMapTab-DZdI-9ig.js} +2 -2
  50. package/extensions/dashboard-client/dist/assets/{MemoryMapTab-BWEUtTSu.js.map → MemoryMapTab-DZdI-9ig.js.map} +1 -1
  51. package/extensions/dashboard-client/dist/assets/{MetricsTab-Dhm1c3Cx.js → MetricsTab-SlpSmNU4.js} +2 -2
  52. package/extensions/dashboard-client/dist/assets/{MetricsTab-Dhm1c3Cx.js.map → MetricsTab-SlpSmNU4.js.map} +1 -1
  53. package/extensions/dashboard-client/dist/assets/{OverviewTab-Cm6cySiQ.js → OverviewTab-C_-_4au9.js} +2 -2
  54. package/extensions/dashboard-client/dist/assets/{OverviewTab-Cm6cySiQ.js.map → OverviewTab-C_-_4au9.js.map} +1 -1
  55. package/extensions/dashboard-client/dist/assets/{ReposTab-DxLN1N4K.js → ReposTab-CyWedWZC.js} +2 -2
  56. package/extensions/dashboard-client/dist/assets/{ReposTab-DxLN1N4K.js.map → ReposTab-CyWedWZC.js.map} +1 -1
  57. package/extensions/dashboard-client/dist/assets/{SessionsTab-CZuI4ISW.js → SessionsTab-wqPBMIJZ.js} +2 -2
  58. package/extensions/dashboard-client/dist/assets/{SessionsTab-CZuI4ISW.js.map → SessionsTab-wqPBMIJZ.js.map} +1 -1
  59. package/extensions/dashboard-client/dist/assets/{SetupTab-C_0VOomm.js → SetupTab-MojXmuUf.js} +2 -2
  60. package/extensions/dashboard-client/dist/assets/{SetupTab-C_0VOomm.js.map → SetupTab-MojXmuUf.js.map} +1 -1
  61. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-BhbaRLmi.js → TimeSavedCard-BxcplEOJ.js} +2 -2
  62. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-BhbaRLmi.js.map → TimeSavedCard-BxcplEOJ.js.map} +1 -1
  63. package/extensions/dashboard-client/dist/assets/{TurnsTab-CXJmbjje.js → TurnsTab-D8_qWbjY.js} +2 -2
  64. package/extensions/dashboard-client/dist/assets/{TurnsTab-CXJmbjje.js.map → TurnsTab-D8_qWbjY.js.map} +1 -1
  65. package/extensions/dashboard-client/dist/assets/VectorCortexTab-B3yisAyB.js +2 -0
  66. package/extensions/dashboard-client/dist/assets/VectorCortexTab-B3yisAyB.js.map +1 -0
  67. package/extensions/dashboard-client/dist/assets/{WikiTab-C5uvMCzp.js → WikiTab-Cfd-QZYz.js} +2 -2
  68. package/extensions/dashboard-client/dist/assets/{WikiTab-C5uvMCzp.js.map → WikiTab-Cfd-QZYz.js.map} +1 -1
  69. package/extensions/dashboard-client/dist/assets/{button-Cl_fxJcg.js → button-tX5ht0bb.js} +2 -2
  70. package/extensions/dashboard-client/dist/assets/{button-Cl_fxJcg.js.map → button-tX5ht0bb.js.map} +1 -1
  71. package/extensions/dashboard-client/dist/assets/{card-BH8Le5YM.js → card-BT3Z5dDg.js} +2 -2
  72. package/extensions/dashboard-client/dist/assets/{card-BH8Le5YM.js.map → card-BT3Z5dDg.js.map} +1 -1
  73. package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-sZ6ZNtBi.js → generateCategoricalChart-B6p2WnkY.js} +2 -2
  74. package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-sZ6ZNtBi.js.map → generateCategoricalChart-B6p2WnkY.js.map} +1 -1
  75. package/extensions/dashboard-client/dist/assets/{index-CX9zv8cJ.js → index-CFLekP12.js} +3 -3
  76. package/extensions/dashboard-client/dist/assets/{index-CX9zv8cJ.js.map → index-CFLekP12.js.map} +1 -1
  77. package/extensions/dashboard-client/dist/assets/{switch-CXJhcjhM.js → switch-B52oAMSw.js} +2 -2
  78. package/extensions/dashboard-client/dist/assets/{switch-CXJhcjhM.js.map → switch-B52oAMSw.js.map} +1 -1
  79. package/extensions/dashboard-client/dist/assets/{toggle-CoLtIc6y.js → toggle-VxxVc5Tp.js} +2 -2
  80. package/extensions/dashboard-client/dist/assets/{toggle-CoLtIc6y.js.map → toggle-VxxVc5Tp.js.map} +1 -1
  81. package/extensions/dashboard-client/dist/assets/{useSSE-fSXho606.js → useSSE-DAVdZnG7.js} +2 -2
  82. package/extensions/dashboard-client/dist/assets/{useSSE-fSXho606.js.map → useSSE-DAVdZnG7.js.map} +1 -1
  83. package/extensions/dashboard-client/dist/index.html +1 -1
  84. package/extensions/dashboard-client/src/api/vector-cortex.ts +9 -0
  85. package/extensions/dashboard-client/src/tabs/VectorCortexTab.tsx +37 -0
  86. package/extensions/dashboard-client/src/types/vector-cortex.ts +16 -0
  87. package/extensions/dashboard-server/api-contracts/vector-cortex.ts +57 -0
  88. package/extensions/dashboard-server/routes-rag-settings-helpers.ts +12 -0
  89. package/extensions/dashboard-server/routes-vector-cortex-reconstruct.ts +41 -0
  90. package/extensions/dashboard-server/routes-vector-cortex-residual.ts +60 -0
  91. package/extensions/dashboard-server/routes-vector-cortex.ts +2 -0
  92. package/extensions/dashboard-server/routes.ts +2 -0
  93. package/extensions/dashboard-server/server.ts +4 -0
  94. package/package.json +1 -1
  95. package/src/config/vector-cortex.ts +27 -0
  96. package/src/config.ts +2 -0
  97. package/src/vector-cortex/reconstruct/_acceptance-helpers.ts +455 -0
  98. package/src/vector-cortex/reconstruct/assemble.ts +170 -0
  99. package/src/vector-cortex/reconstruct/closure.ts +299 -0
  100. package/src/vector-cortex/reconstruct/types.ts +330 -0
  101. package/src/vector-cortex/reconstruct/validate.ts +184 -0
  102. package/src/vector-cortex/residual/codec.ts +292 -0
  103. package/src/vector-cortex/residual/dct.ts +166 -0
  104. package/src/vector-cortex/residual/fixture-payload.ts +90 -0
  105. package/src/vector-cortex/residual/gf256.ts +196 -0
  106. package/src/vector-cortex/residual/parity.ts +283 -0
  107. package/src/vector-cortex/residual/quantize.ts +230 -0
  108. package/src/vector-cortex/residual/stream.ts +135 -0
  109. package/src/vector-cortex/residual/types.ts +236 -0
  110. package/extensions/dashboard-client/dist/assets/VectorCortexTab-BGe9hu3r.js +0 -2
  111. package/extensions/dashboard-client/dist/assets/VectorCortexTab-BGe9hu3r.js.map +0 -1
@@ -0,0 +1,330 @@
1
+ /**
2
+ * vector-cortex/reconstruct/types.ts — conservative closure + reconstruction
3
+ * fidelity contract (VC4C).
4
+ *
5
+ * Owns `ClosureResult` / `ReconstructionV1` — the contract of the sprint failure
6
+ * triad:
7
+ *
8
+ * A = closed semantic + exact/residual reconstruction (the normal path);
9
+ * B = greedy EXACT-only closure, forced when semantic validation fails;
10
+ * C = legacy prompt, forced by an unresolved contradiction (states its loss of
11
+ * old semantic context — TRIAD_RESILIENCE: C is continuity, NOT semantic
12
+ * completeness).
13
+ *
14
+ * Closure is MANDATORY before VC5 (CONTRACTS §plan and closure): recursively add
15
+ * every `depends`/tool-pair predecessor until a fixed point; for contradictions
16
+ * keep the LATER exact source resolution unless an explicit resolution event
17
+ * names the loser; ties keep both and reject live use
18
+ * (`CLO_CONTRADICTION_UNRESOLVED`). The anchor floor is preserved, and the closed
19
+ * mandatory node set is returned with its deterministic token estimate.
20
+ *
21
+ * OWNERSHIP BOUNDARY (CONTRACTS §plan and closure): `mandatoryTokenEstimate`
22
+ * counts CONTENT ONLY — no prompt framing, no role tags, no separators, no
23
+ * budget admission. VC5A exclusively owns framing/budget: it adds framing cost
24
+ * to this estimate and returns `MANDATORY_CLOSURE_OVER_BUDGET` if the mandatory
25
+ * cost exceeds its `tokenBudget`. VC4C therefore NEVER truncates a mandatory
26
+ * node and never reasons about a budget.
27
+ *
28
+ * Consumes only reviewer-accepted predecessor contracts (VC1A `EventV2` byte
29
+ * authority, VC4A `ShardRange`/`ExactShardV1`, VC4B `ParityShardV1` residual
30
+ * decode) and the common contracts. Pure types + registered conformance IDs: no
31
+ * storage, no console, no network (PREVENT-PI-004 / PREVENT-011).
32
+ */
33
+
34
+ import type { ShardRange } from "../shards/types.js";
35
+
36
+ /**
37
+ * The kind of a closure graph node, mirroring `DagNode.kind`
38
+ * (CONTRACTS §PromptDagV1). `exact` nodes carry authoritative source bytes;
39
+ * `semantic` nodes are derived and never claim to recover exact text;
40
+ * `synthetic` nodes have no source span and order after their prerequisites.
41
+ */
42
+ export type ClosureNodeKind = "event" | "exact" | "semantic" | "synthetic";
43
+
44
+ /**
45
+ * One node in the closure graph. `span` is the half-open source byte range this
46
+ * node occupies (absent for `synthetic` nodes, which have no source position).
47
+ * `anchor` marks a node inside the preserved anchor floor — closure preserves it
48
+ * and the validator rejects a reconstruction that drops it (PREVENT-PI-001's
49
+ * anchor-floor discipline, restated for the closed prompt).
50
+ *
51
+ * `resolvedAtMs` is the source resolution TIME used only for contradiction
52
+ * ordering: the LATER exact resolution wins. It is a source fact (the event's
53
+ * `occurredAtMs`), never a wall clock read at closure time — closure is pure and
54
+ * deterministic (TRIAD_RESILIENCE: wall time for records, never for eligibility).
55
+ */
56
+ export interface ClosureNode {
57
+ readonly id: string;
58
+ readonly kind: ClosureNodeKind;
59
+ /** Source span; absent only for `synthetic` nodes. */
60
+ readonly span?: ShardRange;
61
+ /** True when the node belongs to the preserved anchor floor. */
62
+ readonly anchor?: boolean;
63
+ /**
64
+ * Source resolution time for contradiction ordering (from the source event,
65
+ * never `Date.now()`). Two contradicting nodes with EQUAL or ABSENT
66
+ * resolutions are an unresolved tie.
67
+ */
68
+ readonly resolvedAtMs?: bigint;
69
+ /**
70
+ * Deterministic CONTENT token estimate for this node (no framing). Summed into
71
+ * `ClosureResult.mandatoryTokenEstimate` and handed unchanged to VC5A.
72
+ */
73
+ readonly tokenEstimate: number;
74
+ }
75
+
76
+ /**
77
+ * One directed closure edge. Edges point prerequisite/earlier **from →
78
+ * dependent/later to** (CONTRACTS §PromptDagV1).
79
+ *
80
+ * - `depends` — `to` requires `from`; closure pulls `from` in transitively;
81
+ * - `tool-pair` — a tool call/result pair that must be selected WHOLE (never
82
+ * split at a compaction boundary — PREVENT-PI-002);
83
+ * - `contradicts` — mutually exclusive claims; the later exact resolution wins.
84
+ */
85
+ export type ClosureEdgeKind = "depends" | "tool-pair" | "contradicts";
86
+
87
+ /** A directed closure edge (`from` is the prerequisite/earlier endpoint). */
88
+ export interface ClosureEdge {
89
+ readonly from: string;
90
+ readonly to: string;
91
+ readonly kind: ClosureEdgeKind;
92
+ }
93
+
94
+ /**
95
+ * An explicit resolution event that names the LOSER of a contradiction
96
+ * (CONTRACTS §plan and closure: "keep the later exact source unless an explicit
97
+ * resolution event names the loser"). An explicit resolution therefore
98
+ * OVERRIDES the later-wins time rule and breaks what would otherwise be a tie.
99
+ */
100
+ export interface ContradictionResolution {
101
+ /** The node id explicitly superseded (dropped from the closure). */
102
+ readonly loserId: string;
103
+ /** The node id that survives. */
104
+ readonly winnerId: string;
105
+ }
106
+
107
+ /** The closure graph handed to `closeSelection`. */
108
+ export interface ClosureGraph {
109
+ readonly sessionId: string;
110
+ readonly nodes: readonly ClosureNode[];
111
+ readonly edges: readonly ClosureEdge[];
112
+ /** Explicit resolutions naming contradiction losers (may be empty). */
113
+ readonly resolutions?: readonly ContradictionResolution[];
114
+ }
115
+
116
+ /**
117
+ * A single recorded closure step — the PROOF that the fixed point was reached by
118
+ * a defensible derivation rather than asserted. Each step names the node added
119
+ * and the edge/rule that forced it.
120
+ */
121
+ export interface ClosureProofStep {
122
+ /** The node id added by this step. */
123
+ readonly added: string;
124
+ /** The already-selected node that required it (absent for a seed). */
125
+ readonly requiredBy?: string;
126
+ /** Why it was added. */
127
+ readonly rule: "seed" | "depends" | "tool-pair" | "anchor-floor";
128
+ }
129
+
130
+ /** Closure failure codes (registered CLO codes). */
131
+ export type ClosureFailureCode =
132
+ /** A contradiction whose resolutions are equal/unordered — reject live use. */
133
+ | "CLO_CONTRADICTION_UNRESOLVED"
134
+ /** An edge names a node id that is not in the graph. */
135
+ | "CLO_MISSING_NODE"
136
+ /** A seed id is not in the graph. */
137
+ | "CLO_UNKNOWN_SEED";
138
+
139
+ /**
140
+ * The closed mandatory node set (CONTRACTS §plan and closure). `ok:false` means
141
+ * the closure is NOT live-usable and the adapter demotes (C on an unresolved
142
+ * contradiction).
143
+ *
144
+ * `selected` is the fixed point: every seed plus every transitively required
145
+ * dependency and whole tool pair, sorted deterministically by node id so the
146
+ * result is stable across input permutations. `mandatoryTokenEstimate` is the
147
+ * CONTENT-ONLY sum handed UNCHANGED to VC5A (which adds framing and owns budget
148
+ * admission — VC4C never truncates a mandatory node).
149
+ */
150
+ export interface ClosureResult {
151
+ readonly ok: boolean;
152
+ /** The closed selection (sorted by node id). */
153
+ readonly selected: readonly string[];
154
+ /** Dependencies/tool-pair members pulled in beyond the seeds (sorted). */
155
+ readonly addedDependencies: readonly string[];
156
+ /** Contradiction losers removed by the later-exact / explicit rule (sorted). */
157
+ readonly removedContradictions: readonly string[];
158
+ /** Contradictions that could not be resolved (sorted) — reject live use. */
159
+ readonly unresolved: readonly string[];
160
+ /** Ordered derivation proof of the fixed point. */
161
+ readonly proof: readonly ClosureProofStep[];
162
+ /** Failure codes; empty when `ok`. */
163
+ readonly failures: readonly ClosureFailureCode[];
164
+ /**
165
+ * Deterministic CONTENT-ONLY token estimate of the closed mandatory set.
166
+ * Contains NO prompt framing (VC5A adds that and owns budget admission).
167
+ */
168
+ readonly mandatoryTokenEstimate: number;
169
+ }
170
+
171
+ /**
172
+ * One assembled span of the reconstruction. `bytes` are the authoritative source
173
+ * bytes for `range` — either verbatim exact-shard bytes (`source:"exact"`), a
174
+ * byte-exact residual decode (`source:"residual"`), or a derived semantic
175
+ * rendering that NEVER claims to be the exact text (`source:"semantic"`).
176
+ * `protectedSpan` marks a span the validator requires to be present and exact.
177
+ */
178
+ export interface ReconstructionSpan {
179
+ readonly nodeId: string;
180
+ readonly range: ShardRange;
181
+ readonly source: "exact" | "residual" | "semantic";
182
+ readonly bytes: Uint8Array;
183
+ /** SHA-256 of `bytes`, lowercase hex (no `sha256:` prefix). */
184
+ readonly digest: string;
185
+ /** True when this span must survive verbatim (tool pair / anchor / invalid UTF-8). */
186
+ readonly protectedSpan: boolean;
187
+ }
188
+
189
+ /**
190
+ * The assembled reconstruction (VC4C's outbound contract to VC5A). Spans are
191
+ * ordered SOLELY by source range (`byteStart`, then `seqStart`, then node id for
192
+ * a total order) — never by selection order, map iteration, or scoring, so the
193
+ * assembly is deterministic and replayable. `digest` is one SHA-256 over the
194
+ * ordered span digests plus their ranges.
195
+ */
196
+ export interface ReconstructionV1 {
197
+ readonly schema: "reconstruction-v1";
198
+ readonly sessionId: string;
199
+ /** Spans in source order (the concatenation order). */
200
+ readonly spans: readonly ReconstructionSpan[];
201
+ /** Deterministic digest over the ordered spans. */
202
+ readonly digest: string;
203
+ /** Total assembled byte count. */
204
+ readonly byteTotal: number;
205
+ /**
206
+ * CONTENT-ONLY mandatory token estimate, carried UNCHANGED from the closure so
207
+ * VC5A receives exactly the number VC4C computed (no framing, no budget).
208
+ */
209
+ readonly mandatoryTokenEstimate: number;
210
+ }
211
+
212
+ /** Reconstruction/validation failure codes (registered REC codes). */
213
+ export type ReconstructionFailureCode =
214
+ /** A required source shard is missing AND its residual fallback failed. */
215
+ | "REC_SOURCE_UNAVAILABLE"
216
+ /** A protected anchor span is absent from the reconstruction. */
217
+ | "REC_ANCHOR_MISSING"
218
+ /** A tool call/result pair was split (PREVENT-PI-002). */
219
+ | "REC_TOOL_PAIR_SPLIT"
220
+ /** A span's bytes do not hash to its recorded digest. */
221
+ | "REC_DIGEST_MISMATCH"
222
+ /** The closure carried an unresolved contradiction — never goes live. */
223
+ | "REC_CONTRADICTION_UNRESOLVED"
224
+ /** Two assembled spans overlap in the source byte stream. */
225
+ | "REC_SPAN_OVERLAP";
226
+
227
+ /**
228
+ * Validation verdict. Reader-facing surface is SUMMARY + CODES ONLY — never span
229
+ * bytes, never prompt text (SECURITY_PRIVACY: the exact ledger is not training
230
+ * data and is never rendered through a diagnostic surface).
231
+ */
232
+ export type ReconstructionValidation =
233
+ | { readonly ok: true; readonly summary: ReconstructionSummary }
234
+ | { readonly ok: false; readonly codes: readonly ReconstructionFailureCode[] };
235
+
236
+ /**
237
+ * Aggregate-only reconstruction summary exposed to the dashboard. Counts, byte
238
+ * totals and the digest identity — NEVER payload bytes or prompt text.
239
+ */
240
+ export interface ReconstructionSummary {
241
+ readonly sessionId: string;
242
+ readonly spanCount: number;
243
+ readonly protectedSpanCount: number;
244
+ readonly byteTotal: number;
245
+ readonly mandatoryTokenEstimate: number;
246
+ readonly digest: string;
247
+ /** Per-source span counts (exact / residual / semantic). */
248
+ readonly bySource: {
249
+ readonly exact: number;
250
+ readonly residual: number;
251
+ readonly semantic: number;
252
+ };
253
+ }
254
+
255
+ /** The two structured events the VC4C reporter emits. */
256
+ export type ReconstructEventName =
257
+ | "vector_cortex_reconstruction_validated"
258
+ | "vector_cortex_closure_rejected";
259
+
260
+ /** Injected emit callback — same (event, fields) shape as the other VC seams. */
261
+ export type ReconstructEmitter = (
262
+ event: ReconstructEventName,
263
+ fields: Record<string, unknown>,
264
+ ) => void;
265
+
266
+ /** Typed, best-effort reporter bound to the two reconstruction event names. */
267
+ export interface ReconstructReporter {
268
+ readonly reconstructionValidated: (fields: Record<string, unknown>) => void;
269
+ readonly closureRejected: (fields: Record<string, unknown>) => void;
270
+ }
271
+
272
+ /**
273
+ * Aggregate-only reconstruction metrics for the dashboard (counts/bytes only).
274
+ */
275
+ export interface ReconstructMetricsV1 {
276
+ readonly closureAttempts: number;
277
+ readonly closureRejections: number;
278
+ readonly validatedCount: number;
279
+ readonly invalidatedCount: number;
280
+ readonly spanTotal: number;
281
+ readonly byteTotal: number;
282
+ }
283
+
284
+ /**
285
+ * The triad mode VC4C selects (TRIAD_RESILIENCE). A/B/C use INDEPENDENT
286
+ * algorithms: A closes over semantic+exact/residual; B is a greedy EXACT-only
287
+ * closure that shares no semantic index with A; C abandons the closed prompt
288
+ * entirely and returns the legacy transcript, stating its semantic loss.
289
+ */
290
+ export type ReconstructMode = "A" | "B" | "C";
291
+
292
+ /**
293
+ * The outcome of the triad selection: the mode taken, the validated
294
+ * reconstruction (A/B) and the reason C was forced, if it was.
295
+ */
296
+ export interface ReconstructTriadOutcome {
297
+ readonly mode: ReconstructMode;
298
+ readonly reconstruction: ReconstructionV1 | null;
299
+ readonly codes: readonly ReconstructionFailureCode[];
300
+ /**
301
+ * Set only in mode C: the explicit statement that old semantic context is lost
302
+ * (TRIAD_RESILIENCE — "C states its loss of old semantic context").
303
+ */
304
+ readonly semanticLossStated: boolean;
305
+ }
306
+
307
+ /**
308
+ * Registered CLO conformance ID range (CLO-001..030). The acceptance test reads
309
+ * these rows from the v2 manifest and asserts each returns its manifest
310
+ * `ok`/`code`.
311
+ */
312
+ export const CLO_IDS: readonly string[] = Array.from(
313
+ { length: 30 },
314
+ (_v, i) => `CLO-${String(i + 1).padStart(3, "0")}`,
315
+ );
316
+
317
+ /** Registered REC conformance ID range (REC-001..030). */
318
+ export const REC_IDS: readonly string[] = Array.from(
319
+ { length: 30 },
320
+ (_v, i) => `REC-${String(i + 1).padStart(3, "0")}`,
321
+ );
322
+
323
+ /** Named VC4C conformance assertions (the sprint's headline rows). */
324
+ export const RECONSTRUCT_NAMED_IDS = [
325
+ "CLO-TRANSITIVE-001",
326
+ "CLO-CONTRA-002",
327
+ "REC-ORDER-003",
328
+ ] as const;
329
+
330
+ export type { ShardRange };
@@ -0,0 +1,184 @@
1
+ /**
2
+ * vector-cortex/reconstruct/validate.ts — reconstruction validation (VC4C).
3
+ *
4
+ * Task 5: a validator that rejects a closed selection that would corrupt a live
5
+ * prompt and emits exactly two events:
6
+ * - `vector_cortex_reconstruction_validated` (the good outcome)
7
+ * - `vector_cortex_closure_rejected` (a rejected/cancelled closure)
8
+ *
9
+ * Rejection reasons (the failure codes are the ONLY externally-visible detail):
10
+ * - REC_ANCHOR_MISSING an anchor-floor node is absent from the closure
11
+ * - REC_TOOL_PAIR_SPLIT a tool-pair is not contiguous (PREVENT-PI-002)
12
+ * - REC_DIGEST_MISMATCH a decoded shard's bytes disagree with its digest
13
+ * - REC_CONTRADICTION_UNRESOLVED an unresolved tie (closure already failed)
14
+ * - REC_SOURCE_UNAVAILABLE a required shard is missing/erased (failure inj.)
15
+ * - REC_SPAN_OVERLAP two spans intersect in source byte space
16
+ *
17
+ * The validator NEVER emits content; it exposes only a `ReconstructionSummary`
18
+ * (counts + digest + token estimate) or the failure `codes`. Assembly/closure
19
+ * errors are surfaced but the validator is the authoritative last gate.
20
+ *
21
+ * OWNERSHIP: this is a PURE function over its inputs — no storage, no network,
22
+ * no console. The dashboard/seams that consume it live in extensions/, which may
23
+ * emit observability; this module stays silent (structured logging contract).
24
+ */
25
+
26
+ import { createHash } from "node:crypto";
27
+ import { assembleSourceOrder, type DecodedShard } from "./assemble.js";
28
+ import type {
29
+ ClosureEdge,
30
+ ClosureGraph,
31
+ ClosureNode,
32
+ ClosureResult,
33
+ ReconstructEmitter,
34
+ ReconstructReporter,
35
+ ReconstructionFailureCode,
36
+ ReconstructionSummary,
37
+ ReconstructionV1,
38
+ ReconstructionValidation,
39
+ } from "./types.js";
40
+
41
+ /** Flag-gated reporter — mirrors the VC4B residual reporter pattern. */
42
+ export function createReconstructReporter(emit?: ReconstructEmitter): ReconstructReporter {
43
+ const fire = (event: Parameters<ReconstructEmitter>[0], fields: Record<string, unknown>): void => {
44
+ if (!emit) return;
45
+ try {
46
+ emit(event, fields);
47
+ } catch {
48
+ /* non-fatal observability — never break the agent loop */
49
+ }
50
+ };
51
+ return {
52
+ reconstructionValidated: (fields): void => fire("vector_cortex_reconstruction_validated", fields),
53
+ closureRejected: (fields): void => fire("vector_cortex_closure_rejected", fields),
54
+ };
55
+ }
56
+
57
+ /** Sync SHA-256 hex (validator is sync except for assembly's concat digest). */
58
+ function sha256HexSync(bytes: Uint8Array): string {
59
+ return createHash("sha256").update(bytes).digest("hex");
60
+ }
61
+
62
+ /** Verify each decoded shard's bytes hash to its declared digest (REC_DIGEST_MISMATCH). */
63
+ function findDigestMismatch(shards: readonly DecodedShard[]): ReconstructionFailureCode | null {
64
+ for (const s of shards) {
65
+ // A pinned digest of "0" is a placeholder: the source tier did not compute a
66
+ // per-shard digest, so the only guarantee is the post-assembly concatenation
67
+ // digest. Any other digest is a real pin that must match exactly.
68
+ if (s.digest === "0") continue;
69
+ const computed = sha256HexSync(s.bytes);
70
+ if (computed !== s.digest) return "REC_DIGEST_MISMATCH";
71
+ }
72
+ return null;
73
+ }
74
+
75
+ export interface ValidateInput {
76
+ readonly graph: ClosureGraph;
77
+ readonly closure: ClosureResult;
78
+ readonly nodes: readonly ClosureNode[];
79
+ readonly edges: readonly ClosureEdge[];
80
+ readonly shards: readonly DecodedShard[];
81
+ readonly emit?: ReconstructEmitter;
82
+ }
83
+
84
+ /**
85
+ * Validate a closed selection and, on success, assemble it into source order.
86
+ * Returns the discriminated `ReconstructionValidation`: ok -> summary only;
87
+ * fail -> failure codes only. Emits exactly one of the two events.
88
+ */
89
+ export async function validateAndAssemble(input: ValidateInput): Promise<{
90
+ readonly validation: ReconstructionValidation;
91
+ readonly reconstruction: ReconstructionV1 | null;
92
+ }> {
93
+ const { graph, closure, nodes, edges, shards, emit } = input;
94
+ const reporter = createReconstructReporter(emit);
95
+
96
+ // 1. A closure that failed its own contradiction resolution cannot go live.
97
+ if (!closure.ok) {
98
+ const codes: ReconstructionFailureCode[] = ["REC_CONTRADICTION_UNRESOLVED"];
99
+ reporter.closureRejected({ sessionId: graph.sessionId, codes, reason: "closure-not-ok" });
100
+ return {
101
+ validation: { ok: false, codes },
102
+ reconstruction: null,
103
+ };
104
+ }
105
+
106
+ // 2. Anchor-floor discipline (PREVENT-PI-001 restated): every anchor node must
107
+ // be present in the closed set, or the closure silently dropped a floor
108
+ // item and must be rejected.
109
+ const anchorMissing = nodes.some((n) => n.anchor === true && !closure.selected.includes(n.id));
110
+ if (anchorMissing) {
111
+ reporter.closureRejected({ sessionId: graph.sessionId, codes: ["REC_ANCHOR_MISSING"], reason: "anchor-missing" });
112
+ return {
113
+ validation: { ok: false, codes: ["REC_ANCHOR_MISSING"] },
114
+ reconstruction: null,
115
+ };
116
+ }
117
+
118
+ // 3. Unresolved contradiction present in the closed set.
119
+ if (closure.unresolved.length > 0) {
120
+ const codes = ["REC_CONTRADICTION_UNRESOLVED"] as ReconstructionFailureCode[];
121
+ reporter.closureRejected({ sessionId: graph.sessionId, codes, reason: "unresolved-contradiction" });
122
+ return {
123
+ validation: { ok: false, codes },
124
+ reconstruction: null,
125
+ };
126
+ }
127
+
128
+ // 4. Per-shard digest pre-check hook (REC_DIGEST_MISMATCH path preserved).
129
+ const digestCode = findDigestMismatch(shards);
130
+ if (digestCode !== null) {
131
+ reporter.closureRejected({ sessionId: graph.sessionId, codes: [digestCode], reason: "digest-mismatch" });
132
+ return {
133
+ validation: { ok: false, codes: [digestCode] },
134
+ reconstruction: null,
135
+ };
136
+ }
137
+
138
+ // 5. Assembly: missing source (REC_SOURCE_UNAVAILABLE) / split pair
139
+ // (REC_TOOL_PAIR_SPLIT) / overlap (REC_SPAN_OVERLAP) all surface here.
140
+ const assembled = await assembleSourceOrder({
141
+ sessionId: graph.sessionId,
142
+ selected: closure.selected,
143
+ nodes,
144
+ edges,
145
+ shards,
146
+ mandatoryTokenEstimate: closure.mandatoryTokenEstimate,
147
+ });
148
+ if (assembled.code !== null || assembled.reconstruction === null) {
149
+ const code = assembled.code ?? "REC_DIGEST_MISMATCH";
150
+ reporter.closureRejected({ sessionId: graph.sessionId, codes: [code], reason: "assembly-failed" });
151
+ return {
152
+ validation: { ok: false, codes: [code] },
153
+ reconstruction: null,
154
+ };
155
+ }
156
+
157
+ const rec = assembled.reconstruction;
158
+ const summary: ReconstructionSummary = buildSummary(rec);
159
+ reporter.reconstructionValidated({
160
+ sessionId: rec.sessionId,
161
+ spanCount: summary.spanCount,
162
+ protectedSpanCount: summary.protectedSpanCount,
163
+ byteTotal: summary.byteTotal,
164
+ mandatoryTokenEstimate: summary.mandatoryTokenEstimate,
165
+ digest: summary.digest,
166
+ bySource: summary.bySource,
167
+ });
168
+ return { validation: { ok: true, summary }, reconstruction: rec };
169
+ }
170
+
171
+ function buildSummary(rec: ReconstructionV1): ReconstructionSummary {
172
+ const exact = rec.spans.filter((s) => s.source === "exact").length;
173
+ const residual = rec.spans.filter((s) => s.source === "residual").length;
174
+ const semantic = rec.spans.filter((s) => s.source === "semantic").length;
175
+ return {
176
+ sessionId: rec.sessionId,
177
+ spanCount: rec.spans.length,
178
+ protectedSpanCount: rec.spans.filter((s) => s.protectedSpan).length,
179
+ byteTotal: rec.byteTotal,
180
+ mandatoryTokenEstimate: rec.mandatoryTokenEstimate,
181
+ digest: rec.digest,
182
+ bySource: { exact, residual, semantic },
183
+ };
184
+ }