pi-mega-compact 0.8.21 → 0.8.23
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/LICENSE +6 -2
- package/README.md +1 -1
- package/dist/extensions/dashboard-server/dashboard-client-core.js +201 -0
- package/dist/extensions/dashboard-server/dashboard-client-game.js +241 -0
- package/dist/extensions/dashboard-server/dashboard-client-repos.js +212 -0
- package/dist/extensions/dashboard-server/dashboard-client.js +19 -0
- package/dist/extensions/dashboard-server/html.js +2 -621
- package/dist/extensions/dashboard-server/routes-core.js +62 -0
- package/dist/extensions/dashboard-server/routes-game.js +323 -0
- package/dist/extensions/dashboard-server/routes-repo.js +170 -0
- package/dist/extensions/dashboard-server/routes-sessions.js +159 -0
- package/dist/extensions/dashboard-server/routes.js +10 -0
- package/dist/extensions/dashboard-server/server.js +26 -623
- package/dist/extensions/mega-commands.js +4 -3
- package/dist/extensions/mega-events/agent-handlers.js +2 -1
- package/dist/extensions/mega-events/compact-handlers.js +26 -0
- package/dist/extensions/mega-events/session-handlers.js +2 -1
- package/dist/extensions/mega-pipeline/compact.js +3 -2
- package/dist/extensions/mega-runtime/state.js +7 -7
- package/dist/src/dedup/raptor/multilevel.js +172 -0
- package/dist/src/dedup/raptor/multilevel.test.js +203 -0
- package/dist/src/dedup/raptor/promote.test.js +5 -5
- package/dist/src/dedup/raptor/retrieval.js +1 -1
- package/dist/src/dedup/sprint12.test.js +7 -7
- package/dist/src/dedup-engine.test.js +29 -29
- package/dist/src/e2e.test.js +38 -38
- package/dist/src/engine.js +3 -3
- package/dist/src/engine.test.js +6 -6
- package/dist/src/importance.js +197 -0
- package/dist/src/importance.test.js +372 -0
- package/dist/src/ratio.bench.test.js +18 -18
- package/dist/src/recall.js +6 -5
- package/dist/src/recall.test.js +85 -27
- package/dist/src/sprint14.test.js +2 -2
- package/dist/src/store/migrate.test.js +5 -5
- package/dist/src/store/sprint10.test.js +5 -5
- package/dist/src/store/sqlite/global-index.js +5 -174
- package/dist/src/store/sqlite/global-sessions.js +190 -0
- package/dist/src/vector-read.js +168 -0
- package/dist/src/vector-search.js +191 -0
- package/dist/src/vectorStore.js +10 -297
- package/dist/src/vectorStore.test.js +32 -32
- package/extensions/dashboard-server/dashboard-client-core.ts +202 -0
- package/extensions/dashboard-server/dashboard-client-game.ts +242 -0
- package/extensions/dashboard-server/dashboard-client-repos.ts +213 -0
- package/extensions/dashboard-server/dashboard-client.ts +21 -0
- package/extensions/dashboard-server/html.ts +2 -621
- package/extensions/dashboard-server/routes-core.ts +113 -0
- package/extensions/dashboard-server/routes-game.ts +386 -0
- package/extensions/dashboard-server/routes-repo.ts +212 -0
- package/extensions/dashboard-server/routes-sessions.ts +195 -0
- package/extensions/dashboard-server/routes.ts +13 -0
- package/extensions/dashboard-server/server.ts +37 -700
- package/extensions/mega-commands.ts +4 -3
- package/extensions/mega-events/agent-handlers.ts +2 -1
- package/extensions/mega-events/compact-handlers.ts +28 -0
- package/extensions/mega-events/session-handlers.ts +2 -1
- package/extensions/mega-pipeline/compact.ts +3 -2
- package/extensions/mega-runtime/state.ts +7 -7
- package/extensions/openclaw-mega-compact.ts +2 -2
- package/package.json +2 -2
- package/src/dedup/raptor/multilevel.test.ts +278 -0
- package/src/dedup/raptor/multilevel.ts +246 -0
- package/src/dedup/raptor/promote.test.ts +5 -5
- package/src/dedup/raptor/retrieval.ts +1 -1
- package/src/dedup/sprint12.test.ts +7 -7
- package/src/dedup-engine.test.ts +30 -30
- package/src/e2e.test.ts +38 -38
- package/src/engine.test.ts +6 -6
- package/src/engine.ts +3 -3
- package/src/importance.test.ts +538 -0
- package/src/importance.ts +312 -0
- package/src/ratio.bench.test.ts +18 -18
- package/src/recall.test.ts +101 -29
- package/src/recall.ts +9 -9
- package/src/sprint14.test.ts +2 -2
- package/src/store/migrate.test.ts +5 -5
- package/src/store/sprint10.test.ts +5 -5
- package/src/store/sqlite/global-index.ts +18 -290
- package/src/store/sqlite/global-sessions.ts +291 -0
- package/src/vector-read.ts +237 -0
- package/src/vector-search.ts +231 -0
- package/src/vectorStore.test.ts +32 -32
- package/src/vectorStore.ts +29 -356
|
@@ -14,6 +14,7 @@ import { decompressSmart } from "../src/store/compression.js";
|
|
|
14
14
|
import { loadMetrics, fpRate, p95, defaultMetricsPath } from "../src/monitoring.js";
|
|
15
15
|
import { type MegaRuntime, C, recentUserQuery } from "./mega-runtime.js";
|
|
16
16
|
import { runCompact, doRecall, doRecallAsync } from "./mega-pipeline.js";
|
|
17
|
+
import { vectorStats, vectorRepoStats, vectorDataInvariant } from "../src/vectorStore.js";
|
|
17
18
|
import type { MegaConfig } from "./mega-config.js";
|
|
18
19
|
|
|
19
20
|
/** Resolve a checkpoint by id (or "recent"/"last") from this session's store. */
|
|
@@ -95,9 +96,9 @@ export function registerCommands(pi: ExtensionAPI, runtime: MegaRuntime, config:
|
|
|
95
96
|
const pct = usage?.percent != null ? `${usage.percent}%` : "n/a";
|
|
96
97
|
const tokens = usage?.tokens != null ? `${usage.tokens} tok` : "n/a";
|
|
97
98
|
const sid = normalizeSessionId(ctx.sessionManager.getSessionId());
|
|
98
|
-
const st = runtime.store
|
|
99
|
-
const repo = runtime.store
|
|
100
|
-
const di = runtime.store
|
|
99
|
+
const st = vectorStats(runtime.store, sid);
|
|
100
|
+
const repo = vectorRepoStats(runtime.store);
|
|
101
|
+
const di = vectorDataInvariant(runtime.store);
|
|
101
102
|
const fmtB = (b: number) =>
|
|
102
103
|
b >= 1_048_576 ? `${(b / 1_048_576).toFixed(1)} MiB` :
|
|
103
104
|
b >= 1024 ? `${(b / 1024).toFixed(1)} KiB` : `${b} B`;
|
|
@@ -20,6 +20,7 @@ import { isMegaCache } from "../../src/game/scoring.js";
|
|
|
20
20
|
import { resolveRepoRoot } from "../mega-config.js";
|
|
21
21
|
import { classifyError } from "./error-classifier.js";
|
|
22
22
|
import { safeSendUserMessage } from "./send-safe.js";
|
|
23
|
+
import { vectorStats } from "../../src/vectorStore.js";
|
|
23
24
|
|
|
24
25
|
/** Register agent/turn tracking event handlers. */
|
|
25
26
|
export function registerAgentHandlers(
|
|
@@ -244,7 +245,7 @@ export function registerAgentHandlers(
|
|
|
244
245
|
try {
|
|
245
246
|
if (runtime.getCachedGameState().game_mode_on) {
|
|
246
247
|
const repo = resolveRepoRoot(ctx.cwd) ?? runtime.currentStateDir;
|
|
247
|
-
const st = runtime.store
|
|
248
|
+
const st = vectorStats(runtime.store, runtime.rt.sessionId);
|
|
248
249
|
const cachePct = st.dedupHitRate * 100;
|
|
249
250
|
const modelId = runtime.currentModel?.modelId ?? "unknown";
|
|
250
251
|
recordScore(runtime.currentStateDir, {
|
|
@@ -110,6 +110,34 @@ export function registerCompactHandlers(
|
|
|
110
110
|
activeAgents: runtime.activeAgents,
|
|
111
111
|
});
|
|
112
112
|
if (!config.auto) return {}; // let pi run its own native compaction
|
|
113
|
+
|
|
114
|
+
// S38.5: COMPACT-DEDUP RACE GUARD — pi's _runAutoCompaction fires
|
|
115
|
+
// session_before_compact from within the agent loop (after agent_end,
|
|
116
|
+
// _handlePostAgentRun → _checkCompaction → _runAutoCompaction). If a
|
|
117
|
+
// compaction just completed (within the cooldown window), pi's
|
|
118
|
+
// prepareCompaction may still see the last entry as a compaction but
|
|
119
|
+
// the extension's session_compact handler hasn't been called yet, OR
|
|
120
|
+
// the setTimeout deferred ctx.compact() from the agent_end handler is
|
|
121
|
+
// about to race. Skip the durable trim and let pi run its own compact
|
|
122
|
+
// (or no-op if the branch is already compacted). Matches the cooldown
|
|
123
|
+
// in agent-handlers.ts so both call sites are consistent.
|
|
124
|
+
const cooldownMs = config.raceGuardStrict ? 30_000 : 10_000;
|
|
125
|
+
const sinceCompact = Date.now() - (runtime.rt.lastNativeCompactAt ?? 0);
|
|
126
|
+
if (sinceCompact < cooldownMs) {
|
|
127
|
+
runtime.logger.info("before-compact-skip-recent", {
|
|
128
|
+
sessionId: runtime.rt.sessionId,
|
|
129
|
+
reason: event.reason,
|
|
130
|
+
sinceCompactMs: sinceCompact,
|
|
131
|
+
cooldownMs,
|
|
132
|
+
});
|
|
133
|
+
runtime.diagBeforeCompactSupplied++;
|
|
134
|
+
const fb = fallbackCompaction(event);
|
|
135
|
+
if (fb) {
|
|
136
|
+
return { compaction: fb.compaction };
|
|
137
|
+
}
|
|
138
|
+
return {};
|
|
139
|
+
}
|
|
140
|
+
|
|
113
141
|
try {
|
|
114
142
|
const result = driveNativeCompaction(event, runtime, config);
|
|
115
143
|
if (result && result.compaction.summary?.trim()) {
|
|
@@ -17,6 +17,7 @@ import {
|
|
|
17
17
|
doRecallAsync,
|
|
18
18
|
} from "../mega-pipeline.js";
|
|
19
19
|
import { recallMemoriesAndInline } from "../../src/recall.js";
|
|
20
|
+
import { vectorStats } from "../../src/vectorStore.js";
|
|
20
21
|
import type { MegaConfig } from "../mega-config.js";
|
|
21
22
|
|
|
22
23
|
/** Register session lifecycle event handlers. */
|
|
@@ -50,7 +51,7 @@ export function registerSessionHandlers(
|
|
|
50
51
|
if (config.autoInline) {
|
|
51
52
|
const sid = normalizeSessionId(ctx.sessionManager.getSessionId());
|
|
52
53
|
const query = recentUserQuery(ctx);
|
|
53
|
-
if (query && runtime.store
|
|
54
|
+
if (query && vectorStats(runtime.store, sid).checkpointCount > 0) {
|
|
54
55
|
// S17: use the async variant on resume so cross-repo HNSW recall can
|
|
55
56
|
// augment when this repo's store is thin. session_start is an async-safe
|
|
56
57
|
// point (unlike the mid-turn context handler, which stays sync).
|
|
@@ -27,6 +27,7 @@ import { runRaptor } from "../../src/dedup/raptor/index.js";
|
|
|
27
27
|
import { loadDedupConfig } from "../../src/config/dedup.js";
|
|
28
28
|
import { upsertEmbedding as indexUpsertEmbedding } from "../../src/store/vectorIndex.js";
|
|
29
29
|
import { runMemoryReview } from "./memory-review.js";
|
|
30
|
+
import { vectorList } from "../../src/vectorStore.js";
|
|
30
31
|
|
|
31
32
|
export type RunCompactResult =
|
|
32
33
|
| { skipped: true }
|
|
@@ -212,7 +213,7 @@ function doCompact(
|
|
|
212
213
|
if (config.raptorEnabled && !result.deduped) {
|
|
213
214
|
try {
|
|
214
215
|
const dd = loadDedupConfig();
|
|
215
|
-
const all = runtime.store
|
|
216
|
+
const all = vectorList(runtime.store, sid);
|
|
216
217
|
const leaves = all.map((cp) => ({
|
|
217
218
|
id: cp.checkpointId,
|
|
218
219
|
messages: [],
|
|
@@ -248,7 +249,7 @@ function doCompact(
|
|
|
248
249
|
// Non-fatal: a WASM init failure degrades to the sync scan silently.
|
|
249
250
|
if (!result.deduped) {
|
|
250
251
|
try {
|
|
251
|
-
const all = runtime.store
|
|
252
|
+
const all = vectorList(runtime.store, sid);
|
|
252
253
|
const latest = all.find((cp) => cp.checkpointId === result.checkpointId);
|
|
253
254
|
if (latest?.embedding) {
|
|
254
255
|
void indexUpsertEmbedding(
|
|
@@ -14,7 +14,7 @@ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
|
14
14
|
import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
15
15
|
import { join } from "node:path";
|
|
16
16
|
import { appendFileSync, mkdirSync } from "node:fs";
|
|
17
|
-
import { VectorStore } from "../../src/vectorStore.js";
|
|
17
|
+
import { VectorStore, vectorStats, vectorRepoStats, vectorDataInvariant } from "../../src/vectorStore.js";
|
|
18
18
|
import { toEngineMessages } from "../../src/adapt.js";
|
|
19
19
|
import { normalizeSessionId } from "../../src/store.js";
|
|
20
20
|
import { Logger } from "../../src/log.js";
|
|
@@ -365,8 +365,8 @@ export class MegaRuntime {
|
|
|
365
365
|
// never break the per-repo compaction path. Runs only on repo-switch
|
|
366
366
|
// (this branch), so it's infrequent — not per-context-event.
|
|
367
367
|
try {
|
|
368
|
-
const repo = this.store
|
|
369
|
-
const di = this.store
|
|
368
|
+
const repo = vectorRepoStats(this.store);
|
|
369
|
+
const di = vectorDataInvariant(this.store);
|
|
370
370
|
const root = key !== dir ? key : (resolveRepoRoot(cwd ?? dir) ?? dir);
|
|
371
371
|
upsertRepoRegistry({
|
|
372
372
|
repoRoot: root,
|
|
@@ -404,9 +404,9 @@ export class MegaRuntime {
|
|
|
404
404
|
return;
|
|
405
405
|
}
|
|
406
406
|
const perfT0 = performance.now();
|
|
407
|
-
const st = this.store
|
|
408
|
-
const repo = this.store
|
|
409
|
-
const di = this.store
|
|
407
|
+
const st = vectorStats(this.store, this.rt.sessionId);
|
|
408
|
+
const repo = vectorRepoStats(this.store);
|
|
409
|
+
const di = vectorDataInvariant(this.store);
|
|
410
410
|
// Live + store-wide cache-hit / compaction counters for the dashboard.
|
|
411
411
|
const ds = getDedupStats(this.currentStateDir);
|
|
412
412
|
const cacheHitsTotal = ds.deduped + getRecallInjected(this.currentStateDir);
|
|
@@ -555,7 +555,7 @@ export class MegaRuntime {
|
|
|
555
555
|
total: getCompactCount(this.currentStateDir),
|
|
556
556
|
},
|
|
557
557
|
timeSaved: {
|
|
558
|
-
compact: { sessionSec: sec(this.rt.tokensSaved), totalSec: sec(this.store
|
|
558
|
+
compact: { sessionSec: sec(this.rt.tokensSaved), totalSec: sec(vectorRepoStats(this.store).tokensSaved) },
|
|
559
559
|
cacheHit: { sessionSec: sec(this.rt.cacheHitTokens), totalSec: sec(cacheHitsTotalTokens) },
|
|
560
560
|
},
|
|
561
561
|
model,
|
|
@@ -22,7 +22,7 @@ import {
|
|
|
22
22
|
type CompactResult,
|
|
23
23
|
} from "../src/engine.js";
|
|
24
24
|
import { recallAndInline, recallMemoriesAndInline, type RecallInjectResult } from "../src/recall.js";
|
|
25
|
-
import { VectorStore } from "../src/vectorStore.js";
|
|
25
|
+
import { VectorStore, vectorStats } from "../src/vectorStore.js";
|
|
26
26
|
import type { EngineMessage } from "../src/types.js";
|
|
27
27
|
|
|
28
28
|
// ---------------------------------------------------------------------------
|
|
@@ -260,7 +260,7 @@ export default definePluginEntry({
|
|
|
260
260
|
const sessionId = (args as Record<string, string>)?.sessionId ?? "global";
|
|
261
261
|
|
|
262
262
|
try {
|
|
263
|
-
const stats = store
|
|
263
|
+
const stats = vectorStats(store, sessionId);
|
|
264
264
|
const parts: string[] = [
|
|
265
265
|
`**Mega Compact Status**`,
|
|
266
266
|
`Session: ${sessionId}`,
|
package/package.json
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-mega-compact",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.23",
|
|
4
4
|
"description": "Layered, local, vector-backed context compressor for pi — supersede/collapse/cluster compaction with deduped inline recall.",
|
|
5
5
|
"type": "module",
|
|
6
|
-
"license": "BSD-
|
|
6
|
+
"license": "BSD-3-Clause",
|
|
7
7
|
"author": "TheArchitectit",
|
|
8
8
|
"homepage": "https://github.com/TheArchitectit/pi-mega-compact",
|
|
9
9
|
"repository": {
|
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* multilevel.test.ts — hermetic unit tests for S42A multi-level RAPTOR retrieval.
|
|
3
|
+
*
|
|
4
|
+
* Tests the scoreTreeLevels → expandLeafDescendants → deduplicateMultilevelHits
|
|
5
|
+
* → multilevelRetrieval pipeline. No network, no live store — uses TrigramEmbedder
|
|
6
|
+
* and synthetic RaptorTrees built from makeLeaves().
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { test } from "node:test";
|
|
10
|
+
import assert from "node:assert/strict";
|
|
11
|
+
import { TrigramEmbedder } from "../../embedder.js";
|
|
12
|
+
import { buildRaptorTree, type Leaf } from "./tree.js";
|
|
13
|
+
import {
|
|
14
|
+
scoreTreeLevels,
|
|
15
|
+
expandLeafDescendants,
|
|
16
|
+
deduplicateMultilevelHits,
|
|
17
|
+
multilevelRetrieval,
|
|
18
|
+
type MultilevelHit,
|
|
19
|
+
} from "./multilevel.js";
|
|
20
|
+
import type { EngineMessage } from "../../types.js";
|
|
21
|
+
|
|
22
|
+
function msg(text: string): EngineMessage {
|
|
23
|
+
return { role: "user", text };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Build N distinct leaves with deterministic content. */
|
|
27
|
+
function makeLeaves(n: number, embedder = new TrigramEmbedder()): Leaf[] {
|
|
28
|
+
const leaves: Leaf[] = [];
|
|
29
|
+
for (let i = 0; i < n; i++) {
|
|
30
|
+
const text = `topic ${i % 7}: the module ${i} validated the session token and refreshed the cache for region ${i}`;
|
|
31
|
+
leaves.push({
|
|
32
|
+
id: `leaf_${i}`,
|
|
33
|
+
messages: [msg(text)],
|
|
34
|
+
sourceText: text,
|
|
35
|
+
embedding: embedder.embed(text),
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
return leaves;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// ── test: scoreTreeLevels returns nodes at all levels ────────────────────────
|
|
42
|
+
|
|
43
|
+
test("scoreTreeLevels returns results at multiple tree levels", () => {
|
|
44
|
+
const embedder = new TrigramEmbedder();
|
|
45
|
+
const leaves = makeLeaves(50);
|
|
46
|
+
const tree = buildRaptorTree(leaves, { embedder, clustersPerLevel: 4 });
|
|
47
|
+
|
|
48
|
+
const hits = scoreTreeLevels("the auth module validates the session token", tree, {
|
|
49
|
+
embedder,
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
assert.ok(hits.length > 0, "should return hits");
|
|
53
|
+
|
|
54
|
+
// Should include both leaf (level 0) and cluster (level ≥ 1) hits.
|
|
55
|
+
const levels = new Set(hits.map((h) => h.level));
|
|
56
|
+
assert.ok(levels.has(0), "should have leaf-level hits");
|
|
57
|
+
if (tree.levels > 1) {
|
|
58
|
+
const hasCluster = [...levels].some((l) => l >= 1);
|
|
59
|
+
assert.ok(hasCluster, "should have cluster-level hits for multi-level tree");
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// All hits should have valid scores.
|
|
63
|
+
for (const h of hits) {
|
|
64
|
+
assert.ok(h.score >= 0 && h.score <= 1, `score ${h.score} out of range`);
|
|
65
|
+
assert.ok(h.rawScore >= 0 && h.rawScore <= 1, `rawScore ${h.rawScore} out of range`);
|
|
66
|
+
assert.ok(h.score <= h.rawScore, "weighted score <= raw score (level weights ≤ 1)");
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Hits should be sorted by score descending.
|
|
70
|
+
for (let i = 1; i < hits.length; i++) {
|
|
71
|
+
assert.ok(
|
|
72
|
+
hits[i - 1].score >= hits[i].score,
|
|
73
|
+
`hits not sorted: hit[${i - 1}].score=${hits[i - 1].score} < hit[${i}].score=${hits[i].score}`,
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
// ── test: level weights affect scoring ───────────────────────────────────────
|
|
79
|
+
|
|
80
|
+
test("level weights shift scores: higher weight for level → higher weighted score", () => {
|
|
81
|
+
const embedder = new TrigramEmbedder();
|
|
82
|
+
const leaves = makeLeaves(50);
|
|
83
|
+
const tree = buildRaptorTree(leaves, { embedder, clustersPerLevel: 4 });
|
|
84
|
+
|
|
85
|
+
const query = "the auth module validates the session token";
|
|
86
|
+
|
|
87
|
+
// Uniform weights: all levels scored equally.
|
|
88
|
+
const uniform = scoreTreeLevels(query, tree, {
|
|
89
|
+
embedder,
|
|
90
|
+
levelWeights: [1.0, 1.0, 1.0, 1.0, 1.0],
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
// Penalized weights: higher levels penalized.
|
|
94
|
+
const penalized = scoreTreeLevels(query, tree, {
|
|
95
|
+
embedder,
|
|
96
|
+
levelWeights: [1.0, 0.1, 0.1, 0.1, 0.1],
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
// With penalized weights, cluster-level hits should score lower.
|
|
100
|
+
const clusterUniform = uniform.filter((h) => h.level >= 1);
|
|
101
|
+
const clusterPenalized = penalized.filter((h) => h.level >= 1);
|
|
102
|
+
|
|
103
|
+
if (clusterUniform.length > 0 && clusterPenalized.length > 0) {
|
|
104
|
+
const avgUniform =
|
|
105
|
+
clusterUniform.reduce((s, h) => s + h.score, 0) / clusterUniform.length;
|
|
106
|
+
const avgPenalized =
|
|
107
|
+
clusterPenalized.reduce((s, h) => s + h.score, 0) / clusterPenalized.length;
|
|
108
|
+
assert.ok(
|
|
109
|
+
avgPenalized < avgUniform,
|
|
110
|
+
`penalized cluster avg (${avgPenalized.toFixed(3)}) should be < uniform (${avgUniform.toFixed(3)})`,
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
// ── test: expandLeafDescendants adds leaf hits ──────────────────────────────
|
|
116
|
+
|
|
117
|
+
test("expandLeafDescendants adds leaf descendants for cluster hits", () => {
|
|
118
|
+
const embedder = new TrigramEmbedder();
|
|
119
|
+
const leaves = makeLeaves(50);
|
|
120
|
+
const tree = buildRaptorTree(leaves, { embedder, clustersPerLevel: 4 });
|
|
121
|
+
|
|
122
|
+
const query = "the auth module validates the session token";
|
|
123
|
+
const scored = scoreTreeLevels(query, tree, { embedder });
|
|
124
|
+
const qv = embedder.embed(query);
|
|
125
|
+
|
|
126
|
+
// Take only cluster hits (level ≥ 1).
|
|
127
|
+
const clusterHits = scored.filter((h) => !h.isLeaf).slice(0, 3);
|
|
128
|
+
assert.ok(clusterHits.length > 0, "should have cluster hits");
|
|
129
|
+
|
|
130
|
+
const expanded = expandLeafDescendants(
|
|
131
|
+
clusterHits,
|
|
132
|
+
tree,
|
|
133
|
+
5, // maxPerCluster
|
|
134
|
+
embedder,
|
|
135
|
+
qv,
|
|
136
|
+
);
|
|
137
|
+
|
|
138
|
+
// Expanded set should include leaf hits.
|
|
139
|
+
const leafHits = expanded.filter((h) => h.isLeaf);
|
|
140
|
+
assert.ok(leafHits.length > 0, "should have expanded leaf hits");
|
|
141
|
+
assert.ok(
|
|
142
|
+
expanded.length > clusterHits.length,
|
|
143
|
+
`expanded (${expanded.length}) should be > cluster hits (${clusterHits.length})`,
|
|
144
|
+
);
|
|
145
|
+
|
|
146
|
+
// No duplicate ids.
|
|
147
|
+
const ids = new Set(expanded.map((h) => h.nodeId));
|
|
148
|
+
assert.equal(ids.size, expanded.length, "no duplicate node ids");
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
// ── test: deduplicateMultilevelHits removes cluster when leaves present ─────
|
|
152
|
+
|
|
153
|
+
test("deduplicateMultilevelHits removes cluster hits when leaf children are present", () => {
|
|
154
|
+
const embedder = new TrigramEmbedder();
|
|
155
|
+
const leaves = makeLeaves(50);
|
|
156
|
+
const tree = buildRaptorTree(leaves, { embedder, clustersPerLevel: 4 });
|
|
157
|
+
|
|
158
|
+
const query = "the auth module validates the session token";
|
|
159
|
+
const scored = scoreTreeLevels(query, tree, { embedder });
|
|
160
|
+
|
|
161
|
+
// Take a cluster hit and its leaf children.
|
|
162
|
+
const cluster = scored.find((h) => !h.isLeaf);
|
|
163
|
+
assert.ok(cluster, "should have a cluster hit");
|
|
164
|
+
|
|
165
|
+
const leafChildren: MultilevelHit[] = cluster!.leafIds.slice(0, 2).map((lid) => ({
|
|
166
|
+
nodeId: lid,
|
|
167
|
+
level: 0,
|
|
168
|
+
score: 0.5,
|
|
169
|
+
rawScore: 0.5,
|
|
170
|
+
isLeaf: true,
|
|
171
|
+
leafIds: [lid],
|
|
172
|
+
summary: "",
|
|
173
|
+
embedding: cluster!.embedding,
|
|
174
|
+
}));
|
|
175
|
+
|
|
176
|
+
const mixed = [cluster!, ...leafChildren];
|
|
177
|
+
const deduped = deduplicateMultilevelHits(mixed);
|
|
178
|
+
|
|
179
|
+
// Cluster should be removed because its leaf children are present.
|
|
180
|
+
assert.ok(
|
|
181
|
+
!deduped.find((h) => h.nodeId === cluster!.nodeId),
|
|
182
|
+
"cluster hit should be removed when leaf children are present",
|
|
183
|
+
);
|
|
184
|
+
assert.equal(deduped.length, leafChildren.length, "only leaf hits remain");
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
test("deduplicateMultilevelHits keeps cluster hits when no leaf children present", () => {
|
|
188
|
+
const clusterHit: MultilevelHit = {
|
|
189
|
+
nodeId: "cluster_1",
|
|
190
|
+
level: 1,
|
|
191
|
+
score: 0.8,
|
|
192
|
+
rawScore: 0.8,
|
|
193
|
+
isLeaf: false,
|
|
194
|
+
leafIds: ["leaf_1", "leaf_2"],
|
|
195
|
+
summary: "summarized content",
|
|
196
|
+
embedding: [1, 0, 0],
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
const deduped = deduplicateMultilevelHits([clusterHit]);
|
|
200
|
+
assert.equal(deduped.length, 1, "cluster should be kept when no leaf children present");
|
|
201
|
+
assert.equal(deduped[0].nodeId, "cluster_1");
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
// ── test: multilevelRetrieval returns cluster + leaf mix ────────────────────
|
|
205
|
+
|
|
206
|
+
test("multilevelRetrieval returns a mix of cluster and leaf hits", () => {
|
|
207
|
+
const embedder = new TrigramEmbedder();
|
|
208
|
+
const leaves = makeLeaves(50);
|
|
209
|
+
const tree = buildRaptorTree(leaves, { embedder, clustersPerLevel: 4 });
|
|
210
|
+
|
|
211
|
+
const hits = multilevelRetrieval("the auth module validates the session token", tree, {
|
|
212
|
+
embedder,
|
|
213
|
+
k: 5,
|
|
214
|
+
leafExpansion: true,
|
|
215
|
+
maxLeafExpansion: 3,
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
assert.ok(hits.length > 0, "should return hits");
|
|
219
|
+
assert.ok(hits.length <= 5, "should respect k=5");
|
|
220
|
+
|
|
221
|
+
// Should include leaf hits.
|
|
222
|
+
const leafHits = hits.filter((h) => h.isLeaf);
|
|
223
|
+
assert.ok(leafHits.length > 0, "should include leaf hits");
|
|
224
|
+
|
|
225
|
+
// All hits should have valid properties.
|
|
226
|
+
for (const h of hits) {
|
|
227
|
+
assert.ok(h.nodeId, "hit should have nodeId");
|
|
228
|
+
assert.ok(typeof h.level === "number", "hit should have numeric level");
|
|
229
|
+
assert.ok(h.score >= 0, "hit score should be non-negative");
|
|
230
|
+
assert.ok(Array.isArray(h.leafIds), "hit should have leafIds array");
|
|
231
|
+
}
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
test("multilevelRetrieval respects k parameter", () => {
|
|
235
|
+
const embedder = new TrigramEmbedder();
|
|
236
|
+
const leaves = makeLeaves(100);
|
|
237
|
+
const tree = buildRaptorTree(leaves, { embedder, clustersPerLevel: 8 });
|
|
238
|
+
|
|
239
|
+
for (const k of [1, 3, 5, 10]) {
|
|
240
|
+
const hits = multilevelRetrieval("the auth module validates the session token", tree, {
|
|
241
|
+
embedder,
|
|
242
|
+
k,
|
|
243
|
+
});
|
|
244
|
+
assert.ok(
|
|
245
|
+
hits.length <= k,
|
|
246
|
+
`k=${k}: got ${hits.length} hits, should be ≤ ${k}`,
|
|
247
|
+
);
|
|
248
|
+
}
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
test("multilevelRetrieval returns empty for empty tree", () => {
|
|
252
|
+
const embedder = new TrigramEmbedder();
|
|
253
|
+
const emptyTree = { nodes: new Map(), rootId: null, levels: 0, timedOut: false };
|
|
254
|
+
const hits = multilevelRetrieval("any query", emptyTree, { embedder });
|
|
255
|
+
assert.deepEqual(hits, []);
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
test("multilevelRetrieval with leafExpansion=false skips leaf expansion", () => {
|
|
259
|
+
const embedder = new TrigramEmbedder();
|
|
260
|
+
const leaves = makeLeaves(50);
|
|
261
|
+
const tree = buildRaptorTree(leaves, { embedder, clustersPerLevel: 4 });
|
|
262
|
+
|
|
263
|
+
const hits = multilevelRetrieval("the auth module validates the session token", tree, {
|
|
264
|
+
embedder,
|
|
265
|
+
k: 5,
|
|
266
|
+
leafExpansion: false,
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
assert.ok(hits.length > 0, "should still return hits");
|
|
270
|
+
|
|
271
|
+
// With leaf expansion off and tree having multiple levels, we may get
|
|
272
|
+
// cluster hits that are NOT expanded. The mix depends on tree structure.
|
|
273
|
+
// Just verify we got valid results.
|
|
274
|
+
for (const h of hits) {
|
|
275
|
+
assert.ok(h.nodeId, "hit should have nodeId");
|
|
276
|
+
assert.ok(h.score >= 0, "hit score should be non-negative");
|
|
277
|
+
}
|
|
278
|
+
});
|