pi-mega-compact 0.17.1 → 0.18.1
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 +19 -0
- package/dist/config.js +117 -0
- package/dist/extensions/dashboard-server/routes-rag-settings-helpers.js +4 -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/log.js +47 -0
- package/dist/src/config/vector-cortex.js +19 -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-vc2b.js +63 -0
- package/dist/src/vector-cortex/encoder/emit.js +42 -0
- package/dist/src/vector-cortex/encoder/heads.js +113 -0
- package/dist/src/vector-cortex/encoder/lexical.js +104 -0
- package/dist/src/vector-cortex/encoder/router.js +115 -0
- package/dist/src/vector-cortex/encoder/runtime.js +228 -0
- package/dist/src/vector-cortex/encoder/trigram.js +75 -0
- package/dist/src/vector-cortex/encoder/types.js +138 -0
- package/dist/vector-cortex/encoder/asset.js +142 -0
- package/dist/vector-cortex/encoder/emit-vc2b.js +63 -0
- package/dist/vector-cortex/encoder/emit.js +42 -0
- package/dist/vector-cortex/encoder/heads.js +113 -0
- package/dist/vector-cortex/encoder/lexical.js +104 -0
- package/dist/vector-cortex/encoder/router.js +115 -0
- package/dist/vector-cortex/encoder/runtime.js +228 -0
- package/dist/vector-cortex/encoder/trigram.js +75 -0
- package/dist/vector-cortex/encoder/types.js +138 -0
- package/extensions/dashboard-server/routes-rag-settings-helpers.ts +14 -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 +21 -0
- package/src/config.ts +2 -0
- package/src/vector-cortex/encoder/asset.ts +155 -0
- package/src/vector-cortex/encoder/emit-vc2b.ts +82 -0
- package/src/vector-cortex/encoder/emit.ts +51 -0
- package/src/vector-cortex/encoder/heads.ts +142 -0
- package/src/vector-cortex/encoder/lexical.ts +123 -0
- package/src/vector-cortex/encoder/router.ts +163 -0
- package/src/vector-cortex/encoder/runtime.ts +283 -0
- package/src/vector-cortex/encoder/trigram.ts +85 -0
- package/src/vector-cortex/encoder/types.ts +275 -0
|
@@ -63,6 +63,25 @@ 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");
|
|
76
|
+
/**
|
|
77
|
+
* VC2B — multi-head encoder (VectorSetV1 / HeadCalibrationDraft).
|
|
78
|
+
* Default ON. `MEGACOMPACT_VC2B=0` disables and is byte-identical to the
|
|
79
|
+
* predecessor (the encoder emits no per-head vectors and no fallback-selected
|
|
80
|
+
* event; the trigram/lexical paths themselves are unchanged and are the
|
|
81
|
+
* predecessor's mode-B/C producers). The real consumers are the encoder-heads
|
|
82
|
+
* emit seam and the multi-head encoder producers (heads/trigram/lexical).
|
|
83
|
+
*/
|
|
84
|
+
export const VC2B_ENABLED = () => sprintFlag("MEGACOMPACT_VC2B");
|
|
66
85
|
// ---------------------------------------------------------------------------
|
|
67
86
|
// Breaker state machine constants (TRIAD_RESILIENCE.md §breaker).
|
|
68
87
|
// Rolled numbers for one 60s window; VC0C consumes these at its breaker seam.
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* config.ts — shared default paths/constants for the mega-compact engine.
|
|
3
|
+
*
|
|
4
|
+
* Kept tiny and dependency-free so both the extension entry and unit tests can
|
|
5
|
+
* import it without pulling in pi runtime types.
|
|
6
|
+
*/
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { homedir } from "node:os";
|
|
9
|
+
/** Default on-disk location for checkpoints + session state. */
|
|
10
|
+
export const STATE_DIR_DEFAULT = join(homedir(), ".pi", "agent", "extensions", "pi-mega-compact");
|
|
11
|
+
/** Pi custom message / entry type used as the dedup sentinel. */
|
|
12
|
+
export const MARKER_TYPE = "mega-compact-marker";
|
|
13
|
+
/**
|
|
14
|
+
* Derive context-window pressure (0–1) from a usage percentage. Used to scale
|
|
15
|
+
* compression strength + keepFrom depth (Fix E): low pct = room to spare,
|
|
16
|
+
* high pct = near the limit. Deterministic; clamps to [0,1].
|
|
17
|
+
*/
|
|
18
|
+
export function pressureFromPct(pct) {
|
|
19
|
+
if (pct == null || Number.isNaN(pct))
|
|
20
|
+
return 0;
|
|
21
|
+
return pct < 0 ? 0 : pct > 100 ? 1 : pct / 100;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Map pressure → how many recent messages to preserve verbatim. Under low
|
|
25
|
+
* pressure we keep `preserveRecent`; under high pressure we compact deeper,
|
|
26
|
+
* down to `preserveRecentMin`. Never splits a tool pair / anchor floor — the
|
|
27
|
+
* boundary guard (computeDropRange) enforces that downstream.
|
|
28
|
+
*/
|
|
29
|
+
export function preserveRecentForPressure(pressure, preserveRecent, preserveRecentMin) {
|
|
30
|
+
const p = pressure < 0 ? 0 : pressure > 1 ? 1 : pressure;
|
|
31
|
+
const v = Math.round(preserveRecent - (preserveRecent - preserveRecentMin) * p);
|
|
32
|
+
// Floor of 1: even with preserveRecentMin=0 at full pressure, never compact
|
|
33
|
+
// ALL messages — the boundary guard (computeDropRange) needs ≥1 to anchor on.
|
|
34
|
+
return Math.max(1, preserveRecentMin, Math.min(preserveRecent, v));
|
|
35
|
+
}
|
|
36
|
+
/** Clamp a pressure ratio into [0, 1]. */
|
|
37
|
+
function clamp01(p) {
|
|
38
|
+
if (!Number.isFinite(p))
|
|
39
|
+
return 0;
|
|
40
|
+
return p < 0 ? 0 : p > 1 ? 1 : p;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Pressure as a 0–1 ratio from live token usage relative to the compaction
|
|
44
|
+
* threshold. Cheaper + more direct than deriving from a usage percentage when
|
|
45
|
+
* we already have both numbers (the context handler does). Re-exports
|
|
46
|
+
* `pressureFromPct` covers the percentage-only path. (S24.)
|
|
47
|
+
*/
|
|
48
|
+
export function pressureRatio(currentTokens, thresholdTokens) {
|
|
49
|
+
if (!Number.isFinite(currentTokens) || currentTokens <= 0)
|
|
50
|
+
return 0;
|
|
51
|
+
const t = Number.isFinite(thresholdTokens) && thresholdTokens > 0 ? thresholdTokens : 0;
|
|
52
|
+
return clamp01(t > 0 ? currentTokens / t : 0);
|
|
53
|
+
}
|
|
54
|
+
/** Map a 0–1 pressure ratio to a discrete band. (S24.) */
|
|
55
|
+
export function pressureBand(pressure) {
|
|
56
|
+
const p = clamp01(pressure);
|
|
57
|
+
if (p >= 1.0)
|
|
58
|
+
return "mega";
|
|
59
|
+
if (p >= 0.9)
|
|
60
|
+
return "ultra";
|
|
61
|
+
if (p >= 0.75)
|
|
62
|
+
return "high";
|
|
63
|
+
if (p >= 0.5)
|
|
64
|
+
return "medium";
|
|
65
|
+
return "low";
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Memory auto-review cadence (in turns) for a given pressure band. As pressure
|
|
69
|
+
* climbs, the conversation is reviewed more often so durable memories keep pace
|
|
70
|
+
* with the faster context churn. Returns a divisor used as
|
|
71
|
+
* `turn % cadence === 0`. Always >= 1. (S24 — memory cadence tie-in.)
|
|
72
|
+
*/
|
|
73
|
+
export function memoryReviewCadence(band, baseInterval) {
|
|
74
|
+
const base = baseInterval >= 1 ? baseInterval : 1;
|
|
75
|
+
switch (band) {
|
|
76
|
+
case "mega": return Math.max(1, Math.round(base / 5));
|
|
77
|
+
case "ultra": return Math.max(1, Math.round(base / 3));
|
|
78
|
+
case "high": return Math.max(1, Math.round(base / 2));
|
|
79
|
+
case "medium": return Math.max(1, Math.round((base * 2) / 3));
|
|
80
|
+
case "low":
|
|
81
|
+
default: return base;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
// ---------------------------------------------------------------------------
|
|
85
|
+
// S57 RAG Suite feature flags — all default ON with graceful fallback; opt OUT
|
|
86
|
+
// via MEGACOMPACT_<NAME>_DISABLED=true. Every feature degrades to existing
|
|
87
|
+
// behavior on error (non-fatal, best-effort).
|
|
88
|
+
// ---------------------------------------------------------------------------
|
|
89
|
+
function ragFlag(name) {
|
|
90
|
+
const v = process.env[name];
|
|
91
|
+
if (v === undefined)
|
|
92
|
+
return false;
|
|
93
|
+
return v === "true" || v === "1";
|
|
94
|
+
}
|
|
95
|
+
function ragEnabled(name) {
|
|
96
|
+
return !ragFlag(name + "_DISABLED");
|
|
97
|
+
}
|
|
98
|
+
/** B1: Query reformulation (keyword expansion via embedding neighbors). */
|
|
99
|
+
export const RAG_QUERY_REFORMULATION = () => ragEnabled("MEGACOMPACT_QUERY_REFORMULATION");
|
|
100
|
+
/** B2: Tiered recall router (L0 cache → L1 FTS5 → L2 HNSW). */
|
|
101
|
+
export const RAG_TIERED_ROUTER = () => ragEnabled("MEGACOMPACT_TIERED_ROUTER");
|
|
102
|
+
/** B3: Recall quality metrics (precision/recall scoring + logging). */
|
|
103
|
+
export const RAG_RECALL_METRICS = () => ragEnabled("MEGACOMPACT_RECALL_METRICS");
|
|
104
|
+
/** B4: Memory graph traversal (dashboard-oriented). */
|
|
105
|
+
export const RAG_MEMORY_GRAPH = () => ragEnabled("MEGACOMPACT_MEMORY_GRAPH");
|
|
106
|
+
/** B5: HyDE — generate a hypothetical answer doc via LLM. Auto-ON when an
|
|
107
|
+
* HttpEmbedder is active (the LLM is configured for indexing); opt OUT with
|
|
108
|
+
* MEGACOMPACT_HYDE_DISABLED=true. TrigramEmbedder path is unaffected. */
|
|
109
|
+
export const RAG_HYDE_ENABLED = () => ragEnabled("MEGACOMPACT_HYDE");
|
|
110
|
+
/** Spec 1: vbrainstorm visual design migration for the dashboard. */
|
|
111
|
+
export const NEW_UI = () => ragEnabled("MEGACOMPACT_NEW_UI");
|
|
112
|
+
// ---------------------------------------------------------------------------
|
|
113
|
+
// Vector-cortex flags + breaker constants (VC0A+). Positive sprint flags,
|
|
114
|
+
// default ON, `=0`/`_DISABLED` off. Re-exported from src/config/vector-cortex.ts
|
|
115
|
+
// so root consumers share one source of truth.
|
|
116
|
+
// ---------------------------------------------------------------------------
|
|
117
|
+
export { VC0A_ENABLED, VC0B_ENABLED, VC1A_ENABLED, VC0C_ENABLED, VC1B_ENABLED, VC1C_ENABLED, VC2A_ENABLED, VC2B_ENABLED, BREAKER_WINDOW_MS, BREAKER_MIN_ATTEMPTS, BREAKER_PERF_FAILURES, BREAKER_PERF_FAILURE_RATE, BREAKER_CORRECTNESS_FAILURES, BREAKER_COOLDOWN_MS, BREAKER_PROBE_COUNT, BREAKER_RETRY_BASE_MS, BREAKER_RETRY_CAP_MS, BREAKER_RETRY_JITTER, BREAKER_HYSTERESIS_FAILURE_RATE, BREAKER_HYSTERESIS_BUDGET_P95_MS, BREAKER_MIN_HEALTHY_RESIDENCE_MS, } from "./config/vector-cortex.js";
|
|
@@ -127,6 +127,8 @@ export const SETTINGS = [
|
|
|
127
127
|
str("MEGACOMPACT_RAPTOR_MODEL", "RAPTOR Summary Model", "Ollama model for cluster summarization (empty = extractive)", ""),
|
|
128
128
|
str("MEGACOMPACT_RAPTOR_URL", "RAPTOR Ollama URL", "Ollama endpoint for RAPTOR summarization", "http://127.0.0.1:11434"),
|
|
129
129
|
num("MEGACOMPACT_EMBED_CACHE", "Embed Cache Size", "Embedding cache entries (0 = disabled)", 256, 0, 10000),
|
|
130
|
+
num("MEGACOMPACT_EMBEDDING_BATCH_TOKENS", "Embedding Batch Tokens", "Oversized-prompt chunking limit (tokens) for the BYO localhost embedder; text above this is chunked + mean-pooled", 2048, 64, 8192),
|
|
131
|
+
num("MEGACOMPACT_EMBEDDING_CHARS_PER_TOKEN", "Embedding Chars per Token", "Estimated characters per token used for embedder chunking size", 4, 1, 32),
|
|
130
132
|
],
|
|
131
133
|
},
|
|
132
134
|
{
|
|
@@ -138,6 +140,8 @@ export const SETTINGS = [
|
|
|
138
140
|
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
141
|
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
142
|
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),
|
|
143
|
+
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),
|
|
144
|
+
boolDirect("MEGACOMPACT_VC2B", "VC2B Multi-Head Encoder", "VectorSetV1 five L2-normalized heads (384/128/128/64/32) with head-calibration draft + asset-free trigram B (512d) and lexical C fallbacks, plus the per-head emit seam. OFF = mode C, no per-head vectors emitted, byte-identical predecessor.", true),
|
|
141
145
|
],
|
|
142
146
|
},
|
|
143
147
|
{
|
|
@@ -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
|
+
}
|