pi-mega-compact 0.11.1 → 0.11.3
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.
- package/dist/extensions/dashboard-server/api-contracts/endpoints.js +28 -1
- package/dist/extensions/dashboard-server/api-contracts/maintenance.js +7 -0
- package/dist/extensions/dashboard-server/api-contracts/provider-cache.js +7 -0
- package/dist/extensions/dashboard-server/api-contracts.test.js +3 -2
- package/dist/extensions/dashboard-server/index-reader.js +22 -0
- package/dist/extensions/dashboard-server/routes-cache.js +80 -0
- package/dist/extensions/dashboard-server/routes-cache.test.js +248 -0
- package/dist/extensions/dashboard-server/routes-maintenance.js +293 -0
- package/dist/extensions/dashboard-server/routes-repo.js +24 -0
- package/dist/extensions/dashboard-server/routes.js +2 -0
- package/dist/extensions/dashboard-server/server.js +5 -1
- package/dist/extensions/mega-cache-replay.test.js +233 -24
- package/dist/extensions/mega-compact-s38.test.js +201 -6
- package/dist/extensions/mega-config.js +3 -0
- package/dist/extensions/mega-events/agent-handlers.js +23 -7
- package/dist/extensions/mega-events/context-handler.js +37 -19
- package/dist/extensions/mega-events/error-classifier.js +27 -16
- package/dist/extensions/mega-runtime/runtime-snapshot.js +14 -4
- package/dist/extensions/mega-runtime/snapshot.js +1 -1
- package/dist/extensions/mega-runtime/snapshot.test.js +127 -0
- package/dist/extensions/mega-runtime/widget.js +4 -4
- package/dist/extensions/mega-runtime/widget.test.js +103 -12
- package/dist/src/pricing.js +78 -0
- package/dist/src/store/sqlite/maintenance.js +20 -1
- package/dist/src/store/sqlite/perf-samples.js +104 -0
- package/dist/src/store/sqlite/perf-samples.test.js +93 -1
- package/extensions/dashboard-client/dist/assets/{AchievementTiles-DZp_xQOW.js → AchievementTiles-vEo2MtE2.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{AchievementTiles-DZp_xQOW.js.map → AchievementTiles-vEo2MtE2.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/AchievementsTab-DjxfYrDc.js +2 -0
- package/extensions/dashboard-client/dist/assets/{AchievementsTab-BzFHpAHM.js.map → AchievementsTab-DjxfYrDc.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/CacheTab-Dnpv94wq.js +2 -0
- package/extensions/dashboard-client/dist/assets/CacheTab-Dnpv94wq.js.map +1 -0
- package/extensions/dashboard-client/dist/assets/{ConfigTab-DQ4FG33J.js → ConfigTab-Cm6ymbmx.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{ConfigTab-DQ4FG33J.js.map → ConfigTab-Cm6ymbmx.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{EventsTab-D5HoEVYo.js → EventsTab-DXWl_YzI.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{EventsTab-D5HoEVYo.js.map → EventsTab-DXWl_YzI.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{GameTab-Jzsc4yeY.js → GameTab-BLDudcO5.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{GameTab-Jzsc4yeY.js.map → GameTab-BLDudcO5.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/MaintenanceTab-DLkKCztn.js +2 -0
- package/extensions/dashboard-client/dist/assets/MaintenanceTab-DLkKCztn.js.map +1 -0
- package/extensions/dashboard-client/dist/assets/{MetricsTab-D_XnsEYX.js → MetricsTab-Cq4u-rZF.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{MetricsTab-D_XnsEYX.js.map → MetricsTab-Cq4u-rZF.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{OverviewTab-BMREvAth.js → OverviewTab-D4kGvsiQ.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{OverviewTab-BMREvAth.js.map → OverviewTab-D4kGvsiQ.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/ReposTab-C0Wnrf2u.js +2 -0
- package/extensions/dashboard-client/dist/assets/ReposTab-C0Wnrf2u.js.map +1 -0
- package/extensions/dashboard-client/dist/assets/{SessionsTab-mz_vz8i2.js → SessionsTab-DZC2-GCn.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{SessionsTab-mz_vz8i2.js.map → SessionsTab-DZC2-GCn.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/TimeSavedCard-UqljSyP-.js +2 -0
- package/extensions/dashboard-client/dist/assets/TimeSavedCard-UqljSyP-.js.map +1 -0
- package/extensions/dashboard-client/dist/assets/{TopicsTab-DKuct4oD.js → TopicsTab-01G71hv1.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{TopicsTab-DKuct4oD.js.map → TopicsTab-01G71hv1.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{TurnsTab-11MGLxY8.js → TurnsTab-DLRg0LZT.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{TurnsTab-11MGLxY8.js.map → TurnsTab-DLRg0LZT.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/index-BEdKlpAB.css +1 -0
- package/extensions/dashboard-client/dist/assets/{index-CqLN7STl.js → index-BX0bcgLu.js} +10 -10
- package/extensions/dashboard-client/dist/assets/{index-CqLN7STl.js.map → index-BX0bcgLu.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{useSSE-CXrQSbVY.js → useSSE-BBYt5UPB.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{useSSE-CXrQSbVY.js.map → useSSE-BBYt5UPB.js.map} +1 -1
- package/extensions/dashboard-client/dist/index.html +2 -2
- package/extensions/dashboard-client/src/App.tsx +5 -1
- package/extensions/dashboard-client/src/api/client.ts +29 -0
- package/extensions/dashboard-client/src/components/ActiveReposTable.tsx +13 -1
- package/extensions/dashboard-client/src/components/ProviderCacheCard.tsx +141 -0
- package/extensions/dashboard-client/src/components/SavingsByModelTable.tsx +31 -3
- package/extensions/dashboard-client/src/main.tsx +1 -0
- package/extensions/dashboard-client/src/styles/maintenance.css +267 -0
- package/extensions/dashboard-client/src/styles/overview-extra.css +9 -0
- package/extensions/dashboard-client/src/tabs/CacheTab.tsx +83 -29
- package/extensions/dashboard-client/src/tabs/MaintenanceTab.tsx +458 -0
- package/extensions/dashboard-client/src/utils/format.ts +42 -7
- package/extensions/dashboard-server/api-contracts/endpoints.ts +54 -1
- package/extensions/dashboard-server/api-contracts/index.ts +16 -0
- package/extensions/dashboard-server/api-contracts/maintenance.ts +84 -0
- package/extensions/dashboard-server/api-contracts/multi-repo.ts +6 -0
- package/extensions/dashboard-server/api-contracts/provider-cache.ts +30 -0
- package/extensions/dashboard-server/api-contracts.test.ts +3 -2
- package/extensions/dashboard-server/api-contracts.ts +9 -0
- package/extensions/dashboard-server/index-reader.ts +23 -0
- package/extensions/dashboard-server/routes-cache.test.ts +302 -0
- package/extensions/dashboard-server/routes-cache.ts +123 -0
- package/extensions/dashboard-server/routes-maintenance.ts +352 -0
- package/extensions/dashboard-server/routes-repo.ts +31 -4
- package/extensions/dashboard-server/routes.ts +2 -0
- package/extensions/dashboard-server/server.ts +4 -0
- package/extensions/mega-cache-replay.test.ts +481 -166
- package/extensions/mega-compact-s38.test.ts +210 -6
- package/extensions/mega-config.ts +6 -0
- package/extensions/mega-events/agent-handlers.ts +24 -6
- package/extensions/mega-events/context-handler.ts +59 -24
- package/extensions/mega-events/error-classifier.ts +30 -13
- package/extensions/mega-runtime/runtime-snapshot.ts +31 -9
- package/extensions/mega-runtime/snapshot.test.ts +139 -0
- package/extensions/mega-runtime/snapshot.ts +6 -4
- package/extensions/mega-runtime/widget.test.ts +290 -105
- package/extensions/mega-runtime/widget.ts +29 -6
- package/package.json +1 -1
- package/src/pricing.ts +95 -0
- package/src/store/sqlite/maintenance.ts +20 -1
- package/src/store/sqlite/perf-samples.test.ts +107 -3
- package/src/store/sqlite/perf-samples.ts +142 -6
- package/extensions/dashboard-client/dist/assets/AchievementsTab-BzFHpAHM.js +0 -2
- package/extensions/dashboard-client/dist/assets/CacheTab-DEQbTq2T.js +0 -2
- package/extensions/dashboard-client/dist/assets/CacheTab-DEQbTq2T.js.map +0 -1
- package/extensions/dashboard-client/dist/assets/ReposTab-DuyhOktG.js +0 -2
- package/extensions/dashboard-client/dist/assets/ReposTab-DuyhOktG.js.map +0 -1
- package/extensions/dashboard-client/dist/assets/TimeSavedCard-B8AIjNTY.js +0 -2
- package/extensions/dashboard-client/dist/assets/TimeSavedCard-B8AIjNTY.js.map +0 -1
- package/extensions/dashboard-client/dist/assets/index-gn66lYD2.css +0 -1
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dashboard-server/routes-maintenance.ts — S49B Maintenance tab API routes.
|
|
3
|
+
*
|
|
4
|
+
* Handlers for:
|
|
5
|
+
* GET /api/maintenance — DB stats (table row counts + storage)
|
|
6
|
+
* GET /api/maintenance/schema-health — SCHEMA_VERSION + integrity audit
|
|
7
|
+
* POST /api/maintenance/action — Trigger a maintenance action
|
|
8
|
+
*
|
|
9
|
+
* All pi-agnostic; lazy-requires maintenance primitives to avoid a top-level
|
|
10
|
+
* import of the store from the dashboard server process. PREVENT-PI-004: local
|
|
11
|
+
* SQLite only; zero network calls.
|
|
12
|
+
*/
|
|
13
|
+
import { createRequire } from "node:module";
|
|
14
|
+
// ---------------------------------------------------------------------------
|
|
15
|
+
// Lazy imports (via createRequire)
|
|
16
|
+
// ---------------------------------------------------------------------------
|
|
17
|
+
const lazyMaintenance = (() => {
|
|
18
|
+
let mod = null;
|
|
19
|
+
return () => {
|
|
20
|
+
if (!mod)
|
|
21
|
+
mod = createRequire(import.meta.url)("../../src/store/sqlite/maintenance.js");
|
|
22
|
+
return mod;
|
|
23
|
+
};
|
|
24
|
+
})();
|
|
25
|
+
const lazyStoreUtils = (() => {
|
|
26
|
+
let mod = null;
|
|
27
|
+
return () => {
|
|
28
|
+
if (!mod)
|
|
29
|
+
mod = createRequire(import.meta.url)("../../src/store/sqlite/utils.js");
|
|
30
|
+
return mod;
|
|
31
|
+
};
|
|
32
|
+
})();
|
|
33
|
+
// ---------------------------------------------------------------------------
|
|
34
|
+
// GET /api/maintenance and sub-paths
|
|
35
|
+
// ---------------------------------------------------------------------------
|
|
36
|
+
export function handleMaintenance(req, res, ctx) {
|
|
37
|
+
const url = req.url ?? "";
|
|
38
|
+
if (!url.startsWith("/api/maintenance"))
|
|
39
|
+
return false;
|
|
40
|
+
const method = (req.method ?? "GET").toUpperCase();
|
|
41
|
+
// ── GET /api/maintenance/schema-health ────────────────────────────
|
|
42
|
+
if (method === "GET" && url === "/api/maintenance/schema-health") {
|
|
43
|
+
sendSchemaHealth(res, ctx);
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
46
|
+
// ── POST /api/maintenance/action ──────────────────────────────────
|
|
47
|
+
if (method === "POST" && url === "/api/maintenance/action") {
|
|
48
|
+
handleMaintenanceAction(req, res, ctx);
|
|
49
|
+
return true;
|
|
50
|
+
}
|
|
51
|
+
// ── GET /api/maintenance ──────────────────────────────────────────
|
|
52
|
+
if (method === "GET" && url === "/api/maintenance") {
|
|
53
|
+
sendDbStats(res, ctx);
|
|
54
|
+
return true;
|
|
55
|
+
}
|
|
56
|
+
// ── Unknown sub-path ──────────────────────────────────────────────
|
|
57
|
+
sendJson(res, 404, { error: "not found" });
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
// ---------------------------------------------------------------------------
|
|
61
|
+
// GET /api/maintenance — DB stats
|
|
62
|
+
// ---------------------------------------------------------------------------
|
|
63
|
+
function sendDbStats(res, ctx) {
|
|
64
|
+
try {
|
|
65
|
+
const { getDbStats } = lazyMaintenance();
|
|
66
|
+
const raw = getDbStats(ctx.stateDir);
|
|
67
|
+
const tables = Object.entries(raw.tableCounts).map(([table, rowCount]) => ({
|
|
68
|
+
table,
|
|
69
|
+
rowCount,
|
|
70
|
+
}));
|
|
71
|
+
sendJson(res, 200, {
|
|
72
|
+
type: "db-stats",
|
|
73
|
+
tables,
|
|
74
|
+
storage: {
|
|
75
|
+
files: {
|
|
76
|
+
dbBytes: raw.dbBytes,
|
|
77
|
+
walBytes: raw.walBytes,
|
|
78
|
+
shmBytes: raw.shmBytes,
|
|
79
|
+
},
|
|
80
|
+
pageSize: raw.pageSize,
|
|
81
|
+
pageCount: raw.pageCount,
|
|
82
|
+
freelistPages: raw.freelistPages,
|
|
83
|
+
},
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
catch (err) {
|
|
87
|
+
sendJson(res, 500, { error: err.message });
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
// ---------------------------------------------------------------------------
|
|
91
|
+
// GET /api/maintenance/schema-health — schema version + integrity audit
|
|
92
|
+
// ---------------------------------------------------------------------------
|
|
93
|
+
function sendSchemaHealth(res, ctx) {
|
|
94
|
+
try {
|
|
95
|
+
const { integrityCheck } = lazyMaintenance();
|
|
96
|
+
const integrity = integrityCheck(ctx.stateDir);
|
|
97
|
+
const { openStore } = lazyStoreUtils();
|
|
98
|
+
const db = openStore(ctx.stateDir);
|
|
99
|
+
// SCHEMA_VERSION from meta table
|
|
100
|
+
const metaRow = db
|
|
101
|
+
.prepare("SELECT value FROM meta WHERE key = ?")
|
|
102
|
+
.get("schema_version");
|
|
103
|
+
const schemaVersion = metaRow ? Number(metaRow.value) : 0;
|
|
104
|
+
// PRAGMA foreign_key_check
|
|
105
|
+
const fkRows = db.prepare("PRAGMA foreign_key_check").all();
|
|
106
|
+
const fkCheck = fkRows.map((r) => JSON.stringify(r));
|
|
107
|
+
// Per-column audit: every ensureColumn migration column declared in
|
|
108
|
+
// schema.ts, checked via PRAGMA table_info (read-only).
|
|
109
|
+
const expectedColumns = [
|
|
110
|
+
{
|
|
111
|
+
table: "context_chunks",
|
|
112
|
+
column: "original_token_estimate",
|
|
113
|
+
decl: "INTEGER",
|
|
114
|
+
},
|
|
115
|
+
{ table: "raw_transcript", column: "content_ref", decl: "TEXT" },
|
|
116
|
+
{ table: "memories", column: "category", decl: "TEXT" },
|
|
117
|
+
{ table: "memories", column: "target", decl: "TEXT" },
|
|
118
|
+
{ table: "memories", column: "last_referenced", decl: "INTEGER" },
|
|
119
|
+
{ table: "memories", column: "source_turn", decl: "INTEGER" },
|
|
120
|
+
{ table: "raptor_nodes", column: "built_at", decl: "INTEGER" },
|
|
121
|
+
{ table: "raw_transcript", column: "turn_index", decl: "INTEGER" },
|
|
122
|
+
{ table: "session_state", column: "conversation_id", decl: "TEXT" },
|
|
123
|
+
{ table: "session_state", column: "last_turn_id", decl: "INTEGER" },
|
|
124
|
+
];
|
|
125
|
+
const columns = expectedColumns.map((ec) => {
|
|
126
|
+
const cols = db.prepare(`PRAGMA table_info(${ec.table})`).all();
|
|
127
|
+
const present = cols.some((c) => c.name === ec.column);
|
|
128
|
+
return {
|
|
129
|
+
table: ec.table,
|
|
130
|
+
column: ec.column,
|
|
131
|
+
present,
|
|
132
|
+
expectedDecl: ec.decl,
|
|
133
|
+
};
|
|
134
|
+
});
|
|
135
|
+
const healthy = integrity.length === 1 &&
|
|
136
|
+
integrity[0] === "ok" &&
|
|
137
|
+
columns.every((c) => c.present);
|
|
138
|
+
sendJson(res, 200, {
|
|
139
|
+
type: "schema-health",
|
|
140
|
+
schemaVersion,
|
|
141
|
+
integrity,
|
|
142
|
+
fkCheck,
|
|
143
|
+
columns,
|
|
144
|
+
healthy,
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
catch (err) {
|
|
148
|
+
sendJson(res, 500, { error: err.message });
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
// ---------------------------------------------------------------------------
|
|
152
|
+
// POST /api/maintenance/action — Trigger a maintenance action
|
|
153
|
+
// ---------------------------------------------------------------------------
|
|
154
|
+
function handleMaintenanceAction(req, res, ctx) {
|
|
155
|
+
let body = "";
|
|
156
|
+
req.setEncoding("utf8");
|
|
157
|
+
req.on("data", (chunk) => {
|
|
158
|
+
body += chunk;
|
|
159
|
+
if (body.length > 10_000)
|
|
160
|
+
req.destroy();
|
|
161
|
+
});
|
|
162
|
+
req.on("end", () => {
|
|
163
|
+
let payload;
|
|
164
|
+
try {
|
|
165
|
+
payload = JSON.parse(body);
|
|
166
|
+
if (!payload || !payload.action) {
|
|
167
|
+
sendJson(res, 400, { error: "missing 'action' field" });
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
sendJson(res, 400, { error: "invalid JSON" });
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
try {
|
|
176
|
+
const m = lazyMaintenance();
|
|
177
|
+
const u = lazyStoreUtils();
|
|
178
|
+
// All destructive actions: temp backup first
|
|
179
|
+
if (payload.action !== "integrity-check") {
|
|
180
|
+
// Non-blocking — backup failure is non-fatal
|
|
181
|
+
m.backupDb(ctx.stateDir);
|
|
182
|
+
}
|
|
183
|
+
switch (payload.action) {
|
|
184
|
+
case "vacuum": {
|
|
185
|
+
const r = m.vacuumDb(ctx.stateDir);
|
|
186
|
+
sendJson(res, 200, {
|
|
187
|
+
operation: "vacuum",
|
|
188
|
+
success: true,
|
|
189
|
+
affected: r.affected,
|
|
190
|
+
reclaimedBytes: r.reclaimedBytes,
|
|
191
|
+
summary: r.summary,
|
|
192
|
+
});
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
case "checkpoint": {
|
|
196
|
+
const r = m.checkpointWal(ctx.stateDir);
|
|
197
|
+
sendJson(res, 200, {
|
|
198
|
+
operation: "checkpoint",
|
|
199
|
+
success: true,
|
|
200
|
+
affected: r.affected,
|
|
201
|
+
reclaimedBytes: r.reclaimedBytes,
|
|
202
|
+
summary: r.summary,
|
|
203
|
+
});
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
case "reindex": {
|
|
207
|
+
const db = u.openStore(ctx.stateDir);
|
|
208
|
+
db.exec("REINDEX");
|
|
209
|
+
sendJson(res, 200, {
|
|
210
|
+
operation: "reindex",
|
|
211
|
+
success: true,
|
|
212
|
+
affected: 0,
|
|
213
|
+
reclaimedBytes: 0,
|
|
214
|
+
summary: "REINDEX completed",
|
|
215
|
+
});
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
case "fts5-rebuild": {
|
|
219
|
+
const db = u.openStore(ctx.stateDir);
|
|
220
|
+
db.exec("INSERT INTO context_chunks_trgm(context_chunks_trgm) VALUES('rebuild')");
|
|
221
|
+
sendJson(res, 200, {
|
|
222
|
+
operation: "fts5-rebuild",
|
|
223
|
+
success: true,
|
|
224
|
+
affected: 0,
|
|
225
|
+
reclaimedBytes: 0,
|
|
226
|
+
summary: "FTS5 rebuild triggered",
|
|
227
|
+
});
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
case "reconcile-dedup": {
|
|
231
|
+
const r = m.reconcileDedupMirror(ctx.stateDir);
|
|
232
|
+
const lines = [];
|
|
233
|
+
if (r.fixedRefCount)
|
|
234
|
+
lines.push(`${r.fixedRefCount} ref_counts corrected`);
|
|
235
|
+
if (r.orphansDeleted)
|
|
236
|
+
lines.push(`${r.orphansDeleted} orphans deleted`);
|
|
237
|
+
if (r.refsBackfilled)
|
|
238
|
+
lines.push(`${r.refsBackfilled} refs backfilled`);
|
|
239
|
+
sendJson(res, 200, {
|
|
240
|
+
operation: "reconcile-dedup",
|
|
241
|
+
success: true,
|
|
242
|
+
affected: r.fixedRefCount + r.orphansDeleted + r.refsBackfilled,
|
|
243
|
+
reclaimedBytes: 0,
|
|
244
|
+
summary: lines.length ? lines.join(", ") : "nothing to fix",
|
|
245
|
+
});
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
case "prune": {
|
|
249
|
+
const days = Number(payload.daysOld) || 30;
|
|
250
|
+
const r = m.pruneOldRows(ctx.stateDir, days);
|
|
251
|
+
sendJson(res, 200, {
|
|
252
|
+
operation: "prune",
|
|
253
|
+
success: true,
|
|
254
|
+
affected: r.affected,
|
|
255
|
+
reclaimedBytes: r.reclaimedBytes,
|
|
256
|
+
summary: r.summary,
|
|
257
|
+
});
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
case "integrity-check": {
|
|
261
|
+
const lines = m.integrityCheck(ctx.stateDir);
|
|
262
|
+
sendJson(res, 200, {
|
|
263
|
+
operation: "integrity-check",
|
|
264
|
+
success: lines.length === 1 && lines[0] === "ok",
|
|
265
|
+
affected: 0,
|
|
266
|
+
reclaimedBytes: 0,
|
|
267
|
+
summary: lines.join("; "),
|
|
268
|
+
detail: lines,
|
|
269
|
+
});
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
default:
|
|
273
|
+
sendJson(res, 400, {
|
|
274
|
+
error: `unknown action: ${payload.action}`,
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
catch (err) {
|
|
279
|
+
sendJson(res, 500, { error: err.message });
|
|
280
|
+
}
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
// ---------------------------------------------------------------------------
|
|
284
|
+
// JSON helper
|
|
285
|
+
// ---------------------------------------------------------------------------
|
|
286
|
+
function sendJson(res, status, data) {
|
|
287
|
+
const body = JSON.stringify(data);
|
|
288
|
+
res.writeHead(status, {
|
|
289
|
+
"Content-Type": "application/json",
|
|
290
|
+
"Content-Length": Buffer.byteLength(body),
|
|
291
|
+
});
|
|
292
|
+
res.end(body);
|
|
293
|
+
}
|
|
@@ -7,6 +7,9 @@ import { readSnapshot } from "./snapshot.js";
|
|
|
7
7
|
import { dashboardHtml } from "./html.js";
|
|
8
8
|
import { readIndex, getIndexDir } from "./index-reader.js";
|
|
9
9
|
import { ACTIVE_WINDOW_SEC } from "./types.js";
|
|
10
|
+
import { readProviderCacheForRepo } from "../../src/store/sqlite/perf-samples.js";
|
|
11
|
+
import { computeCacheSavings, lookupModelInputRate } from "../../src/pricing.js";
|
|
12
|
+
import { latestModelSnapshot } from "../../src/store/sqlite/model-snapshots.js";
|
|
10
13
|
// ---------------------------------------------------------------------------
|
|
11
14
|
// handleIndex — "/" | "/index.html" | "/api/snapshot" | "/api/version"
|
|
12
15
|
// ---------------------------------------------------------------------------
|
|
@@ -132,6 +135,27 @@ export function handleRepoIndex(req, res, ctx) {
|
|
|
132
135
|
out.compacts = snap.compacts ?? null;
|
|
133
136
|
out.timeSaved = snap.timeSaved ?? null;
|
|
134
137
|
out.updatedAt = snap.updatedAt ?? null;
|
|
138
|
+
// Provider cache per-repo lifetime (E.2)
|
|
139
|
+
try {
|
|
140
|
+
const pc = readProviderCacheForRepo(r.stateDir);
|
|
141
|
+
// Price from model snapshot if available
|
|
142
|
+
const modelSnap = latestModelSnapshot(r.stateDir);
|
|
143
|
+
const inputRate = modelSnap
|
|
144
|
+
? modelSnap.inputRate
|
|
145
|
+
: lookupModelInputRate(r.modelName ?? "") ?? 0;
|
|
146
|
+
const savings = computeCacheSavings(pc.totalCacheRead, pc.totalCacheWrite, inputRate);
|
|
147
|
+
out.providerCache = {
|
|
148
|
+
avgHitPct: pc.avgHitPct,
|
|
149
|
+
cacheRead: pc.totalCacheRead,
|
|
150
|
+
cacheWrite: pc.totalCacheWrite,
|
|
151
|
+
totalInput: pc.totalInput,
|
|
152
|
+
sampleCount: pc.sampleCount,
|
|
153
|
+
estimatedSaved: savings.netSaved > 0 ? savings.netSaved : null,
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
catch {
|
|
157
|
+
/* best-effort — repo may not have perf_samples */
|
|
158
|
+
}
|
|
135
159
|
}
|
|
136
160
|
}
|
|
137
161
|
catch {
|
|
@@ -10,3 +10,5 @@ export { handleGameState, handleGameScores, handlePerf, handleAchievements, } fr
|
|
|
10
10
|
export { handleEvents, handleSessions } from "./routes-sessions.js";
|
|
11
11
|
export { handleTopics } from "./routes-topics.js";
|
|
12
12
|
export { handleTurns } from "./routes-turns.js";
|
|
13
|
+
export { handleMaintenance } from "./routes-maintenance.js";
|
|
14
|
+
export { handleProviderCache } from "./routes-cache.js";
|
|
@@ -12,7 +12,7 @@ import { join, dirname } from "node:path";
|
|
|
12
12
|
import { fileURLToPath } from "node:url";
|
|
13
13
|
import { createRequire } from "node:module";
|
|
14
14
|
import { log, setLogPath, setDashboardServerVersion } from "./state.js";
|
|
15
|
-
import { buildRouteContext, handleIndex, handleRepoIndex, handleEvents, handleGameState, handleGameScores, handlePerf, handleAchievements, handleSessions, handleTopics, handleTurns, handleStatic, } from "./routes.js";
|
|
15
|
+
import { buildRouteContext, handleIndex, handleRepoIndex, handleEvents, handleGameState, handleGameScores, handlePerf, handleAchievements, handleSessions, handleTopics, handleTurns, handleMaintenance, handleProviderCache, handleStatic, } from "./routes.js";
|
|
16
16
|
export async function launchDashboardServer(stateDir) {
|
|
17
17
|
// Our own package version — exposed at /api/version so the launcher can
|
|
18
18
|
// detect a stale server (started by an older build) and replace it on
|
|
@@ -191,6 +191,10 @@ export async function launchDashboardServer(stateDir) {
|
|
|
191
191
|
return;
|
|
192
192
|
if (handleTurns(req, res, ctx))
|
|
193
193
|
return;
|
|
194
|
+
if (handleMaintenance(req, res, ctx))
|
|
195
|
+
return;
|
|
196
|
+
if (handleProviderCache(req, res, ctx))
|
|
197
|
+
return;
|
|
194
198
|
handleStatic(req, res, ctx);
|
|
195
199
|
});
|
|
196
200
|
// Bind base + range are env-configurable so tests can use a private,
|
|
@@ -53,17 +53,48 @@ function harness() {
|
|
|
53
53
|
// raising `tokens` while keeping `percent` null (→ token gate + token
|
|
54
54
|
// grewEnough path in context-handler.ts). The REPLAY test keeps percent=100 so
|
|
55
55
|
// the percent-basis grewEnough (>=10) never trips (no re-compact → pure replay).
|
|
56
|
-
const usage = {
|
|
56
|
+
const usage = {
|
|
57
|
+
tokens: 200000,
|
|
58
|
+
contextWindow: 200000,
|
|
59
|
+
percent: 100,
|
|
60
|
+
};
|
|
57
61
|
const handlers = {};
|
|
58
62
|
const compactCalls = [];
|
|
59
63
|
function msg(role, text, toolName) {
|
|
60
64
|
if (role === "assistant" && toolName) {
|
|
61
|
-
return {
|
|
65
|
+
return {
|
|
66
|
+
role: "assistant",
|
|
67
|
+
content: [
|
|
68
|
+
{ type: "toolCall", name: toolName, id: "c1", arguments: {} },
|
|
69
|
+
],
|
|
70
|
+
api: "anthropic-messages",
|
|
71
|
+
provider: "anthropic",
|
|
72
|
+
model: "m",
|
|
73
|
+
usage: {
|
|
74
|
+
inputTokens: 1,
|
|
75
|
+
outputTokens: 1,
|
|
76
|
+
cacheReadTokens: 0,
|
|
77
|
+
cacheWriteTokens: 0,
|
|
78
|
+
},
|
|
79
|
+
stopReason: "tool_use",
|
|
80
|
+
timestamp: 0,
|
|
81
|
+
};
|
|
62
82
|
}
|
|
63
83
|
if (role === "toolResult" && toolName) {
|
|
64
|
-
return {
|
|
84
|
+
return {
|
|
85
|
+
role: "toolResult",
|
|
86
|
+
content: [{ type: "text", text }],
|
|
87
|
+
toolCallId: "c1",
|
|
88
|
+
toolName,
|
|
89
|
+
isError: false,
|
|
90
|
+
timestamp: 0,
|
|
91
|
+
};
|
|
65
92
|
}
|
|
66
|
-
return {
|
|
93
|
+
return {
|
|
94
|
+
role: "user",
|
|
95
|
+
content: text,
|
|
96
|
+
timestamp: 0,
|
|
97
|
+
};
|
|
67
98
|
}
|
|
68
99
|
// Build a session of `n` tool-call triples tagged `tag`. Set A and B differ in
|
|
69
100
|
// content (so B never dedups against A) but A === A reproduces the same
|
|
@@ -77,7 +108,13 @@ function harness() {
|
|
|
77
108
|
}
|
|
78
109
|
return s;
|
|
79
110
|
}
|
|
80
|
-
const toEntry = (m, i) => ({
|
|
111
|
+
const toEntry = (m, i) => ({
|
|
112
|
+
type: "message",
|
|
113
|
+
id: `e${i}`,
|
|
114
|
+
parentId: null,
|
|
115
|
+
timestamp: String(i),
|
|
116
|
+
message: m,
|
|
117
|
+
});
|
|
81
118
|
const sessionManager = {
|
|
82
119
|
getSessionId: () => "sess_cache_001",
|
|
83
120
|
getEntries: () => buildSession("A", 14).map(toEntry),
|
|
@@ -85,39 +122,86 @@ function harness() {
|
|
|
85
122
|
};
|
|
86
123
|
function makeCtx(over = {}) {
|
|
87
124
|
return {
|
|
88
|
-
ui: {
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
125
|
+
ui: {
|
|
126
|
+
setStatus: () => { },
|
|
127
|
+
notify: () => { },
|
|
128
|
+
select: () => { },
|
|
129
|
+
confirm: async () => true,
|
|
130
|
+
input: async () => "",
|
|
131
|
+
setWidget: () => { },
|
|
132
|
+
},
|
|
133
|
+
mode: "tui",
|
|
134
|
+
hasUI: true,
|
|
135
|
+
cwd: stateDir,
|
|
136
|
+
sessionManager,
|
|
137
|
+
modelRegistry: {},
|
|
138
|
+
model: undefined,
|
|
139
|
+
isIdle: () => true,
|
|
140
|
+
isProjectTrusted: () => true,
|
|
141
|
+
signal: undefined,
|
|
142
|
+
abort: () => { },
|
|
143
|
+
hasPendingMessages: () => false,
|
|
144
|
+
shutdown: () => { },
|
|
92
145
|
getContextUsage: () => ({ ...usage }),
|
|
93
|
-
compact: (opts) => {
|
|
146
|
+
compact: (opts) => {
|
|
147
|
+
compactCalls.push(opts);
|
|
148
|
+
return undefined;
|
|
149
|
+
},
|
|
94
150
|
getSystemPrompt: () => "system base",
|
|
95
151
|
...over,
|
|
96
152
|
};
|
|
97
153
|
}
|
|
98
154
|
const pi = {
|
|
99
|
-
on: (ev, h) => {
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
155
|
+
on: (ev, h) => {
|
|
156
|
+
if (!handlers[ev])
|
|
157
|
+
handlers[ev] = [];
|
|
158
|
+
handlers[ev].push(h);
|
|
159
|
+
},
|
|
160
|
+
registerCommand: () => { },
|
|
161
|
+
registerTool: () => { },
|
|
162
|
+
registerShortcut: () => { },
|
|
163
|
+
registerFlag: () => { },
|
|
164
|
+
getFlag: () => undefined,
|
|
165
|
+
registerMessageRenderer: () => { },
|
|
166
|
+
registerEntryRenderer: () => { },
|
|
167
|
+
sendMessage: () => { },
|
|
168
|
+
sendUserMessage: () => { },
|
|
169
|
+
appendEntry: () => { },
|
|
170
|
+
setSessionName: () => { },
|
|
171
|
+
getSessionName: () => undefined,
|
|
172
|
+
setLabel: () => { },
|
|
173
|
+
exec: async () => ({ stdout: "", stderr: "", code: 0 }),
|
|
174
|
+
getActiveTools: () => [],
|
|
175
|
+
getAllTools: () => [],
|
|
176
|
+
setActiveTools: () => { },
|
|
177
|
+
getCommands: () => [],
|
|
178
|
+
setModel: async () => false,
|
|
179
|
+
getThinkingLevel: () => "off",
|
|
108
180
|
setThinkingLevel: () => { },
|
|
109
181
|
};
|
|
110
182
|
const mod = require("./mega-compact.js");
|
|
111
183
|
mod.default(pi);
|
|
112
184
|
const { lastRuntime } = require("./mega-events.js");
|
|
113
|
-
const fire = async (ev, event, ctx) => {
|
|
114
|
-
|
|
185
|
+
const fire = async (ev, event, ctx) => {
|
|
186
|
+
let r;
|
|
187
|
+
for (const h of handlers[ev] || [])
|
|
188
|
+
r = await h(event, ctx);
|
|
189
|
+
return r;
|
|
190
|
+
};
|
|
115
191
|
return {
|
|
116
|
-
stateDir,
|
|
192
|
+
stateDir,
|
|
193
|
+
handlers,
|
|
194
|
+
compactCalls,
|
|
195
|
+
fire,
|
|
196
|
+
ctx: makeCtx,
|
|
197
|
+
usage,
|
|
198
|
+
buildSession,
|
|
117
199
|
runtime: lastRuntime, // MegaRuntime with diag* counters + rt + trimCache
|
|
118
200
|
// Bypass the 2s debounce so each fire proceeds without real waiting.
|
|
119
|
-
clearDebounce: () => {
|
|
120
|
-
lastRuntime
|
|
201
|
+
clearDebounce: () => {
|
|
202
|
+
if (lastRuntime)
|
|
203
|
+
lastRuntime.debounceUntil = 0;
|
|
204
|
+
},
|
|
121
205
|
};
|
|
122
206
|
}
|
|
123
207
|
test("REPLAY: >=2 gated context events within one epoch replay verbatim (byte-identical)", async () => {
|
|
@@ -185,6 +269,131 @@ test("DEDUP: re-compact that dedups onto a DIFFERENT checkpoint still replays ne
|
|
|
185
269
|
await h.fire("context", { type: "context", messages: setA }, ctx);
|
|
186
270
|
assert.ok(rt.diagLiveTrimReplays > replaysBefore, `replay fired after dedup-onto-different-checkpoint (got ${rt.diagLiveTrimReplays}, was ${replaysBefore})`);
|
|
187
271
|
});
|
|
272
|
+
// D.4-test-1 — Debounce exemption: the replay path sits BEFORE the debounce guard.
|
|
273
|
+
// Two gated events <2s apart (no clearDebounce) must both replay — diagCtxDebounce
|
|
274
|
+
// must NOT increment because the debounce guard is never reached when replay fires.
|
|
275
|
+
test("DEBOUNCE-EXEMPTION: two events <2s apart (no clearDebounce) both replay; debounce never reached", async () => {
|
|
276
|
+
const h = harness();
|
|
277
|
+
const ctx = h.ctx();
|
|
278
|
+
const session = h.buildSession("A", 14);
|
|
279
|
+
// 1) Fresh trim.
|
|
280
|
+
h.clearDebounce(); // first event always needs a clear to pass the time guard
|
|
281
|
+
await h.fire("context", { type: "context", messages: session }, ctx);
|
|
282
|
+
assert.equal(h.runtime.diagLiveTrimFires, 1, "first fire was fresh trim");
|
|
283
|
+
// 2) Fire two events IN QUICK SUCCESSION without clearing the debounce.
|
|
284
|
+
// The replay path (D.2) sits BEFORE the debounce guard, so both should
|
|
285
|
+
// replay the cached trim and the debounce guard is NEVER reached.
|
|
286
|
+
const dbgBefore = h.runtime.diagCtxDebounce;
|
|
287
|
+
const rpyBefore = h.runtime.diagLiveTrimReplays;
|
|
288
|
+
await h.fire("context", { type: "context", messages: session }, ctx);
|
|
289
|
+
await h.fire("context", { type: "context", messages: session }, ctx);
|
|
290
|
+
assert.equal(h.runtime.diagCtxDebounce, dbgBefore, `debounce counter unchanged (${h.runtime.diagCtxDebounce} == ${dbgBefore}) — replay path was reached, not debounce`);
|
|
291
|
+
assert.ok(h.runtime.diagLiveTrimReplays >= rpyBefore + 2, `both events replayed (replays ${h.runtime.diagLiveTrimReplays} >= ${rpyBefore}+2)`);
|
|
292
|
+
});
|
|
293
|
+
// D.4-test-2 — Skip→replay fallback: when runCompact returns {skipped: true} and
|
|
294
|
+
// a valid trimCache exists, the handler replays the cached trim instead of returning
|
|
295
|
+
// empty. We force a skip by firing with a 1-message session (view.length ≤ 1) AFTER
|
|
296
|
+
// a fresh trim with a full session has populated trimCache.
|
|
297
|
+
test("SKIP-FALLBACK: runCompact skipped + valid trimCache → replays cached trim", async () => {
|
|
298
|
+
const h = harness();
|
|
299
|
+
const ctx = h.ctx();
|
|
300
|
+
const session = h.buildSession("A", 14);
|
|
301
|
+
// 1) Fresh trim with full session → populates trimCache with a valid cut.
|
|
302
|
+
h.clearDebounce();
|
|
303
|
+
await h.fire("context", { type: "context", messages: session }, ctx);
|
|
304
|
+
assert.equal(h.runtime.diagLiveTrimFires, 1, "fresh trim populated trimCache");
|
|
305
|
+
assert.ok(h.runtime.trimCache, "trimCache is set");
|
|
306
|
+
// 2) Lower the cut so a 1-message session still passes the cut≤length guard.
|
|
307
|
+
// The skip→replay path checks cut <= messages.length before replaying.
|
|
308
|
+
h.runtime.trimCache.cut = 0;
|
|
309
|
+
// 3) Drive context growth so grewEnough=true (replay skipped → runCompact runs).
|
|
310
|
+
// Then fire with just 1 message → runCompact: view.length ≤ 1 → {skipped: true}.
|
|
311
|
+
h.usage.percent = null; // token-basis path
|
|
312
|
+
h.usage.tokens = 200100; // grew 100 >= 25 (effectiveThreshold * 0.5)
|
|
313
|
+
h.clearDebounce();
|
|
314
|
+
const oneMsg = [h.buildSession("X", 1)[0]]; // single user message
|
|
315
|
+
await h.fire("context", { type: "context", messages: oneMsg }, ctx);
|
|
316
|
+
assert.ok(h.runtime.diagCtxRunSkipped >= 1, `diagCtxRunSkipped incremented (got ${h.runtime.diagCtxRunSkipped})`);
|
|
317
|
+
// The skip path replays trimCache → diagLiveTrimReplays increments.
|
|
318
|
+
assert.ok(h.runtime.diagLiveTrimReplays >= 1, `skip→replay fired (replays ${h.runtime.diagLiveTrimReplays} >= 1)`);
|
|
319
|
+
});
|
|
320
|
+
// D.4-test-3 — Recompact delta boundary: config.recompactPctDelta = 50.
|
|
321
|
+
// 49% growth → replay (not enough to re-compact).
|
|
322
|
+
// 51% growth → fresh compaction (exceeds the 50% delta threshold).
|
|
323
|
+
//
|
|
324
|
+
// diagLiveTrimFires counts every trim response (replay OR fresh), including
|
|
325
|
+
// the initial fresh trim, so cumulative counts can't validate discrete steps.
|
|
326
|
+
// Instead we snapshot (fires, replays) before each step and assert the delta.
|
|
327
|
+
test("DELTA-BOUNDARY: 49% growth → replay; 51% growth → fresh compaction", async () => {
|
|
328
|
+
const h = harness();
|
|
329
|
+
const ctx = h.ctx();
|
|
330
|
+
const session = h.buildSession("A", 14);
|
|
331
|
+
// Start at low context (percent=5). The handler captures ctxPct from the first
|
|
332
|
+
// trim, then checks pct - ctxPct >= 50 (config.recompactPctDelta default=50).
|
|
333
|
+
h.usage.percent = 5;
|
|
334
|
+
h.usage.tokens = 200000;
|
|
335
|
+
// 1) Fresh trim at pct=5 → trimCache.ctxPct = 5.
|
|
336
|
+
h.clearDebounce();
|
|
337
|
+
await h.fire("context", { type: "context", messages: session }, ctx);
|
|
338
|
+
assert.ok(h.runtime.diagLiveTrimFires >= 1, "fresh trim at pct=5");
|
|
339
|
+
assert.equal(h.runtime.trimCache?.ctxPct, 5, "ctxPct captured as 5");
|
|
340
|
+
// 2) 49% growth: pct=54. grewEnough = 54-5 = 49 < 50 → replay.
|
|
341
|
+
// Replay increments BOTH fires and replays (line 247-248).
|
|
342
|
+
h.usage.percent = 54;
|
|
343
|
+
h.clearDebounce();
|
|
344
|
+
const { fires: f2, replays: r2 } = {
|
|
345
|
+
fires: h.runtime.diagLiveTrimFires,
|
|
346
|
+
replays: h.runtime.diagLiveTrimReplays,
|
|
347
|
+
};
|
|
348
|
+
await h.fire("context", { type: "context", messages: session }, ctx);
|
|
349
|
+
assert.equal(h.runtime.diagLiveTrimFires, f2 + 1, `49% growth: fires +1 (replay counted as fire, ${f2}→${h.runtime.diagLiveTrimFires})`);
|
|
350
|
+
assert.equal(h.runtime.diagLiveTrimReplays, r2 + 1, `49% growth: replays +1 (${r2}→${h.runtime.diagLiveTrimReplays})`);
|
|
351
|
+
// 3) 51% growth: pct=56. grewEnough = 56-5 = 51 >= 50 → falls through to
|
|
352
|
+
// debounce → runCompact → fresh compaction (line 509).
|
|
353
|
+
// Fresh compaction increments fires but NOT replays.
|
|
354
|
+
h.usage.percent = 56;
|
|
355
|
+
h.clearDebounce();
|
|
356
|
+
const { fires: f3, replays: r3 } = {
|
|
357
|
+
fires: h.runtime.diagLiveTrimFires,
|
|
358
|
+
replays: h.runtime.diagLiveTrimReplays,
|
|
359
|
+
};
|
|
360
|
+
await h.fire("context", { type: "context", messages: session }, ctx);
|
|
361
|
+
assert.equal(h.runtime.diagLiveTrimFires, f3 + 1, `51% growth: fires +1 (fresh compaction, ${f3}→${h.runtime.diagLiveTrimFires})`);
|
|
362
|
+
assert.equal(h.runtime.diagLiveTrimReplays, r3, `51% growth: replays unchanged (fresh compaction ≠ replay, stays ${r3})`);
|
|
363
|
+
});
|
|
364
|
+
// D.4-test-4 — Epoch invalidation (PREVENT-PI-001/002 guard): a checkpointId
|
|
365
|
+
// mismatch means the durable transcript was truncated (session_compact or
|
|
366
|
+
// resetRuntime). The replay guard MUST reject a stale trimCache in that case.
|
|
367
|
+
test("EPOCH-INVALIDATION: checkpointId mismatch → replay does NOT fire (PREVENT-PI-001/002)", async () => {
|
|
368
|
+
const h = harness();
|
|
369
|
+
const ctx = h.ctx();
|
|
370
|
+
const session = h.buildSession("A", 14);
|
|
371
|
+
// 1) Fresh trim → trimCache.checkpointId = lastCheckpointId = "cp-1".
|
|
372
|
+
h.clearDebounce();
|
|
373
|
+
await h.fire("context", { type: "context", messages: session }, ctx);
|
|
374
|
+
assert.equal(h.runtime.diagLiveTrimFires, 1, "fresh trim");
|
|
375
|
+
assert.ok(h.runtime.trimCache?.checkpointId, "trimCache has checkpointId");
|
|
376
|
+
// 2) Simulate a session_compact (durable truncation) by advancing
|
|
377
|
+
// lastCheckpointId (harder: the compact path tracks its own epoch).
|
|
378
|
+
// A mismatch between trimCache.checkpointId and rt.lastCheckpointId means
|
|
379
|
+
// the cached cut is for a truncated transcript → replay must NOT fire.
|
|
380
|
+
h.runtime.rt.lastCheckpointId = "cp-mismatch";
|
|
381
|
+
assert.notEqual(h.runtime.trimCache?.checkpointId, h.runtime.rt.lastCheckpointId, "checkpointIds differ after simulated durable truncation");
|
|
382
|
+
// 3) Fire the same session (no growth → would normally replay if epoch matched).
|
|
383
|
+
const rpyBefore = h.runtime.diagLiveTrimReplays;
|
|
384
|
+
h.clearDebounce();
|
|
385
|
+
await h.fire("context", { type: "context", messages: session }, ctx);
|
|
386
|
+
// Replay path was blocked by the checkpointId guard → a fresh trim fires instead.
|
|
387
|
+
assert.equal(h.runtime.diagLiveTrimReplays, rpyBefore, `replay NOT incremented (was ${rpyBefore}, still ${h.runtime.diagLiveTrimReplays}) — stale trimCache rejected`);
|
|
388
|
+
// A fresh compaction should have been triggered instead (grewEnough=false, but
|
|
389
|
+
// replay guard failed → falls through to debounce → runCompact → fresh trim).
|
|
390
|
+
// Actually: grewEnough is false (no growth since last fire), and the replay
|
|
391
|
+
// guard rejected → falls to debounce (cleared) → runCompact.
|
|
392
|
+
// runCompact may skip or produce a fresh trim; either way the stale replay is blocked.
|
|
393
|
+
assert.ok(h.runtime.diagLiveTrimFires >= 2 || h.runtime.diagCtxRunSkipped >= 1, `handler did NOT replay stale trimCache (fires=${h.runtime.diagLiveTrimFires}, skipped=${h.runtime.diagCtxRunSkipped}, replays=${h.runtime.diagLiveTrimReplays})`);
|
|
394
|
+
// Restore for cleanup.
|
|
395
|
+
h.runtime.rt.lastCheckpointId = "cp-1";
|
|
396
|
+
});
|
|
188
397
|
test("cleanup", async () => {
|
|
189
398
|
await closeVectorIndex();
|
|
190
399
|
rmSync(baseTmp, { recursive: true, force: true });
|