pi-mega-compact 0.11.4 → 0.11.5
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 +19 -0
- package/dist/extensions/dashboard-server/api-contracts/memory.js +8 -0
- package/dist/extensions/dashboard-server/api-contracts/provider-cache.js +1 -0
- package/dist/extensions/dashboard-server/api-contracts/setup.js +10 -0
- package/dist/extensions/dashboard-server/index-reader.js +6 -2
- package/dist/extensions/dashboard-server/routes-cache.js +115 -55
- package/dist/extensions/dashboard-server/routes-memory.js +51 -0
- package/dist/extensions/dashboard-server/routes-repo.js +2 -2
- package/dist/extensions/dashboard-server/routes-setup.js +162 -0
- package/dist/extensions/dashboard-server/routes.js +2 -0
- package/dist/extensions/dashboard-server/server.js +7 -1
- package/dist/extensions/mega-commands.js +189 -1
- package/dist/extensions/mega-config.js +2 -0
- package/dist/extensions/mega-events/agent-handlers.js +19 -4
- package/dist/extensions/mega-events/compact-handlers.js +1 -0
- package/dist/extensions/mega-events/context-handler.js +37 -92
- package/dist/extensions/mega-events/context-hwm.js +51 -0
- package/dist/extensions/mega-events/error-classifier.js +16 -5
- package/dist/extensions/mega-events/mirror-append.js +107 -0
- package/dist/extensions/mega-events/outage-advisor.js +7 -1
- package/dist/extensions/mega-events/perf-handler.js +51 -1
- package/dist/extensions/mega-events/recall-tail.js +59 -0
- package/dist/extensions/mega-events/session-handlers.js +15 -8
- package/dist/extensions/mega-runtime/reset-runtime.js +5 -0
- package/dist/extensions/mega-runtime/runtime.js +6 -0
- package/dist/src/embedder.js +41 -2
- package/dist/src/memoryStats.js +75 -0
- package/dist/src/prefix-break.js +43 -0
- package/dist/src/pricing.js +1 -1
- package/dist/src/store/sqlite/perf-samples.js +144 -16
- package/dist/src/store/turns/memory-store.js +8 -0
- package/dist/src/store/turns/sqlite-store.js +14 -3
- package/dist/src/store/turns/types.js +18 -1
- package/dist/src/store/vectorIndex.js +26 -5
- package/extensions/dashboard-client/dist/assets/{AchievementTiles-vEo2MtE2.js → AchievementTiles-BoL7qBOJ.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{AchievementTiles-vEo2MtE2.js.map → AchievementTiles-BoL7qBOJ.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/AchievementsTab-BFDE3HYc.js +2 -0
- package/extensions/dashboard-client/dist/assets/{AchievementsTab-DjxfYrDc.js.map → AchievementsTab-BFDE3HYc.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/CacheTab-eKVc-NV1.js +2 -0
- package/extensions/dashboard-client/dist/assets/CacheTab-eKVc-NV1.js.map +1 -0
- package/extensions/dashboard-client/dist/assets/{ConfigTab-Cm6ymbmx.js → ConfigTab-DDFE-ckA.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{ConfigTab-Cm6ymbmx.js.map → ConfigTab-DDFE-ckA.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{EventsTab-DXWl_YzI.js → EventsTab-B6UxZ7PM.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{EventsTab-DXWl_YzI.js.map → EventsTab-B6UxZ7PM.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{GameTab-BLDudcO5.js → GameTab-DehUX-KE.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{GameTab-BLDudcO5.js.map → GameTab-DehUX-KE.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{MaintenanceTab-DLkKCztn.js → MaintenanceTab-0GWRt4wn.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{MaintenanceTab-DLkKCztn.js.map → MaintenanceTab-0GWRt4wn.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{MetricsTab-Cq4u-rZF.js → MetricsTab-C3rwMVsN.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{MetricsTab-Cq4u-rZF.js.map → MetricsTab-C3rwMVsN.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/OverviewTab-39O9_x5j.js +2 -0
- package/extensions/dashboard-client/dist/assets/{OverviewTab-D4kGvsiQ.js.map → OverviewTab-39O9_x5j.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/ReposTab-Cfj6Q5sH.js +2 -0
- package/extensions/dashboard-client/dist/assets/ReposTab-Cfj6Q5sH.js.map +1 -0
- package/extensions/dashboard-client/dist/assets/{SessionsTab-DZC2-GCn.js → SessionsTab-DXDTCi3r.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{SessionsTab-DZC2-GCn.js.map → SessionsTab-DXDTCi3r.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/SetupTab-mMlfunJa.js +2 -0
- package/extensions/dashboard-client/dist/assets/SetupTab-mMlfunJa.js.map +1 -0
- package/extensions/dashboard-client/dist/assets/TimeSavedCard-Cw1dJ4e9.js +2 -0
- package/extensions/dashboard-client/dist/assets/TimeSavedCard-Cw1dJ4e9.js.map +1 -0
- package/extensions/dashboard-client/dist/assets/{TopicsTab-01G71hv1.js → TopicsTab-BAw972BV.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{TopicsTab-01G71hv1.js.map → TopicsTab-BAw972BV.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{TurnsTab-DLRg0LZT.js → TurnsTab-Cf5mGIdl.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{TurnsTab-DLRg0LZT.js.map → TurnsTab-Cf5mGIdl.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/format-COjDIVGj.js +2 -0
- package/extensions/dashboard-client/dist/assets/format-COjDIVGj.js.map +1 -0
- package/extensions/dashboard-client/dist/assets/{index-BX0bcgLu.js → index-4gQ7auad.js} +10 -10
- package/extensions/dashboard-client/dist/assets/index-4gQ7auad.js.map +1 -0
- package/extensions/dashboard-client/dist/assets/pricing-CvE4NllQ.js +2 -0
- package/extensions/dashboard-client/dist/assets/pricing-CvE4NllQ.js.map +1 -0
- package/extensions/dashboard-client/dist/assets/{useSSE-BBYt5UPB.js → useSSE-DNgMuyP6.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{useSSE-BBYt5UPB.js.map → useSSE-DNgMuyP6.js.map} +1 -1
- package/extensions/dashboard-client/dist/index.html +1 -1
- package/extensions/dashboard-client/src/App.tsx +4 -0
- package/extensions/dashboard-client/src/api/client.ts +14 -0
- package/extensions/dashboard-client/src/components/ActiveReposTable.tsx +21 -12
- package/extensions/dashboard-client/src/components/ProviderCacheCard.tsx +56 -0
- package/extensions/dashboard-client/src/components/SavingsByModelTable.tsx +38 -57
- package/extensions/dashboard-client/src/tabs/CacheTab.tsx +1 -0
- package/extensions/dashboard-client/src/tabs/SetupTab.tsx +355 -0
- package/extensions/dashboard-client/tsconfig.json +3 -2
- package/extensions/dashboard-client/vite.config.ts +2 -0
- package/extensions/dashboard-server/api-contracts/endpoints.ts +36 -3
- package/extensions/dashboard-server/api-contracts/index.ts +7 -0
- package/extensions/dashboard-server/api-contracts/memory.ts +27 -0
- package/extensions/dashboard-server/api-contracts/multi-repo.ts +231 -231
- package/extensions/dashboard-server/api-contracts/provider-cache.ts +37 -0
- package/extensions/dashboard-server/api-contracts/setup.ts +58 -0
- package/extensions/dashboard-server/index-reader.ts +138 -121
- package/extensions/dashboard-server/routes-cache.ts +161 -85
- package/extensions/dashboard-server/routes-memory.ts +63 -0
- package/extensions/dashboard-server/routes-repo.ts +36 -36
- package/extensions/dashboard-server/routes-setup.ts +181 -0
- package/extensions/dashboard-server/routes.ts +2 -0
- package/extensions/dashboard-server/server.ts +6 -0
- package/extensions/mega-commands.ts +211 -1
- package/extensions/mega-config.ts +10 -0
- package/extensions/mega-events/agent-handlers.ts +20 -4
- package/extensions/mega-events/compact-handlers.ts +1 -0
- package/extensions/mega-events/context-handler.ts +45 -110
- package/extensions/mega-events/context-hwm.ts +85 -0
- package/extensions/mega-events/error-classifier.ts +15 -4
- package/extensions/mega-events/mirror-append.ts +155 -0
- package/extensions/mega-events/outage-advisor.ts +11 -5
- package/extensions/mega-events/perf-handler.ts +79 -5
- package/extensions/mega-events/recall-tail.ts +88 -0
- package/extensions/mega-events/session-handlers.ts +14 -7
- package/extensions/mega-runtime/helpers.ts +12 -0
- package/extensions/mega-runtime/reset-runtime.ts +5 -0
- package/extensions/mega-runtime/runtime.ts +6 -0
- package/package.json +5 -2
- package/src/embedder.ts +42 -2
- package/src/memoryStats.ts +107 -0
- package/src/prefix-break.ts +83 -0
- package/src/pricing.ts +2 -2
- package/src/store/sqlite/perf-samples.ts +215 -22
- package/src/store/turns/memory-store.ts +10 -1
- package/src/store/turns/sqlite-store.ts +27 -15
- package/src/store/turns/types.ts +21 -0
- package/src/store/vectorIndex.ts +33 -4
- package/dist/extensions/conflict-scan.test.js +0 -115
- package/dist/extensions/dashboard-server/api-contracts.test.js +0 -884
- package/dist/extensions/dashboard-server/html.test.js +0 -52
- package/dist/extensions/dashboard-server/perf-server.test.js +0 -80
- package/dist/extensions/dashboard-server/routes-cache.test.js +0 -248
- package/dist/extensions/dashboard-server/server.test.js +0 -120
- package/dist/extensions/dashboard-server-s32.test.js +0 -181
- package/dist/extensions/dashboard-server.test.js +0 -339
- package/dist/extensions/mega-cache-replay.test.js +0 -400
- package/dist/extensions/mega-compact-s38.test.js +0 -1383
- package/dist/extensions/mega-compact.test.js +0 -1112
- package/dist/extensions/mega-events.test.js +0 -47
- package/dist/extensions/mega-game-cmds.test.js +0 -163
- package/dist/extensions/mega-runtime/snapshot.test.js +0 -127
- package/dist/extensions/mega-runtime/state.test.js +0 -266
- package/dist/extensions/mega-runtime/widget.test.js +0 -343
- package/dist/extensions/mega-shutdown-widget.test.js +0 -121
- package/dist/extensions/mega-teamrun.test.js +0 -156
- package/dist/extensions/mega-trim.test.js +0 -58
- package/dist/extensions/mega-turn-store.test.js +0 -68
- package/dist/src/boundary.test.js +0 -170
- package/dist/src/compact.test.js +0 -78
- package/dist/src/config/themes.test.js +0 -94
- package/dist/src/dedup/dedup.test.js +0 -41
- package/dist/src/dedup/l1.test.js +0 -50
- package/dist/src/dedup/raptor/buildHistory.test.js +0 -292
- package/dist/src/dedup/raptor/multilevel-serve.test.js +0 -229
- package/dist/src/dedup/raptor/multilevel.test.js +0 -238
- package/dist/src/dedup/raptor/promote.test.js +0 -69
- package/dist/src/dedup/raptor/raptor.test.js +0 -248
- package/dist/src/dedup/raptor/retrieval.test.js +0 -95
- package/dist/src/dedup/raptor/serve-gate.test.js +0 -298
- package/dist/src/dedup/sprint12.test.js +0 -219
- package/dist/src/dedup-engine.test.js +0 -472
- package/dist/src/driftDetection.test.js +0 -87
- package/dist/src/e2e.test.js +0 -698
- package/dist/src/engine.test.js +0 -111
- package/dist/src/extractive.test.js +0 -147
- package/dist/src/fork.test.js +0 -81
- package/dist/src/game/scoring.test.js +0 -98
- package/dist/src/httpEmbedder.test.js +0 -277
- package/dist/src/importance.test.js +0 -372
- package/dist/src/intent.test.js +0 -78
- package/dist/src/log.test.js +0 -42
- package/dist/src/mechanical-fix.test.js +0 -65
- package/dist/src/memory.test.js +0 -70
- package/dist/src/memoryConsolidate.test.js +0 -38
- package/dist/src/memoryOps.test.js +0 -129
- package/dist/src/memoryRecall.test.js +0 -171
- package/dist/src/memoryRoundtrip.test.js +0 -137
- package/dist/src/metrics/turns.test.js +0 -152
- package/dist/src/mirror/mirror.test.js +0 -185
- package/dist/src/raptor-inject-summaries.test.js +0 -162
- package/dist/src/ratio.bench.test.js +0 -897
- package/dist/src/recall.integration.test.js +0 -77
- package/dist/src/recall.test.js +0 -379
- package/dist/src/sprint14.test.js +0 -219
- package/dist/src/sprint4x-rag-verification.test.js +0 -93
- package/dist/src/store/compression.test.js +0 -139
- package/dist/src/store/memoryIndex.test.js +0 -51
- package/dist/src/store/migrate.test.js +0 -139
- package/dist/src/store/pgOpenGuard.test.js +0 -74
- package/dist/src/store/phase01.test.js +0 -81
- package/dist/src/store/phase04.test.js +0 -54
- package/dist/src/store/sprint10.test.js +0 -186
- package/dist/src/store/sqlite/game-achievements.test.js +0 -67
- package/dist/src/store/sqlite/game-scores.test.js +0 -106
- package/dist/src/store/sqlite/game-state.test.js +0 -76
- package/dist/src/store/sqlite/global-index.test.js +0 -136
- package/dist/src/store/sqlite/mechanical-fix.test.js +0 -146
- package/dist/src/store/sqlite/perf-samples.test.js +0 -146
- package/dist/src/store/sqlite/raptor.test.js +0 -106
- package/dist/src/store/sqlite/turns.test.js +0 -183
- package/dist/src/store/sqlite.cachehit.test.js +0 -55
- package/dist/src/store/sqlite.dbmaint.test.js +0 -158
- package/dist/src/store/sqlite.dbmirror.test.js +0 -184
- package/dist/src/store/turns/contract-compliance.test.js +0 -428
- package/dist/src/store/turns/memory-store.test.js +0 -9
- package/dist/src/store/turns/migrations.test.js +0 -138
- package/dist/src/store/turns/sqlite-store.test.js +0 -144
- package/dist/src/store/vectorIndex.test.js +0 -123
- package/dist/src/store.test.js +0 -161
- package/dist/src/supersede.test.js +0 -36
- package/dist/src/topics/cluster.test.js +0 -150
- package/dist/src/topics/store.test.js +0 -117
- package/dist/src/types.test.js +0 -9
- package/dist/src/vector-search-cache.test.js +0 -157
- package/dist/src/vectorStore.test.js +0 -479
- package/dist/src/wiki.test.js +0 -171
- package/extensions/conflict-scan.test.ts +0 -129
- package/extensions/dashboard-client/dist/assets/AchievementsTab-DjxfYrDc.js +0 -2
- package/extensions/dashboard-client/dist/assets/CacheTab-Dnpv94wq.js +0 -2
- package/extensions/dashboard-client/dist/assets/CacheTab-Dnpv94wq.js.map +0 -1
- package/extensions/dashboard-client/dist/assets/OverviewTab-D4kGvsiQ.js +0 -2
- package/extensions/dashboard-client/dist/assets/ReposTab-C0Wnrf2u.js +0 -2
- package/extensions/dashboard-client/dist/assets/ReposTab-C0Wnrf2u.js.map +0 -1
- package/extensions/dashboard-client/dist/assets/TimeSavedCard-UqljSyP-.js +0 -2
- package/extensions/dashboard-client/dist/assets/TimeSavedCard-UqljSyP-.js.map +0 -1
- package/extensions/dashboard-client/dist/assets/index-BX0bcgLu.js.map +0 -1
- package/extensions/dashboard-server/api-contracts.test.ts +0 -1065
- package/extensions/dashboard-server/html.test.ts +0 -62
- package/extensions/dashboard-server/perf-server.test.ts +0 -101
- package/extensions/dashboard-server/routes-cache.test.ts +0 -302
- package/extensions/dashboard-server/server.test.ts +0 -131
- package/extensions/dashboard-server-s32.test.ts +0 -195
- package/extensions/dashboard-server.test.ts +0 -382
- package/extensions/mega-cache-replay.test.ts +0 -526
- package/extensions/mega-compact-s38.test.ts +0 -1433
- package/extensions/mega-compact.test.ts +0 -1509
- package/extensions/mega-events.test.ts +0 -55
- package/extensions/mega-game-cmds.test.ts +0 -197
- package/extensions/mega-runtime/snapshot.test.ts +0 -139
- package/extensions/mega-runtime/state.test.ts +0 -262
- package/extensions/mega-runtime/widget.test.ts +0 -468
- package/extensions/mega-shutdown-widget.test.ts +0 -141
- package/extensions/mega-teamrun.test.ts +0 -176
- package/extensions/mega-trim.test.ts +0 -64
- package/extensions/mega-turn-store.test.ts +0 -108
- package/src/boundary.test.ts +0 -187
- package/src/compact.test.ts +0 -99
- package/src/config/themes.test.ts +0 -116
- package/src/dedup/dedup.test.ts +0 -46
- package/src/dedup/l1.test.ts +0 -57
- package/src/dedup/raptor/buildHistory.test.ts +0 -353
- package/src/dedup/raptor/multilevel-serve.test.ts +0 -273
- package/src/dedup/raptor/multilevel.test.ts +0 -325
- package/src/dedup/raptor/promote.test.ts +0 -82
- package/src/dedup/raptor/raptor.test.ts +0 -297
- package/src/dedup/raptor/retrieval.test.ts +0 -118
- package/src/dedup/raptor/serve-gate.test.ts +0 -348
- package/src/dedup/sprint12.test.ts +0 -242
- package/src/dedup-engine.test.ts +0 -670
- package/src/driftDetection.test.ts +0 -100
- package/src/e2e.test.ts +0 -843
- package/src/engine.test.ts +0 -123
- package/src/extractive.test.ts +0 -174
- package/src/fork.test.ts +0 -94
- package/src/game/scoring.test.ts +0 -103
- package/src/httpEmbedder.test.ts +0 -286
- package/src/importance.test.ts +0 -538
- package/src/intent.test.ts +0 -87
- package/src/log.test.ts +0 -47
- package/src/mechanical-fix.test.ts +0 -70
- package/src/memory.test.ts +0 -92
- package/src/memoryConsolidate.test.ts +0 -47
- package/src/memoryOps.test.ts +0 -148
- package/src/memoryRecall.test.ts +0 -194
- package/src/memoryRoundtrip.test.ts +0 -155
- package/src/metrics/turns.test.ts +0 -165
- package/src/mirror/mirror.test.ts +0 -240
- package/src/raptor-inject-summaries.test.ts +0 -228
- package/src/ratio.bench.test.ts +0 -1316
- package/src/recall.integration.test.ts +0 -96
- package/src/recall.test.ts +0 -467
- package/src/sprint14.test.ts +0 -245
- package/src/sprint4x-rag-verification.test.ts +0 -119
- package/src/store/compression.test.ts +0 -168
- package/src/store/memoryIndex.test.ts +0 -61
- package/src/store/migrate.test.ts +0 -158
- package/src/store/pgOpenGuard.test.ts +0 -89
- package/src/store/phase01.test.ts +0 -88
- package/src/store/phase04.test.ts +0 -58
- package/src/store/sprint10.test.ts +0 -214
- package/src/store/sqlite/game-achievements.test.ts +0 -80
- package/src/store/sqlite/game-scores.test.ts +0 -132
- package/src/store/sqlite/game-state.test.ts +0 -89
- package/src/store/sqlite/global-index.test.ts +0 -222
- package/src/store/sqlite/mechanical-fix.test.ts +0 -162
- package/src/store/sqlite/perf-samples.test.ts +0 -169
- package/src/store/sqlite/raptor.test.ts +0 -139
- package/src/store/sqlite/turns.test.ts +0 -218
- package/src/store/sqlite.cachehit.test.ts +0 -68
- package/src/store/sqlite.dbmaint.test.ts +0 -193
- package/src/store/sqlite.dbmirror.test.ts +0 -229
- package/src/store/turns/contract-compliance.test.ts +0 -562
- package/src/store/turns/memory-store.test.ts +0 -15
- package/src/store/turns/migrations.test.ts +0 -161
- package/src/store/turns/sqlite-store.test.ts +0 -161
- package/src/store/vectorIndex.test.ts +0 -140
- package/src/store.test.ts +0 -191
- package/src/supersede.test.ts +0 -42
- package/src/topics/cluster.test.ts +0 -176
- package/src/topics/store.test.ts +0 -132
- package/src/types.test.ts +0 -10
- package/src/vector-search-cache.test.ts +0 -190
- package/src/vectorStore.test.ts +0 -533
- package/src/wiki.test.ts +0 -217
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { appendRawTranscript } from "../../src/store/sqlite.js";
|
|
2
|
+
import { computeContentDigest } from "../../src/dedup/digest.js";
|
|
3
|
+
import { ensureHwmTable, readHwm, writeHwm, dropHwm, } from "./context-hwm.js";
|
|
4
|
+
/**
|
|
5
|
+
* Append incoming messages to raw_transcript with HWM incremental support.
|
|
6
|
+
*
|
|
7
|
+
* On fork/rewind (shorter message list or boundary hash mismatch), the HWM
|
|
8
|
+
* is dropped and all messages are reprocessed.
|
|
9
|
+
*/
|
|
10
|
+
export function appendMirrorMessages(db, messages, sessionId, epochId, currentTurn) {
|
|
11
|
+
ensureHwmTable(db);
|
|
12
|
+
const hwm = readHwm(db, sessionId);
|
|
13
|
+
let tailStart = 0;
|
|
14
|
+
let needDrop = false;
|
|
15
|
+
if (hwm) {
|
|
16
|
+
if (messages.length <= hwm.lastSeq) {
|
|
17
|
+
// Session was shortened (fork/rewind/clear) — full reprocess.
|
|
18
|
+
needDrop = true;
|
|
19
|
+
}
|
|
20
|
+
else {
|
|
21
|
+
// Verify boundary integrity: hash of message at hwm.lastSeq-1
|
|
22
|
+
// must match the stored hash.
|
|
23
|
+
const boundaryMsg = messages[hwm.lastSeq - 1];
|
|
24
|
+
const boundaryHash = contentHashOf(boundaryMsg.content);
|
|
25
|
+
if (boundaryHash === hwm.lastContentHash) {
|
|
26
|
+
tailStart = hwm.lastSeq;
|
|
27
|
+
}
|
|
28
|
+
else {
|
|
29
|
+
needDrop = true;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
if (needDrop) {
|
|
34
|
+
dropHwm(db, sessionId);
|
|
35
|
+
}
|
|
36
|
+
// Process tail (or all if tailStart === 0).
|
|
37
|
+
let rowsProcessed = 0;
|
|
38
|
+
for (let i = tailStart; i < messages.length; i++) {
|
|
39
|
+
const raw = toRawRow(messages[i], sessionId, epochId, currentTurn);
|
|
40
|
+
if (raw) {
|
|
41
|
+
appendRawTranscript(db, raw);
|
|
42
|
+
rowsProcessed++;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
// Write new HWM.
|
|
46
|
+
if (messages.length > 0) {
|
|
47
|
+
const lastMsg = messages[messages.length - 1];
|
|
48
|
+
writeHwm(db, {
|
|
49
|
+
sessionId,
|
|
50
|
+
lastSeq: messages.length,
|
|
51
|
+
lastContentHash: contentHashOf(lastMsg.content),
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
return { rowsProcessed };
|
|
55
|
+
}
|
|
56
|
+
/** Single rule for hashing message content on BOTH sides of the HWM
|
|
57
|
+
* (write + boundary check) — a mismatch here silently defeats the
|
|
58
|
+
* incremental path (every event would full-reprocess). null/undefined → "". */
|
|
59
|
+
function contentHashOf(content) {
|
|
60
|
+
if (content == null)
|
|
61
|
+
return "";
|
|
62
|
+
const bytes = typeof content === "string"
|
|
63
|
+
? content
|
|
64
|
+
: JSON.stringify(canonicalize(content));
|
|
65
|
+
return computeContentDigest(bytes).contentHash;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Canonicalize a value for deterministic JSON serialization (keys sorted).
|
|
69
|
+
* This is the same logic as the inline function in context-handler.ts.
|
|
70
|
+
*/
|
|
71
|
+
function canonicalize(value) {
|
|
72
|
+
if (value === null || value === undefined)
|
|
73
|
+
return value;
|
|
74
|
+
if (typeof value !== "object")
|
|
75
|
+
return value;
|
|
76
|
+
if (Array.isArray(value))
|
|
77
|
+
return value.map(canonicalize);
|
|
78
|
+
const sorted = Object.keys(value).sort();
|
|
79
|
+
const out = {};
|
|
80
|
+
for (const k of sorted) {
|
|
81
|
+
out[k] = canonicalize(value[k]);
|
|
82
|
+
}
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
85
|
+
/** Convert an AgentMessage to a RawTranscriptRow (same logic as toRawTranscriptRow in context-handler.ts). */
|
|
86
|
+
function toRawRow(msg, sessionId, epochId, currentTurn) {
|
|
87
|
+
const m = msg;
|
|
88
|
+
const content = m.content;
|
|
89
|
+
if (content == null || content === "")
|
|
90
|
+
return null;
|
|
91
|
+
const contentBytes = typeof content === "string"
|
|
92
|
+
? content
|
|
93
|
+
: JSON.stringify(canonicalize(content));
|
|
94
|
+
return {
|
|
95
|
+
contentHash: computeContentDigest(contentBytes).contentHash,
|
|
96
|
+
sessionId,
|
|
97
|
+
seq: 0, // assigned by appendRawTranscript
|
|
98
|
+
role: m.role ?? "unknown",
|
|
99
|
+
contentBytes,
|
|
100
|
+
toolName: m.toolName ?? null,
|
|
101
|
+
messageTimestamp: m.timestamp ?? null,
|
|
102
|
+
checkpointEpoch: epochId,
|
|
103
|
+
turnIndex: currentTurn ?? null,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
// Re-export for convenience when the handler only needs the table ensure.
|
|
107
|
+
export { ensureHwmTable, readHwm, writeHwm, dropHwm };
|
|
@@ -49,5 +49,11 @@ export async function maybeSendProviderOutageAdvisory(effectiveCategory, runtime
|
|
|
49
49
|
...(detail?.signal !== undefined ? { signal: detail.signal } : {}),
|
|
50
50
|
...(detail?.rawText !== undefined ? { rawText: detail.rawText } : {}),
|
|
51
51
|
});
|
|
52
|
-
|
|
52
|
+
// Advisory is dashboard-only (events tab + log). No user-visible message —
|
|
53
|
+
// injecting into the conversation scares users and triggers false-positive
|
|
54
|
+
// re-classification of the resulting turn (2026-07-31 incident).
|
|
55
|
+
if (!config.advisoryChannel) {
|
|
56
|
+
// Legacy path (flag OFF): user-role message injection.
|
|
57
|
+
await safeSendUserMessage(pi, `[mega-compact] the provider is having issues (${runtime.rt.consecutiveErrors} consecutive failures — timeouts/5xx/rate-limits). Retries are bounded and continue automatically; your context is fine — do NOT clear or reset it. Work resumes as soon as the provider recovers.`);
|
|
58
|
+
}
|
|
53
59
|
}
|
|
@@ -1,10 +1,44 @@
|
|
|
1
1
|
import { recordPerfSample } from "../../src/store/sqlite.js";
|
|
2
|
+
import { classifyPrefixBreak } from "../../src/prefix-break.js";
|
|
2
3
|
/** Narrow a turn_end message to its usage block when it is an assistant msg. */
|
|
3
4
|
function usageOf(msg) {
|
|
4
5
|
if (msg.role !== "assistant" || !msg.usage)
|
|
5
6
|
return null;
|
|
6
7
|
return msg.usage;
|
|
7
8
|
}
|
|
9
|
+
/**
|
|
10
|
+
* Attempt to record a prefix_break sample when a significant cache_hit_pct
|
|
11
|
+
* drop is detected between two consecutive turns.
|
|
12
|
+
*
|
|
13
|
+
* Drop threshold: 20 percentage points. When triggered, calls
|
|
14
|
+
* classifyPrefixBreak with the three candidate event timestamps from the
|
|
15
|
+
* runtime and records a `prefix_break` sample. Best-effort + non-fatal.
|
|
16
|
+
*
|
|
17
|
+
* PREVENT-PI-004: guardrails-allow PREVENT-PI-004: local SQLite write only.
|
|
18
|
+
* PREVENT-002: SQL is fully parameterized via recordPerfSample.
|
|
19
|
+
*/
|
|
20
|
+
function tryRecordPrefixBreak(stateDir, prevHitPct, currHitPct, breakAt, runtime) {
|
|
21
|
+
try {
|
|
22
|
+
if (prevHitPct - currHitPct < 20)
|
|
23
|
+
return; // no significant drop
|
|
24
|
+
const events = {
|
|
25
|
+
lastRecallAt: runtime.rt.lastInjectAt, // S53: inject fires alongside recall
|
|
26
|
+
lastCompactAt: runtime.rt.lastCompactAt,
|
|
27
|
+
lastInjectAt: runtime.rt.lastInjectAt,
|
|
28
|
+
};
|
|
29
|
+
const { cause, confidence } = classifyPrefixBreak(breakAt, events);
|
|
30
|
+
recordPerfSample(stateDir, "prefix_break", 0, {
|
|
31
|
+
cause,
|
|
32
|
+
confidence,
|
|
33
|
+
prevHitPct,
|
|
34
|
+
currHitPct,
|
|
35
|
+
breakAt,
|
|
36
|
+
}); // guardrails-allow PREVENT-PI-004: local SQLite write (loopback perf instrumentation)
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
/* non-fatal: prefix-break detection never blocks the agent loop */
|
|
40
|
+
}
|
|
41
|
+
}
|
|
8
42
|
/** Register perf instrumentation handlers + start the 5s cpu/mem interval. */
|
|
9
43
|
export function registerPerfHandler(pi, runtime) {
|
|
10
44
|
// turn_start: record the wall-clock start of the turn. Using Date.now() (not
|
|
@@ -23,6 +57,7 @@ export function registerPerfHandler(pi, runtime) {
|
|
|
23
57
|
});
|
|
24
58
|
// turn_end: compute turn latency + TPS + cache hit % from the assistant
|
|
25
59
|
// message's usage block. One perf_samples row per metric per turn.
|
|
60
|
+
// S53A: tracks prevHitPct across turns to detect prefix breaks.
|
|
26
61
|
pi.on("turn_end", async (event) => {
|
|
27
62
|
try {
|
|
28
63
|
if (runtime.perfTurnStart > 0) {
|
|
@@ -36,7 +71,22 @@ export function registerPerfHandler(pi, runtime) {
|
|
|
36
71
|
recordPerfSample(runtime.currentStateDir, "tps", u.output / durSec, { outputTokens: u.output });
|
|
37
72
|
const denom = u.cacheRead + u.input + u.cacheWrite;
|
|
38
73
|
const hitPct = denom > 0 ? (u.cacheRead / denom) * 100 : 0;
|
|
39
|
-
recordPerfSample(runtime.currentStateDir, "cache_hit_pct", hitPct, {
|
|
74
|
+
recordPerfSample(runtime.currentStateDir, "cache_hit_pct", hitPct, {
|
|
75
|
+
input: u.input,
|
|
76
|
+
cacheRead: u.cacheRead,
|
|
77
|
+
cacheWrite: u.cacheWrite,
|
|
78
|
+
modelName: runtime.currentModel?.modelName,
|
|
79
|
+
modelId: runtime.currentModel?.modelId,
|
|
80
|
+
});
|
|
81
|
+
// S53A: detect significant cache hit % drop → record prefix_break.
|
|
82
|
+
// Only trigger when we have a previous value AND the drop is >20pp.
|
|
83
|
+
if (runtime.rt._prevCacheHitPct != null &&
|
|
84
|
+
runtime.rt._prevCacheHitPct - hitPct >= 20) {
|
|
85
|
+
const breakAt = runtime.perfTurnStart;
|
|
86
|
+
tryRecordPrefixBreak(runtime.currentStateDir, runtime.rt._prevCacheHitPct, hitPct, breakAt, runtime);
|
|
87
|
+
}
|
|
88
|
+
// Stamp for the next turn's comparison (even when no break fires).
|
|
89
|
+
runtime.rt._prevCacheHitPct = hitPct;
|
|
40
90
|
}
|
|
41
91
|
}
|
|
42
92
|
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* True when recall blocks are staged AND the feature flag is ON. Called by the
|
|
3
|
+
* context handler to decide whether to call withRecallTail.
|
|
4
|
+
*/
|
|
5
|
+
export function stagedForTail(runtime, config) {
|
|
6
|
+
if (!config.recallTailInject)
|
|
7
|
+
return false;
|
|
8
|
+
return (runtime.pendingRecallBlock != null ||
|
|
9
|
+
runtime.pendingMemoryRecallBlock != null);
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Append staged recall/memory blocks as a single user-role message at the very
|
|
13
|
+
* tail of the messages array. Returns a NEW array (does not mutate input).
|
|
14
|
+
*
|
|
15
|
+
* Sets `runtime.recallInjectedThisTurn = true` when it actually appends, so the
|
|
16
|
+
* turn_end handler (agent-handlers.ts) consumes the staged blocks only if they
|
|
17
|
+
* reached a view this turn. If a turn ends with no context event, the flag
|
|
18
|
+
* stays false and the blocks remain staged for the next turn.
|
|
19
|
+
*
|
|
20
|
+
* Stable timestamp (runtime.perfTurnStart ?? Date.now()) so replays within the
|
|
21
|
+
* turn are byte-identical (mirrors the v0.8.6 summaryAgentMsg rationale).
|
|
22
|
+
*
|
|
23
|
+
* Non-fatal: on any failure, returns messages unmodified and does NOT set the
|
|
24
|
+
* injected flag. PREVENT-PI-003: the injected message has role "user", never
|
|
25
|
+
* "system".
|
|
26
|
+
*/
|
|
27
|
+
export function withRecallTail(messages, runtime, config) {
|
|
28
|
+
if (!config.recallTailInject)
|
|
29
|
+
return messages;
|
|
30
|
+
try {
|
|
31
|
+
const blocks = [];
|
|
32
|
+
if (runtime.pendingRecallBlock != null) {
|
|
33
|
+
blocks.push(runtime.pendingRecallBlock);
|
|
34
|
+
}
|
|
35
|
+
if (runtime.pendingMemoryRecallBlock != null) {
|
|
36
|
+
blocks.push(runtime.pendingMemoryRecallBlock);
|
|
37
|
+
}
|
|
38
|
+
if (blocks.length === 0)
|
|
39
|
+
return messages;
|
|
40
|
+
const tailText = blocks.join("\n\n");
|
|
41
|
+
const timestamp = runtime.perfTurnStart ?? // stable within a turn
|
|
42
|
+
Date.now();
|
|
43
|
+
const tailMsg = {
|
|
44
|
+
role: "user",
|
|
45
|
+
content: tailText,
|
|
46
|
+
timestamp,
|
|
47
|
+
};
|
|
48
|
+
runtime.rt.recallInjectedThisTurn = true;
|
|
49
|
+
// Append at the very tail — never splits toolCall/toolResult.
|
|
50
|
+
// PREVENT-PI-001/002: a single message appended after a complete
|
|
51
|
+
// transcript prefix cannot split a toolCall/toolResult pair.
|
|
52
|
+
return [...messages, tailMsg];
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
// Non-fatal: leave blocks staged (flag stays unset) and return the
|
|
56
|
+
// unmodified view. The context event still proceeds normally.
|
|
57
|
+
return messages;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -149,14 +149,21 @@ export function registerSessionHandlers(pi, runtime, config) {
|
|
|
149
149
|
catch {
|
|
150
150
|
/* non-fatal: intent polling never breaks the agent loop */
|
|
151
151
|
}
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
152
|
+
// S53: when recallTailInject is ON, the staged blocks are injected as a
|
|
153
|
+
// user-role tail message by the context handler (recall-tail.ts), NOT
|
|
154
|
+
// here. This prepend path is the legacy behavior (flag OFF = byte-
|
|
155
|
+
// identical pre-sprint). captureModel + rewind-intent consumption above
|
|
156
|
+
// stay unconditional regardless of the flag.
|
|
157
|
+
if (!config.recallTailInject) {
|
|
158
|
+
const cpBlock = runtime.pendingRecallBlock;
|
|
159
|
+
const memBlock = runtime.pendingMemoryRecallBlock;
|
|
160
|
+
if (!cpBlock && !memBlock)
|
|
161
|
+
return;
|
|
162
|
+
runtime.pendingRecallBlock = undefined;
|
|
163
|
+
runtime.pendingMemoryRecallBlock = undefined;
|
|
164
|
+
const composed = [cpBlock, memBlock].filter(Boolean).join("\n\n");
|
|
165
|
+
return { systemPrompt: `${event.systemPrompt}\n\n${composed}` };
|
|
166
|
+
}
|
|
160
167
|
});
|
|
161
168
|
pi.on("session_shutdown", async (_event, ctx) => {
|
|
162
169
|
runtime.setStatus(ctx, undefined);
|
|
@@ -24,6 +24,9 @@ export function resetRuntimeImpl(self, sessionId) {
|
|
|
24
24
|
dedupAttempts: 0,
|
|
25
25
|
tokensSaved: 0,
|
|
26
26
|
lastCompactAt: null,
|
|
27
|
+
lastRecallAt: null,
|
|
28
|
+
lastInjectAt: null,
|
|
29
|
+
_prevCacheHitPct: null,
|
|
27
30
|
lastNativeCompactAt: null,
|
|
28
31
|
compactCount: 0,
|
|
29
32
|
recallInjections: 0,
|
|
@@ -40,7 +43,9 @@ export function resetRuntimeImpl(self, sessionId) {
|
|
|
40
43
|
poisonedAdviseSent: false,
|
|
41
44
|
providerOutageAdvised: false,
|
|
42
45
|
poisonedCompactSignatures: new Set(),
|
|
46
|
+
recallInjectedThisTurn: false,
|
|
43
47
|
poisonedCount: 0,
|
|
48
|
+
extensionInitiatedTurn: false,
|
|
44
49
|
};
|
|
45
50
|
self.trimCache = null; // v0.8.6: never replay a stale trim into a new session
|
|
46
51
|
self.statusKey = undefined;
|
|
@@ -49,6 +49,9 @@ export class MegaRuntime {
|
|
|
49
49
|
dedupAttempts: 0,
|
|
50
50
|
tokensSaved: 0,
|
|
51
51
|
lastCompactAt: null,
|
|
52
|
+
lastRecallAt: null,
|
|
53
|
+
lastInjectAt: null,
|
|
54
|
+
_prevCacheHitPct: null,
|
|
52
55
|
lastNativeCompactAt: null,
|
|
53
56
|
compactCount: 0,
|
|
54
57
|
recallInjections: 0,
|
|
@@ -65,7 +68,10 @@ export class MegaRuntime {
|
|
|
65
68
|
poisonedAdviseSent: false,
|
|
66
69
|
providerOutageAdvised: false,
|
|
67
70
|
poisonedCompactSignatures: new Set(),
|
|
71
|
+
// S53: tracks whether withRecallTail injected this turn (consumed at turn_end).
|
|
72
|
+
recallInjectedThisTurn: false,
|
|
68
73
|
poisonedCount: 0,
|
|
74
|
+
extensionInitiatedTurn: false,
|
|
69
75
|
};
|
|
70
76
|
// v0.8.6 cache-stability: the cached live-trim view for the current
|
|
71
77
|
// compaction epoch. Set after a fresh runCompact + computeLiveTrimCut, and
|
package/dist/src/embedder.js
CHANGED
|
@@ -49,20 +49,60 @@ function fnv1a(str) {
|
|
|
49
49
|
* Default embedder: character 3-gram bag-of-counts, hashed into a fixed-dim
|
|
50
50
|
* vector, L2-normalized. Captures local lexical/structure overlap well enough
|
|
51
51
|
* for checkpoint relevance ranking.
|
|
52
|
+
*
|
|
53
|
+
* S53B: includes a 256-entry (configurable) FIFO cache keyed by FNV-1a(text).
|
|
54
|
+
* Each cache entry holds a DEFENSIVE COPY of the embedding to prevent mutation
|
|
55
|
+
* from corrupting stored vectors. Set MEGACOMPACT_EMBED_CACHE=0 to disable.
|
|
52
56
|
*/
|
|
53
57
|
export class TrigramEmbedder {
|
|
54
58
|
dim;
|
|
55
59
|
seed;
|
|
60
|
+
/** @type {Map<string, Vector>} */
|
|
61
|
+
_cache;
|
|
62
|
+
_cacheSize;
|
|
63
|
+
_hits = 0;
|
|
64
|
+
_misses = 0;
|
|
56
65
|
constructor(dim = 512, seed = 0x9e3779b9) {
|
|
57
66
|
this.dim = dim;
|
|
58
67
|
this.seed = seed >>> 0;
|
|
68
|
+
const cap = Number(process.env.MEGACOMPACT_EMBED_CACHE ?? "256");
|
|
69
|
+
this._cacheSize = cap > 0 ? Math.floor(cap) : 0;
|
|
70
|
+
this._cache = new Map();
|
|
71
|
+
}
|
|
72
|
+
/** Cache statistics — always { hits: 0, misses: 0 } when cache is disabled. */
|
|
73
|
+
getEmbedCacheStats() {
|
|
74
|
+
return { hits: this._hits, misses: this._misses };
|
|
59
75
|
}
|
|
60
76
|
embed(text) {
|
|
77
|
+
if (this._cacheSize === 0) {
|
|
78
|
+
return this._embedRaw(text);
|
|
79
|
+
}
|
|
80
|
+
const key = fnv1a(text).toString(36);
|
|
81
|
+
const cached = this._cache.get(key);
|
|
82
|
+
if (cached !== undefined) {
|
|
83
|
+
this._hits++;
|
|
84
|
+
// Defensive copy: caller mutating the returned vector must not corrupt cache.
|
|
85
|
+
return cached.slice();
|
|
86
|
+
}
|
|
87
|
+
this._misses++;
|
|
88
|
+
const vec = this._embedRaw(text);
|
|
89
|
+
// Store a defensive copy (slice) so caller mutation cannot corrupt stored value.
|
|
90
|
+
this._cache.set(key, vec.slice());
|
|
91
|
+
// FIFO eviction: remove the oldest entry when at capacity.
|
|
92
|
+
if (this._cache.size > this._cacheSize) {
|
|
93
|
+
// Map insertion order is guaranteed — first key is the oldest.
|
|
94
|
+
const firstKey = this._cache.keys().next().value;
|
|
95
|
+
if (firstKey !== undefined)
|
|
96
|
+
this._cache.delete(firstKey);
|
|
97
|
+
}
|
|
98
|
+
return vec;
|
|
99
|
+
}
|
|
100
|
+
/** Raw embed computation (no cache logic). Public so tests can bypass cache. */
|
|
101
|
+
_embedRaw(text) {
|
|
61
102
|
const vec = new Array(this.dim).fill(0);
|
|
62
103
|
const norm = text.toLowerCase().replace(/\s+/g, " ");
|
|
63
104
|
if (norm.length === 0)
|
|
64
105
|
return l2Normalize(vec);
|
|
65
|
-
// Whole-string + word + char-trigram signals.
|
|
66
106
|
vec[fnv1a(norm) % this.dim] += 1;
|
|
67
107
|
for (const word of norm.split(" ")) {
|
|
68
108
|
if (word.length === 0)
|
|
@@ -74,7 +114,6 @@ export class TrigramEmbedder {
|
|
|
74
114
|
vec[idx] += 1;
|
|
75
115
|
}
|
|
76
116
|
}
|
|
77
|
-
// Edge: very short tokens still get a slot.
|
|
78
117
|
if (norm.length < 3)
|
|
79
118
|
vec[fnv1a(norm) % this.dim] += 1;
|
|
80
119
|
return l2Normalize(vec);
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* memoryStats.ts — aggregate memory-store statistics (S53B).
|
|
3
|
+
*
|
|
4
|
+
* Reads from the durable SQLite memories table to produce:
|
|
5
|
+
* - totalMemories: all memories in the store
|
|
6
|
+
* - memoriesInLast30Days: memories created within the last 30 days
|
|
7
|
+
* - topStableMemories: top-N memories by recall count (desc)
|
|
8
|
+
* - avgRecallScore: mean recallCount across all memories
|
|
9
|
+
*
|
|
10
|
+
* recallCount = 1 if last_recalled_at IS NOT NULL, else 0.
|
|
11
|
+
* This is the durable signal from recallMemory() — a memory that was
|
|
12
|
+
* recalled at least once is "stable" (still relevant). The exact recall
|
|
13
|
+
* frequency is tracked via turn_recall rows (source='memory') for
|
|
14
|
+
* cross-session analysis, but the memories table provides a reliable
|
|
15
|
+
* on-store signal that is always present without a schema migration.
|
|
16
|
+
*
|
|
17
|
+
* Real-store only (PREVENT-PI-004). No mocks. No network.
|
|
18
|
+
*/
|
|
19
|
+
import { openStore } from "./store/sqlite/utils.js";
|
|
20
|
+
/**
|
|
21
|
+
* Aggregate memory statistics from the SQLite store.
|
|
22
|
+
* Always returns a valid MemoryStatsResult; never throws.
|
|
23
|
+
*/
|
|
24
|
+
export async function memoryStats(stateDir, opts = {}) {
|
|
25
|
+
const topN = opts.topN ?? 5;
|
|
26
|
+
try {
|
|
27
|
+
const db = openStore(stateDir);
|
|
28
|
+
// ── totalMemories ──────────────────────────────────────────────────────
|
|
29
|
+
const totalRow = db
|
|
30
|
+
.prepare("SELECT COUNT(*) AS n FROM memories")
|
|
31
|
+
.get();
|
|
32
|
+
const totalMemories = totalRow.n;
|
|
33
|
+
// ── memoriesInLast30Days ───────────────────────────────────────────────
|
|
34
|
+
const thirtyDaysAgo = Math.floor(Date.now() / 1000) - 30 * 86_400;
|
|
35
|
+
const recentRow = db
|
|
36
|
+
.prepare("SELECT COUNT(*) AS n FROM memories WHERE created_at >= ?")
|
|
37
|
+
.get(thirtyDaysAgo);
|
|
38
|
+
const memoriesInLast30Days = recentRow.n;
|
|
39
|
+
// ── topStableMemories + avgRecallScore ─────────────────────────────────
|
|
40
|
+
// recallCount: 1 if last_recalled_at IS NOT NULL (recalled at least once),
|
|
41
|
+
// 0 otherwise. Stable memories score high.
|
|
42
|
+
const topRows = db
|
|
43
|
+
.prepare(`SELECT
|
|
44
|
+
m.id,
|
|
45
|
+
m.content AS text,
|
|
46
|
+
m.last_recalled_at AS lastRecalledAt,
|
|
47
|
+
CASE WHEN m.last_recalled_at IS NOT NULL THEN 1 ELSE 0 END AS recallCount
|
|
48
|
+
FROM memories m
|
|
49
|
+
ORDER BY recallCount DESC, m.id ASC
|
|
50
|
+
LIMIT ?`)
|
|
51
|
+
.all(topN);
|
|
52
|
+
// avgRecallScore = (count of recalled memories) / totalMemories.
|
|
53
|
+
// This represents the fraction of memories that are "stable" (recalled at least once).
|
|
54
|
+
const recalledRow = db
|
|
55
|
+
.prepare("SELECT COUNT(*) AS n FROM memories WHERE last_recalled_at IS NOT NULL")
|
|
56
|
+
.get();
|
|
57
|
+
const avgRecallScore = totalMemories > 0 ? recalledRow.n / totalMemories : 0;
|
|
58
|
+
const topStableMemories = topRows.map((r) => ({
|
|
59
|
+
id: r.id,
|
|
60
|
+
text: r.text ?? "",
|
|
61
|
+
recallCount: r.recallCount ?? 0,
|
|
62
|
+
lastRecalledAt: r.lastRecalledAt ?? null,
|
|
63
|
+
}));
|
|
64
|
+
return { totalMemories, memoriesInLast30Days, topStableMemories, avgRecallScore };
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
// Non-fatal: return zeros rather than propagating an error.
|
|
68
|
+
return {
|
|
69
|
+
totalMemories: 0,
|
|
70
|
+
memoriesInLast30Days: 0,
|
|
71
|
+
topStableMemories: [],
|
|
72
|
+
avgRecallScore: 0,
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* prefix-break.ts — S53A prefix-break classification.
|
|
3
|
+
*
|
|
4
|
+
* Classifies WHY the provider cache prefix broke on a given turn by comparing
|
|
5
|
+
* the break timestamp against the three candidate event timestamps with a
|
|
6
|
+
* configurable tolerance window.
|
|
7
|
+
*
|
|
8
|
+
* The classification is best-effort (non-fatal): null timestamps are absent,
|
|
9
|
+
* and a break outside all tolerance windows is classified as 'other'.
|
|
10
|
+
*
|
|
11
|
+
* Pi-agnostic: no pi runtime types, no network.
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* Classify why the provider cache prefix broke at `breakTimestamp`.
|
|
15
|
+
*
|
|
16
|
+
* @param breakTimestamp Wall-clock ms of the cache hit % drop sample.
|
|
17
|
+
* @param events Recent event timestamps from the runtime.
|
|
18
|
+
* @param toleranceMs Max ms gap to consider a match (default 2000).
|
|
19
|
+
* @returns Classification result with cause + confidence.
|
|
20
|
+
*
|
|
21
|
+
* Priority: recall > compaction > inject. Confidence = 1 − (gap / (2·tolerance)),
|
|
22
|
+
* capped at [0.5, 1.0]. Returns 'other' when no event is within tolerance.
|
|
23
|
+
*/
|
|
24
|
+
export function classifyPrefixBreak(breakTimestamp, events, toleranceMs = 2000) {
|
|
25
|
+
// Ordered by priority (recall wins if multiple match).
|
|
26
|
+
const candidates = [
|
|
27
|
+
{ cause: "recall", ts: events.lastRecallAt },
|
|
28
|
+
{ cause: "compaction", ts: events.lastCompactAt },
|
|
29
|
+
{ cause: "inject", ts: events.lastInjectAt },
|
|
30
|
+
];
|
|
31
|
+
for (const { cause, ts } of candidates) {
|
|
32
|
+
if (ts == null)
|
|
33
|
+
continue;
|
|
34
|
+
const gap = Math.abs(breakTimestamp - ts);
|
|
35
|
+
if (gap <= toleranceMs) {
|
|
36
|
+
// confidence = 1 − (gap / (2·tolerance)) ∈ [0.5, 1.0]
|
|
37
|
+
// exact match (gap=0) → 1.0; at boundary (gap=tolerance) → 0.5
|
|
38
|
+
const confidence = Math.max(0.5, 1 - gap / (2 * toleranceMs));
|
|
39
|
+
return { cause, confidence };
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return { cause: "other", confidence: 0 };
|
|
43
|
+
}
|
package/dist/src/pricing.js
CHANGED