pi-mega-compact 0.20.38 → 0.20.40

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 (114) hide show
  1. package/dist/config/vector-cortex-ml5c.js +28 -0
  2. package/dist/config/vector-cortex-ml5d.js +28 -0
  3. package/dist/config/vector-cortex.js +4 -3
  4. package/dist/config.js +1 -1
  5. package/dist/extensions/dashboard-server/api-contracts/cortex-improve.js +14 -0
  6. package/dist/extensions/dashboard-server/api-contracts/endpoints/registry-ext.js +13 -0
  7. package/dist/extensions/dashboard-server/route-dispatch.js +5 -1
  8. package/dist/extensions/dashboard-server/routes-cortex-improve.js +220 -0
  9. package/dist/extensions/dashboard-server/routes-rag-settings-vector-cortex.js +2 -0
  10. package/dist/extensions/dashboard-server/routes.js +1 -0
  11. package/dist/extensions/mega-runtime/dashboard-snapshot.js +2 -2
  12. package/dist/src/config/vector-cortex-ml5c.js +28 -0
  13. package/dist/src/config/vector-cortex-ml5d.js +28 -0
  14. package/dist/src/config/vector-cortex.js +4 -3
  15. package/dist/src/config.js +1 -1
  16. package/dist/src/store/backfill.js +0 -9
  17. package/dist/src/vector-cortex/encoder/runtime-emit.js +42 -0
  18. package/dist/src/vector-cortex/encoder/runtime-native.js +77 -0
  19. package/dist/src/vector-cortex/encoder/runtime-select.js +122 -0
  20. package/dist/src/vector-cortex/encoder/runtime-stub.js +35 -0
  21. package/dist/src/vector-cortex/encoder/runtime-wasm.js +71 -0
  22. package/dist/src/vector-cortex/encoder/runtime.js +49 -61
  23. package/dist/src/vector-cortex/improve.js +24 -0
  24. package/dist/vector-cortex/encoder/runtime-emit.js +42 -0
  25. package/dist/vector-cortex/encoder/runtime-native.js +77 -0
  26. package/dist/vector-cortex/encoder/runtime-select.js +122 -0
  27. package/dist/vector-cortex/encoder/runtime-stub.js +35 -0
  28. package/dist/vector-cortex/encoder/runtime-wasm.js +71 -0
  29. package/dist/vector-cortex/encoder/runtime.js +49 -61
  30. package/dist/vector-cortex/improve.js +24 -0
  31. package/extensions/dashboard-client/dist/assets/{AreaChart-DjXp8u2Y.js → AreaChart-BT7YPcp7.js} +2 -2
  32. package/extensions/dashboard-client/dist/assets/{AreaChart-DjXp8u2Y.js.map → AreaChart-BT7YPcp7.js.map} +1 -1
  33. package/extensions/dashboard-client/dist/assets/{BarChart-BZbus-dR.js → BarChart-DceGcBUh.js} +2 -2
  34. package/extensions/dashboard-client/dist/assets/{BarChart-BZbus-dR.js.map → BarChart-DceGcBUh.js.map} +1 -1
  35. package/extensions/dashboard-client/dist/assets/{CacheTab-DQ2CjxVW.js → CacheTab-B9lCouRl.js} +2 -2
  36. package/extensions/dashboard-client/dist/assets/{CacheTab-DQ2CjxVW.js.map → CacheTab-B9lCouRl.js.map} +1 -1
  37. package/extensions/dashboard-client/dist/assets/{EventsTab-DUpnOV1p.js → EventsTab-oqJ11jY7.js} +2 -2
  38. package/extensions/dashboard-client/dist/assets/{EventsTab-DUpnOV1p.js.map → EventsTab-oqJ11jY7.js.map} +1 -1
  39. package/extensions/dashboard-client/dist/assets/{HealthTab-Bul_xjcn.js → HealthTab-Dbosf2Ik.js} +2 -2
  40. package/extensions/dashboard-client/dist/assets/{HealthTab-Bul_xjcn.js.map → HealthTab-Dbosf2Ik.js.map} +1 -1
  41. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-DLUjdKd3.js → MaintenanceTab-6TiApCVE.js} +2 -2
  42. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-DLUjdKd3.js.map → MaintenanceTab-6TiApCVE.js.map} +1 -1
  43. package/extensions/dashboard-client/dist/assets/MemoryMapTab-cBsE4mTf.js +2 -0
  44. package/extensions/dashboard-client/dist/assets/{MemoryMapTab-BFy0hb6F.js.map → MemoryMapTab-cBsE4mTf.js.map} +1 -1
  45. package/extensions/dashboard-client/dist/assets/{MetricsTab-BpYuUkq3.js → MetricsTab-CX-X9hhy.js} +2 -2
  46. package/extensions/dashboard-client/dist/assets/{MetricsTab-BpYuUkq3.js.map → MetricsTab-CX-X9hhy.js.map} +1 -1
  47. package/extensions/dashboard-client/dist/assets/{OverviewTab-z7yuT-uq.js → OverviewTab-CpPYaTJF.js} +2 -2
  48. package/extensions/dashboard-client/dist/assets/{OverviewTab-z7yuT-uq.js.map → OverviewTab-CpPYaTJF.js.map} +1 -1
  49. package/extensions/dashboard-client/dist/assets/{ReposTab-ClORoDy_.js → ReposTab-D_Ot4QbU.js} +2 -2
  50. package/extensions/dashboard-client/dist/assets/{ReposTab-ClORoDy_.js.map → ReposTab-D_Ot4QbU.js.map} +1 -1
  51. package/extensions/dashboard-client/dist/assets/{SessionsTab-CUpehIt9.js → SessionsTab-BUzO3iGK.js} +2 -2
  52. package/extensions/dashboard-client/dist/assets/{SessionsTab-CUpehIt9.js.map → SessionsTab-BUzO3iGK.js.map} +1 -1
  53. package/extensions/dashboard-client/dist/assets/{SetupTab-Cii80Fdz.js → SetupTab-Be4w9v4j.js} +2 -2
  54. package/extensions/dashboard-client/dist/assets/{SetupTab-Cii80Fdz.js.map → SetupTab-Be4w9v4j.js.map} +1 -1
  55. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-BV2iCSdV.js → TimeSavedCard-Cx-g6CXH.js} +2 -2
  56. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-BV2iCSdV.js.map → TimeSavedCard-Cx-g6CXH.js.map} +1 -1
  57. package/extensions/dashboard-client/dist/assets/{TurnsTab-1T86rHnD.js → TurnsTab-CC_7T7ad.js} +3 -3
  58. package/extensions/dashboard-client/dist/assets/{TurnsTab-1T86rHnD.js.map → TurnsTab-CC_7T7ad.js.map} +1 -1
  59. package/extensions/dashboard-client/dist/assets/{VcStatusBadge-DKPleja8.js → VcStatusBadge-ZTItXSiH.js} +2 -2
  60. package/extensions/dashboard-client/dist/assets/{VcStatusBadge-DKPleja8.js.map → VcStatusBadge-ZTItXSiH.js.map} +1 -1
  61. package/extensions/dashboard-client/dist/assets/VectorCortexTab-DgAUZ4Pg.js +2 -0
  62. package/extensions/dashboard-client/dist/assets/VectorCortexTab-DgAUZ4Pg.js.map +1 -0
  63. package/extensions/dashboard-client/dist/assets/WikiTab-DnKupXTv.js +2 -0
  64. package/extensions/dashboard-client/dist/assets/{WikiTab-DKTILa1M.js.map → WikiTab-DnKupXTv.js.map} +1 -1
  65. package/extensions/dashboard-client/dist/assets/button-CFt3e0yc.js +2 -0
  66. package/extensions/dashboard-client/dist/assets/{button-5fSU8BZj.js.map → button-CFt3e0yc.js.map} +1 -1
  67. package/extensions/dashboard-client/dist/assets/{card-BFUnpXE_.js → card-C6ZjsHrl.js} +2 -2
  68. package/extensions/dashboard-client/dist/assets/{card-BFUnpXE_.js.map → card-C6ZjsHrl.js.map} +1 -1
  69. package/extensions/dashboard-client/dist/assets/client-extra-DdEdGTIe.js +2 -0
  70. package/extensions/dashboard-client/dist/assets/client-extra-DdEdGTIe.js.map +1 -0
  71. package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-xCzi6pWn.js → generateCategoricalChart-C9_fu2hc.js} +2 -2
  72. package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-xCzi6pWn.js.map → generateCategoricalChart-C9_fu2hc.js.map} +1 -1
  73. package/extensions/dashboard-client/dist/assets/{index-DqjmZ88m.js → index-DY81TY4f.js} +11 -11
  74. package/extensions/dashboard-client/dist/assets/index-DY81TY4f.js.map +1 -0
  75. package/extensions/dashboard-client/dist/assets/{switch-CeZUPf_e.js → switch-BOqa1d6x.js} +2 -2
  76. package/extensions/dashboard-client/dist/assets/{switch-CeZUPf_e.js.map → switch-BOqa1d6x.js.map} +1 -1
  77. package/extensions/dashboard-client/dist/assets/{toggle-MQQwdkwD.js → toggle-DToFaIEd.js} +2 -2
  78. package/extensions/dashboard-client/dist/assets/{toggle-MQQwdkwD.js.map → toggle-DToFaIEd.js.map} +1 -1
  79. package/extensions/dashboard-client/dist/assets/{useSSE-BetS7QHN.js → useSSE-CZqkhU18.js} +2 -2
  80. package/extensions/dashboard-client/dist/assets/{useSSE-BetS7QHN.js.map → useSSE-CZqkhU18.js.map} +1 -1
  81. package/extensions/dashboard-client/dist/index.html +1 -1
  82. package/extensions/dashboard-client/src/api/client-extra.ts +19 -1
  83. package/extensions/dashboard-client/src/components/ModelImprovementCard.tsx +141 -0
  84. package/extensions/dashboard-client/src/tabs/VectorCortexTab.tsx +6 -0
  85. package/extensions/dashboard-client/src/types/cortex-improve.ts +42 -0
  86. package/extensions/dashboard-server/api-contracts/cortex-improve.ts +82 -0
  87. package/extensions/dashboard-server/api-contracts/endpoints/registry-ext.ts +31 -0
  88. package/extensions/dashboard-server/api-contracts/index.ts +12 -0
  89. package/extensions/dashboard-server/route-dispatch.ts +4 -0
  90. package/extensions/dashboard-server/routes-cortex-improve.ts +256 -0
  91. package/extensions/dashboard-server/routes-rag-settings-vector-cortex.ts +12 -0
  92. package/extensions/dashboard-server/routes.ts +4 -0
  93. package/extensions/mega-runtime/dashboard-snapshot.ts +2 -2
  94. package/package.json +1 -1
  95. package/src/config/vector-cortex-ml5c.ts +30 -0
  96. package/src/config/vector-cortex-ml5d.ts +30 -0
  97. package/src/config/vector-cortex.ts +4 -4
  98. package/src/config.ts +2 -0
  99. package/src/store/backfill.ts +0 -7
  100. package/src/vector-cortex/encoder/runtime-emit.ts +47 -0
  101. package/src/vector-cortex/encoder/runtime-native.ts +117 -0
  102. package/src/vector-cortex/encoder/runtime-select.ts +167 -0
  103. package/src/vector-cortex/encoder/runtime-stub.ts +38 -0
  104. package/src/vector-cortex/encoder/runtime-wasm.ts +110 -0
  105. package/src/vector-cortex/encoder/runtime.ts +59 -66
  106. package/src/vector-cortex/improve.ts +28 -0
  107. package/extensions/dashboard-client/dist/assets/MemoryMapTab-BFy0hb6F.js +0 -2
  108. package/extensions/dashboard-client/dist/assets/VectorCortexTab-BRzvd_pU.js +0 -2
  109. package/extensions/dashboard-client/dist/assets/VectorCortexTab-BRzvd_pU.js.map +0 -1
  110. package/extensions/dashboard-client/dist/assets/WikiTab-DKTILa1M.js +0 -2
  111. package/extensions/dashboard-client/dist/assets/button-5fSU8BZj.js +0 -2
  112. package/extensions/dashboard-client/dist/assets/client-extra-BZbw21wu.js +0 -2
  113. package/extensions/dashboard-client/dist/assets/client-extra-BZbw21wu.js.map +0 -1
  114. package/extensions/dashboard-client/dist/assets/index-DqjmZ88m.js.map +0 -1
@@ -0,0 +1,47 @@
1
+ /**
2
+ * vector-cortex/encoder/runtime-emit.ts — ML5-C seller event emitter.
3
+ *
4
+ * Emits the `vector_cortex_runtime_selected` seller event to the local
5
+ * events.log so the dashboard Setup Cortex blockers card can surface the HG-3
6
+ * (install budget) / HG-4 (darwin-x64 demotion) closure state. Aggregate
7
+ * fields only — never payload bytes (EVAL-REDACT-002).
8
+ *
9
+ * Extracted from runtime.ts so the runtime delegate-shell stays under the
10
+ * 300-line soft limit after the ML5-C dispatch was added. All writes are
11
+ * best-effort / non-fatal; a disk-full or missing state dir never breaks the
12
+ * encoder loop.
13
+ *
14
+ * Pi-agnostic, dependency-free (PREVENT-PI-004 — local filesystem append only;
15
+ * no network). No `any` (PREVENT-011).
16
+ */
17
+
18
+ import { appendFileSync, mkdirSync } from "node:fs";
19
+ import { dirname } from "node:path";
20
+ import { defaultEventsPath } from "../../monitoring.js";
21
+ import type { RuntimeSelectionResult } from "./runtime-select.js";
22
+
23
+ /**
24
+ * Emit the ML5-C `vector_cortex_runtime_selected` seller event (best-effort).
25
+ * The event carries ONLY the four aggregate fields the sprint spec pins
26
+ * ({backend, p95Ms, budgetOk, platform}) — never message content.
27
+ */
28
+ export function emitRuntimeSelected(
29
+ stateDir: string,
30
+ result: Pick<RuntimeSelectionResult, "backend" | "p95Ms" | "budgetOk" | "platform">,
31
+ ): void {
32
+ try {
33
+ const path = defaultEventsPath(stateDir);
34
+ const payload = {
35
+ ts: Date.now(),
36
+ event: "vector_cortex_runtime_selected",
37
+ backend: result.backend,
38
+ p95Ms: result.p95Ms,
39
+ budgetOk: result.budgetOk,
40
+ platform: result.platform,
41
+ };
42
+ mkdirSync(dirname(path), { recursive: true });
43
+ appendFileSync(path, JSON.stringify(payload) + "\n", "utf8");
44
+ } catch {
45
+ /* best-effort — never break the encoder loop */
46
+ }
47
+ }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * vector-cortex/encoder/runtime-native.ts — ML5-C native backend (Option N).
3
+ *
4
+ * Loads an `InferenceSession` from the `onnxruntime-node` native binding for
5
+ * the committed encoder-v1 ONNX asset. This is the CHOSEN selection when
6
+ * `MEGACOMPACT_ENCODER_NATIVE=1` (the native opt-in marker) is set AND the
7
+ * package is present — it uses the platform-specific prebuilt binary (no
8
+ * postinstall compilation needed; per vc2-model-prep §1 the allowScripts
9
+ * removal is safe because only CUDA/TensorRT downloads use it, and pi blocks
10
+ * all scripts anyway).
11
+ *
12
+ * The package is NOT declared in package.json dependencies — it is a lazily-
13
+ * resolved peer that the runtime loads ONLY when the native opt-in is set AND
14
+ * selected. Loading uses dynamic `import()` so the module graph compiles
15
+ * cleanly on hosts without the package (absent installs return null, never
16
+ * throw), so the ML5-C dispatch demotes to mode B trigram rather than
17
+ * breaking.
18
+ *
19
+ * Pi-agnostic, dependency-free (PREVENT-PI-004 — the native binary + model are
20
+ * committed local files). No `any` (PREVENT-011).
21
+ */
22
+
23
+ import {
24
+ ENCODER_OPSET,
25
+ ENCODER_SEMANTIC_WIDTH,
26
+ ENCODER_MAX_TOKENS,
27
+ } from "./types.js";
28
+
29
+ /** The shape of the optionalImport result when onnxruntime-node is present.
30
+ * Shadow-types instead of `import("onnxruntime-node")` so the module graph
31
+ * builds without the package being declared in package.json (ML5-B precedent). */
32
+ export interface OrtNativeModule {
33
+ InferenceSession: {
34
+ create(
35
+ path: string,
36
+ opts: { executionProviders: string[]; intraOpNumThreads: number },
37
+ ): Promise<{
38
+ run(
39
+ feeds: Record<string, Float32Array>,
40
+ outputNames: string[],
41
+ ): Promise<Record<string, { data: Float32Array }>>;
42
+ }>;
43
+ };
44
+ }
45
+
46
+ /** The backend's inference session — a thin wrapper over the real native session. */
47
+ export interface NativeSession {
48
+ /** The declared ONNX opset in the loaded manifest (normative 17). */
49
+ readonly opset: number;
50
+ /** The semantic embedding width (normative 384). */
51
+ readonly semanticWidth: number;
52
+ /** The per-asset token capacity cap (normative <= 512). */
53
+ readonly maxTokens: number;
54
+ /** Run one inference over already shape-checked input tokens. */
55
+ infer(inputIds: Float32Array): Promise<Float32Array>;
56
+ }
57
+
58
+ /** True when `MEGACOMPACT_ENCODER_NATIVE=1` (the native opt-in operator flag). */
59
+ export function nativeOptIn(): boolean {
60
+ return process.env.MEGACOMPACT_ENCODER_NATIVE === "1";
61
+ }
62
+
63
+ /** True if `onnxruntime-node` resolves on this host (loading is best-effort).
64
+ * Absent installs return null (never throw) so the ML5-C dispatch can demote
65
+ * to mode B trigram cleanly. */
66
+ async function loadOrtNative(): Promise<OrtNativeModule | null> {
67
+ try {
68
+ // @ts-expect-error — optional peer; the shadow type above covers the surface
69
+ const mod = (await import("onnxruntime-node")) as OrtNativeModule;
70
+ return mod;
71
+ } catch {
72
+ return null;
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Create a native-backed `NativeSession` over the committed ONNX asset, gated
78
+ * first on `nativeOptIn()`. Returns null (never throws) on any failure
79
+ * (opt-in off, absent package, unreadable asset, bad session creation) so the
80
+ * caller demotes to mode B trigram.
81
+ */
82
+ export async function createNativeSession(
83
+ modelPath: string,
84
+ options: { threads?: number; maxTokens?: number } = {},
85
+ ): Promise<NativeSession | null> {
86
+ if (!nativeOptIn()) return null;
87
+
88
+ const ort = await loadOrtNative();
89
+ if (!ort || !ort.InferenceSession?.create) return null;
90
+
91
+ const threads = options.threads ?? 4;
92
+ const maxTokens = options.maxTokens ?? ENCODER_MAX_TOKENS;
93
+
94
+ try {
95
+ const session = await ort.InferenceSession.create(modelPath, {
96
+ executionProviders: ["cpu"],
97
+ intraOpNumThreads: threads,
98
+ });
99
+
100
+ return {
101
+ opset: ENCODER_OPSET,
102
+ semanticWidth: ENCODER_SEMANTIC_WIDTH,
103
+ maxTokens,
104
+ async infer(inputIds: Float32Array): Promise<Float32Array> {
105
+ const feeds = { input_ids: inputIds };
106
+ const results = await session.run(feeds, ["embedding"]);
107
+ const out = results["embedding"];
108
+ if (!out || !(out.data instanceof Float32Array)) {
109
+ return new Float32Array(ENCODER_SEMANTIC_WIDTH);
110
+ }
111
+ return out.data;
112
+ },
113
+ };
114
+ } catch {
115
+ return null;
116
+ }
117
+ }
@@ -0,0 +1,167 @@
1
+ /**
2
+ * vector-cortex/encoder/runtime-select.ts — ML5-C decision-rule dispatch.
3
+ *
4
+ * Pure function of {platform, benchRecord, nativeOptIn} → the chosen ONNX
5
+ * runtime backend. This is the deterministic selection that closes HG-3
6
+ * (install budget) and HG-4 (darwin-x64 disposition) per the ML5-C spec:
7
+ *
8
+ * - Measured p95 at 512 tokens on 4 threads (linux-x64) <= 40 ms → Option W (WASM)
9
+ * - Measured p95 > 40 ms or absent (degraded) → Option N (native)
10
+ * - Platform is darwin-x64 (Intel Mac, HG-1 deferral) → WASM demotion or mode B
11
+ *
12
+ * The `platform` comes from `detectPlatform()` (already in `asset.ts`); the
13
+ * `benchRecord` is the latest `BenchResultV1` (from ML5-B / JSONL); the
14
+ * `nativeOptIn` helper reads `MEGACOMPACT_ENCODER_NATIVE=1`. The selection is
15
+ * PURE — no side effects, no I/O, no network. The caller stamps the result on
16
+ * the `vector_cortex_runtime_selected` event carried to the dashboard.
17
+ *
18
+ * Pi-agnostic, dependency-free (PREVENT-PI-004 — selection is computed+in memory;
19
+ * no fetch/HTTP). No `any` (PREVENT-011).
20
+ */
21
+
22
+ import {
23
+ ENCODER_LATENCY_P95_MS,
24
+ type EncoderPlatform,
25
+ } from "./types.js";
26
+ import type { BenchResultV1 } from "./bench-export.js";
27
+ import { ML5C_ENABLED } from "../../config/vector-cortex.js";
28
+
29
+ /** The chosen runtime backend name as it appears on the seller event. */
30
+ export type RuntimeBackendChoice = "wasm" | "native" | "modeB";
31
+
32
+ /** Inputs to the backend selection. `platform` is `${process.platform}-${process.arch}`. */
33
+ export interface RuntimeSelectionInput {
34
+ /** The platform this process is running on (from detectPlatform()). */
35
+ readonly platform: EncoderPlatform | "unsupported";
36
+ /**
37
+ * The ML5-B bench record for this platform (linux-x64 normative). Null when
38
+ * no bench has run yet (degraded: the 42-byte placeholder has no real p95).
39
+ * Must provide a numeric p95Ms for WASM consideration; a null/error record
40
+ * (gates.all:false) forces the native fallback per the decision rule.
41
+ */
42
+ readonly benchRecord: BenchResultV1 | null;
43
+ /** True when the operator opted into onnxruntime-node via MEGACOMPACT_ENCODER_NATIVE=1. */
44
+ readonly nativeOptIn: boolean;
45
+ }
46
+
47
+ /** The output of the ML5-C decision-rule dispatch. */
48
+ export interface RuntimeSelectionResult {
49
+ /** The chosen backend. */
50
+ readonly backend: RuntimeBackendChoice;
51
+ /** HG-3 closure state: whether the 80 MiB install budget is satisfied. */
52
+ readonly budgetOk: boolean;
53
+ /** The measured p95 (ms) that drove the decision, from BenchResultV1. */
54
+ readonly p95Ms: number | null;
55
+ /** The platform the selection is valid for. */
56
+ readonly platform: string;
57
+ /** Short human-readable rationale for the choice (record on the event). */
58
+ readonly rationale: string;
59
+ }
60
+
61
+ /** The 80 MiB install budget in bytes (the HG-3 ceiling, unamended). */
62
+ export const RUNTIME_NATIVE_INSTALL_BUDGET_MIB = 80;
63
+
64
+ /**
65
+ * Per-platform optionalDependency footprint of onnxruntime-node (MiB, approx).
66
+ * These sum to ~160 MiB SHIPPED in the npm package (every target platform is
67
+ * included so the resolver lands on a concrete row at install time) — which is
68
+ * what exceeds the 80 MiB HG-3 budget and forces the amendment the fixtures
69
+ * record (ML5-RUNTIME-001). The per-host INSTALLED footprint (one row only)
70
+ * is 28–35 MiB and irrelevant to the 80 MiB ceiling — the budget covers the
71
+ * shipped tarball, not the single-platform install.
72
+ */
73
+ export const NATIVE_FOOTPRINT_MIB: Readonly<Record<EncoderPlatform, number>> = {
74
+ "linux-x64": 33,
75
+ "darwin-arm64": 28,
76
+ "darwin-x64": 33,
77
+ "linux-arm64": 31,
78
+ "win32-x64": 35,
79
+ };
80
+
81
+ /**
82
+ * ML5-C decision-rule dispatch: choose the ONNX runtime backend (pure).
83
+ *
84
+ * When the flag is OFF (`MEGACOMPACT_ML5_C=0`), returns mode B trigram — byte-
85
+ * identical to the ML5-B survivor with no selection event emitted.
86
+ *
87
+ * The rule (from the sprint spec):
88
+ * - If nativeOptIn && platform is supported → native (Option N)
89
+ * - If benchRecord has p95Ms <= 40 ms on linux-x64 → WASM (Option W)
90
+ * - Else → native (Option N) with the budget amendment recorded (p95 exceeds
91
+ * the WASM gate or is absent — the placeholder has no measured p95)
92
+ * - darwin-x64 → WASM or mode B demotion per HG-4 (never native here)
93
+ */
94
+ export function selectRuntimeBackend(input: RuntimeSelectionInput): RuntimeSelectionResult {
95
+ if (!ML5C_ENABLED()) {
96
+ return {
97
+ backend: "modeB",
98
+ budgetOk: true,
99
+ p95Ms: null,
100
+ platform: input.platform,
101
+ rationale: "flag-off: byte-identical mode-B trigram (no selection)",
102
+ };
103
+ }
104
+
105
+ // HG-4: Intel Mac (darwin-x64) is out-of-scope per HG-1's deferral — always demote.
106
+ if (input.platform === "darwin-x64") {
107
+ return {
108
+ backend: "wasm",
109
+ budgetOk: true,
110
+ p95Ms: null,
111
+ platform: input.platform,
112
+ rationale: "darwin-x64 demoted to WASM per HG-4 (never native on this platform)",
113
+ };
114
+ }
115
+
116
+ // Native opt-in short-circuits: operator explicitly wants the native path.
117
+ // The HG-3 budget compares the SHIPPED byte-count (sum across every platform
118
+ // row in the package's optionalDependencies map) against the 80 MiB ceiling
119
+ // — not the single-platform install size. Native always exceeds 80 MiB across
120
+ // 5 platforms (~160 MiB shipped), so budgetOk is false and the evidence
121
+ // records the amended budget (the ML5-C spec, HG-3 closure).
122
+ if (input.nativeOptIn) {
123
+ const shippedMib = Object.values(NATIVE_FOOTPRINT_MIB).reduce((a, b) => a + b, 0);
124
+ return {
125
+ backend: "native",
126
+ budgetOk: shippedMib <= RUNTIME_NATIVE_INSTALL_BUDGET_MIB,
127
+ p95Ms: input.benchRecord?.p95Ms ?? null,
128
+ platform: input.platform,
129
+ rationale: `native opt-in (MEGACOMPACT_ENCODER_NATIVE=1); shipped ${shippedMib} MiB across 5 platforms → budget amended to ${shippedMib} MiB`,
130
+ };
131
+ }
132
+
133
+ // No bench record or degraded (gates.all:false) → WASM cannot qualify (the
134
+ // placeholder 42-byte asset has no measured real p95), so native is selected
135
+ // with the SAME amended-budget disposition as the opt-in path above: the
136
+ // evidence records the closed HG-3 amendment.
137
+ if (!input.benchRecord || !input.benchRecord.gates.all || input.benchRecord.p95Ms === null) {
138
+ const shippedMib = Object.values(NATIVE_FOOTPRINT_MIB).reduce((a, b) => a + b, 0);
139
+ return {
140
+ backend: "native",
141
+ budgetOk: false, // amended: native ships > 80 MiB across the 5-platform matrix
142
+ p95Ms: input.benchRecord?.p95Ms ?? null,
143
+ platform: input.platform,
144
+ rationale: `no qualifying bench record — native fallback with budget amendment (${shippedMib} MiB shipped, HG-3 amendment recorded)`,
145
+ };
146
+ }
147
+
148
+ // The decision rule: WASM iff p95 <= 40 ms (linux-x64, 512 tokens, 4 threads) —
149
+ // native required otherwise, with the same budget amendment recorded.
150
+ if (input.benchRecord.p95Ms <= ENCODER_LATENCY_P95_MS) {
151
+ return {
152
+ backend: "wasm",
153
+ budgetOk: true,
154
+ p95Ms: input.benchRecord.p95Ms,
155
+ platform: input.platform,
156
+ rationale: `WASM qualifies: p95 ${input.benchRecord.p95Ms}ms <= ${ENCODER_LATENCY_P95_MS}ms`,
157
+ };
158
+ }
159
+
160
+ return {
161
+ backend: "native",
162
+ budgetOk: false, // amended: native exceeds the 80 MiB budget per the evidence
163
+ p95Ms: input.benchRecord.p95Ms,
164
+ platform: input.platform,
165
+ rationale: `native required: p95 ${input.benchRecord.p95Ms}ms > ${ENCODER_LATENCY_P95_MS}ms on WASM`,
166
+ };
167
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * vector-cortex/encoder/runtime-stub.ts — the VC2A-era deterministic LCG
3
+ * placeholder (`projectSemantic`) + token-seed helper, split out of runtime.ts
4
+ * so `runtime.ts` stays under its 300-line soft limit as the delegate-shell.
5
+ *
6
+ * This placeholder is the VC2A-era stand-in for a real ONNX EncoderRuntime
7
+ * inference result (the actual weights were VC2C and the runtime-selection
8
+ * dispatch is ML5-C). It remains exported so tests driving end-to-end shape
9
+ * keep working even when no backend session is active.
10
+ *
11
+ * Pi-agnostic, dependency-free (PREVENT-PI-004 / PREVENT-011).
12
+ */
13
+
14
+ import { ENCODER_SEMANTIC_WIDTH } from "./types.js";
15
+
16
+ /** A deterministic seeded projection so the mode-A inference path is testable
17
+ * end-to-end without onnxruntime (real weights + execution are VC2C). */
18
+ export function projectSemantic(seed: number, n: number): Float32Array {
19
+ const out = new Float32Array(n);
20
+ let state = (seed >>> 0) ^ 0x9e3779b9;
21
+ let sum = 0;
22
+ for (let i = 0; i < n; i++) {
23
+ state = (state * 1664525 + 1013904223) >>> 0;
24
+ out[i] = (state / 4294967296) * 2 - 1;
25
+ sum += out[i]! * out[i]!;
26
+ }
27
+ const norm = Math.sqrt(sum) || 1;
28
+ for (let i = 0; i < n; i++) out[i] = out[i]! / norm;
29
+ return out;
30
+ }
31
+
32
+ /** Deterministic token seed derived from the verified asset bytes count. */
33
+ export function seedFromBytes(embeddedBytes: number): number {
34
+ return (embeddedBytes * 2654435761) >>> 0;
35
+ }
36
+
37
+ /** The semantic embedding width from the normative types barrel. */
38
+ export { ENCODER_SEMANTIC_WIDTH };
@@ -0,0 +1,110 @@
1
+ /**
2
+ * vector-cortex/encoder/runtime-wasm.ts — ML5-C WASM backend (Option W).
3
+ *
4
+ * Loads an `InferenceSession` from the `onnxruntime-web` WASM execution
5
+ * provider for the committed encoder-v1 ONNX asset. This is the default
6
+ * backend when the WASM path is selected by `select.ts` — it covers all Node
7
+ * platforms (no per-platform optionalDependencies), is pure JS + WASM (~9 MiB),
8
+ * and never fetches from the network (PREVENT-PI-004).
9
+ *
10
+ * The package is NOT declared in package.json dependencies — it is a lazily-
11
+ * resolved peer that the runtime loads ONLY when the WASM backend is actually
12
+ * selected. Loading uses dynamic `import()` so the module graph compiles
13
+ * cleanly on hosts without the package; absent installs return null (never
14
+ * throw), so the ML5-C dispatch demotes to mode B trigram rather than
15
+ * breaking (ML5-B-bench precedent: the fixtures declare the shape even when
16
+ * the package is absent).
17
+ *
18
+ * Pi-agnostic, dependency-free (PREVENT-PI-004 — the WASM artifact is loaded
19
+ * from the committed local path; no fetch/HTTP anywhere). No `any`
20
+ * (PREVENT-011).
21
+ */
22
+
23
+ import {
24
+ ENCODER_OPSET,
25
+ ENCODER_SEMANTIC_WIDTH,
26
+ ENCODER_MAX_TOKENS,
27
+ } from "./types.js";
28
+
29
+ /** The shape of the optionalImport result when onnxruntime-web is present.
30
+ * Shadow-types instead of `import("onnxruntime-web")` so the module graph builds
31
+ * without the package being declared in package.json (ML5-B precedent). */
32
+ export interface OrtWasmModule {
33
+ InferenceSession: {
34
+ create(
35
+ path: string,
36
+ opts: { executionProviders: string[]; intraOpNumThreads: number },
37
+ ): Promise<{
38
+ run(
39
+ feeds: Record<string, Float32Array>,
40
+ outputNames: string[],
41
+ ): Promise<Record<string, { data: Float32Array }>>;
42
+ }>;
43
+ };
44
+ }
45
+
46
+ /** The backend's inference session — a thin wrapper over the real WASM session. */
47
+ export interface WasmSession {
48
+ /** The declared ONNX opset in the loaded manifest (normative 17). */
49
+ readonly opset: number;
50
+ /** The semantic embedding width (normative 384). */
51
+ readonly semanticWidth: number;
52
+ /** The per-asset token capacity cap (normative <= 512). */
53
+ readonly maxTokens: number;
54
+ /** Run one inference over already shape-checked input tokens. */
55
+ infer(inputIds: Float32Array): Promise<Float32Array>;
56
+ }
57
+
58
+ /** True if `onnxruntime-web` resolves on this host (loading is best-effort).
59
+ * Absent installs return null (never throw) so the ML5-C dispatch can demote
60
+ * to mode B trigram cleanly. */
61
+ async function loadOrtWasm(): Promise<OrtWasmModule | null> {
62
+ try {
63
+ // @ts-expect-error — optional peer; the shadow type above covers the surface
64
+ const mod = (await import("onnxruntime-web")) as OrtWasmModule;
65
+ return mod;
66
+ } catch {
67
+ return null;
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Create a WASM-backed `WasmSession` over the committed ONNX asset. Returns
73
+ * null (never throws) on any failure (absent package, unreadable asset, bad
74
+ * session creation) so the caller demotes to mode B trigram per HG-4 mode-B
75
+ * disposition when the WASM path is unavailable on a darwin-x64 host.
76
+ */
77
+ export async function createWasmSession(
78
+ modelPath: string,
79
+ options: { threads?: number; maxTokens?: number } = {},
80
+ ): Promise<WasmSession | null> {
81
+ const ort = await loadOrtWasm();
82
+ if (!ort || !ort.InferenceSession?.create) return null;
83
+
84
+ const threads = options.threads ?? 4;
85
+ const maxTokens = options.maxTokens ?? ENCODER_MAX_TOKENS;
86
+
87
+ try {
88
+ const session = await ort.InferenceSession.create(modelPath, {
89
+ executionProviders: ["wasm"],
90
+ intraOpNumThreads: threads,
91
+ });
92
+
93
+ return {
94
+ opset: ENCODER_OPSET,
95
+ semanticWidth: ENCODER_SEMANTIC_WIDTH,
96
+ maxTokens,
97
+ async infer(inputIds: Float32Array): Promise<Float32Array> {
98
+ const feeds = { input_ids: inputIds };
99
+ const results = await session.run(feeds, ["embedding"]);
100
+ const out = results["embedding"];
101
+ if (!out || !(out.data instanceof Float32Array)) {
102
+ return new Float32Array(ENCODER_SEMANTIC_WIDTH);
103
+ }
104
+ return out.data;
105
+ },
106
+ };
107
+ } catch {
108
+ return null;
109
+ }
110
+ }