pi-mega-compact 0.19.3 → 0.20.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 +24 -0
- package/dist/config.js +1 -1
- package/dist/extensions/dashboard-server/routes-cache.test/_helpers.js +2 -0
- package/dist/extensions/dashboard-server/routes-rag-settings-helpers.js +2 -0
- package/dist/extensions/dashboard-server/routes-vector-cortex-helpers.js +100 -0
- package/dist/extensions/dashboard-server/routes-vector-cortex-residual.js +51 -0
- package/dist/extensions/dashboard-server/routes-vector-cortex-shards.js +48 -0
- package/dist/extensions/dashboard-server/routes-vector-cortex.js +2 -0
- package/dist/extensions/dashboard-server/routes.js +1 -1
- package/dist/extensions/dashboard-server/server.js +41 -16
- package/dist/extensions/dashboard-server/tailscale.js +32 -0
- package/dist/src/config/vector-cortex.js +24 -0
- package/dist/src/config.js +1 -1
- package/dist/src/vector-cortex/residual/codec.js +224 -0
- package/dist/src/vector-cortex/residual/dct.js +158 -0
- package/dist/src/vector-cortex/residual/fixture-payload.js +77 -0
- package/dist/src/vector-cortex/residual/gf256.js +182 -0
- package/dist/src/vector-cortex/residual/parity.js +245 -0
- package/dist/src/vector-cortex/residual/quantize.js +200 -0
- package/dist/src/vector-cortex/residual/stream.js +124 -0
- package/dist/src/vector-cortex/residual/types.js +55 -0
- package/dist/src/vector-cortex/shards/exact.js +134 -0
- package/dist/src/vector-cortex/shards/manifest.js +237 -0
- package/dist/src/vector-cortex/shards/semantic.js +137 -0
- package/dist/src/vector-cortex/shards/types.js +51 -0
- package/dist/vector-cortex/residual/codec.js +224 -0
- package/dist/vector-cortex/residual/dct.js +158 -0
- package/dist/vector-cortex/residual/fixture-payload.js +77 -0
- package/dist/vector-cortex/residual/gf256.js +182 -0
- package/dist/vector-cortex/residual/parity.js +245 -0
- package/dist/vector-cortex/residual/quantize.js +200 -0
- package/dist/vector-cortex/residual/stream.js +124 -0
- package/dist/vector-cortex/residual/types.js +55 -0
- package/dist/vector-cortex/shards/exact.js +134 -0
- package/dist/vector-cortex/shards/manifest.js +237 -0
- package/dist/vector-cortex/shards/semantic.js +137 -0
- package/dist/vector-cortex/shards/types.js +51 -0
- package/extensions/dashboard-client/dist/assets/{AreaChart-DqiFSnDx.js → AreaChart-n4z5w9Ox.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{AreaChart-DqiFSnDx.js.map → AreaChart-n4z5w9Ox.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{BarChart-Cqg-PQMK.js → BarChart-BLGjWWBr.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{BarChart-Cqg-PQMK.js.map → BarChart-BLGjWWBr.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{CacheTab-BPNs0xIF.js → CacheTab-CAnrKKVK.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{CacheTab-BPNs0xIF.js.map → CacheTab-CAnrKKVK.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{EventsTab-BQf7OGkf.js → EventsTab-D-GL7Ngq.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{EventsTab-BQf7OGkf.js.map → EventsTab-D-GL7Ngq.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{HealthTab-B14TaSPN.js → HealthTab-C4x5qQ8s.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{HealthTab-B14TaSPN.js.map → HealthTab-C4x5qQ8s.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{MaintenanceTab-D8lkRoa1.js → MaintenanceTab-BSPs0eq5.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{MaintenanceTab-D8lkRoa1.js.map → MaintenanceTab-BSPs0eq5.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{MemoryMapTab-BOWtGfpx.js → MemoryMapTab-BWEUtTSu.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{MemoryMapTab-BOWtGfpx.js.map → MemoryMapTab-BWEUtTSu.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{MetricsTab-7XI9cWaX.js → MetricsTab-Dhm1c3Cx.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{MetricsTab-7XI9cWaX.js.map → MetricsTab-Dhm1c3Cx.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{OverviewTab-C9KaGYvh.js → OverviewTab-Cm6cySiQ.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{OverviewTab-C9KaGYvh.js.map → OverviewTab-Cm6cySiQ.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{ReposTab-BwESNhox.js → ReposTab-DxLN1N4K.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{ReposTab-BwESNhox.js.map → ReposTab-DxLN1N4K.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{SessionsTab-DKH55Rda.js → SessionsTab-CZuI4ISW.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{SessionsTab-DKH55Rda.js.map → SessionsTab-CZuI4ISW.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{SetupTab-zDxf-nJd.js → SetupTab-C_0VOomm.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{SetupTab-zDxf-nJd.js.map → SetupTab-C_0VOomm.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{TimeSavedCard-C9isog4L.js → TimeSavedCard-BhbaRLmi.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{TimeSavedCard-C9isog4L.js.map → TimeSavedCard-BhbaRLmi.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{TurnsTab-ciI6ydvj.js → TurnsTab-CXJmbjje.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{TurnsTab-ciI6ydvj.js.map → TurnsTab-CXJmbjje.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/VectorCortexTab-BGe9hu3r.js +2 -0
- package/extensions/dashboard-client/dist/assets/VectorCortexTab-BGe9hu3r.js.map +1 -0
- package/extensions/dashboard-client/dist/assets/{WikiTab-DcYHc734.js → WikiTab-C5uvMCzp.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{WikiTab-DcYHc734.js.map → WikiTab-C5uvMCzp.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{button-DF8lx4bt.js → button-Cl_fxJcg.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{button-DF8lx4bt.js.map → button-Cl_fxJcg.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{card-DIoDheSZ.js → card-BH8Le5YM.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{card-DIoDheSZ.js.map → card-BH8Le5YM.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-BFRzeYX3.js → generateCategoricalChart-sZ6ZNtBi.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-BFRzeYX3.js.map → generateCategoricalChart-sZ6ZNtBi.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{index-DSZON0Yi.js → index-CX9zv8cJ.js} +3 -3
- package/extensions/dashboard-client/dist/assets/{index-DSZON0Yi.js.map → index-CX9zv8cJ.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{switch-l4qo22mU.js → switch-CXJhcjhM.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{switch-l4qo22mU.js.map → switch-CXJhcjhM.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{toggle-DPn6td1_.js → toggle-CoLtIc6y.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{toggle-DPn6td1_.js.map → toggle-CoLtIc6y.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{useSSE-BLmolqTJ.js → useSSE-fSXho606.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{useSSE-BLmolqTJ.js.map → useSSE-fSXho606.js.map} +1 -1
- package/extensions/dashboard-client/dist/index.html +1 -1
- package/extensions/dashboard-client/src/api/vector-cortex.ts +9 -0
- package/extensions/dashboard-client/src/tabs/VectorCortexTab.tsx +35 -0
- package/extensions/dashboard-client/src/types/vector-cortex.ts +13 -0
- package/extensions/dashboard-server/api-contracts/vector-cortex.ts +53 -0
- package/extensions/dashboard-server/routes-cache.test/_helpers.ts +2 -0
- package/extensions/dashboard-server/routes-rag-settings-helpers.ts +12 -0
- package/extensions/dashboard-server/routes-vector-cortex-helpers.ts +110 -0
- package/extensions/dashboard-server/routes-vector-cortex-residual.ts +60 -0
- package/extensions/dashboard-server/routes-vector-cortex-shards.ts +57 -0
- package/extensions/dashboard-server/routes-vector-cortex.ts +2 -0
- package/extensions/dashboard-server/routes.ts +2 -0
- package/extensions/dashboard-server/server.ts +46 -17
- package/extensions/dashboard-server/tailscale.ts +32 -0
- package/package.json +1 -1
- package/src/config/vector-cortex.ts +26 -0
- package/src/config.ts +2 -0
- package/src/vector-cortex/residual/codec.ts +292 -0
- package/src/vector-cortex/residual/dct.ts +166 -0
- package/src/vector-cortex/residual/fixture-payload.ts +90 -0
- package/src/vector-cortex/residual/gf256.ts +196 -0
- package/src/vector-cortex/residual/parity.ts +283 -0
- package/src/vector-cortex/residual/quantize.ts +230 -0
- package/src/vector-cortex/residual/stream.ts +135 -0
- package/src/vector-cortex/residual/types.ts +236 -0
- package/src/vector-cortex/shards/exact.ts +141 -0
- package/src/vector-cortex/shards/manifest.ts +276 -0
- package/src/vector-cortex/shards/semantic.ts +156 -0
- package/src/vector-cortex/shards/types.ts +212 -0
- package/extensions/dashboard-client/dist/assets/VectorCortexTab-qTZ7NWng.js +0 -2
- package/extensions/dashboard-client/dist/assets/VectorCortexTab-qTZ7NWng.js.map +0 -1
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* vector-cortex/residual/codec.ts — reversible residual payload codec (VC4B).
|
|
3
|
+
*
|
|
4
|
+
* Encode: split `EventV2.originalBytes` into 4096-byte blocks (zero-padding only
|
|
5
|
+
* the final block), map bytes to `x=(byte-127.5)/127.5`, take the orthonormal
|
|
6
|
+
* DCT-II, quantize to int16 with a per-block float32 scale, reconstruct, and
|
|
7
|
+
* append a block-scoped EXACT correction stream wherever the reconstruction
|
|
8
|
+
* differs. Post-decode byte error for an admitted artifact is therefore exactly
|
|
9
|
+
* ZERO — the digest is verified before admission, never assumed.
|
|
10
|
+
*
|
|
11
|
+
* Admission (RESIDUAL_CODEC §admission): residual is admitted only when the FULL
|
|
12
|
+
* encoded size — header, scales, coefficients, corrections, shard index/length
|
|
13
|
+
* metadata, all 9 shards and their digests — is `<= floor(0.95 *
|
|
14
|
+
* exactCompressedSize)` AND the complete decode + digest check succeeds.
|
|
15
|
+
* Otherwise the caller stores the exact compressed payload (mode B). Coefficient
|
|
16
|
+
* bytes alone are never compared.
|
|
17
|
+
*
|
|
18
|
+
* Emits `vector_cortex_residual_admitted` / `vector_cortex_parity_recovery_failed`
|
|
19
|
+
* through the flag-gated reporter and exposes AGGREGATE-ONLY residual metrics
|
|
20
|
+
* (counts/byte totals — never payload).
|
|
21
|
+
*
|
|
22
|
+
* Guardrails: local hashing only, no storage, no console, no network
|
|
23
|
+
* (PREVENT-PI-004 / PREVENT-011).
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import { createHash } from "node:crypto";
|
|
27
|
+
import { VC4B_ENABLED } from "../../config/vector-cortex.js";
|
|
28
|
+
import {
|
|
29
|
+
bytesToSignal,
|
|
30
|
+
forwardDct,
|
|
31
|
+
inverseDct,
|
|
32
|
+
signalToBytes,
|
|
33
|
+
splitBlocks,
|
|
34
|
+
} from "./dct.js";
|
|
35
|
+
import {
|
|
36
|
+
applyCorrections,
|
|
37
|
+
dequantizeBlock,
|
|
38
|
+
diffBlock,
|
|
39
|
+
quantizeBlock,
|
|
40
|
+
} from "./quantize.js";
|
|
41
|
+
import { encodeShards, recoverStream, sha256Hex } from "./parity.js";
|
|
42
|
+
import { parseStream, serializeStream } from "./stream.js";
|
|
43
|
+
import {
|
|
44
|
+
ADMISSION_DENOMINATOR,
|
|
45
|
+
ADMISSION_NUMERATOR,
|
|
46
|
+
RESIDUAL_BLOCK_SIZE,
|
|
47
|
+
RESIDUAL_MAGIC,
|
|
48
|
+
RS_DATA_SHARDS,
|
|
49
|
+
RS_PARITY_SHARDS,
|
|
50
|
+
type BlockCorrectionsV1,
|
|
51
|
+
type ParityShardV1,
|
|
52
|
+
type QuantizedBlockV1,
|
|
53
|
+
type ResidualAccountingV1,
|
|
54
|
+
type ResidualCodecV1,
|
|
55
|
+
type ResidualDecodeResult,
|
|
56
|
+
type ResidualEmitter,
|
|
57
|
+
type ResidualEncodeResult,
|
|
58
|
+
type ResidualMetricsV1,
|
|
59
|
+
type ResidualReporter,
|
|
60
|
+
} from "./types.js";
|
|
61
|
+
|
|
62
|
+
/** Per-shard persisted metadata: u8 index + u32 LE length + 32-byte digest. */
|
|
63
|
+
const SHARD_METADATA_BYTES = 1 + 4 + 32;
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* The inclusive admission ceiling `floor(0.95 * exactCompressedSize)`, computed
|
|
67
|
+
* in integer arithmetic so the boundary is exact (a fractional 0.95 multiply
|
|
68
|
+
* would make the "one byte above rejects" case depend on float rounding).
|
|
69
|
+
*/
|
|
70
|
+
export function admissionCeiling(exactCompressedSize: number): number {
|
|
71
|
+
return Math.floor(
|
|
72
|
+
(exactCompressedSize * ADMISSION_NUMERATOR) / ADMISSION_DENOMINATOR,
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Total persisted bytes of the shard set (payload + per-shard metadata). */
|
|
77
|
+
export function shardSetBytes(shards: readonly ParityShardV1[]): number {
|
|
78
|
+
return shards.reduce(
|
|
79
|
+
(n, s) => n + s.bytes.length + SHARD_METADATA_BYTES,
|
|
80
|
+
0,
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Build the codec artifact (transform + quantize + exact corrections). */
|
|
85
|
+
export function buildArtifact(
|
|
86
|
+
payload: Uint8Array,
|
|
87
|
+
): { ok: true; codec: ResidualCodecV1 } | { ok: false; code: "RES_QUANTIZE_RANGE" } {
|
|
88
|
+
const digest = sha256Hex(payload);
|
|
89
|
+
const rawBlocks = splitBlocks(payload, RESIDUAL_BLOCK_SIZE);
|
|
90
|
+
const blocks: QuantizedBlockV1[] = [];
|
|
91
|
+
const corrections: BlockCorrectionsV1[] = [];
|
|
92
|
+
|
|
93
|
+
for (let b = 0; b < rawBlocks.length; b++) {
|
|
94
|
+
const original = rawBlocks[b]!;
|
|
95
|
+
const quantized = quantizeBlock(forwardDct(bytesToSignal(original)));
|
|
96
|
+
if (!quantized.ok) return { ok: false, code: "RES_QUANTIZE_RANGE" };
|
|
97
|
+
blocks.push(quantized.block);
|
|
98
|
+
// Reconstruct and diff: any residual byte error becomes an exact correction.
|
|
99
|
+
const reconstructed = signalToBytes(
|
|
100
|
+
inverseDct(dequantizeBlock(quantized.block)),
|
|
101
|
+
);
|
|
102
|
+
const diff = diffBlock(original, reconstructed);
|
|
103
|
+
if (diff.length > 0) corrections.push({ blockIndex: b, corrections: diff });
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
return {
|
|
107
|
+
ok: true,
|
|
108
|
+
codec: {
|
|
109
|
+
schema: "residual-codec-v1",
|
|
110
|
+
header: {
|
|
111
|
+
magic: RESIDUAL_MAGIC,
|
|
112
|
+
originalLength: payload.length,
|
|
113
|
+
payloadDigest: digest,
|
|
114
|
+
blockSize: RESIDUAL_BLOCK_SIZE,
|
|
115
|
+
dataShards: RS_DATA_SHARDS,
|
|
116
|
+
parityShards: RS_PARITY_SHARDS,
|
|
117
|
+
},
|
|
118
|
+
blocks,
|
|
119
|
+
corrections,
|
|
120
|
+
},
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Encode a payload and decide admission against the competing exact compressed
|
|
126
|
+
* size. Admission requires BOTH the <=95% byte accounting AND a full decode whose
|
|
127
|
+
* digest matches the original payload.
|
|
128
|
+
*/
|
|
129
|
+
export function encodeResidual(
|
|
130
|
+
payload: Uint8Array,
|
|
131
|
+
exactCompressedSize: number,
|
|
132
|
+
emit?: ResidualEmitter,
|
|
133
|
+
): ResidualEncodeResult {
|
|
134
|
+
const built = buildArtifact(payload);
|
|
135
|
+
if (!built.ok) return { ok: false, code: built.code };
|
|
136
|
+
const codec = built.codec;
|
|
137
|
+
|
|
138
|
+
const stream = serializeStream(codec);
|
|
139
|
+
const shards = encodeShards(stream);
|
|
140
|
+
const encodedSize = stream.length + shardSetBytes(shards);
|
|
141
|
+
const correctionCount = codec.corrections.reduce(
|
|
142
|
+
(n, b) => n + b.corrections.length,
|
|
143
|
+
0,
|
|
144
|
+
);
|
|
145
|
+
const accounting: ResidualAccountingV1 = {
|
|
146
|
+
encodedSize,
|
|
147
|
+
exactCompressedSize,
|
|
148
|
+
admissionCeiling: admissionCeiling(exactCompressedSize),
|
|
149
|
+
correctionCount,
|
|
150
|
+
blockCount: codec.blocks.length,
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
const reporter = createResidualReporter(emit);
|
|
154
|
+
if (encodedSize > accounting.admissionCeiling) {
|
|
155
|
+
return { ok: true, admitted: false, code: "RES_NOT_ADMITTED", accounting };
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// Never admit without proving the full decode round-trips to the exact bytes.
|
|
159
|
+
const verified = decodeResidual(shards, emit);
|
|
160
|
+
if (!verified.ok) return { ok: false, code: verified.code };
|
|
161
|
+
if (sha256Hex(verified.bytes) !== codec.header.payloadDigest) {
|
|
162
|
+
return { ok: false, code: "RES_PAYLOAD_DIGEST_MISMATCH" };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
reporter.residualAdmitted({
|
|
166
|
+
encodedSize,
|
|
167
|
+
exactCompressedSize,
|
|
168
|
+
admissionCeiling: accounting.admissionCeiling,
|
|
169
|
+
blockCount: accounting.blockCount,
|
|
170
|
+
correctionCount,
|
|
171
|
+
});
|
|
172
|
+
return { ok: true, admitted: true, codec, shards, accounting };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Decode from a (possibly partial / partially corrupt) shard set: recover the
|
|
177
|
+
* protected stream, invert the transform, apply the exact corrections, truncate
|
|
178
|
+
* to the original length, and verify the payload digest.
|
|
179
|
+
*/
|
|
180
|
+
export function decodeResidual(
|
|
181
|
+
shards: readonly ParityShardV1[],
|
|
182
|
+
emit?: ResidualEmitter,
|
|
183
|
+
): ResidualDecodeResult {
|
|
184
|
+
const reporter = createResidualReporter(emit);
|
|
185
|
+
const recovered = recoverStream(shards);
|
|
186
|
+
if (!recovered.ok) {
|
|
187
|
+
reporter.parityRecoveryFailed({
|
|
188
|
+
code: recovered.code,
|
|
189
|
+
shardCount: shards.length,
|
|
190
|
+
});
|
|
191
|
+
return { ok: false, code: recovered.code };
|
|
192
|
+
}
|
|
193
|
+
const codec = parseStream(recovered.stream);
|
|
194
|
+
if (!codec) {
|
|
195
|
+
reporter.parityRecoveryFailed({
|
|
196
|
+
code: "RES_HEADER_INVALID",
|
|
197
|
+
shardCount: shards.length,
|
|
198
|
+
});
|
|
199
|
+
return { ok: false, code: "RES_HEADER_INVALID" };
|
|
200
|
+
}
|
|
201
|
+
return decodeArtifact(codec);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Decode a parsed artifact directly (no parity layer). */
|
|
205
|
+
export function decodeArtifact(codec: ResidualCodecV1): ResidualDecodeResult {
|
|
206
|
+
const blockSize = codec.header.blockSize;
|
|
207
|
+
const out = new Uint8Array(codec.blocks.length * blockSize);
|
|
208
|
+
const byIndex = new Map<number, readonly { offset: number; original: number }[]>();
|
|
209
|
+
for (const b of codec.corrections) byIndex.set(b.blockIndex, b.corrections);
|
|
210
|
+
|
|
211
|
+
for (let b = 0; b < codec.blocks.length; b++) {
|
|
212
|
+
const reconstructed = signalToBytes(
|
|
213
|
+
inverseDct(dequantizeBlock(codec.blocks[b]!)),
|
|
214
|
+
);
|
|
215
|
+
const applied = applyCorrections(reconstructed, byIndex.get(b) ?? []);
|
|
216
|
+
if (!applied.ok) return { ok: false, code: applied.code };
|
|
217
|
+
out.set(reconstructed, b * blockSize);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const bytes = out.subarray(0, codec.header.originalLength);
|
|
221
|
+
if (sha256Hex(bytes) !== codec.header.payloadDigest) {
|
|
222
|
+
return { ok: false, code: "RES_PAYLOAD_DIGEST_MISMATCH" };
|
|
223
|
+
}
|
|
224
|
+
// Return an independent copy so the caller cannot alias the working buffer.
|
|
225
|
+
return { ok: true, bytes: Uint8Array.from(bytes) };
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** SHA-256 of arbitrary bytes (re-exported so callers need one import). */
|
|
229
|
+
export function payloadDigest(bytes: Uint8Array): string {
|
|
230
|
+
return createHash("sha256").update(bytes).digest("hex");
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// ── aggregate-only metrics + reporter ───────────────────────────────────────
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Accumulate AGGREGATE-ONLY residual metrics (counts/byte totals). Never
|
|
237
|
+
* payload, never prompt text: the dashboard reads this shape and nothing else.
|
|
238
|
+
*/
|
|
239
|
+
export function accumulateMetrics(
|
|
240
|
+
previous: ResidualMetricsV1,
|
|
241
|
+
result: ResidualEncodeResult,
|
|
242
|
+
): ResidualMetricsV1 {
|
|
243
|
+
if (!result.ok) {
|
|
244
|
+
return { ...previous, encodeAttempts: previous.encodeAttempts + 1 };
|
|
245
|
+
}
|
|
246
|
+
const base = {
|
|
247
|
+
...previous,
|
|
248
|
+
encodeAttempts: previous.encodeAttempts + 1,
|
|
249
|
+
encodedByteTotal: previous.encodedByteTotal + result.accounting.encodedSize,
|
|
250
|
+
exactByteTotal:
|
|
251
|
+
previous.exactByteTotal + result.accounting.exactCompressedSize,
|
|
252
|
+
};
|
|
253
|
+
return result.admitted
|
|
254
|
+
? { ...base, admittedCount: base.admittedCount + 1 }
|
|
255
|
+
: { ...base, rejectedCount: base.rejectedCount + 1 };
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** A zeroed metrics accumulator. */
|
|
259
|
+
export function emptyMetrics(): ResidualMetricsV1 {
|
|
260
|
+
return {
|
|
261
|
+
encodeAttempts: 0,
|
|
262
|
+
admittedCount: 0,
|
|
263
|
+
rejectedCount: 0,
|
|
264
|
+
recoveryFailures: 0,
|
|
265
|
+
encodedByteTotal: 0,
|
|
266
|
+
exactByteTotal: 0,
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Build the flag-gated typed reporter (mirrors the VC4A shard reporter). */
|
|
271
|
+
export function createResidualReporter(emit?: ResidualEmitter): ResidualReporter {
|
|
272
|
+
const fire = (
|
|
273
|
+
event: Parameters<ResidualEmitter>[0],
|
|
274
|
+
fields: Record<string, unknown>,
|
|
275
|
+
): void => {
|
|
276
|
+
if (!VC4B_ENABLED()) return;
|
|
277
|
+
if (!emit) return;
|
|
278
|
+
try {
|
|
279
|
+
emit(event, fields);
|
|
280
|
+
} catch {
|
|
281
|
+
/* non-fatal observability — never break the agent loop */
|
|
282
|
+
}
|
|
283
|
+
};
|
|
284
|
+
return {
|
|
285
|
+
residualAdmitted(fields) {
|
|
286
|
+
fire("vector_cortex_residual_admitted", fields);
|
|
287
|
+
},
|
|
288
|
+
parityRecoveryFailed(fields) {
|
|
289
|
+
fire("vector_cortex_parity_recovery_failed", fields);
|
|
290
|
+
},
|
|
291
|
+
};
|
|
292
|
+
}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* vector-cortex/residual/dct.ts — orthonormal DCT-II basis V1 (VC4B).
|
|
3
|
+
*
|
|
4
|
+
* Basis V1 is the orthonormal DCT-II matrix generated ANALYTICALLY and never
|
|
5
|
+
* learned or stored (RESIDUAL_CODEC §byte scope):
|
|
6
|
+
*
|
|
7
|
+
* alpha(0) = sqrt(1/n), alpha(k>0) = sqrt(2/n)
|
|
8
|
+
* C[k][i] = alpha(k) * cos(pi * (2i + 1) * k / (2n))
|
|
9
|
+
*
|
|
10
|
+
* Forward coefficients are the dot product with each basis row (the orthonormal
|
|
11
|
+
* least-squares solve); the inverse is the transpose applied to the coefficient
|
|
12
|
+
* vector. Byte mapping is `x = (byte - 127.5) / 127.5`; the inverse maps back
|
|
13
|
+
* with round-to-nearest-even and clamps to 0..255.
|
|
14
|
+
*
|
|
15
|
+
* The full 4096x4096 matrix is ~134 MB of float64, so it is NEVER materialized.
|
|
16
|
+
* Instead the cosine argument `pi*(2i+1)*k/(2n)` is reduced modulo `2n` against
|
|
17
|
+
* a precomputed half-period table of length `2n` — this is EXACTLY the same set
|
|
18
|
+
* of cosine values the matrix would hold (cos is sampled only at the `2n`
|
|
19
|
+
* distinct arguments `pi*j/(2n)`, j = 0..2n-1), so the transform is bit-stable
|
|
20
|
+
* and table-generation is O(n) rather than O(n^2).
|
|
21
|
+
*
|
|
22
|
+
* Pure numeric transform: no storage, no console, no network (PREVENT-PI-004 /
|
|
23
|
+
* PREVENT-011).
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import { RESIDUAL_BLOCK_SIZE } from "./types.js";
|
|
27
|
+
|
|
28
|
+
/** Byte-to-signal mapping midpoint / half-range (RESIDUAL_CODEC §transform). */
|
|
29
|
+
const BYTE_MIDPOINT = 127.5;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Cosine table cache keyed by block length. `table[j] = cos(pi * j / (2n))` for
|
|
33
|
+
* j = 0..2n-1; every DCT argument `pi*(2i+1)*k/(2n)` reduces to one of these
|
|
34
|
+
* entries (with a sign) because cos has period `2*pi` = index period `4n`.
|
|
35
|
+
*/
|
|
36
|
+
const cosTables = new Map<number, Float64Array>();
|
|
37
|
+
|
|
38
|
+
/** Build (or fetch) the `4n`-entry cosine table for block length `n`. */
|
|
39
|
+
function cosTable(n: number): Float64Array {
|
|
40
|
+
const cached = cosTables.get(n);
|
|
41
|
+
if (cached) return cached;
|
|
42
|
+
const period = 4 * n;
|
|
43
|
+
const table = new Float64Array(period);
|
|
44
|
+
for (let j = 0; j < period; j++) {
|
|
45
|
+
table[j] = Math.cos((Math.PI * j) / (2 * n));
|
|
46
|
+
}
|
|
47
|
+
cosTables.set(n, table);
|
|
48
|
+
return table;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Orthonormal DCT-II row scale: alpha(0)=sqrt(1/n), else sqrt(2/n). */
|
|
52
|
+
export function alpha(k: number, n: number): number {
|
|
53
|
+
return k === 0 ? Math.sqrt(1 / n) : Math.sqrt(2 / n);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Map a padded byte block to the signal domain: `x = (byte - 127.5) / 127.5`.
|
|
58
|
+
* The input must be exactly `n` bytes (the caller zero-pads the final block).
|
|
59
|
+
*/
|
|
60
|
+
export function bytesToSignal(block: Uint8Array): Float64Array {
|
|
61
|
+
const out = new Float64Array(block.length);
|
|
62
|
+
for (let i = 0; i < block.length; i++) {
|
|
63
|
+
out[i] = (block[i]! - BYTE_MIDPOINT) / BYTE_MIDPOINT;
|
|
64
|
+
}
|
|
65
|
+
return out;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Map a reconstructed signal back to bytes: invert the affine map, round to
|
|
70
|
+
* nearest with ties-to-even, and clamp to 0..255 (RESIDUAL_CODEC §transform).
|
|
71
|
+
*/
|
|
72
|
+
export function signalToBytes(signal: Float64Array): Uint8Array {
|
|
73
|
+
const out = new Uint8Array(signal.length);
|
|
74
|
+
for (let i = 0; i < signal.length; i++) {
|
|
75
|
+
const v = signal[i]! * BYTE_MIDPOINT + BYTE_MIDPOINT;
|
|
76
|
+
const r = roundHalfToEven(v);
|
|
77
|
+
out[i] = r < 0 ? 0 : r > 255 ? 255 : r;
|
|
78
|
+
}
|
|
79
|
+
return out;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Round to nearest, ties to even (banker's rounding). `Math.round` rounds ties
|
|
84
|
+
* toward +Infinity, which is NOT the rule RESIDUAL_CODEC mandates.
|
|
85
|
+
*/
|
|
86
|
+
export function roundHalfToEven(v: number): number {
|
|
87
|
+
const floor = Math.floor(v);
|
|
88
|
+
const diff = v - floor;
|
|
89
|
+
if (diff > 0.5) return floor + 1;
|
|
90
|
+
if (diff < 0.5) return floor;
|
|
91
|
+
// Exact tie: pick the even neighbour.
|
|
92
|
+
return floor % 2 === 0 ? floor : floor + 1;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Forward orthonormal DCT-II over one block of length `n` (default 4096).
|
|
97
|
+
* `coefficients[k] = alpha(k) * sum_i x[i] * cos(pi*(2i+1)*k/(2n))`, emitted in
|
|
98
|
+
* ascending frequency order `k = 0..n-1` (the exact RESIDUAL_CODEC coefficient
|
|
99
|
+
* order).
|
|
100
|
+
*/
|
|
101
|
+
export function forwardDct(signal: Float64Array): Float64Array {
|
|
102
|
+
const n = signal.length;
|
|
103
|
+
const table = cosTable(n);
|
|
104
|
+
const period = 4 * n;
|
|
105
|
+
const out = new Float64Array(n);
|
|
106
|
+
for (let k = 0; k < n; k++) {
|
|
107
|
+
let sum = 0;
|
|
108
|
+
// Argument index advances by 2k each step, starting at k (i=0 gives
|
|
109
|
+
// (2*0+1)*k = k). Reduce modulo the 4n-entry period.
|
|
110
|
+
let idx = k % period;
|
|
111
|
+
const step = (2 * k) % period;
|
|
112
|
+
for (let i = 0; i < n; i++) {
|
|
113
|
+
sum += signal[i]! * table[idx]!;
|
|
114
|
+
idx += step;
|
|
115
|
+
if (idx >= period) idx -= period;
|
|
116
|
+
}
|
|
117
|
+
out[k] = alpha(k, n) * sum;
|
|
118
|
+
}
|
|
119
|
+
return out;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Inverse orthonormal DCT (the transpose of the forward matrix):
|
|
124
|
+
* `x[i] = sum_k alpha(k) * c[k] * cos(pi*(2i+1)*k/(2n))`.
|
|
125
|
+
*/
|
|
126
|
+
export function inverseDct(coefficients: Float64Array): Float64Array {
|
|
127
|
+
const n = coefficients.length;
|
|
128
|
+
const table = cosTable(n);
|
|
129
|
+
const period = 4 * n;
|
|
130
|
+
// Pre-scale each coefficient by its row alpha so the inner loop is a plain
|
|
131
|
+
// dot product (identical arithmetic to scaling inside the loop for k, and it
|
|
132
|
+
// keeps the per-i accumulation order stable).
|
|
133
|
+
const scaled = new Float64Array(n);
|
|
134
|
+
for (let k = 0; k < n; k++) scaled[k] = alpha(k, n) * coefficients[k]!;
|
|
135
|
+
const out = new Float64Array(n);
|
|
136
|
+
for (let i = 0; i < n; i++) {
|
|
137
|
+
let sum = 0;
|
|
138
|
+
const step = (2 * i + 1) % period;
|
|
139
|
+
let idx = 0;
|
|
140
|
+
for (let k = 0; k < n; k++) {
|
|
141
|
+
sum += scaled[k]! * table[idx]!;
|
|
142
|
+
idx += step;
|
|
143
|
+
if (idx >= period) idx -= period;
|
|
144
|
+
}
|
|
145
|
+
out[i] = sum;
|
|
146
|
+
}
|
|
147
|
+
return out;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Split a payload into fixed 4096-byte blocks, zero-padding ONLY the final
|
|
152
|
+
* block. The original length is retained by the caller (the header) so the
|
|
153
|
+
* padding is dropped on decode.
|
|
154
|
+
*/
|
|
155
|
+
export function splitBlocks(
|
|
156
|
+
payload: Uint8Array,
|
|
157
|
+
blockSize: number = RESIDUAL_BLOCK_SIZE,
|
|
158
|
+
): Uint8Array[] {
|
|
159
|
+
const blocks: Uint8Array[] = [];
|
|
160
|
+
for (let off = 0; off < payload.length; off += blockSize) {
|
|
161
|
+
const block = new Uint8Array(blockSize);
|
|
162
|
+
block.set(payload.subarray(off, Math.min(off + blockSize, payload.length)));
|
|
163
|
+
blocks.push(block);
|
|
164
|
+
}
|
|
165
|
+
return blocks;
|
|
166
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* vector-cortex/residual/fixture-payload.ts — deterministic payload
|
|
3
|
+
* materialization for the VC4B conformance corpus.
|
|
4
|
+
*
|
|
5
|
+
* The residual fixtures describe their payloads GENERATIVELY (`kind` + `length`
|
|
6
|
+
* + `seed`) rather than embedding megabytes of base64, so this module is the
|
|
7
|
+
* single normative generator both the fixture producer and the acceptance test
|
|
8
|
+
* agree on. Every generator is pure and deterministic — the same descriptor
|
|
9
|
+
* always yields byte-identical output, which is what makes the committed
|
|
10
|
+
* fixtures meaningful.
|
|
11
|
+
*
|
|
12
|
+
* Pure byte generation: no storage, no console, no network (PREVENT-PI-004 /
|
|
13
|
+
* PREVENT-011).
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/** A generative payload descriptor as carried by a residual fixture. */
|
|
17
|
+
export interface PayloadDescriptor {
|
|
18
|
+
readonly kind: string;
|
|
19
|
+
readonly length?: number;
|
|
20
|
+
readonly seed?: number;
|
|
21
|
+
readonly value?: number;
|
|
22
|
+
readonly outlierOffset?: number;
|
|
23
|
+
readonly bytesBase64?: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Linear congruential generator (numerical-recipes constants), deterministic. */
|
|
27
|
+
function lcgBytes(length: number, seed: number): Uint8Array {
|
|
28
|
+
const out = new Uint8Array(length);
|
|
29
|
+
let state = seed >>> 0;
|
|
30
|
+
for (let i = 0; i < length; i++) {
|
|
31
|
+
state = (Math.imul(state, 1664525) + 1013904223) >>> 0;
|
|
32
|
+
out[i] = (state >>> 24) & 0xff;
|
|
33
|
+
}
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Materialize a fixture payload descriptor into exact bytes.
|
|
39
|
+
*
|
|
40
|
+
* empty zero bytes
|
|
41
|
+
* zeros `length` 0x00 bytes
|
|
42
|
+
* constant `length` copies of `value`
|
|
43
|
+
* sequence `i % 256`
|
|
44
|
+
* lcg deterministic pseudorandom stream from `seed`
|
|
45
|
+
* text repeating printable ASCII (valid UTF-8)
|
|
46
|
+
* invalid-utf8 a stream containing lone continuation/overlong bytes
|
|
47
|
+
* dc-outlier all 0xff except one 0x00 at `outlierOffset` (forces the exact
|
|
48
|
+
* correction stream: a DC-dominant block whose coarse scale
|
|
49
|
+
* cannot reproduce the outlier's neighbourhood)
|
|
50
|
+
* alternating 0x00/0xff alternation (maximum Nyquist energy)
|
|
51
|
+
*/
|
|
52
|
+
export function materializePayload(d: PayloadDescriptor): Uint8Array {
|
|
53
|
+
const length = d.length ?? 0;
|
|
54
|
+
switch (d.kind) {
|
|
55
|
+
case "empty":
|
|
56
|
+
return new Uint8Array(0);
|
|
57
|
+
case "zeros":
|
|
58
|
+
return new Uint8Array(length);
|
|
59
|
+
case "constant":
|
|
60
|
+
return new Uint8Array(length).fill((d.value ?? 0) & 0xff);
|
|
61
|
+
case "sequence":
|
|
62
|
+
return Uint8Array.from({ length }, (_v, i) => i % 256);
|
|
63
|
+
case "lcg":
|
|
64
|
+
return lcgBytes(length, d.seed ?? 1);
|
|
65
|
+
case "text": {
|
|
66
|
+
const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789 ";
|
|
67
|
+
return Uint8Array.from({ length }, (_v, i) =>
|
|
68
|
+
alphabet.charCodeAt(i % alphabet.length),
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
case "invalid-utf8": {
|
|
72
|
+
// Deliberately invalid: lone 0x80 continuation, 0xff (never valid), and
|
|
73
|
+
// the overlong 0xc0 0xaf encoding of "/". Never normalized by the codec.
|
|
74
|
+
const pattern = [0xff, 0x80, 0xc0, 0xaf, 0x00, 0xfe];
|
|
75
|
+
return Uint8Array.from({ length }, (_v, i) => pattern[i % pattern.length]!);
|
|
76
|
+
}
|
|
77
|
+
case "dc-outlier": {
|
|
78
|
+
const out = new Uint8Array(length).fill(255);
|
|
79
|
+
const at = d.outlierOffset ?? 0;
|
|
80
|
+
if (at < length) out[at] = 0;
|
|
81
|
+
return out;
|
|
82
|
+
}
|
|
83
|
+
case "alternating":
|
|
84
|
+
return Uint8Array.from({ length }, (_v, i) => (i % 2 === 0 ? 0 : 255));
|
|
85
|
+
case "literal":
|
|
86
|
+
return new Uint8Array(Buffer.from(d.bytesBase64 ?? "", "base64"));
|
|
87
|
+
default:
|
|
88
|
+
throw new Error(`unknown residual payload kind: ${d.kind}`);
|
|
89
|
+
}
|
|
90
|
+
}
|