pi-mega-compact 0.20.88 → 0.21.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.
@@ -134,6 +134,13 @@ export const SETTINGS = [
134
134
  num("MEGACOMPACT_THRASH_REARM_PCT", "Thrash Re-arm %", "After an ineffective compaction (live window did not shrink), refuse to re-fire until the live window grows by this fraction of the effective threshold. Default 0.10 (10%)", 0.1, 0.01, 0.5),
135
135
  ],
136
136
  },
137
+ {
138
+ name: "Three-Way Failback",
139
+ settings: [
140
+ boolDirect("MEGACOMPACT_THREE_WAY_FAILBACK", "Three-Way Failback", "Umbrella for the 3-way failback safety system: TriggerGuard (stages a recall block even when session_start never fires), the live-window ReductionValidator + persisted ThrashGuard (stops ineffective compaction re-fire loops), the 3-source read-only recall vote + same-repo relevance floor, and InjectionConfirm (asserts the staged block reached the message list pi sends). OFF = byte-identical pre-3WF behavior (v0.20.83). Runtime reads envBool(plain key), so this uses the plain-write convention (not _DISABLED).", true),
141
+ boolDirect("MEGACOMPACT_RECALL_TAIL_INJECT", "Recall Tail Inject", "Compose the staged recall block as a trailing user message on the context event (tail inject) instead of the legacy system-prompt prepend. Tail mode keeps the cache prefix stable and is the mode InjectionConfirm verifies against ContextEvent.messages; OFF falls back to the legacy prepend path (verified by string-contains). Runtime reads envBool(plain key), so this uses the plain-write convention (not _DISABLED).", true),
142
+ ],
143
+ },
137
144
  VECTOR_CORTEX_SETTINGS,
138
145
  {
139
146
  name: "Cost API",
@@ -48,8 +48,17 @@ export const ReductionValidator = {
48
48
  * Infinity/NaN into meta (getMetaNumber would read it back as 0). Skip arming
49
49
  * + log instead; the next over-threshold event simply re-fires (pre-sprint
50
50
  * behavior) rather than corrupting the guard.
51
+ *
52
+ * 3WF-5 telemetry: `logger` is the debug-gated runtime logger (mega-compact.log,
53
+ * silent unless config.debug) — which means the breadcrumb was invisible to the
54
+ * dashboard Events tab, whose SSE tail reads the repo's events.log. `emit` is
55
+ * the always-on events.log sink (MegaRuntime.appendEvent), so the armed
56
+ * breadcrumb lands in the same stream as the other 3WF events
57
+ * (three_way_guard_fired / three_way_floor_used / injection_confirmed /
58
+ * injection_recovered). Both sinks are optional + best-effort; passing neither
59
+ * keeps the pre-3WF-5 behavior.
51
60
  */
52
- export function armThrashGuard(currentTokens, rearmPct, effectiveThreshold, stateDir, logger) {
61
+ export function armThrashGuard(currentTokens, rearmPct, effectiveThreshold, stateDir, logger, emit) {
53
62
  if (!Number.isFinite(currentTokens) || currentTokens <= 0)
54
63
  return;
55
64
  if (!Number.isFinite(rearmPct) || rearmPct <= 0)
@@ -65,11 +74,18 @@ export function armThrashGuard(currentTokens, rearmPct, effectiveThreshold, stat
65
74
  const n = Math.round(rearmPct * effectiveThreshold);
66
75
  setMetaNumber(THRASH_BASELINE_KEY, Math.round(currentTokens), stateDir);
67
76
  setMetaNumber(THRASH_BLOCKED_KEY, Math.round(currentTokens + n), stateDir);
68
- logger?.info("thrasguard_armed", {
77
+ const fields = {
69
78
  baselineTokens: Math.round(currentTokens),
70
79
  blockedUntilTokens: Math.round(currentTokens + n),
71
80
  rearmTokens: n,
72
- });
81
+ };
82
+ logger?.info("thrasguard_armed", fields);
83
+ try {
84
+ emit?.("thrasguard_armed", fields);
85
+ }
86
+ catch {
87
+ /* non-fatal: events.log sink must never break arming */
88
+ }
73
89
  }
74
90
  catch {
75
91
  /* non-fatal: best-effort meta write */
@@ -177,7 +193,13 @@ export function evaluatePendingReduction(runtime, currentTokens, config) {
177
193
  // Remember which event armed us so the consult later in THIS SAME event
178
194
  // does not swallow it (see armedOnEvent).
179
195
  armedOnEvent.set(runtime, currentTokens);
180
- armThrashGuard(currentTokens, config.thrashRearmPct, runtime.effectiveThreshold, runtime.currentStateDir, runtime.logger);
196
+ // 3WF-5: also emit the breadcrumb on the always-on events.log sink so
197
+ // the dashboard Events tab sees it (runtime.logger is debug-gated).
198
+ // Optional-chained: a thin runtime stub without appendEvent stays valid.
199
+ const emit = typeof runtime.appendEvent === "function"
200
+ ? runtime.appendEvent.bind(runtime)
201
+ : undefined;
202
+ armThrashGuard(currentTokens, config.thrashRearmPct, runtime.effectiveThreshold, runtime.currentStateDir, runtime.logger, emit);
181
203
  }
182
204
  }
183
205
  catch {
@@ -0,0 +1,128 @@
1
+ /**
2
+ * context-handler/threeWayTelemetry.fixture.ts — shared fixtures for the 3WF-5
3
+ * telemetry verification tests.
4
+ *
5
+ * Split out so the test file stays under the soft cap, mirroring
6
+ * src/recall/recall3wf.fixture.ts (3WF-3) and injectionConfirm.fixture.ts (3WF-4).
7
+ *
8
+ * These are REAL fixtures, not mocks/stubs. The critical difference from the
9
+ * 3WF-1..4 fixtures: those record `appendEvent` calls into an in-memory array,
10
+ * which proves the CALL happened but says nothing about the wire format or the
11
+ * file the dashboard actually tails. Here `appendEvent` is wired to the REAL
12
+ * `appendEventImpl` (extensions/mega-runtime/append-event.ts) against a temp
13
+ * stateDir, so each breadcrumb is serialized to a real events.log exactly as it
14
+ * is in production. The tests then read that file back and parse the JSON — the
15
+ * `ts` + `event` shape is observed, never simulated.
16
+ */
17
+ import { mkdtempSync, readFileSync, existsSync } from "node:fs";
18
+ import { tmpdir } from "node:os";
19
+ import { join } from "node:path";
20
+ import { VectorStore } from "../../../src/vectorStore.js";
21
+ import { compactSession } from "../../../src/engine.js";
22
+ import { appendEventImpl } from "../../mega-runtime/append-event.js";
23
+ /** Real EngineMessage fixture. */
24
+ export function msg(role, text) {
25
+ return { role, text };
26
+ }
27
+ /** A user-role AgentMessage carrying `text` (the tail-block shape). */
28
+ export function userMsg(text) {
29
+ return { role: "user", content: text, timestamp: 1 };
30
+ }
31
+ /** Fresh isolated state dir per VectorStore. */
32
+ export function freshStore() {
33
+ const dir = mkdtempSync(join(tmpdir(), "mc-3wf5-"));
34
+ return { store: new VectorStore({ dedupSim: 0.9, stateDir: dir }), dir };
35
+ }
36
+ /** Persist N distinct checkpoints with ascending timestamps. */
37
+ export function seed(store, topics, sid) {
38
+ topics.forEach((t, i) => {
39
+ compactSession({
40
+ sessionId: sid,
41
+ messages: [msg("user", t), msg("assistant", "ok")],
42
+ keepFrom: 2,
43
+ timestamp: i + 1,
44
+ }, store);
45
+ });
46
+ }
47
+ /**
48
+ * Read + JSON-parse every line of the REAL events.log written under `stateDir`.
49
+ * PREVENT-001: parse failures are surfaced as null and filtered, never thrown.
50
+ */
51
+ export function readEventsLog(stateDir) {
52
+ const path = join(stateDir, "events.log");
53
+ if (!existsSync(path))
54
+ return [];
55
+ return readFileSync(path, "utf-8")
56
+ .split("\n")
57
+ .filter((l) => l.trim().length > 0)
58
+ .map((line) => {
59
+ try {
60
+ const parsed = JSON.parse(line);
61
+ if (parsed == null || typeof parsed !== "object")
62
+ return null;
63
+ return parsed;
64
+ }
65
+ catch {
66
+ return null;
67
+ }
68
+ })
69
+ .filter((e) => e != null);
70
+ }
71
+ /** Silent logger (the debug-gated sink is not under test here). */
72
+ export const noopLogger = {
73
+ info: () => { },
74
+ warn: () => { },
75
+ error: () => { },
76
+ };
77
+ /**
78
+ * MegaRuntime whose `appendEvent` is the REAL events.log writer bound to
79
+ * `stateDir`. Only the fields the 3WF guards touch are populated.
80
+ */
81
+ export function realEventRuntime(store, stateDir, over = {}) {
82
+ const self = {
83
+ store,
84
+ currentStateDir: stateDir,
85
+ pendingRecallBlock: over.pendingRecallBlock,
86
+ pendingMemoryRecallBlock: over.pendingMemoryRecallBlock,
87
+ effectiveThreshold: over.effectiveThreshold ?? 100_000,
88
+ lastCtxWindow: 0,
89
+ logger: noopLogger,
90
+ perfTurnStart: undefined,
91
+ rt: { recallInjectedThisTurn: false, lastCheckpointId: null },
92
+ appendEvent(event, fields) {
93
+ appendEventImpl({ currentStateDir: stateDir }, event, fields);
94
+ },
95
+ };
96
+ return self;
97
+ }
98
+ /** ctx stub with a configurable session id + latest-user query. */
99
+ export function ctxStub(opts = {}) {
100
+ const sessionId = opts.sessionId ?? "sess_3wf5";
101
+ const query = opts.query ?? "dedupe race in store";
102
+ return {
103
+ cwd: "/tmp",
104
+ sessionManager: {
105
+ getSessionId: () => sessionId,
106
+ getEntries: () => [
107
+ {
108
+ type: "message",
109
+ id: "e1",
110
+ parentId: null,
111
+ timestamp: "1",
112
+ message: { role: "user", content: query },
113
+ },
114
+ ],
115
+ },
116
+ };
117
+ }
118
+ /** Config stub: only the flags the 3WF guards read. */
119
+ export function configStub(over = {}) {
120
+ return {
121
+ threeWayFailback: over.threeWayFailback ?? true,
122
+ recallTailInject: over.recallTailInject ?? true,
123
+ thrashRearmPct: over.thrashRearmPct ?? 0.1,
124
+ autoInlineK: 3,
125
+ tier: "custom",
126
+ tierPct: null,
127
+ };
128
+ }
@@ -296,6 +296,23 @@ export const SETTINGS: ReadonlyArray<SettingGroup> = [
296
296
  ),
297
297
  ],
298
298
  },
299
+ {
300
+ name: "Three-Way Failback",
301
+ settings: [
302
+ boolDirect(
303
+ "MEGACOMPACT_THREE_WAY_FAILBACK",
304
+ "Three-Way Failback",
305
+ "Umbrella for the 3-way failback safety system: TriggerGuard (stages a recall block even when session_start never fires), the live-window ReductionValidator + persisted ThrashGuard (stops ineffective compaction re-fire loops), the 3-source read-only recall vote + same-repo relevance floor, and InjectionConfirm (asserts the staged block reached the message list pi sends). OFF = byte-identical pre-3WF behavior (v0.20.83). Runtime reads envBool(plain key), so this uses the plain-write convention (not _DISABLED).",
306
+ true,
307
+ ),
308
+ boolDirect(
309
+ "MEGACOMPACT_RECALL_TAIL_INJECT",
310
+ "Recall Tail Inject",
311
+ "Compose the staged recall block as a trailing user message on the context event (tail inject) instead of the legacy system-prompt prepend. Tail mode keeps the cache prefix stable and is the mode InjectionConfirm verifies against ContextEvent.messages; OFF falls back to the legacy prepend path (verified by string-contains). Runtime reads envBool(plain key), so this uses the plain-write convention (not _DISABLED).",
312
+ true,
313
+ ),
314
+ ],
315
+ },
299
316
  VECTOR_CORTEX_SETTINGS,
300
317
  {
301
318
  name: "Cost API",
@@ -75,6 +75,15 @@ export const ReductionValidator = {
75
75
  * Infinity/NaN into meta (getMetaNumber would read it back as 0). Skip arming
76
76
  * + log instead; the next over-threshold event simply re-fires (pre-sprint
77
77
  * behavior) rather than corrupting the guard.
78
+ *
79
+ * 3WF-5 telemetry: `logger` is the debug-gated runtime logger (mega-compact.log,
80
+ * silent unless config.debug) — which means the breadcrumb was invisible to the
81
+ * dashboard Events tab, whose SSE tail reads the repo's events.log. `emit` is
82
+ * the always-on events.log sink (MegaRuntime.appendEvent), so the armed
83
+ * breadcrumb lands in the same stream as the other 3WF events
84
+ * (three_way_guard_fired / three_way_floor_used / injection_confirmed /
85
+ * injection_recovered). Both sinks are optional + best-effort; passing neither
86
+ * keeps the pre-3WF-5 behavior.
78
87
  */
79
88
  export function armThrashGuard(
80
89
  currentTokens: number,
@@ -82,6 +91,7 @@ export function armThrashGuard(
82
91
  effectiveThreshold: number,
83
92
  stateDir: string,
84
93
  logger?: { info(event: string, fields?: Record<string, unknown>): void },
94
+ emit?: (event: string, fields: Record<string, unknown>) => void,
85
95
  ): void {
86
96
  if (!Number.isFinite(currentTokens) || currentTokens <= 0) return;
87
97
  if (!Number.isFinite(rearmPct) || rearmPct <= 0) return;
@@ -96,11 +106,17 @@ export function armThrashGuard(
96
106
  const n = Math.round(rearmPct * effectiveThreshold);
97
107
  setMetaNumber(THRASH_BASELINE_KEY, Math.round(currentTokens), stateDir);
98
108
  setMetaNumber(THRASH_BLOCKED_KEY, Math.round(currentTokens + n), stateDir);
99
- logger?.info("thrasguard_armed", {
109
+ const fields = {
100
110
  baselineTokens: Math.round(currentTokens),
101
111
  blockedUntilTokens: Math.round(currentTokens + n),
102
112
  rearmTokens: n,
103
- });
113
+ };
114
+ logger?.info("thrasguard_armed", fields);
115
+ try {
116
+ emit?.("thrasguard_armed", fields);
117
+ } catch {
118
+ /* non-fatal: events.log sink must never break arming */
119
+ }
104
120
  } catch {
105
121
  /* non-fatal: best-effort meta write */
106
122
  }
@@ -214,12 +230,20 @@ export function evaluatePendingReduction(
214
230
  // Remember which event armed us so the consult later in THIS SAME event
215
231
  // does not swallow it (see armedOnEvent).
216
232
  armedOnEvent.set(runtime, currentTokens);
233
+ // 3WF-5: also emit the breadcrumb on the always-on events.log sink so
234
+ // the dashboard Events tab sees it (runtime.logger is debug-gated).
235
+ // Optional-chained: a thin runtime stub without appendEvent stays valid.
236
+ const emit =
237
+ typeof runtime.appendEvent === "function"
238
+ ? runtime.appendEvent.bind(runtime)
239
+ : undefined;
217
240
  armThrashGuard(
218
241
  currentTokens,
219
242
  config.thrashRearmPct,
220
243
  runtime.effectiveThreshold,
221
244
  runtime.currentStateDir,
222
245
  runtime.logger,
246
+ emit,
223
247
  );
224
248
  }
225
249
  } catch {
@@ -0,0 +1,164 @@
1
+ /**
2
+ * context-handler/threeWayTelemetry.fixture.ts — shared fixtures for the 3WF-5
3
+ * telemetry verification tests.
4
+ *
5
+ * Split out so the test file stays under the soft cap, mirroring
6
+ * src/recall/recall3wf.fixture.ts (3WF-3) and injectionConfirm.fixture.ts (3WF-4).
7
+ *
8
+ * These are REAL fixtures, not mocks/stubs. The critical difference from the
9
+ * 3WF-1..4 fixtures: those record `appendEvent` calls into an in-memory array,
10
+ * which proves the CALL happened but says nothing about the wire format or the
11
+ * file the dashboard actually tails. Here `appendEvent` is wired to the REAL
12
+ * `appendEventImpl` (extensions/mega-runtime/append-event.ts) against a temp
13
+ * stateDir, so each breadcrumb is serialized to a real events.log exactly as it
14
+ * is in production. The tests then read that file back and parse the JSON — the
15
+ * `ts` + `event` shape is observed, never simulated.
16
+ */
17
+ import { mkdtempSync, readFileSync, existsSync } from "node:fs";
18
+ import { tmpdir } from "node:os";
19
+ import { join } from "node:path";
20
+
21
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
22
+ import { VectorStore } from "../../../src/vectorStore.js";
23
+ import { compactSession } from "../../../src/engine.js";
24
+ import { appendEventImpl } from "../../mega-runtime/append-event.js";
25
+ import type { MegaRuntime } from "../../mega-runtime.js";
26
+ import type { MegaConfig } from "../../mega-config.js";
27
+ import type { Logger } from "../../../src/log.js";
28
+
29
+ /** Real EngineMessage fixture. */
30
+ export function msg(role: "user" | "assistant", text: string): any {
31
+ return { role, text };
32
+ }
33
+
34
+ /** A user-role AgentMessage carrying `text` (the tail-block shape). */
35
+ export function userMsg(text: string): AgentMessage {
36
+ return { role: "user", content: text, timestamp: 1 } as unknown as AgentMessage;
37
+ }
38
+
39
+ /** One parsed events.log line. `ts` + `event` are the contract the dashboard
40
+ * Events tab (server.ts SSE tail of stateDir/events.log) consumes. */
41
+ export interface LoggedEvent {
42
+ ts: unknown;
43
+ event: unknown;
44
+ [k: string]: unknown;
45
+ }
46
+
47
+ /** Fresh isolated state dir per VectorStore. */
48
+ export function freshStore(): { store: VectorStore; dir: string } {
49
+ const dir = mkdtempSync(join(tmpdir(), "mc-3wf5-"));
50
+ return { store: new VectorStore({ dedupSim: 0.9, stateDir: dir }), dir };
51
+ }
52
+
53
+ /** Persist N distinct checkpoints with ascending timestamps. */
54
+ export function seed(store: VectorStore, topics: string[], sid: string): void {
55
+ topics.forEach((t, i) => {
56
+ compactSession(
57
+ {
58
+ sessionId: sid,
59
+ messages: [msg("user", t), msg("assistant", "ok")],
60
+ keepFrom: 2,
61
+ timestamp: i + 1,
62
+ },
63
+ store,
64
+ );
65
+ });
66
+ }
67
+
68
+ /**
69
+ * Read + JSON-parse every line of the REAL events.log written under `stateDir`.
70
+ * PREVENT-001: parse failures are surfaced as null and filtered, never thrown.
71
+ */
72
+ export function readEventsLog(stateDir: string): LoggedEvent[] {
73
+ const path = join(stateDir, "events.log");
74
+ if (!existsSync(path)) return [];
75
+ return readFileSync(path, "utf-8")
76
+ .split("\n")
77
+ .filter((l) => l.trim().length > 0)
78
+ .map((line): LoggedEvent | null => {
79
+ try {
80
+ const parsed: unknown = JSON.parse(line);
81
+ if (parsed == null || typeof parsed !== "object") return null;
82
+ return parsed as LoggedEvent;
83
+ } catch {
84
+ return null;
85
+ }
86
+ })
87
+ .filter((e): e is LoggedEvent => e != null);
88
+ }
89
+
90
+ /** Silent logger (the debug-gated sink is not under test here). */
91
+ export const noopLogger: Logger = {
92
+ info: () => {},
93
+ warn: () => {},
94
+ error: () => {},
95
+ } as unknown as Logger;
96
+
97
+ /**
98
+ * MegaRuntime whose `appendEvent` is the REAL events.log writer bound to
99
+ * `stateDir`. Only the fields the 3WF guards touch are populated.
100
+ */
101
+ export function realEventRuntime(
102
+ store: VectorStore,
103
+ stateDir: string,
104
+ over: Partial<{
105
+ pendingRecallBlock: string | undefined;
106
+ pendingMemoryRecallBlock: string | undefined;
107
+ effectiveThreshold: number;
108
+ }> = {},
109
+ ): MegaRuntime {
110
+ const self = {
111
+ store,
112
+ currentStateDir: stateDir,
113
+ pendingRecallBlock: over.pendingRecallBlock,
114
+ pendingMemoryRecallBlock: over.pendingMemoryRecallBlock,
115
+ effectiveThreshold: over.effectiveThreshold ?? 100_000,
116
+ lastCtxWindow: 0,
117
+ logger: noopLogger,
118
+ perfTurnStart: undefined,
119
+ rt: { recallInjectedThisTurn: false, lastCheckpointId: null as string | null },
120
+ appendEvent(event: string, fields: Record<string, unknown>): void {
121
+ appendEventImpl({ currentStateDir: stateDir }, event, fields);
122
+ },
123
+ };
124
+ return self as unknown as MegaRuntime;
125
+ }
126
+
127
+ /** ctx stub with a configurable session id + latest-user query. */
128
+ export function ctxStub(opts: { sessionId?: string; query?: string } = {}): any {
129
+ const sessionId = opts.sessionId ?? "sess_3wf5";
130
+ const query = opts.query ?? "dedupe race in store";
131
+ return {
132
+ cwd: "/tmp",
133
+ sessionManager: {
134
+ getSessionId: () => sessionId,
135
+ getEntries: () => [
136
+ {
137
+ type: "message",
138
+ id: "e1",
139
+ parentId: null,
140
+ timestamp: "1",
141
+ message: { role: "user", content: query },
142
+ },
143
+ ],
144
+ },
145
+ };
146
+ }
147
+
148
+ /** Config stub: only the flags the 3WF guards read. */
149
+ export function configStub(
150
+ over: Partial<{
151
+ threeWayFailback: boolean;
152
+ recallTailInject: boolean;
153
+ thrashRearmPct: number;
154
+ }> = {},
155
+ ): MegaConfig {
156
+ return {
157
+ threeWayFailback: over.threeWayFailback ?? true,
158
+ recallTailInject: over.recallTailInject ?? true,
159
+ thrashRearmPct: over.thrashRearmPct ?? 0.1,
160
+ autoInlineK: 3,
161
+ tier: "custom",
162
+ tierPct: null,
163
+ } as unknown as MegaConfig;
164
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-mega-compact",
3
- "version": "0.20.88",
3
+ "version": "0.21.0",
4
4
  "description": "Layered, local, vector-backed context compressor for pi — supersede/collapse/cluster compaction with deduped inline recall.",
5
5
  "type": "module",
6
6
  "license": "BSD-3-Clause",