pi-mega-compact 0.20.22 → 0.20.23

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 (92) hide show
  1. package/dist/extensions/dashboard-server/resolve-snapshot.js +42 -28
  2. package/dist/extensions/dashboard-server/routes-setup.js +4 -1
  3. package/dist/extensions/dashboard-server/routes-vector-cortex-crystals.js +11 -3
  4. package/dist/extensions/dashboard-server/routes-vector-cortex-diagnostics.js +7 -2
  5. package/dist/extensions/dashboard-server/routes-vector-cortex-economics.js +1 -0
  6. package/dist/extensions/dashboard-server/routes-vector-cortex-heal.js +18 -6
  7. package/dist/extensions/dashboard-server/routes-vector-cortex-policy.js +1 -0
  8. package/dist/extensions/dashboard-server/routes-vector-cortex-reconstruct.js +10 -3
  9. package/dist/extensions/dashboard-server/routes-vector-cortex-repair.js +13 -5
  10. package/dist/extensions/dashboard-server/routes-vector-cortex-shards.js +12 -4
  11. package/dist/extensions/dashboard-server/vc-event-counts.js +63 -0
  12. package/dist/extensions/mega-events/context-handler/afterCompact.js +34 -0
  13. package/dist/extensions/mega-events/context-handler/pipelineRun.js +33 -0
  14. package/dist/extensions/mega-runtime/dashboard-snapshot.js +9 -6
  15. package/dist/extensions/mega-runtime/runtime-snapshot.js +2 -0
  16. package/dist/extensions/mega-runtime/vc-observer.js +98 -0
  17. package/extensions/dashboard-client/dist/assets/{AreaChart-BkfB-LSQ.js → AreaChart-BzEedilo.js} +2 -2
  18. package/extensions/dashboard-client/dist/assets/{AreaChart-BkfB-LSQ.js.map → AreaChart-BzEedilo.js.map} +1 -1
  19. package/extensions/dashboard-client/dist/assets/{BarChart-Cs1kogko.js → BarChart-CzAVg1_J.js} +2 -2
  20. package/extensions/dashboard-client/dist/assets/{BarChart-Cs1kogko.js.map → BarChart-CzAVg1_J.js.map} +1 -1
  21. package/extensions/dashboard-client/dist/assets/{CacheTab-BZgaguGr.js → CacheTab-D2-rzTuX.js} +2 -2
  22. package/extensions/dashboard-client/dist/assets/{CacheTab-BZgaguGr.js.map → CacheTab-D2-rzTuX.js.map} +1 -1
  23. package/extensions/dashboard-client/dist/assets/{EventsTab-BFbkI_MO.js → EventsTab-DB7g1Szy.js} +2 -2
  24. package/extensions/dashboard-client/dist/assets/{EventsTab-BFbkI_MO.js.map → EventsTab-DB7g1Szy.js.map} +1 -1
  25. package/extensions/dashboard-client/dist/assets/{HealthTab-CvlOENCX.js → HealthTab-Cvkmi-R3.js} +2 -2
  26. package/extensions/dashboard-client/dist/assets/{HealthTab-CvlOENCX.js.map → HealthTab-Cvkmi-R3.js.map} +1 -1
  27. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-CtBuz2qL.js → MaintenanceTab-g_udcOO7.js} +2 -2
  28. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-CtBuz2qL.js.map → MaintenanceTab-g_udcOO7.js.map} +1 -1
  29. package/extensions/dashboard-client/dist/assets/{MemoryMapTab-K4775S4d.js → MemoryMapTab-DAjBaf8P.js} +2 -2
  30. package/extensions/dashboard-client/dist/assets/{MemoryMapTab-K4775S4d.js.map → MemoryMapTab-DAjBaf8P.js.map} +1 -1
  31. package/extensions/dashboard-client/dist/assets/{MetricsTab-DVGcFInz.js → MetricsTab-13dYYocB.js} +2 -2
  32. package/extensions/dashboard-client/dist/assets/{MetricsTab-DVGcFInz.js.map → MetricsTab-13dYYocB.js.map} +1 -1
  33. package/extensions/dashboard-client/dist/assets/{OverviewTab-4LmW5ZCl.js → OverviewTab-CLpCyLvx.js} +2 -2
  34. package/extensions/dashboard-client/dist/assets/{OverviewTab-4LmW5ZCl.js.map → OverviewTab-CLpCyLvx.js.map} +1 -1
  35. package/extensions/dashboard-client/dist/assets/{ReposTab-StebchgQ.js → ReposTab-EdAqUrwG.js} +2 -2
  36. package/extensions/dashboard-client/dist/assets/{ReposTab-StebchgQ.js.map → ReposTab-EdAqUrwG.js.map} +1 -1
  37. package/extensions/dashboard-client/dist/assets/{SessionsTab-C3D_XAkX.js → SessionsTab-C21ZuOL_.js} +2 -2
  38. package/extensions/dashboard-client/dist/assets/{SessionsTab-C3D_XAkX.js.map → SessionsTab-C21ZuOL_.js.map} +1 -1
  39. package/extensions/dashboard-client/dist/assets/SetupTab-CP7lE3L_.js +2 -0
  40. package/extensions/dashboard-client/dist/assets/SetupTab-CP7lE3L_.js.map +1 -0
  41. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-CTPi_AAW.js → TimeSavedCard-DZ3QR8qt.js} +2 -2
  42. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-CTPi_AAW.js.map → TimeSavedCard-DZ3QR8qt.js.map} +1 -1
  43. package/extensions/dashboard-client/dist/assets/{TurnsTab-DSOGcY5Q.js → TurnsTab-CNchE5rD.js} +2 -2
  44. package/extensions/dashboard-client/dist/assets/{TurnsTab-DSOGcY5Q.js.map → TurnsTab-CNchE5rD.js.map} +1 -1
  45. package/extensions/dashboard-client/dist/assets/{VectorCortexTab-OMW8_RFf.js → VectorCortexTab-B3WuPeyn.js} +2 -2
  46. package/extensions/dashboard-client/dist/assets/{VectorCortexTab-OMW8_RFf.js.map → VectorCortexTab-B3WuPeyn.js.map} +1 -1
  47. package/extensions/dashboard-client/dist/assets/{WikiTab-Db-qFDdg.js → WikiTab-BIe5Z9Nc.js} +2 -2
  48. package/extensions/dashboard-client/dist/assets/{WikiTab-Db-qFDdg.js.map → WikiTab-BIe5Z9Nc.js.map} +1 -1
  49. package/extensions/dashboard-client/dist/assets/{button-BF4UgBAD.js → button-BrVreSt5.js} +2 -2
  50. package/extensions/dashboard-client/dist/assets/{button-BF4UgBAD.js.map → button-BrVreSt5.js.map} +1 -1
  51. package/extensions/dashboard-client/dist/assets/{card-XmXoYQqB.js → card-D9F4wbqs.js} +2 -2
  52. package/extensions/dashboard-client/dist/assets/{card-XmXoYQqB.js.map → card-D9F4wbqs.js.map} +1 -1
  53. package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-Be8hM1aU.js → generateCategoricalChart-mkdzCnMP.js} +2 -2
  54. package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-Be8hM1aU.js.map → generateCategoricalChart-mkdzCnMP.js.map} +1 -1
  55. package/extensions/dashboard-client/dist/assets/{index-NXDgILxv.js → index-CtlmOlj1.js} +3 -3
  56. package/extensions/dashboard-client/dist/assets/{index-NXDgILxv.js.map → index-CtlmOlj1.js.map} +1 -1
  57. package/extensions/dashboard-client/dist/assets/{switch-kUZCrbia.js → switch-BXmp5iwA.js} +2 -2
  58. package/extensions/dashboard-client/dist/assets/{switch-kUZCrbia.js.map → switch-BXmp5iwA.js.map} +1 -1
  59. package/extensions/dashboard-client/dist/assets/{toggle-DEe5mCwF.js → toggle-BgawNwW9.js} +2 -2
  60. package/extensions/dashboard-client/dist/assets/{toggle-DEe5mCwF.js.map → toggle-BgawNwW9.js.map} +1 -1
  61. package/extensions/dashboard-client/dist/assets/{useSSE-BlCyLqge.js → useSSE-DZKX73Ea.js} +2 -2
  62. package/extensions/dashboard-client/dist/assets/{useSSE-BlCyLqge.js.map → useSSE-DZKX73Ea.js.map} +1 -1
  63. package/extensions/dashboard-client/dist/index.html +1 -1
  64. package/extensions/dashboard-client/src/tabs/SetupTab/CustomEndpointSection.tsx +65 -0
  65. package/extensions/dashboard-client/src/tabs/SetupTab/EmbedderSetup.tsx +19 -108
  66. package/extensions/dashboard-client/src/tabs/SetupTab/EmbedderSetupStyles.ts +69 -0
  67. package/extensions/dashboard-client/src/tabs/VectorCortexTab.tsx +5 -3
  68. package/extensions/dashboard-server/api-contracts/setup.ts +4 -3
  69. package/extensions/dashboard-server/api-contracts/vector-cortex-cache.ts +5 -0
  70. package/extensions/dashboard-server/api-contracts/vector-cortex-diagnostics.ts +2 -0
  71. package/extensions/dashboard-server/api-contracts/vector-cortex-economics.ts +2 -0
  72. package/extensions/dashboard-server/api-contracts/vector-cortex-policy.ts +2 -0
  73. package/extensions/dashboard-server/resolve-snapshot.ts +42 -28
  74. package/extensions/dashboard-server/routes-setup.ts +3 -1
  75. package/extensions/dashboard-server/routes-vector-cortex-crystals.ts +12 -3
  76. package/extensions/dashboard-server/routes-vector-cortex-diagnostics.ts +8 -2
  77. package/extensions/dashboard-server/routes-vector-cortex-economics.ts +1 -0
  78. package/extensions/dashboard-server/routes-vector-cortex-heal.ts +19 -6
  79. package/extensions/dashboard-server/routes-vector-cortex-policy.ts +1 -0
  80. package/extensions/dashboard-server/routes-vector-cortex-reconstruct.ts +11 -3
  81. package/extensions/dashboard-server/routes-vector-cortex-repair.ts +14 -5
  82. package/extensions/dashboard-server/routes-vector-cortex-shards.ts +13 -4
  83. package/extensions/dashboard-server/vc-event-counts.ts +67 -0
  84. package/extensions/mega-dashboard.ts +2 -0
  85. package/extensions/mega-events/context-handler/afterCompact.ts +46 -0
  86. package/extensions/mega-events/context-handler/pipelineRun.ts +39 -0
  87. package/extensions/mega-runtime/dashboard-snapshot.ts +12 -6
  88. package/extensions/mega-runtime/runtime-snapshot.ts +6 -0
  89. package/extensions/mega-runtime/vc-observer.ts +120 -0
  90. package/package.json +1 -1
  91. package/extensions/dashboard-client/dist/assets/SetupTab-BTBGyppF.js +0 -2
  92. package/extensions/dashboard-client/dist/assets/SetupTab-BTBGyppF.js.map +0 -1
@@ -11,12 +11,19 @@ import type { IncomingMessage, ServerResponse } from "node:http";
11
11
  import type { RouteContext } from "./routes-core.js";
12
12
  import { VC4C_ENABLED } from "../../src/config.js";
13
13
  import { sendJson } from "./routes-vector-cortex-shared.js";
14
+ import { countVcEvents, vcCount } from "./vc-event-counts.js";
14
15
  import type { VectorCortexReconstructView } from "./api-contracts/vector-cortex.js";
15
16
 
17
+ // Closure attempt/rejection events emitted by src/vector-cortex/heal/emit.ts.
18
+ const RECONSTRUCT_EVENTS = [
19
+ "vector_cortex_closure_optimized",
20
+ "vector_cortex_closure_proof_rejected",
21
+ ] as const;
22
+
16
23
  export function handleVectorCortexReconstruct(
17
24
  req: IncomingMessage,
18
25
  res: ServerResponse,
19
- _ctx: RouteContext,
26
+ ctx: RouteContext,
20
27
  ): boolean {
21
28
  const url = req.url ?? "";
22
29
  const path = url.split("?")[0] ?? url;
@@ -26,10 +33,11 @@ export function handleVectorCortexReconstruct(
26
33
  return true;
27
34
  }
28
35
  const enabled = VC4C_ENABLED();
36
+ const counts = countVcEvents(ctx.stateDir, RECONSTRUCT_EVENTS);
29
37
  const body: VectorCortexReconstructView = {
30
38
  enabled,
31
- closureAttempts: 0,
32
- closureRejections: 0,
39
+ closureAttempts: vcCount(counts, "vector_cortex_closure_optimized"),
40
+ closureRejections: vcCount(counts, "vector_cortex_closure_proof_rejected"),
33
41
  validatedCount: 0,
34
42
  invalidatedCount: 0,
35
43
  spanTotal: 0,
@@ -25,8 +25,16 @@ import type { IncomingMessage, ServerResponse } from "node:http";
25
25
  import type { RouteContext } from "./routes-core.js";
26
26
  import { VC6C_ENABLED } from "../../src/config.js";
27
27
  import { sendJson } from "./routes-vector-cortex-shared.js";
28
+ import { countVcEvents, vcCount } from "./vc-event-counts.js";
28
29
  import type { VectorCortexRepairView } from "./api-contracts/vector-cortex.js";
29
30
 
31
+ // Actual event names emitted by src/vector-cortex/heal/repair-emit.ts.
32
+ const REPAIR_EVENTS = [
33
+ "vector_cortex_repair_planned",
34
+ "vector_cortex_repair_pointer_switched",
35
+ "vector_cortex_repair_backoff",
36
+ ] as const;
37
+
30
38
  /**
31
39
  * Reader-only GET /api/vector-cortex/repair (VC6C).
32
40
  *
@@ -38,7 +46,7 @@ import type { VectorCortexRepairView } from "./api-contracts/vector-cortex.js";
38
46
  export function handleVectorCortexRepair(
39
47
  req: IncomingMessage,
40
48
  res: ServerResponse,
41
- _ctx: RouteContext,
49
+ ctx: RouteContext,
42
50
  ): boolean {
43
51
  const url = req.url ?? "";
44
52
  const path = url.split("?")[0] ?? url;
@@ -49,6 +57,7 @@ export function handleVectorCortexRepair(
49
57
  }
50
58
 
51
59
  const enabled = VC6C_ENABLED();
60
+ const counts = countVcEvents(ctx.stateDir, REPAIR_EVENTS);
52
61
  // Flag-off routes to mode C: with VC6C off no self-healing controller runs at
53
62
  // all, so neither the targeted rebuild (mode A) nor the full deterministic
54
63
  // rebuild (mode B) path is available. Mode C is exactly the spec's "derived
@@ -59,10 +68,10 @@ export function handleVectorCortexRepair(
59
68
  const body: VectorCortexRepairView = {
60
69
  enabled,
61
70
  mode,
62
- repairAttempts: 0,
63
- repairsPlanned: 0,
64
- pointersSwitched: 0,
65
- backoffs: 0,
71
+ repairAttempts: vcCount(counts, "vector_cortex_repair_planned"),
72
+ repairsPlanned: vcCount(counts, "vector_cortex_repair_planned"),
73
+ pointersSwitched: vcCount(counts, "vector_cortex_repair_pointer_switched"),
74
+ backoffs: vcCount(counts, "vector_cortex_repair_backoff"),
66
75
  lastBackoffMs: null,
67
76
  lastFailure: null,
68
77
  updatedAt: new Date().toISOString(),
@@ -22,15 +22,22 @@ import type { IncomingMessage, ServerResponse } from "node:http";
22
22
  import type { RouteContext } from "./routes-core.js";
23
23
  import { VC4A_ENABLED } from "../../src/config.js";
24
24
  import { sendJson } from "./routes-vector-cortex-shared.js";
25
+ import { countVcEvents, vcCount } from "./vc-event-counts.js";
25
26
  import type { VectorCortexShardsView } from "./api-contracts/vector-cortex.js";
26
27
 
28
+ // Actual events emitted by src/vector-cortex/shards/manifest.ts. VC4A has no
29
+ // per-tier (semantic/exact) write event — the manifest build is the single
30
+ // shard-write signal — so semanticCount is wired to it and exactCount stays 0
31
+ // until a per-tier write event exists.
32
+ const SHARD_EVENTS = ["vector_cortex_shard_manifest_built"] as const;
33
+
27
34
  /**
28
35
  * Reader-only GET /api/vector-cortex/shards (VC4A).
29
36
  */
30
37
  export function handleVectorCortexShards(
31
38
  req: IncomingMessage,
32
39
  res: ServerResponse,
33
- _ctx: RouteContext,
40
+ ctx: RouteContext,
34
41
  ): boolean {
35
42
  const url = req.url ?? "";
36
43
  const path = url.split("?")[0] ?? url;
@@ -42,11 +49,13 @@ export function handleVectorCortexShards(
42
49
  }
43
50
 
44
51
  const enabled = VC4A_ENABLED();
52
+ const counts = countVcEvents(ctx.stateDir, SHARD_EVENTS);
45
53
  const body: VectorCortexShardsView = {
46
54
  enabled,
47
- // No durable shard manifest is staged yet in this sprint (pure in-memory
48
- // partition), so the aggregates are truthfully zero.
49
- semanticCount: 0,
55
+ // The manifest-build event is the only VC4A shard-write signal; semanticCount
56
+ // reflects manifests built and exactCount stays 0 (no per-tier write event
57
+ // distinguishes exact shards in events.log yet).
58
+ semanticCount: vcCount(counts, "vector_cortex_shard_manifest_built"),
50
59
  exactCount: 0,
51
60
  byteTotal: 0,
52
61
  protectedByteTotal: 0,
@@ -0,0 +1,67 @@
1
+ /**
2
+ * dashboard-server/vc-event-counts.ts — lightweight events.log tail reader for
3
+ * the Vector Cortex dashboard routes.
4
+ *
5
+ * The VC event reporters in `src/vector-cortex/*` emit structured JSON events
6
+ * (one per line) into the per-repo `events.log`. Instead of the dashboard
7
+ * hardcoding zero for aggregate counters, this module reads the event tail and
8
+ * counts real occurrences of named events. It is the single shared seam so every
9
+ * route stays a small, thin consumer and the counting logic lives in one place
10
+ * (extensions/ 400-line soft-as-hard split trigger).
11
+ *
12
+ * NEVER throws: a missing/unreadable file degrades to an empty Map, malformed
13
+ * lines are skipped silently, and only the `.event` string field is inspected —
14
+ * no payload, bytes, span ids, digests, or ledger text ever leaves this module
15
+ * (SECURITY_PRIVACY, reader-only aggregate).
16
+ *
17
+ * Guardrails: PREVENT-PI-004 (local in-process file read only), PREVENT-011
18
+ * (no `any`).
19
+ */
20
+
21
+ import { join } from "node:path";
22
+ import { readFileSync } from "node:fs";
23
+
24
+ /**
25
+ * Count occurrences of the given named events within the last `maxLines` of the
26
+ * per-repo events.log adjacent to `stateDir`. Returns a Map keyed by event name;
27
+ * a missing/unreadable log or zero matching lines yields an empty Map. Best-effort
28
+ * and non-fatal by construction (matches the non-fatal-stores invariant).
29
+ */
30
+ export function countVcEvents(
31
+ stateDir: string,
32
+ eventNames: readonly string[],
33
+ maxLines = 10000,
34
+ ): Map<string, number> {
35
+ const counts = new Map<string, number>();
36
+ let raw: string;
37
+ try {
38
+ raw = readFileSync(join(stateDir, "events.log"), "utf-8");
39
+ } catch {
40
+ // Missing or unreadable log → nothing to count, never throw.
41
+ return counts;
42
+ }
43
+ // Walk only the tail: split into lines and keep the last `maxLines`.
44
+ const lines = raw.split("\n");
45
+ const start = Math.max(0, lines.length - maxLines);
46
+ const wanted = new Set(eventNames);
47
+ for (let i = start; i < lines.length; i++) {
48
+ const line = lines[i] as string;
49
+ if (line.length === 0) continue;
50
+ let ev: { event?: unknown } | null = null;
51
+ try {
52
+ ev = JSON.parse(line) as { event?: unknown };
53
+ } catch {
54
+ // Malformed line — skip silently, never break the reader.
55
+ continue;
56
+ }
57
+ if (typeof ev?.event === "string" && wanted.has(ev.event)) {
58
+ counts.set(ev.event, (counts.get(ev.event) ?? 0) + 1);
59
+ }
60
+ }
61
+ return counts;
62
+ }
63
+
64
+ /** Read a value from an event-count map, defaulting to 0 when absent. */
65
+ export function vcCount(counts: Map<string, number>, name: string): number {
66
+ return counts.get(name) ?? 0;
67
+ }
@@ -25,6 +25,8 @@ export interface DashboardSnapshot {
25
25
  presetTier: string;
26
26
  /** Live 0–1 pressure ratio (currentTokens / thresholdTokens). */
27
27
  pressure: number;
28
+ /** VC0A: count of eval-observer latency samples (0 when disabled/absent). */
29
+ vcObserverSamples: number;
28
30
  config: {
29
31
  fastGatePct: number;
30
32
  thresholdTokens: number;
@@ -28,12 +28,17 @@ import { assignNewMemoriesIncremental } from "../../../src/wiki/index.js";
28
28
  import { TrigramEmbedder } from "../../../src/embedder.js";
29
29
  import type { EmbeddedChunk } from "../../../src/topics/types.js";
30
30
  import type { MegaConfig } from "../../mega-config.js";
31
+ import { reportClosureOptimized } from "../../../src/vector-cortex/heal/emit.js";
32
+ import { reportRepairPlanned } from "../../../src/vector-cortex/heal/repair-emit.js";
33
+ import { VC6A_ENABLED, VC6C_ENABLED } from "../../../src/config/vector-cortex.js";
31
34
 
32
35
  /** Shape of the compact result consumed by the epoch/maintenance writes. */
33
36
  interface CompactResult {
34
37
  checkpointId?: string;
35
38
  compactedFrom: number;
36
39
  summary: string;
40
+ tokenEstimate?: number;
41
+ originalTokenEstimate?: number;
37
42
  }
38
43
 
39
44
  /**
@@ -253,4 +258,45 @@ export async function persistEpochAndMaintain(
253
258
  runtime.logger.warn("db-mirror-epoch-fail", { error: String(e) });
254
259
  }
255
260
  }
261
+
262
+ // VC6 Heal lifecycle emits (post-compact). Wiring stubs — dashboard graph +
263
+ // event counts move; real gap detection/rebuild is a future sprint.
264
+ // VC6A: closure-optimization savings from the compact token delta.
265
+ const savings = Math.max(
266
+ 0,
267
+ (ran.result.originalTokenEstimate ?? 0) - (ran.result.tokenEstimate ?? 0),
268
+ );
269
+ if (VC6A_ENABLED()) {
270
+ try {
271
+ reportClosureOptimized(
272
+ (name, payload) =>
273
+ runtime.appendEvent(name, payload as Record<string, unknown>),
274
+ {
275
+ sessionId: runtime.rt.sessionId,
276
+ removed: 0,
277
+ retained: ran.result.compactedFrom,
278
+ savings,
279
+ },
280
+ );
281
+ } catch {
282
+ /* non-fatal: VC6A heal emit never breaks compaction */
283
+ }
284
+ }
285
+ // VC6C: repair-planner placeholder (no real gap detection yet).
286
+ if (VC6C_ENABLED()) {
287
+ try {
288
+ reportRepairPlanned(
289
+ (name, payload) =>
290
+ runtime.appendEvent(name, payload as Record<string, unknown>),
291
+ {
292
+ subsystem: "post_compact",
293
+ generation: 1,
294
+ backoffMs: 0,
295
+ gapSize: 0,
296
+ },
297
+ );
298
+ } catch {
299
+ /* non-fatal: VC6C heal emit never breaks compaction */
300
+ }
301
+ }
256
302
  }
@@ -19,6 +19,9 @@ import { pressureFromPct, pressureRatio } from "../../mega-config.js";
19
19
  import type { MegaRuntime } from "../../mega-runtime.js";
20
20
  import type { MegaConfig } from "../../mega-config.js";
21
21
  import type { TailResultFn } from "./gateCheck.js";
22
+ import { recordCompactLatency } from "../../mega-runtime/vc-observer.js";
23
+ import { decideLivePath } from "../../mega-runtime/vector-cortex-live.js";
24
+ import { VC5C_ENABLED } from "../../../src/config/vector-cortex.js";
22
25
 
23
26
  /** The non-skipped variant of the runCompact result. */
24
27
  export type RanResult = Extract<RunCompactResult, { skipped: false }>;
@@ -45,6 +48,32 @@ export function invokePipeline(
45
48
  tailResult: TailResultFn;
46
49
  },
47
50
  ): PipelineOutcome {
51
+ // VC5C: emit the rollout decision per compact event (observability seam).
52
+ // vcGate/vcHardFaults are not yet declared on MegaRuntime.rt — cast to the
53
+ // rollout shapes. Best-effort + non-fatal; decision does NOT gate behavior yet.
54
+ if (VC5C_ENABLED()) {
55
+ try {
56
+ const decision = decideLivePath(runtime.rt.sessionId, {
57
+ emit: runtime.appendEvent.bind(runtime),
58
+ currentGate:
59
+ (runtime.rt as { vcGate?: 0 | 1 | 2 | 3 | 4 }).vcGate ?? 0,
60
+ hardFaults:
61
+ (runtime.rt as { vcHardFaults?: import("../../../src/vector-cortex/rollout/types.js").RolloutHardFault[] })
62
+ .vcHardFaults ?? [],
63
+ });
64
+ runtime.appendEvent("vector_cortex_rollout_decision", {
65
+ sessionId: runtime.rt.sessionId,
66
+ vcActive: decision.vcActive,
67
+ forcedPreVc: decision.forcedPreVc,
68
+ mode: decision.mode,
69
+ bucket: decision.bucket,
70
+ gateIndex: decision.gateIndex,
71
+ promotionBlocked: decision.promotionBlocked,
72
+ });
73
+ } catch {
74
+ /* non-fatal: rollout decision emission never breaks compaction */
75
+ }
76
+ }
48
77
  // Adaptive compression (Fix E): scale compression strength + keepFrom depth
49
78
  // with how close we are to the model context limit. Null-safe: when the
50
79
  // token-fallback path ran (pct unavailable) use the token-basis pressure
@@ -53,9 +82,19 @@ export function invokePipeline(
53
82
  opts.pct != null
54
83
  ? pressureFromPct(opts.pct)
55
84
  : pressureRatio(opts.currentTokens, runtime.effectiveThreshold);
85
+ const t0 = Date.now();
56
86
  const ran = runCompact(pi, runtime, config, ctx, opts.messages, {
57
87
  compressionPressure: pressure,
58
88
  });
89
+ // VC0A: record compact latency on the eval observer (mode A) on every
90
+ // outcome so the dashboard histogram reflects real data. No-op when the
91
+ // observer is absent (flag off / construction failure).
92
+ recordCompactLatency(
93
+ runtime,
94
+ Date.now() - t0,
95
+ runtime.rt.sessionId,
96
+ runtime.rt.compactCount,
97
+ );
59
98
  // D.3: skip paths fall back to replay instead of returning empty.
60
99
  // If runCompact skipped and we have a valid trimCache, replay it
61
100
  // (free stability win) — otherwise defer to the next event.
@@ -39,6 +39,9 @@ export interface SnapshotBuildContext {
39
39
  readonly pressureBand: string;
40
40
  readonly pressure: number;
41
41
  readonly effectiveThreshold: number;
42
+ /** VC0A: count of latency samples the eval observer histogram should show
43
+ * (0 when the observer is absent / flag off). */
44
+ readonly vcObserverSamples?: number;
42
45
  readonly statusKey: string | undefined;
43
46
  readonly lastCtxTokens: number | null;
44
47
  readonly lastCtxPercent: number | null;
@@ -76,6 +79,7 @@ export function buildDashboardSnapshot(ctx: SnapshotBuildContext): DashboardSnap
76
79
  tier: ctx.pressureBand,
77
80
  presetTier: ctx.config.tier,
78
81
  pressure: ctx.pressure,
82
+ vcObserverSamples: ctx.vcObserverSamples ?? 0,
79
83
  config: {
80
84
  fastGatePct: ctx.config.fastGatePct,
81
85
  thresholdTokens: ctx.effectiveThreshold,
@@ -132,17 +136,17 @@ export function buildDashboardSnapshot(ctx: SnapshotBuildContext): DashboardSnap
132
136
  repo: ctx.repo,
133
137
  compression: {
134
138
  session: {
135
- tokensIn: ctx.rt.tokensSaved + (ctx.st.totalTokenEstimate - ctx.st.originalTokens),
139
+ tokensIn: ctx.st.originalTokens,
136
140
  tokensOut: ctx.st.totalTokenEstimate,
137
141
  tokensFreed: ctx.rt.tokensSaved,
138
- compressionPct: ctx.rt.tokensSaved / Math.max(1, ctx.rt.tokensSaved + (ctx.st.totalTokenEstimate - ctx.st.originalTokens)),
142
+ compressionPct: ctx.rt.tokensSaved / Math.max(1, ctx.st.originalTokens),
139
143
  dedupPct: ctx.rt.dedupAttempts > 0 ? ctx.rt.dedupSkips / ctx.rt.dedupAttempts : 0,
140
144
  },
141
145
  repo: {
142
- tokensIn: ctx.repo.tokensSaved + (ctx.repo.totalTokenEstimate - ctx.repo.originalTokens),
146
+ tokensIn: ctx.repo.originalTokens,
143
147
  tokensOut: ctx.repo.totalTokenEstimate,
144
148
  tokensFreed: ctx.repo.tokensSaved,
145
- compressionPct: ctx.repo.tokensSaved / Math.max(1, ctx.repo.tokensSaved + (ctx.repo.totalTokenEstimate - ctx.repo.originalTokens)),
149
+ compressionPct: ctx.repo.tokensSaved / Math.max(1, ctx.repo.originalTokens),
146
150
  dedupPct: ctx.repo.dedupAttempts > 0 ? ctx.repo.dedupCollapsed / ctx.repo.dedupAttempts : 0,
147
151
  },
148
152
  },
@@ -155,7 +159,9 @@ export function buildDashboardSnapshot(ctx: SnapshotBuildContext): DashboardSnap
155
159
  // per-session in rt and there's no cumulative counter yet.
156
160
  total: ctx.repo.dedupCollapsed,
157
161
  sessionTokensSaved: ctx.rt.cacheHitTokens,
158
- totalTokensSaved: ctx.repo.dedupCollapsed > 0 ? ctx.repo.dedupCollapsed * 100 : 0,
162
+ // Cumulative tokens saved across all sessions in this repo —
163
+ // was a placeholder (dedupCollapsed * 100).
164
+ totalTokensSaved: ctx.repo.tokensSaved,
159
165
  },
160
166
  compacts: {
161
167
  session: ctx.rt.compactCount,
@@ -168,7 +174,7 @@ export function buildDashboardSnapshot(ctx: SnapshotBuildContext): DashboardSnap
168
174
  },
169
175
  cacheHit: {
170
176
  sessionSec: ctx.rt.cacheHitTokens / 1000,
171
- totalSec: (ctx.repo.dedupCollapsed * 100) / 1000,
177
+ totalSec: ctx.repo.tokensSaved / 1000,
172
178
  },
173
179
  },
174
180
  model: ctx.currentModel
@@ -42,6 +42,7 @@ import type { Dashboard } from "../mega-dashboard.js";
42
42
  import type { WidgetData } from "./widget.js";
43
43
  import { computeMegaSnapshot } from "./snapshot.js";
44
44
  import { buildDashboardSnapshot } from "./dashboard-snapshot.js";
45
+ import { getVcObserver } from "./vc-observer.js";
45
46
  import {
46
47
  type RuntimeHelpersContext,
47
48
  materialSigImpl,
@@ -65,6 +66,10 @@ export interface RuntimeSnapshotContext extends RuntimeHelpersContext {
65
66
  store: VectorStore;
66
67
  config: MegaConfig;
67
68
  dashboard: Dashboard;
69
+ // VC0A: appendEvent + currentStateDir are consumed by getVcObserver()
70
+ // (vc-observer.ts WeakMap cache) to surface how many latency samples the
71
+ // dashboard histogram should expect.
72
+ appendEvent(event: string, fields: Record<string, unknown>): void;
68
73
  currentStateDir: string;
69
74
  widgetData: WidgetData | null;
70
75
  /** v0.8.5: material-change signature; read + written by snapshot(). Public so
@@ -164,6 +169,7 @@ export function snapshotImpl(
164
169
  pressureBand: self.pressureBand,
165
170
  pressure: self.pressure,
166
171
  effectiveThreshold: self.effectiveThreshold,
172
+ vcObserverSamples: getVcObserver(self)?.rows().length ?? 0,
167
173
  statusKey: self.statusKey,
168
174
  lastCtxTokens: self.lastCtxTokens,
169
175
  lastCtxPercent: self.lastCtxPercent,
@@ -0,0 +1,120 @@
1
+ /**
2
+ * vc-observer.ts — VC0A mode-A eval observer wiring for MegaRuntime.
3
+ *
4
+ * Bridges the pure in-memory EvalObserver (src/vector-cortex/eval/observer.ts)
5
+ * into the production runtime: every recorded compact/recall latency sample is
6
+ * both emitted to events.log (via MegaRuntime.appendEvent) and appended to the
7
+ * redacted evaluation.jsonl (via appendEvalRow) so the Vector Cortex dashboard
8
+ * "Observer" histogram reads real data instead of an empty file.
9
+ *
10
+ * All wiring is gated on VC0A_ENABLED() (MEGACOMPACT_VC0A). Flag-off and any
11
+ * construction/persistence error are non-fatal (PREVENT-PI-004: local FS only,
12
+ * no network) and degrade to a null observer — byte-identical to the
13
+ * predecessor (mode C). PREVENT-011: no `any` type.
14
+ *
15
+ * Follows the capture-model.ts / append-event.ts pattern: a context interface +
16
+ * free functions + a thin delegate. No import-time side effects — merely
17
+ * importing these functions is inert regardless of the flag.
18
+ */
19
+
20
+ import { VC0A_ENABLED } from "../../src/config.js";
21
+ import { createEvalObserver } from "../../src/vector-cortex/eval/observer.js";
22
+ import type { EvalObserver } from "../../src/vector-cortex/eval/observer.js";
23
+ import { appendEvalRow } from "../../src/vector-cortex/eval/persist.js";
24
+
25
+ // ---------------------------------------------------------------------- types
26
+
27
+ /** The slice of `MegaRuntime` the observer bridge reads/writes. */
28
+ export interface VcObserverContext {
29
+ appendEvent(event: string, fields: Record<string, unknown>): void;
30
+ readonly currentStateDir: string;
31
+ }
32
+
33
+ // ------------------------------------------------------------- construction
34
+
35
+ /**
36
+ * Build the production-wired eval observer (mode A) if the VC0A flag is on.
37
+ * Returns null when the flag is off or on any construction error (non-fatal).
38
+ * The returned observer is a thin, best-effort observability seam that never
39
+ * breaks the agent loop.
40
+ */
41
+ export function createVcObserver(self: VcObserverContext): EvalObserver | null {
42
+ if (!VC0A_ENABLED()) return null;
43
+ try {
44
+ return createEvalObserver({
45
+ emit: self.appendEvent.bind(self),
46
+ persist: (sample) => appendEvalRow(self.currentStateDir, [sample]),
47
+ });
48
+ } catch {
49
+ /* non-fatal observability — never break the agent loop */
50
+ return null;
51
+ }
52
+ }
53
+
54
+ // ---------------------------------------------------------------- weak cache
55
+
56
+ /**
57
+ * Module-level observer cache keyed by the runtime object. Avoids adding a
58
+ * `vcObserver` field to MegaRuntime (keeping runtime.ts under its soft limit
59
+ * — no field, no constructor line, no import bloat). One observer per runtime
60
+ * instance, lazily built on the first latency recording.
61
+ */
62
+ const observerCache = new WeakMap<object, EvalObserver | null>();
63
+
64
+ /** Lazily create + cache the observer for the given runtime context. */
65
+ export function getVcObserver(self: VcObserverContext): EvalObserver | null {
66
+ let obs = observerCache.get(self);
67
+ if (obs === undefined) {
68
+ obs = createVcObserver(self);
69
+ observerCache.set(self, obs);
70
+ }
71
+ return obs;
72
+ }
73
+
74
+ // ---------------------------------------------------------------- reporting
75
+
76
+ /** Record a compact latency sample on the observer (no-op when absent). */
77
+ export function recordCompactLatency(
78
+ self: VcObserverContext,
79
+ elapsedMs: number,
80
+ sessionId: string,
81
+ epoch: number,
82
+ ): void {
83
+ const obs = getVcObserver(self);
84
+ if (obs == null) return;
85
+ try {
86
+ obs.record({
87
+ session: sessionId,
88
+ seq: epoch,
89
+ event: "compact",
90
+ value: elapsedMs,
91
+ unit: "ms",
92
+ mode: "A",
93
+ });
94
+ } catch {
95
+ /* non-fatal observability */
96
+ }
97
+ }
98
+
99
+ /** Record a recall latency sample on the observer (no-op when absent). */
100
+ export function recordRecallLatency(
101
+ self: VcObserverContext,
102
+ elapsedMs: number,
103
+ sessionId: string,
104
+ epoch: number,
105
+ ): void {
106
+ const obs = getVcObserver(self);
107
+ if (obs == null) return;
108
+ try {
109
+ obs.record({
110
+ session: sessionId,
111
+ seq: epoch,
112
+ event: "recall",
113
+ value: elapsedMs,
114
+ unit: "ms",
115
+ mode: "A",
116
+ });
117
+ } catch {
118
+ /* non-fatal observability */
119
+ }
120
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-mega-compact",
3
- "version": "0.20.22",
3
+ "version": "0.20.23",
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",
@@ -1,2 +0,0 @@
1
- import{r as s,j as e,h as L,i as W,k as F,p as q,l as K,m as X,C as Y,n as J,o as Q,q as Z,s as ee,t as te,v as se,w as ne,x as ae,y as re}from"./index-NXDgILxv.js";import{S as le}from"./switch-kUZCrbia.js";import{T as ie}from"./toggle-DEe5mCwF.js";function oe(t){try{return new Date(t*1e3).toLocaleString()}catch{return"—"}}function G({achievements:t}){const c=s.useRef(0),[n,h]=s.useState(null),l=t.reduce((a,i)=>Math.max(a,i.unlocked_at??0),0),d=c.current;s.useEffect(()=>{l>c.current&&(c.current=l)},[l]),s.useEffect(()=>{if(d>0&&l>d){const a=t.filter(i=>i.unlocked_at!=null&&(i.unlocked_at??0)>d);if(a.length>0){const i=a.map(o=>`${o.icon??""} ${o.title}`.trim()).join(", ")+" unlocked!";h(i);const f=setTimeout(()=>h(null),4e3);return()=>clearTimeout(f)}}},[t,l,d]);const u=t.filter(a=>!(a.hidden===1&&a.unlocked_at==null));return e.jsxs("div",{className:"ach-section",children:[n!=null&&e.jsx("div",{className:"ach-toast show",children:n}),e.jsxs("div",{className:"ach-tiles",children:[u.length===0&&e.jsx("span",{className:"repo-none",children:"no achievements yet"}),u.map(a=>{if(a.unlocked_at!=null){const i=d>0&&(a.unlocked_at??0)>d;return e.jsxs("div",{className:`ach-tile unlocked${i?" just-unlocked":""}`,children:[a.icon??""," ",a.title,e.jsxs("span",{className:"ach-detail",children:["unlocked ",oe(a.unlocked_at)]})]},a.id)}return e.jsxs("div",{className:"ach-tile locked",children:["??? ",a.title]},a.id)})]})]})}function I(t){return(Math.round(t*10)/10).toString()+"%"}function D(t){return t!=null?new Date(t).toLocaleString():"—"}function O(t){return t&&typeof t=="object"?t:{}}function ce(t){return t.split("/").pop()||t}function _({title:t,rows:c,badge:n,renderValue:h}){return e.jsxs("div",{className:"lb-card",children:[e.jsxs("h3",{children:[t,n]}),c.length===0?e.jsx("div",{className:"lb-empty",children:"—"}):e.jsx("table",{children:e.jsx("tbody",{children:c.map((l,d)=>e.jsxs("tr",{children:[e.jsx("td",{title:l.repo_root,children:ce(l.repo_root)}),e.jsx("td",{className:"num",children:h(l)})]},`${l.repo_root}-${d}`))})})]})}function de(){const[t,c]=s.useState({}),[n,h]=s.useState(0),[l,d]=s.useState([]),[u,a]=s.useState(!1),[i,f]=s.useState(!0),[o,g]=s.useState(null),r=s.useRef(0),p=s.useCallback(async()=>{try{const[b,y,x,N,E,V]=await Promise.all([L({metric:"cache",limit:25}),L({metric:"dedupe",limit:25}),L({metric:"turns",limit:25}),L({metric:"mega_cache",limit:25}),L({metric:"repos",limit:1}),W()]),U=N.find(P=>P.ts>r.current&&P.value>100);r.current>0&&U&&(g(`oopsie! cache went to ${Math.round(U.value)}% — MEGA CACHE 🥧`),setTimeout(()=>g(null),4e3)),N.length>0&&(r.current=Math.max(...N.map(P=>P.ts))),c({cache:b,dedupe:y,turns:x,mega_cache:N}),h(E[0]?.value??0),d(V)}catch{}finally{f(!1)}},[]);s.useEffect(()=>{let b=!0;const y=async()=>{b&&await p()};y();const x=setInterval(()=>void y(),15e3);return()=>{b=!1,clearInterval(x)}},[p]),s.useEffect(()=>{let b=!0;const y=async()=>{try{const N=await F();b&&(a(!!N.game_mode_on),N.theme&&(document.documentElement.dataset.theme=N.theme))}catch{}};y();const x=setInterval(()=>void y(),15e3);return()=>{b=!1,clearInterval(x)}},[]);const S=t.mega_cache??[];let v=null,w=null;for(const b of S){(v==null||b.value>v)&&(v=b.value);const y=O(b.meta),x=y.firstSeenTs??y.firstSeen??b.ts;(w==null||x<w)&&(w=x)}const k=v!=null&&v>100,j=t.turns??[],M=j.reduce((b,y)=>Math.max(b,y.value),0),z=Math.floor(Math.log2(M+1))+1,R=(t.cache?.length??0)>0||(t.dedupe?.length??0)>0||j.length>0||S.length>0||n>0;return e.jsxs("div",{className:`game-tab${u?" game-mode-on":""}`,children:[o!=null&&e.jsx("div",{className:"mega-cache-toast show",children:o}),k&&e.jsxs("div",{className:"mega-cache-banner",children:["🥧"," MEGA CACHE! peak ",I(v)," — first reached ",D(w)]}),k&&e.jsxs("div",{className:"achievement-tile unlocked",children:["🏆"," Opie's Wild Ride",e.jsxs("span",{className:"ach-detail",children:["best ",I(v)," · first ",D(w)]})]}),e.jsx("h2",{children:"High Scores"}),!R&&!i&&e.jsx("div",{className:"game-empty",children:"No scores yet — run a session with game mode on."}),R&&e.jsxs("div",{className:"game-leaderboards",children:[e.jsx(_,{title:"Cache %",rows:t.cache??[],renderValue:b=>I(b.value)}),e.jsx(_,{title:"Dedupe (collapsed)",rows:t.dedupe??[],renderValue:b=>b.value.toLocaleString()}),e.jsx(_,{title:"Turns",rows:j,badge:j.length>0?e.jsxs("span",{className:"lvl-badge",children:["LVL ",z]}):void 0,renderValue:b=>b.value.toLocaleString()}),e.jsx(_,{title:"MEGA CACHE trophies",rows:S,renderValue:b=>e.jsxs(e.Fragment,{children:[I(b.value),e.jsx("span",{className:"lb-meta",children:D(O(b.meta).firstSeenTs??O(b.meta).firstSeen??b.ts)})]})})]}),n>0&&e.jsx("div",{className:"repos-badge-line",children:e.jsxs("span",{className:"repos-badge",children:[n," repos"]})}),e.jsx("h3",{children:"Achievements"}),e.jsx(G,{achievements:l})]})}function me(){const[t,c]=s.useState([]),[n,h]=s.useState(!0),[l,d]=s.useState(null),u=s.useCallback(async()=>{try{const a=await W();c(a),d(null)}catch(a){d(a instanceof Error?a:new Error(String(a)))}finally{h(!1)}},[]);return s.useEffect(()=>{let a=!0;const i=async()=>{a&&await u()};i();const f=setInterval(()=>void i(),15e3);return()=>{a=!1,clearInterval(f)}},[u]),n&&t.length===0?e.jsx("div",{className:"tab-stub",children:"Loading achievements…"}):l&&t.length===0?e.jsxs("div",{className:"tab-stub",children:["Error: ",l.message]}):e.jsxs("div",{className:"achievements-tab",children:[e.jsx("h2",{children:"Achievements"}),e.jsx(G,{achievements:t})]})}const H=[{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"}}],$=H.map(t=>t.id),T={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 ue(t,c,n){let h=t.toLocaleString();return c!=null&&n>0&&(h+=` (${Math.round(c*100)}% of ${n.toLocaleString()})`),h}function he(t){return`${Math.round((t||0)*100)}%`}function fe(){const[t,c]=s.useState(null),[n,h]=s.useState(null),[l,d]=s.useState(!1);s.useEffect(()=>{let r=!0;const p=async()=>{try{const v=await K();r&&c(v)}catch{}};p();const S=setInterval(()=>void p(),5e3);return()=>{r=!1,clearInterval(S)}},[]),s.useEffect(()=>{let r=!0;const p=async()=>{try{const v=await F();r&&(h(v),v.theme&&(document.documentElement.dataset.theme=v.theme))}catch{}};p();const S=setInterval(()=>void p(),5e3);return()=>{r=!1,clearInterval(S)}},[]);const u=s.useCallback(async r=>{d(!0);try{const p=await q(r);h(p),p.theme&&(document.documentElement.dataset.theme=p.theme)}catch{}d(!1)},[]),a=n?.game_mode_on??!1,i=n?.theme??"transparent",f=n?.tui_display_mode??"full",o=t?.config,g=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:T.gameMode,children:[e.jsx("input",{type:"checkbox",checked:a,onChange:r=>u({game_mode_on:r.currentTarget.checked}),disabled:l}),"Game Mode"]})}),e.jsx("div",{className:"settings-row",children:e.jsxs("label",{title:T.theme,children:["Theme",e.jsx("select",{value:i,onChange:r=>u({theme:r.currentTarget.value}),disabled:l,children:H.map(r=>e.jsx("option",{value:r.id,children:r.label},r.id))}),e.jsx("button",{type:"button",disabled:l,className:"theme-cycle-btn",title:"Cycle to the next theme (P3)",onClick:()=>{const r=$.indexOf(i),p=$[(r<0?0:r+1)%$.length];p&&u({theme:p})},children:"Next theme →"})]})}),e.jsx("div",{className:"settings-row",children:e.jsxs("label",{title:T.tuiMode,children:["TUI Mode",e.jsxs("select",{value:f,onChange:r=>u({tui_display_mode:r.currentTarget.value}),disabled:l,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:T.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:T.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:T.pressure,children:"Pressure"}),e.jsx("span",{className:"config-value",children:t?he(t.pressure):"—"})]}),e.jsxs("div",{className:"config-item",children:[e.jsx("span",{className:"config-label",title:T.threshold,children:"Threshold"}),e.jsx("span",{className:"config-value",children:o?ue(o.thresholdTokens,o.tierPct,g):"—"})]}),e.jsxs("div",{className:"config-item",children:[e.jsx("span",{className:"config-label",title:T.fastGate,children:"Fast Gate"}),e.jsx("span",{className:"config-value",children:o?`${o.fastGatePct}%`:"—"})]}),e.jsxs("div",{className:"config-item",children:[e.jsx("span",{className:"config-label",children:"Auto"}),e.jsx("span",{className:"config-value",children:o?o.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:o?.anchorUserMessages??"—"})]})]})]})]})}const C={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 ge(){const[t,c]=s.useState(null),[n,h]=s.useState(null),l=s.useCallback(()=>{X().then(c).catch(f=>h(f instanceof Error?f.message:String(f)))},[]);s.useEffect(()=>{l()},[l]),s.useEffect(()=>{const f=setInterval(l,3e4);return()=>clearInterval(f)},[l]);const d=t?.status==="ok",u=t?.status==="ok"?"Working":t?.status==="unreachable"?"Unreachable":"Error",a=d?"#4caf50":"#f44336",i=d?"✓":"✗";return e.jsxs("div",{style:C.section,children:[e.jsx("h3",{style:C.sectionTitle,children:"Embedder Health"}),n&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:["Error: ",n]}),!t&&!n&&e.jsx("p",{style:{color:"#888",fontSize:"0.85rem"},children:"Probing embedder..."}),t&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:C.row,children:[e.jsxs("span",{style:{...C.label,color:`${a}`},children:[i," ",u,":"]}),e.jsxs("span",{style:C.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:C.row,children:[e.jsx("span",{style:C.label,children:"Endpoint:"}),e.jsx("span",{style:C.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 xe({title:t,children:c}){const[n,h]=s.useState(!0),l=`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:()=>h(d=>!d),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":n,"aria-controls":l,children:[e.jsx("span",{children:t}),e.jsx(Y,{className:J("h-4 w-4 text-muted-foreground transition-transform",n&&"rotate-180"),"aria-hidden":"true"})]}),n&&e.jsx("div",{id:l,className:"divide-y divide-border px-4 py-1",children:c})]})}const pe="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 be(){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 je({setting:t,id:c,llmActive:n,saving:h,onUpdate:l}){const[d,u]=s.useState(null),a=t.requiresLlm&&!n,i=s.useRef(null);s.useEffect(()=>()=>{i.current&&clearTimeout(i.current)},[]);const f=s.useCallback(r=>{l(t.key,r).then(p=>u(p)).catch(p=>u(p instanceof Error?p.message:String(p)))},[l,t.key]),o=s.useCallback(r=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>f(r),500)},[f]),g=h||a;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:`${c}-input`,className:"cursor-pointer",children:t.label}),t.requiresLlm&&!n&&e.jsx(be,{})]}),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(le,{id:`${c}-input`,checked:!!t.value,disabled:g||a,onCheckedChange:r=>f(String(r)),"aria-label":t.label}):e.jsxs(e.Fragment,{children:[e.jsx("input",{id:`${c}-input`,type:t.type==="number"?"number":"text",defaultValue:String(t.value??""),min:t.min,max:t.max,disabled:g,onChange:r=>o(r.target.value),className:`${pe} ${t.type==="number"?"w-24":"w-56"}`}),t.unit&&e.jsx("span",{className:"text-xs text-muted-foreground",children:t.unit})]})})]}),d&&e.jsxs("p",{className:"mt-1 text-xs text-danger",children:["Error: ",d]})]})}function ve(){const[t,c]=s.useState(null),[n,h]=s.useState(null),[l,d]=s.useState(!1),[u,a]=s.useState(null),i=s.useCallback(()=>{Q().then(c).catch(o=>h(o instanceof Error?o.message:String(o)))},[]);s.useEffect(()=>{i()},[i]);const f=s.useCallback(async(o,g)=>{d(!0);try{const r=await Z({key:o,value:g});return a(r.restartRequired?"Saved — restart pi to apply changes.":"Saved."),i(),null}catch(r){return r instanceof Error?r.message:String(r)}finally{d(!1)}},[i]);return e.jsxs("div",{className:"flex flex-col gap-3",children:[n&&e.jsxs("p",{className:"text-sm text-danger",children:["Error: ",n]}),!t&&!n&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading settings..."}),t?.categories.map(o=>e.jsx(xe,{title:o.name,children:o.settings.map(g=>e.jsx(je,{setting:g,id:`${o.name.replace(/[^a-z0-9]+/gi,"-")}-${g.key}`,llmActive:t.llmActive,saving:l,onUpdate:f},g.key))},o.name)),u&&e.jsx("div",{className:"mt-1 rounded-md border border-warning/40 bg-warning/10 p-2 text-xs text-warning",role:"status",children:u})]})}const m={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 ye(){const[t,c]=s.useState(null),[n,h]=s.useState(null),[l,d]=s.useState(null),[u,a]=s.useState(null),[i,f]=s.useState(!1),[o,g]=s.useState(null),[r,p]=s.useState(null),[S,v]=s.useState(null),[w,k]=s.useState(""),j=s.useCallback(()=>{ee().then(c).catch(x=>d(x instanceof Error?x.message:String(x)))},[]),M=s.useCallback((x,N)=>{g(x),v(null),p(null),te({embedder:x,url:N}).then(E=>{p(E),g(null),j()}).catch(E=>{v(E instanceof Error?E.message:String(E)),g(null)})},[j]),z=s.useCallback(()=>{f(!0),a(null),se().then(x=>{h(x),f(!1)}).catch(x=>{a(x instanceof Error?x.message:String(x)),f(!1)})},[]);s.useEffect(()=>{j()},[j]),s.useEffect(()=>{const x=setInterval(j,3e4);return()=>clearInterval(x)},[j]);const R=x=>{switch(x){case"trigram":return"TrigramEmbedder (heuristic, default)";case"http":return"HTTP Embedder (BYO localhost)";case"minilm":return"MiniLM (experimental)";default:return"Unknown"}},b=t?.currentEmbedder==="trigram"&&e.jsxs("div",{style:m.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."]}),y=x=>{const N=x?"#1a5a1a":"#3a1a1a",E=x?"#4caf50":"#f44336";return e.jsx("span",{style:{...m.badge,background:N,color:E},children:x?"Detected":"Not found"})};return e.jsxs("div",{style:m.container,children:[e.jsx("h2",{style:{fontSize:"1.3rem",marginTop:0,marginBottom:"1rem"},children:"Embedder Setup"}),e.jsx(ge,{}),e.jsxs("div",{style:m.section,children:[e.jsx("h3",{style:m.sectionTitle,children:"Current Embedder Configuration"}),l&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:["Error: ",l]}),t&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:m.row,children:[e.jsx("span",{style:m.label,children:"Active Embedder:"}),e.jsx("span",{style:m.value,children:R(t.currentEmbedder)})]}),"configuredEmbedder"in t&&t.configuredEmbedder!==t.currentEmbedder&&e.jsxs("div",{style:m.warning,children:[e.jsx("strong",{children:"Configured but not active:"})," ",R(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:{...m.row,color:"#ff9800"},children:[e.jsx("span",{style:m.label,children:"Status:"}),e.jsx("span",{style:m.value,children:"Restart required to activate the configured embedder"})]}),e.jsxs("div",{style:m.row,children:[e.jsx("span",{style:m.label,children:"Embedding URL:"}),e.jsx("span",{style:m.value,children:t.embeddingUrl??e.jsx("span",{style:{color:"#888"},children:"not set"})})]}),e.jsxs("div",{style:m.row,children:[e.jsx("span",{style:m.label,children:"Embed Cache:"}),e.jsx("span",{style:m.value,children:t.embedCache??e.jsx("span",{style:{color:"#888"},children:"not set"})})]}),e.jsxs("div",{style:m.row,children:[e.jsx("span",{style:m.label,children:"MiniLM:"}),e.jsx("span",{style:m.value,children:t.minilm?"enabled":"disabled"})]}),b]}),!t&&!l&&e.jsx("p",{style:{color:"#888",fontSize:"0.85rem"},children:"Loading configuration..."})]}),e.jsxs("div",{style:m.section,children:[e.jsx("h3",{style:m.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."}),n&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:m.detectRow,children:[e.jsx("span",{children:e.jsx("strong",{children:"Ollama"})}),n.ollama!==null?e.jsxs("span",{children:[y(n.ollama.installed),n.ollama.installed&&e.jsx("span",{style:{fontSize:"0.8rem",color:"#a0a0c0",marginLeft:"0.5rem"},children:n.ollama.running?`server running, ${n.ollama.models.length} model(s)`:"server not running"})]}):e.jsx("span",{style:{color:"#888",fontSize:"0.85rem"},children:"not checked"})]}),e.jsxs("div",{style:m.detectRow,children:[e.jsx("span",{children:e.jsx("strong",{children:"llama.cpp"})}),n.llamaCpp!==null?e.jsxs("span",{children:[y(n.llamaCpp.installed),n.llamaCpp.installed&&n.llamaCpp.detail&&e.jsx("span",{style:{fontSize:"0.8rem",color:"#a0a0c0",marginLeft:"0.5rem"},children:n.llamaCpp.detail})]}):e.jsx("span",{style:{color:"#888",fontSize:"0.85rem"},children:"not checked"})]}),e.jsxs("div",{style:m.detectRow,children:[e.jsx("span",{children:e.jsx("strong",{children:"ONNX Runtime"})}),n.onnx!==null?e.jsxs("span",{children:[y(n.onnx.installed),n.onnx.installed&&n.onnx.detail&&e.jsx("span",{style:{fontSize:"0.8rem",color:"#a0a0c0",marginLeft:"0.5rem"},children:n.onnx.detail})]}):e.jsx("span",{style:{color:"#888",fontSize:"0.85rem"},children:"not checked"})]}),n.error&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.8rem",marginTop:"0.5rem"},children:["Detection error: ",n.error]})]}),u&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem"},children:["Error: ",u]}),e.jsxs("div",{style:{marginTop:"1rem"},children:[e.jsx("button",{style:m.button,onClick:z,disabled:i,children:i?"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."]})]}),n&&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:{...m.button,opacity:n.ollama?.installed?1:.4},onClick:()=>M("ollama"),disabled:!n.ollama?.installed||o!==null,children:o==="ollama"?"Writing...":"Use Ollama"}),e.jsx("button",{style:{...m.button,opacity:n.llamaCpp?.installed?1:.4},onClick:()=>M("llama"),disabled:!n.llamaCpp?.installed||o!==null,children:o==="llama"?"Writing...":"Use llama.cpp"}),e.jsx("button",{style:{...m.button,background:"#444"},onClick:()=>M("trigram"),disabled:o!==null,children:o==="trigram"?"Writing...":"Use Trigram (default)"})]}),r&&e.jsx("div",{style:m.warning,children:r.alreadyActive?"Already active — no restart needed.":`Configured ${r.embedder}. Restart pi to activate (config written to ${r.envPath}).`}),S&&e.jsxs("p",{style:{color:"#f44336",fontSize:"0.85rem",marginTop:"0.5rem"},children:["Configure error: ",S]})]})]}),e.jsxs("div",{style:m.section,children:[e.jsx("h3",{style:m.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:w,onChange:x=>k(x.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:{...m.button,opacity:w?1:.4},onClick:()=>M("custom",w),disabled:!w||o!==null,children:o==="custom"?"Writing...":"Use Custom URL"})]}),e.jsxs("div",{style:m.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."]})]}),e.jsxs("div",{style:m.section,children:[e.jsx("h3",{style:m.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:"})," Install"," ",e.jsx("code",{children:"onnxruntime-node"})," in the project root. Not yet integrated — see docs for manual setup."]})]})]}),e.jsxs("div",{style:m.section,children:[e.jsx("h3",{style:m.sectionTitle,children:"Settings"}),e.jsx(ve,{})]})]})}function A(t){return t>=1e6?`${(t/1e6).toFixed(2)}M`:t>=1e3?`${Math.round(t/1e3)}K`:String(t)}function Se(t,c,n){if(t<=0)return"—";const l=(c>0?c:Math.ceil(t*.1))+Math.ceil(t*(n/100)),d=t-l;return d<=0?"0 (at risk)":`${A(d)} tokens`}function B({label:t,value:c,min:n,max:h,step:l=1,onChange:d,warning:u}){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 ${u?"text-warning":"text-fg"}`,title:u,children:[c,"%"]})]}),e.jsx("input",{type:"range",min:n,max:h,step:l,value:c,onChange:a=>d(Number(a.target.value)),className:"threshold-slider w-full"}),u&&e.jsxs("p",{className:"text-[10px] text-warning",children:["⚠ ",u]})]})}function we({model:t,defaults:c,safetyRange:n,fireRange:h,onSave:l,onReset:d,saving:u}){const[a,i]=s.useState(t.threshold.safetyMarginPct),[f,o]=s.useState(t.threshold.firePointPct),[g,r]=s.useState(!1),[p,S]=s.useState(null);s.useEffect(()=>{i(t.threshold.safetyMarginPct),o(t.threshold.firePointPct),r(!1)},[t.threshold.safetyMarginPct,t.threshold.firePointPct]);const v=a<5?'Low safety margin — risks "conversation too long" errors when a single turn injects a large tool output between gate fires.':void 0,w=f>85?"High fire point — compaction may trigger close to the window cap; a single large turn can overshoot before the gate fires.":void 0,k=s.useCallback(async()=>{S(null);try{await l(t.modelId,a,f),r(!1)}catch(j){S(j instanceof Error?j.message:String(j))}},[t.modelId,a,f,l]);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," · ",A(t.contextWindow)," window ·"," ",A(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:Se(t.contextWindow,t.maxTokens,a)})]}),e.jsxs("div",{children:["Compaction fires at:"," ",e.jsx("span",{className:"font-mono text-fg",children:A(Math.ceil(t.contextWindow*(f/100)))})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[e.jsx(B,{label:"Safety margin",value:a,min:n[0],max:n[1],onChange:j=>{i(j),r(!0)},warning:v}),e.jsx(B,{label:"Fire point",value:f,min:h[0],max:h[1],onChange:j=>{o(j),r(!0)},warning:w})]}),e.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[e.jsx("button",{type:"button",onClick:k,disabled:!g||u,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:g?"Save override":"Saved"}),t.threshold.isOverride&&e.jsxs("button",{type:"button",onClick:()=>d(t.modelId),disabled:u,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 (",c.safetyMarginPct,"% /"," ",c.firePointPct,"%)"]}),p&&e.jsx("span",{className:"text-[11px] text-error",children:p})]})]})}function Ne(){const[t,c]=s.useState(null),[n,h]=s.useState(!0),[l,d]=s.useState(null),[u,a]=s.useState(!1),i=s.useCallback(async()=>{try{d(null),c(await ne())}catch(g){d(g instanceof Error?g.message:String(g))}finally{h(!1)}},[]);s.useEffect(()=>{i()},[i]);const f=s.useCallback(async(g,r,p)=>{a(!0);try{await ae({modelId:g,safetyMarginPct:r,firePointPct:p}),await i()}finally{a(!1)}},[i]),o=s.useCallback(async g=>{a(!0);try{await re(g),await i()}finally{a(!1)}},[i]);return n?e.jsx("div",{className:"p-4 text-sm text-fg-muted",children:"Loading thresholds…"}):l?e.jsxs("div",{className:"p-4 text-sm text-error",children:["Error: ",l]}):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(g=>e.jsx(we,{model:g,defaults:t.defaults,safetyRange:t.defaults.safetyMarginRange,fireRange:t.defaults.firePointRange,onSave:f,onReset:o,saving:u},g.modelId))})]}):e.jsx("div",{className:"p-4 text-sm text-fg-muted",children:"No data."})}const Ee=[{id:"embedder",label:"Embedder"},{id:"thresholds",label:"Thresholds"},{id:"config",label:"Config"},{id:"game",label:"Game Mode"},{id:"achievements",label:"Achievements"}];function Me(){const[t,c]=s.useState("embedder");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:Ee.map(n=>e.jsx(ie,{pressed:t===n.id,onClick:()=>c(n.id),children:n.label},n.id))}),t==="embedder"&&e.jsx(ye,{}),t==="thresholds"&&e.jsx(Ne,{}),t==="config"&&e.jsx(fe,{}),t==="game"&&e.jsx(de,{}),t==="achievements"&&e.jsx(me,{})]})}export{Me as default};
2
- //# sourceMappingURL=SetupTab-BTBGyppF.js.map