pi-mega-compact 0.13.6 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/README.md +13 -6
  2. package/dist/extensions/dashboard-server/api-contracts/endpoints/registry.js +6 -0
  3. package/dist/extensions/dashboard-server/index-reader.js +50 -25
  4. package/dist/extensions/dashboard-server/resolve-snapshot.js +81 -0
  5. package/dist/extensions/dashboard-server/routes-core.js +8 -3
  6. package/dist/extensions/dashboard-server/routes-rag-settings-helpers.js +7 -0
  7. package/dist/extensions/dashboard-server/routes-raptor.js +60 -0
  8. package/dist/extensions/dashboard-server/routes-repo.js +5 -1
  9. package/dist/extensions/dashboard-server/routes-sessions.js +6 -3
  10. package/dist/extensions/dashboard-server/routes.js +1 -1
  11. package/dist/extensions/dashboard-server/server.js +3 -1
  12. package/dist/extensions/mega-pipeline/recall.js +24 -16
  13. package/dist/extensions/mega-runtime/capture-model.js +5 -2
  14. package/dist/src/config/dedup.js +2 -1
  15. package/dist/src/costApi.js +113 -0
  16. package/dist/src/dedup/raptor/incremental.js +31 -3
  17. package/dist/src/dedup/raptor/index.js +10 -6
  18. package/dist/src/pricing.js +8 -0
  19. package/dist/src/vector-search.js +3 -3
  20. package/extensions/dashboard-client/dist/assets/{AreaChart-KAmp_6bL.js → AreaChart-C68tGr2J.js} +2 -2
  21. package/extensions/dashboard-client/dist/assets/{AreaChart-KAmp_6bL.js.map → AreaChart-C68tGr2J.js.map} +1 -1
  22. package/extensions/dashboard-client/dist/assets/{CacheTab-Bk-gm-R0.js → CacheTab-CDyZqMO-.js} +2 -2
  23. package/extensions/dashboard-client/dist/assets/{CacheTab-Bk-gm-R0.js.map → CacheTab-CDyZqMO-.js.map} +1 -1
  24. package/extensions/dashboard-client/dist/assets/EventsTab-ByPYMJVG.js +2 -0
  25. package/extensions/dashboard-client/dist/assets/EventsTab-ByPYMJVG.js.map +1 -0
  26. package/extensions/dashboard-client/dist/assets/{HealthTab-D-IzmV29.js → HealthTab-CeHQR0py.js} +2 -2
  27. package/extensions/dashboard-client/dist/assets/{HealthTab-D-IzmV29.js.map → HealthTab-CeHQR0py.js.map} +1 -1
  28. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-CrlkCFVj.js → MaintenanceTab-ceTD_c1A.js} +2 -2
  29. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-CrlkCFVj.js.map → MaintenanceTab-ceTD_c1A.js.map} +1 -1
  30. package/extensions/dashboard-client/dist/assets/MemoryMapTab-CRUdVR7u.js +2 -0
  31. package/extensions/dashboard-client/dist/assets/{MemoryMapTab-DHUdZ7RR.js.map → MemoryMapTab-CRUdVR7u.js.map} +1 -1
  32. package/extensions/dashboard-client/dist/assets/{MetricsTab-B7I4HWVg.js → MetricsTab-DP7Kmdu9.js} +2 -2
  33. package/extensions/dashboard-client/dist/assets/{MetricsTab-B7I4HWVg.js.map → MetricsTab-DP7Kmdu9.js.map} +1 -1
  34. package/extensions/dashboard-client/dist/assets/{OverviewTab-K6j4ZI7u.js → OverviewTab-4CGP0djv.js} +2 -2
  35. package/extensions/dashboard-client/dist/assets/{OverviewTab-K6j4ZI7u.js.map → OverviewTab-4CGP0djv.js.map} +1 -1
  36. package/extensions/dashboard-client/dist/assets/{ReposTab-BSRWhn56.js → ReposTab-DUrP7Efa.js} +2 -2
  37. package/extensions/dashboard-client/dist/assets/{ReposTab-BSRWhn56.js.map → ReposTab-DUrP7Efa.js.map} +1 -1
  38. package/extensions/dashboard-client/dist/assets/{SessionsTab-BXdizHN1.js → SessionsTab-Cg-IsijD.js} +2 -2
  39. package/extensions/dashboard-client/dist/assets/{SessionsTab-BXdizHN1.js.map → SessionsTab-Cg-IsijD.js.map} +1 -1
  40. package/extensions/dashboard-client/dist/assets/{SetupTab-CAgyfqY3.js → SetupTab-ZE1daXjN.js} +2 -2
  41. package/extensions/dashboard-client/dist/assets/{SetupTab-CAgyfqY3.js.map → SetupTab-ZE1daXjN.js.map} +1 -1
  42. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-DwgCzPD9.js → TimeSavedCard-BkTgi3Af.js} +2 -2
  43. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-DwgCzPD9.js.map → TimeSavedCard-BkTgi3Af.js.map} +1 -1
  44. package/extensions/dashboard-client/dist/assets/{TurnsTab-CVKcStBp.js → TurnsTab-CZvudHQF.js} +2 -2
  45. package/extensions/dashboard-client/dist/assets/{TurnsTab-CVKcStBp.js.map → TurnsTab-CZvudHQF.js.map} +1 -1
  46. package/extensions/dashboard-client/dist/assets/{WikiTab-BNohxTbs.js → WikiTab-BVAnGp8_.js} +2 -2
  47. package/extensions/dashboard-client/dist/assets/{WikiTab-BNohxTbs.js.map → WikiTab-BVAnGp8_.js.map} +1 -1
  48. package/extensions/dashboard-client/dist/assets/{button-B4A-_dCA.js → button-CUrzhi2A.js} +2 -2
  49. package/extensions/dashboard-client/dist/assets/{button-B4A-_dCA.js.map → button-CUrzhi2A.js.map} +1 -1
  50. package/extensions/dashboard-client/dist/assets/{card-Cjn7Ifoe.js → card-BsfojHfp.js} +2 -2
  51. package/extensions/dashboard-client/dist/assets/{card-Cjn7Ifoe.js.map → card-BsfojHfp.js.map} +1 -1
  52. package/extensions/dashboard-client/dist/assets/{index-CQjCLvv7.js → index-OM3w-l2T.js} +11 -11
  53. package/extensions/dashboard-client/dist/assets/index-OM3w-l2T.js.map +1 -0
  54. package/extensions/dashboard-client/dist/assets/pricing-DkYp8-vi.js +2 -0
  55. package/extensions/dashboard-client/dist/assets/pricing-DkYp8-vi.js.map +1 -0
  56. package/extensions/dashboard-client/dist/assets/{switch-CcdXX0Zm.js → switch-qSz2Un3t.js} +2 -2
  57. package/extensions/dashboard-client/dist/assets/{switch-CcdXX0Zm.js.map → switch-qSz2Un3t.js.map} +1 -1
  58. package/extensions/dashboard-client/dist/assets/{toggle-KdBnFLu3.js → toggle-DyBKcLe-.js} +2 -2
  59. package/extensions/dashboard-client/dist/assets/{toggle-KdBnFLu3.js.map → toggle-DyBKcLe-.js.map} +1 -1
  60. package/extensions/dashboard-client/dist/assets/{useSSE-B6t44vzc.js → useSSE-DqVouqww.js} +2 -2
  61. package/extensions/dashboard-client/dist/assets/{useSSE-B6t44vzc.js.map → useSSE-DqVouqww.js.map} +1 -1
  62. package/extensions/dashboard-client/dist/index.html +1 -1
  63. package/extensions/dashboard-client/src/api/client.ts +10 -0
  64. package/extensions/dashboard-client/src/components/EventStream.tsx +1 -1
  65. package/extensions/dashboard-client/src/tabs/MemoryMapTab/RaptorTreeView.tsx +58 -4
  66. package/extensions/dashboard-server/api-contracts/endpoints/registry.ts +9 -1
  67. package/extensions/dashboard-server/api-contracts/index.ts +2 -2
  68. package/extensions/dashboard-server/api-contracts/raptor.ts +19 -0
  69. package/extensions/dashboard-server/index-reader.ts +29 -4
  70. package/extensions/dashboard-server/resolve-snapshot.ts +98 -0
  71. package/extensions/dashboard-server/routes-core.ts +8 -3
  72. package/extensions/dashboard-server/routes-rag-settings-helpers.ts +17 -0
  73. package/extensions/dashboard-server/routes-raptor.ts +88 -1
  74. package/extensions/dashboard-server/routes-repo.ts +5 -1
  75. package/extensions/dashboard-server/routes-sessions.ts +6 -3
  76. package/extensions/dashboard-server/routes.ts +1 -1
  77. package/extensions/dashboard-server/server.ts +2 -0
  78. package/extensions/mega-pipeline/recall.ts +30 -21
  79. package/extensions/mega-runtime/capture-model.ts +5 -2
  80. package/package.json +1 -1
  81. package/src/config/dedup.ts +2 -1
  82. package/src/costApi.ts +131 -0
  83. package/src/dedup/raptor/incremental.ts +48 -3
  84. package/src/dedup/raptor/index.ts +10 -6
  85. package/src/pricing.ts +8 -0
  86. package/src/vector-search.ts +3 -3
  87. package/extensions/dashboard-client/dist/assets/EventsTab-Cyylo0of.js +0 -2
  88. package/extensions/dashboard-client/dist/assets/EventsTab-Cyylo0of.js.map +0 -1
  89. package/extensions/dashboard-client/dist/assets/MemoryMapTab-DHUdZ7RR.js +0 -2
  90. package/extensions/dashboard-client/dist/assets/index-CQjCLvv7.js.map +0 -1
  91. package/extensions/dashboard-client/dist/assets/pricing-CvE4NllQ.js +0 -2
  92. package/extensions/dashboard-client/dist/assets/pricing-CvE4NllQ.js.map +0 -1
package/README.md CHANGED
@@ -13,13 +13,14 @@ A local-first context compressor for the [pi coding agent](https://github.com/ea
13
13
  - **Durable memory** — on a cadence the store auto-reviews and safe-keeps decisions, facts, and preferences as first-class RAG memories, so long-running projects remember what mattered.
14
14
  - **Prompt-cache optimization** — message separation + cache striping (default OFF, opt-in). Targets 82-90% cache hit rate by structuring context around provider cache boundaries. Enables with `MEGACOMPACT_MESSAGE_SEPARATION` and `MEGACOMPACT_CACHE_STRIPING`.
15
15
  - **Context health + KV cache poison validation** (v0.12) — a real-time composite 0-1 health score per turn from five sub-scores (drift, output quality, error rate, cache health, cache poison). Catches garbled/hallucinated output and provider-side KV-cache corruption *before* they waste tokens — the failure mode where a large-context model (e.g. DeepSeek V4 Flash, 1M window) degrades at <1% usage. Tri-layer cache poison validation: prefix hash (L1 FNV-1a), output-quality-by-cache-hit (L2 semantic), error-rate correlation (L3 behavioral). The dashboard **Health tab** shows a gauge, sparkline, sub-score bars, alerts, and per-model breakdown. Auto-mitigation (force compaction on degraded context, prefix break on poisoned cache) is default OFF — toggle it in the Maintenance tab.
16
- - **RAG suite** — query reformulation (TF-IDF + RRF), tiered routing (L0 cache -> L1 FTS5 -> L2 PGlite), recall-quality metrics (CRAG), memory graph, and HyDE (hypothetical document embeddings). All default ON with graceful fallback — opt out via `MEGACOMPACT_<NAME>_DISABLED=true`. HyDE auto-activates only when an LLM embedder (Ollama/HTTP) is configured — it's a no-op with the default TrigramEmbedder. Toggle any flag from the dashboard Setup tab.
17
- - **Stacked memory graph** — the dashboard shows memory composition over time from 3 content sources (turns, durable memories, wiki) with a 9-gate validation system and a graph-health indicator. Per-model provider cache breakdown in the Cache tab.
16
+ - **RAG suite** — query reformulation (TF-IDF + RRF), tiered routing (L0 cache -> L1 FTS5 -> L2 PGlite), recall-quality metrics (CRAG), memory graph, and HyDE (hypothetical document embeddings). All default ON with graceful fallback — opt out via `MEGACOMPACT_<NAME>_DISABLED=true`. HyDE auto-activates only when an LLM embedder (Ollama/HTTP) is configured — it's a no-op with the default TrigramEmbedder. The dashboard **Metrics tab** (v0.13) shows RAG recall-quality metrics (pass rate, avg lift, telemetry turns, HyDE runs) and the Overview tab has a RAG health card. Toggle any flag from the dashboard Setup tab.
18
17
  - **Debug bundle** — Maintenance tab in the dashboard has a **Gather Debug Logs** button that collects events, config, and store state into a shareable archive for bug reports.
19
- - **Local-first by default** — node:sqlite + trigram embeddings by default, zero calls off your machine. Bring your own localhost embedder (Ollama, ONNX, TEI) for better semantic matches — the embedder endpoint is loopback-only by default (`MEGACOMPACT_ALLOW_REMOTE_EMBEDDER=1` opts in to a remote/third-party endpoint). The optional dashboard is localhost-only. No cloud, no API calls, no telemetry.
18
+ - **Local-first by default** — node:sqlite + trigram embeddings by default, zero calls off your machine. Bring your own localhost embedder (Ollama, ONNX, TEI) for better semantic matches — the embedder endpoint is loopback-only by default (`MEGACOMPACT_ALLOW_REMOTE_EMBEDDER=1` opts in to a remote/third-party endpoint). The optional dashboard is localhost-only. No cloud, no API calls, no telemetry. The optional Cost API lookup (`MEGACOMPACT_COST_API_ENABLED`, default OFF) is the one network exception — it fetches model pricing from a user-configured endpoint to show real $/token rates in the dashboard.
20
19
  - **Team-run aware** — fine-grained durable trim fires at agent settle during sub-agent runs, so long multi-agent work doesn't just collapse at the end.
21
- - **Multi-pi dashboard** — one dashboard tab per active pi process with the context stack, per-repo stats, and a live SSE feed across all of them. The React SPA has 15 lazy-loaded tabs — **Overview**, **Cache**, **Sessions**, **Turns** (per-turn memory + recall + rewind), and **Health** (context-health gauge + cache-poison alerts) are primary; **Repos**, **Events**, **Config**, **Setup** (embedding wizard), **Metrics** (perf latency/TPS/CPU), **Game**, **Achievements**, **Topics** (wiki), **Memory Map** (D3 graph), and **Maintenance** (debug bundle) are advanced.
22
- - **Auto-categorizing wiki.** Every 3 compactions (seeds from turns before that), the store clusters your real memory embeddings (k-means) and labels each cluster with its most discriminative terms (TF-IDF) — no LLM, no Ollama, fully local. The dashboard **Wiki tab** browses topics, searches by label or term, and drills down into the member memories of each cluster.
20
+ - **Multi-pi dashboard** — one dashboard tab per active pi process with the context stack, per-repo stats, and a live SSE feed across all of them. The React SPA (Tailwind v3 + shadcn/ui, v0.13) has 12 lazy-loaded tabs — **Overview**, **Cache**, **Sessions**, and **Turns** (per-turn memory + recall + rewind) are primary; **Repos**, **Events**, **Setup** (embedding wizard + comprehensive settings panel), **Metrics** (perf latency/TPS/CPU + RAG recall quality), **Wiki** (auto-categorizing topic browser + evolution graph), **Memory Map** (D3 graph), **Maintenance** (debug bundle), and **Health** (context-health gauge + cache-poison alerts) are advanced. The Overview tab dynamically resolves the most recently active repo's snapshot so it always shows live data.
21
+ - **Auto-categorizing wiki.** Every 3 compactions (seeds from turns before that), the store clusters your real memory embeddings (k-means) and labels each cluster with its most discriminative terms (TF-IDF) — no LLM, no Ollama, fully local. The dashboard **Wiki tab** (v0.13) browses topics, searches by label or term, drills down into the member memories of each cluster, and shows a topic evolution graph over time. Curation supports rename/merge/split operations with durable overrides that survive full rebuilds.
22
+ - **Comprehensive settings panel** (v0.13.6) — every adjustable `MEGACOMPACT_*` env var is surfaced in the dashboard Setup tab, grouped by category (RAG Pipeline, Wiki/Turns, Dedup Tiers, Dedup Thresholds, RAPTOR Tuning). Toggle booleans, edit numerics with units, change strings — all write to `.mega-compact.env` via POST. The regression gate enforces that no new config flag ships without a dashboard entry.
23
+ - **Stacked memory graph** — the dashboard shows memory composition over time from 3 content sources (turns, durable memories, wiki) with a 9-gate validation system and a graph-health indicator. Per-model provider cache breakdown in the Cache tab.
23
24
 
24
25
  ## Install
25
26
 
@@ -85,6 +86,12 @@ Set env vars before starting pi. Defaults are in `src/config/dedup.ts`.
85
86
  | `MEGACOMPACT_CONTEXT_HEALTH_OUTPUT_QUALITY` | `true` | Sub-score: repetition, coherence, token-salad detection |
86
87
  | `MEGACOMPACT_CONTEXT_HEALTH_CACHE_POISON` | `true` | Sub-score: tri-layer KV cache poison validation |
87
88
  | `MEGACOMPACT_CONTEXT_HEALTH_MITIGATE` | `false` | Opt-in: auto-compaction on degraded context, prefix break on poisoned cache |
89
+ | `MEGACOMPACT_WIKI_ENHANCED` | `true` | Enhanced wiki with topic overrides + evolution tracking |
90
+ | `MEGACOMPACT_WIKI_INCREMENTAL` | `true` | Incremental wiki updates (no full rebuild) |
91
+ | `MEGACOMPACT_AUTO_WIKI` | `true` | Auto-generate wiki from turns |
92
+ | `MEGACOMPACT_NEW_UI` | `true` | Use the new Tailwind/shadcn dashboard shell |
93
+ | `MEGACOMPACT_COST_API_ENABLED` | `false` | Opt-in: fetch model pricing from an external API (PREVENT-PI-004 network exception). Enriches dashboard cost data for models not in the local pricing table |
94
+ | `MEGACOMPACT_COST_API_URL` | _(unset)_ | OpenRouter-compatible model pricing endpoint (e.g. `https://openrouter.ai/api/v1/models`). Only contacted when `MEGACOMPACT_COST_API_ENABLED=true` |
88
95
 
89
96
  Full config reference: [`docs/CONFIGURATION.md`](docs/CONFIGURATION.md)
90
97
 
@@ -107,7 +114,7 @@ Detailed architecture: [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md)
107
114
 
108
115
  ```bash
109
116
  npm run build # TypeScript compile
110
- npm test # Build + 1145 tests
117
+ npm test # Build + 1197 tests
111
118
  npm run lint # Type check + guardrails scan
112
119
  ```
113
120
 
@@ -259,6 +259,12 @@ export const ENDPOINTS = {
259
259
  path: "/api/raptor-tree",
260
260
  description: "Hierarchical RAPTOR tree (summary nodes by level) for a session; defaults to the latest session with nodes.",
261
261
  },
262
+ /** GET /api/raptor-build-history — Build history (coherence, depth, timeout) for a session. */
263
+ raptorBuildHistory: {
264
+ method: "GET",
265
+ path: "/api/raptor-build-history",
266
+ description: "RAPTOR build history rows (node/leaf count, depth, coherence score, timed_out) for a session; defaults to the latest session with builds.",
267
+ },
262
268
  /** GET /api/embedder-health — Round-trip a test embed through the active embedder. */
263
269
  embedderHealth: {
264
270
  method: "GET",
@@ -13,6 +13,8 @@ import { homedir } from "node:os";
13
13
  import { join } from "node:path";
14
14
  import { DatabaseSync } from "node:sqlite";
15
15
  import { readProviderCacheForRepo, } from "../../src/store/sqlite/perf-samples.js";
16
+ import { lookupModelInputRate } from "../../src/pricing.js";
17
+ import { costApiConfig, lookupCostApiPricing } from "../../src/costApi.js";
16
18
  export function getIndexDir() {
17
19
  const override = process.env.MEGACOMPACT_INDEX_DIR;
18
20
  if (override && override.trim() !== "")
@@ -37,31 +39,54 @@ export function readIndex() {
37
39
  const rows = db
38
40
  .prepare("SELECT * FROM repo_registry ORDER BY last_seen DESC")
39
41
  .all();
40
- const mapped = rows.map((r) => ({
41
- repoRoot: String(r.repo_root ?? ""),
42
- displayName: String(r.display_name ?? ""),
43
- stateDir: String(r.state_dir ?? ""),
44
- checkpointCount: Number(r.checkpoint_count ?? 0),
45
- tokensSaved: Number(r.tokens_saved ?? 0),
46
- compressedOriginalBytes: Number(r.compressed_original_bytes ?? 0),
47
- lastCompactedAt: r.last_compacted_at ?? null,
48
- provider: r.provider ?? null,
49
- providerName: r.provider_name ?? null,
50
- modelName: r.model_name ?? null,
51
- inputRate: r.input_rate ?? null,
52
- outputRate: r.output_rate ?? null,
53
- lastSeen: Number(r.last_seen ?? 0),
54
- // Defaults enriched below from each repo's own store.
55
- tokensKept: 0,
56
- tokensDropped: 0,
57
- sessions: 0,
58
- contextWindow: null,
59
- maxTokens: null,
60
- reasoning: null,
61
- providerCachePct: null,
62
- providerCacheRead: null,
63
- providerCacheWrite: null,
64
- }));
42
+ // Lazily fetch cost-API pricing once per readIndex call (cached for 1 hour
43
+ // inside costApi.ts). Avoids per-row network calls.
44
+ const costApi = costApiConfig();
45
+ const mapped = rows.map((r) => {
46
+ const modelName = String(r.model_name ?? "");
47
+ const localRate = r.input_rate ||
48
+ lookupModelInputRate(modelName) ||
49
+ null;
50
+ let inputRate = localRate;
51
+ let outputRate = r.output_rate ?? null;
52
+ // Fall back to the cost API when the local table has no data.
53
+ if (costApi.enabled && (inputRate == null || outputRate == null) && modelName) {
54
+ const apiPricing = lookupCostApiPricing(modelName);
55
+ if (apiPricing) {
56
+ if (inputRate == null && apiPricing.inputRate != null) {
57
+ inputRate = apiPricing.inputRate;
58
+ }
59
+ if (outputRate == null && apiPricing.outputRate != null) {
60
+ outputRate = apiPricing.outputRate;
61
+ }
62
+ }
63
+ }
64
+ return {
65
+ repoRoot: String(r.repo_root ?? ""),
66
+ displayName: String(r.display_name ?? ""),
67
+ stateDir: String(r.state_dir ?? ""),
68
+ checkpointCount: Number(r.checkpoint_count ?? 0),
69
+ tokensSaved: Number(r.tokens_saved ?? 0),
70
+ compressedOriginalBytes: Number(r.compressed_original_bytes ?? 0),
71
+ lastCompactedAt: r.last_compacted_at ?? null,
72
+ provider: r.provider ?? null,
73
+ providerName: r.provider_name ?? null,
74
+ modelName: r.model_name ?? null,
75
+ inputRate,
76
+ outputRate,
77
+ lastSeen: Number(r.last_seen ?? 0),
78
+ // Defaults — enriched below from each repo's own store.
79
+ tokensKept: 0,
80
+ tokensDropped: 0,
81
+ sessions: 0,
82
+ contextWindow: null,
83
+ maxTokens: null,
84
+ reasoning: null,
85
+ providerCachePct: null,
86
+ providerCacheRead: null,
87
+ providerCacheWrite: null,
88
+ };
89
+ });
65
90
  // Enrich each repo with per-store token + model detail read directly via
66
91
  // node:sqlite (same zero-dependency invariant as readIndex; no store graph
67
92
  // import). Best-effort: a missing/corrupt store degrades to the defaults
@@ -0,0 +1,81 @@
1
+ /**
2
+ * dashboard-server/resolve-snapshot.ts — dynamic per-repo snapshot resolver.
3
+ *
4
+ * The dashboard server is launched with a single static stateDir, but the
5
+ * active pi session may be running in a different repo. This module queries
6
+ * the repo registry to find the most recently active repo's dashboard.json,
7
+ * so the Overview always shows live data from the repo pi is actually running
8
+ * in — not the stale launcher dir.
9
+ *
10
+ * Resolution order:
11
+ * 1. Most recently seen repo (by last_seen in repo_registry) whose
12
+ * dashboard.json exists and has a non-null updatedAt
13
+ * 2. The static launch stateDir's dashboard.json (original behavior)
14
+ */
15
+ import { existsSync } from "node:fs";
16
+ import { join } from "node:path";
17
+ import { createRequire } from "node:module";
18
+ import { readSnapshot } from "./snapshot.js";
19
+ import { getIndexDir } from "./index-reader.js";
20
+ const require = createRequire(import.meta.url);
21
+ /**
22
+ * Find the most recently active repo's stateDir by scanning the repo registry
23
+ * for repos whose dashboard.json exists and was written recently. Returns null
24
+ * if no suitable repo is found.
25
+ */
26
+ function mostRecentRepoStateDir(staticStateDir) {
27
+ const indexPath = join(getIndexDir(), "index.sqlite");
28
+ if (!existsSync(indexPath))
29
+ return null;
30
+ let db;
31
+ try {
32
+ const { DatabaseSync } = require("node:sqlite");
33
+ db = new DatabaseSync(indexPath, { readOnly: true });
34
+ const rows = db
35
+ .prepare(`SELECT state_dir, last_seen FROM repo_registry
36
+ WHERE state_dir IS NOT NULL AND state_dir != ?
37
+ ORDER BY last_seen DESC`)
38
+ .all(staticStateDir);
39
+ for (const r of rows) {
40
+ const dashPath = join(r.state_dir, "dashboard.json");
41
+ if (!existsSync(dashPath))
42
+ continue;
43
+ const snap = readSnapshot(dashPath);
44
+ if (snap.updatedAt) {
45
+ return r.state_dir;
46
+ }
47
+ }
48
+ return null;
49
+ }
50
+ catch {
51
+ return null;
52
+ }
53
+ finally {
54
+ try {
55
+ db?.close();
56
+ }
57
+ catch {
58
+ /* ignore */
59
+ }
60
+ }
61
+ }
62
+ /**
63
+ * Resolve the best snapshot to serve. Tries the most recently active repo's
64
+ * dashboard.json first, then falls back to the static launch path.
65
+ */
66
+ export function resolveSnapshot(staticSnapshotPath, staticStateDir) {
67
+ // Try the most recently active repo first.
68
+ const activeDir = mostRecentRepoStateDir(staticStateDir);
69
+ if (activeDir) {
70
+ const activePath = join(activeDir, "dashboard.json");
71
+ const snap = readSnapshot(activePath);
72
+ if (snap.updatedAt) {
73
+ return { snapshot: snap, stateDir: activeDir };
74
+ }
75
+ }
76
+ // Fall back to the static launch path.
77
+ return {
78
+ snapshot: readSnapshot(staticSnapshotPath),
79
+ stateDir: staticStateDir,
80
+ };
81
+ }
@@ -5,7 +5,7 @@
5
5
  * builds it. Route handler files import from here; the barrel (routes.ts)
6
6
  * re-exports everything for server.ts.
7
7
  */
8
- import { readSnapshot } from "./snapshot.js";
8
+ import { resolveSnapshot } from "./resolve-snapshot.js";
9
9
  // ---------------------------------------------------------------------------
10
10
  // Helper: overlayCurrentRepo
11
11
  // ---------------------------------------------------------------------------
@@ -13,16 +13,21 @@ function makeOverlayCurrentRepo(snapshotPath, stateDir) {
13
13
  return (idx) => {
14
14
  if (!idx || !idx.repos.length)
15
15
  return;
16
+ // Dynamically resolve the most recently active repo's snapshot so the
17
+ // overlay matches what /api/snapshot serves (not the stale launch dir).
16
18
  let snap = null;
19
+ let activeStateDir = stateDir;
17
20
  try {
18
- snap = readSnapshot(snapshotPath);
21
+ const resolved = resolveSnapshot(snapshotPath, stateDir);
22
+ snap = resolved.snapshot;
23
+ activeStateDir = resolved.stateDir;
19
24
  }
20
25
  catch {
21
26
  return;
22
27
  }
23
28
  if (!snap || !snap.repo)
24
29
  return;
25
- const cur = idx.repos.find((r) => r.stateDir === stateDir);
30
+ const cur = idx.repos.find((r) => r.stateDir === activeStateDir);
26
31
  if (!cur)
27
32
  return;
28
33
  const prevSaved = cur.tokensSaved;
@@ -129,6 +129,13 @@ export const SETTINGS = [
129
129
  num("MEGACOMPACT_EMBED_CACHE", "Embed Cache Size", "Embedding cache entries (0 = disabled)", 256, 0, 10000),
130
130
  ],
131
131
  },
132
+ {
133
+ name: "Cost API",
134
+ settings: [
135
+ boolDirect("MEGACOMPACT_COST_API_ENABLED", "Cost API Lookup", "Fetch model pricing from an external API (PREVENT-PI-004 network exception — opt-in). Enriches the dashboard Cache/Repos tabs with real $/token rates for models not in the local pricing table.", false),
136
+ str("MEGACOMPACT_COST_API_URL", "Cost API URL", "OpenRouter-compatible model pricing endpoint (e.g. https://openrouter.ai/api/v1/models). Only contacted when Cost API Lookup is ON.", ""),
137
+ ],
138
+ },
132
139
  ];
133
140
  /** Flat index of every setting by key for O(1) lookup + validation. */
134
141
  export const SETTING_BY_KEY = new Map(SETTINGS.flatMap((c) => c.settings).map((s) => [s.key, s]));
@@ -86,3 +86,63 @@ export function handleRaptorTree(req, res, ctx) {
86
86
  return true;
87
87
  }
88
88
  }
89
+ /** Find the most recent session that has build history rows (else null). */
90
+ function latestBuildSession(stateDir) {
91
+ try {
92
+ const db = openStore(stateDir);
93
+ const row = db
94
+ .prepare("SELECT DISTINCT session_id FROM raptor_build_history ORDER BY completed_at DESC LIMIT 1")
95
+ .get();
96
+ return row?.session_id ?? null;
97
+ }
98
+ catch {
99
+ return null;
100
+ }
101
+ }
102
+ export function handleRaptorBuildHistory(req, res, ctx) {
103
+ if (req.method !== "GET")
104
+ return false;
105
+ const parsed = parseUrl(req.url ?? "", true);
106
+ if (parsed.pathname !== "/api/raptor-build-history")
107
+ return false;
108
+ try {
109
+ const { listBuildHistory } = _req("../../src/dedup/raptor/buildHistory.js");
110
+ let sessionId = typeof parsed.query.sessionId === "string" ? parsed.query.sessionId : "";
111
+ if (!sessionId) {
112
+ sessionId = latestBuildSession(ctx.stateDir) ?? "";
113
+ if (!sessionId) {
114
+ const body = { builds: [], empty: true };
115
+ res.writeHead(200, { "Content-Type": "application/json" });
116
+ res.end(JSON.stringify(body));
117
+ return true;
118
+ }
119
+ }
120
+ const rows = listBuildHistory(sessionId, ctx.stateDir);
121
+ if (rows.length === 0) {
122
+ const body = { builds: [], empty: true };
123
+ res.writeHead(200, { "Content-Type": "application/json" });
124
+ res.end(JSON.stringify(body));
125
+ return true;
126
+ }
127
+ const dtos = rows.map((r) => ({
128
+ buildId: r.buildId,
129
+ sessionId: r.sessionId,
130
+ startedAt: r.startedAt,
131
+ completedAt: r.completedAt,
132
+ nodeCount: r.nodeCount,
133
+ leafCount: r.leafCount,
134
+ depth: r.depth,
135
+ coherenceScore: r.coherenceScore,
136
+ timedOut: r.timedOut,
137
+ }));
138
+ const body = { builds: dtos, empty: false };
139
+ res.writeHead(200, { "Content-Type": "application/json" });
140
+ res.end(JSON.stringify(body));
141
+ return true;
142
+ }
143
+ catch (e) {
144
+ res.writeHead(500, { "Content-Type": "application/json" });
145
+ res.end(JSON.stringify({ error: String(e) }));
146
+ return true;
147
+ }
148
+ }
@@ -4,6 +4,7 @@
4
4
  import { existsSync, readFileSync } from "node:fs";
5
5
  import { join } from "node:path";
6
6
  import { readSnapshot } from "./snapshot.js";
7
+ import { resolveSnapshot } from "./resolve-snapshot.js";
7
8
  import { dashboardHtml } from "./html.js";
8
9
  import { readIndex, getIndexDir } from "./index-reader.js";
9
10
  import { ACTIVE_WINDOW_SEC } from "./types.js";
@@ -26,7 +27,10 @@ export function handleIndex(req, res, ctx) {
26
27
  return true;
27
28
  }
28
29
  if (req.url === "/api/snapshot") {
29
- const snap = readSnapshot(snapshotPath);
30
+ // Dynamically resolve the most recently active session's dashboard.json
31
+ // so the Overview shows live data from the repo pi is running in — not
32
+ // the stale launcher dir the server was started with.
33
+ const { snapshot: snap } = resolveSnapshot(snapshotPath, ctx.stateDir);
30
34
  res.writeHead(200, { "Content-Type": "application/json" });
31
35
  res.end(JSON.stringify(snap));
32
36
  return true;
@@ -16,10 +16,13 @@ export function handleEvents(req, res, ctx) {
16
16
  "Cache-Control": "no-cache",
17
17
  Connection: "keep-alive",
18
18
  });
19
- // Drain existing events so the client starts with history
19
+ // Drain existing events so the client starts with history.
20
+ // Only stream events with a "type" field — events.log also contains
21
+ // internal monitoring rows (e.g. captureModel:recorded) that use "event"
22
+ // instead of "type" and aren't part of the SseEvent contract.
20
23
  const { data: existing, offset: initialOffset } = readFrom(eventsPath, 0);
21
24
  eventOffsetRef.value = initialOffset;
22
- const lines = existing.split("\n").filter((l) => l.trim());
25
+ const lines = existing.split("\n").filter((l) => l.trim() && l.includes('"type"'));
23
26
  for (const line of lines) {
24
27
  res.write(`data: ${line}\n\n`);
25
28
  }
@@ -32,7 +35,7 @@ export function handleEvents(req, res, ctx) {
32
35
  watchTimer = null;
33
36
  const { data, offset } = readFrom(eventsPath, eventOffsetRef.value);
34
37
  eventOffsetRef.value = offset;
35
- const newLines = data.split("\n").filter((l) => l.trim());
38
+ const newLines = data.split("\n").filter((l) => l.trim() && l.includes('"type"'));
36
39
  for (const line of newLines) {
37
40
  res.write(`data: ${line}\n\n`);
38
41
  }
@@ -15,7 +15,7 @@ export { handleProviderCache } from "./routes-cache.js";
15
15
  export { handleMemoryStatus } from "./routes-memory.js";
16
16
  export { handleSetupStatus, handleSetupDetect, handleSetupConfigure } from "./routes-setup.js";
17
17
  export { handleMemoryMap } from "./routes-memory-map.js";
18
- export { handleRaptorTree } from "./routes-raptor.js";
18
+ export { handleRaptorTree, handleRaptorBuildHistory } from "./routes-raptor.js";
19
19
  export { handleCacheStripes } from "./routes-cache.js";
20
20
  export { handleContextHealth, handleCachePoison, handleHealthSettings } from "./routes-health.js";
21
21
  export { handleEmbedderHealth } from "./routes-embedder-health.js";
@@ -13,7 +13,7 @@ import { fileURLToPath } from "node:url";
13
13
  import { createRequire } from "node:module";
14
14
  import { NEW_UI } from "../../src/config.js";
15
15
  import { log, setLogPath, setDashboardServerVersion } from "./state.js";
16
- import { buildRouteContext, handleIndex, handleRepoIndex, handleEvents, handleGameState, handleGameScores, handlePerf, handleAchievements, handleSessions, handleTopics, handleTurns, handleMaintenance, handleProviderCache, handleCacheStripes, handleMemoryStatus, handleSetupStatus, handleSetupDetect, handleSetupConfigure, handleMemoryMap, handleRaptorTree, handleContextHealth, handleCachePoison, handleHealthSettings, handleEmbedderHealth, handleRagSettings, handleRagMetrics, handleWiki, handleStatic, } from "./routes.js";
16
+ import { buildRouteContext, handleIndex, handleRepoIndex, handleEvents, handleGameState, handleGameScores, handlePerf, handleAchievements, handleSessions, handleTopics, handleTurns, handleMaintenance, handleProviderCache, handleCacheStripes, handleMemoryStatus, handleSetupStatus, handleSetupDetect, handleSetupConfigure, handleMemoryMap, handleRaptorTree, handleRaptorBuildHistory, handleContextHealth, handleCachePoison, handleHealthSettings, handleEmbedderHealth, handleRagSettings, handleRagMetrics, handleWiki, handleStatic, } from "./routes.js";
17
17
  export async function launchDashboardServer(stateDir) {
18
18
  // Our own package version — exposed at /api/version so the launcher can
19
19
  // detect a stale server (started by an older build) and replace it on
@@ -219,6 +219,8 @@ export async function launchDashboardServer(stateDir) {
219
219
  return;
220
220
  if (handleRaptorTree(req, res, ctx))
221
221
  return;
222
+ if (handleRaptorBuildHistory(req, res, ctx))
223
+ return;
222
224
  if (handleContextHealth(req, res, ctx))
223
225
  return;
224
226
  if (handleCachePoison(req, res, ctx))
@@ -79,17 +79,23 @@ export function doRecall(runtime, config, ctx, query, source) {
79
79
  runtime.pushTicker(`${C.amber}↩${C.reset} recalled ${top.checkpoint.checkpointId} · ${scorePct}% · ${label}`);
80
80
  runtime.lastWhy = `why: recalled@${scorePct}% (${result.toInject.length} chkpt)`;
81
81
  }
82
+ let sumTokens = 0;
83
+ for (const h of result.toInject)
84
+ sumTokens += h.checkpoint.tokenEstimate;
82
85
  if (result.toInject.length > 0) {
83
- let sumTokens = 0;
84
- for (const h of result.toInject)
85
- sumTokens += h.checkpoint.tokenEstimate;
86
86
  runtime.rt.recallInjections += result.toInject.length;
87
87
  runtime.rt.cacheHitTokens += sumTokens;
88
88
  incRecallInjected(result.toInject.length, runtime.currentStateDir);
89
89
  incCacheHitTokens(sumTokens, runtime.currentStateDir);
90
- // S43: record recall provenance — which checkpoints/summaries served this
91
- // turn, their score + source path. Linked to the turn row written at
92
- // turn_end via the conversation+turnIndex. Best-effort + non-fatal.
90
+ }
91
+ // S43: record recall provenance which checkpoints/summaries served this
92
+ // turn, their score + source path. Linked to the turn row written at
93
+ // turn_end via the conversation+turnIndex. Best-effort + non-fatal.
94
+ // Persists telemetry (HyDE + recall metrics) even when recall returned
95
+ // no hits, so empty-recall HyDE invocations are still visible in the
96
+ // dashboard Turns/Metrics tabs.
97
+ const hasTelemetry = result.hydeInfo != null || result.recallMetrics != null;
98
+ if (result.toInject.length > 0 || hasTelemetry) {
93
99
  try {
94
100
  const convId = ensureConversationIdFor(config, sid, runtime.currentStateDir);
95
101
  const turnId = recordTurnWrite(config, {
@@ -101,16 +107,18 @@ export function doRecall(runtime, config, ctx, query, source) {
101
107
  hyde: result.hydeInfo ?? undefined,
102
108
  recallMetrics: result.recallMetrics ?? undefined,
103
109
  }, runtime.currentStateDir);
104
- recordRecallWrite(config, turnId, result.toInject.map((h) => ({
105
- checkpointId: h.checkpoint.checkpointId,
106
- score: h.score,
107
- source: h.raptorLevel !== undefined
108
- ? "raptor"
109
- : h.repoId
110
- ? "cross-repo"
111
- : "flat",
112
- raptorLevel: h.raptorLevel,
113
- })), runtime.currentStateDir);
110
+ if (result.toInject.length > 0) {
111
+ recordRecallWrite(config, turnId, result.toInject.map((h) => ({
112
+ checkpointId: h.checkpoint.checkpointId,
113
+ score: h.score,
114
+ source: h.raptorLevel !== undefined
115
+ ? "raptor"
116
+ : h.repoId
117
+ ? "cross-repo"
118
+ : "flat",
119
+ raptorLevel: h.raptorLevel,
120
+ })), runtime.currentStateDir);
121
+ }
114
122
  }
115
123
  catch {
116
124
  /* non-fatal: recall provenance never breaks the recall path */
@@ -7,6 +7,7 @@
7
7
  */
8
8
  import { resolveRepoRoot } from "../mega-config.js";
9
9
  import { recordModelSnapshot, recordRepoModel } from "../../src/store/sqlite.js";
10
+ import { lookupModelInputRate } from "../../src/pricing.js";
10
11
  // -------------------------------------------------------------- captureModel
11
12
  export function captureModelImpl(ctx, ectx) {
12
13
  const m = ectx.model;
@@ -26,12 +27,14 @@ export function captureModelImpl(ctx, ectx) {
26
27
  catch {
27
28
  /* optional */
28
29
  }
30
+ const modelId = m.id;
31
+ const fallbackInput = lookupModelInputRate(modelId);
29
32
  const snap = {
30
33
  provider: m.provider,
31
34
  providerName,
32
- modelId: m.id,
35
+ modelId,
33
36
  modelName: m.name ?? null,
34
- inputRate: m.cost?.input ?? 0,
37
+ inputRate: m.cost?.input || fallbackInput || 0,
35
38
  outputRate: m.cost?.output ?? 0,
36
39
  contextWindow: m.contextWindow ?? 0,
37
40
  maxTokens: m.maxTokens ?? 0,
@@ -43,7 +43,8 @@ export function loadDedupConfig() {
43
43
  L2_ENABLED: envBool("MEGACOMPACT_L2_ENABLED", true),
44
44
  // Fix D: RAPTOR promoted to live recall. Default ON; canary.ts sequences it
45
45
  // last (L0→L1→L2→RAPTOR) and auto-disables on p95 breach, so promotion is
46
- // safe. `RAPTOR_SHADOW_MODE=false` still gates serving during transition.
46
+ // safe. Shadow mode (RAPTOR_SHADOW_MODE=true) opts out of serving while
47
+ // still building + persisting the tree (transition/eval use).
47
48
  RAPTOR_ENABLED: envBool("MEGACOMPACT_RAPTOR_ENABLED", true),
48
49
  MARK_ONLY_L0: envBool("MEGACOMPACT_MARK_ONLY_L0", false),
49
50
  MARK_ONLY_L1: envBool("MEGACOMPACT_MARK_ONLY_L1", false),
@@ -0,0 +1,113 @@
1
+ /**
2
+ * costApi.ts — optional model pricing lookup from an external API.
3
+ *
4
+ * PREVENT-PI-004 EXEMPTION: This module makes network calls to fetch model
5
+ * pricing data. It is disabled by default and must be explicitly opted in via
6
+ * MEGACOMPACT_COST_API_ENABLED=true + MEGACOMPACT_COST_API_URL=<url>.
7
+ *
8
+ * The dashboard server uses this to enrich the inputRate/outputRate fields
9
+ * when the local pricing table (pricing.ts) has no data for a model.
10
+ *
11
+ * Results are cached for 1 hour to minimize network calls.
12
+ */
13
+ import { spawnSync } from "node:child_process"; // guardrails-allow PREVENT-PI-004: user-opted-in cost API — fetches model pricing from a user-configured endpoint, never called unless MEGACOMPACT_COST_API_ENABLED=true
14
+ let _cache = null;
15
+ const CACHE_TTL_MS = 60 * 60 * 1000; // 1 hour
16
+ export function costApiConfig() {
17
+ const enabled = process.env.MEGACOMPACT_COST_API_ENABLED === "true" ||
18
+ process.env.MEGACOMPACT_COST_API_ENABLED === "1";
19
+ const url = process.env.MEGACOMPACT_COST_API_URL ?? "";
20
+ return { enabled, url };
21
+ }
22
+ /**
23
+ * Fetch model pricing from the configured API endpoint.
24
+ *
25
+ * Expects a JSON response of shape:
26
+ * { "data": [{ "id": "model-name", "pricing": { "prompt": "0.000003", "completion": "0.000015" } }] }
27
+ * (OpenRouter-compatible format). Values are USD per token as strings.
28
+ *
29
+ * Returns a map keyed by lowercase model id → { inputRate, outputRate }.
30
+ * Returns an empty map on any error. Never throws.
31
+ */
32
+ export function fetchModelPricing() {
33
+ const cfg = costApiConfig();
34
+ if (!cfg.enabled || !cfg.url)
35
+ return new Map();
36
+ // Return cached data if fresh.
37
+ if (_cache && Date.now() - _cache.timestamp < CACHE_TTL_MS) {
38
+ return _cache.data;
39
+ }
40
+ const result = _doFetch(cfg.url);
41
+ _cache = { timestamp: Date.now(), data: result };
42
+ return result;
43
+ }
44
+ function _doFetch(url) {
45
+ // Synchronous bridge: spawnSync an inline worker so the call blocks without
46
+ // deadlocking fetch (mirrors HttpEmbedder / RAPTOR summarizer pattern).
47
+ const WORKER = String.raw `
48
+ try {
49
+ const r = await fetch(process.env.COST_API_URL, { // guardrails-allow PREVENT-PI-004: user-opted-in cost API — fetches model pricing from a user-configured endpoint
50
+ method: "GET",
51
+ headers: { "accept": "application/json" },
52
+ });
53
+ const j = await r.json();
54
+ process.stdout.write(JSON.stringify({ ok: r.ok, data: j }));
55
+ } catch (e) {
56
+ process.stdout.write(JSON.stringify({ ok: false, error: String(e && e.message ? e.message : e) }));
57
+ }
58
+ `;
59
+ const res = spawnSync(process.execPath, ["-e", WORKER], {
60
+ encoding: "utf8",
61
+ timeout: 15_000,
62
+ env: { ...process.env, COST_API_URL: url },
63
+ });
64
+ const out = new Map();
65
+ let parsed;
66
+ try {
67
+ parsed = JSON.parse(res.stdout);
68
+ }
69
+ catch {
70
+ return out;
71
+ }
72
+ if (!parsed.ok || !parsed.data)
73
+ return out;
74
+ // OpenRouter-compatible: { data: [{ id, pricing: { prompt, completion } }] }
75
+ const models = parsed.data?.data;
76
+ if (!Array.isArray(models))
77
+ return out;
78
+ for (const m of models) {
79
+ if (!m.id)
80
+ continue;
81
+ const prompt = m.pricing?.prompt;
82
+ const completion = m.pricing?.completion;
83
+ const inputRate = prompt != null ? parseFloat(prompt) : null;
84
+ const outputRate = completion != null ? parseFloat(completion) : null;
85
+ if (inputRate != null || outputRate != null) {
86
+ out.set(m.id.toLowerCase(), { inputRate, outputRate });
87
+ }
88
+ }
89
+ return out;
90
+ }
91
+ /**
92
+ * Look up pricing for a model name from the cost API cache.
93
+ * Tries exact match, then prefix match (same pattern as lookupModelInputRate).
94
+ */
95
+ export function lookupCostApiPricing(model) {
96
+ const data = fetchModelPricing();
97
+ if (data.size === 0)
98
+ return null;
99
+ const lower = model.toLowerCase();
100
+ // Exact match.
101
+ if (data.has(lower))
102
+ return data.get(lower) ?? null;
103
+ // Prefix match.
104
+ for (const [key, pricing] of data) {
105
+ if (lower.startsWith(key))
106
+ return pricing;
107
+ }
108
+ return null;
109
+ }
110
+ /** Clear the pricing cache (useful for testing). */
111
+ export function clearCostApiCache() {
112
+ _cache = null;
113
+ }