pi-mega-compact 0.17.1 → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/config/vector-cortex.js +10 -0
- package/dist/extensions/dashboard-server/routes-rag-settings-helpers.js +1 -0
- package/dist/extensions/mega-events/context-handler/dbMirrorAppend.js +63 -0
- package/dist/extensions/mega-events/context-handler/gateCheck.js +59 -0
- package/dist/extensions/mega-events/context-handler/liveTrim.js +178 -0
- package/dist/extensions/mega-events/context-handler/pipelineRun.js +37 -0
- package/dist/extensions/mega-events/context-handler.js +39 -305
- package/dist/src/config/vector-cortex.js +10 -0
- package/dist/src/config.js +1 -1
- package/dist/src/vector-cortex/encoder/asset.js +142 -0
- package/dist/src/vector-cortex/encoder/emit.js +42 -0
- package/dist/src/vector-cortex/encoder/runtime.js +228 -0
- package/dist/src/vector-cortex/encoder/types.js +85 -0
- package/dist/vector-cortex/encoder/asset.js +142 -0
- package/dist/vector-cortex/encoder/emit.js +42 -0
- package/dist/vector-cortex/encoder/runtime.js +228 -0
- package/dist/vector-cortex/encoder/types.js +85 -0
- package/extensions/dashboard-server/routes-rag-settings-helpers.ts +6 -0
- package/extensions/mega-events/context-handler/dbMirrorAppend.ts +93 -0
- package/extensions/mega-events/context-handler/gateCheck.ts +101 -0
- package/extensions/mega-events/context-handler/liveTrim.ts +241 -0
- package/extensions/mega-events/context-handler/pipelineRun.ts +79 -0
- package/extensions/mega-events/context-handler.ts +45 -347
- package/package.json +1 -1
- package/src/config/vector-cortex.ts +11 -0
- package/src/config.ts +1 -0
- package/src/vector-cortex/encoder/asset.ts +155 -0
- package/src/vector-cortex/encoder/emit.ts +51 -0
- package/src/vector-cortex/encoder/runtime.ts +283 -0
- package/src/vector-cortex/encoder/types.ts +165 -0
|
@@ -63,6 +63,16 @@ export const VC0C_ENABLED = () => sprintFlag("MEGACOMPACT_VC0C");
|
|
|
63
63
|
* emit seam, the minhash-v2 backfill seam and the downgrade-export seam.
|
|
64
64
|
*/
|
|
65
65
|
export const VC1C_ENABLED = () => sprintFlag("MEGACOMPACT_VC1C");
|
|
66
|
+
/**
|
|
67
|
+
* VC2A — offline model runtime and asset decision (ModelManifestV1 /
|
|
68
|
+
* EncoderRuntime).
|
|
69
|
+
* Default ON. `MEGACOMPACT_VC2A=0` disables and is byte-identical to the
|
|
70
|
+
* predecessor (mode C: no asset manifest is read/verified, the encoder runtime
|
|
71
|
+
* idles in mode C, zero `vector_cortex_encoder_*` emissions; the trigram/lexical
|
|
72
|
+
* paths are unchanged). The real consumers are the encoder emit seam and the
|
|
73
|
+
* encoder runtime's A/B/C selection.
|
|
74
|
+
*/
|
|
75
|
+
export const VC2A_ENABLED = () => sprintFlag("MEGACOMPACT_VC2A");
|
|
66
76
|
// ---------------------------------------------------------------------------
|
|
67
77
|
// Breaker state machine constants (TRIAD_RESILIENCE.md §breaker).
|
|
68
78
|
// Rolled numbers for one 60s window; VC0C consumes these at its breaker seam.
|
|
@@ -138,6 +138,7 @@ export const SETTINGS = [
|
|
|
138
138
|
boolDirect("MEGACOMPACT_VC1B", "VC1B Occurrence Ledger + Tool Identity", "Neutral occurrence ledger (LedgerReader/Writer/Admin + CompatJournalV1): per-session monotonic seq, tool result references one earlier call, uniqueness by (eventId,digest) only, and the M2 copy-validate-switch downgrade journal. OFF = mode C, ledger unwritten, byte-identical.", true),
|
|
139
139
|
boolDirect("MEGACOMPACT_VC0C", "VC0C Live Safety Envelope", "TriadResult/Breaker live circuit breaker (60s window, 20 attempts, 30s cooldown, 3 probes, 5min healthy residence) + durable spool before provider invocation; manual reset clears cooldown but never evidence. OFF = mode C, unchanged transcript, byte-identical.", true),
|
|
140
140
|
boolDirect("MEGACOMPACT_VC1C", "VC1C Cross-Language Conformance v2", "FixtureManifestV2 canonical manifest validator + DowngradeReport deterministic downgrade export + MinHashV2 exact big-integer signatures and the M4 copy/validate/switch minhash-v2 migration (seed table frozen, cross-language byte-exact). OFF = mode C, v1 sync dedup scan unchanged, byte-identical.", true),
|
|
141
|
+
boolDirect("MEGACOMPACT_VC2A", "VC2A Offline Model Runtime", "ModelManifestV1 digest-before-load ONNX runtime (opset17/batch1/max512) + asset-free trigram demotion. Asset path assets/vector-cortex/encoder-v1 is immutable/digest-pinned. OFF = mode C, byte-identical to predecessor.", true),
|
|
141
142
|
],
|
|
142
143
|
},
|
|
143
144
|
{
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { openStore } from "../../../src/store/sqlite.js";
|
|
2
|
+
import { appendMirrorMessages } from "../mirror-append.js";
|
|
3
|
+
import { appendMessagesToLedger } from "../../mega-runtime/vector-cortex-ledger.js";
|
|
4
|
+
import { epochIdFor } from "../../../src/mirror/epoch.js";
|
|
5
|
+
import { messageContentText } from "./messageText.js";
|
|
6
|
+
/**
|
|
7
|
+
* Append incoming messages to the DB mirror (raw_transcript + thread/tool
|
|
8
|
+
* tables) and the v2 ledger. Gated on config.dbMirror for the mirror; the VC1B
|
|
9
|
+
* ledger append is flag-gated inside appendMessagesToLedger (flag-OFF opens no
|
|
10
|
+
* DB, byte-identical to the predecessor). Non-fatal end-to-end.
|
|
11
|
+
*/
|
|
12
|
+
export function appendMirrorAndLedger(runtime, config, messages) {
|
|
13
|
+
// S27 DB-mirror: append incoming messages to raw_transcript.
|
|
14
|
+
// Runs BEFORE fast-gate so every message is captured, even if we
|
|
15
|
+
// don't compact this turn. Append is idempotent (content_hash PK).
|
|
16
|
+
// F3: high-water mark (mirror-append.ts) skips already-processed
|
|
17
|
+
// messages on subsequent events. On fork/rewind (shorter list or
|
|
18
|
+
// boundary hash mismatch) the mark is dropped, falling back to a
|
|
19
|
+
// full reprocess.
|
|
20
|
+
if (config.dbMirror) {
|
|
21
|
+
try {
|
|
22
|
+
const db = openStore(runtime.currentStateDir);
|
|
23
|
+
appendMirrorMessages(db, messages, runtime.rt.sessionId, epochIdFor(runtime.rt.sessionId), runtime.currentTurn);
|
|
24
|
+
// P2.2: populate conversation_thread + tool_results tables for
|
|
25
|
+
// prompt-cache analytics and durable separation. The live-array
|
|
26
|
+
// separation (buildSeparatedPrompt / buildCacheOptimizedPrompt in
|
|
27
|
+
// tailResult) is sufficient for the prompt-construction path;
|
|
28
|
+
// these DB writes persist the split for post-hoc analysis, dashboard
|
|
29
|
+
// queries, and future readers. Non-fatal — failure here never breaks
|
|
30
|
+
// the agent loop (PREVENT-PI-004: zero network, local SQLite only).
|
|
31
|
+
{
|
|
32
|
+
const sid = runtime.rt.sessionId;
|
|
33
|
+
const turn = runtime.currentTurn;
|
|
34
|
+
const now = Date.now();
|
|
35
|
+
const threadStmt = db.prepare("INSERT OR IGNORE INTO conversation_thread (conversation_id, role, content, turn_index, timestamp) VALUES (?, ?, ?, ?, ?)");
|
|
36
|
+
const toolStmt = db.prepare("INSERT OR IGNORE INTO tool_results (conversation_id, role, content, turn_index, timestamp) VALUES (?, ?, ?, ?, ?)");
|
|
37
|
+
for (const m of messages) {
|
|
38
|
+
const role = m.role;
|
|
39
|
+
const content = messageContentText(m);
|
|
40
|
+
if (role === "user" || role === "assistant") {
|
|
41
|
+
threadStmt.run(sid, role, content, turn, now);
|
|
42
|
+
}
|
|
43
|
+
else if (role === "toolResult" || role === "bashExecution") {
|
|
44
|
+
toolStmt.run(sid, role, content, turn, now);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
catch (e) {
|
|
50
|
+
runtime.logger.warn("db-mirror-append-fail", { error: String(e) });
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
// VC1B (S1): canonical messages -> v2 ledger occurrences. Flag-OFF opens
|
|
54
|
+
// no DB (byte-identical predecessor); non-fatal. onFailure surfaces
|
|
55
|
+
// per-append rejections (e.g. EVT_SEQ_REGRESSION on rewind/fork) as
|
|
56
|
+
// structured warnings rather than swallowing them silently.
|
|
57
|
+
try {
|
|
58
|
+
appendMessagesToLedger(runtime.currentStateDir, runtime.rt.sessionId, messages, runtime.logger);
|
|
59
|
+
}
|
|
60
|
+
catch (e) {
|
|
61
|
+
runtime.logger.warn("vc1b-ledger-append-fail", { error: String(e) });
|
|
62
|
+
}
|
|
63
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { resolveModelThreshold, DEFAULT_SAFETY_MARGIN_PCT, DEFAULT_FIRE_POINT_PCT, } from "../../../src/store/sqlite.js";
|
|
2
|
+
import { autoCompactCheck } from "../../../src/compact.js";
|
|
3
|
+
/**
|
|
4
|
+
* Evaluate whether the current context warrants compaction. Returns a tailed
|
|
5
|
+
* view ("return") when the gate does not pass, or "proceed" with the resolved
|
|
6
|
+
* per-model threshold (reused by the live-trim token-budget tail cap).
|
|
7
|
+
*/
|
|
8
|
+
export function evaluateGate(runtime, config, opts) {
|
|
9
|
+
const pct = opts.pct;
|
|
10
|
+
const currentTokens = opts.currentTokens;
|
|
11
|
+
const tailResult = opts.tailResult;
|
|
12
|
+
// S52 / v0.16.1: per-model threshold override. The user can tune the
|
|
13
|
+
// fire point + safety margin PER MODEL (different providers' models range
|
|
14
|
+
// 8K-1M+ context, so one global tier % is wrong). Falls back to env/default
|
|
15
|
+
// when no override row exists. Computed once here + reused in the tail cap
|
|
16
|
+
// below; the lookup is a single SQLite PK hit (cheap; cached after the
|
|
17
|
+
// first read in a session).
|
|
18
|
+
const modelIdForThreshold = runtime.currentModel?.modelId ?? null;
|
|
19
|
+
const perModelThreshold = resolveModelThreshold(modelIdForThreshold, {
|
|
20
|
+
safetyMarginFallback: DEFAULT_SAFETY_MARGIN_PCT,
|
|
21
|
+
firePointFallback: config.tierPct != null
|
|
22
|
+
? Math.round(config.tierPct * 100)
|
|
23
|
+
: DEFAULT_FIRE_POINT_PCT,
|
|
24
|
+
stateDir: runtime.currentStateDir,
|
|
25
|
+
});
|
|
26
|
+
// S29 FAST GATE: `custom` (absolute MEGACOMPACT_THRESHOLD_TOKENS,
|
|
27
|
+
// tierPct null) is an explicit opt-out of percent scaling — it keeps the
|
|
28
|
+
// token gate. When pct is unavailable (window unknown / a model that
|
|
29
|
+
// doesn't report percent) a tiered config falls back to the token gate
|
|
30
|
+
// (S27 boot-fallback guarantee) instead of skipping compaction — a
|
|
31
|
+
// percent-only gate would regress that.
|
|
32
|
+
let gatePassed = false;
|
|
33
|
+
if (config.tierPct != null && pct != null) {
|
|
34
|
+
// Per-model override is a % (10-90); tierPct is a fraction (0.1-1.0).
|
|
35
|
+
// Prefer the override; fall back to autoPctTrigger + tierPct.
|
|
36
|
+
const tierPctFraction = config.autoPctTrigger ?? config.tierPct;
|
|
37
|
+
const perModelFraction = perModelThreshold.firePointPct / 100;
|
|
38
|
+
const firePct = modelIdForThreshold != null ? perModelFraction : tierPctFraction;
|
|
39
|
+
gatePassed = pct / 100 >= firePct;
|
|
40
|
+
}
|
|
41
|
+
else {
|
|
42
|
+
// custom tier OR tiered-but-pct-unavailable → token gate (S27 fallback).
|
|
43
|
+
if (currentTokens < runtime.effectiveThreshold) {
|
|
44
|
+
runtime.diagCtxFastGate++;
|
|
45
|
+
return { kind: "return", view: tailResult() ?? undefined };
|
|
46
|
+
}
|
|
47
|
+
const check = autoCompactCheck(currentTokens, runtime.effectiveThreshold); // SERVER-STYLE CONFIRM (local)
|
|
48
|
+
if (!check.shouldCompact) {
|
|
49
|
+
runtime.diagCtxNoCompact++;
|
|
50
|
+
return { kind: "return", view: tailResult() ?? undefined };
|
|
51
|
+
}
|
|
52
|
+
gatePassed = true;
|
|
53
|
+
}
|
|
54
|
+
if (!gatePassed) {
|
|
55
|
+
runtime.diagCtxFastGate++;
|
|
56
|
+
return { kind: "return", view: tailResult() ?? undefined };
|
|
57
|
+
}
|
|
58
|
+
return { kind: "proceed", perModelThreshold };
|
|
59
|
+
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import { estimateBlockTokens, estimateMessageTokens, } from "../../../src/tokens.js";
|
|
2
|
+
import { computeLiveTrimCut, liveTrimSummaryMessage } from "../../mega-trim.js";
|
|
3
|
+
import { messageContentText } from "./messageText.js";
|
|
4
|
+
/**
|
|
5
|
+
* Reconstruct the live-trim window (summary + recent anchor) for this LLM
|
|
6
|
+
* call. Returns the tailed view, or undefined when no trim is safe this call.
|
|
7
|
+
*/
|
|
8
|
+
export function buildLiveTrimView(runtime, config, ctx, opts) {
|
|
9
|
+
const { messages, view, pct, currentTokens, usageTokens, pressure, ran, perModelThreshold, tailResult, } = opts;
|
|
10
|
+
// S16 LIVE trim: collapse the compacted region to a summary + recent anchor.
|
|
11
|
+
// Non-destructive: pi keeps the real transcript; only this LLM call sees the
|
|
12
|
+
// trimmed window. We compute the cut on the engine view (pure, tested) then
|
|
13
|
+
// slice the ORIGINAL pi AgentMessage[] from that index (lossless alignment,
|
|
14
|
+
// mirroring dropCompactedRange) and prepend a user-role summary message.
|
|
15
|
+
// A build failure or unsafe cut returns nothing (no trim this call — the
|
|
16
|
+
// next context event retries). The anchor floor is read live from env (the
|
|
17
|
+
// config value is the cached default) so it can be tuned per-test / per-run
|
|
18
|
+
// without reloading the module.
|
|
19
|
+
try {
|
|
20
|
+
const anchorEnv = process.env.MEGACOMPACT_ANCHOR_USER_MESSAGES;
|
|
21
|
+
const anchorUserMessages = anchorEnv != null &&
|
|
22
|
+
anchorEnv !== "" &&
|
|
23
|
+
Number.isFinite(Number(anchorEnv))
|
|
24
|
+
? Number(anchorEnv)
|
|
25
|
+
: config.anchorUserMessages;
|
|
26
|
+
const cut = computeLiveTrimCut(view, {
|
|
27
|
+
compactedFrom: ran.result.compactedFrom,
|
|
28
|
+
summary: ran.result.summary,
|
|
29
|
+
anchorUserMessages,
|
|
30
|
+
// CRITICAL-OVER ESCAPE HATCH: when context is at/over ~90% of the
|
|
31
|
+
// window, relief takes priority over the anchor floor. Without this,
|
|
32
|
+
// computeLiveTrimCut bails to null (can't satisfy the floor) and the
|
|
33
|
+
// model is fed a raw overflow that errors every turn — the
|
|
34
|
+
// "Already compacted" + overflow death-spiral (2026-08-01 incident).
|
|
35
|
+
// A thin anchor is recoverable; an overflowed session is not.
|
|
36
|
+
//
|
|
37
|
+
// CRITICAL: pct is null for OpenAI-compatible providers that don't
|
|
38
|
+
// report usage.percent (e.g. neuralwatt). Without the token-pressure
|
|
39
|
+
// fallback the hatch never armed → cut=null → raw overflow → 400
|
|
40
|
+
// "conversation too long even after compaction" (2026-08-03 incident
|
|
41
|
+
// on glm-5.2-short, 200K window). Now also fires on pressure >= 0.9
|
|
42
|
+
// (token-basis) so the hatch arms regardless of whether the provider
|
|
43
|
+
// reports pct.
|
|
44
|
+
criticalOver: (pct ?? 0) >= 90 || pressure >= 0.9,
|
|
45
|
+
});
|
|
46
|
+
if (cut === null) {
|
|
47
|
+
runtime.diagCtxCutNull++;
|
|
48
|
+
runtime.logger.info("live-trim-skip", {
|
|
49
|
+
sessionId: runtime.rt.sessionId,
|
|
50
|
+
compactedFrom: ran.result.compactedFrom,
|
|
51
|
+
viewLen: view.length,
|
|
52
|
+
anchorUserMessages,
|
|
53
|
+
criticalOver: (pct ?? 0) >= 90,
|
|
54
|
+
});
|
|
55
|
+
return tailResult() ?? undefined; // unsafe / below anchor floor — no trim this call
|
|
56
|
+
}
|
|
57
|
+
const summaryMsg = liveTrimSummaryMessage({
|
|
58
|
+
compactedFrom: ran.result.compactedFrom,
|
|
59
|
+
summary: ran.result.summary,
|
|
60
|
+
anchorUserMessages: config.anchorUserMessages,
|
|
61
|
+
});
|
|
62
|
+
// Synthesize a user-role AgentMessage carrying the compacted summary.
|
|
63
|
+
const summaryAgentMsg = {
|
|
64
|
+
role: "user",
|
|
65
|
+
content: summaryMsg.text,
|
|
66
|
+
// v0.8.6: stable timestamp across the epoch (NOT Date.now()) so the
|
|
67
|
+
// summary message bytes — and thus the KV-cache prefix — don't drift
|
|
68
|
+
// on every replay within the same compaction epoch.
|
|
69
|
+
timestamp: runtime.rt.lastCompactAt ?? Date.now(),
|
|
70
|
+
};
|
|
71
|
+
const recentRaw = 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.
|
|
72
|
+
// FIX 2 (2026-08-03 incident): TOKEN-BUDGET CAP on the live-trim view.
|
|
73
|
+
// Compaction fires at tier% of the window (140K for a 200K window),
|
|
74
|
+
// but a SINGLE turn can inject a huge tool output (file read, bash) that
|
|
75
|
+
// jumps context from 139K → 199K+ before the next gate fires. When that
|
|
76
|
+
// happens [summary + preserved tail] can STILL exceed the model window,
|
|
77
|
+
// and the provider rejects with 400 "conversation too long even after
|
|
78
|
+
// compaction". The anchor floor (PREVENT-PI-001) keeps ≥N user messages
|
|
79
|
+
// but has NO token cap, so a 2-message tail of two 80K bash outputs sails
|
|
80
|
+
// right past the window.
|
|
81
|
+
//
|
|
82
|
+
// Cap: when the model context window is known, reserve room for the
|
|
83
|
+
// summary + the model's max output tokens + a 10% safety margin, then
|
|
84
|
+
// drop oldest preserved messages from the front of `recentRaw` until the
|
|
85
|
+
// tail fits. Never drops below the FINAL message (always keep the latest
|
|
86
|
+
// turn so the agent can respond). This is a last-resort HARD cap — it
|
|
87
|
+
// only fires when the preserved tail alone is oversized, which is rare.
|
|
88
|
+
const ctxWindow = runtime.lastCtxWindow;
|
|
89
|
+
// Reuse the per-model threshold resolved at the gate (single lookup).
|
|
90
|
+
const modelThreshold = perModelThreshold;
|
|
91
|
+
// Reserve room for output tokens. Use the model's reported max output
|
|
92
|
+
// when known; fall back to 10% of the window (scales with any model —
|
|
93
|
+
// 20K for a 200K window, 100K for a 1M window) so we never let the
|
|
94
|
+
// preserved tail eat the model's output budget when maxTokens is unknown.
|
|
95
|
+
const maxOutput = runtime.currentModel?.maxTokens && runtime.currentModel.maxTokens > 0
|
|
96
|
+
? runtime.currentModel.maxTokens
|
|
97
|
+
: Math.ceil(ctxWindow * 0.1);
|
|
98
|
+
let recent = recentRaw;
|
|
99
|
+
if (ctxWindow > 0 && recentRaw.length > 1) {
|
|
100
|
+
const summaryTokens = estimateBlockTokens(summaryMsg.text);
|
|
101
|
+
// Reserve: summary + max output + per-model safety margin (0-20%).
|
|
102
|
+
const safetyMargin = Math.ceil(ctxWindow * (modelThreshold.safetyMarginPct / 100));
|
|
103
|
+
const budget = ctxWindow - maxOutput - safetyMargin - summaryTokens;
|
|
104
|
+
if (budget > 0) {
|
|
105
|
+
// Walk recent from the front, dropping oldest first until the
|
|
106
|
+
// remaining tail fits. Use the AgentMessage→engine-text estimate via
|
|
107
|
+
// messageContentText (already imported) + estimateMessageTokens.
|
|
108
|
+
let tailTokens = 0;
|
|
109
|
+
for (let i = recentRaw.length - 1; i >= 0; i--) {
|
|
110
|
+
const m = recentRaw[i];
|
|
111
|
+
tailTokens += estimateMessageTokens({
|
|
112
|
+
text: messageContentText(m),
|
|
113
|
+
});
|
|
114
|
+
if (tailTokens > budget) {
|
|
115
|
+
// Keep from i+1 onward; but never fewer than the final message.
|
|
116
|
+
const startIdx = Math.min(i + 1, recentRaw.length - 1);
|
|
117
|
+
if (startIdx > 0) {
|
|
118
|
+
recent = recentRaw.slice(startIdx);
|
|
119
|
+
runtime.logger.warn("live-trim-tail-cap", {
|
|
120
|
+
sessionId: runtime.rt.sessionId,
|
|
121
|
+
dropped: startIdx,
|
|
122
|
+
tailTokens,
|
|
123
|
+
safetyMarginPct: modelThreshold.safetyMarginPct,
|
|
124
|
+
budget,
|
|
125
|
+
ctxWindow,
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
break;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
// v0.8.6: cache the trim view so subsequent gated calls in this epoch
|
|
134
|
+
// replay it verbatim (stabilizing the KV-cache prefix) instead of
|
|
135
|
+
// regenerating a fresh summary + sentinel every fire.
|
|
136
|
+
runtime.trimCache = {
|
|
137
|
+
// v0.8.7: key the replay cache on the STABLE epoch signal
|
|
138
|
+
// (rt.lastCheckpointId) instead of ran.result.checkpointId, which is
|
|
139
|
+
// dedup-volatile: on a re-compact that dedups onto a DIFFERENT existing
|
|
140
|
+
// checkpoint, result.checkpointId is the matched id (engine.ts:188) while
|
|
141
|
+
// lastCheckpointId is only updated on a genuinely new checkpoint
|
|
142
|
+
// (compact.ts:100-104). Keying on result.checkpointId would make
|
|
143
|
+
// trimCache.checkpointId != rt.lastCheckpointId forever after that
|
|
144
|
+
// dedup fire, disabling replay for the rest of the epoch (the
|
|
145
|
+
// alternating cache-miss that 0.8.6 meant to fix). Prefer the stable
|
|
146
|
+
// signal; fall back to result.checkpointId then the epoch timestamp
|
|
147
|
+
// only for the no-checkpoint edge case.
|
|
148
|
+
checkpointId: runtime.rt.lastCheckpointId ??
|
|
149
|
+
ran.result.checkpointId ??
|
|
150
|
+
`epoch-${runtime.rt.lastCompactAt ?? Date.now()}`,
|
|
151
|
+
cut,
|
|
152
|
+
summaryAgentMsg,
|
|
153
|
+
ctxPct: pct ?? null,
|
|
154
|
+
ctxTokens: currentTokens,
|
|
155
|
+
};
|
|
156
|
+
runtime.snapshot(ctx);
|
|
157
|
+
// DIAG (team-run relief): confirm the live trim actually fires + how big
|
|
158
|
+
// the window still is. The return is non-durable (per-LLM-call only), so
|
|
159
|
+
// this is the signal that the model is being fed a compacted view while
|
|
160
|
+
// the on-disk transcript + context meter keep growing.
|
|
161
|
+
runtime.diagLiveTrimFires++;
|
|
162
|
+
runtime.logger.info("live-trim", {
|
|
163
|
+
sessionId: runtime.rt.sessionId,
|
|
164
|
+
inputMsgs: messages.length,
|
|
165
|
+
outputMsgs: recent.length + 1,
|
|
166
|
+
compactedFrom: cut,
|
|
167
|
+
ctxPct: pct,
|
|
168
|
+
ctxTokens: usageTokens,
|
|
169
|
+
});
|
|
170
|
+
return (tailResult([summaryAgentMsg, ...recent]) ?? {
|
|
171
|
+
messages: [summaryAgentMsg, ...recent],
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
catch {
|
|
175
|
+
runtime.diagCtxThrown++;
|
|
176
|
+
return tailResult() ?? undefined; // non-fatal: no trim this call; the next context event retries
|
|
177
|
+
}
|
|
178
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { runCompact } from "../../mega-pipeline.js";
|
|
2
|
+
import { pressureFromPct, pressureRatio } from "../../mega-config.js";
|
|
3
|
+
/**
|
|
4
|
+
* Invoke the compaction pipeline with adaptive pressure. Returns a tailed view
|
|
5
|
+
* ("return") when compaction skipped, or "proceed" with the non-skipped result
|
|
6
|
+
* and the computed pressure (consumed by live-trim's critical-over hatch).
|
|
7
|
+
*/
|
|
8
|
+
export function invokePipeline(pi, runtime, config, ctx, opts) {
|
|
9
|
+
// Adaptive compression (Fix E): scale compression strength + keepFrom depth
|
|
10
|
+
// with how close we are to the model context limit. Null-safe: when the
|
|
11
|
+
// token-fallback path ran (pct unavailable) use the token-basis pressure
|
|
12
|
+
// (the same basis the runtime `pressure` getter uses for custom/no-window).
|
|
13
|
+
const pressure = opts.pct != null
|
|
14
|
+
? pressureFromPct(opts.pct)
|
|
15
|
+
: pressureRatio(opts.currentTokens, runtime.effectiveThreshold);
|
|
16
|
+
const ran = runCompact(pi, runtime, config, ctx, opts.messages, {
|
|
17
|
+
compressionPressure: pressure,
|
|
18
|
+
});
|
|
19
|
+
// D.3: skip paths fall back to replay instead of returning empty.
|
|
20
|
+
// If runCompact skipped and we have a valid trimCache, replay it
|
|
21
|
+
// (free stability win) — otherwise defer to the next event.
|
|
22
|
+
if (ran.skipped) {
|
|
23
|
+
runtime.diagCtxRunSkipped++;
|
|
24
|
+
if (runtime.trimCache &&
|
|
25
|
+
runtime.trimCache.checkpointId === runtime.rt.lastCheckpointId &&
|
|
26
|
+
runtime.trimCache.cut <= opts.messages.length) {
|
|
27
|
+
const recent = opts.messages.slice(runtime.trimCache.cut); // guardrails-allow PREVENT-PI-002: cached `cut` was sanitized by computeLiveTrimCut (src/boundary.ts); replayed verbatim, transcript only grows within an epoch.
|
|
28
|
+
runtime.diagLiveTrimFires++;
|
|
29
|
+
runtime.diagLiveTrimReplays++;
|
|
30
|
+
runtime.snapshot(ctx);
|
|
31
|
+
const skipView = [{ ...runtime.trimCache.summaryAgentMsg }, ...recent];
|
|
32
|
+
return { kind: "return", view: opts.tailResult(skipView) ?? { messages: skipView } };
|
|
33
|
+
}
|
|
34
|
+
return { kind: "return", view: opts.tailResult() ?? undefined };
|
|
35
|
+
}
|
|
36
|
+
return { kind: "proceed", ran, pressure };
|
|
37
|
+
}
|