pi-mega-compact 0.18.0 → 0.19.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 (97) hide show
  1. package/assets/vector-cortex/encoder-v1/manifest.json +1 -0
  2. package/assets/vector-cortex/encoder-v1/model-card.json +1 -0
  3. package/assets/vector-cortex/encoder-v1/model.onnx +0 -0
  4. package/assets/vector-cortex/encoder-v1/tokenizer.json +1 -0
  5. package/dist/config/vector-cortex.js +18 -0
  6. package/dist/config.js +117 -0
  7. package/dist/extensions/dashboard-server/routes-rag-settings-helpers.js +4 -0
  8. package/dist/extensions/dashboard-server/routes-vector-cortex.js +89 -1
  9. package/dist/log.js +47 -0
  10. package/dist/src/config/vector-cortex.js +18 -0
  11. package/dist/src/config.js +1 -1
  12. package/dist/src/vector-cortex/encoder/calibrate.js +174 -0
  13. package/dist/src/vector-cortex/encoder/emit-vc2b.js +63 -0
  14. package/dist/src/vector-cortex/encoder/emit-vc2c.js +59 -0
  15. package/dist/src/vector-cortex/encoder/fallback.js +62 -0
  16. package/dist/src/vector-cortex/encoder/heads.js +113 -0
  17. package/dist/src/vector-cortex/encoder/lexical.js +104 -0
  18. package/dist/src/vector-cortex/encoder/router.js +115 -0
  19. package/dist/src/vector-cortex/encoder/select.js +172 -0
  20. package/dist/src/vector-cortex/encoder/trigram.js +75 -0
  21. package/dist/src/vector-cortex/encoder/types.js +84 -0
  22. package/dist/vector-cortex/encoder/calibrate.js +174 -0
  23. package/dist/vector-cortex/encoder/emit-vc2b.js +63 -0
  24. package/dist/vector-cortex/encoder/emit-vc2c.js +59 -0
  25. package/dist/vector-cortex/encoder/fallback.js +62 -0
  26. package/dist/vector-cortex/encoder/heads.js +113 -0
  27. package/dist/vector-cortex/encoder/lexical.js +104 -0
  28. package/dist/vector-cortex/encoder/router.js +115 -0
  29. package/dist/vector-cortex/encoder/select.js +172 -0
  30. package/dist/vector-cortex/encoder/trigram.js +75 -0
  31. package/dist/vector-cortex/encoder/types.js +84 -0
  32. package/extensions/dashboard-client/dist/assets/{AreaChart-BQXFF7UI.js → AreaChart-DywU5SSt.js} +2 -2
  33. package/extensions/dashboard-client/dist/assets/{AreaChart-BQXFF7UI.js.map → AreaChart-DywU5SSt.js.map} +1 -1
  34. package/extensions/dashboard-client/dist/assets/{BarChart-BVtoz9Eg.js → BarChart-But7WN6K.js} +2 -2
  35. package/extensions/dashboard-client/dist/assets/{BarChart-BVtoz9Eg.js.map → BarChart-But7WN6K.js.map} +1 -1
  36. package/extensions/dashboard-client/dist/assets/{CacheTab-trI2TIGy.js → CacheTab-7aZWa1DR.js} +2 -2
  37. package/extensions/dashboard-client/dist/assets/{CacheTab-trI2TIGy.js.map → CacheTab-7aZWa1DR.js.map} +1 -1
  38. package/extensions/dashboard-client/dist/assets/{EventsTab-CNUbk9__.js → EventsTab-Bf_boNG2.js} +2 -2
  39. package/extensions/dashboard-client/dist/assets/{EventsTab-CNUbk9__.js.map → EventsTab-Bf_boNG2.js.map} +1 -1
  40. package/extensions/dashboard-client/dist/assets/{HealthTab-K-bd_CM-.js → HealthTab-AbGc1nXP.js} +2 -2
  41. package/extensions/dashboard-client/dist/assets/{HealthTab-K-bd_CM-.js.map → HealthTab-AbGc1nXP.js.map} +1 -1
  42. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-CoEioKzx.js → MaintenanceTab-BfHHhn5F.js} +2 -2
  43. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-CoEioKzx.js.map → MaintenanceTab-BfHHhn5F.js.map} +1 -1
  44. package/extensions/dashboard-client/dist/assets/{MemoryMapTab-CJo24ulv.js → MemoryMapTab-DrcWti0-.js} +2 -2
  45. package/extensions/dashboard-client/dist/assets/{MemoryMapTab-CJo24ulv.js.map → MemoryMapTab-DrcWti0-.js.map} +1 -1
  46. package/extensions/dashboard-client/dist/assets/{MetricsTab-DCNlQWWP.js → MetricsTab-ALiglXQq.js} +2 -2
  47. package/extensions/dashboard-client/dist/assets/{MetricsTab-DCNlQWWP.js.map → MetricsTab-ALiglXQq.js.map} +1 -1
  48. package/extensions/dashboard-client/dist/assets/{OverviewTab-CQQlyIQ6.js → OverviewTab-nnaJdNyR.js} +2 -2
  49. package/extensions/dashboard-client/dist/assets/{OverviewTab-CQQlyIQ6.js.map → OverviewTab-nnaJdNyR.js.map} +1 -1
  50. package/extensions/dashboard-client/dist/assets/{ReposTab-Cqm82_yn.js → ReposTab-BTK0nofM.js} +2 -2
  51. package/extensions/dashboard-client/dist/assets/{ReposTab-Cqm82_yn.js.map → ReposTab-BTK0nofM.js.map} +1 -1
  52. package/extensions/dashboard-client/dist/assets/{SessionsTab-A8xTAdET.js → SessionsTab-RXPNqO6x.js} +2 -2
  53. package/extensions/dashboard-client/dist/assets/{SessionsTab-A8xTAdET.js.map → SessionsTab-RXPNqO6x.js.map} +1 -1
  54. package/extensions/dashboard-client/dist/assets/{SetupTab-CqaSgaZl.js → SetupTab-Dab0AVfs.js} +2 -2
  55. package/extensions/dashboard-client/dist/assets/{SetupTab-CqaSgaZl.js.map → SetupTab-Dab0AVfs.js.map} +1 -1
  56. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-C_f3q8GR.js → TimeSavedCard-DIVG8hdt.js} +2 -2
  57. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-C_f3q8GR.js.map → TimeSavedCard-DIVG8hdt.js.map} +1 -1
  58. package/extensions/dashboard-client/dist/assets/{TurnsTab-BEsafACo.js → TurnsTab-9uz2fBwx.js} +2 -2
  59. package/extensions/dashboard-client/dist/assets/{TurnsTab-BEsafACo.js.map → TurnsTab-9uz2fBwx.js.map} +1 -1
  60. package/extensions/dashboard-client/dist/assets/{VectorCortexTab-DD1CMK80.js → VectorCortexTab-DnKY61EJ.js} +2 -2
  61. package/extensions/dashboard-client/dist/assets/VectorCortexTab-DnKY61EJ.js.map +1 -0
  62. package/extensions/dashboard-client/dist/assets/{WikiTab-Bf01M2_Z.js → WikiTab-CpcgaggS.js} +2 -2
  63. package/extensions/dashboard-client/dist/assets/{WikiTab-Bf01M2_Z.js.map → WikiTab-CpcgaggS.js.map} +1 -1
  64. package/extensions/dashboard-client/dist/assets/{button-BEJPTk_E.js → button-B0Q2fuKY.js} +2 -2
  65. package/extensions/dashboard-client/dist/assets/{button-BEJPTk_E.js.map → button-B0Q2fuKY.js.map} +1 -1
  66. package/extensions/dashboard-client/dist/assets/{card-DK1V382s.js → card-Cnik3TFr.js} +2 -2
  67. package/extensions/dashboard-client/dist/assets/{card-DK1V382s.js.map → card-Cnik3TFr.js.map} +1 -1
  68. package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-CRtaPphL.js → generateCategoricalChart-DrSwgn1V.js} +2 -2
  69. package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-CRtaPphL.js.map → generateCategoricalChart-DrSwgn1V.js.map} +1 -1
  70. package/extensions/dashboard-client/dist/assets/{index-CB6BslE4.js → index-DraytcOY.js} +3 -3
  71. package/extensions/dashboard-client/dist/assets/{index-CB6BslE4.js.map → index-DraytcOY.js.map} +1 -1
  72. package/extensions/dashboard-client/dist/assets/{switch-C4FV6B9k.js → switch-DVQ1aB9b.js} +2 -2
  73. package/extensions/dashboard-client/dist/assets/{switch-C4FV6B9k.js.map → switch-DVQ1aB9b.js.map} +1 -1
  74. package/extensions/dashboard-client/dist/assets/{toggle-GBmeENMd.js → toggle-Dkppx-49.js} +2 -2
  75. package/extensions/dashboard-client/dist/assets/{toggle-GBmeENMd.js.map → toggle-Dkppx-49.js.map} +1 -1
  76. package/extensions/dashboard-client/dist/assets/{useSSE-BOKZGSn1.js → useSSE-CPkjU4Gx.js} +2 -2
  77. package/extensions/dashboard-client/dist/assets/{useSSE-BOKZGSn1.js.map → useSSE-CPkjU4Gx.js.map} +1 -1
  78. package/extensions/dashboard-client/dist/index.html +1 -1
  79. package/extensions/dashboard-client/src/tabs/VectorCortexTab.tsx +2 -0
  80. package/extensions/dashboard-client/src/types/vector-cortex.ts +11 -0
  81. package/extensions/dashboard-server/api-contracts/vector-cortex.ts +11 -0
  82. package/extensions/dashboard-server/routes-rag-settings-helpers.ts +14 -0
  83. package/extensions/dashboard-server/routes-vector-cortex.ts +108 -1
  84. package/package.json +2 -1
  85. package/src/config/vector-cortex.ts +20 -0
  86. package/src/config.ts +2 -0
  87. package/src/vector-cortex/encoder/calibrate.ts +225 -0
  88. package/src/vector-cortex/encoder/emit-vc2b.ts +82 -0
  89. package/src/vector-cortex/encoder/emit-vc2c.ts +70 -0
  90. package/src/vector-cortex/encoder/fallback.ts +99 -0
  91. package/src/vector-cortex/encoder/heads.ts +142 -0
  92. package/src/vector-cortex/encoder/lexical.ts +123 -0
  93. package/src/vector-cortex/encoder/router.ts +163 -0
  94. package/src/vector-cortex/encoder/select.ts +237 -0
  95. package/src/vector-cortex/encoder/trigram.ts +85 -0
  96. package/src/vector-cortex/encoder/types.ts +226 -0
  97. package/extensions/dashboard-client/dist/assets/VectorCortexTab-DD1CMK80.js.map +0 -1
@@ -0,0 +1,59 @@
1
+ /**
2
+ * vector-cortex/encoder/emit-vc2c.ts — VC2C observability seam.
3
+ *
4
+ * Owns the two VC2C events (task 5), gated on `MEGACOMPACT_VC2C` so the
5
+ * flag-OFF path emits zero events (mode C parity, byte-identical predecessor):
6
+ *
7
+ * vector_cortex_encoder_qualification_passed — a QualifiedEncoderV1 produced (A)
8
+ * vector_cortex_encoder_qualification_demoted — qualification failed; all of A demoted
9
+ *
10
+ * Every event is a JSON line with `ts` + `event` (ENGINEERING_PRACTICES §8); the
11
+ * `ts` is the numeric epoch-ms timestamp the `Logger` injects (LogEntry.ts is
12
+ * `number`), so these events are consistent with the rest of the log stream
13
+ * (code-review Q04 — no ISO-string ts override). The emitters are non-fatal
14
+ * (never break the agent loop). Pi-agnostic, zero network (PREVENT-PI-004), no
15
+ * `any` (PREVENT-011).
16
+ */
17
+ import { VC2C_ENABLED } from "../../config/vector-cortex.js";
18
+ import { Logger } from "../../log.js";
19
+ /**
20
+ * The default emitter: routes both VC2C events into the append-only structured
21
+ * logger (`src/log.ts`) as JSON lines with `event` (the logger injects the
22
+ * numeric `ts`). Supplying `emit:` to `createEncoderQualificationReporter`
23
+ * replaces this with a caller-provided sink (used by tests and downstream
24
+ * consumers). Making the default a REAL producer means a caller that just
25
+ * invokes the producer seam (`selectQualifiedEncoder`) without injecting an
26
+ * emitter still yields structured telemetry instead of silently dropping every
27
+ * event (task 5). Best-effort: the logger swallows all I/O errors.
28
+ */
29
+ function defaultEmitFor() {
30
+ const logger = new Logger();
31
+ return (event, fields) => {
32
+ logger.info(event, fields);
33
+ };
34
+ }
35
+ /**
36
+ * Flag-gated emit, defaulting to a real logger-backed sink. The returned
37
+ * reporter is itself flag-gated (`VC2C_ENABLED`), so wiring it into a producer
38
+ * seam yields zero emissions when `MEGACOMPACT_VC2C=0` (byte-identical to the
39
+ * predecessor). Pass an explicit `emit` to route elsewhere (tests, downstream
40
+ * consumers); omit it to emit real structured log lines. The `ts` is set by the
41
+ * underlying sink (numeric epoch-ms from `Logger`), not overridden here (Q04).
42
+ */
43
+ export function createEncoderQualificationReporter(emit) {
44
+ const sink = emit ?? defaultEmitFor();
45
+ const fire = (event, fields) => {
46
+ if (!VC2C_ENABLED())
47
+ return;
48
+ try {
49
+ sink(event, fields);
50
+ }
51
+ catch {
52
+ /* non-fatal observability */
53
+ }
54
+ };
55
+ return {
56
+ qualificationPassed: (fields) => fire("vector_cortex_encoder_qualification_passed", fields),
57
+ qualificationDemoted: (fields) => fire("vector_cortex_encoder_qualification_demoted", fields),
58
+ };
59
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * vector-cortex/encoder/fallback.ts — VC2C qualification fallback selection.
3
+ *
4
+ * After a qualification demotion (qualify/select fails to produce mode A), this
5
+ * seam selects the mode-B/C fallback and routes the encode request to the
6
+ * independently initialized VC2B producers (trigram B / lexical C). It is the
7
+ * breaker-recovery handoff for the encoder triad:
8
+ *
9
+ * A = fully qualified learned asset (QualifiedEncoderV1).
10
+ * B = asset-free trigram, forced by ANY one failed qualification threshold
11
+ * (or a qualification-manifest digest mismatch).
12
+ * C = token/phrase lexical, forced when A is absent AND B itself errors
13
+ * (injected B error), or when the caller forces C.
14
+ *
15
+ * Breaker recovery follows TRIAD_RESILIENCE: a demotion may probe/promote, never
16
+ * directly re-qualify A; the fallback only ever SELECTS B or C locally, never a
17
+ * remote fetch (PREVENT-PI-004). C states its loss of old semantic context.
18
+ *
19
+ * Pi-agnostic, zero network (PREVENT-PI-004), no `any` (PREVENT-011).
20
+ */
21
+ import { createEncoderHeadsReporter } from "./emit-vc2b.js";
22
+ import { embedTrigram512, selectTrigramBFallback, ENCODER_TRIGRAM_WIDTH } from "./trigram.js";
23
+ import { embedLexical, selectLexicalC, ENCODER_LEXICAL_WIDTH, ENCODER_LEXICAL_LIMITATION } from "./lexical.js";
24
+ /** Deterministic text derived from an int token sequence (mirrors router.ts). */
25
+ function textFromTokens(tokens) {
26
+ return tokens.join("-");
27
+ }
28
+ /**
29
+ * Select the B/C fallback for a failed qualification and produce the encode
30
+ * vector. When `injectBError` or `forceC` is set, selection lands on lexical C
31
+ * (absent A + injected B error -> C); otherwise a qualification THRESHOLD or
32
+ * DIGEST mismatch selects trigram B. Never returns without an explicit verdict.
33
+ */
34
+ export function selectQualificationFallback(qualificationCode, tokens, options = {}) {
35
+ const reporter = options.reporter ?? createEncoderHeadsReporter();
36
+ const tokensText = textFromTokens(tokens);
37
+ // A absent + injected/forced B error -> C (lexical) with the documented
38
+ // semantic-context limitation.
39
+ if (options.forceC || options.injectBError) {
40
+ selectLexicalC({ reporter });
41
+ const vector = embedLexical(tokensText);
42
+ return {
43
+ ok: true,
44
+ mode: "C",
45
+ vector,
46
+ width: ENCODER_LEXICAL_WIDTH,
47
+ code: options.injectBError ? "ENC_B_INJECTED_ERROR" : qualificationCode,
48
+ limitation: ENCODER_LEXICAL_LIMITATION,
49
+ };
50
+ }
51
+ // A qualification demotion selects the independently initialized trigram B.
52
+ selectTrigramBFallback({ reporter });
53
+ const vector = embedTrigram512(tokensText);
54
+ return {
55
+ ok: true,
56
+ mode: "B",
57
+ vector,
58
+ width: ENCODER_TRIGRAM_WIDTH,
59
+ code: qualificationCode,
60
+ limitation: null,
61
+ };
62
+ }
@@ -0,0 +1,113 @@
1
+ /**
2
+ * vector-cortex/encoder/heads.ts — VC2B multi-head encoder (tasks 1–2).
3
+ *
4
+ * Produces a `VectorSetV1`: five independent L2-normalized projection heads in
5
+ * STABLE order — semantic 384, dependency 128, contradiction 128, cacheStability
6
+ * 64, payloadRouting 32 (MODEL_ASSET §decision record). Each head L2-normalizes
7
+ * its raw projection; a zero-norm projection maps to an all-zero vector (task 2).
8
+ *
9
+ * The raw per-head projection is a deterministic seeded compression of the input
10
+ * token sequence (seeded by `ENCODER_SEED` and the head's stable index), which
11
+ * mirrors the VC2A `projectSemantic` placeholder pattern: the contract, shape
12
+ * gating, normalization, zero-norm mapping, ordering and loss/seed constants are
13
+ * all normative here; real trained weights are substituted in VC2C. This keeps
14
+ * the mode-A multi-head path fully testable end-to-end today with zero network.
15
+ *
16
+ * The VC2B emit seam (task 5) is wired: producing a VectorSetV1 emits
17
+ * `vector_cortex_encoder_heads_emitted`; selecting a mode B/C fallback emits
18
+ * `vector_cortex_encoder_fallback_selected` — both gated on MEGACOMPACT_VC2B.
19
+ *
20
+ * Pi-agnostic, zero network (PREVENT-PI-004), no `any` (PREVENT-011).
21
+ */
22
+ import { ENCODER_HEAD_DIMS, ENCODER_HEAD_ORDER, ENCODER_HEAD_LOSS_WEIGHTS, ENCODER_HEAD_LOSS_SUM, ENCODER_SEED, } from "./types.js";
23
+ import { createEncoderHeadsReporter, NOOP_VC2B_REPORTER, } from "./emit-vc2b.js";
24
+ /** The stable head index of a head name (its position in ENCODER_HEAD_ORDER). */
25
+ const HEAD_INDEX = {
26
+ semantic: 0,
27
+ dependency: 1,
28
+ contradiction: 2,
29
+ cacheStability: 3,
30
+ payloadRouting: 4,
31
+ };
32
+ /** Deterministic 32-bit LCG step (matches runtime.ts projectSemantic). */
33
+ function nextState(state) {
34
+ return (state * 1664525 + 1013904223) >>> 0;
35
+ }
36
+ /**
37
+ * L2-normalize a float vector in place semantics (returns a new Float32Array).
38
+ * A zero-norm (or empty) input maps to an all-zero vector of the same length
39
+ * (task 2: "mapping zero norm to an all-zero vector"). All finite.
40
+ */
41
+ export function l2Normalize(values) {
42
+ const out = new Float32Array(values.length);
43
+ let sum = 0;
44
+ for (const v of values)
45
+ sum += v * v;
46
+ const norm = Math.sqrt(sum);
47
+ if (!(norm > 0))
48
+ return out; // zero norm -> all-zero
49
+ for (let i = 0; i < values.length; i++)
50
+ out[i] = values[i] / norm;
51
+ return out;
52
+ }
53
+ /** L2 norm of a Float32Array (0 for empty/all-zero). */
54
+ export function l2Norm(values) {
55
+ let sum = 0;
56
+ for (const v of values)
57
+ sum += v * v;
58
+ return Math.sqrt(sum);
59
+ }
60
+ /** A deterministic per-head projection over the token sequence, pre-normalization. */
61
+ function projectRaw(head, tokens, seed) {
62
+ const dim = ENCODER_HEAD_DIMS[head];
63
+ const out = new Float32Array(dim);
64
+ // An EMPTY token sequence has no signal: the raw projection is the zero vector,
65
+ // so after L2 normalization it maps to the all-zero vector (task 2: "mapping
66
+ // zero norm to an all-zero vector"; ENC-ZERO-002). This keeps empty input
67
+ // finite and zero-norm instead of seeding spurious unit-norm noise.
68
+ if (tokens.length === 0)
69
+ return out;
70
+ // Mix the stable head index + ENCODER_SEED + seed into a per-head state so
71
+ // each head is a distinct independent projection (failure-triad independence).
72
+ let state = (((ENCODER_SEED ^ HEAD_INDEX[head]) >>> 0) ^ (seed >>> 0)) ^ 0x9e3779b9;
73
+ for (const t of tokens)
74
+ state = nextState(state ^ ((t >>> 0) * 2654435761));
75
+ for (let i = 0; i < dim; i++) {
76
+ state = nextState(state ^ seed);
77
+ out[i] = (state / 4294967296) * 2 - 1;
78
+ }
79
+ return out;
80
+ }
81
+ /**
82
+ * Compute one head's L2-normalized vector (all-zero on zero norm) for a token
83
+ * sequence. Deterministic for a given seed (repeat drift == 0).
84
+ */
85
+ export function projectHead(head, tokens, seed = ENCODER_SEED) {
86
+ const raw = projectRaw(head, tokens, seed);
87
+ return { head, dim: ENCODER_HEAD_DIMS[head], values: l2Normalize(raw) };
88
+ }
89
+ /**
90
+ * Encode a token sequence into a `VectorSetV1`: the five heads in stable order,
91
+ * each L2-normalized (all-zero on zero norm). Emits `heads_emitted` via the
92
+ * reporter (non-fatal, flag-gated). Deterministic for a given seed.
93
+ */
94
+ export function encodeVectorSet(tokens, options = {}) {
95
+ const seed = options.seed ?? ENCODER_SEED;
96
+ const reporter = options.reporter ?? createEncoderHeadsReporter();
97
+ const heads = ENCODER_HEAD_ORDER.map((h) => projectHead(h, tokens, seed));
98
+ reporter.headsEmitted({
99
+ heads: heads.length,
100
+ dims: heads.map((h) => h.dim).join("/"),
101
+ normalized: true,
102
+ tokens: tokens.length,
103
+ });
104
+ return { schema: "vector-set-v1", inputTokens: [...tokens], heads, normalized: true };
105
+ }
106
+ /**
107
+ * The per-head loss weights (must sum to ENCODER_HEAD_LOSS_SUM exactly).
108
+ * Exposed for training/tests to assert the normative .35/.20/.20/.15/.10 split.
109
+ */
110
+ export function headLossWeights() {
111
+ return { ...ENCODER_HEAD_LOSS_WEIGHTS };
112
+ }
113
+ export { ENCODER_HEAD_ORDER, ENCODER_HEAD_DIMS, ENCODER_HEAD_LOSS_SUM, ENCODER_SEED, NOOP_VC2B_REPORTER };
@@ -0,0 +1,104 @@
1
+ /**
2
+ * vector-cortex/encoder/lexical.ts — VC2B mode C: token/phrase lexical encoder.
3
+ *
4
+ * Lexical C is a token/phrase lexical feature generator used when both mode A
5
+ * (learned asset) and mode B (trigram) are unavailable or fail. It is continuity,
6
+ * NOT semantic completeness: C operates on exact current tokens/phrases only and
7
+ * MUST state that it has lost old semantic context (task 4 + TRIAD_RESILIENCE.
8
+ * "C is continuity, not semantic completeness: it may omit old context and must
9
+ * report that limitation").
10
+ *
11
+ * C never imports the learned asset or learned calibration (task 4): it is a
12
+ * pure token/phrase lexical projection (token counts + phrase hashes) computed
13
+ * from the exact input. It is independently implemented from B (which hashes
14
+ * byte-level trigrams) — C works at the token/phrase level, B at the byte-ngram
15
+ * level, so the two share no algorithm.
16
+ *
17
+ * Authority outage freezes derived high-water: C never advances any derived
18
+ * frontier; it is purely a local reconstruction from the exact present tokens.
19
+ *
20
+ * Pi-agnostic, zero network (PREVENT-PI-004), no `any` (PREVENT-011).
21
+ */
22
+ import { createHash } from "node:crypto";
23
+ import { l2Normalize } from "./heads.js";
24
+ import { createEncoderHeadsReporter, } from "./emit-vc2b.js";
25
+ /** Fixed output width of lexical C. */
26
+ export const ENCODER_LEXICAL_WIDTH = 256;
27
+ /** The documented limitation lexical C reports (continuity, not semantics). */
28
+ export const ENCODER_LEXICAL_LIMITATION = "lexical C: token/phrase-level continuity only; old semantic context is omitted";
29
+ export function tokenizeLexical(text) {
30
+ // Split into lowercase token/phrase units on non-alphanumeric boundaries.
31
+ return text.toLowerCase().split(/[^a-z0-9_]+/).filter((t) => t.length > 0);
32
+ }
33
+ /**
34
+ * Normalize a single token/phrase unit the same way `tokenizeLexical` does for
35
+ * the string form: lowercase and strip leading/trailing non-alphanumeric runs.
36
+ * Applied to array-form tokens so both accepted input forms of `embedLexical`
37
+ * hash identical conceptual content to identical buckets, regardless of how the
38
+ * caller chose to pass it (code-review Q03).
39
+ */
40
+ function normalizeToken(tok) {
41
+ return tok.toLowerCase().split(/[^a-z0-9_]+/).join("");
42
+ }
43
+ /**
44
+ * Resolve either accepted input form to a normalized token sequence: the string
45
+ * form routes through `tokenizeLexical` (split on non-alphanumeric boundaries,
46
+ * fragmented tokens discarded); the array form applies the same per-token
47
+ * lowercase/strip normalization and drops tokens that normalize to empty. Both
48
+ * paths therefore agree on hash buckets for the same conceptual content.
49
+ */
50
+ function resolveTokens(tokensOrText) {
51
+ if (typeof tokensOrText === "string")
52
+ return tokenizeLexical(tokensOrText);
53
+ const out = [];
54
+ for (const raw of tokensOrText) {
55
+ const norm = normalizeToken(raw);
56
+ if (norm.length > 0)
57
+ out.push(norm);
58
+ }
59
+ return out;
60
+ }
61
+ /**
62
+ * Encode a token/phrase sequence into a 256-dim L2-normalized lexical vector
63
+ * (all-zero on empty input). Features: exact token count + token id-hash sums +
64
+ * phrase-adjacency hashes. Deterministic (repeat drift == 0). Pure local compute.
65
+ */
66
+ export function embedLexical(tokensOrText) {
67
+ const width = ENCODER_LEXICAL_WIDTH;
68
+ const out = new Float32Array(width);
69
+ const tokens = resolveTokens(tokensOrText);
70
+ for (let i = 0; i < tokens.length; i++) {
71
+ const tok = tokens[i];
72
+ const h = createHash("sha256").update(`t:${tok}`).digest();
73
+ const bucket = h.readUInt32BE(0) % width;
74
+ const weight = (h.readUInt32BE(4) / 4294967295) * 2 - 1;
75
+ out[bucket] += weight;
76
+ // Phrase adjacency: bigram hash blended in so semantic-free ordering matters.
77
+ if (i > 0) {
78
+ const pair = createHash("sha256").update(`p:${tokens[i - 1]}:${tok}`).digest();
79
+ const pb = pair.readUInt32BE(0) % width;
80
+ const pw = (pair.readUInt32BE(4) / 4294967295) * 2 - 1;
81
+ out[pb] += pw;
82
+ }
83
+ }
84
+ return l2Normalize(out);
85
+ }
86
+ /** The documented limitation string, surfaced when lexical C is selected. */
87
+ export function selectLexicalC(options = {}) {
88
+ const reporter = options.reporter ?? createEncoderHeadsReporter();
89
+ const selection = {
90
+ ok: true,
91
+ mode: "C",
92
+ dim: ENCODER_LEXICAL_WIDTH,
93
+ width: ENCODER_LEXICAL_WIDTH,
94
+ limitation: ENCODER_LEXICAL_LIMITATION,
95
+ };
96
+ reporter.fallbackSelected({
97
+ mode: selection.mode,
98
+ dim: selection.dim,
99
+ width: selection.width,
100
+ limitation: selection.limitation,
101
+ });
102
+ return selection;
103
+ }
104
+ export { l2Normalize };
@@ -0,0 +1,115 @@
1
+ /**
2
+ * vector-cortex/encoder/router.ts — VC2B encode-or-fallback router (S2).
3
+ *
4
+ * The single production seam that catches a real VC2A `load()` failure and
5
+ * hands off to the independently initialized VC2B fallbacks:
6
+ *
7
+ * - mode A: the learned multi-head projection — an EncoderRuntime that
8
+ * verifies+loads a local qualified ONNX (VC2A) plus `encodeVectorSet`
9
+ * producing VectorSetV1, emitting `vector_cortex_encoder_heads_emitted`;
10
+ * - when that `load()` fails for ANY reason (removed model ->
11
+ * ENC_ASSET_UNREADABLE, digest mismatch -> ENC_DIGEST_MISMATCH, missing
12
+ * manifest -> ENC_MANIFEST_INVALID, unsupported platform, RSS over budget,
13
+ * ...) the router catches the real failure and selects the independently
14
+ * initialized asset-free trigram B (`selectTrigramBFallback`) — or lexical C
15
+ * when the runtime reports B-unavailable / the caller forces mode C. The
16
+ * `vector_cortex_encoder_fallback_selected` event fires from the REAL
17
+ * producer seam, not test wiring (task 5 + code-review S1).
18
+ *
19
+ * Best-effort and non-fatal: every branch returns an explicit verdict and never
20
+ * throws across the boundary into the agent loop. Flag-OFF parity: with
21
+ * `MEGACOMPACT_VC2B=0` the VC2B reporter is a no-op (zero emissions), and the
22
+ * mode-A path is governed by the VC2A runtime itself — the router only adds the
23
+ * fallback handoff and changes no producer bytes.
24
+ *
25
+ * Pi-agnostic, zero network (PREVENT-PI-004), no `any` (PREVENT-011).
26
+ */
27
+ import { createEncoderRuntime } from "./runtime.js";
28
+ import { encodeVectorSet } from "./heads.js";
29
+ import { embedTrigram512, selectTrigramBFallback } from "./trigram.js";
30
+ import { embedLexical, selectLexicalC } from "./lexical.js";
31
+ import { createEncoderHeadsReporter } from "./emit-vc2b.js";
32
+ import { ENC_FAIL, } from "./types.js";
33
+ /** Deterministic text derived from an int token sequence so the asset-free
34
+ * fallback producers operate on the same authority the learned path encoded. */
35
+ function textFromTokens(tokens) {
36
+ return tokens.join("-");
37
+ }
38
+ /**
39
+ * Try to produce an encoding for an input token sequence. Mode A: verify+load
40
+ * the local learned asset via the EncoderRuntime; on a real `load()` failure
41
+ * (removed model, digest mismatch, missing manifest, ...) the router catches it
42
+ * and selects the independently initialized trigram B or lexical C, emitting
43
+ * `vector_cortex_encoder_fallback_selected` (and `heads_emitted` when A wins).
44
+ */
45
+ export function encodeOrFallback(input, assetDir, options = {}) {
46
+ const reporter = options.reporter ?? createEncoderHeadsReporter();
47
+ const tokens = Array.isArray(input?.tokens) ? input.tokens : [];
48
+ const runtime = options.runtime ?? createEncoderRuntime();
49
+ // A caller that explicitly forces a fallback mode wins even over the empty-
50
+ // input degenerate case: the forced-mode contract must hold for ANY input, so
51
+ // handle forceFallback before the empty-input selection below (Q02). A forced
52
+ // B/C is NOT a rollback and NOT a demotion — it is an intentional selection
53
+ // for capacity/testing — so the verdict carries `code: null`, never
54
+ // ENC_FAIL.ROLLBACK, so a consumer that reads `verdict.code` as "what
55
+ // triggered the fallback" won't misread a deliberately forced mode as a
56
+ // rollback and take rollback-specific action (code-review Q04).
57
+ if (options.forceFallback !== undefined) {
58
+ if (options.forceFallback === "C") {
59
+ const sel = selectLexicalC({ reporter });
60
+ const vector = embedLexical(textFromTokens(tokens));
61
+ return { ok: true, mode: "C", vector, width: sel.width, limitation: sel.limitation, code: null };
62
+ }
63
+ const sel = selectTrigramBFallback({ reporter });
64
+ const vector = embedTrigram512(textFromTokens(tokens));
65
+ return { ok: true, mode: "B", vector, width: sel.width, limitation: null, code: null };
66
+ }
67
+ // Empty input yields the asset-free fallback (finite, deterministic zero
68
+ // vector, ENC-ZERO-002). This is legitimate degenerate behavior, NOT a shape
69
+ // failure, so the verdict carries no failure code (code === null) — a consumer
70
+ // that interprets `code` as "what went wrong" must not misread a valid all-zero
71
+ // B vector as a shape rejection (Q05). Only reached when no mode is forced, so
72
+ // a forced B/C is never subverted by empty tokens.
73
+ if (tokens.length === 0) {
74
+ const sel = selectTrigramBFallback({ reporter });
75
+ const vector = embedTrigram512("");
76
+ return { ok: true, mode: "B", vector, width: sel.width, limitation: null, code: null };
77
+ }
78
+ // Mode A attempt — reached only when no mode is forced (the forceFallback
79
+ // guard at the top already returned), so `options.forceFallback` is undefined here.
80
+ const loaded = runtime.load(assetDir);
81
+ if (!loaded.ok) {
82
+ return fallbackFromLoad(loaded, reporter, tokens);
83
+ }
84
+ // Q01/Q03: a qualified mode-A load is not enough — the verified per-manifest
85
+ // token capacity (maxTokens, <= global 512) must also be enforced before we
86
+ // produce a VectorSetV1. run inference over the input; an over-cap sequence
87
+ // (e.g. 100 tokens against a verified maxTokens=64 manifest) or an
88
+ // over-budget inference is rejected here and routed to the B/C fallback with
89
+ // the real failure code, rather than silently emitting an ok:true mode-A
90
+ // set whose inputTokens breach the model's declared capacity.
91
+ const inferred = runtime.infer({ tokens });
92
+ if (!inferred.ok) {
93
+ return fallbackFromLoad({ ok: false, mode: "B", code: inferred.code }, reporter, tokens);
94
+ }
95
+ const vectorSet = encodeVectorSet(tokens, { reporter, seed: options.seed });
96
+ return { ok: true, mode: "A", vectorSet, code: null };
97
+ }
98
+ /**
99
+ * Catch a (real or forced) A load failure (ok === false only) and select the
100
+ * B/C fallback that emits `vector_cortex_encoder_fallback_selected` from the
101
+ * production seam. The parameter is narrowed to the failed-load variant because
102
+ * the router hands off here only on a non-A/failed load — a qualified mode-A
103
+ * success never reaches this function (Q04).
104
+ */
105
+ function fallbackFromLoad(loaded, reporter, tokens) {
106
+ if (loaded.mode === "C") {
107
+ const sel = selectLexicalC({ reporter });
108
+ const vector = embedLexical(textFromTokens(tokens));
109
+ return { ok: true, mode: "C", vector, width: sel.width, limitation: sel.limitation, code: loaded.code };
110
+ }
111
+ const sel = selectTrigramBFallback({ reporter });
112
+ const vector = embedTrigram512(textFromTokens(tokens));
113
+ return { ok: true, mode: "B", vector, width: sel.width, limitation: null, code: loaded.code };
114
+ }
115
+ export { ENC_FAIL };
@@ -0,0 +1,172 @@
1
+ /**
2
+ * vector-cortex/encoder/select.ts — VC2C atomic qualification selection (task 3).
3
+ *
4
+ * Selects mode A (a `QualifiedEncoderV1`) ONLY when EVERY MODEL_ASSET
5
+ * constraint AND every per-head EVALUATION threshold passes — the eligibility
6
+ * check is ATOMIC: any single failed field demotes the ENTIRE candidate to
7
+ * mode B/C (never a partial A). The failed field is reported so the caller/UI
8
+ * can inspect which threshold tripped.
9
+ *
10
+ * - asset fields (MODEL_ASSET §qualification): maxTokens <= 512, p95 latency
11
+ * <= 40 ms, encoder RSS delta <= 150 MiB. When an asset field fails, the
12
+ * demotion code is `ENC_QUALIFICATION_ASSET_FAILED`; per-head / reconstruction
13
+ * failures report `ENC_QUALIFICATION_THRESHOLD_FAILED`. Either way the check is
14
+ * atomic — the field that tripped is surfaced via `failedField`.
15
+ * - per-head EVALUATION thresholds (EVALUATION.md §metrics):
16
+ * semantic spearman >= .75, recall@10 >= .90
17
+ * dependency precision >= .97, recall >= .95
18
+ * contradiction precision >= .98, recall >= .90, ECE <= .05
19
+ * cacheStability precision >= .999, recall >= .90
20
+ * payloadRouting macro-F1 >= .97, exact/anchor recall = 1.0
21
+ * - reconstruction: zero causal/tool/anchor/exact violations, dependency
22
+ * closure recall = 1.0, task-success non-inferior to C.
23
+ *
24
+ * Unique failure injection: when a candidate supplies an expected
25
+ * `qualificationManifestDigest` (the digest of the qualification manifest
26
+ * sealed at calibration time) and the presented calibration digest differs,
27
+ * selection returns ENC_QUALIFICATION_DIGEST_MISMATCH and demotes A — the
28
+ * "corrupt qualification manifest after calibration but before selection" case.
29
+ *
30
+ * Emits `vector_cortex_encoder_qualification_passed` on success and
31
+ * `vector_cortex_encoder_qualification_demoted` on any demotion, via the
32
+ * flag-gated VC2C reporter. Pi-agnostic, zero network (PREVENT-PI-004), no
33
+ * `any` (PREVENT-011).
34
+ */
35
+ import { createHash } from "node:crypto";
36
+ import { ENC_QUALIFICATION_FAIL, EVALUATION_THRESHOLDS, } from "./types.js";
37
+ import { createEncoderQualificationReporter, } from "./emit-vc2c.js";
38
+ /** Canonical digest over a CalibrationV1's stable identity (split digest, heads,
39
+ * temps, thresholds, seed) — the "qualification manifest digest". */
40
+ export function qualificationManifestDigest(calibration) {
41
+ const payload = JSON.stringify({
42
+ headOrder: [...calibration.headOrder].sort(),
43
+ splitDigest: calibration.calibrationSplitDigest,
44
+ temps: calibration.temperatures,
45
+ thresholds: calibration.thresholds,
46
+ seed: calibration.seed,
47
+ });
48
+ return createHash("sha256").update(payload).digest("hex");
49
+ }
50
+ /** True when one per-head metric row clears its normative EVALUATION threshold. */
51
+ function headPasses(head, m) {
52
+ switch (head) {
53
+ case "semantic":
54
+ return m.semantic.spearman >= EVALUATION_THRESHOLDS.semantic.spearman &&
55
+ m.semantic.recallAt10 >= EVALUATION_THRESHOLDS.semantic.recallAt10;
56
+ case "dependency":
57
+ return m.dependency.precision >= EVALUATION_THRESHOLDS.dependency.precision &&
58
+ m.dependency.recall >= EVALUATION_THRESHOLDS.dependency.recall;
59
+ case "contradiction":
60
+ return m.contradiction.precision >= EVALUATION_THRESHOLDS.contradiction.precision &&
61
+ m.contradiction.recall >= EVALUATION_THRESHOLDS.contradiction.recall &&
62
+ m.contradiction.ece <= EVALUATION_THRESHOLDS.contradiction.ece;
63
+ case "cacheStability":
64
+ return m.cacheStability.precision >= EVALUATION_THRESHOLDS.cacheStability.precision &&
65
+ m.cacheStability.recall >= EVALUATION_THRESHOLDS.cacheStability.recall;
66
+ case "payloadRouting":
67
+ return m.payloadRouting.macroF1 >= EVALUATION_THRESHOLDS.payloadRouting.macroF1 &&
68
+ m.payloadRouting.exactAnchorRecall >= EVALUATION_THRESHOLDS.payloadRouting.exactAnchorRecall;
69
+ }
70
+ }
71
+ function reconstructionPasses(m) {
72
+ return (m.reconstruction.votesOk &&
73
+ m.reconstruction.dependencyClosureRecall >= EVALUATION_THRESHOLDS.reconstruction.dependencyClosureRecall &&
74
+ m.reconstruction.taskSuccessNonInferior);
75
+ }
76
+ function assetPasses(a, failed) {
77
+ let ok = true;
78
+ if (a.maxTokens > EVALUATION_THRESHOLDS.asset.maxTokens) {
79
+ failed.push("asset.maxTokens");
80
+ ok = false;
81
+ }
82
+ if (a.latencyP95Ms > EVALUATION_THRESHOLDS.asset.maxLatencyP95Ms) {
83
+ failed.push("asset.latencyP95Ms");
84
+ ok = false;
85
+ }
86
+ if (a.rssDeltaMib > EVALUATION_THRESHOLDS.asset.maxRssDeltaMib) {
87
+ failed.push("asset.rssDeltaMib");
88
+ ok = false;
89
+ }
90
+ return ok;
91
+ }
92
+ /**
93
+ * Atomic eligibility check across every MODEL_ASSET + per-head EVALUATION
94
+ * threshold (task 3). Any single failed field demotes ALL of A (returns
95
+ * `ok:false`); there is no partial qualification. On success returns a
96
+ * `QualifiedEncoderV1` pinning asset/calibration digests + held-out evidence.
97
+ */
98
+ export function selectQualifiedEncoder(candidate, options = {}) {
99
+ const reporter = options.reporter ?? createEncoderQualificationReporter();
100
+ // Unique failure injection: corrupt qualification manifest between calibration
101
+ // and selection. The sealed manifest digest must match the presented
102
+ // calibration's digest; a mismatch demotes A to B/C with the dedicated code.
103
+ if (candidate.expectedQualificationManifestDigest !== undefined) {
104
+ const presented = qualificationManifestDigest(candidate.calibration);
105
+ if (presented !== candidate.expectedQualificationManifestDigest) {
106
+ reporter.qualificationDemoted({
107
+ reason: ENC_QUALIFICATION_FAIL.DIGEST_MISMATCH,
108
+ modelVersion: candidate.modelVersion,
109
+ mode: "B",
110
+ });
111
+ return {
112
+ ok: false,
113
+ mode: "B",
114
+ code: ENC_QUALIFICATION_FAIL.DIGEST_MISMATCH,
115
+ failedField: "qualificationManifestDigest",
116
+ };
117
+ }
118
+ }
119
+ // Atomic: collect EVERY failed field across asset + all heads + reconstruction.
120
+ const failed = [];
121
+ assetPasses(candidate.asset, failed);
122
+ const heads = ["semantic", "dependency", "contradiction", "cacheStability", "payloadRouting"];
123
+ for (const h of heads) {
124
+ if (!headPasses(h, candidate.heldOut))
125
+ failed.push(`head.${h}`);
126
+ }
127
+ if (!reconstructionPasses(candidate.heldOut))
128
+ failed.push("reconstruction");
129
+ if (failed.length > 0) {
130
+ // Any failed field demotes all of A — no partial A. Route the demotion code
131
+ // by the failed-field class: an asset-field failure (maxTokens/latency/RSS)
132
+ // reports ENC_QUALIFICATION_ASSET_FAILED; a per-head/reconstruction failure
133
+ // reports ENC_QUALIFICATION_THRESHOLD_FAILED. `failedField` always carries the
134
+ // specific field that tripped, so the code + field together fully identify it.
135
+ const assetFailed = failed.some((f) => f.startsWith("asset."));
136
+ const code = assetFailed
137
+ ? ENC_QUALIFICATION_FAIL.ASSET_FAILED
138
+ : ENC_QUALIFICATION_FAIL.THRESHOLD_FAILED;
139
+ reporter.qualificationDemoted({
140
+ reason: code,
141
+ failed: failed.join("/"),
142
+ modelVersion: candidate.modelVersion,
143
+ mode: "B",
144
+ });
145
+ return {
146
+ ok: false,
147
+ mode: "B",
148
+ code,
149
+ failedField: failed[0] ?? null,
150
+ };
151
+ }
152
+ const qualified = {
153
+ schema: "qualified-encoder-v1",
154
+ modelVersion: candidate.modelVersion,
155
+ mode: "A",
156
+ // The REAL ModelManifestV1 asset-manifest digest (passed through the
157
+ // candidate), not a calibration-derived hash — matches the documented
158
+ // contract and the dashboard health card's encoderAssetDigest.
159
+ assetDigest: candidate.assetManifestDigest,
160
+ calibrationDigest: candidate.calibration.calibrationSplitDigest,
161
+ onnxDigest: candidate.onnxDigest,
162
+ heldOut: candidate.heldOut,
163
+ calibration: candidate.calibration,
164
+ };
165
+ reporter.qualificationPassed({
166
+ modelVersion: candidate.modelVersion,
167
+ mode: "A",
168
+ assetDigest: qualified.assetDigest.slice(0, 12),
169
+ calibrationDigest: qualified.calibrationDigest.slice(0, 12),
170
+ });
171
+ return { ok: true, mode: "A", qualified, code: null };
172
+ }