pi-mega-compact 0.7.8 → 0.7.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/README.md +11 -12
  2. package/dist/extensions/dashboard-server/helpers.js +37 -0
  3. package/dist/extensions/dashboard-server/html/all-repos-tab.js +26 -0
  4. package/dist/extensions/dashboard-server/html/body-open.js +23 -0
  5. package/dist/extensions/dashboard-server/html/current-repo-tab.js +130 -0
  6. package/dist/extensions/dashboard-server/html/head-open.js +16 -0
  7. package/dist/extensions/dashboard-server/html/high-score-tab.js +25 -0
  8. package/dist/extensions/dashboard-server/html/repo-detail-modal.js +26 -0
  9. package/dist/extensions/dashboard-server/html/script.js +259 -0
  10. package/dist/extensions/dashboard-server/html/styles.js +103 -0
  11. package/dist/extensions/dashboard-server/html/summary-tab.js +19 -0
  12. package/dist/extensions/dashboard-server/html-template.js +41 -0
  13. package/dist/extensions/dashboard-server/html.js +756 -0
  14. package/dist/extensions/dashboard-server/index-reader.js +133 -0
  15. package/dist/extensions/dashboard-server/server.js +370 -0
  16. package/dist/extensions/dashboard-server/snapshot.js +43 -0
  17. package/dist/extensions/dashboard-server/state.js +30 -0
  18. package/dist/extensions/dashboard-server/types.js +5 -0
  19. package/dist/extensions/dashboard-server.js +7 -1315
  20. package/dist/extensions/mega-commands.js +162 -134
  21. package/dist/extensions/mega-compact.test.js +90 -21
  22. package/dist/extensions/mega-conflict-cmds.js +5 -1
  23. package/dist/extensions/mega-dashboard-cmds.js +29 -22
  24. package/dist/extensions/mega-db-cmds.js +11 -2
  25. package/dist/extensions/mega-events/agent-handlers.js +173 -0
  26. package/dist/extensions/mega-events/compact-handlers.js +133 -0
  27. package/dist/extensions/mega-events/context-handler.js +249 -0
  28. package/dist/extensions/mega-events/register.js +21 -0
  29. package/dist/extensions/mega-events/session-handlers.js +142 -0
  30. package/dist/extensions/mega-events.js +15 -699
  31. package/dist/extensions/mega-pipeline/compact.js +324 -0
  32. package/dist/extensions/mega-pipeline/memory-review.js +38 -0
  33. package/dist/extensions/mega-pipeline/recall.js +147 -0
  34. package/dist/extensions/mega-pipeline.js +9 -480
  35. package/dist/extensions/mega-runtime/helpers.js +40 -0
  36. package/dist/extensions/mega-runtime/query.js +29 -0
  37. package/dist/extensions/mega-runtime/state.js +711 -0
  38. package/dist/extensions/mega-runtime/widget.js +197 -0
  39. package/dist/extensions/mega-runtime.js +15 -947
  40. package/dist/src/store/sqlite/checkpoints.js +145 -0
  41. package/dist/src/store/sqlite/connection.js +35 -0
  42. package/dist/src/store/sqlite/dedup-mirror.js +64 -0
  43. package/dist/src/store/sqlite/foundation.js +38 -0
  44. package/dist/src/store/sqlite/global-index.js +224 -0
  45. package/dist/src/store/sqlite/index-store.js +167 -0
  46. package/dist/src/store/sqlite/maintenance.js +235 -0
  47. package/dist/src/store/sqlite/memories.js +164 -0
  48. package/dist/src/store/sqlite/memory.js +54 -0
  49. package/dist/src/store/sqlite/meta.js +82 -0
  50. package/dist/src/store/sqlite/minhash-lsh.js +47 -0
  51. package/dist/src/store/sqlite/model-snapshots.js +47 -0
  52. package/dist/src/store/sqlite/raptor.js +57 -0
  53. package/dist/src/store/sqlite/raw-transcript.js +134 -0
  54. package/dist/src/store/sqlite/schema.js +250 -0
  55. package/dist/src/store/sqlite/session-state.js +28 -0
  56. package/dist/src/store/sqlite/sessions.js +39 -0
  57. package/dist/src/store/sqlite/stats.js +66 -0
  58. package/dist/src/store/sqlite/transaction.js +19 -0
  59. package/dist/src/store/sqlite/utils.js +120 -0
  60. package/dist/src/store/sqlite.js +20 -1607
  61. package/dist/src/vectorStore/add.js +260 -0
  62. package/dist/src/vectorStore/dedup.js +52 -0
  63. package/dist/src/vectorStore/index.js +10 -0
  64. package/dist/src/vectorStore/queries.js +83 -0
  65. package/dist/src/vectorStore/search.js +95 -0
  66. package/dist/src/vectorStore/session.js +19 -0
  67. package/dist/src/vectorStore/store.js +105 -0
  68. package/dist/src/vectorStore/types.js +6 -0
  69. package/dist/src/vectorStore/utils.js +23 -0
  70. package/extensions/dashboard-server/html.ts +758 -0
  71. package/extensions/dashboard-server/index-reader.ts +130 -0
  72. package/extensions/dashboard-server/server.ts +358 -0
  73. package/extensions/dashboard-server/snapshot.ts +44 -0
  74. package/extensions/dashboard-server/state.ts +33 -0
  75. package/extensions/dashboard-server/types.ts +134 -0
  76. package/extensions/dashboard-server.ts +7 -1431
  77. package/extensions/mega-commands.ts +33 -10
  78. package/extensions/mega-compact.test.ts +198 -43
  79. package/extensions/mega-conflict-cmds.ts +6 -2
  80. package/extensions/mega-dashboard-cmds.ts +30 -23
  81. package/extensions/mega-db-cmds.ts +11 -3
  82. package/extensions/mega-events/agent-handlers.ts +214 -0
  83. package/extensions/mega-events/compact-handlers.ts +164 -0
  84. package/extensions/mega-events/context-handler.ts +290 -0
  85. package/extensions/mega-events/register.ts +37 -0
  86. package/extensions/mega-events/session-handlers.ts +165 -0
  87. package/extensions/mega-events.ts +15 -780
  88. package/extensions/mega-pipeline/compact.ts +366 -0
  89. package/extensions/mega-pipeline/memory-review.ts +46 -0
  90. package/extensions/mega-pipeline/recall.ts +165 -0
  91. package/extensions/mega-pipeline.ts +9 -537
  92. package/extensions/mega-runtime/helpers.ts +68 -0
  93. package/extensions/mega-runtime/query.ts +29 -0
  94. package/extensions/mega-runtime/state.ts +797 -0
  95. package/extensions/mega-runtime/widget.ts +258 -0
  96. package/extensions/mega-runtime.ts +15 -1093
  97. package/package.json +4 -3
  98. package/src/store/sqlite/checkpoints.ts +204 -0
  99. package/src/store/sqlite/dedup-mirror.ts +114 -0
  100. package/src/store/sqlite/foundation.ts +63 -0
  101. package/src/store/sqlite/global-index.ts +305 -0
  102. package/src/store/sqlite/maintenance.ts +294 -0
  103. package/src/store/sqlite/memories.ts +217 -0
  104. package/src/store/sqlite/meta.ts +108 -0
  105. package/src/store/sqlite/model-snapshots.ts +83 -0
  106. package/src/store/sqlite/raptor.ts +107 -0
  107. package/src/store/sqlite/raw-transcript.ts +221 -0
  108. package/src/store/sqlite/schema.ts +258 -0
  109. package/src/store/sqlite/session-state.ts +38 -0
  110. package/src/store/sqlite/stats.ts +127 -0
  111. package/src/store/sqlite/utils.ts +125 -0
  112. package/src/store/sqlite.ts +20 -2204
@@ -0,0 +1,249 @@
1
+ import { openStore, appendRawTranscript, writeCheckpointEpoch, } from "../../src/store/sqlite.js";
2
+ import { epochIdFor } from "../../src/mirror/epoch.js";
3
+ import { autoCompactCheck } from "../../src/compact.js";
4
+ import { estimateSessionTokens } from "../../src/tokens.js";
5
+ import { runCompact, piCompactWouldNoop } from "../mega-pipeline.js";
6
+ import { computeLiveTrimCut, liveTrimSummaryMessage } from "../mega-trim.js";
7
+ import { pressureFromPct, pressureRatio, } from "../mega-config.js";
8
+ import { createHash } from "node:crypto";
9
+ /**
10
+ * Convert a pi AgentMessage to a RawTranscriptRow for the DB mirror.
11
+ * content_bytes is canonical JSON (sorted keys) for deterministic hashing.
12
+ * Returns null if the message has no usable content.
13
+ */
14
+ function toRawTranscriptRow(msg, sessionId, epochId) {
15
+ // Narrow to Message union (has content + timestamp).
16
+ const m = msg;
17
+ const content = m.content;
18
+ if (content == null || content === "")
19
+ return null;
20
+ // Canonical form: sort object keys for deterministic hashing.
21
+ const contentBytes = typeof content === "string"
22
+ ? content
23
+ : JSON.stringify(content, Object.keys(content).sort());
24
+ const contentHash = createHash("sha256").update(contentBytes).digest("hex");
25
+ return {
26
+ contentHash,
27
+ sessionId,
28
+ seq: 0, // assigned by appendRawTranscript (COALESCE(MAX(seq),0)+1)
29
+ role: m.role ?? "unknown",
30
+ contentBytes,
31
+ toolName: m.toolName ?? null,
32
+ messageTimestamp: m.timestamp ?? null,
33
+ checkpointEpoch: epochId,
34
+ };
35
+ }
36
+ /** Register the context event handler (live-trim auto-trigger). */
37
+ export function registerContextHandler(pi, runtime, config) {
38
+ // ---- Auto-trigger: live trim (compact and continue) + native durable ----
39
+ // S16 redesign: we NO LONGER call ctx.compact() from the auto-trigger by
40
+ // default. That mapped to pi's MANUAL compaction path, which abort()s the
41
+ // in-flight turn (agent-session.js:1345) and stops the agent. Instead:
42
+ // - LIVE: return { messages: trimmedView } from the context event. This
43
+ // feeds pi's transformContext (sdk.js:226 → agent-loop.js:180) so the
44
+ // model sees a compacted window EVERY LLM call, with no abort. The turn
45
+ // continues. We persist our recall checkpoint (the durable value) first.
46
+ // - DURABLE: pi's NATIVE auto-compaction fires at agent-end
47
+ // (agent-session.js:1565), continues (return hasQueuedMessages()), and
48
+ // emits session_before_compact — where OUR driveNativeCompaction supplies
49
+ // the summary and pi truncates the transcript on disk. No ctx.compact().
50
+ // Legacy: MEGACOMPACT_LEGACY_DURABLE_TRIM=true restores the v0.4.28 ctx.compact
51
+ // path (kept one release as rollback).
52
+ pi.on("context", async (event, ctx) => {
53
+ if (!config.auto)
54
+ return;
55
+ const usage = ctx.getContextUsage();
56
+ const pct = usage?.percent;
57
+ // Always track context for the dashboard, even if we return early below.
58
+ runtime.lastCtxTokens = usage?.tokens ?? null;
59
+ runtime.lastCtxPercent = pct ?? null;
60
+ runtime.lastCtxWindow = usage?.contextWindow ?? 0;
61
+ runtime.snapshot(ctx);
62
+ const messages = event.messages;
63
+ const view = runtime.engineView(messages);
64
+ const currentTokens = usage?.tokens ??
65
+ estimateSessionTokens(view) ??
66
+ Math.round(((pct ?? 0) / 100) * (usage?.contextWindow ?? 0));
67
+ // S27 DB-mirror: append ALL incoming messages to raw_transcript.
68
+ // Runs BEFORE fast-gate so every message is captured, even if we
69
+ // don't compact this turn. Append is idempotent (content_hash PK).
70
+ if (config.dbMirror) {
71
+ try {
72
+ const db = openStore(runtime.currentStateDir);
73
+ const epochId = epochIdFor(runtime.rt.sessionId);
74
+ for (const msg of messages) {
75
+ const raw = toRawTranscriptRow(msg, runtime.rt.sessionId, epochId);
76
+ if (raw)
77
+ appendRawTranscript(db, raw);
78
+ }
79
+ }
80
+ catch (e) {
81
+ runtime.logger.warn("db-mirror-append-fail", { error: String(e) });
82
+ }
83
+ }
84
+ // S29 FAST GATE: drive the auto-trigger off the context % (the number the
85
+ // menu bar shows), NOT the token count — the model under-reports tokens,
86
+ // so a token-only gate misses the overshoot that causes max-output-tokens
87
+ // truncation. The fire point is the tier's percent threshold (tierPct)
88
+ // unless overridden by MEGACOMPACT_AUTO_PCT_TRIGGER. `custom` (absolute
89
+ // MEGACOMPACT_THRESHOLD_TOKENS, tierPct null) is an explicit opt-out of
90
+ // percent scaling — it keeps the token gate. When pct is unavailable
91
+ // (window unknown / a model that doesn't report percent) a tiered config
92
+ // falls back to the token gate (S27 boot-fallback guarantee) instead of
93
+ // skipping compaction — a percent-only gate would regress that.
94
+ let gatePassed = false;
95
+ if (config.tierPct != null && pct != null) {
96
+ const firePct = config.autoPctTrigger ?? config.tierPct;
97
+ gatePassed = pct / 100 >= firePct;
98
+ }
99
+ else {
100
+ // custom tier OR tiered-but-pct-unavailable → token gate (S27 fallback).
101
+ if (currentTokens < runtime.effectiveThreshold) {
102
+ runtime.diagCtxFastGate++;
103
+ return;
104
+ }
105
+ const check = autoCompactCheck(currentTokens, runtime.effectiveThreshold); // SERVER-STYLE CONFIRM (local)
106
+ if (!check.shouldCompact) {
107
+ runtime.diagCtxNoCompact++;
108
+ return;
109
+ }
110
+ gatePassed = true;
111
+ }
112
+ if (!gatePassed) {
113
+ runtime.diagCtxFastGate++;
114
+ return;
115
+ }
116
+ // Debounce so we don't fire on every context event past threshold.
117
+ const now = Date.now();
118
+ if (now < runtime.debounceUntil) {
119
+ runtime.diagCtxDebounce++;
120
+ return;
121
+ }
122
+ runtime.debounceUntil = now + 2000;
123
+ // Adaptive compression (Fix E): scale compression strength + keepFrom depth
124
+ // with how close we are to the model context limit. Null-safe: when the
125
+ // token-fallback path ran (pct unavailable) use the token-basis pressure
126
+ // (the same basis the runtime `pressure` getter uses for custom/no-window).
127
+ const pressure = pct != null ? pressureFromPct(pct) : pressureRatio(currentTokens, runtime.effectiveThreshold);
128
+ const ran = runCompact(pi, runtime, config, ctx, messages, {
129
+ compressionPressure: pressure,
130
+ });
131
+ if (ran.skipped) {
132
+ runtime.diagCtxRunSkipped++;
133
+ return;
134
+ }
135
+ // S27 DB-mirror: write checkpoint_epoch with deterministic nonce.
136
+ // This makes the cache key stable across identical compactions.
137
+ if (config.dbMirror) {
138
+ try {
139
+ const db = openStore(runtime.currentStateDir);
140
+ const cpId = ran.result.checkpointId ?? `epoch-${Date.now()}`;
141
+ const epoch = {
142
+ epochId: epochIdFor(cpId),
143
+ sessionId: runtime.rt.sessionId,
144
+ startedSeq: 0,
145
+ committedSeq: ran.result.compactedFrom,
146
+ checkpointId: cpId,
147
+ cutIndex: ran.result.compactedFrom,
148
+ summaryMessageText: ran.result.summary,
149
+ createdAt: Date.now(),
150
+ };
151
+ writeCheckpointEpoch(db, epoch);
152
+ // S27 Task 6: Fire-and-forget dedup pipeline.
153
+ // Deduplicates raw_transcript rows for the compacted range.
154
+ try {
155
+ const { dedupTranscript } = await import("../../src/mirror/dedup.js");
156
+ dedupTranscript(db, runtime.rt.sessionId, 0, ran.result.compactedFrom);
157
+ }
158
+ catch (_dedupErr) {
159
+ // Fire-and-forget: dedup failure is non-fatal
160
+ }
161
+ }
162
+ catch (e) {
163
+ runtime.logger.warn("db-mirror-epoch-fail", { error: String(e) });
164
+ }
165
+ }
166
+ // LEGACY path (rollback): v0.4.28 ctx.compact() + the no-op gate. The
167
+ // manual compact path aborts the in-flight turn — only used behind the flag.
168
+ // Read live from env (in addition to the load-time config) so the flag can be
169
+ // toggled per-test without reloading the module; config.legacyDurableTrim is
170
+ // the cached default. (Mirrors how piCompactWouldNoop re-reads its floor.)
171
+ const legacy = config.legacyDurableTrim ||
172
+ process.env.MEGACOMPACT_LEGACY_DURABLE_TRIM === "true" ||
173
+ process.env.MEGACOMPACT_LEGACY_DURABLE_TRIM === "1";
174
+ if (legacy) {
175
+ // COMPACT-DEDUP FIX: same race guard as the agent_end path. Skip when a
176
+ // NATIVE compaction just fired (avoids racing pi and surfacing a spurious
177
+ // "Already compacted" / "Nothing to compact" toast). Uses lastNativeCompactAt
178
+ // (NOT lastCompactAt, which runCompact also stamps for our own checkpoint).
179
+ const sinceCompact = Date.now() - (runtime.rt.lastNativeCompactAt ?? 0);
180
+ if (sinceCompact < 10_000 || piCompactWouldNoop(ctx))
181
+ return;
182
+ ctx.compact({ customInstructions: undefined }); // race-guarded by lastNativeCompactAt cooldown (ctx.compact returns void → not catchable; the cooldown prevents the call)
183
+ return;
184
+ }
185
+ // S16 LIVE trim: collapse the compacted region to a summary + recent anchor.
186
+ // Non-destructive: pi keeps the real transcript; only this LLM call sees the
187
+ // trimmed window. We compute the cut on the engine view (pure, tested) then
188
+ // slice the ORIGINAL pi AgentMessage[] from that index (lossless alignment,
189
+ // mirroring dropCompactedRange) and prepend a user-role summary message.
190
+ // A build failure or unsafe cut returns nothing (no trim this call — the
191
+ // next context event retries). The anchor floor is read live from env (the
192
+ // config value is the cached default) so it can be tuned per-test / per-run
193
+ // without reloading the module.
194
+ try {
195
+ const anchorEnv = process.env.MEGACOMPACT_ANCHOR_USER_MESSAGES;
196
+ const anchorUserMessages = anchorEnv != null &&
197
+ anchorEnv !== "" &&
198
+ Number.isFinite(Number(anchorEnv))
199
+ ? Number(anchorEnv)
200
+ : config.anchorUserMessages;
201
+ const cut = computeLiveTrimCut(view, {
202
+ compactedFrom: ran.result.compactedFrom,
203
+ summary: ran.result.summary,
204
+ anchorUserMessages,
205
+ });
206
+ if (cut === null) {
207
+ runtime.diagCtxCutNull++;
208
+ runtime.logger.info("live-trim-skip", {
209
+ sessionId: runtime.rt.sessionId,
210
+ compactedFrom: ran.result.compactedFrom,
211
+ viewLen: view.length,
212
+ anchorUserMessages,
213
+ });
214
+ return; // unsafe / below anchor floor — no trim this call
215
+ }
216
+ const summaryMsg = liveTrimSummaryMessage({
217
+ compactedFrom: ran.result.compactedFrom,
218
+ summary: ran.result.summary,
219
+ anchorUserMessages: config.anchorUserMessages,
220
+ });
221
+ // Synthesize a user-role AgentMessage carrying the compacted summary.
222
+ const summaryAgentMsg = {
223
+ role: "user",
224
+ content: summaryMsg.text,
225
+ timestamp: Date.now(),
226
+ };
227
+ const recent = messages.slice(cut); // guardrails-allow PREVENT-PI-002: `cut` is the pre-sanitized `compactedFrom` produced by src/boundary.ts computeDropRange, so the preserved run begins on a toolPair-safe index.
228
+ runtime.snapshot(ctx);
229
+ // DIAG (team-run relief): confirm the live trim actually fires + how big
230
+ // the window still is. The return is non-durable (per-LLM-call only), so
231
+ // this is the signal that the model is being fed a compacted view while
232
+ // the on-disk transcript + context meter keep growing.
233
+ runtime.diagLiveTrimFires++;
234
+ runtime.logger.info("live-trim", {
235
+ sessionId: runtime.rt.sessionId,
236
+ inputMsgs: messages.length,
237
+ outputMsgs: recent.length + 1,
238
+ compactedFrom: cut,
239
+ ctxPct: pct,
240
+ ctxTokens: usage?.tokens ?? null,
241
+ });
242
+ return { messages: [summaryAgentMsg, ...recent] };
243
+ }
244
+ catch {
245
+ runtime.diagCtxThrown++;
246
+ return; // non-fatal: no trim this call; the next context event retries
247
+ }
248
+ });
249
+ }
@@ -0,0 +1,21 @@
1
+ import { registerSessionHandlers } from "./session-handlers.js";
2
+ import { registerAgentHandlers } from "./agent-handlers.js";
3
+ import { registerContextHandler } from "./context-handler.js";
4
+ import { registerCompactHandlers } from "./compact-handlers.js";
5
+ /**
6
+ * DIAG accessor for the headless test harness: the most recently constructed
7
+ * MegaRuntime, so a test that loads the compiled extension via its default
8
+ * export can read diag counters (diagLiveTrimFires / diagBeforeCompactFires /
9
+ * diagBeforeCompactSupplied / diagAgentEndIdle) after firing synthetic events.
10
+ * No-op in production — nothing reads this outside tests.
11
+ */
12
+ export let lastRuntime;
13
+ /** Register all pi lifecycle event handlers. */
14
+ export function registerEventHandlers(pi, runtime, config) {
15
+ lastRuntime = runtime;
16
+ // ---- Session lifecycle (state reset points) -------------------------------
17
+ registerSessionHandlers(pi, runtime, config);
18
+ registerAgentHandlers(pi, runtime, config);
19
+ registerContextHandler(pi, runtime, config);
20
+ registerCompactHandlers(pi, runtime, config);
21
+ }
@@ -0,0 +1,142 @@
1
+ import { normalizeSessionId } from "../../src/store.js";
2
+ import { autoMaintain } from "../../src/store/sqlite.js";
3
+ import { recentUserQuery, WIDGET_KEY, } from "../mega-runtime.js";
4
+ import { doRecall, doRecallAsync, } from "../mega-pipeline.js";
5
+ import { recallMemoriesAndInline } from "../../src/recall.js";
6
+ /** Register session lifecycle event handlers. */
7
+ export function registerSessionHandlers(pi, runtime, config) {
8
+ // Capture model/provider whenever it changes (drives real cost estimation).
9
+ pi.on("model_select", async (_event, ctx) => {
10
+ runtime.captureModel(ctx);
11
+ runtime.snapshot(ctx);
12
+ });
13
+ pi.on("session_start", async (event, ctx) => {
14
+ runtime.resetRuntime(ctx.sessionManager.getSessionId());
15
+ runtime.captureModel(ctx); // best-effort: ctx.model may be set by session start
16
+ runtime.setStatus(ctx, config.auto ? "mega-compact: ready" : "mega-compact: manual only");
17
+ // S21: clear any stale memory block from a prior session.
18
+ runtime.pendingMemoryRecallBlock = undefined;
19
+ // Auto-inline on resume/fork/continue: stage the most relevant checkpoints
20
+ // so the next before_agent_start prepends them to the system prompt.
21
+ // Triggered whenever this session already has persisted checkpoints AND a
22
+ // usable query — that covers reason "resume"/"fork" (explicit) and
23
+ // reason "startup" (e.g. `pi --continue`s an existing session, which still
24
+ // emits "startup" but with a populated message window). A brand-new empty
25
+ // session has no checkpoints, so it's naturally excluded.
26
+ if (config.autoInline) {
27
+ const sid = normalizeSessionId(ctx.sessionManager.getSessionId());
28
+ const query = recentUserQuery(ctx);
29
+ if (query && runtime.store.stats(sid).checkpointCount > 0) {
30
+ // S17: use the async variant on resume so cross-repo HNSW recall can
31
+ // augment when this repo's store is thin. session_start is an async-safe
32
+ // point (unlike the mid-turn context handler, which stays sync).
33
+ const r = await doRecallAsync(runtime, config, ctx, query, "resume", {
34
+ crossRepo: config.crossRepoEnabled,
35
+ });
36
+ if (!r.empty) {
37
+ runtime.pendingRecallBlock = r.block;
38
+ const crossLabel = r.toInject.some((h) => h.repoId)
39
+ ? " (cross-repo)"
40
+ : "";
41
+ runtime.setStatus(ctx, `mega-compact: recalled ${r.toInject.length} chkpt${crossLabel}`);
42
+ runtime.logger.info("auto-inline", {
43
+ reason: event.reason,
44
+ query,
45
+ injected: r.toInject.map((h) => h.checkpoint.checkpointId),
46
+ crossRepo: r.toInject.some((h) => h.repoId),
47
+ });
48
+ }
49
+ }
50
+ // S21: parallel memory recall. Same async context so we can await without
51
+ // breaking the handler contract. Best-effort — never throws.
52
+ try {
53
+ const mr = await recallMemoriesAndInline({
54
+ query,
55
+ stateDir: runtime.getStateDir(),
56
+ limit: 5,
57
+ crossRepo: config.crossRepoEnabled,
58
+ crossRepoCosine: config.crossRepoCosine,
59
+ });
60
+ if (!mr.empty)
61
+ runtime.pendingMemoryRecallBlock = mr.block;
62
+ }
63
+ catch (err) {
64
+ runtime.logger.warn("memory-recall skipped", { err: String(err) });
65
+ }
66
+ }
67
+ // S27 Task 10: best-effort auto-maintenance on session start (prune rows
68
+ // older than 30d, checkpoint WAL if >10MB, VACUUM if DB >100MB + >20%
69
+ // freelist). Never blocks session start — swallows errors and logs a
70
+ // one-line summary for diagnostics.
71
+ try {
72
+ const m = autoMaintain(runtime.currentStateDir);
73
+ if (m && !m.endsWith("nothing to do"))
74
+ runtime.logger.info("db-auto-maintain", { result: m });
75
+ }
76
+ catch (e) {
77
+ runtime.logger.warn("db-auto-maintain-fail", { error: String(e) });
78
+ }
79
+ runtime.dashboard.event("session_start", {
80
+ reason: event.reason,
81
+ sessionId: runtime.rt.sessionId,
82
+ });
83
+ runtime.snapshot(ctx);
84
+ });
85
+ pi.on("session_tree", async (_event, ctx) => {
86
+ // Branch navigation invalidates region indexes — reset checkpoint memory but
87
+ // keep the on-disk store (markers replayed from entries below if needed).
88
+ runtime.resetRuntime(ctx.sessionManager.getSessionId());
89
+ runtime.setStatus(ctx, "mega-compact: ready (branch)");
90
+ if (config.autoInline) {
91
+ const query = recentUserQuery(ctx);
92
+ if (query) {
93
+ const r = doRecall(runtime, config, ctx, query, "resume");
94
+ if (!r.empty) {
95
+ runtime.pendingRecallBlock = r.block;
96
+ runtime.logger.info("auto-inline", {
97
+ reason: "session_tree",
98
+ query,
99
+ injected: r.toInject.map((h) => h.checkpoint.checkpointId),
100
+ });
101
+ }
102
+ // S21: parallel memory recall. Trigram embedder is sub-ms; await is fine.
103
+ try {
104
+ const mr = await recallMemoriesAndInline({
105
+ query,
106
+ stateDir: runtime.getStateDir(),
107
+ limit: 5,
108
+ crossRepo: config.crossRepoEnabled,
109
+ crossRepoCosine: config.crossRepoCosine,
110
+ });
111
+ if (!mr.empty)
112
+ runtime.pendingMemoryRecallBlock = mr.block;
113
+ }
114
+ catch (err) {
115
+ runtime.logger.warn("memory-recall skipped", { err: String(err) });
116
+ }
117
+ }
118
+ }
119
+ runtime.dashboard.event("session_tree", {
120
+ sessionId: runtime.rt.sessionId,
121
+ });
122
+ runtime.snapshot(ctx);
123
+ });
124
+ // ---- Auto-inline injection point: prepend staged recall to systemPrompt ----
125
+ pi.on("before_agent_start", async (event, ctx) => {
126
+ runtime.captureModel(ctx); // most reliable point ctx.model is populated
127
+ const cpBlock = runtime.pendingRecallBlock;
128
+ const memBlock = runtime.pendingMemoryRecallBlock;
129
+ if (!cpBlock && !memBlock)
130
+ return;
131
+ runtime.pendingRecallBlock = undefined;
132
+ runtime.pendingMemoryRecallBlock = undefined;
133
+ const composed = [cpBlock, memBlock].filter(Boolean).join("\n\n");
134
+ return { systemPrompt: `${event.systemPrompt}\n\n${composed}` };
135
+ });
136
+ pi.on("session_shutdown", async (_event, ctx) => {
137
+ runtime.setStatus(ctx, undefined);
138
+ runtime.activeAgents = 0;
139
+ runtime.currentTurn = 0;
140
+ ctx.ui.setWidget(WIDGET_KEY, [], { placement: "aboveEditor" });
141
+ });
142
+ }