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
|
@@ -13,6 +13,11 @@ import { loadMetrics, fpRate, p95, defaultMetricsPath } from "../src/monitoring.
|
|
|
13
13
|
import { C, recentUserQuery } from "./mega-runtime.js";
|
|
14
14
|
import { runCompact, doRecall, doRecallAsync } from "./mega-pipeline.js";
|
|
15
15
|
import { vectorStats, vectorRepoStats, vectorDataInvariant } from "../src/vectorStore.js";
|
|
16
|
+
import { spawnSync } from "node:child_process"; // guardrails-allow PREVENT-PI-004: local subprocess detection only (no network)
|
|
17
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
18
|
+
import path from "node:path";
|
|
19
|
+
import os from "node:os";
|
|
20
|
+
import { createRequire } from "node:module";
|
|
16
21
|
/** Resolve a checkpoint by id (or "recent"/"last") from this session's store. */
|
|
17
22
|
export function findCheckpoint(runtime, sid, ref) {
|
|
18
23
|
const all = listCheckpoints(sid, runtime.currentStateDir);
|
|
@@ -73,7 +78,7 @@ export function registerCommands(pi, runtime, config) {
|
|
|
73
78
|
runtime.logger.info("recall", { query, crossRepo, injected: r.toInject.map((h) => h.checkpoint.checkpointId) });
|
|
74
79
|
runtime.setStatus(ctx, `mega-compact: recalled ${r.toInject.length} chkpt${crossRepo ? " (cross-repo)" : ""}`);
|
|
75
80
|
ctx.ui.notify(`[mega-compact] recall staged ${r.toInject.length} checkpoint(s) for "${query}"${crossRepo ? " (cross-repo)" : ""}:\n${list}\n` +
|
|
76
|
-
`(injected at the next turn
|
|
81
|
+
`(injected at the tail of the next turn's context)`);
|
|
77
82
|
}
|
|
78
83
|
catch (e) {
|
|
79
84
|
ctx.ui.notify(`[mega-compact] /mega-recall failed: ${String(e)}`);
|
|
@@ -255,6 +260,189 @@ export function registerCommands(pi, runtime, config) {
|
|
|
255
260
|
`• data safety — every compressed region is kept verbatim; nothing is permanently deleted. /mega-restore brings any of it back.`);
|
|
256
261
|
},
|
|
257
262
|
});
|
|
263
|
+
pi.registerCommand("mega-setup", {
|
|
264
|
+
description: "Local embedding setup wizard — detect available embedders and configure mega-compact.",
|
|
265
|
+
handler: async (_args, ctx) => {
|
|
266
|
+
try {
|
|
267
|
+
const log = (msg) => ctx.ui.notify(msg);
|
|
268
|
+
// --- 1. Current config ---
|
|
269
|
+
const embeddingUrl = process.env["MEGACOMPACT_EMBEDDING_URL"];
|
|
270
|
+
const minilm = process.env["MEGACOMPACT_MINILM"];
|
|
271
|
+
let currentEmbedder = "TrigramEmbedder (heuristic, default)";
|
|
272
|
+
if (embeddingUrl)
|
|
273
|
+
currentEmbedder = `httpEmbedder → ${embeddingUrl}`;
|
|
274
|
+
else if (minilm)
|
|
275
|
+
currentEmbedder = "MiniLM (experimental)";
|
|
276
|
+
// --- 2. Detection ---
|
|
277
|
+
let ollamaDetected = false;
|
|
278
|
+
let ollamaModels = [];
|
|
279
|
+
let ollamaRunning = false;
|
|
280
|
+
let llamaDetected = false;
|
|
281
|
+
let onnxDetected = false;
|
|
282
|
+
try {
|
|
283
|
+
const ollamaVer = spawnSync("ollama", ["--version"], {
|
|
284
|
+
timeout: 5000,
|
|
285
|
+
encoding: "utf-8",
|
|
286
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
287
|
+
}); // guardrails-allow PREVENT-PI-004: local subprocess detection only
|
|
288
|
+
if (ollamaVer.status === 0) {
|
|
289
|
+
ollamaDetected = true;
|
|
290
|
+
try {
|
|
291
|
+
const listResult = spawnSync("ollama", ["list"], {
|
|
292
|
+
timeout: 5000,
|
|
293
|
+
encoding: "utf-8",
|
|
294
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
295
|
+
}); // guardrails-allow PREVENT-PI-004: local subprocess detection only
|
|
296
|
+
if (listResult.status === 0) {
|
|
297
|
+
ollamaRunning = true;
|
|
298
|
+
const lines = listResult.stdout?.split("\n") ?? [];
|
|
299
|
+
for (const line of lines) {
|
|
300
|
+
const name = line.split(/\s+/)[0];
|
|
301
|
+
if (name && name !== "NAME")
|
|
302
|
+
ollamaModels.push(name);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
catch {
|
|
307
|
+
// ollama list fails if server not running — that's fine
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
catch {
|
|
312
|
+
// ollama not found
|
|
313
|
+
}
|
|
314
|
+
try {
|
|
315
|
+
const whichLlama = spawnSync("which", ["llama-server"], {
|
|
316
|
+
timeout: 3000,
|
|
317
|
+
encoding: "utf-8",
|
|
318
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
319
|
+
}); // guardrails-allow PREVENT-PI-004: local subprocess detection only
|
|
320
|
+
llamaDetected = whichLlama.status === 0;
|
|
321
|
+
}
|
|
322
|
+
catch {
|
|
323
|
+
// not found
|
|
324
|
+
}
|
|
325
|
+
try {
|
|
326
|
+
const req = createRequire(import.meta.url);
|
|
327
|
+
try {
|
|
328
|
+
req.resolve("onnxruntime-node");
|
|
329
|
+
onnxDetected = true;
|
|
330
|
+
}
|
|
331
|
+
catch {
|
|
332
|
+
// not in node_modules
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
catch {
|
|
336
|
+
// require error
|
|
337
|
+
}
|
|
338
|
+
const choices = [];
|
|
339
|
+
if (ollamaDetected && ollamaRunning) {
|
|
340
|
+
const model = ollamaModels.find((m) => m.includes("nomic-embed") ||
|
|
341
|
+
m.includes("embed") ||
|
|
342
|
+
m.includes("mxbai"));
|
|
343
|
+
const suggestedModel = model ?? "nomic-embed-text";
|
|
344
|
+
choices.push({
|
|
345
|
+
label: `Use Ollama (${suggestedModel}) at localhost:11434`,
|
|
346
|
+
value: `ollama:${suggestedModel}`,
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
else if (ollamaDetected && !ollamaRunning) {
|
|
350
|
+
choices.push({
|
|
351
|
+
label: "Ollama detected but server is not running — start it first",
|
|
352
|
+
value: "ollama:offline",
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
if (llamaDetected) {
|
|
356
|
+
choices.push({
|
|
357
|
+
label: "Use llama.cpp server at localhost:8080",
|
|
358
|
+
value: "llama:default",
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
if (onnxDetected) {
|
|
362
|
+
choices.push({
|
|
363
|
+
label: "Use ONNX Runtime (experimental, requires config)",
|
|
364
|
+
value: "onnx:default",
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
choices.push({
|
|
368
|
+
label: "Keep TrigramEmbedder (default, no setup)",
|
|
369
|
+
value: "trigram",
|
|
370
|
+
});
|
|
371
|
+
// --- 4. Prompt user ---
|
|
372
|
+
log(`Current embedder: ${currentEmbedder}`);
|
|
373
|
+
let selected = "trigram";
|
|
374
|
+
if (choices.length > 1) {
|
|
375
|
+
try {
|
|
376
|
+
const labels = choices.map((c) => c.label);
|
|
377
|
+
const picked = await ctx.ui.select("Select an embedder to configure:", labels);
|
|
378
|
+
if (picked === undefined) {
|
|
379
|
+
log("Setup cancelled by user.");
|
|
380
|
+
return;
|
|
381
|
+
}
|
|
382
|
+
const match = choices.find((c) => c.label === picked);
|
|
383
|
+
selected = match?.value ?? "trigram";
|
|
384
|
+
}
|
|
385
|
+
catch {
|
|
386
|
+
log("Setup cancelled by user.");
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
else {
|
|
391
|
+
log("No local embedders detected. Keeping TrigramEmbedder default.");
|
|
392
|
+
}
|
|
393
|
+
// --- 5. Apply selection ---
|
|
394
|
+
if (selected.startsWith("ollama:")) {
|
|
395
|
+
const model = selected.split(":")[1];
|
|
396
|
+
const url = `http://localhost:11434/api/embeddings`; // guardrails-allow PREVENT-PI-004: localhost-only config string, not a runtime fetch
|
|
397
|
+
const lines = [
|
|
398
|
+
`# Mega-Compact Embedder Configuration — Ollama`,
|
|
399
|
+
`# Generated by /megasetup at ${new Date().toISOString()}`,
|
|
400
|
+
`export MEGACOMPACT_EMBEDDING_URL="${url}"`,
|
|
401
|
+
`# Optional: uncomment to set cache size (default 1000)`,
|
|
402
|
+
`# export MEGACOMPACT_EMBED_CACHE=1000`,
|
|
403
|
+
];
|
|
404
|
+
const envContent = lines.join("\n") + "\n";
|
|
405
|
+
// Write .mega-compact.env to state dir
|
|
406
|
+
const stateDir = process.env["MEGACOMPACT_STATE_DIR"] ?? path.join(os.homedir(), ".pi", "mega-compact");
|
|
407
|
+
try {
|
|
408
|
+
mkdirSync(stateDir, { recursive: true });
|
|
409
|
+
writeFileSync(path.join(stateDir, ".mega-compact.env"), envContent, "utf-8");
|
|
410
|
+
}
|
|
411
|
+
catch {
|
|
412
|
+
// non-fatal
|
|
413
|
+
}
|
|
414
|
+
log(`Configured for Ollama (${model}).\n\nAdd to your shell profile (~/.bashrc, ~/.zshrc, or ~/.config/fish/config.fish):\n\n source "${path.join(stateDir, ".mega-compact.env")}"\n\nOr export manually:\n\n export MEGACOMPACT_EMBEDDING_URL="${url}"\n\nThen restart pi to activate the http embedder.`);
|
|
415
|
+
}
|
|
416
|
+
else if (selected.startsWith("llama:")) {
|
|
417
|
+
const url = "http://localhost:8080/v1/embeddings"; // guardrails-allow PREVENT-PI-004: localhost-only config string, not a runtime fetch
|
|
418
|
+
const lines = [
|
|
419
|
+
`# Mega-Compact Embedder Configuration — llama.cpp`,
|
|
420
|
+
`# Generated by /megasetup at ${new Date().toISOString()}`,
|
|
421
|
+
`export MEGACOMPACT_EMBEDDING_URL="${url}"`,
|
|
422
|
+
];
|
|
423
|
+
const envContent = lines.join("\n") + "\n";
|
|
424
|
+
const stateDir = process.env["MEGACOMPACT_STATE_DIR"] ?? path.join(os.homedir(), ".pi", "mega-compact");
|
|
425
|
+
try {
|
|
426
|
+
mkdirSync(stateDir, { recursive: true });
|
|
427
|
+
writeFileSync(path.join(stateDir, ".mega-compact.env"), envContent, "utf-8");
|
|
428
|
+
}
|
|
429
|
+
catch {
|
|
430
|
+
// non-fatal
|
|
431
|
+
}
|
|
432
|
+
log(`Configured for llama.cpp server.\n\nAdd to your shell profile:\n\n source "${path.join(stateDir, ".mega-compact.env")}"\n\nOr export manually:\n\n export MEGACOMPACT_EMBEDDING_URL="${url}"\n\nThen restart pi to activate the http embedder.`);
|
|
433
|
+
}
|
|
434
|
+
else if (selected.startsWith("onnx:")) {
|
|
435
|
+
log("ONNX Runtime configuration is experimental.\n\nSet MEGACOMPACT_EMBEDDING_URL to your local ONNX server URL, or see docs for manual setup.\nKeeping TrigramEmbedder for now.");
|
|
436
|
+
}
|
|
437
|
+
else {
|
|
438
|
+
log("Keeping TrigramEmbedder (default). No configuration needed.");
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
catch (e) {
|
|
442
|
+
ctx.ui.notify(`[mega-compact] /mega-setup failed: ${String(e)}`);
|
|
443
|
+
}
|
|
444
|
+
},
|
|
445
|
+
});
|
|
258
446
|
// NOTE: /mega-tier was removed in S24. The tier the user sees is now the LIVE
|
|
259
447
|
// pressure band (low/medium/high/ultra/mega), which climbs automatically as
|
|
260
448
|
// context fills — there is no manual tier to set. See docs/specs/s24-unified-pressure.md.
|
|
@@ -149,6 +149,7 @@ export function loadConfig() {
|
|
|
149
149
|
errorRetrySessionMax: envFlag("MEGACOMPACT_ERROR_RETRY_SESSION_MAX", 3),
|
|
150
150
|
poisonedContextRepeatThreshold: envFlag("MEGACOMPACT_POISONED_REPEAT_THRESHOLD", 3),
|
|
151
151
|
providerOutageAdviseThreshold: envFlag("MEGACOMPACT_PROVIDER_OUTAGE_THRESHOLD", 3),
|
|
152
|
+
advisoryChannel: envBool("MEGACOMPACT_ADVISORY_CHANNEL", true),
|
|
152
153
|
autoPctTrigger,
|
|
153
154
|
autoInlineK: envFlag("MEGACOMPACT_AUTO_INLINE_K", 3),
|
|
154
155
|
dedupSim: Number(process.env.MEGACOMPACT_DEDUP_SIM ?? "0.9"),
|
|
@@ -165,6 +166,7 @@ export function loadConfig() {
|
|
|
165
166
|
memoryReviewInterval: envFlag("MEGACOMPACT_MEMORY_REVIEW_INTERVAL", 10),
|
|
166
167
|
recallMaxTokens: envFlag("MEGACOMPACT_RECALL_MAX_TOKENS", 1500),
|
|
167
168
|
windowDedupe: envBool("MEGACOMPACT_WINDOW_DEDUPE", true),
|
|
169
|
+
recallTailInject: envBool("MEGACOMPACT_RECALL_TAIL_INJECT", true),
|
|
168
170
|
tuiWidget: envBool("MEGACOMPACT_TUI_WIDGET", true),
|
|
169
171
|
// D.1: env-overridable recompact delta (minimum context growth % before
|
|
170
172
|
// re-compacting instead of replaying the cached live trim). Default 50.
|
|
@@ -154,7 +154,10 @@ export function registerAgentHandlers(pi, runtime, config) {
|
|
|
154
154
|
try {
|
|
155
155
|
if (runtime.rt.sessionId !== liveSid)
|
|
156
156
|
return; // session reset
|
|
157
|
-
|
|
157
|
+
// IMPORTANT: recompute Date.now() inside the timeout.
|
|
158
|
+
// `now` above is the durable-trim handler's timestamp and can be
|
|
159
|
+
// ~500ms stale by the time this callback runs.
|
|
160
|
+
const since2 = Date.now() - (runtime.rt.lastNativeCompactAt ?? 0);
|
|
158
161
|
if (runtime.rt.lastNativeCompactAt !== stamp &&
|
|
159
162
|
since2 < cooldownMs)
|
|
160
163
|
return;
|
|
@@ -227,6 +230,15 @@ export function registerAgentHandlers(pi, runtime, config) {
|
|
|
227
230
|
pi.on("turn_end", async (event, ctx) => {
|
|
228
231
|
runtime.dashboard.event("turn_end", { turnIndex: event.turnIndex });
|
|
229
232
|
runtime.snapshot(ctx);
|
|
233
|
+
// S53: consume staged recall blocks ONLY if they were actually injected
|
|
234
|
+
// into a view this turn. If no context event fired (edge: turn ended
|
|
235
|
+
// before any LLM call), recallInjectedThisTurn stays false and the blocks
|
|
236
|
+
// remain staged for the next turn's first context event.
|
|
237
|
+
if (config.recallTailInject && runtime.rt.recallInjectedThisTurn) {
|
|
238
|
+
runtime.pendingRecallBlock = undefined;
|
|
239
|
+
runtime.pendingMemoryRecallBlock = undefined;
|
|
240
|
+
runtime.rt.recallInjectedThisTurn = false;
|
|
241
|
+
}
|
|
230
242
|
// S43 (per-turn tracking): record one turn row with the cached metrics so
|
|
231
243
|
// the turn layer is queryable + forkable. Best-effort + non-fatal: a write
|
|
232
244
|
// failure never breaks the agent loop.
|
|
@@ -518,9 +530,12 @@ export function registerAgentHandlers(pi, runtime, config) {
|
|
|
518
530
|
rawText: (errSig || '').slice(0, 500),
|
|
519
531
|
...(detail.httpStatus !== undefined ? { httpStatus: detail.httpStatus } : {}),
|
|
520
532
|
});
|
|
521
|
-
// (b)
|
|
522
|
-
|
|
523
|
-
|
|
533
|
+
// (b) throttle flag: set unconditionally so the advise fires at
|
|
534
|
+
// most once per session regardless of channel.
|
|
535
|
+
runtime.rt.poisonedAdviseSent = true;
|
|
536
|
+
// Legacy flag-OFF path: user-role advise message.
|
|
537
|
+
// Default ON (advisoryChannel=true): dashboard-only, no user message.
|
|
538
|
+
if (!config.advisoryChannel) {
|
|
524
539
|
// PREVENT-PI-003: user-role sendUserMessage only.
|
|
525
540
|
await safeSendUserMessage(pi, "[mega-compact] this session's context may be poisoned (the provider is rejecting every request). Run /clear or /new to start a fresh context.");
|
|
526
541
|
}
|
|
@@ -46,6 +46,7 @@ async function nudgeResume(pi, runtime) {
|
|
|
46
46
|
const now = Date.now();
|
|
47
47
|
if (now >= runtime.resumeNudgeUntil) {
|
|
48
48
|
runtime.resumeNudgeUntil = now + 30_000;
|
|
49
|
+
runtime.rt.extensionInitiatedTurn = true; // R13: suppress self-classification
|
|
49
50
|
await safeSendUserMessage(pi, "[mega-compact] continue from the compacted context above.");
|
|
50
51
|
}
|
|
51
52
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { openStore,
|
|
1
|
+
import { openStore, writeCheckpointEpoch, } from "../../src/store/sqlite.js";
|
|
2
2
|
import { epochIdFor } from "../../src/mirror/epoch.js";
|
|
3
3
|
import { autoCompactCheck } from "../../src/compact.js";
|
|
4
4
|
import { estimateSessionTokens } from "../../src/tokens.js";
|
|
@@ -9,75 +9,8 @@ import { openTurnStore } from "../../src/store/turns/connection.js";
|
|
|
9
9
|
import { buildTopicModel, createTopicStore, bumpWikiCompactCounter, } from "../../src/topics/index.js";
|
|
10
10
|
import { computeLiveTrimCut, liveTrimSummaryMessage } from "../mega-trim.js";
|
|
11
11
|
import { pressureFromPct, pressureRatio, } from "../mega-config.js";
|
|
12
|
-
import {
|
|
13
|
-
|
|
14
|
-
* Recursively canonicalize a value for deterministic JSON serialization:
|
|
15
|
-
* - Objects: keys sorted alphabetically, values recursively canonicalized
|
|
16
|
-
* - Arrays: elements recursively canonicalized (array ORDER is preserved)
|
|
17
|
-
* - Primitives: returned as-is
|
|
18
|
-
*
|
|
19
|
-
* F5 fix: shallow-sorted JSON.stringify(content, Object.keys(content).sort())
|
|
20
|
-
* omitted nested keys not in the top-level keys array and only sorted one level.
|
|
21
|
-
* This recursively sorts every object at every depth so semantically-equal
|
|
22
|
-
* differently-ordered content hashes identically.
|
|
23
|
-
*/
|
|
24
|
-
function canonicalize(value) {
|
|
25
|
-
if (value === null || value === undefined)
|
|
26
|
-
return value;
|
|
27
|
-
if (typeof value !== "object")
|
|
28
|
-
return value;
|
|
29
|
-
if (Array.isArray(value))
|
|
30
|
-
return value.map(canonicalize);
|
|
31
|
-
// Plain object: sort keys, recursively canonicalize values.
|
|
32
|
-
const sorted = Object.keys(value).sort();
|
|
33
|
-
const out = {};
|
|
34
|
-
for (const k of sorted) {
|
|
35
|
-
out[k] = canonicalize(value[k]);
|
|
36
|
-
}
|
|
37
|
-
return out;
|
|
38
|
-
}
|
|
39
|
-
/**
|
|
40
|
-
* Convert a pi AgentMessage to a RawTranscriptRow for the DB mirror.
|
|
41
|
-
* content_bytes is canonical JSON (sorted keys, recursive) for deterministic
|
|
42
|
-
* storage; contentHash is the canonical digest (normalize + hash) that matches
|
|
43
|
-
* what dedupTranscript computes so the two pipelines use the same linkage key.
|
|
44
|
-
*
|
|
45
|
-
* F4 fix: the hash key MUST match on both sides of the append/dedup split.
|
|
46
|
-
* Using computeContentDigest here (normalize → hash) ensures content_ref set
|
|
47
|
-
* by dedupTranscript always resolves to an existing dedup_mirror row even for
|
|
48
|
-
* whitespace/case-variant content. F5 fix: recursive canonicalize replaces the
|
|
49
|
-
* broken shallow-sorted JSON.stringify replacer.
|
|
50
|
-
*/
|
|
51
|
-
function toRawTranscriptRow(msg, sessionId, epochId, currentTurn) {
|
|
52
|
-
// Narrow to Message union (has content + timestamp).
|
|
53
|
-
const m = msg;
|
|
54
|
-
const content = m.content;
|
|
55
|
-
if (content == null || content === "")
|
|
56
|
-
return null;
|
|
57
|
-
// Canonical bytes: string content → normalize for consistent byte content;
|
|
58
|
-
// object content → recursive canonicalize then JSON (no replacer).
|
|
59
|
-
const contentBytes = typeof content === "string"
|
|
60
|
-
? content // F5: strings are primitives; their byte content is fixed
|
|
61
|
-
: JSON.stringify(canonicalize(content));
|
|
62
|
-
// F4 fix: use the same digest as dedupTranscript so contentHash is consistent
|
|
63
|
-
// on both sides of the append/dedup split. computeContentDigest normalizes
|
|
64
|
-
// (strip ANSI, NFC, case-fold, collapse whitespace) then hashes → the same
|
|
65
|
-
// key is stored in raw_transcript.content_hash AND used as the dedup link.
|
|
66
|
-
const { contentHash } = computeContentDigest(contentBytes);
|
|
67
|
-
return {
|
|
68
|
-
contentHash,
|
|
69
|
-
sessionId,
|
|
70
|
-
seq: 0, // assigned by appendRawTranscript (COALESCE(MAX(seq),0)+1)
|
|
71
|
-
role: m.role ?? "unknown",
|
|
72
|
-
contentBytes,
|
|
73
|
-
toolName: m.toolName ?? null,
|
|
74
|
-
messageTimestamp: m.timestamp ?? null,
|
|
75
|
-
checkpointEpoch: epochId,
|
|
76
|
-
// S50: label the row with the turn that produced it (per-turn dedup /
|
|
77
|
-
// compression-by-turn metrics). Null when the writer omits it (back-compat).
|
|
78
|
-
turnIndex: currentTurn ?? null,
|
|
79
|
-
};
|
|
80
|
-
}
|
|
12
|
+
import { appendMirrorMessages } from "./mirror-append.js";
|
|
13
|
+
import { stagedForTail, withRecallTail } from "./recall-tail.js";
|
|
81
14
|
/** Register the context event handler (live-trim auto-trigger). */
|
|
82
15
|
export function registerContextHandler(pi, runtime, config) {
|
|
83
16
|
// ---- Auto-trigger: live trim (compact and continue) + native durable ----
|
|
@@ -98,6 +31,17 @@ export function registerContextHandler(pi, runtime, config) {
|
|
|
98
31
|
const usage = ctx.getContextUsage();
|
|
99
32
|
const pct = usage?.percent;
|
|
100
33
|
const messages = event.messages;
|
|
34
|
+
// S53: helper to inject the staged recall/memory block as a user-role
|
|
35
|
+
// tail message at any view-return point. Returns undefined when nothing
|
|
36
|
+
// is staged (or the flag is OFF) so the caller falls through to its
|
|
37
|
+
// normal return. The F3 mirror append (above the gates) runs on the
|
|
38
|
+
// REAL transcript before any view is built, so the injected tail never
|
|
39
|
+
// reaches raw_transcript (PREVENT-PI: append-only, view-only).
|
|
40
|
+
const tailResult = (msgs) => {
|
|
41
|
+
if (!stagedForTail(runtime, config))
|
|
42
|
+
return undefined;
|
|
43
|
+
return { messages: withRecallTail(msgs ?? messages, runtime, config) };
|
|
44
|
+
};
|
|
101
45
|
// Always track context for the dashboard/widget, even when auto is off.
|
|
102
46
|
// (v0.8 regression: !config.auto gate sat above this, leaving ctx stats
|
|
103
47
|
// null -> widget '?% / ?/?' when auto disabled. Track first, THEN gate.)
|
|
@@ -118,21 +62,24 @@ export function registerContextHandler(pi, runtime, config) {
|
|
|
118
62
|
runtime.lastCtxPercent = pct ?? null;
|
|
119
63
|
runtime.lastCtxWindow = usage?.contextWindow ?? 0;
|
|
120
64
|
runtime.snapshot(ctx);
|
|
121
|
-
if (!config.auto)
|
|
65
|
+
if (!config.auto) {
|
|
66
|
+
const tailed = tailResult();
|
|
67
|
+
if (tailed)
|
|
68
|
+
return tailed;
|
|
122
69
|
return;
|
|
70
|
+
}
|
|
123
71
|
const view = viewForFallback ?? runtime.engineView(messages);
|
|
124
|
-
// S27 DB-mirror: append
|
|
72
|
+
// S27 DB-mirror: append incoming messages to raw_transcript.
|
|
125
73
|
// Runs BEFORE fast-gate so every message is captured, even if we
|
|
126
74
|
// don't compact this turn. Append is idempotent (content_hash PK).
|
|
75
|
+
// F3: high-water mark (mirror-append.ts) skips already-processed
|
|
76
|
+
// messages on subsequent events. On fork/rewind (shorter list or
|
|
77
|
+
// boundary hash mismatch) the mark is dropped, falling back to a
|
|
78
|
+
// full reprocess.
|
|
127
79
|
if (config.dbMirror) {
|
|
128
80
|
try {
|
|
129
81
|
const db = openStore(runtime.currentStateDir);
|
|
130
|
-
|
|
131
|
-
for (const msg of messages) {
|
|
132
|
-
const raw = toRawTranscriptRow(msg, runtime.rt.sessionId, epochId, runtime.currentTurn);
|
|
133
|
-
if (raw)
|
|
134
|
-
appendRawTranscript(db, raw);
|
|
135
|
-
}
|
|
82
|
+
appendMirrorMessages(db, messages, runtime.rt.sessionId, epochIdFor(runtime.rt.sessionId), runtime.currentTurn);
|
|
136
83
|
}
|
|
137
84
|
catch (e) {
|
|
138
85
|
runtime.logger.warn("db-mirror-append-fail", { error: String(e) });
|
|
@@ -157,18 +104,18 @@ export function registerContextHandler(pi, runtime, config) {
|
|
|
157
104
|
// custom tier OR tiered-but-pct-unavailable → token gate (S27 fallback).
|
|
158
105
|
if (currentTokens < runtime.effectiveThreshold) {
|
|
159
106
|
runtime.diagCtxFastGate++;
|
|
160
|
-
return;
|
|
107
|
+
return tailResult() ?? undefined;
|
|
161
108
|
}
|
|
162
109
|
const check = autoCompactCheck(currentTokens, runtime.effectiveThreshold); // SERVER-STYLE CONFIRM (local)
|
|
163
110
|
if (!check.shouldCompact) {
|
|
164
111
|
runtime.diagCtxNoCompact++;
|
|
165
|
-
return;
|
|
112
|
+
return tailResult() ?? undefined;
|
|
166
113
|
}
|
|
167
114
|
gatePassed = true;
|
|
168
115
|
}
|
|
169
116
|
if (!gatePassed) {
|
|
170
117
|
runtime.diagCtxFastGate++;
|
|
171
|
-
return;
|
|
118
|
+
return tailResult() ?? undefined;
|
|
172
119
|
}
|
|
173
120
|
// D.2: Replay MUST be exempt from debounce — replay is free (no compute,
|
|
174
121
|
// no re-write) and prevents unnecessary KV-cache invalidation. Check
|
|
@@ -197,9 +144,8 @@ export function registerContextHandler(pi, runtime, config) {
|
|
|
197
144
|
runtime.snapshot(ctx);
|
|
198
145
|
// v0.8.7: shallow-copy the cached summary so pi's transformContext can't
|
|
199
146
|
// mutate the shared reference across replays (audit P3).
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
};
|
|
147
|
+
const replayView = [{ ...runtime.trimCache.summaryAgentMsg }, ...recent];
|
|
148
|
+
return tailResult(replayView) ?? { messages: replayView };
|
|
203
149
|
}
|
|
204
150
|
// else: context grew enough → fall through to re-compact (cache is stale)
|
|
205
151
|
}
|
|
@@ -208,7 +154,7 @@ export function registerContextHandler(pi, runtime, config) {
|
|
|
208
154
|
const now = Date.now();
|
|
209
155
|
if (now < runtime.debounceUntil) {
|
|
210
156
|
runtime.diagCtxDebounce++;
|
|
211
|
-
return;
|
|
157
|
+
return tailResult() ?? undefined;
|
|
212
158
|
}
|
|
213
159
|
runtime.debounceUntil = now + 2000;
|
|
214
160
|
// Adaptive compression (Fix E): scale compression strength + keepFrom depth
|
|
@@ -233,11 +179,10 @@ export function registerContextHandler(pi, runtime, config) {
|
|
|
233
179
|
runtime.diagLiveTrimFires++;
|
|
234
180
|
runtime.diagLiveTrimReplays++;
|
|
235
181
|
runtime.snapshot(ctx);
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
};
|
|
182
|
+
const skipView = [{ ...runtime.trimCache.summaryAgentMsg }, ...recent];
|
|
183
|
+
return tailResult(skipView) ?? { messages: skipView };
|
|
239
184
|
}
|
|
240
|
-
return;
|
|
185
|
+
return tailResult() ?? undefined;
|
|
241
186
|
}
|
|
242
187
|
// S27 DB-mirror: write checkpoint_epoch with deterministic nonce.
|
|
243
188
|
// This makes the cache key stable across identical compactions.
|
|
@@ -392,7 +337,7 @@ export function registerContextHandler(pi, runtime, config) {
|
|
|
392
337
|
viewLen: view.length,
|
|
393
338
|
anchorUserMessages,
|
|
394
339
|
});
|
|
395
|
-
return; // unsafe / below anchor floor — no trim this call
|
|
340
|
+
return tailResult() ?? undefined; // unsafe / below anchor floor — no trim this call
|
|
396
341
|
}
|
|
397
342
|
const summaryMsg = liveTrimSummaryMessage({
|
|
398
343
|
compactedFrom: ran.result.compactedFrom,
|
|
@@ -446,11 +391,11 @@ export function registerContextHandler(pi, runtime, config) {
|
|
|
446
391
|
ctxPct: pct,
|
|
447
392
|
ctxTokens: usage?.tokens ?? null,
|
|
448
393
|
});
|
|
449
|
-
return { messages: [summaryAgentMsg, ...recent] };
|
|
394
|
+
return tailResult([summaryAgentMsg, ...recent]) ?? { messages: [summaryAgentMsg, ...recent] };
|
|
450
395
|
}
|
|
451
396
|
catch {
|
|
452
397
|
runtime.diagCtxThrown++;
|
|
453
|
-
return; // non-fatal: no trim this call; the next context event retries
|
|
398
|
+
return tailResult() ?? undefined; // non-fatal: no trim this call; the next context event retries
|
|
454
399
|
}
|
|
455
400
|
});
|
|
456
401
|
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
const TABLE_DDL = `CREATE TABLE IF NOT EXISTS context_hwm (
|
|
2
|
+
session_id TEXT PRIMARY KEY,
|
|
3
|
+
last_seq INTEGER NOT NULL,
|
|
4
|
+
last_content_hash TEXT NOT NULL
|
|
5
|
+
)`;
|
|
6
|
+
/** Ensure the context_hwm table exists. Idempotent. */
|
|
7
|
+
export function ensureHwmTable(db) {
|
|
8
|
+
try {
|
|
9
|
+
db.exec(TABLE_DDL);
|
|
10
|
+
}
|
|
11
|
+
catch {
|
|
12
|
+
// non-fatal
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
/** Read the high-water mark for a session. Returns undefined if none. */
|
|
16
|
+
export function readHwm(db, sessionId) {
|
|
17
|
+
try {
|
|
18
|
+
const row = db
|
|
19
|
+
.prepare("SELECT session_id, last_seq, last_content_hash FROM context_hwm WHERE session_id = ?")
|
|
20
|
+
.get(sessionId);
|
|
21
|
+
if (!row)
|
|
22
|
+
return undefined;
|
|
23
|
+
return {
|
|
24
|
+
sessionId: row.session_id,
|
|
25
|
+
lastSeq: Number(row.last_seq),
|
|
26
|
+
lastContentHash: row.last_content_hash,
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return undefined;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/** Write (INSERT OR REPLACE) the high-water mark for a session. */
|
|
34
|
+
export function writeHwm(db, hwm) {
|
|
35
|
+
try {
|
|
36
|
+
db.prepare("INSERT OR REPLACE INTO context_hwm (session_id, last_seq, last_content_hash) VALUES (?, ?, ?)").run(hwm.sessionId, hwm.lastSeq, hwm.lastContentHash);
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
// non-fatal
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/** Drop the high-water mark for a session (invalidation). */
|
|
43
|
+
export function dropHwm(db, sessionId) {
|
|
44
|
+
try {
|
|
45
|
+
db.prepare("DELETE FROM context_hwm WHERE session_id = ?").run(sessionId);
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
// non-fatal
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
export const TEST_ONLY = { TABLE_DDL };
|
|
@@ -63,7 +63,7 @@ export function classifyErrorDetailed(message) {
|
|
|
63
63
|
return { category: null, signal: 'length-guard' };
|
|
64
64
|
if (sr === 'aborted')
|
|
65
65
|
return { category: 'cancelled', signal: 'cancelled' };
|
|
66
|
-
if (
|
|
66
|
+
if (/^(stop|tool_?use|end_?turn|max_?tokens|complete|finished|done)$/i.test(sr))
|
|
67
67
|
return { category: null, signal: 'success' };
|
|
68
68
|
const usage = m.usage;
|
|
69
69
|
usagePresent = usage != null && typeof usage === 'object';
|
|
@@ -100,10 +100,21 @@ export function classifyErrorDetailed(message) {
|
|
|
100
100
|
}
|
|
101
101
|
}
|
|
102
102
|
if (!sr) {
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
103
|
+
// A missing stopReason alone is not sufficient evidence of stream death.
|
|
104
|
+
// Require at least one corroborating signal: an error field, or 0 total tokens
|
|
105
|
+
// (indicating the stream died before producing anything). A normal completion
|
|
106
|
+
// from a runtime that omits stopReason has content and tokens — not an error.
|
|
107
|
+
const hasError = (m.error != null && m.error !== undefined && m.error !== '') ||
|
|
108
|
+
(typeof m.errorMessage === 'string' && m.errorMessage !== '');
|
|
109
|
+
if (hasError || (usagePresent && totalTokens === 0)) {
|
|
110
|
+
const r = { category: 'transient', signal: 'stream-death-no-stopreason' };
|
|
111
|
+
if (httpStatus !== undefined)
|
|
112
|
+
r.httpStatus = httpStatus;
|
|
113
|
+
return r;
|
|
114
|
+
}
|
|
115
|
+
// No stopReason, no error field, tokens present — likely a normal completion
|
|
116
|
+
// from a runtime that omits stopReason (pi-crew, etc.). Not an error.
|
|
117
|
+
return { category: null, signal: 'success' };
|
|
107
118
|
}
|
|
108
119
|
text = parts.join(' ');
|
|
109
120
|
}
|