pi-mega-compact 0.20.48 → 0.20.50

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 (90) hide show
  1. package/dist/config/vector-cortex-enc0g.js +37 -0
  2. package/dist/config/vector-cortex-enc1a.js +39 -0
  3. package/dist/config/vector-cortex.js +2 -0
  4. package/dist/config.js +1 -1
  5. package/dist/extensions/dashboard-server/qualification-record.js +71 -0
  6. package/dist/extensions/dashboard-server/routes-rag-settings-vector-cortex.js +2 -0
  7. package/dist/extensions/dashboard-server/routes-setup-cortex-actions.js +49 -3
  8. package/dist/extensions/dashboard-server/routes-setup-cortex.js +65 -16
  9. package/dist/extensions/dashboard-server/routes-setup-enc1a.js +157 -0
  10. package/dist/extensions/dashboard-server/routes-setup.js +21 -0
  11. package/dist/extensions/dashboard-server/setup-cortex-actions.js +21 -4
  12. package/dist/extensions/dashboard-server/setup-cortex-blockers.js +3 -69
  13. package/dist/src/config/vector-cortex-enc0g.js +37 -0
  14. package/dist/src/config/vector-cortex-enc1a.js +39 -0
  15. package/dist/src/config/vector-cortex.js +2 -0
  16. package/dist/src/config.js +1 -1
  17. package/dist/src/vector-cortex/setup-cortex-blockers-compute.js +160 -0
  18. package/dist/vector-cortex/setup-cortex-blockers-compute.js +160 -0
  19. package/extensions/dashboard-client/dist/assets/{AreaChart-COnj8FHi.js → AreaChart-CeVnaV-0.js} +2 -2
  20. package/extensions/dashboard-client/dist/assets/{AreaChart-COnj8FHi.js.map → AreaChart-CeVnaV-0.js.map} +1 -1
  21. package/extensions/dashboard-client/dist/assets/{BarChart-BYqt8c5-.js → BarChart-DoNd35sw.js} +2 -2
  22. package/extensions/dashboard-client/dist/assets/{BarChart-BYqt8c5-.js.map → BarChart-DoNd35sw.js.map} +1 -1
  23. package/extensions/dashboard-client/dist/assets/{CacheTab-PLRjMrZV.js → CacheTab-BROshdFf.js} +2 -2
  24. package/extensions/dashboard-client/dist/assets/{CacheTab-PLRjMrZV.js.map → CacheTab-BROshdFf.js.map} +1 -1
  25. package/extensions/dashboard-client/dist/assets/{EventsTab-DXKSft6w.js → EventsTab-DAD6NeBR.js} +2 -2
  26. package/extensions/dashboard-client/dist/assets/{EventsTab-DXKSft6w.js.map → EventsTab-DAD6NeBR.js.map} +1 -1
  27. package/extensions/dashboard-client/dist/assets/{HealthTab-BgVIsrde.js → HealthTab-BBVMM54F.js} +2 -2
  28. package/extensions/dashboard-client/dist/assets/{HealthTab-BgVIsrde.js.map → HealthTab-BBVMM54F.js.map} +1 -1
  29. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-DNgFC8KZ.js → MaintenanceTab-f9VhlFco.js} +2 -2
  30. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-DNgFC8KZ.js.map → MaintenanceTab-f9VhlFco.js.map} +1 -1
  31. package/extensions/dashboard-client/dist/assets/{MemoryMapTab-B6yY47sz.js → MemoryMapTab-BaxfyzN2.js} +2 -2
  32. package/extensions/dashboard-client/dist/assets/{MemoryMapTab-B6yY47sz.js.map → MemoryMapTab-BaxfyzN2.js.map} +1 -1
  33. package/extensions/dashboard-client/dist/assets/{MetricsTab-BrhJ6rkx.js → MetricsTab-DkUvoeS_.js} +2 -2
  34. package/extensions/dashboard-client/dist/assets/{MetricsTab-BrhJ6rkx.js.map → MetricsTab-DkUvoeS_.js.map} +1 -1
  35. package/extensions/dashboard-client/dist/assets/{OverviewTab-RFHU9L4x.js → OverviewTab-BCpK1vgt.js} +2 -2
  36. package/extensions/dashboard-client/dist/assets/{OverviewTab-RFHU9L4x.js.map → OverviewTab-BCpK1vgt.js.map} +1 -1
  37. package/extensions/dashboard-client/dist/assets/{ReposTab-UFIWKkJM.js → ReposTab-cJ5neYIG.js} +2 -2
  38. package/extensions/dashboard-client/dist/assets/{ReposTab-UFIWKkJM.js.map → ReposTab-cJ5neYIG.js.map} +1 -1
  39. package/extensions/dashboard-client/dist/assets/{SessionsTab-BHFYsmK8.js → SessionsTab-8DyQv1Ry.js} +2 -2
  40. package/extensions/dashboard-client/dist/assets/{SessionsTab-BHFYsmK8.js.map → SessionsTab-8DyQv1Ry.js.map} +1 -1
  41. package/extensions/dashboard-client/dist/assets/SetupTab-BQGPf9CI.js +3 -0
  42. package/extensions/dashboard-client/dist/assets/SetupTab-BQGPf9CI.js.map +1 -0
  43. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-aPG5Knqn.js → TimeSavedCard-8N7Vvlch.js} +2 -2
  44. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-aPG5Knqn.js.map → TimeSavedCard-8N7Vvlch.js.map} +1 -1
  45. package/extensions/dashboard-client/dist/assets/{TurnsTab-fGm9n-Tk.js → TurnsTab-CCijkQoH.js} +2 -2
  46. package/extensions/dashboard-client/dist/assets/{TurnsTab-fGm9n-Tk.js.map → TurnsTab-CCijkQoH.js.map} +1 -1
  47. package/extensions/dashboard-client/dist/assets/{VcStatusBadge-BtmSNH8X.js → VcStatusBadge-D9a7By8x.js} +2 -2
  48. package/extensions/dashboard-client/dist/assets/{VcStatusBadge-BtmSNH8X.js.map → VcStatusBadge-D9a7By8x.js.map} +1 -1
  49. package/extensions/dashboard-client/dist/assets/{VectorCortexTab-meALMMOZ.js → VectorCortexTab-pviD6CCy.js} +2 -2
  50. package/extensions/dashboard-client/dist/assets/{VectorCortexTab-meALMMOZ.js.map → VectorCortexTab-pviD6CCy.js.map} +1 -1
  51. package/extensions/dashboard-client/dist/assets/{WikiTab-0TK6q6g1.js → WikiTab-DLyicguz.js} +2 -2
  52. package/extensions/dashboard-client/dist/assets/{WikiTab-0TK6q6g1.js.map → WikiTab-DLyicguz.js.map} +1 -1
  53. package/extensions/dashboard-client/dist/assets/{button-CKEnMZ98.js → button-D8nKit8Y.js} +2 -2
  54. package/extensions/dashboard-client/dist/assets/{button-CKEnMZ98.js.map → button-D8nKit8Y.js.map} +1 -1
  55. package/extensions/dashboard-client/dist/assets/{card-BVVhm3sL.js → card-Xf5wHHBL.js} +2 -2
  56. package/extensions/dashboard-client/dist/assets/{card-BVVhm3sL.js.map → card-Xf5wHHBL.js.map} +1 -1
  57. package/extensions/dashboard-client/dist/assets/{client-extra-BvGxKZpm.js → client-extra-CvxDLpQr.js} +2 -2
  58. package/extensions/dashboard-client/dist/assets/{client-extra-BvGxKZpm.js.map → client-extra-CvxDLpQr.js.map} +1 -1
  59. package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-B1PeCct1.js → generateCategoricalChart-DhQquRa8.js} +2 -2
  60. package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-B1PeCct1.js.map → generateCategoricalChart-DhQquRa8.js.map} +1 -1
  61. package/extensions/dashboard-client/dist/assets/{index-DuThOA-d.js → index-BUP3MK5S.js} +3 -3
  62. package/extensions/dashboard-client/dist/assets/{index-DuThOA-d.js.map → index-BUP3MK5S.js.map} +1 -1
  63. package/extensions/dashboard-client/dist/assets/{switch-7qLS7ajc.js → switch-B13rb8Z2.js} +2 -2
  64. package/extensions/dashboard-client/dist/assets/{switch-7qLS7ajc.js.map → switch-B13rb8Z2.js.map} +1 -1
  65. package/extensions/dashboard-client/dist/assets/{toggle-D7mgOVxz.js → toggle-4h6DUEB5.js} +2 -2
  66. package/extensions/dashboard-client/dist/assets/{toggle-D7mgOVxz.js.map → toggle-4h6DUEB5.js.map} +1 -1
  67. package/extensions/dashboard-client/dist/assets/{useSSE-ChpyZVeX.js → useSSE-Djom4z1K.js} +2 -2
  68. package/extensions/dashboard-client/dist/assets/{useSSE-ChpyZVeX.js.map → useSSE-Djom4z1K.js.map} +1 -1
  69. package/extensions/dashboard-client/dist/index.html +1 -1
  70. package/extensions/dashboard-client/src/tabs/SetupTab/CustomEndpointSection.tsx +57 -2
  71. package/extensions/dashboard-client/src/tabs/SetupTab/EmbedderSetup.tsx +9 -39
  72. package/extensions/dashboard-client/src/tabs/SetupTab/EmbedderSetupHelpers.tsx +50 -0
  73. package/extensions/dashboard-server/api-contracts/setup-cortex.ts +6 -2
  74. package/extensions/dashboard-server/api-contracts/setup.ts +12 -0
  75. package/extensions/dashboard-server/qualification-record.ts +70 -0
  76. package/extensions/dashboard-server/routes-rag-settings-vector-cortex.ts +12 -0
  77. package/extensions/dashboard-server/routes-setup-cortex-actions.ts +50 -3
  78. package/extensions/dashboard-server/routes-setup-cortex.ts +92 -16
  79. package/extensions/dashboard-server/routes-setup-enc1a.ts +184 -0
  80. package/extensions/dashboard-server/routes-setup.ts +21 -0
  81. package/extensions/dashboard-server/setup-cortex-actions.ts +23 -4
  82. package/extensions/dashboard-server/setup-cortex-blockers.ts +3 -97
  83. package/package.json +1 -1
  84. package/src/config/vector-cortex-enc0g.ts +39 -0
  85. package/src/config/vector-cortex-enc1a.ts +41 -0
  86. package/src/config/vector-cortex.ts +2 -0
  87. package/src/config.ts +2 -0
  88. package/src/vector-cortex/setup-cortex-blockers-compute.ts +216 -0
  89. package/extensions/dashboard-client/dist/assets/SetupTab-C3dnKa8y.js +0 -3
  90. package/extensions/dashboard-client/dist/assets/SetupTab-C3dnKa8y.js.map +0 -1
@@ -36,6 +36,11 @@ import {
36
36
  verifyEncoderAsset,
37
37
  detectPlatform,
38
38
  } from "../../src/vector-cortex/encoder/asset.js";
39
+ import { ENC_0G_ENABLED, ENC_0F_ENABLED } from "../../src/config.js";
40
+ import {
41
+ readQualificationRecord,
42
+ encoderStateDir,
43
+ } from "./qualification-record.js";
39
44
 
40
45
  /** Cap applied to every log tail served by the action-log route. */
41
46
  export const ACTION_LOG_TAIL_BYTES = 8192;
@@ -174,23 +179,37 @@ function runVerifyAsset(stateDir: string): SetupCortexActionResult {
174
179
  };
175
180
  }
176
181
 
182
+ /**
183
+ * The ENC-0g honesty suffix for the verify-asset summary line: when both gates
184
+ * are ON, surface the QualificationV1 record verdict so the action log is honest
185
+ * alongside the (possibly demoted) status card. Returns "" byte-identical when
186
+ * ENC_0G is off. Bounded + redacted (verdict + reasons only).
187
+ */
188
+ function qualificationRecordSuffix(): string {
189
+ if (!ENC_0G_ENABLED() || !ENC_0F_ENABLED()) return "";
190
+ const record = readQualificationRecord(encoderStateDir());
191
+ if (record === null) return " record_verdict=unavailable";
192
+ return ` record_verdict=${record.verdict} record_reasons=${record.reasons.join(",")}`;
193
+ }
194
+
177
195
  /** Compute the redacted verify-asset summary lines (digests + codes only). */
178
196
  function buildVerifySummary(): string {
197
+ const suffix = qualificationRecordSuffix();
179
198
  const dir = encoderAssetDir();
180
199
  if (dir === null) {
181
- return "mode=C verdict=unavailable reason=asset_missing\n";
200
+ return `mode=C verdict=unavailable reason=asset_missing${suffix}\n`;
182
201
  }
183
202
  const manifest = readEncoderManifest(dir);
184
203
  if (manifest === null) {
185
- return "mode=B verdict=demoted reason=ENC_MANIFEST_INVALID\n";
204
+ return `mode=B verdict=demoted reason=ENC_MANIFEST_INVALID${suffix}\n`;
186
205
  }
187
206
  const platform = detectPlatform();
188
207
  const verify = verifyEncoderAsset(dir, manifest, platform);
189
208
  if (verify.ok) {
190
209
  const prefix = verify.onnxDigest.slice(0, 12);
191
- return `mode=A verdict=qualified onnx_digest_prefix=${prefix} embedded_bytes=${verify.embeddedBytes}\n`;
210
+ return `mode=A verdict=qualified onnx_digest_prefix=${prefix} embedded_bytes=${verify.embeddedBytes}${suffix}\n`;
192
211
  }
193
- return `mode=B verdict=demoted reason=${verify.code}\n`;
212
+ return `mode=B verdict=demoted reason=${verify.code}${suffix}\n`;
194
213
  }
195
214
 
196
215
  /** Walk up to the committed encoder-v1 asset dir (mirrors routes-setup-cortex.ts). */
@@ -1,99 +1,5 @@
1
1
  /**
2
- * dashboard-server/setup-cortex-blockers.ts — canonical blocker manifest for the
3
- * dashboard Setup Cortex status read path (VC9A).
4
- *
5
- * The hard-gate items enumerated in docs/vector-cortex/vc2-model-prep.md §6
6
- * (per the 2026-08-05 research update: the opset-14→17 re-export blocker is
7
- * REMOVED because onnx-community exports are now opset 21). This module is the
8
- * SINGLE canonical source of those blockers — the route file
9
- * (routes-setup-cortex.ts) carries NO string literals for them; it reads this
10
- * static manifest so the UI rows and the spec stay in one place.
11
- *
12
- * Reader-only, static: zero network, no writes (PREVENT-PI-004), no `any`
13
- * (PREVENT-011).
2
+ * dashboard-server/setup-cortex-blockers.ts — thin shell re-exporting the
3
+ * canonical Setup Cortex blocker compute from src (single source of truth).
14
4
  */
15
-
16
- /** The open hard-gate items VC9A surfaces (nothing is closed in-workstream). */
17
- export interface SetupCortexBlockerV1 {
18
- /** Stable machine id (e.g. HG-1) the client can key rows on. */
19
- readonly id: string;
20
- /** Human title shown on the blockers card. */
21
- readonly title: string;
22
- /** Severity: blocker | high | medium. */
23
- readonly severity: "blocker" | "high" | "medium";
24
- /** Lifecycle state — all OPEN (hard gates are never silently closed). */
25
- readonly status: "open";
26
- /** Optional candidate resolution surfaced for the controller / user. */
27
- readonly resolution?: string;
28
- }
29
-
30
- /**
31
- * The four blockers VC9A reports. Enumerates the vc2-model-prep §6 items that
32
- * remain per the 2026-08-05 research. The opset re-export blocker (formerly
33
- * §6 #2) is NOT listed: onnx-community exports are opset 21, so it is removed.
34
- */
35
- export const SETUP_CORTEX_BLOCKERS: readonly SetupCortexBlockerV1[] = [
36
- {
37
- id: "HG-1",
38
- title: "Five projection heads do not exist",
39
- severity: "blocker",
40
- status: "open",
41
- resolution:
42
- "Supervision transfer onto a frozen bge-small-en-v1.5 trunk (contradiction distilled from cross-encoder/nli-deberta-v3-small; dependency NLI-assisted; cache-stability deterministic; payload-routing small MLP) — VC2B training + export.",
43
- },
44
- {
45
- id: "HG-3",
46
- title: "onnxruntime-node install exceeds the 80 MiB asset budget",
47
- severity: "blocker",
48
- status: "open",
49
- resolution:
50
- "onnxruntime-node bundles ~258 MiB across all platforms. Candidate: transformers.js v4.2.0 (9.5 MiB shell, pure-Node via onnxruntime-web WASM) measured against budget + p95 gate before committing.",
51
- },
52
- {
53
- id: "HG-4",
54
- title: "No darwin-x64 binary in onnxruntime-node",
55
- severity: "high",
56
- status: "open",
57
- resolution:
58
- "Intel-Mac mode-A users demote to the WASM path (if HG-3 resolves that way) or mode B. " +
59
- "darwin-x64: no native binary upstream (arm64-only); mode-B WASM per HG-4.",
60
- },
61
- {
62
- id: "HG-5",
63
- title: "RSS margin at 512 tokens is ~0.5%",
64
- severity: "medium",
65
- status: "open",
66
- resolution:
67
- "149.2 MiB vs 150 MiB cap with run-to-run variance 119-149 MiB; considers capping mode A at 384 tokens or using the marginal-footprint accounting runtime.ts already implements.",
68
- },
69
- ];
70
-
71
- /** Look up one blocker by id; undefined when unknown (defensive). */
72
- export function setupCortexBlocker(id: string): SetupCortexBlockerV1 | undefined {
73
- return SETUP_CORTEX_BLOCKERS.find((b) => b.id === id);
74
- }
75
-
76
- // ─── VC9B action gating ─────────────────────────────────────────────────────
77
-
78
- /** The VC9B action kinds the drivers know how to run. */
79
- export type SetupCortexActionKind = "fetch-model" | "bench" | "verify-asset";
80
-
81
- /**
82
- * The open hard-gate ids that BLOCK a given action. fetch-model and bench are
83
- * gated by HG-1 (five-head training open) and HG-3 (install budget open) per the
84
- * VC9 workstream plan; verify-asset is a pure re-read of committed assets and is
85
- * NOT gated. When a gated action is requested, the route returns
86
- * action_blocked_by_open_item with these ids and does NOT spawn. The ids are
87
- * always drawn from SETUP_CORTEX_BLOCKERS (each exists — verified by test).
88
- */
89
- export function setupCortexActionBlockers(
90
- action: SetupCortexActionKind,
91
- ): readonly string[] {
92
- switch (action) {
93
- case "fetch-model":
94
- case "bench":
95
- return ["HG-1", "HG-3"];
96
- case "verify-asset":
97
- return [];
98
- }
99
- }
5
+ export * from "../../src/vector-cortex/setup-cortex-blockers-compute.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-mega-compact",
3
- "version": "0.20.48",
3
+ "version": "0.20.50",
4
4
  "description": "Layered, local, vector-backed context compressor for pi — supersede/collapse/cluster compaction with deduped inline recall.",
5
5
  "type": "module",
6
6
  "license": "BSD-3-Clause",
@@ -0,0 +1,39 @@
1
+ /**
2
+ * config/vector-cortex-enc0g.ts — ENC-0g Setup Cortex status route honest state.
3
+ *
4
+ * Extracted from vector-cortex.ts so that file stays under the 300-line soft
5
+ * limit (soft-as-hard gate), exactly as vector-cortex-enc0a.ts .. enc0f.ts and
6
+ * the VC8C/VC9A-D/ML5A-E/DEDUP_ATTR siblings were. vector-cortex.ts re-exports
7
+ * the flag below and root src/config.ts re-exports it, so no consumer import
8
+ * path changes.
9
+ *
10
+ * ENC-0g makes the Setup Cortex status route honest: the status route reads the
11
+ * latest ENC-0f `QualificationV1` record (when ENC_0F is ON and a record
12
+ * exists) and lets its verdict override the structural verifyEncoderAsset
13
+ * result for the `qualification` field; the blocker list becomes a pure
14
+ * computed function over (platform, qualification record, manifest head-count)
15
+ * with corrected HG statuses/wording; and VC9B action gating is re-derived from
16
+ * the live computed blockers instead of the stale static manifest.
17
+ *
18
+ * `MEGACOMPACT_ENC_0G=0` disables: the status route derives its `qualification`
19
+ * verdict from `verifyEncoderAsset(...).ok` alone, the blocker list is the
20
+ * static `SETUP_CORTEX_BLOCKERS` array exactly as ENC-0f-era, and action gating
21
+ * reads the static table as today — byte-identical to the predecessor. The flag
22
+ * MUST also be a dashboard SETTINGS toggle (visible in config UI, never in
23
+ * EXCLUDED_SETTINGS).
24
+ *
25
+ * Pi-agnostic, dependency-free (PREVENT-PI-004 / PREVENT-011).
26
+ */
27
+
28
+ import { sprintFlag } from "./vector-cortex-flag.js";
29
+
30
+ /**
31
+ * ENC-0g — Setup Cortex status route honest state (verdict override + live
32
+ * blockers + re-derived gating). Default ON. `MEGACOMPACT_ENC_0G=0` disables
33
+ * and is byte-identical to the predecessor (ENC-0f): verdict from
34
+ * `verifyEncoderAsset` alone, static `SETUP_CORTEX_BLOCKERS`, static
35
+ * `setupCortexActionBlockers`. This flag MUST also be a dashboard SETTINGS
36
+ * toggle (visible in config UI, never in EXCLUDED_SETTINGS), mirroring
37
+ * ENC_0A/ENC_0B/ENC_0C/ENC_0D/ENC_0E/ENC_0F.
38
+ */
39
+ export const ENC_0G_ENABLED = (): boolean => sprintFlag("MEGACOMPACT_ENC_0G");
@@ -0,0 +1,41 @@
1
+ /**
2
+ * config/vector-cortex-enc1a.ts — ENC-1a external embedder API key + endpoint
3
+ * Settings fields.
4
+ *
5
+ * Extracted from vector-cortex.ts so that file stays under the 300-line soft
6
+ * limit (soft-as-hard gate), exactly as the ENC-0a..ENC-0g siblings were.
7
+ * vector-cortex.ts re-exports the flag below and root src/config.ts re-exports
8
+ * it, so no consumer import path changes.
9
+ *
10
+ * ENC-1a adds a Settings-visible field pair for the external embedder endpoint
11
+ * URL + optional Bearer API key. The runtime already reads
12
+ * `MEGACOMPACT_EMBEDDING_URL` and `MEGACOMPACT_EMBEDDING_KEY` from the process
13
+ * env (src/httpEmbedder.ts:embeddingConfigFromEnv) and the Setup tab's
14
+ * CustomEndpointSection already accepts a custom URL — but there is no
15
+ * dashboard-visible API-key field and no server route persists the pair to the
16
+ * per-repo `.mega-compact.env` so the session survives a restart. ENC-1a adds
17
+ * two additive contract fields on GET /api/setup-status (`embeddingEndpointUrl`
18
+ * echoed + `embeddingApiKeySet` boolean only — the raw key is NEVER returned),
19
+ * an additive writer branch on POST /api/setup-configure accepting
20
+ * `embeddingEndpointUrl` / `embeddingApiKey`, and two additive Setup text rows.
21
+ *
22
+ * `MEGACOMPACT_ENC_1A=0` disables: the Settings panel renders no ENC-1a text
23
+ * fields (only the existing boolDirect toggles remain), the GET body omits the
24
+ * two new fields, and the POST handler does not recognize the new keys —
25
+ * byte-identical to the ENC-0g predecessor. The flag MUST also be a dashboard
26
+ * SETTINGS toggle (visible in config UI, never in EXCLUDED_SETTINGS).
27
+ *
28
+ * Pi-agnostic, dependency-free (PREVENT-PI-004 / PREVENT-011).
29
+ */
30
+
31
+ import { sprintFlag } from "./vector-cortex-flag.js";
32
+
33
+ /**
34
+ * ENC-1a — external embedder API key + endpoint Settings fields. Default ON.
35
+ * `MEGACOMPACT_ENC_1A=0` disables and is byte-identical to the predecessor
36
+ * (ENC-0g): no new GET fields, no writer branch, no new Setup text rows (only
37
+ * the existing boolDirect toggles remain). This flag MUST also be a dashboard
38
+ * SETTINGS toggle (visible in config UI, never in EXCLUDED_SETTINGS), mirroring
39
+ * ENC_0A..ENC_0G.
40
+ */
41
+ export const ENC_1A_ENABLED = (): boolean => sprintFlag("MEGACOMPACT_ENC_1A");
@@ -61,6 +61,8 @@ export { ENC_0C_ENABLED } from "./vector-cortex-enc0c.js";
61
61
  export { ENC_0D_ENABLED } from "./vector-cortex-enc0d.js";
62
62
  export { ENC_0E_ENABLED } from "./vector-cortex-enc0e.js";
63
63
  export { ENC_0F_ENABLED } from "./vector-cortex-enc0f.js";
64
+ export { ENC_0G_ENABLED } from "./vector-cortex-enc0g.js";
65
+ export { ENC_1A_ENABLED } from "./vector-cortex-enc1a.js";
64
66
  // Breaker constants (TRIAD_RESILIENCE.md §breaker) extracted to vector-cortex-breakers.ts.
65
67
  export {
66
68
  BREAKER_WINDOW_MS,
package/src/config.ts CHANGED
@@ -195,6 +195,8 @@ export {
195
195
  ENC_0D_ENABLED,
196
196
  ENC_0E_ENABLED,
197
197
  ENC_0F_ENABLED,
198
+ ENC_0G_ENABLED,
199
+ ENC_1A_ENABLED,
198
200
  BREAKER_WINDOW_MS,
199
201
  BREAKER_MIN_ATTEMPTS,
200
202
  BREAKER_PERF_FAILURES,
@@ -0,0 +1,216 @@
1
+ /**
2
+ * src/vector-cortex/setup-cortex-blockers-compute.ts — canonical blocker
3
+ * manifest + pure computed blocker derivation for the Setup Cortex status
4
+ * read path (VC9A/ENC-0g).
5
+ *
6
+ * The hard-gate items enumerated in docs/vector-cortex/vc2-model-prep.md §6
7
+ * (per the 2026-08-05 research update: the opset-14→17 re-export blocker is
8
+ * REMOVED because onnx-community exports are now opset 21). This module is the
9
+ * SINGLE canonical source of those blockers — the route file
10
+ * (routes-setup-cortex.ts) carries NO string literals for them; it reads this
11
+ * manifest so the UI rows and the spec stay in one place.
12
+ *
13
+ * ENC-0g: `SETUP_CORTEX_BLOCKERS` remains the canonical BASE data (authored
14
+ * all-open, byte-identical to ENC-0f-era for flag-off). `computeSetupCortexBlockers`
15
+ * is a PURE function over (platform, ENC-0f QualificationV1 record, asset-manifest
16
+ * head-count) that returns the live blocker list: HG-1 closes on a five-head
17
+ * manifest (ENC-0c), HG-5 reflects the measured qualification verdict, HG-4
18
+ * notes the ENC-0e visibility close while the binary gap persists, HG-3 stays
19
+ * open (genuinely unresolved). `setupCortexActionBlockers` re-derives VC9B
20
+ * action gating from the live computed blockers (intersects each action's
21
+ * static candidate gate ids with the currently-open blocker ids).
22
+ *
23
+ * Reader-only, pure computation: zero network, no writes (PREVENT-PI-004), no
24
+ * `any` (PREVENT-011). Thresholds come from src/vector-cortex/encoder/types.js
25
+ * (ENCODER_HEAD_ORDER / ENCODER_LATENCY_P95_MS / ENCODER_RSS_BUDGET_BYTES) —
26
+ * never magic numbers in the computed path.
27
+ */
28
+
29
+ import type { QualificationV1 } from "./encoder/qualify.js";
30
+ import {
31
+ ENCODER_HEAD_ORDER,
32
+ ENCODER_LATENCY_P95_MS,
33
+ ENCODER_RSS_BUDGET_BYTES,
34
+ } from "./encoder/types.js";
35
+
36
+ const MIB = 1024 * 1024;
37
+
38
+ /**
39
+ * Marker threshold-failure emitted by the status route when NO QualificationV1
40
+ * record exists on the device (or it is missing / unreadable / corrupt) — the
41
+ * route falls back to the verify-only verdict and includes this marker, never a
42
+ * fabricated pass and never a bare silent fallback. SINGLE source: the status
43
+ * route references this const, never a re-literal (no-scattered-literal scan).
44
+ */
45
+ export const QUALIFICATION_RECORD_UNAVAILABLE = "qualification_record_unavailable";
46
+
47
+ /** Lifecycle of a hard-gate item surfaced on the blockers card. */
48
+ export type SetupCortexBlockerStatusV1 = "open" | "closed" | "superseded";
49
+
50
+ /**
51
+ * A hard-gate item VC9A surfaces. `status` is `"open"` by default (a hard gate
52
+ * is never silently closed); a computed blocker may mark it `"closed"` (a
53
+ * measured/gated close) or `"superseded"` (an open question, but no live
54
+ * measurement exists on this device). The client renders `status` as a row
55
+ * label (no exhaustive switch), so widening is renderer-safe.
56
+ */
57
+ export interface SetupCortexBlockerV1 {
58
+ /** Stable machine id (e.g. HG-1) the client can key rows on. */
59
+ readonly id: string;
60
+ /** Human title shown on the blockers card. */
61
+ readonly title: string;
62
+ /** Severity: blocker | high | medium. */
63
+ readonly severity: "blocker" | "high" | "medium";
64
+ /** Lifecycle state — authored OPEN (ENC-0f-era base), computed from live state. */
65
+ readonly status: SetupCortexBlockerStatusV1;
66
+ /** Optional candidate resolution surfaced for the controller / user. */
67
+ readonly resolution?: string;
68
+ }
69
+
70
+ /**
71
+ * The four blockers VC9A reports. Enumerates the vc2-model-prep §6 items that
72
+ * remain per the 2026-08-05 research. The opset re-export blocker (formerly
73
+ * §6 #2) is NOT listed: onnx-community exports are opset 21, so it is removed.
74
+ * This is the canonical BASE (all `status:"open"`); `computeSetupCortexBlockers`
75
+ * derives the live list from it. Flag-off consumes this array verbatim.
76
+ */
77
+ export const SETUP_CORTEX_BLOCKERS: readonly SetupCortexBlockerV1[] = [
78
+ {
79
+ id: "HG-1",
80
+ title: "Five projection heads do not exist",
81
+ severity: "blocker",
82
+ status: "open",
83
+ resolution:
84
+ "Supervision transfer onto a frozen bge-small-en-v1.5 trunk (contradiction distilled from cross-encoder/nli-deberta-v3-small; dependency NLI-assisted; cache-stability deterministic; payload-routing small MLP) — VC2B training + export.",
85
+ },
86
+ {
87
+ id: "HG-3",
88
+ title: "onnxruntime-node install exceeds the 80 MiB asset budget",
89
+ severity: "blocker",
90
+ status: "open",
91
+ resolution:
92
+ "onnxruntime-node bundles ~258 MiB across all platforms. Candidate: transformers.js v4.2.0 (9.5 MiB shell, pure-Node via onnxruntime-web WASM) measured against budget + p95 gate before committing.",
93
+ },
94
+ {
95
+ id: "HG-4",
96
+ title: "No darwin-x64 binary in onnxruntime-node",
97
+ severity: "high",
98
+ status: "open",
99
+ resolution:
100
+ "Intel-Mac mode-A users demote to the WASM path (if HG-3 resolves that way) or mode B. " +
101
+ "darwin-x64: no native binary upstream (arm64-only); mode-B WASM per HG-4.",
102
+ },
103
+ {
104
+ id: "HG-5",
105
+ title: "RSS margin at 512 tokens is ~0.5%",
106
+ severity: "medium",
107
+ status: "open",
108
+ resolution:
109
+ "149.2 MiB vs 150 MiB cap with run-to-run variance 119-149 MiB; considers capping mode A at 384 tokens or using the marginal-footprint accounting runtime.ts already implements.",
110
+ },
111
+ ];
112
+
113
+ /** Look up one blocker by id; undefined when unknown (defensive). */
114
+ export function setupCortexBlocker(id: string): SetupCortexBlockerV1 | undefined {
115
+ return SETUP_CORTEX_BLOCKERS.find((b) => b.id === id);
116
+ }
117
+
118
+ /**
119
+ * The live blockers computed from (platform, ENC-0f QualificationV1 record,
120
+ * asset-manifest head-count). Pure + deterministic — no IO, no clock, no flag
121
+ * dependence. Rules:
122
+ * - HG-1 → `"closed"` when the asset manifest declares all five projection
123
+ * heads (`headCount === ENCODER_HEAD_ORDER.length`); otherwise stays open.
124
+ * - HG-3 → unchanged (genuinely open — onnxruntime-node budget unresolved).
125
+ * - HG-4 → stays `"open"` (the upstream binary gap is unchanged); resolution
126
+ * notes that ENC-0e ships the darwin demotion visibility surface.
127
+ * - HG-5 → derived from the qualification record: an empty record is
128
+ * `"superseded"` (no measurement on this device); a `failed` verdict closes
129
+ * it with the measured p95/RSS wording; a `qualified` verdict closes it with
130
+ * "measured" wording. Severity stays `"medium"` from the base row.
131
+ * `platform` is carried for contract symmetry with Worker B's route input; the
132
+ * HG rules here do not branch on it (HG-4's darwin note applies regardless).
133
+ */
134
+ export function computeSetupCortexBlockers(input: {
135
+ platform: string | null;
136
+ qualification: QualificationV1 | null;
137
+ headCount: number | null;
138
+ }): readonly SetupCortexBlockerV1[] {
139
+ const { qualification, headCount } = input;
140
+ return SETUP_CORTEX_BLOCKERS.map((base): SetupCortexBlockerV1 => {
141
+ switch (base.id) {
142
+ case "HG-1":
143
+ return headCount === ENCODER_HEAD_ORDER.length
144
+ ? { ...base, status: "closed" }
145
+ : base;
146
+ case "HG-4":
147
+ return {
148
+ ...base,
149
+ resolution: `${base.resolution} ENC-0e shipped the darwin demotion visibility surface.`,
150
+ };
151
+ case "HG-5":
152
+ if (qualification === null) {
153
+ return {
154
+ ...base,
155
+ status: "superseded",
156
+ resolution:
157
+ "No QualificationV1 record on this device — run the gate (scripts/encoder/gate-qualify.mjs) to measure.",
158
+ };
159
+ }
160
+ if (qualification.verdict === "failed") {
161
+ return {
162
+ ...base,
163
+ title: "Real-asset qualification: failed (latency + marginal-RSS over budget)",
164
+ status: "closed",
165
+ resolution:
166
+ `p95 ${qualification.p95Ms} ms vs ${ENCODER_LATENCY_P95_MS} ms gate, marginal RSS ${qualification.rssMib} MiB vs ${ENCODER_RSS_BUDGET_BYTES / MIB} MiB cap — mode A requires the native onnxruntime-node selection`,
167
+ };
168
+ }
169
+ return {
170
+ ...base,
171
+ title: "Real-asset qualification: measured",
172
+ status: "closed",
173
+ };
174
+ default:
175
+ return base;
176
+ }
177
+ });
178
+ }
179
+
180
+ // ─── VC9B action gating ─────────────────────────────────────────────────────
181
+
182
+ /** The VC9B action kinds the drivers know how to run. */
183
+ export type SetupCortexActionKind = "fetch-model" | "bench" | "verify-asset";
184
+
185
+ /**
186
+ * The static PER-ACTION CANDIDATE gate ids — this is POLICY, NOT the derived
187
+ * gating. fetch-model and bench ARE candidates for HG-1 (five-head training)
188
+ * and HG-3 (install budget); verify-asset is a pure re-read of committed assets
189
+ * and is NEVER gated (empty candidate list). The derived gating (below)
190
+ * intersects these candidates with the currently-OPEN blockers from the live
191
+ * computed list, so a candidate only blocks when its blocker is actually open.
192
+ */
193
+ const ACTION_GATE_CANDIDATES: Readonly<Record<SetupCortexActionKind, readonly string[]>> = {
194
+ "fetch-model": ["HG-1", "HG-3"],
195
+ bench: ["HG-1", "HG-3"],
196
+ "verify-asset": [],
197
+ };
198
+
199
+ /**
200
+ * Re-derived VC9B action gating from the LIVE computed blockers. An action is
201
+ * gated by exactly the candidate ids that are `status:"open"` AND
202
+ * `severity:"blocker"` in the supplied blockers. `blockers` defaults to the
203
+ * base `SETUP_CORTEX_BLOCKERS` (authored all-open) for backward compatibility
204
+ * with single-arg callers — with HG-1 closed by a computed list, fetch-model
205
+ * and bench surface `["HG-3"]`; verify-asset always `[]`.
206
+ */
207
+ export function setupCortexActionBlockers(
208
+ action: SetupCortexActionKind,
209
+ blockers?: readonly SetupCortexBlockerV1[],
210
+ ): readonly string[] {
211
+ const live = blockers ?? SETUP_CORTEX_BLOCKERS;
212
+ const openBlockerIds = new Set(
213
+ live.filter((b) => b.status === "open" && b.severity === "blocker").map((b) => b.id),
214
+ );
215
+ return ACTION_GATE_CANDIDATES[action].filter((id) => openBlockerIds.has(id));
216
+ }
@@ -1,3 +0,0 @@
1
- import{r as n,j as e,h as A,i as F,k as G,p as K,l as Q,m as J,C as Y,n as Z,o as ee,q as te,s as se,t as ne,v as re}from"./index-DuThOA-d.js";import{S as ae}from"./switch-7qLS7ajc.js";import{f as le,p as oe,d as ie}from"./client-extra-BvGxKZpm.js";import{V as ce}from"./VcStatusBadge-BtmSNH8X.js";import{T as de}from"./toggle-D7mgOVxz.js";function me(t){try{return new Date(t*1e3).toLocaleString()}catch{return"—"}}function H({achievements:t}){const a=n.useRef(0),[s,l]=n.useState(null),r=t.reduce((o,d)=>Math.max(o,d.unlocked_at??0),0),i=a.current;n.useEffect(()=>{r>a.current&&(a.current=r)},[r]),n.useEffect(()=>{if(i>0&&r>i){const o=t.filter(d=>d.unlocked_at!=null&&(d.unlocked_at??0)>i);if(o.length>0){const d=o.map(m=>`${m.icon??""} ${m.title}`.trim()).join(", ")+" unlocked!";l(d);const g=setTimeout(()=>l(null),4e3);return()=>clearTimeout(g)}}},[t,r,i]);const f=t.filter(o=>!(o.hidden===1&&o.unlocked_at==null));return e.jsxs("div",{className:"ach-section",children:[s!=null&&e.jsx("div",{className:"ach-toast show",children:s}),e.jsxs("div",{className:"ach-tiles",children:[f.length===0&&e.jsx("span",{className:"repo-none",children:"no achievements yet"}),f.map(o=>{if(o.unlocked_at!=null){const d=i>0&&(o.unlocked_at??0)>i;return e.jsxs("div",{className:`ach-tile unlocked${d?" just-unlocked":""}`,children:[o.icon??""," ",o.title,e.jsxs("span",{className:"ach-detail",children:["unlocked ",me(o.unlocked_at)]})]},o.id)}return e.jsxs("div",{className:"ach-tile locked",children:["??? ",o.title]},o.id)})]})]})}function I(t){return(Math.round(t*10)/10).toString()+"%"}function O(t){return t!=null?new Date(t).toLocaleString():"—"}function D(t){return t&&typeof t=="object"?t:{}}function ue(t){return t.split("/").pop()||t}function P({title:t,rows:a,badge:s,renderValue:l}){return e.jsxs("div",{className:"lb-card",children:[e.jsxs("h3",{children:[t,s]}),a.length===0?e.jsx("div",{className:"lb-empty",children:"—"}):e.jsx("table",{children:e.jsx("tbody",{children:a.map((r,i)=>e.jsxs("tr",{children:[e.jsx("td",{title:r.repo_root,children:ue(r.repo_root)}),e.jsx("td",{className:"num",children:l(r)})]},`${r.repo_root}-${i}`))})})]})}function he(){const[t,a]=n.useState({}),[s,l]=n.useState(0),[r,i]=n.useState([]),[f,o]=n.useState(!1),[d,g]=n.useState(!0),[m,x]=n.useState(null),c=n.useRef(0),u=n.useCallback(async()=>{try{const[y,w,p,k,T,X]=await Promise.all([A({metric:"cache",limit:25}),A({metric:"dedupe",limit:25}),A({metric:"turns",limit:25}),A({metric:"mega_cache",limit:25}),A({metric:"repos",limit:1}),F()]),W=k.find(B=>B.ts>c.current&&B.value>100);c.current>0&&W&&(x(`oopsie! cache went to ${Math.round(W.value)}% — MEGA CACHE 🥧`),setTimeout(()=>x(null),4e3)),k.length>0&&(c.current=Math.max(...k.map(B=>B.ts))),a({cache:y,dedupe:w,turns:p,mega_cache:k}),l(T[0]?.value??0),i(X)}catch{}finally{g(!1)}},[]);n.useEffect(()=>{let y=!0;const w=async()=>{y&&await u()};w();const p=setInterval(()=>void w(),15e3);return()=>{y=!1,clearInterval(p)}},[u]),n.useEffect(()=>{let y=!0;const w=async()=>{try{const k=await G();y&&(o(!!k.game_mode_on),k.theme&&(document.documentElement.dataset.theme=k.theme))}catch{}};w();const p=setInterval(()=>void w(),15e3);return()=>{y=!1,clearInterval(p)}},[]);const j=t.mega_cache??[];let v=null,N=null;for(const y of j){(v==null||y.value>v)&&(v=y.value);const w=D(y.meta),p=w.firstSeenTs??w.firstSeen??y.ts;(N==null||p<N)&&(N=p)}const C=v!=null&&v>100,S=t.turns??[],M=S.reduce((y,w)=>Math.max(y,w.value),0),L=Math.floor(Math.log2(M+1))+1,z=(t.cache?.length??0)>0||(t.dedupe?.length??0)>0||S.length>0||j.length>0||s>0;return e.jsxs("div",{className:`game-tab${f?" game-mode-on":""}`,children:[m!=null&&e.jsx("div",{className:"mega-cache-toast show",children:m}),C&&e.jsxs("div",{className:"mega-cache-banner",children:["🥧"," MEGA CACHE! peak ",I(v)," — first reached ",O(N)]}),C&&e.jsxs("div",{className:"achievement-tile unlocked",children:["🏆"," Opie's Wild Ride",e.jsxs("span",{className:"ach-detail",children:["best ",I(v)," · first ",O(N)]})]}),e.jsx("h2",{children:"High Scores"}),!z&&!d&&e.jsx("div",{className:"game-empty",children:"No scores yet — run a session with game mode on."}),z&&e.jsxs("div",{className:"game-leaderboards",children:[e.jsx(P,{title:"Cache %",rows:t.cache??[],renderValue:y=>I(y.value)}),e.jsx(P,{title:"Dedupe (collapsed)",rows:t.dedupe??[],renderValue:y=>y.value.toLocaleString()}),e.jsx(P,{title:"Turns",rows:S,badge:S.length>0?e.jsxs("span",{className:"lvl-badge",children:["LVL ",L]}):void 0,renderValue:y=>y.value.toLocaleString()}),e.jsx(P,{title:"MEGA CACHE trophies",rows:j,renderValue:y=>e.jsxs(e.Fragment,{children:[I(y.value),e.jsx("span",{className:"lb-meta",children:O(D(y.meta).firstSeenTs??D(y.meta).firstSeen??y.ts)})]})})]}),s>0&&e.jsx("div",{className:"repos-badge-line",children:e.jsxs("span",{className:"repos-badge",children:[s," repos"]})}),e.jsx("h3",{children:"Achievements"}),e.jsx(H,{achievements:r})]})}function fe(){const[t,a]=n.useState([]),[s,l]=n.useState(!0),[r,i]=n.useState(null),f=n.useCallback(async()=>{try{const o=await F();a(o),i(null)}catch(o){i(o instanceof Error?o:new Error(String(o)))}finally{l(!1)}},[]);return n.useEffect(()=>{let o=!0;const d=async()=>{o&&await f()};d();const g=setInterval(()=>void d(),15e3);return()=>{o=!1,clearInterval(g)}},[f]),s&&t.length===0?e.jsx("div",{className:"tab-stub",children:"Loading achievements…"}):r&&t.length===0?e.jsxs("div",{className:"tab-stub",children:["Error: ",r.message]}):e.jsxs("div",{className:"achievements-tab",children:[e.jsx("h2",{children:"Achievements"}),e.jsx(H,{achievements:t})]})}const q=[{id:"transparent",label:"Transparent (accents only)",css:{bg:null,fg:"#c9d1d9",accent:"#3fb950",mega:"#f0883e"},ansi:{bg:null,fg:"39",accent:"32",mega:"33"}},{id:"retro",label:"Retro 8-bit green",css:{bg:"#003300",fg:"#33ff33",accent:"#00ff41",mega:"#39ff14"},ansi:{bg:"40",fg:"92",accent:"92",mega:"1;92"}},{id:"orange-bold",label:"Orange bold",css:{bg:"#1a0f00",fg:"#ff8c00",accent:"#ff6b00",mega:"#ff4500"},ansi:{bg:"48;5;52",fg:"38;5;208",accent:"38;5;208",mega:"1;38;5;202"}},{id:"cyan-neon",label:"Cyan neon",css:{bg:"#001a1a",fg:"#00ffff",accent:"#22d3ee",mega:"#7df9ff"},ansi:{bg:"48;5;23",fg:"38;5;51",accent:"38;5;51",mega:"1;38;5;51"}},{id:"amber-mono",label:"Amber phosphor",css:{bg:"#1a1200",fg:"#ffb000",accent:"#ff8c00",mega:"#ff5500"},ansi:{bg:"48;5;58",fg:"38;5;214",accent:"38;5;214",mega:"1;38;5;208"}},{id:"grayscale",label:"Grayscale minimal",css:{bg:"#161616",fg:"#b0b0b0",accent:"#8b949e",mega:"#e6edf3"},ansi:{bg:"48;5;235",fg:"38;5;249",accent:"38;5;249",mega:"1;38;5;255"}}],$=q.map(t=>t.id),E={gameMode:"Turn game mode on/off (themes the widget + dashboard)",theme:"Visual theme (applies instantly)",tuiMode:"TUI widget display density",tier:"Live pressure band — climbs low→mega as context fills the window.",preset:"The env-resolved base compaction preset (low/medium/high/ultra/mega) that set the token threshold.",pressure:"Live pressure = currentTokens / threshold — % of the model context window (threshold fires at the tier's % of window).",threshold:"Compaction threshold = tierPct × model context window — mega-compact trims BELOW pi's native ~80% auto-compact for any model size.",fastGate:"Fast-gate arming floor — the live trim arms once context passes this % of the window."};function ge(t,a,s){let l=t.toLocaleString();return a!=null&&s>0&&(l+=` (${Math.round(a*100)}% of ${s.toLocaleString()})`),l}function xe(t){return`${Math.round((t||0)*100)}%`}function pe(){const[t,a]=n.useState(null),[s,l]=n.useState(null),[r,i]=n.useState(!1);n.useEffect(()=>{let c=!0;const u=async()=>{try{const v=await Q();c&&a(v)}catch{}};u();const j=setInterval(()=>void u(),5e3);return()=>{c=!1,clearInterval(j)}},[]),n.useEffect(()=>{let c=!0;const u=async()=>{try{const v=await G();c&&(l(v),v.theme&&(document.documentElement.dataset.theme=v.theme))}catch{}};u();const j=setInterval(()=>void u(),5e3);return()=>{c=!1,clearInterval(j)}},[]);const f=n.useCallback(async c=>{i(!0);try{const u=await K(c);l(u),u.theme&&(document.documentElement.dataset.theme=u.theme)}catch{}i(!1)},[]),o=s?.game_mode_on??!1,d=s?.theme??"transparent",g=s?.tui_display_mode??"full",m=t?.config,x=t?.context.contextWindow??0;return e.jsxs("div",{className:"config-tab",children:[e.jsxs("section",{className:"config-settings",children:[e.jsx("h3",{children:"Settings"}),e.jsx("div",{className:"settings-row",children:e.jsxs("label",{title:E.gameMode,children:[e.jsx("input",{type:"checkbox",checked:o,onChange:c=>f({game_mode_on:c.currentTarget.checked}),disabled:r}),"Game Mode"]})}),e.jsx("div",{className:"settings-row",children:e.jsxs("label",{title:E.theme,children:["Theme",e.jsx("select",{value:d,onChange:c=>f({theme:c.currentTarget.value}),disabled:r,children:q.map(c=>e.jsx("option",{value:c.id,children:c.label},c.id))}),e.jsx("button",{type:"button",disabled:r,className:"theme-cycle-btn",title:"Cycle to the next theme (P3)",onClick:()=>{const c=$.indexOf(d),u=$[(c<0?0:c+1)%$.length];u&&f({theme:u})},children:"Next theme →"})]})}),e.jsx("div",{className:"settings-row",children:e.jsxs("label",{title:E.tuiMode,children:["TUI Mode",e.jsxs("select",{value:g,onChange:c=>f({tui_display_mode:c.currentTarget.value}),disabled:r,children:[e.jsx("option",{value:"full",children:"Full"}),e.jsx("option",{value:"minimal",children:"Minimal"})]})," ",e.jsx("span",{className:"tui-mode-hint",children:"(affects the in-app TUI widget; not shown here)"})]})})]}),e.jsxs("section",{className:"config-display",children:[e.jsx("h3",{children:"Configuration"}),e.jsxs("div",{className:"config-grid",children:[e.jsxs("div",{className:"config-item",children:[e.jsx("span",{className:"config-label",title:E.tier,children:"Tier"}),e.jsx("span",{className:"config-value",children:t?`${t.tier} (live)`:"—"})]}),e.jsxs("div",{className:"config-item",children:[e.jsx("span",{className:"config-label",title:E.preset,children:"Preset"}),e.jsx("span",{className:"config-value",children:t?.presetTier??"—"})]}),e.jsxs("div",{className:"config-item",children:[e.jsx("span",{className:"config-label",title:E.pressure,children:"Pressure"}),e.jsx("span",{className:"config-value",children:t?xe(t.pressure):"—"})]}),e.jsxs("div",{className:"config-item",children:[e.jsx("span",{className:"config-label",title:E.threshold,children:"Threshold"}),e.jsx("span",{className:"config-value",children:m?ge(m.thresholdTokens,m.tierPct,x):"—"})]}),e.jsxs("div",{className:"config-item",children:[e.jsx("span",{className:"config-label",title:E.fastGate,children:"Fast Gate"}),e.jsx("span",{className:"config-value",children:m?`${m.fastGatePct}%`:"—"})]}),e.jsxs("div",{className:"config-item",children:[e.jsx("span",{className:"config-label",children:"Auto"}),e.jsx("span",{className:"config-value",children:m?m.auto?"enabled":"disabled":"—"})]}),e.jsxs("div",{className:"config-item",children:[e.jsx("span",{className:"config-label",children:"Anchor"}),e.jsx("span",{className:"config-value",children:m?.anchorUserMessages??"—"})]})]})]})]})}const R={section:{background:"#1a1a2e",borderRadius:"8px",padding:"1rem",marginBottom:"1rem",border:"1px solid #2a2a4e"},sectionTitle:{fontSize:"1.1rem",fontWeight:700,marginTop:0,marginBottom:"0.75rem",color:"#e0e0e0",borderBottom:"1px solid #333",paddingBottom:"0.5rem"},label:{fontWeight:600,color:"#a0a0c0",marginRight:"0.5rem"},value:{color:"#e0e0e0"},row:{marginBottom:"0.4rem",fontSize:"0.9rem"}};function be(){const[t,a]=n.useState(null),[s,l]=n.useState(null),r=n.useCallback(()=>{J().then(a).catch(g=>l(g instanceof Error?g.message:String(g)))},[]);n.useEffect(()=>{r()},[r]),n.useEffect(()=>{const g=setInterval(r,3e4);return()=>clearInterval(g)},[r]);const i=t?.status==="ok",f=t?.status==="ok"?"Working":t?.status==="unreachable"?"Unreachable":"Error",o=i?"#4caf50":"#f44336",d=i?"✓":"✗";return e.jsxs("div",{style:R.section,children:[e.jsx("h3",{style:R.sectionTitle,children:"Embedder Health"}),s&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:["Error: ",s]}),!t&&!s&&e.jsx("p",{style:{color:"#888",fontSize:"0.85rem"},children:"Probing embedder..."}),t&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:R.row,children:[e.jsxs("span",{style:{...R.label,color:`${o}`},children:[d," ",f,":"]}),e.jsxs("span",{style:R.value,children:[t.dim," dims"]}),t.latencyMs!==void 0&&e.jsxs("span",{style:{color:"#a0a0c0",marginLeft:"0.5rem"},children:["(",t.latencyMs.toFixed(1)," ms)"]})]}),e.jsxs("div",{style:R.row,children:[e.jsx("span",{style:R.label,children:"Endpoint:"}),e.jsx("span",{style:R.value,children:t.url??e.jsx("span",{style:{color:"#888"},children:"built-in (no URL)"})})]}),t.error&&e.jsx("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:t.error})]})]})}function je({title:t,children:a}){const[s,l]=n.useState(!0),r=`settings-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`;return e.jsxs("section",{className:"overflow-hidden rounded-xl border border-border bg-bg-elevated/40",children:[e.jsxs("button",{type:"button",onClick:()=>l(i=>!i),className:"flex w-full items-center justify-between rounded-t-xl bg-bg-elevated/60 px-4 py-3 text-left text-sm font-semibold text-foreground transition-colors hover:bg-bg-elevated","aria-expanded":s,"aria-controls":r,children:[e.jsx("span",{children:t}),e.jsx(Y,{className:Z("h-4 w-4 text-muted-foreground transition-transform",s&&"rotate-180"),"aria-hidden":"true"})]}),s&&e.jsx("div",{id:r,className:"divide-y divide-border px-4 py-1",children:a})]})}const ye="rounded-md border border-border bg-bg-elevated/50 px-2 py-1 text-sm outline-none transition-colors focus:border-primary disabled:cursor-not-allowed disabled:opacity-50";function ve(){return e.jsx("span",{className:"ml-2 inline-flex items-center rounded-md border border-warning/40 bg-warning/15 px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-warning",title:"Requires an LLM embedder (Ollama/HTTP) to be effective",children:"LLM"})}function Se({setting:t,id:a,llmActive:s,saving:l,onUpdate:r}){const[i,f]=n.useState(null),o=t.requiresLlm&&!s,d=n.useRef(null);n.useEffect(()=>()=>{d.current&&clearTimeout(d.current)},[]);const g=n.useCallback(c=>{r(t.key,c).then(u=>f(u)).catch(u=>f(u instanceof Error?u.message:String(u)))},[r,t.key]),m=n.useCallback(c=>{d.current&&clearTimeout(d.current),d.current=setTimeout(()=>g(c),500)},[g]),x=l||o;return e.jsxs("div",{className:"py-2.5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center text-sm font-semibold text-foreground",children:[e.jsx("label",{htmlFor:`${a}-input`,className:"cursor-pointer",children:t.label}),t.requiresLlm&&!s&&e.jsx(ve,{})]}),e.jsx("div",{className:"mt-0.5 text-xs text-muted-foreground",children:t.description})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-2",children:t.type==="boolean"?e.jsx(ae,{id:`${a}-input`,checked:!!t.value,disabled:x||o,onCheckedChange:c=>g(String(c)),"aria-label":t.label}):e.jsxs(e.Fragment,{children:[e.jsx("input",{id:`${a}-input`,type:t.type==="number"?"number":"text",defaultValue:String(t.value??""),min:t.min,max:t.max,disabled:x,onChange:c=>m(c.target.value),className:`${ye} ${t.type==="number"?"w-24":"w-56"}`}),t.unit&&e.jsx("span",{className:"text-xs text-muted-foreground",children:t.unit})]})})]}),i&&e.jsxs("p",{className:"mt-1 text-xs text-danger",children:["Error: ",i]})]})}function we(){const[t,a]=n.useState(null),[s,l]=n.useState(null),[r,i]=n.useState(!1),[f,o]=n.useState(null),d=n.useCallback(()=>{ee().then(a).catch(m=>l(m instanceof Error?m.message:String(m)))},[]);n.useEffect(()=>{d()},[d]);const g=n.useCallback(async(m,x)=>{i(!0);try{const c=await te({key:m,value:x});return o(c.restartRequired?"Saved — restart pi to apply changes.":"Saved."),d(),null}catch(c){return c instanceof Error?c.message:String(c)}finally{i(!1)}},[d]);return e.jsxs("div",{className:"flex flex-col gap-3",children:[s&&e.jsxs("p",{className:"text-sm text-danger",children:["Error: ",s]}),!t&&!s&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading settings..."}),t?.categories.map(m=>e.jsx(je,{title:m.name,children:m.settings.map(x=>e.jsx(Se,{setting:x,id:`${m.name.replace(/[^a-z0-9]+/gi,"-")}-${x.key}`,llmActive:t.llmActive,saving:r,onUpdate:g},x.key))},m.name)),f&&e.jsx("div",{className:"mt-1 rounded-md border border-warning/40 bg-warning/10 p-2 text-xs text-warning",role:"status",children:f})]})}const h={container:{padding:"1rem",maxWidth:"720px",margin:"0 auto",fontFamily:"system-ui, sans-serif",color:"#e0e0e0"},section:{background:"#1a1a2e",borderRadius:"8px",padding:"1rem",marginBottom:"1rem",border:"1px solid #2a2a4e"},sectionTitle:{fontSize:"1.1rem",fontWeight:700,marginTop:0,marginBottom:"0.75rem",color:"#e0e0e0",borderBottom:"1px solid #333",paddingBottom:"0.5rem"},label:{fontWeight:600,color:"#a0a0c0",marginRight:"0.5rem"},value:{color:"#e0e0e0"},row:{marginBottom:"0.4rem",fontSize:"0.9rem"},warning:{background:"#3a2a00",border:"1px solid #665500",borderRadius:"8px",padding:"0.75rem",marginTop:"0.5rem",color:"#ffcc00",fontSize:"0.85rem"},badge:{display:"inline-block",padding:"0.15rem 0.5rem",borderRadius:"4px",fontSize:"0.8rem",fontWeight:600,marginLeft:"0.5rem"},detectRow:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.5rem 0",borderBottom:"1px solid #2a2a4e"},button:{background:"#3a5a9f",color:"#fff",border:"none",borderRadius:"6px",padding:"0.5rem 1rem",cursor:"pointer",fontSize:"0.9rem",fontWeight:600}};function Ne({customUrl:t,setCustomUrl:a,applyEmbedder:s,configuring:l}){return e.jsxs("div",{style:h.section,children:[e.jsx("h3",{style:h.sectionTitle,children:"Custom Endpoint (remote / third-party)"}),e.jsxs("p",{style:{fontSize:"0.85rem",color:"#a0a0c0",marginTop:0},children:["Point at any OpenAI-compatible embeddings API or hosted endpoint. This opts in to a non-loopback connection (sets"," ",e.jsx("code",{children:"MEGACOMPACT_ALLOW_REMOTE_EMBEDDER=1"}),") — your prompts' embedding requests will be sent to the URL you enter. Default is loopback-only."]}),e.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap",alignItems:"center"},children:[e.jsx("input",{type:"url",placeholder:"https://api.example.com/v1/embeddings",value:t,onChange:r=>a(r.target.value),style:{flex:"1 1 300px",background:"#12122a",color:"#e0e0e0",border:"1px solid #2a2a4e",borderRadius:"6px",padding:"0.4rem 0.6rem",fontSize:"0.85rem",fontFamily:"monospace"}}),e.jsx("button",{style:{...h.button,opacity:t?1:.4},onClick:()=>s("custom",t),disabled:!t||l!==null,children:l==="custom"?"Writing...":"Use Custom URL"})]}),e.jsxs("div",{style:h.warning,children:[e.jsx("strong",{children:"Heads up:"})," a remote endpoint receives the text you embed (it does NOT receive your full conversation — only the strings passed to",e.jsx("code",{children:" embed()"})," for recall/dedup). Verify the endpoint's privacy policy before use."]})]})}function ke(){const[t,a]=n.useState(null),[s,l]=n.useState(null),[r,i]=n.useState(null),[f,o]=n.useState(null),[d,g]=n.useState(!1),[m,x]=n.useState(null),[c,u]=n.useState(null),[j,v]=n.useState(null),[N,C]=n.useState(""),S=n.useCallback(()=>{se().then(a).catch(p=>i(p instanceof Error?p.message:String(p)))},[]),M=n.useCallback((p,k)=>{x(p),v(null),u(null),ne({embedder:p,url:k}).then(T=>{u(T),x(null),S()}).catch(T=>{v(T instanceof Error?T.message:String(T)),x(null)})},[S]),L=n.useCallback(()=>{g(!0),o(null),re().then(p=>{l(p),g(!1)}).catch(p=>{o(p instanceof Error?p.message:String(p)),g(!1)})},[]);n.useEffect(()=>{S()},[S]),n.useEffect(()=>{const p=setInterval(S,5e3);return()=>clearInterval(p)},[S]),n.useEffect(()=>{L();const p=setInterval(L,5e3);return()=>clearInterval(p)},[L]);const z=p=>{switch(p){case"trigram":return"TrigramEmbedder (heuristic, default)";case"http":return"HTTP Embedder (BYO localhost)";case"minilm":return"MiniLM (experimental)";default:return"Unknown"}},y=t?.currentEmbedder==="trigram"&&e.jsxs("div",{style:h.warning,children:[e.jsx("strong",{children:"Note:"})," TrigramEmbedder is a heuristic-strength default embedder. It works without any setup but recall quality may be lower than a dedicated embedding backend. If you notice poor recall results, consider installing Ollama and running the"," ",e.jsx("code",{children:"/megasetup"})," command, or set"," ",e.jsx("code",{children:"MEGACOMPACT_EMBEDDING_URL"})," to point at your own localhost embedding server."]}),w=p=>{const k=p?"#1a5a1a":"#3a1a1a",T=p?"#4caf50":"#f44336";return e.jsx("span",{style:{...h.badge,background:k,color:T},children:p?"Detected":"Not found"})};return e.jsxs("div",{style:h.container,children:[e.jsx("h2",{style:{fontSize:"1.3rem",marginTop:0,marginBottom:"1rem"},children:"Embedder Setup"}),e.jsx(be,{}),e.jsxs("div",{style:h.section,children:[e.jsx("h3",{style:h.sectionTitle,children:"Current Embedder Configuration"}),r&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:["Error: ",r]}),t&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:h.row,children:[e.jsx("span",{style:h.label,children:"Active Embedder:"}),e.jsx("span",{style:h.value,children:z(t.currentEmbedder)})]}),"configuredEmbedder"in t&&t.configuredEmbedder!==t.currentEmbedder&&e.jsxs("div",{style:h.warning,children:[e.jsx("strong",{children:"Configured but not active:"})," ",z(t.configuredEmbedder)," is configured in .mega-compact.env but not yet loaded."," ",e.jsx("strong",{children:"Restart pi"})," to activate it.",t.configuredUrl&&e.jsxs(e.Fragment,{children:[" (",t.configuredUrl,")"]})]}),"restartRequired"in t&&t.restartRequired&&e.jsxs("div",{style:{...h.row,color:"#ff9800"},children:[e.jsx("span",{style:h.label,children:"Status:"}),e.jsx("span",{style:h.value,children:"Restart required to activate the configured embedder"})]}),e.jsxs("div",{style:h.row,children:[e.jsx("span",{style:h.label,children:"Embedding URL:"}),e.jsx("span",{style:h.value,children:t.embeddingUrl??e.jsx("span",{style:{color:"#888"},children:"not set"})})]}),e.jsxs("div",{style:h.row,children:[e.jsx("span",{style:h.label,children:"Embed Cache:"}),e.jsx("span",{style:h.value,children:t.embedCache??e.jsx("span",{style:{color:"#888"},children:"not set"})})]}),e.jsxs("div",{style:h.row,children:[e.jsx("span",{style:h.label,children:"MiniLM:"}),e.jsx("span",{style:h.value,children:t.minilm?"enabled":"disabled"})]}),y]}),!t&&!r&&e.jsx("p",{style:{color:"#888",fontSize:"0.85rem"},children:"Loading configuration..."})]}),e.jsxs("div",{style:h.section,children:[e.jsx("h3",{style:h.sectionTitle,children:"Local Embedder Detection"}),e.jsx("p",{style:{fontSize:"0.85rem",color:"#a0a0c0",marginTop:0},children:"Detect which local embedding backends are available on this machine. No software is installed — detection only."}),s&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:h.detectRow,children:[e.jsx("span",{children:e.jsx("strong",{children:"Ollama"})}),s.ollama!==null?e.jsxs("span",{children:[w(s.ollama.installed),s.ollama.installed&&e.jsx("span",{style:{fontSize:"0.8rem",color:"#a0a0c0",marginLeft:"0.5rem"},children:s.ollama.running?`server running, ${s.ollama.models.length} model(s)`:"server not running"})]}):e.jsx("span",{style:{color:"#888",fontSize:"0.85rem"},children:"not checked"})]}),e.jsxs("div",{style:h.detectRow,children:[e.jsx("span",{children:e.jsx("strong",{children:"llama.cpp"})}),s.llamaCpp!==null?e.jsxs("span",{children:[w(s.llamaCpp.installed),s.llamaCpp.installed&&s.llamaCpp.detail&&e.jsx("span",{style:{fontSize:"0.8rem",color:"#a0a0c0",marginLeft:"0.5rem"},children:s.llamaCpp.detail})]}):e.jsx("span",{style:{color:"#888",fontSize:"0.85rem"},children:"not checked"})]}),e.jsxs("div",{style:h.detectRow,children:[e.jsx("span",{children:e.jsx("strong",{children:"ONNX Runtime"})}),s.onnx!==null?e.jsxs("span",{children:[w(s.onnx.installed),s.onnx.installed&&s.onnx.detail&&e.jsx("span",{style:{fontSize:"0.8rem",color:"#a0a0c0",marginLeft:"0.5rem"},children:s.onnx.detail})]}):e.jsx("span",{style:{color:"#888",fontSize:"0.85rem"},children:"not checked"})]}),s.error&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.8rem",marginTop:"0.5rem"},children:["Detection error: ",s.error]})]}),f&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:["Error: ",f]}),e.jsxs("div",{style:{marginTop:"1rem"},children:[e.jsx("button",{style:h.button,onClick:L,disabled:d,children:d?"Detecting...":"Run Detection"}),e.jsxs("span",{style:{fontSize:"0.8rem",color:"#888",marginLeft:"0.75rem"},children:["Or run ",e.jsx("code",{children:"/megasetup"})," in the chat for an interactive wizard."]})]}),s&&e.jsxs("div",{style:{marginTop:"1rem",paddingTop:"0.75rem",borderTop:"1px solid #2a2a4e"},children:[e.jsx("div",{style:{fontSize:"0.9rem",fontWeight:600,marginBottom:"0.5rem"},children:"Configure"}),e.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap"},children:[e.jsx("button",{style:{...h.button,opacity:s.ollama?.installed?1:.4},onClick:()=>M("ollama"),disabled:!s.ollama?.installed||m!==null,children:m==="ollama"?"Writing...":"Use Ollama"}),e.jsx("button",{style:{...h.button,opacity:s.llamaCpp?.installed?1:.4},onClick:()=>M("llama"),disabled:!s.llamaCpp?.installed||m!==null,children:m==="llama"?"Writing...":"Use llama.cpp"}),e.jsx("button",{style:{...h.button,opacity:s.onnx?.installed?1:.4},onClick:()=>M("onnx"),disabled:!s.onnx?.installed||m!==null,children:m==="onnx"?"Writing...":"Use ONNX"}),e.jsx("button",{style:{...h.button,background:"#444"},onClick:()=>M("trigram"),disabled:m!==null,children:m==="trigram"?"Writing...":"Use Trigram (default)"})]}),c&&e.jsx("div",{style:h.warning,children:c.alreadyActive?"Already active — no restart needed.":`Configured ${c.embedder}. Restart pi to activate (config written to ${c.envPath}).`}),j&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem",marginTop:"0.5rem"},children:["Configure error: ",j]})]})]}),e.jsx(Ne,{customUrl:N,setCustomUrl:C,applyEmbedder:M,configuring:m}),e.jsxs("div",{style:h.section,children:[e.jsx("h3",{style:h.sectionTitle,children:"How to Upgrade"}),e.jsxs("ul",{style:{fontSize:"0.85rem",lineHeight:1.6,paddingLeft:"1.25rem"},children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Ollama:"})," Install from"," ",e.jsx("a",{href:"https://ollama.com",style:{color:"#6a9fff"},target:"_blank",rel:"noopener noreferrer",children:"ollama.com"}),", then ",e.jsx("code",{children:"ollama pull nomic-embed-text"})," and restart pi. Set ",e.jsx("code",{children:"MEGACOMPACT_EMBEDDING_URL=http://localhost:11434/api/embeddings"}),"."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"llama.cpp:"})," Build or install llama.cpp, run"," ",e.jsx("code",{children:"llama-server"})," with an embedding model, and set the URL accordingly."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"ONNX Runtime:"})," Run a local text-embeddings server (e.g. TEI) and click ",e.jsx("strong",{children:"Use ONNX"})," above. Default URL: ",e.jsx("code",{children:"http://localhost:8081/v1/embeddings"}),"."]})]})]}),e.jsxs("div",{style:h.section,children:[e.jsx("h3",{style:h.sectionTitle,children:"Settings"}),e.jsx(we,{})]})]})}function _(t){return t>=1e6?`${(t/1e6).toFixed(2)}M`:t>=1e3?`${Math.round(t/1e3)}K`:String(t)}function Ce(t,a,s){if(t<=0)return"—";const r=(a>0?a:Math.ceil(t*.1))+Math.ceil(t*(s/100)),i=t-r;return i<=0?"0 (at risk)":`${_(i)} tokens`}function U({label:t,value:a,min:s,max:l,step:r=1,onChange:i,warning:f}){return e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"font-medium text-fg-muted",children:t}),e.jsxs("span",{className:`font-mono ${f?"text-warning":"text-fg"}`,title:f,children:[a,"%"]})]}),e.jsx("input",{type:"range",min:s,max:l,step:r,value:a,onChange:o=>i(Number(o.target.value)),className:"threshold-slider w-full"}),f&&e.jsxs("p",{className:"text-[10px] text-warning",children:["⚠ ",f]})]})}function Te({model:t,defaults:a,safetyRange:s,fireRange:l,onSave:r,onReset:i,saving:f}){const[o,d]=n.useState(t.threshold.safetyMarginPct),[g,m]=n.useState(t.threshold.firePointPct),[x,c]=n.useState(!1),[u,j]=n.useState(null);n.useEffect(()=>{d(t.threshold.safetyMarginPct),m(t.threshold.firePointPct),c(!1)},[t.threshold.safetyMarginPct,t.threshold.firePointPct]);const v=o<5?'Low safety margin — risks "conversation too long" errors when a single turn injects a large tool output between gate fires.':void 0,N=g>85?"High fire point — compaction may trigger close to the window cap; a single large turn can overshoot before the gate fires.":void 0,C=n.useCallback(async()=>{j(null);try{await r(t.modelId,o,g),c(!1)}catch(S){j(S instanceof Error?S.message:String(S))}},[t.modelId,o,g,r]);return e.jsxs("div",{className:"rounded-md border border-border bg-bg-elevated/30 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-semibold text-fg",children:t.modelName??t.modelId}),t.threshold.isOverride&&e.jsx("span",{className:"rounded border border-primary/40 bg-primary/15 px-1.5 py-0.5 text-[10px] font-semibold uppercase text-primary",title:"This model has a custom override (not the default)",children:"Override"})]}),e.jsxs("div",{className:"text-[11px] text-fg-muted",children:[t.provider," · ",_(t.contextWindow)," window ·"," ",_(t.maxTokens)," output"]})]}),e.jsxs("div",{className:"text-right text-[11px] text-fg-muted",children:[e.jsxs("div",{children:["Usable tail:"," ",e.jsx("span",{className:"font-mono text-fg",children:Ce(t.contextWindow,t.maxTokens,o)})]}),e.jsxs("div",{children:["Compaction fires at:"," ",e.jsx("span",{className:"font-mono text-fg",children:_(Math.ceil(t.contextWindow*(g/100)))})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[e.jsx(U,{label:"Safety margin",value:o,min:s[0],max:s[1],onChange:S=>{d(S),c(!0)},warning:v}),e.jsx(U,{label:"Fire point",value:g,min:l[0],max:l[1],onChange:S=>{m(S),c(!0)},warning:N})]}),e.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[e.jsx("button",{type:"button",onClick:C,disabled:!x||f,className:"rounded-md bg-primary px-2.5 py-1 text-xs font-semibold text-primary-fg disabled:cursor-not-allowed disabled:opacity-50",children:x?"Save override":"Saved"}),t.threshold.isOverride&&e.jsxs("button",{type:"button",onClick:()=>i(t.modelId),disabled:f,className:"rounded-md border border-border px-2.5 py-1 text-xs text-fg-muted disabled:cursor-not-allowed disabled:opacity-50",children:["Reset to default (",a.safetyMarginPct,"% /"," ",a.firePointPct,"%)"]}),u&&e.jsx("span",{className:"text-[11px] text-error",children:u})]})]})}function Ee(){const[t,a]=n.useState(null),[s,l]=n.useState(!0),[r,i]=n.useState(null),[f,o]=n.useState(!1),d=n.useCallback(async()=>{try{i(null),a(await le())}catch(x){i(x instanceof Error?x.message:String(x))}finally{l(!1)}},[]);n.useEffect(()=>{d()},[d]);const g=n.useCallback(async(x,c,u)=>{o(!0);try{await oe({modelId:x,safetyMarginPct:c,firePointPct:u}),await d()}finally{o(!1)}},[d]),m=n.useCallback(async x=>{o(!0);try{await ie(x),await d()}finally{o(!1)}},[d]);return s?e.jsx("div",{className:"p-4 text-sm text-fg-muted",children:"Loading thresholds…"}):r?e.jsxs("div",{className:"p-4 text-sm text-error",children:["Error: ",r]}):t?e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"rounded-md border border-border bg-bg-elevated/20 p-3",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Per-Model Compaction Thresholds"}),e.jsxs("p",{className:"mt-1 text-[11px] text-fg-muted",children:["Tune when compaction fires + how much safety margin to reserve,",e.jsx("strong",{children:" per model"}),". Different providers' models range from 8K to 1M+ context — one global % is wrong. Defaults:"," ",e.jsxs("span",{className:"font-mono",children:[t.defaults.safetyMarginPct,"% safety"]})," ","/"," ",e.jsxs("span",{className:"font-mono",children:[t.defaults.firePointPct,"% fire"]}),". Values outside the safe band show warnings."]})]}),t.models.length===0?e.jsx("div",{className:"rounded-md border border-border p-4 text-sm text-fg-muted",children:"No models captured yet. Start a pi session in any repo to populate model snapshots, then return here to tune per-model thresholds."}):e.jsx("div",{className:"flex flex-col gap-3",children:t.models.map(x=>e.jsx(Te,{model:x,defaults:t.defaults,safetyRange:t.defaults.safetyMarginRange,fireRange:t.defaults.firePointRange,onSave:g,onReset:m,saving:f},x.modelId))})]}):e.jsx("div",{className:"p-4 text-sm text-fg-muted",children:"No data."})}async function Re(){const t=await fetch("/api/setup-cortex-status");if(!t.ok)throw new Error(`setup-cortex status: ${t.status}`);return t.json()}async function Me(t){const a=await fetch("/api/setup-cortex-action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(a.ok)return{ok:!0,result:await a.json()};let s;try{s=await a.json()}catch{s={error:"disabled"}}return{ok:!1,status:a.status,error:s}}async function Le(t){const a=await fetch(`/api/setup-cortex-action-log?name=${encodeURIComponent(t)}`);if(!a.ok)throw new Error(`setup-cortex action-log: ${a.status}`);return a.json()}function ze(t){return t===null?!0:t.enabled&&t.status!=="off"}function V(){const[t,a]=n.useState({loading:!0,error:null,data:null}),s=n.useCallback(()=>{a(l=>({...l,loading:!0})),Re().then(l=>a(r=>({...r,data:l,loading:!1,error:null}))).catch(l=>a(r=>({...r,loading:!1,error:l instanceof Error?l.message:String(l)})))},[]);return n.useEffect(()=>{s();const l=setInterval(s,5e3);return()=>clearInterval(l)},[s]),[t,s]}const b={container:{padding:"1rem",maxWidth:"720px",margin:"0 auto",fontFamily:"system-ui, sans-serif",color:"#e0e0e0"},section:{background:"#1a1a2e",borderRadius:"8px",padding:"1rem",marginBottom:"1rem",border:"1px solid #2a2a4e"},sectionTitle:{fontSize:"1.1rem",fontWeight:700,marginTop:0,marginBottom:"0.75rem",color:"#e0e0e0",borderBottom:"1px solid #333",paddingBottom:"0.5rem"},label:{fontWeight:600,color:"#a0a0c0",marginRight:"0.5rem"},value:{color:"#e0e0e0"},row:{marginBottom:"0.4rem",fontSize:"0.9rem"},warning:{background:"#3a2a00",border:"1px solid #665500",borderRadius:"8px",padding:"0.75rem",marginTop:"0.5rem",color:"#ffcc00",fontSize:"0.85rem"},blocked:{background:"#3a1a1a",border:"1px solid #662222",borderRadius:"8px",padding:"0.75rem",marginTop:"0.5rem",color:"#ff6666",fontSize:"0.85rem"},badge:{display:"inline-block",padding:"0.15rem 0.5rem",borderRadius:"4px",fontSize:"0.8rem",fontWeight:600,marginLeft:"0.5rem"},button:{background:"#3a5a9f",color:"#fff",border:"none",borderRadius:"6px",padding:"0.5rem 1rem",cursor:"pointer",fontSize:"0.9rem",fontWeight:600},buttonDanger:{background:"#6a2a2a",color:"#ffb3b3",border:"1px solid #662222",borderRadius:"6px",padding:"0.5rem 1rem",cursor:"pointer",fontSize:"0.9rem",fontWeight:600},blockerRow:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"0.5rem",padding:"0.5rem 0.6rem",borderRadius:"6px",marginBottom:"0.35rem",fontSize:"0.85rem"},blockerRowHighlighted:{background:"#3a1a1a",border:"1px solid #662222"},mono:{fontFamily:"ui-monospace, monospace",fontSize:"0.8rem"}};function Ae(t){switch(t){case"A":return"A — qualified learned encoder asset";case"B":return"B — demoted (heuristic/trigram)";case"C":return"C — absent (asset not verified)";default:return"—"}}function Be(t){const a=t==="qualified"?"#1a5a1a":t==="demoted"?"#3a3a1a":"#3a1a1a",s=t==="qualified"?"#4caf50":t==="demoted"?"#ffcc00":"#f44336";return e.jsx("span",{style:{...b.badge,background:a,color:s},children:t??"unknown"})}function Ie({data:t,error:a}){return e.jsxs("div",{style:b.section,children:[e.jsxs("h3",{style:b.sectionTitle,children:[e.jsx("span",{style:{marginRight:"0.5rem"},children:"Cortex Encoder"}),e.jsx(ce,{status:t?.status})]}),a&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:["Error: ",a]}),!t&&!a&&e.jsx("p",{style:{color:"#888",fontSize:"0.85rem"},children:"Loading cortex status..."}),!t?.enabled&&e.jsx("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:"Cortex status disabled (VC9A off)."}),e.jsxs("div",{style:b.row,children:[e.jsx("span",{style:b.label,children:"Mode:"}),e.jsx("span",{style:b.value,children:Ae(t?.encoderHealth.mode)})]}),e.jsxs("div",{style:b.row,children:[e.jsx("span",{style:b.label,children:"Asset digest prefix:"}),e.jsx("span",{style:{...b.value,...b.mono},children:t?.assetDigestPrefix??e.jsx("span",{style:{color:"#888"},children:"not available"})})]}),e.jsxs("div",{style:b.row,children:[e.jsx("span",{style:b.label,children:"Qualification:"}),Be(t?.qualification.verdict)]}),(t?.qualification.thresholdFailures.length??0)>0&&e.jsxs("div",{style:b.warning,children:[e.jsx("strong",{children:"Threshold failure(s):"})," ",t?.qualification.thresholdFailures.join(", ")]}),t?.status==="awaiting_data"&&e.jsx("p",{style:{color:"#a0a0c0",fontSize:"0.85rem"},children:"Awaiting encoder data. Qualification will appear once an asset is present."}),t?.status==="deferred"&&e.jsx("p",{style:{color:"#a0a0c0",fontSize:"0.85rem"},children:"Encoder status deferred."})]})}function Pe(t){switch(t){case"blocker":return"#f44336";case"high":return"#ff9800";default:return"#a0a0c0"}}function _e({blockers:t,highlight:a,darwinX64:s}){const l=a??[];return e.jsxs("div",{style:b.section,children:[e.jsxs("h3",{style:b.sectionTitle,children:["Open Hard-Gate Blockers",e.jsx("span",{style:{...b.badge,background:"#3a1a1a",color:"#f44336"},children:t.length})]}),t.length===0&&e.jsx("p",{style:{color:"#4caf50",fontSize:"0.85rem"},children:"No open hard-gate blockers."}),s?.demoted===!0&&e.jsxs("div",{style:b.blockerRow,"data-darwin-x64-demoted":"true",children:[e.jsx("span",{style:{...b.mono,fontWeight:700},children:"HG-4"}),e.jsx("span",{style:{flex:1,color:"#e0e0e0"},children:s.reason||"darwin-x64: demoted to WASM (reason unavailable)"}),e.jsx("span",{style:{color:"#ff9800"},children:"high"}),e.jsx("span",{style:{color:"#4caf50",fontStyle:"italic"},children:"diagnosed"})]}),t.map(r=>{const i=l.includes(r.id);return e.jsxs("div",{style:{...b.blockerRow,...i?b.blockerRowHighlighted:{}},children:[e.jsx("span",{style:{...b.mono,fontWeight:700},children:r.id}),e.jsx("span",{style:{flex:1,color:"#e0e0e0"},children:r.title}),e.jsx("span",{style:{color:Pe(r.severity)},children:r.severity}),e.jsx("span",{style:{color:"#a0a0c0",fontStyle:"italic"},children:i?"gates this action":r.status})]},r.id)}),l.length>0&&e.jsxs("div",{style:b.blocked,children:[e.jsx("strong",{children:"Blocked:"})," the requested action is gated by the highlighted open hard-gate item(s). It was not run."]})]})}const Oe=[{key:"fetch-model",label:"Fetch Model",desc:"Fetch the qualified encoder model asset",dangerous:!0,confirm:"Fetch the encoder model asset onto this host? (Gated by any open hard gate.)"},{key:"bench",label:"Bench Encoder",desc:"Benchmark the encoder runtime on this host",dangerous:!0,confirm:"Run an encoder benchmark on this host? (Gated by any open hard gate.)"},{key:"verify-asset",label:"Verify Asset",desc:"Re-verify the committed encoder asset",dangerous:!1,confirm:"Re-verify the committed encoder asset?"}];function De({data:t,onBlocked:a,onAction:s}){const[l,r]=n.useState(null),[i,f]=n.useState(null),[o,d]=n.useState(null),[g,m]=n.useState(!1),x=n.useCallback(async u=>{r(u.key),d(null),f(null),m(!1),a([]);try{const j=await Me({action:u.key,confirm:!0});if(j.ok){const v=j.result;let N=null,C=null;try{const S=await Le(v.logName);N=S.tail,C=S.complete}catch{}f({action:v.action,logName:v.logName,tail:N,complete:C,message:v.ok?`${v.action} completed (spawned: ${v.spawned})`:`${v.action} did not complete cleanly`}),s()}else j.error.error==="action_blocked_by_open_item"?(a(j.error.blockers),d("The action is blocked by an open hard-gate item and was not run.")):j.error.error==="confirmation_required"?d("The server rejected the action: explicit confirmation is required."):(m(!0),d(j.status===404?"Setup Cortex actions are disabled (off).":`Action failed (${j.status}).`))}catch(j){d(j instanceof Error?j.message:String(j))}finally{r(null)}},[a,s]),c=u=>{window.confirm(u.confirm)&&x(u)};return e.jsxs("div",{style:b.section,children:[e.jsx("h3",{style:b.sectionTitle,children:"Cortex Actions"}),Oe.map(u=>{const j=l===u.key;return e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"0.5rem",padding:"0.5rem 0",borderBottom:"1px solid #2a2a4e"},children:[e.jsxs("div",{children:[e.jsx("div",{style:{fontWeight:600},children:u.label}),e.jsx("div",{style:{fontSize:"0.8rem",color:"#a0a0c0"},children:u.desc})]}),e.jsx("button",{style:u.dangerous?b.buttonDanger:b.button,disabled:l!==null,onClick:()=>c(u),children:j?"Running…":"Run"})]},u.key)}),g&&e.jsx("div",{style:b.blocked,children:"Setup Cortex actions are disabled. Enable MEGACOMPACT_VC9B to run them."}),o&&!g&&e.jsx("p",{style:{color:"#f44336",fontSize:"0.85rem",marginTop:"0.5rem"},children:o}),i&&e.jsxs("div",{style:b.warning,"data-testid":"cortex-action-result",children:[e.jsxs("strong",{children:["Result (",i.action,"):"]})," ",i.message,i.logName&&e.jsxs("span",{style:{...b.mono,marginLeft:"0.5rem"},children:["log: ",i.logName]}),i.tail!==null&&e.jsxs("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:"0.75rem",maxHeight:"12rem",overflow:"auto",marginTop:"0.5rem"},children:[i.tail,i.complete===!1&&`
2
- … (truncated)`]})]}),!t?.enabled&&!g&&e.jsx("p",{style:{color:"#a0a0c0",fontSize:"0.8rem",marginTop:"0.5rem"},children:"Cortex status unavailable — actions may not be schedulable."})]})}function $e(){const[t,a]=V(),[s,l]=n.useState([]),r=n.useCallback(f=>{l(f)},[]),i=n.useCallback(()=>{a()},[a]);return e.jsxs("div",{style:b.container,children:[e.jsx("h2",{style:{fontSize:"1.3rem",marginTop:0,marginBottom:"1rem"},children:"Setup Cortex"}),e.jsx("p",{style:{fontSize:"0.85rem",color:"#a0a0c0",marginTop:0},children:"Vector-cortex encoder gate: mode, qualification, open hard-gate blockers, and the confirmation-gated fetch/bench/verify actions."}),e.jsx(Ie,{data:t.data,error:t.error}),e.jsx(_e,{blockers:t.data?.blockers??[],highlight:s,darwinX64:t.data?.darwinX64}),e.jsx(De,{data:t.data,onBlocked:r,onAction:i})]})}const We=[{id:"embedder",label:"Embedder"},{id:"thresholds",label:"Thresholds"},{id:"config",label:"Config"},{id:"game",label:"Game Mode"},{id:"achievements",label:"Achievements"}],Ue={id:"cortex",label:"Cortex"};function Xe(){const[t,a]=n.useState("embedder"),[s]=V(),l=n.useMemo(()=>{const r=[...We];return ze(s.data)&&r.push(Ue),r},[s.data]);return e.jsxs("div",{className:"mx-auto flex max-w-3xl flex-col gap-4 p-4",children:[e.jsx("nav",{className:"flex gap-2 border-b border-border pb-2","aria-label":"Setup sections",children:l.map(r=>e.jsx(de,{pressed:t===r.id,onClick:()=>a(r.id),children:r.label},r.id))}),t==="embedder"&&e.jsx(ke,{}),t==="thresholds"&&e.jsx(Ee,{}),t==="config"&&e.jsx(pe,{}),t==="game"&&e.jsx(he,{}),t==="achievements"&&e.jsx(fe,{}),t==="cortex"&&e.jsx($e,{})]})}export{Xe as default};
3
- //# sourceMappingURL=SetupTab-C3dnKa8y.js.map