pi-mega-compact 0.8.23 → 0.8.25

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 (157) hide show
  1. package/README.md +26 -0
  2. package/dist/extensions/dashboard-server/api-contracts/endpoints.js +8 -0
  3. package/dist/extensions/dashboard-server/api-contracts/game-types.js +7 -0
  4. package/dist/extensions/mega-compact-s38.test.js +263 -14
  5. package/dist/extensions/mega-compact.js +15 -0
  6. package/dist/extensions/mega-config.js +3 -0
  7. package/dist/extensions/mega-events/agent-handlers.js +211 -26
  8. package/dist/extensions/mega-events/context-handler.js +45 -7
  9. package/dist/extensions/mega-events/error-classifier.js +125 -18
  10. package/dist/extensions/mega-pipeline/compact.js +24 -13
  11. package/dist/extensions/mega-pipeline/recall.js +31 -2
  12. package/dist/extensions/mega-runtime/append-event.js +24 -0
  13. package/dist/extensions/mega-runtime/bind-repo.js +65 -0
  14. package/dist/extensions/mega-runtime/capture-model.js +87 -0
  15. package/dist/extensions/mega-runtime/dashboard-snapshot.js +122 -0
  16. package/dist/extensions/mega-runtime/effects.js +86 -0
  17. package/dist/extensions/mega-runtime/engine-view.js +11 -0
  18. package/dist/extensions/mega-runtime/game-state.js +116 -0
  19. package/dist/extensions/mega-runtime/get-state-dir.js +10 -0
  20. package/dist/extensions/mega-runtime/perf.js +49 -0
  21. package/dist/extensions/mega-runtime/pressure-getters.js +64 -0
  22. package/dist/extensions/mega-runtime/render-widget.js +17 -0
  23. package/dist/extensions/mega-runtime/reset-runtime.js +50 -0
  24. package/dist/extensions/mega-runtime/runtime-helpers.js +73 -0
  25. package/dist/extensions/mega-runtime/runtime-snapshot.js +208 -0
  26. package/dist/extensions/mega-runtime/runtime.js +405 -0
  27. package/dist/extensions/mega-runtime/snapshot.js +142 -0
  28. package/dist/extensions/mega-runtime/state.js +5 -1151
  29. package/dist/extensions/mega-runtime/status.js +11 -0
  30. package/dist/extensions/mega-runtime/widget-ansi.js +207 -0
  31. package/dist/extensions/mega-runtime/widget-types.js +8 -0
  32. package/dist/extensions/mega-runtime/widget.js +15 -204
  33. package/dist/extensions/openclaw-mega-compact.js +291 -0
  34. package/dist/src/boundary.js +79 -43
  35. package/dist/src/boundary.test.js +119 -2
  36. package/dist/src/canary.js +10 -0
  37. package/dist/src/config/dedup.js +14 -0
  38. package/dist/src/config.js +3 -1
  39. package/dist/src/dedup/raptor/buildHistory.js +164 -0
  40. package/dist/src/dedup/raptor/buildHistory.test.js +292 -0
  41. package/dist/src/dedup/raptor/index.js +38 -0
  42. package/dist/src/dedup/raptor/multilevel-serve.test.js +229 -0
  43. package/dist/src/dedup/raptor/multilevel.js +17 -5
  44. package/dist/src/dedup/raptor/multilevel.test.js +36 -1
  45. package/dist/src/dedup/raptor/raptor.test.js +43 -0
  46. package/dist/src/dedup/raptor/retrieval.js +14 -2
  47. package/dist/src/dedup/raptor/retrieval.test.js +95 -0
  48. package/dist/src/dedup/raptor/serve-gate.test.js +298 -0
  49. package/dist/src/dedup/raptor/summarizer.js +1 -0
  50. package/dist/src/dedup/raptor/tree.js +16 -2
  51. package/dist/src/engine.js +18 -2
  52. package/dist/src/httpEmbedder.js +96 -6
  53. package/dist/src/httpEmbedder.test.js +277 -0
  54. package/dist/src/mechanical-fix.test.js +65 -0
  55. package/dist/src/minilm.js +92 -0
  56. package/dist/src/raptor-inject-summaries.test.js +155 -0
  57. package/dist/src/recall.js +135 -21
  58. package/dist/src/recall.test.js +179 -4
  59. package/dist/src/store/sqlite/dedup-mirror.js +32 -15
  60. package/dist/src/store/sqlite/maintenance.js +2 -2
  61. package/dist/src/store/sqlite/mechanical-fix.test.js +146 -0
  62. package/dist/src/store/sqlite/memories.js +5 -5
  63. package/dist/src/store/sqlite/meta.js +1 -1
  64. package/dist/src/store/sqlite/raptor.js +56 -17
  65. package/dist/src/store/sqlite/raptor.test.js +106 -0
  66. package/dist/src/store/sqlite/schema.js +90 -1
  67. package/dist/src/store/sqlite/session-state.js +9 -3
  68. package/dist/src/store/sqlite/stats.js +9 -5
  69. package/dist/src/store/sqlite/turns.js +181 -0
  70. package/dist/src/store/sqlite/turns.test.js +183 -0
  71. package/dist/src/store/sqlite/utils.js +15 -4
  72. package/dist/src/store/sqlite.js +1 -0
  73. package/dist/src/store.js +2 -2
  74. package/dist/src/vector-search-cache.test.js +157 -0
  75. package/dist/src/vector-search.js +107 -15
  76. package/dist/src/vectorStore.js +36 -8
  77. package/dist/src/wordpiece.js +129 -0
  78. package/extensions/dashboard-client/dist/assets/index-D_WtU2TV.js.map +1 -1
  79. package/extensions/dashboard-server/api-contracts/endpoints.ts +30 -155
  80. package/extensions/dashboard-server/api-contracts/game-types.ts +172 -0
  81. package/extensions/mega-compact-s38.test.ts +259 -14
  82. package/extensions/mega-compact.ts +15 -0
  83. package/extensions/mega-config.ts +18 -0
  84. package/extensions/mega-dashboard.ts +10 -1
  85. package/extensions/mega-events/agent-handlers.ts +211 -26
  86. package/extensions/mega-events/context-handler.ts +43 -7
  87. package/extensions/mega-events/error-classifier.ts +125 -17
  88. package/extensions/mega-pipeline/compact.ts +28 -16
  89. package/extensions/mega-pipeline/recall.ts +34 -2
  90. package/extensions/mega-runtime/DECOMPOSITION.md +180 -0
  91. package/extensions/mega-runtime/README.md +38 -0
  92. package/extensions/mega-runtime/append-event.ts +40 -0
  93. package/extensions/mega-runtime/bind-repo.ts +81 -0
  94. package/extensions/mega-runtime/capture-model.ts +101 -0
  95. package/extensions/mega-runtime/dashboard-snapshot.ts +181 -0
  96. package/extensions/mega-runtime/effects.ts +129 -0
  97. package/extensions/mega-runtime/engine-view.ts +17 -0
  98. package/extensions/mega-runtime/game-state.ts +149 -0
  99. package/extensions/mega-runtime/get-state-dir.ts +19 -0
  100. package/extensions/mega-runtime/helpers.ts +25 -1
  101. package/extensions/mega-runtime/perf.ts +60 -0
  102. package/extensions/mega-runtime/pressure-getters.ts +96 -0
  103. package/extensions/mega-runtime/render-widget.ts +41 -0
  104. package/extensions/mega-runtime/runtime-helpers.ts +119 -0
  105. package/extensions/mega-runtime/runtime-snapshot.ts +293 -0
  106. package/extensions/mega-runtime/runtime.ts +483 -0
  107. package/extensions/mega-runtime/snapshot.ts +230 -0
  108. package/extensions/mega-runtime/state.ts +5 -1268
  109. package/extensions/mega-runtime/status.ts +26 -0
  110. package/extensions/mega-runtime/widget-ansi.ts +217 -0
  111. package/extensions/mega-runtime/widget-types.ts +80 -0
  112. package/extensions/mega-runtime/widget.ts +34 -285
  113. package/package.json +1 -1
  114. package/src/boundary.test.ts +128 -2
  115. package/src/boundary.ts +75 -39
  116. package/src/canary.ts +10 -0
  117. package/src/config/dedup.ts +25 -0
  118. package/src/config.ts +3 -1
  119. package/src/dedup/raptor/buildHistory.test.ts +353 -0
  120. package/src/dedup/raptor/buildHistory.ts +259 -0
  121. package/src/dedup/raptor/index.ts +38 -0
  122. package/src/dedup/raptor/multilevel-serve.test.ts +273 -0
  123. package/src/dedup/raptor/multilevel.test.ts +47 -0
  124. package/src/dedup/raptor/multilevel.ts +18 -8
  125. package/src/dedup/raptor/raptor.test.ts +59 -0
  126. package/src/dedup/raptor/retrieval.test.ts +118 -0
  127. package/src/dedup/raptor/retrieval.ts +14 -2
  128. package/src/dedup/raptor/serve-gate.test.ts +348 -0
  129. package/src/dedup/raptor/summarizer.ts +1 -0
  130. package/src/dedup/raptor/tree.ts +17 -2
  131. package/src/engine.ts +32 -3
  132. package/src/httpEmbedder.test.ts +286 -0
  133. package/src/httpEmbedder.ts +98 -8
  134. package/src/mechanical-fix.test.ts +70 -0
  135. package/src/raptor-inject-summaries.test.ts +212 -0
  136. package/src/recall.test.ts +220 -4
  137. package/src/recall.ts +151 -22
  138. package/src/store/sqlite/dedup-mirror.ts +35 -18
  139. package/src/store/sqlite/maintenance.ts +2 -2
  140. package/src/store/sqlite/mechanical-fix.test.ts +162 -0
  141. package/src/store/sqlite/memories.ts +5 -5
  142. package/src/store/sqlite/meta.ts +1 -1
  143. package/src/store/sqlite/raptor.test.ts +139 -0
  144. package/src/store/sqlite/raptor.ts +135 -81
  145. package/src/store/sqlite/schema.ts +90 -1
  146. package/src/store/sqlite/session-state.ts +9 -3
  147. package/src/store/sqlite/stats.ts +10 -8
  148. package/src/store/sqlite/turns.test.ts +218 -0
  149. package/src/store/sqlite/turns.ts +292 -0
  150. package/src/store/sqlite/utils.ts +14 -4
  151. package/src/store/sqlite.ts +1 -0
  152. package/src/store.ts +9 -2
  153. package/src/vector-search-cache.test.ts +190 -0
  154. package/src/vector-search.ts +273 -156
  155. package/src/vectorStore.ts +443 -382
  156. package/dist/extensions/dashboard-client/src/hooks/useApi.js +0 -51
  157. package/dist/extensions/dashboard-client/src/hooks/useSSE.js +0 -63
@@ -7,6 +7,7 @@ function user(t: string): EngineMessage { return { role: "user", text: t }; }
7
7
  function assistant(t: string): EngineMessage { return { role: "assistant", text: t }; }
8
8
  function toolUse(n: string, i = "{}"): EngineMessage { return { role: "assistant", text: "", toolName: n, input: i }; }
9
9
  function toolResult(n: string, o = "ok"): EngineMessage { return { role: "tool", text: "", toolName: n, output: o }; }
10
+ function custom(t: string): EngineMessage { return { role: "custom", text: t }; }
10
11
 
11
12
  test("walks back so first preserved message is not an orphaned tool result", () => {
12
13
  const messages = [
@@ -25,9 +26,14 @@ test("walks back so first preserved message is not an orphaned tool result", ()
25
26
  assert.equal(kept[0].toolName, "search"); // assistant tool-call preserved
26
27
  });
27
28
 
28
- test("isBoundarySafe: tool result at boundary with preceding tool use is safe", () => {
29
+ test("isBoundarySafe: cut that drops a toolCall but keeps its toolResult is unsafe (PREVENT-PI-002)", () => {
29
30
  const messages = [user("a"), toolUse("search"), toolResult("search")];
30
- assert.equal(isBoundarySafe(messages, 2), true);
31
+ // keepFrom=2 drops the toolUse at index 1 but keeps the toolResult at index 2 →
32
+ // the preserved run starts on an orphaned tool result. This is the shape the old
33
+ // check mis-validated (it only compared messages[keepFrom] to messages[keepFrom-1]).
34
+ assert.equal(isBoundarySafe(messages, 2), false);
35
+ // keepFrom=1 keeps the toolCall together with its toolResult → safe.
36
+ assert.equal(isBoundarySafe(messages, 1), true);
31
37
  });
32
38
 
33
39
  test("isBoundarySafe: orphaned tool result without preceding tool use is unsafe", () => {
@@ -59,3 +65,123 @@ test("dropBefore returns original when range is empty", () => {
59
65
  const messages = [user("a"), assistant("b")];
60
66
  assert.equal(dropBefore(messages, 0, 1), messages);
61
67
  });
68
+
69
+ // --- PREVENT-PI-002 regression cases for arbitrary interleavings ---
70
+
71
+ test("interleaved custom message between toolCall and toolResult: walk-back keeps the call", () => {
72
+ // [user, assistant(tc=read), custom/bashExecution, tool(read-result)] with
73
+ // desired keepFrom=3. The old walk-back saw messages[2] was not a toolUse and
74
+ // broke at k=2, dropping the assistant toolCall at index 1 while KEEPING its
75
+ // tool result at index 3 → orphaned tool result → provider 400.
76
+ const messages = [
77
+ user("Search for files"),
78
+ toolUse("read"),
79
+ custom("bash: ls -la"),
80
+ toolResult("read", "file contents"),
81
+ assistant("Done."),
82
+ ];
83
+ const [start, end] = computeDropRange(messages, 3, 0);
84
+ assert.equal(start, 0);
85
+ assert.equal(end, 1); // keep the assistant toolCall at index 1 with its result
86
+ const kept = messages.slice(end);
87
+ assert.equal(kept[0].toolName, "read"); // assistant tool-call preserved
88
+ assert.ok(kept.some((m) => m.role === "tool" && m.toolName === "read"));
89
+ // The toolCall and its toolResult are both in the kept run.
90
+ const callIdx = kept.findIndex((m) => m.role === "assistant" && m.toolName === "read");
91
+ const resultIdx = kept.findIndex((m) => m.role === "tool" && m.toolName === "read");
92
+ assert.ok(callIdx !== -1 && resultIdx !== -1 && callIdx < resultIdx);
93
+ });
94
+
95
+ test("consecutive tool results sharing one call: no-op when the call cannot be kept", () => {
96
+ // [assistant(tc), T1, T2] with keepFrom=1: dropping the call orphans BOTH T1
97
+ // and T2. No pair-safe positive cut exists below keepFrom → no-op compaction
98
+ // (the [start,end) contract preserves a non-zero result only when one exists).
99
+ const messages = [toolUse("multi"), toolResult("multi", "r1"), toolResult("multi", "r2")];
100
+ const [start, end] = computeDropRange(messages, 1, 0);
101
+ assert.equal(start, 0);
102
+ assert.equal(end, 0); // no-op — pair rule outranks dropping
103
+ assert.equal(dropBefore(messages, 1, 0), messages);
104
+ });
105
+
106
+ test("consecutive tool results sharing one call: safe cut keeps the call with both results", () => {
107
+ // [user, assistant(tc), T1, T2, user2] — keepFrom=3 would orphan T2; the guard
108
+ // walks back to keep the call (dropEnd=1, only the first user is dropped).
109
+ const messages = [
110
+ user("u1"),
111
+ toolUse("multi"),
112
+ toolResult("multi", "r1"),
113
+ toolResult("multi", "r2"),
114
+ user("u2"),
115
+ ];
116
+ const [start, end] = computeDropRange(messages, 3, 0);
117
+ assert.equal(start, 0);
118
+ assert.equal(end, 1); // keep [assistant(tc), T1, T2, user2]
119
+ const kept = messages.slice(end);
120
+ const callIdx = kept.findIndex((m) => m.role === "assistant" && m.toolName === "multi");
121
+ const r1Idx = kept.findIndex((m) => m.role === "tool" && m.output === "r1");
122
+ const r2Idx = kept.findIndex((m) => m.role === "tool" && m.output === "r2");
123
+ assert.ok(callIdx < r1Idx && r1Idx < r2Idx);
124
+ });
125
+
126
+ test("consecutive shared-call results: dropping call + all results together is safe", () => {
127
+ // keepFrom=4 preserves only the trailing user — the call and BOTH results are
128
+ // dropped together, so nothing is orphaned.
129
+ const messages = [
130
+ user("u1"),
131
+ toolUse("multi"),
132
+ toolResult("multi", "r1"),
133
+ toolResult("multi", "r2"),
134
+ user("u2"),
135
+ ];
136
+ const [start, end] = computeDropRange(messages, 4, 0);
137
+ assert.equal(start, 0);
138
+ assert.equal(end, 4);
139
+ assert.deepEqual(messages.slice(end), [user("u2")]);
140
+ });
141
+
142
+ test("keepFrom landing on a call whose results follow is safe", () => {
143
+ // [user, assistant(tc1), T1, assistant(tc2), T2, user2] keepFrom=3 → preserved
144
+ // run starts on assistant(tc2) at index 3, whose result T2 follows. Safe.
145
+ const messages = [
146
+ user("u1"),
147
+ toolUse("read"),
148
+ toolResult("read", "r1"),
149
+ toolUse("write"),
150
+ toolResult("write", "r2"),
151
+ user("u2"),
152
+ ];
153
+ const [start, end] = computeDropRange(messages, 3, 0);
154
+ assert.equal(start, 0);
155
+ assert.equal(end, 3);
156
+ const kept = messages.slice(end);
157
+ assert.equal(kept[0].role, "assistant");
158
+ assert.equal(kept[0].toolName, "write");
159
+ assert.ok(kept.some((m) => m.role === "tool" && m.toolName === "write"));
160
+ });
161
+
162
+ test("anchor floor + pair-rule conflict: pair rule wins, drop less", () => {
163
+ // [assistant(tc), user, T] with anchor=1: the anchor floor wants dropEnd<=1
164
+ // (keep the user at index 1), but keeping from index 1 orphans T (its owner at
165
+ // index 0 would be dropped). The pair rule outranks the floor — we drop LESS,
166
+ // keeping everything (no-op) rather than cross a pair.
167
+ const messages = [toolUse("read"), user("keep me"), toolResult("read", "r")];
168
+ const out = dropBefore(messages, 2, 1);
169
+ assert.equal(out, messages, "anchor floor would orphan the tool result → no-op");
170
+ });
171
+
172
+ test("isBoundarySafe: interleaved custom between call and result is detected unsafe", () => {
173
+ const messages = [user("a"), toolUse("read"), custom("bash"), toolResult("read", "r")];
174
+ // keepFrom=3 drops the call at index 1, keeps the result at index 3 → unsafe.
175
+ assert.equal(isBoundarySafe(messages, 3), false);
176
+ // keepFrom=2 ALSO drops the call at index 1 (drop [0,2) = [user, toolUse]) and
177
+ // keeps the result at index 3 → still orphaned → unsafe.
178
+ assert.equal(isBoundarySafe(messages, 2), false);
179
+ // keepFrom=1 keeps the call (index 1) together with its result at index 3 → safe.
180
+ assert.equal(isBoundarySafe(messages, 1), true);
181
+ });
182
+
183
+ test("isBoundarySafe: cut before any tool result is safe", () => {
184
+ const messages = [user("a"), toolUse("read"), toolResult("read", "r"), assistant("done")];
185
+ assert.equal(isBoundarySafe(messages, 0), true); // out of range → safe
186
+ assert.equal(isBoundarySafe(messages, messages.length), true); // out of range → safe
187
+ });
package/src/boundary.ts CHANGED
@@ -5,10 +5,19 @@
5
5
  * 1. ANCHOR FLOOR: never drop the most recent N user messages.
6
6
  * 2. TOOL-PAIR: never split an assistant(toolCall) from its following
7
7
  * tool-result message — an orphaned `tool` role with no preceding
8
- * assistant tool call causes a 400 on the OpenAI-compat path.
8
+ * assistant tool call causes a 400 on the OpenAI-compat path. The pair
9
+ * invariant outranks the anchor floor: on conflict we drop LESS (lower the
10
+ * drop end), never cross a pair.
9
11
  *
10
12
  * The engine reasons over EngineMessage; the pi adapter maps role "tool" +
11
- * toolName to the tool-result shape.
13
+ * toolName to the tool-result shape. EngineMessage carries no tool-call id, so
14
+ * ownership is positional: a tool result's owner is its nearest preceding
15
+ * assistant tool-call (the last assistant message with a `toolName` before it).
16
+ * A preserved tool result is orphaned by a cut when its owner is dropped; the
17
+ * guard rejects any cut that drops an owner while preserving its result, for
18
+ * ARBITRARY interleavings (custom/non-tool messages between call and result,
19
+ * consecutive results sharing one call, a cut landing directly on a call whose
20
+ * results follow).
12
21
  */
13
22
 
14
23
  import type { EngineMessage } from "./types.js";
@@ -23,16 +32,53 @@ function hasToolUse(m: EngineMessage): boolean {
23
32
  return Boolean(m.toolName) && m.role !== "tool";
24
33
  }
25
34
 
35
+ /**
36
+ * Is the drop boundary at `dropEnd` pair-safe? The preserved run is
37
+ * [dropEnd, messages.length). The cut is pair-safe iff NO preserved tool result
38
+ * is orphaned: for every tool result at index >= dropEnd, its nearest preceding
39
+ * assistant tool-call must EXIST and be PRESERVED (index >= dropEnd). A tool
40
+ * result with no preceding assistant tool-call is already orphaned in the
41
+ * input — we treat that as unsafe too, so the guard never endorses shipping an
42
+ * orphaned result to the provider.
43
+ *
44
+ * O(messages.length) single forward pass; early-exits on the first orphan. The
45
+ * owner of each result is the most recent `hasToolUse` message seen so far
46
+ * (tracked across the whole stream, including dropped messages, because a
47
+ * dropped assistant tool-call is exactly the owner we must reject).
48
+ */
49
+ export function isPairSafe(messages: EngineMessage[], dropEnd: number): boolean {
50
+ if (dropEnd <= 0 || dropEnd >= messages.length) return true;
51
+ let lastToolCall = -1;
52
+ for (let i = 0; i < messages.length; i++) {
53
+ if (hasToolUse(messages[i])) lastToolCall = i;
54
+ if (i >= dropEnd && isToolResult(messages[i])) {
55
+ if (lastToolCall === -1) return false; // no preceding call → orphaned
56
+ if (lastToolCall < dropEnd) return false; // owner dropped → orphaned
57
+ }
58
+ }
59
+ return true;
60
+ }
61
+
26
62
  /**
27
63
  * Compute the safe drop range [dropStart, dropEnd) within `messages`.
28
- * `keepFrom` is the caller's desired first-preserved index. We then:
29
- * 1. Walk it back (lower dropEnd = keep more) so the first preserved message
30
- * is never an orphaned tool result (tool-pair invariant).
31
- * 2. Raise it (lower dropEnd) to the anchor floor so the last N user messages
32
- * are never dropped, when enough user messages exist.
33
64
  *
34
- * dropEnd is the first index KEPT. Returns [dropStart, dropEnd]; empty range
35
- * if nothing should be dropped.
65
+ * Contract:
66
+ * - `keepFrom` is the caller's desired first-preserved index (drop [0, keepFrom)).
67
+ * - `dropEnd` is the first index KEPT; we may LOWER it (keep more) to satisfy the
68
+ * guards, never raise it above keepFrom.
69
+ * - The anchor floor (PREVENT-PI-001) caps dropEnd at the index of the
70
+ * Nth-from-last user message so the last N user messages are never dropped.
71
+ * - The tool-pair invariant (PREVENT-PI-002) rejects any dropEnd that orphans a
72
+ * preserved tool result; on conflict with the anchor floor the pair rule wins
73
+ * (we drop less, never cross a pair).
74
+ * - We return the LARGEST pair-safe dropEnd <= min(keepFrom, anchorStart) so the
75
+ * caller drops as much as is safe. When no pair-safe positive cut exists at
76
+ * or below keepFrom, we return [0, 0] (no-op) — the pair rule outranks
77
+ * dropping. dropStart is always 0 today (we drop a prefix); reserved for
78
+ * future two-sided trimming.
79
+ *
80
+ * Returns [0, 0] (empty range, drop nothing) when keepFrom is out of range or no
81
+ * pair-safe positive cut exists.
36
82
  */
37
83
  export function computeDropRange(
38
84
  messages: EngineMessage[],
@@ -44,48 +90,38 @@ export function computeDropRange(
44
90
  const userIndexes: number[] = [];
45
91
  messages.forEach((m, i) => { if (m.role === "user") userIndexes.push(i); });
46
92
  const anchorActive = anchorUserMessages > 0 && userIndexes.length >= anchorUserMessages;
47
- const anchorStart = anchorActive ? userIndexes[userIndexes.length - anchorUserMessages] : 0;
48
- const floor = anchorActive ? anchorStart : 0;
93
+ const anchorStart = anchorActive ? userIndexes[userIndexes.length - anchorUserMessages] : keepFrom;
94
+ // Upper bound on dropEnd: never keep less than the caller asked (dropEnd <= keepFrom)
95
+ // and never drop a must-keep user message (dropEnd <= anchorStart).
96
+ const upperBound = Math.min(keepFrom, anchorActive ? anchorStart : keepFrom);
49
97
 
50
- // Walk back for the tool-pair invariant (keep more when needed).
51
- let k = keepFrom;
52
- while (k > floor) {
53
- const firstPreserved = messages[k];
54
- if (!firstPreserved || !isToolResult(firstPreserved)) break;
55
- const preceding = messages[k - 1];
56
- if (preceding && hasToolUse(preceding)) {
57
- k -= 1; // pair intact across boundary — include the assistant turn
58
- break;
59
- }
60
- k -= 1;
98
+ // Walk down from the upper bound to find the largest pair-safe cut. dropEnd=0
99
+ // (drop nothing) is always pair-safe; the loop finds the largest positive cut,
100
+ // and falls back to [0, 0] when none exists — the pair rule outranks dropping.
101
+ for (let dropEnd = upperBound; dropEnd > 0; dropEnd--) {
102
+ if (isPairSafe(messages, dropEnd)) return [0, dropEnd];
61
103
  }
62
- if (k < floor) k = floor;
63
-
64
- // Anchor floor: never drop a must-keep user message. Raise dropEnd so we keep
65
- // from anchorStart onward when the walk didn't already.
66
- if (anchorActive && k > anchorStart) k = anchorStart;
67
-
68
- if (k <= 0) return [0, 0];
69
- return [0, k];
104
+ return [0, 0];
70
105
  }
71
106
 
72
107
  /**
73
108
  * Validate that the intended split at `keepFrom` (drop [0, keepFrom), keep the
74
- * rest) does not start the preserved run on an orphaned tool result. Checks
75
- * messages[keepFrom] against messages[keepFrom-1] directly independent of the
76
- * walk-back that computeDropRange may apply.
109
+ * rest) does not orphan any preserved tool result. Checks the FULL preserved
110
+ * run, not just the first message, so it holds for arbitrary interleavings
111
+ * (custom messages between call and result, consecutive shared-call results, a
112
+ * cut landing on a call whose results follow). Used on the every-LLM-call
113
+ * live-trim hot path (extensions/mega-trim.ts) and by dropCompactedRange
114
+ * (src/adapt.ts).
77
115
  */
78
116
  export function isBoundarySafe(messages: EngineMessage[], keepFrom: number): boolean {
79
- if (keepFrom <= 0 || keepFrom >= messages.length) return true;
80
- const firstPreserved = messages[keepFrom];
81
- if (!isToolResult(firstPreserved)) return true;
82
- const preceding = messages[keepFrom - 1];
83
- return Boolean(preceding && hasToolUse(preceding));
117
+ return isPairSafe(messages, keepFrom);
84
118
  }
85
119
 
86
120
  /**
87
121
  * Drop everything before the safe keep-index, honoring both guards, returning
88
- * the filtered message list.
122
+ * the filtered message list. Returns the original array reference (unchanged)
123
+ * when the safe range is empty so callers can short-circuit on reference
124
+ * equality.
89
125
  */
90
126
  export function dropBefore(messages: EngineMessage[], keepFrom: number, anchorUserMessages: number): EngineMessage[] {
91
127
  const [dropStart, dropEnd] = computeDropRange(messages, keepFrom, anchorUserMessages);
package/src/canary.ts CHANGED
@@ -8,6 +8,16 @@
8
8
  * The controller owns a MUTABLE working copy of the dedup config; callers read
9
9
  * `controller.config` after each step. Tiers disabled via MARK_ONLY degrade
10
10
  * gracefully rather than fully off.
11
+ *
12
+ * Persistence design: disabled state is IN-MEMORY ONLY by design. The dedup
13
+ * config loads from MEGACOMPACT_* env vars (config/dedup.ts) with no durable
14
+ * save mechanism. `setEnabled` DOES mutate `this.config.L1_ENABLED` etc. so
15
+ * callers reading `controller.config` see the disabled state for the current
16
+ * session. On restart, env defaults re-apply and the canary sequences again
17
+ * from L0 — this is intentional: a tier disabled due to a cold cache or
18
+ * transient load gets a fresh evaluation each run rather than being locked
19
+ * out forever. To permanently disable a tier, set the corresponding
20
+ * MEGACOMPACT_*_ENABLED env var to false.
11
21
  */
12
22
 
13
23
  import type { DedupConfigShape, DedupTier } from "./config/dedup.js";
@@ -28,6 +28,14 @@ function envNum(name: string, def: number): number {
28
28
  return Number.isFinite(n) ? n : def;
29
29
  }
30
30
 
31
+ /** S42B: parse a comma-separated numeric env var (e.g. "1.0,0.9,0.8"). */
32
+ function envNumArray(name: string, def: number[]): number[] {
33
+ const v = process.env[name];
34
+ if (v === undefined) return def;
35
+ const parts = v.split(",").map((x) => Number(x.trim()));
36
+ return parts.length > 0 && parts.every((n) => Number.isFinite(n)) ? parts : def;
37
+ }
38
+
31
39
  export interface DedupConfigShape {
32
40
  // Tier enable flags.
33
41
  L0_ENABLED: boolean;
@@ -54,6 +62,17 @@ export interface DedupConfigShape {
54
62
  RAPTOR_BUDGET_MS: number;
55
63
  RAPTOR_CLUSTERS_PER_LEVEL: number;
56
64
  RAPTOR_CONSISTENCY: number;
65
+ // S42B: multi-level retrieval (score all tree levels + leaf expansion).
66
+ RAPTOR_MULTILEVEL_ENABLED: boolean;
67
+ RAPTOR_LEVEL_WEIGHTS: number[]; // per-level weights, index 0 = leaves (uncalibrated)
68
+ RAPTOR_LEAF_EXPANSION: boolean;
69
+ RAPTOR_MAX_LEAF_EXPANSION: number; // uncalibrated
70
+ RAPTOR_FRESHNESS_HOURS: number; // S42D: skip rebuild when tree is fresh (uncalibrated)
71
+ /** S25 Phase-2: inject top-level RAPTOR summary nodes (root + level-1
72
+ * clusters) into the recall block as a hierarchical overview header.
73
+ * Default true — the high-level map helps the model see the session's
74
+ * topical structure before detailed checkpoint hits. */
75
+ RAPTOR_INJECT_SUMMARIES: boolean;
57
76
  // Monitoring / alerting.
58
77
  FP_RATE_L0: number; // FP alert threshold for exact tier
59
78
  FP_RATE_L1L2: number; // FP alert threshold for fuzzy tiers
@@ -87,6 +106,12 @@ export function loadDedupConfig(): DedupConfigShape {
87
106
  RAPTOR_BUDGET_MS: envNum("MEGACOMPACT_RAPTOR_BUDGET_MS", 5000),
88
107
  RAPTOR_CLUSTERS_PER_LEVEL: envNum("MEGACOMPACT_RAPTOR_CLUSTERS", 5),
89
108
  RAPTOR_CONSISTENCY: envNum("MEGACOMPACT_RAPTOR_CONSISTENCY", 0.6),
109
+ RAPTOR_MULTILEVEL_ENABLED: envBool("MEGACOMPACT_RAPTOR_MULTILEVEL", true),
110
+ RAPTOR_LEVEL_WEIGHTS: envNumArray("MEGACOMPACT_RAPTOR_LEVEL_WEIGHTS", [1.0, 0.9, 0.8, 0.7, 0.5]),
111
+ RAPTOR_LEAF_EXPANSION: envBool("MEGACOMPACT_RAPTOR_LEAF_EXPANSION", true),
112
+ RAPTOR_MAX_LEAF_EXPANSION: envNum("MEGACOMPACT_RAPTOR_MAX_LEAF_EXP", 10),
113
+ RAPTOR_FRESHNESS_HOURS: envNum("MEGACOMPACT_RAPTOR_FRESHNESS_HOURS", 4),
114
+ RAPTOR_INJECT_SUMMARIES: envBool("MEGACOMPACT_RAPTOR_INJECT_SUMMARIES", true),
90
115
  FP_RATE_L0: envNum("MEGACOMPACT_FP_RATE_L0", 0.01),
91
116
  FP_RATE_L1L2: envNum("MEGACOMPACT_FP_RATE_L1L2", 0.05),
92
117
  ALERT_WINDOW_MS: envNum("MEGACOMPACT_ALERT_WINDOW_MS", 600_000),
package/src/config.ts CHANGED
@@ -37,7 +37,9 @@ export function preserveRecentForPressure(
37
37
  ): number {
38
38
  const p = pressure < 0 ? 0 : pressure > 1 ? 1 : pressure;
39
39
  const v = Math.round(preserveRecent - (preserveRecent - preserveRecentMin) * p);
40
- return Math.max(preserveRecentMin, Math.min(preserveRecent, v));
40
+ // Floor of 1: even with preserveRecentMin=0 at full pressure, never compact
41
+ // ALL messages — the boundary guard (computeDropRange) needs ≥1 to anchor on.
42
+ return Math.max(1, preserveRecentMin, Math.min(preserveRecent, v));
41
43
  }
42
44
 
43
45
  /**