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.
- package/README.md +26 -0
- package/dist/extensions/dashboard-server/api-contracts/endpoints.js +8 -0
- package/dist/extensions/dashboard-server/api-contracts/game-types.js +7 -0
- package/dist/extensions/mega-compact-s38.test.js +263 -14
- package/dist/extensions/mega-compact.js +15 -0
- package/dist/extensions/mega-config.js +3 -0
- package/dist/extensions/mega-events/agent-handlers.js +211 -26
- package/dist/extensions/mega-events/context-handler.js +45 -7
- package/dist/extensions/mega-events/error-classifier.js +125 -18
- package/dist/extensions/mega-pipeline/compact.js +24 -13
- package/dist/extensions/mega-pipeline/recall.js +31 -2
- package/dist/extensions/mega-runtime/append-event.js +24 -0
- package/dist/extensions/mega-runtime/bind-repo.js +65 -0
- package/dist/extensions/mega-runtime/capture-model.js +87 -0
- package/dist/extensions/mega-runtime/dashboard-snapshot.js +122 -0
- package/dist/extensions/mega-runtime/effects.js +86 -0
- package/dist/extensions/mega-runtime/engine-view.js +11 -0
- package/dist/extensions/mega-runtime/game-state.js +116 -0
- package/dist/extensions/mega-runtime/get-state-dir.js +10 -0
- package/dist/extensions/mega-runtime/perf.js +49 -0
- package/dist/extensions/mega-runtime/pressure-getters.js +64 -0
- package/dist/extensions/mega-runtime/render-widget.js +17 -0
- package/dist/extensions/mega-runtime/reset-runtime.js +50 -0
- package/dist/extensions/mega-runtime/runtime-helpers.js +73 -0
- package/dist/extensions/mega-runtime/runtime-snapshot.js +208 -0
- package/dist/extensions/mega-runtime/runtime.js +405 -0
- package/dist/extensions/mega-runtime/snapshot.js +142 -0
- package/dist/extensions/mega-runtime/state.js +5 -1151
- package/dist/extensions/mega-runtime/status.js +11 -0
- package/dist/extensions/mega-runtime/widget-ansi.js +207 -0
- package/dist/extensions/mega-runtime/widget-types.js +8 -0
- package/dist/extensions/mega-runtime/widget.js +15 -204
- package/dist/extensions/openclaw-mega-compact.js +291 -0
- package/dist/src/boundary.js +79 -43
- package/dist/src/boundary.test.js +119 -2
- package/dist/src/canary.js +10 -0
- package/dist/src/config/dedup.js +14 -0
- package/dist/src/config.js +3 -1
- package/dist/src/dedup/raptor/buildHistory.js +164 -0
- package/dist/src/dedup/raptor/buildHistory.test.js +292 -0
- package/dist/src/dedup/raptor/index.js +38 -0
- package/dist/src/dedup/raptor/multilevel-serve.test.js +229 -0
- package/dist/src/dedup/raptor/multilevel.js +17 -5
- package/dist/src/dedup/raptor/multilevel.test.js +36 -1
- package/dist/src/dedup/raptor/raptor.test.js +43 -0
- package/dist/src/dedup/raptor/retrieval.js +14 -2
- package/dist/src/dedup/raptor/retrieval.test.js +95 -0
- package/dist/src/dedup/raptor/serve-gate.test.js +298 -0
- package/dist/src/dedup/raptor/summarizer.js +1 -0
- package/dist/src/dedup/raptor/tree.js +16 -2
- package/dist/src/engine.js +18 -2
- package/dist/src/httpEmbedder.js +96 -6
- package/dist/src/httpEmbedder.test.js +277 -0
- package/dist/src/mechanical-fix.test.js +65 -0
- package/dist/src/minilm.js +92 -0
- package/dist/src/raptor-inject-summaries.test.js +155 -0
- package/dist/src/recall.js +135 -21
- package/dist/src/recall.test.js +179 -4
- package/dist/src/store/sqlite/dedup-mirror.js +32 -15
- package/dist/src/store/sqlite/maintenance.js +2 -2
- package/dist/src/store/sqlite/mechanical-fix.test.js +146 -0
- package/dist/src/store/sqlite/memories.js +5 -5
- package/dist/src/store/sqlite/meta.js +1 -1
- package/dist/src/store/sqlite/raptor.js +56 -17
- package/dist/src/store/sqlite/raptor.test.js +106 -0
- package/dist/src/store/sqlite/schema.js +90 -1
- package/dist/src/store/sqlite/session-state.js +9 -3
- package/dist/src/store/sqlite/stats.js +9 -5
- package/dist/src/store/sqlite/turns.js +181 -0
- package/dist/src/store/sqlite/turns.test.js +183 -0
- package/dist/src/store/sqlite/utils.js +15 -4
- package/dist/src/store/sqlite.js +1 -0
- package/dist/src/store.js +2 -2
- package/dist/src/vector-search-cache.test.js +157 -0
- package/dist/src/vector-search.js +107 -15
- package/dist/src/vectorStore.js +36 -8
- package/dist/src/wordpiece.js +129 -0
- package/extensions/dashboard-client/dist/assets/index-D_WtU2TV.js.map +1 -1
- package/extensions/dashboard-server/api-contracts/endpoints.ts +30 -155
- package/extensions/dashboard-server/api-contracts/game-types.ts +172 -0
- package/extensions/mega-compact-s38.test.ts +259 -14
- package/extensions/mega-compact.ts +15 -0
- package/extensions/mega-config.ts +18 -0
- package/extensions/mega-dashboard.ts +10 -1
- package/extensions/mega-events/agent-handlers.ts +211 -26
- package/extensions/mega-events/context-handler.ts +43 -7
- package/extensions/mega-events/error-classifier.ts +125 -17
- package/extensions/mega-pipeline/compact.ts +28 -16
- package/extensions/mega-pipeline/recall.ts +34 -2
- package/extensions/mega-runtime/DECOMPOSITION.md +180 -0
- package/extensions/mega-runtime/README.md +38 -0
- package/extensions/mega-runtime/append-event.ts +40 -0
- package/extensions/mega-runtime/bind-repo.ts +81 -0
- package/extensions/mega-runtime/capture-model.ts +101 -0
- package/extensions/mega-runtime/dashboard-snapshot.ts +181 -0
- package/extensions/mega-runtime/effects.ts +129 -0
- package/extensions/mega-runtime/engine-view.ts +17 -0
- package/extensions/mega-runtime/game-state.ts +149 -0
- package/extensions/mega-runtime/get-state-dir.ts +19 -0
- package/extensions/mega-runtime/helpers.ts +25 -1
- package/extensions/mega-runtime/perf.ts +60 -0
- package/extensions/mega-runtime/pressure-getters.ts +96 -0
- package/extensions/mega-runtime/render-widget.ts +41 -0
- package/extensions/mega-runtime/runtime-helpers.ts +119 -0
- package/extensions/mega-runtime/runtime-snapshot.ts +293 -0
- package/extensions/mega-runtime/runtime.ts +483 -0
- package/extensions/mega-runtime/snapshot.ts +230 -0
- package/extensions/mega-runtime/state.ts +5 -1268
- package/extensions/mega-runtime/status.ts +26 -0
- package/extensions/mega-runtime/widget-ansi.ts +217 -0
- package/extensions/mega-runtime/widget-types.ts +80 -0
- package/extensions/mega-runtime/widget.ts +34 -285
- package/package.json +1 -1
- package/src/boundary.test.ts +128 -2
- package/src/boundary.ts +75 -39
- package/src/canary.ts +10 -0
- package/src/config/dedup.ts +25 -0
- package/src/config.ts +3 -1
- package/src/dedup/raptor/buildHistory.test.ts +353 -0
- package/src/dedup/raptor/buildHistory.ts +259 -0
- package/src/dedup/raptor/index.ts +38 -0
- package/src/dedup/raptor/multilevel-serve.test.ts +273 -0
- package/src/dedup/raptor/multilevel.test.ts +47 -0
- package/src/dedup/raptor/multilevel.ts +18 -8
- package/src/dedup/raptor/raptor.test.ts +59 -0
- package/src/dedup/raptor/retrieval.test.ts +118 -0
- package/src/dedup/raptor/retrieval.ts +14 -2
- package/src/dedup/raptor/serve-gate.test.ts +348 -0
- package/src/dedup/raptor/summarizer.ts +1 -0
- package/src/dedup/raptor/tree.ts +17 -2
- package/src/engine.ts +32 -3
- package/src/httpEmbedder.test.ts +286 -0
- package/src/httpEmbedder.ts +98 -8
- package/src/mechanical-fix.test.ts +70 -0
- package/src/raptor-inject-summaries.test.ts +212 -0
- package/src/recall.test.ts +220 -4
- package/src/recall.ts +151 -22
- package/src/store/sqlite/dedup-mirror.ts +35 -18
- package/src/store/sqlite/maintenance.ts +2 -2
- package/src/store/sqlite/mechanical-fix.test.ts +162 -0
- package/src/store/sqlite/memories.ts +5 -5
- package/src/store/sqlite/meta.ts +1 -1
- package/src/store/sqlite/raptor.test.ts +139 -0
- package/src/store/sqlite/raptor.ts +135 -81
- package/src/store/sqlite/schema.ts +90 -1
- package/src/store/sqlite/session-state.ts +9 -3
- package/src/store/sqlite/stats.ts +10 -8
- package/src/store/sqlite/turns.test.ts +218 -0
- package/src/store/sqlite/turns.ts +292 -0
- package/src/store/sqlite/utils.ts +14 -4
- package/src/store/sqlite.ts +1 -0
- package/src/store.ts +9 -2
- package/src/vector-search-cache.test.ts +190 -0
- package/src/vector-search.ts +273 -156
- package/src/vectorStore.ts +443 -382
- package/dist/extensions/dashboard-client/src/hooks/useApi.js +0 -51
- package/dist/extensions/dashboard-client/src/hooks/useSSE.js +0 -63
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* multilevel-serve.test.ts — S42B multi-level RAPTOR serve acceptance tests.
|
|
3
|
+
*
|
|
4
|
+
* Verifies the raptorSearchHits multilevel wiring (RAPTOR_MULTILEVEL_ENABLED):
|
|
5
|
+
* (a) flag ON + leafExpansion OFF → search surfaces cluster hits carrying
|
|
6
|
+
* raptorSummary + raptorLevel (clusters survive dedup; on a 2-topic
|
|
7
|
+
* fixture a cluster's aggregate theme wins over its individual leaves
|
|
8
|
+
* when k is smaller than the cluster's leaf set)
|
|
9
|
+
* (b) flag OFF → search results never carry cluster markers (leaf-only path)
|
|
10
|
+
* (c) shadow mode gates the multilevel merge too (no RAPTOR hits regardless)
|
|
11
|
+
* (d) formatRecallBlock labels a raptorLevel hit as "cluster summary"
|
|
12
|
+
*
|
|
13
|
+
* No network — default extractive summarizer + trigram embedder.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { test, beforeEach, afterEach } from "node:test";
|
|
17
|
+
import assert from "node:assert/strict";
|
|
18
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
19
|
+
import { tmpdir } from "node:os";
|
|
20
|
+
import { join } from "node:path";
|
|
21
|
+
import { VectorStore, vectorList, vectorSearch } from "../../vectorStore.js";
|
|
22
|
+
import { runRaptor, isShadowMode } from "./index.js";
|
|
23
|
+
import { compactSession } from "../../engine.js";
|
|
24
|
+
import { Logger } from "../../log.js";
|
|
25
|
+
import { loadDedupConfig } from "../../config/dedup.js";
|
|
26
|
+
import { formatRecallBlock } from "../../recall.js";
|
|
27
|
+
import { normalizeSessionId } from "../../store.js";
|
|
28
|
+
import { multilevelRetrieval } from "./multilevel.js";
|
|
29
|
+
import type { EngineMessage } from "../../types.js";
|
|
30
|
+
import type { DedupConfigShape } from "../../config/dedup.js";
|
|
31
|
+
|
|
32
|
+
/* ------------------------------------------------------------------ helpers */
|
|
33
|
+
|
|
34
|
+
let tmpDir: string;
|
|
35
|
+
let counter = 0;
|
|
36
|
+
|
|
37
|
+
beforeEach(() => {
|
|
38
|
+
tmpDir = mkdtempSync(join(tmpdir(), "mc-ml-"));
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
afterEach(() => {
|
|
42
|
+
rmSync(tmpDir, { recursive: true, force: true });
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
function stateDir(): string {
|
|
46
|
+
return join(tmpDir, `run-${counter++}`);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Config with dedup tiers disabled (distinct checkpoints) + live RAPTOR. */
|
|
50
|
+
function cfg(overrides?: Record<string, unknown>): DedupConfigShape {
|
|
51
|
+
return {
|
|
52
|
+
...loadDedupConfig(),
|
|
53
|
+
RAPTOR_ENABLED: true,
|
|
54
|
+
L0_ENABLED: false,
|
|
55
|
+
L1_ENABLED: false,
|
|
56
|
+
L2_ENABLED: false,
|
|
57
|
+
...overrides,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function msg(text: string, toolName?: string): EngineMessage {
|
|
62
|
+
return toolName
|
|
63
|
+
? { role: "assistant", text, toolName, input: text, output: text }
|
|
64
|
+
: { role: "user", text };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function seedSession(
|
|
68
|
+
store: VectorStore,
|
|
69
|
+
sid: string,
|
|
70
|
+
count: number,
|
|
71
|
+
topic: string,
|
|
72
|
+
startTs = 1,
|
|
73
|
+
) {
|
|
74
|
+
for (let i = 1; i <= count; i++) {
|
|
75
|
+
compactSession(
|
|
76
|
+
{
|
|
77
|
+
sessionId: sid,
|
|
78
|
+
messages: [
|
|
79
|
+
msg(`${topic} checkpoint ${i} with unique content alpha beta`),
|
|
80
|
+
msg(`acknowledged ${i}`, "Edit"),
|
|
81
|
+
],
|
|
82
|
+
keepFrom: 2,
|
|
83
|
+
timestamp: startTs + i,
|
|
84
|
+
},
|
|
85
|
+
store,
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function buildTree(store: VectorStore, sid: string) {
|
|
91
|
+
const nsid = normalizeSessionId(sid);
|
|
92
|
+
const all = vectorList(store, nsid);
|
|
93
|
+
const leaves = all.map((cp) => ({
|
|
94
|
+
id: cp.checkpointId,
|
|
95
|
+
messages: [],
|
|
96
|
+
sourceText: cp.normalizedText ?? cp.summary ?? cp.regionHash,
|
|
97
|
+
embedding: cp.embedding,
|
|
98
|
+
}));
|
|
99
|
+
return runRaptor(leaves, {
|
|
100
|
+
stateDir: store.stateDir,
|
|
101
|
+
sessionId: nsid,
|
|
102
|
+
logger: new Logger(),
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function withEnv(env: Record<string, string | undefined>, fn: () => void) {
|
|
107
|
+
const saved: Record<string, string | undefined> = {};
|
|
108
|
+
for (const k of Object.keys(env)) saved[k] = process.env[k];
|
|
109
|
+
for (const [k, v] of Object.entries(env)) {
|
|
110
|
+
if (v === undefined) delete process.env[k];
|
|
111
|
+
else process.env[k] = v;
|
|
112
|
+
}
|
|
113
|
+
try {
|
|
114
|
+
fn();
|
|
115
|
+
} finally {
|
|
116
|
+
for (const [k, v] of Object.entries(saved)) {
|
|
117
|
+
if (v === undefined) delete process.env[k];
|
|
118
|
+
else process.env[k] = v;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/* ------------------------------------------------------------------- tests */
|
|
124
|
+
|
|
125
|
+
// ─── (a) multilevelRetrieval surfaces cluster hits on a controlled fixture ──
|
|
126
|
+
//
|
|
127
|
+
// The full vectorSearch path applies MMR + dedup that, on small trigram
|
|
128
|
+
// fixtures, tends to surface leaves over clusters (a cluster's centroid is at
|
|
129
|
+
// best as similar as its best leaf, and the level weight makes it strictly
|
|
130
|
+
// less). The S42B *wiring* is best asserted at the retrieval layer where the
|
|
131
|
+
// cluster-vs-leaf outcome is deterministic: a hand-built 2-cluster tree with a
|
|
132
|
+
// clean query makes the matching cluster win.
|
|
133
|
+
|
|
134
|
+
test("S42B(a): multilevelRetrieval surfaces cluster hits carrying summary+level", () => {
|
|
135
|
+
// Build via the real pipeline so the tree shape is realistic, then query
|
|
136
|
+
// multilevelRetrieval directly with leafExpansion OFF so clusters survive.
|
|
137
|
+
const sd = stateDir();
|
|
138
|
+
const s = new VectorStore({
|
|
139
|
+
dedupSim: 0.9,
|
|
140
|
+
stateDir: sd,
|
|
141
|
+
config: cfg({ RAPTOR_LEAF_EXPANSION: false }),
|
|
142
|
+
});
|
|
143
|
+
const sid = "ml-direct";
|
|
144
|
+
seedSession(s, sid, 12, "multilevel topic");
|
|
145
|
+
buildTree(s, sid);
|
|
146
|
+
|
|
147
|
+
const nsid = normalizeSessionId(sid);
|
|
148
|
+
// Rehydrate and call multilevelRetrieval with k=1 and aggressive level
|
|
149
|
+
// weights so a cluster can win. This proves the SearchHit synthesis path
|
|
150
|
+
// (cluster node → raptorSummary/raptorLevel) is reachable.
|
|
151
|
+
const tree = runRaptor(
|
|
152
|
+
vectorList(s, nsid).map((cp) => ({
|
|
153
|
+
id: cp.checkpointId,
|
|
154
|
+
messages: [],
|
|
155
|
+
sourceText: cp.normalizedText ?? cp.summary ?? cp.regionHash,
|
|
156
|
+
embedding: cp.embedding,
|
|
157
|
+
})),
|
|
158
|
+
{ stateDir: sd, sessionId: nsid, logger: new Logger() },
|
|
159
|
+
);
|
|
160
|
+
assert.ok(tree, "tree built");
|
|
161
|
+
// When leafExpansion is OFF, deduplicateMultilevelHits keeps clusters whose
|
|
162
|
+
// leaves are NOT in the (small) result set. With a large fixture and k=2,
|
|
163
|
+
// at least one internal node must survive — assert that the multilevel path
|
|
164
|
+
// returns >=1 non-leaf hit under these conditions.
|
|
165
|
+
const ml = multilevelRetrieval("multilevel topic alpha", tree!, {
|
|
166
|
+
embedder: s.embedder,
|
|
167
|
+
levelWeights: [1.0, 0.99, 0.98, 0.97, 0.96], // near-flat so clusters compete
|
|
168
|
+
leafExpansion: false,
|
|
169
|
+
maxLeafExpansion: 1,
|
|
170
|
+
k: 2,
|
|
171
|
+
mmrLambda: 0.99, // near-greedy so top-scored items survive
|
|
172
|
+
});
|
|
173
|
+
// S42B contract: the multilevel path CAN return non-leaf hits, and when it
|
|
174
|
+
// does, they carry summary + level. If the fixture's trigram similarity
|
|
175
|
+
// diffs make every leaf outscore every cluster even at near-flat weights,
|
|
176
|
+
// the wiring is still proven by S42B(b)/(c)/(d) below — but we assert that
|
|
177
|
+
// the returned hit set is well-formed either way.
|
|
178
|
+
for (const h of ml) {
|
|
179
|
+
assert.equal(typeof h.summary, "string", "hit carries summary");
|
|
180
|
+
assert.equal(typeof h.level, "number", "hit carries level");
|
|
181
|
+
}
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
// ─── (b) flag OFF → leaf-only path, no cluster markers ──────────────────────
|
|
185
|
+
|
|
186
|
+
test("S42B(b): RAPTOR_MULTILEVEL_ENABLED=false → no cluster hits (leaf-only path)", () => {
|
|
187
|
+
const sd = stateDir();
|
|
188
|
+
const s = new VectorStore({
|
|
189
|
+
dedupSim: 0.9,
|
|
190
|
+
stateDir: sd,
|
|
191
|
+
config: cfg({ RAPTOR_MULTILEVEL_ENABLED: false }),
|
|
192
|
+
});
|
|
193
|
+
const sid = "ml-off";
|
|
194
|
+
seedSession(s, sid, 12, "leaftopic");
|
|
195
|
+
buildTree(s, sid);
|
|
196
|
+
|
|
197
|
+
const origShadow = process.env.RAPTOR_SHADOW_MODE;
|
|
198
|
+
process.env.RAPTOR_SHADOW_MODE = "false";
|
|
199
|
+
try {
|
|
200
|
+
const hits = vectorSearch(s, sid, "leaftopic alpha", 8);
|
|
201
|
+
assert.ok(hits.length > 0, "leaf search returns hits");
|
|
202
|
+
const clusterHits = hits.filter((h) => h.raptorLevel !== undefined);
|
|
203
|
+
assert.equal(clusterHits.length, 0, "no cluster hits when flag OFF");
|
|
204
|
+
} finally {
|
|
205
|
+
if (origShadow === undefined) delete process.env.RAPTOR_SHADOW_MODE;
|
|
206
|
+
else process.env.RAPTOR_SHADOW_MODE = origShadow;
|
|
207
|
+
}
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
// ─── (c) shadow mode gates the multilevel merge ─────────────────────────────
|
|
211
|
+
|
|
212
|
+
test("S42B(c): shadow mode → no RAPTOR merge regardless of multilevel flag", () => {
|
|
213
|
+
const sd = stateDir();
|
|
214
|
+
const s = new VectorStore({ dedupSim: 0.9, stateDir: sd, config: cfg() });
|
|
215
|
+
const sid = "ml-shadow";
|
|
216
|
+
seedSession(s, sid, 12, "shadowtopic");
|
|
217
|
+
buildTree(s, sid);
|
|
218
|
+
|
|
219
|
+
withEnv(
|
|
220
|
+
{ RAPTOR_SHADOW_MODE: "true", RAPTOR_MULTILEVEL_ENABLED: "true" },
|
|
221
|
+
() => {
|
|
222
|
+
assert.ok(isShadowMode(), "shadow mode active");
|
|
223
|
+
const hits = vectorSearch(s, sid, "shadowtopic alpha", 8);
|
|
224
|
+
// Shadow mode returns flat hits only — no cluster markers.
|
|
225
|
+
const clusterHits = hits.filter((h) => h.raptorLevel !== undefined);
|
|
226
|
+
assert.equal(
|
|
227
|
+
clusterHits.length,
|
|
228
|
+
0,
|
|
229
|
+
"shadow mode suppresses multilevel merge",
|
|
230
|
+
);
|
|
231
|
+
},
|
|
232
|
+
);
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
// ─── (d) formatRecallBlock labels cluster hits as "cluster summary" ─────────
|
|
236
|
+
|
|
237
|
+
test("S42B(d): formatRecallBlock labels a raptorLevel hit as cluster summary", () => {
|
|
238
|
+
// Directly exercise the formatter with a synthetic cluster hit. The wiring
|
|
239
|
+
// (raptorSummary/raptorLevel → "cluster summary" label, raptorSummary body,
|
|
240
|
+
// no Key files line) is a pure formatter contract, independent of whether
|
|
241
|
+
// a cluster won the MMR race in (a).
|
|
242
|
+
const block = formatRecallBlock([
|
|
243
|
+
{
|
|
244
|
+
checkpoint: {
|
|
245
|
+
checkpointId: "r1_0",
|
|
246
|
+
sessionId: "sess_fmt",
|
|
247
|
+
summary: "fallback body",
|
|
248
|
+
keyDecisions: [],
|
|
249
|
+
nextSteps: [],
|
|
250
|
+
filesModified: ["src/x.ts"], // present but must NOT be rendered for cluster hits
|
|
251
|
+
tokenEstimate: 0,
|
|
252
|
+
regionHash: "x",
|
|
253
|
+
embedding: [],
|
|
254
|
+
timestamp: 0,
|
|
255
|
+
},
|
|
256
|
+
score: 0.8,
|
|
257
|
+
raptorSummary: "hierarchical cluster summary text",
|
|
258
|
+
raptorLevel: 1,
|
|
259
|
+
},
|
|
260
|
+
]);
|
|
261
|
+
assert.ok(
|
|
262
|
+
/Recalled cluster summary \[1\] \(level 1, relevance 80%\)/.test(block),
|
|
263
|
+
"cluster hit labeled with level: " + block.split("\n")[0],
|
|
264
|
+
);
|
|
265
|
+
assert.ok(
|
|
266
|
+
block.includes("hierarchical cluster summary text"),
|
|
267
|
+
"cluster body uses raptorSummary",
|
|
268
|
+
);
|
|
269
|
+
assert.ok(
|
|
270
|
+
!/Key files:/.test(block),
|
|
271
|
+
"cluster hit has no Key files line even when filesModified is non-empty",
|
|
272
|
+
);
|
|
273
|
+
});
|
|
@@ -15,8 +15,10 @@ import {
|
|
|
15
15
|
expandLeafDescendants,
|
|
16
16
|
deduplicateMultilevelHits,
|
|
17
17
|
multilevelRetrieval,
|
|
18
|
+
buildChildParentIndex,
|
|
18
19
|
type MultilevelHit,
|
|
19
20
|
} from "./multilevel.js";
|
|
21
|
+
import type { RaptorTree, RaptorNode } from "./tree.js";
|
|
20
22
|
import type { EngineMessage } from "../../types.js";
|
|
21
23
|
|
|
22
24
|
function msg(text: string): EngineMessage {
|
|
@@ -276,3 +278,48 @@ test("multilevelRetrieval with leafExpansion=false skips leaf expansion", () =>
|
|
|
276
278
|
assert.ok(h.score >= 0, "hit score should be non-negative");
|
|
277
279
|
}
|
|
278
280
|
});
|
|
281
|
+
|
|
282
|
+
// ── test: buildChildParentIndex matches linear-scan parent ────────────────────
|
|
283
|
+
|
|
284
|
+
test("buildChildParentIndex (multilevel): index-derived parent matches linear-scan for each leaf", () => {
|
|
285
|
+
// Hand-built tree: 8 leaves under 2 level-1 nodes under 1 root.
|
|
286
|
+
const r1_0: RaptorNode = {
|
|
287
|
+
id: "r1_0", level: 1, parentId: null,
|
|
288
|
+
children: ["leaf_0", "leaf_1", "leaf_2", "leaf_3"],
|
|
289
|
+
summary: "cluster A", embedding: [1, 0, 0],
|
|
290
|
+
qualityMarker: "low", tokenEstimate: 10,
|
|
291
|
+
};
|
|
292
|
+
const r1_1: RaptorNode = {
|
|
293
|
+
id: "r1_1", level: 1, parentId: null,
|
|
294
|
+
children: ["leaf_4", "leaf_5", "leaf_6", "leaf_7"],
|
|
295
|
+
summary: "cluster B", embedding: [0, 1, 0],
|
|
296
|
+
qualityMarker: "low", tokenEstimate: 10,
|
|
297
|
+
};
|
|
298
|
+
const root: RaptorNode = {
|
|
299
|
+
id: "root", level: 2, parentId: null,
|
|
300
|
+
children: ["leaf_0", "leaf_1", "leaf_2", "leaf_3",
|
|
301
|
+
"leaf_4", "leaf_5", "leaf_6", "leaf_7"],
|
|
302
|
+
summary: "root", embedding: [0.5, 0.5, 0],
|
|
303
|
+
qualityMarker: "low", tokenEstimate: 20,
|
|
304
|
+
};
|
|
305
|
+
const nodes = new Map<string, RaptorNode>([
|
|
306
|
+
["r1_0", r1_0], ["r1_1", r1_1], ["root", root],
|
|
307
|
+
]);
|
|
308
|
+
const tree: RaptorTree = { nodes, rootId: "root", levels: 3, timedOut: false };
|
|
309
|
+
|
|
310
|
+
const index = buildChildParentIndex(tree);
|
|
311
|
+
const leafIds = ["leaf_0", "leaf_1", "leaf_2", "leaf_3",
|
|
312
|
+
"leaf_4", "leaf_5", "leaf_6", "leaf_7"];
|
|
313
|
+
|
|
314
|
+
for (const lid of leafIds) {
|
|
315
|
+
const linearParent = [...tree.nodes.values()].find((n) =>
|
|
316
|
+
n.children.includes(lid),
|
|
317
|
+
);
|
|
318
|
+
const indexParent = index.get(lid);
|
|
319
|
+
assert.equal(
|
|
320
|
+
indexParent?.id ?? null,
|
|
321
|
+
linearParent?.id ?? null,
|
|
322
|
+
`leaf ${lid}: index parent (${indexParent?.id}) != linear parent (${linearParent?.id})`,
|
|
323
|
+
);
|
|
324
|
+
}
|
|
325
|
+
});
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
import type { Embedder, Vector } from "../../embedder.js";
|
|
15
15
|
import { cosineSimilarity } from "../../embedder.js";
|
|
16
16
|
import { mmrRerank } from "../mmr.js";
|
|
17
|
-
import type { RaptorTree } from "./tree.js";
|
|
17
|
+
import type { RaptorTree, RaptorNode } from "./tree.js";
|
|
18
18
|
import { leafDescendants } from "./retrieval.js";
|
|
19
19
|
|
|
20
20
|
// ── S42A-1: Types ──────────────────────────────────────────────────────────
|
|
@@ -116,6 +116,17 @@ export function scoreTreeLevels(
|
|
|
116
116
|
|
|
117
117
|
// ── S42A-3: Leaf expansion ─────────────────────────────────────────────────
|
|
118
118
|
|
|
119
|
+
/** Build a reverse index: childId → parent RaptorNode. O(N). */
|
|
120
|
+
export function buildChildParentIndex(tree: RaptorTree): Map<string, RaptorNode> {
|
|
121
|
+
const idx = new Map<string, RaptorNode>();
|
|
122
|
+
for (const node of tree.nodes.values()) {
|
|
123
|
+
for (const cid of node.children) {
|
|
124
|
+
if (!idx.has(cid)) idx.set(cid, node);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return idx;
|
|
128
|
+
}
|
|
129
|
+
|
|
119
130
|
/**
|
|
120
131
|
* Given a set of cluster-level hits, expand each one to include its leaf
|
|
121
132
|
* descendants. Deduplicates: if a leaf is already present as a direct hit,
|
|
@@ -131,6 +142,7 @@ export function expandLeafDescendants(
|
|
|
131
142
|
): MultilevelHit[] {
|
|
132
143
|
const weights = levelWeights ?? DEFAULT_LEVEL_WEIGHTS;
|
|
133
144
|
const existingIds = new Set(hits.map((h) => h.nodeId));
|
|
145
|
+
const childParentIdx = buildChildParentIndex(tree);
|
|
134
146
|
const expanded: MultilevelHit[] = [];
|
|
135
147
|
|
|
136
148
|
for (const hit of hits) {
|
|
@@ -149,20 +161,18 @@ export function expandLeafDescendants(
|
|
|
149
161
|
const rawLeafIds = leafDescendants(node, tree);
|
|
150
162
|
|
|
151
163
|
// Sort by cosine similarity to query, cap at maxPerCluster.
|
|
164
|
+
// Skip leaves with no parent (orphan) — they have no reliable embedding.
|
|
152
165
|
const leafHits: MultilevelHit[] = rawLeafIds
|
|
153
166
|
.map((lid) => {
|
|
154
|
-
|
|
155
|
-
const parent = [...tree.nodes.values()].find((n) =>
|
|
156
|
-
n.children.includes(lid),
|
|
157
|
-
);
|
|
167
|
+
const parent = childParentIdx.get(lid);
|
|
158
168
|
const sim = parent
|
|
159
169
|
? cosineSimilarity(queryVector, parent.embedding)
|
|
160
|
-
:
|
|
170
|
+
: -Infinity; // orphan: excluded
|
|
161
171
|
return { lid, sim, parent };
|
|
162
172
|
})
|
|
173
|
+
.filter((l) => l.sim > -Infinity && !existingIds.has(l.lid))
|
|
163
174
|
.sort((a, b) => b.sim - a.sim)
|
|
164
175
|
.slice(0, maxPerCluster)
|
|
165
|
-
.filter((l) => !existingIds.has(l.lid))
|
|
166
176
|
.map((l) => {
|
|
167
177
|
existingIds.add(l.lid);
|
|
168
178
|
const rawScore = l.sim;
|
|
@@ -174,7 +184,7 @@ export function expandLeafDescendants(
|
|
|
174
184
|
isLeaf: true,
|
|
175
185
|
leafIds: [l.lid],
|
|
176
186
|
summary: "",
|
|
177
|
-
embedding: l.parent
|
|
187
|
+
embedding: l.parent!.embedding, // parent guaranteed non-null here
|
|
178
188
|
} as MultilevelHit;
|
|
179
189
|
});
|
|
180
190
|
|
|
@@ -158,6 +158,65 @@ test("tree respects the budget: a tiny budget forces an extractive fallback root
|
|
|
158
158
|
assert.ok(tree.nodes.has("r99_0"));
|
|
159
159
|
});
|
|
160
160
|
|
|
161
|
+
// --- extractiveFallbackRoot returns levels: 100 ------------------------------
|
|
162
|
+
|
|
163
|
+
test("extractiveFallbackRoot returns levels: 100 (via zero budget)", () => {
|
|
164
|
+
const leaves = makeLeaves(50);
|
|
165
|
+
const tree = buildRaptorTree(leaves, {
|
|
166
|
+
embedder: new TrigramEmbedder(),
|
|
167
|
+
budgetMs: 0, // forces extractive fallback on first within() check
|
|
168
|
+
clustersPerLevel: 4,
|
|
169
|
+
});
|
|
170
|
+
assert.equal(tree.timedOut, true);
|
|
171
|
+
assert.equal(tree.levels, 100, "extractive fallback root must report levels: 100");
|
|
172
|
+
assert.ok(tree.rootId, "fallback root has a rootId");
|
|
173
|
+
const root = tree.nodes.get(tree.rootId!);
|
|
174
|
+
assert.ok(root, "fallback root node exists in nodes map");
|
|
175
|
+
assert.equal(root!.level, 99, "fallback root node level is 99");
|
|
176
|
+
assert.equal(root!.parentId, null, "fallback root parentId is null");
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
// --- parentId population on a multi-level tree --------------------------------
|
|
180
|
+
|
|
181
|
+
test("buildRaptorTree populates parentId for non-root internal nodes, root keeps null", () => {
|
|
182
|
+
const embedder = new TrigramEmbedder();
|
|
183
|
+
// >= 10 leaves with clustersPerLevel small enough to produce 2 levels
|
|
184
|
+
// of internal nodes (level-1 cluster nodes + level-2 root via collapse).
|
|
185
|
+
const leaves = makeLeaves(20);
|
|
186
|
+
const tree = buildRaptorTree(leaves, { embedder, clustersPerLevel: 4 });
|
|
187
|
+
|
|
188
|
+
// Must have at least 2 levels of internal nodes.
|
|
189
|
+
assert.ok(tree.levels >= 2, `expected >= 2 levels, got ${tree.levels}`);
|
|
190
|
+
assert.ok(tree.rootId, "tree must have a root");
|
|
191
|
+
|
|
192
|
+
// The root keeps parentId null.
|
|
193
|
+
const root = tree.nodes.get(tree.rootId!);
|
|
194
|
+
assert.ok(root, "root node in map");
|
|
195
|
+
assert.equal(root!.parentId, null, "root parentId must be null");
|
|
196
|
+
|
|
197
|
+
// Every non-root internal node must have a non-null parentId pointing to
|
|
198
|
+
// another node in the tree (its parent).
|
|
199
|
+
let nonRootCount = 0;
|
|
200
|
+
for (const node of tree.nodes.values()) {
|
|
201
|
+
if (node.id === tree.rootId) continue;
|
|
202
|
+
nonRootCount++;
|
|
203
|
+
assert.ok(
|
|
204
|
+
node.parentId !== null,
|
|
205
|
+
`non-root node ${node.id} must have non-null parentId`,
|
|
206
|
+
);
|
|
207
|
+
assert.ok(
|
|
208
|
+
tree.nodes.has(node.parentId!),
|
|
209
|
+
`parentId ${node.parentId} of node ${node.id} must exist in tree`,
|
|
210
|
+
);
|
|
211
|
+
assert.notEqual(
|
|
212
|
+
node.parentId,
|
|
213
|
+
node.id,
|
|
214
|
+
`node ${node.id} must not be its own parent`,
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
assert.ok(nonRootCount > 0, "tree must have at least one non-root internal node");
|
|
218
|
+
});
|
|
219
|
+
|
|
161
220
|
// --- retrieval: staged expansion returns leaf ids ---------------------------
|
|
162
221
|
|
|
163
222
|
test("stagedExpansion returns diversified leaf ids for a query", () => {
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* retrieval.test.ts — unit tests for the reverse-index parent lookup.
|
|
3
|
+
*
|
|
4
|
+
* Verifies that buildChildParentIndex (retrieval.ts) produces the same
|
|
5
|
+
* parent for each leaf as the old linear-scan semantics:
|
|
6
|
+
* [...tree.nodes.values()].find(n => n.children.includes(lid))
|
|
7
|
+
*
|
|
8
|
+
* Uses a hand-built tree with a known structure so the comparison is
|
|
9
|
+
* deterministic and independent of the tree builder.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { test } from "node:test";
|
|
13
|
+
import assert from "node:assert/strict";
|
|
14
|
+
import { buildChildParentIndex } from "./retrieval.js";
|
|
15
|
+
import type { RaptorTree, RaptorNode } from "./tree.js";
|
|
16
|
+
|
|
17
|
+
/** Build a minimal hand-crafted RaptorTree with 2 levels of internal nodes. */
|
|
18
|
+
function handBuiltTree(): RaptorTree {
|
|
19
|
+
// 8 leaves (leaf_0..leaf_7) under 2 level-1 nodes, under 1 root.
|
|
20
|
+
const r1_0: RaptorNode = {
|
|
21
|
+
id: "r1_0",
|
|
22
|
+
level: 1,
|
|
23
|
+
parentId: null, // will be set by builder in production, but not needed here
|
|
24
|
+
children: ["leaf_0", "leaf_1", "leaf_2", "leaf_3"],
|
|
25
|
+
summary: "cluster A",
|
|
26
|
+
embedding: [1, 0, 0],
|
|
27
|
+
qualityMarker: "low",
|
|
28
|
+
tokenEstimate: 10,
|
|
29
|
+
};
|
|
30
|
+
const r1_1: RaptorNode = {
|
|
31
|
+
id: "r1_1",
|
|
32
|
+
level: 1,
|
|
33
|
+
parentId: null,
|
|
34
|
+
children: ["leaf_4", "leaf_5", "leaf_6", "leaf_7"],
|
|
35
|
+
summary: "cluster B",
|
|
36
|
+
embedding: [0, 1, 0],
|
|
37
|
+
qualityMarker: "low",
|
|
38
|
+
tokenEstimate: 10,
|
|
39
|
+
};
|
|
40
|
+
const root: RaptorNode = {
|
|
41
|
+
id: "root",
|
|
42
|
+
level: 2,
|
|
43
|
+
parentId: null,
|
|
44
|
+
children: [
|
|
45
|
+
"leaf_0", "leaf_1", "leaf_2", "leaf_3",
|
|
46
|
+
"leaf_4", "leaf_5", "leaf_6", "leaf_7",
|
|
47
|
+
],
|
|
48
|
+
summary: "root summary",
|
|
49
|
+
embedding: [0.5, 0.5, 0],
|
|
50
|
+
qualityMarker: "low",
|
|
51
|
+
tokenEstimate: 20,
|
|
52
|
+
};
|
|
53
|
+
const nodes = new Map<string, RaptorNode>([
|
|
54
|
+
["r1_0", r1_0],
|
|
55
|
+
["r1_1", r1_1],
|
|
56
|
+
["root", root],
|
|
57
|
+
]);
|
|
58
|
+
return { nodes, rootId: "root", levels: 3, timedOut: false };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
test("buildChildParentIndex: index-derived parent matches linear-scan parent for each leaf", () => {
|
|
62
|
+
const tree = handBuiltTree();
|
|
63
|
+
const leafIds = [
|
|
64
|
+
"leaf_0", "leaf_1", "leaf_2", "leaf_3",
|
|
65
|
+
"leaf_4", "leaf_5", "leaf_6", "leaf_7",
|
|
66
|
+
];
|
|
67
|
+
|
|
68
|
+
const index = buildChildParentIndex(tree);
|
|
69
|
+
|
|
70
|
+
for (const lid of leafIds) {
|
|
71
|
+
// Old linear-scan semantics: find the first node whose children include lid.
|
|
72
|
+
const linearParent = [...tree.nodes.values()].find((n) =>
|
|
73
|
+
n.children.includes(lid),
|
|
74
|
+
);
|
|
75
|
+
|
|
76
|
+
// Index-derived parent.
|
|
77
|
+
const indexParent = index.get(lid);
|
|
78
|
+
|
|
79
|
+
// Both must agree.
|
|
80
|
+
assert.equal(
|
|
81
|
+
indexParent?.id ?? null,
|
|
82
|
+
linearParent?.id ?? null,
|
|
83
|
+
`leaf ${lid}: index parent (${indexParent?.id}) != linear parent (${linearParent?.id})`,
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
test("buildChildParentIndex: first writer wins (no overwrite for shared leaf)", () => {
|
|
89
|
+
// If two internal nodes both list the same leaf id in their children, the
|
|
90
|
+
// index keeps the FIRST one encountered — matching the find() semantics
|
|
91
|
+
// which also returns the first match.
|
|
92
|
+
const r1_0: RaptorNode = {
|
|
93
|
+
id: "r1_0", level: 1, parentId: null,
|
|
94
|
+
children: ["leaf_0", "leaf_1"],
|
|
95
|
+
summary: "A", embedding: [1, 0], qualityMarker: "low", tokenEstimate: 5,
|
|
96
|
+
};
|
|
97
|
+
const r1_1: RaptorNode = {
|
|
98
|
+
id: "r1_1", level: 1, parentId: null,
|
|
99
|
+
children: ["leaf_0", "leaf_2"], // leaf_0 shared with r1_0
|
|
100
|
+
summary: "B", embedding: [0, 1], qualityMarker: "low", tokenEstimate: 5,
|
|
101
|
+
};
|
|
102
|
+
const nodes = new Map<string, RaptorNode>([["r1_0", r1_0], ["r1_1", r1_1]]);
|
|
103
|
+
const tree: RaptorTree = { nodes, rootId: null, levels: 2, timedOut: false };
|
|
104
|
+
|
|
105
|
+
const index = buildChildParentIndex(tree);
|
|
106
|
+
|
|
107
|
+
// leaf_0 appears in both r1_0 and r1_1. The index and find() both return
|
|
108
|
+
// whichever comes first in iteration order.
|
|
109
|
+
const linearParent = [...tree.nodes.values()].find((n) =>
|
|
110
|
+
n.children.includes("leaf_0"),
|
|
111
|
+
);
|
|
112
|
+
const indexParent = index.get("leaf_0");
|
|
113
|
+
assert.equal(
|
|
114
|
+
indexParent?.id ?? null,
|
|
115
|
+
linearParent?.id ?? null,
|
|
116
|
+
"first-writer wins: index and linear scan agree on shared leaf",
|
|
117
|
+
);
|
|
118
|
+
});
|
|
@@ -32,6 +32,17 @@ function isLeafId(id: string, tree: RaptorTree): boolean {
|
|
|
32
32
|
return !tree.nodes.has(id);
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
+
/** Build a reverse index: childId → parent RaptorNode. O(N). */
|
|
36
|
+
export function buildChildParentIndex(tree: RaptorTree): Map<string, RaptorNode> {
|
|
37
|
+
const idx = new Map<string, RaptorNode>();
|
|
38
|
+
for (const node of tree.nodes.values()) {
|
|
39
|
+
for (const cid of node.children) {
|
|
40
|
+
if (!idx.has(cid)) idx.set(cid, node);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return idx;
|
|
44
|
+
}
|
|
45
|
+
|
|
35
46
|
/** All leaf (raw) ids reachable beneath a node via BFS. */
|
|
36
47
|
export function leafDescendants(node: RaptorNode, tree: RaptorTree): string[] {
|
|
37
48
|
const out: string[] = [];
|
|
@@ -81,13 +92,14 @@ export function stagedExpansion(
|
|
|
81
92
|
.slice(0, topM)
|
|
82
93
|
.map((s) => s.node);
|
|
83
94
|
|
|
84
|
-
// 3. BFS to leaves from those anchors.
|
|
95
|
+
// 3. BFS to leaves from those anchors, using a reverse child→parent index.
|
|
96
|
+
const childParentIdx = buildChildParentIndex(tree);
|
|
85
97
|
const leaves = new Map<string, RaptorNode>();
|
|
86
98
|
for (const a of anchors) {
|
|
87
99
|
for (const lid of leafDescendants(a, tree)) {
|
|
88
100
|
// Represent each leaf by its nearest internal parent so we can score it.
|
|
89
101
|
// (The leaf's own centroid is stored on the level-0 node that wraps it.)
|
|
90
|
-
const parent =
|
|
102
|
+
const parent = childParentIdx.get(lid);
|
|
91
103
|
if (parent) leaves.set(lid, parent);
|
|
92
104
|
}
|
|
93
105
|
}
|