pi-mega-compact 0.11.4 → 0.11.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/extensions/dashboard-server/api-contracts/endpoints.js +19 -0
- package/dist/extensions/dashboard-server/api-contracts/memory.js +8 -0
- package/dist/extensions/dashboard-server/api-contracts/provider-cache.js +1 -0
- package/dist/extensions/dashboard-server/api-contracts/setup.js +10 -0
- package/dist/extensions/dashboard-server/index-reader.js +6 -2
- package/dist/extensions/dashboard-server/routes-cache.js +115 -55
- package/dist/extensions/dashboard-server/routes-memory.js +51 -0
- package/dist/extensions/dashboard-server/routes-repo.js +2 -2
- package/dist/extensions/dashboard-server/routes-setup.js +162 -0
- package/dist/extensions/dashboard-server/routes.js +2 -0
- package/dist/extensions/dashboard-server/server.js +7 -1
- package/dist/extensions/mega-commands.js +189 -1
- package/dist/extensions/mega-config.js +2 -0
- package/dist/extensions/mega-events/agent-handlers.js +19 -4
- package/dist/extensions/mega-events/compact-handlers.js +1 -0
- package/dist/extensions/mega-events/context-handler.js +37 -92
- package/dist/extensions/mega-events/context-hwm.js +51 -0
- package/dist/extensions/mega-events/error-classifier.js +16 -5
- package/dist/extensions/mega-events/mirror-append.js +107 -0
- package/dist/extensions/mega-events/outage-advisor.js +7 -1
- package/dist/extensions/mega-events/perf-handler.js +51 -1
- package/dist/extensions/mega-events/recall-tail.js +59 -0
- package/dist/extensions/mega-events/session-handlers.js +15 -8
- package/dist/extensions/mega-runtime/reset-runtime.js +5 -0
- package/dist/extensions/mega-runtime/runtime.js +6 -0
- package/dist/src/embedder.js +41 -2
- package/dist/src/memoryStats.js +75 -0
- package/dist/src/prefix-break.js +43 -0
- package/dist/src/pricing.js +1 -1
- package/dist/src/store/sqlite/perf-samples.js +144 -16
- package/dist/src/store/turns/memory-store.js +8 -0
- package/dist/src/store/turns/sqlite-store.js +14 -3
- package/dist/src/store/turns/types.js +18 -1
- package/dist/src/store/vectorIndex.js +26 -5
- package/extensions/dashboard-client/dist/assets/{AchievementTiles-vEo2MtE2.js → AchievementTiles-BoL7qBOJ.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{AchievementTiles-vEo2MtE2.js.map → AchievementTiles-BoL7qBOJ.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/AchievementsTab-BFDE3HYc.js +2 -0
- package/extensions/dashboard-client/dist/assets/{AchievementsTab-DjxfYrDc.js.map → AchievementsTab-BFDE3HYc.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/CacheTab-eKVc-NV1.js +2 -0
- package/extensions/dashboard-client/dist/assets/CacheTab-eKVc-NV1.js.map +1 -0
- package/extensions/dashboard-client/dist/assets/{ConfigTab-Cm6ymbmx.js → ConfigTab-DDFE-ckA.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{ConfigTab-Cm6ymbmx.js.map → ConfigTab-DDFE-ckA.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{EventsTab-DXWl_YzI.js → EventsTab-B6UxZ7PM.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{EventsTab-DXWl_YzI.js.map → EventsTab-B6UxZ7PM.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{GameTab-BLDudcO5.js → GameTab-DehUX-KE.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{GameTab-BLDudcO5.js.map → GameTab-DehUX-KE.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{MaintenanceTab-DLkKCztn.js → MaintenanceTab-0GWRt4wn.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{MaintenanceTab-DLkKCztn.js.map → MaintenanceTab-0GWRt4wn.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{MetricsTab-Cq4u-rZF.js → MetricsTab-C3rwMVsN.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{MetricsTab-Cq4u-rZF.js.map → MetricsTab-C3rwMVsN.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/OverviewTab-39O9_x5j.js +2 -0
- package/extensions/dashboard-client/dist/assets/{OverviewTab-D4kGvsiQ.js.map → OverviewTab-39O9_x5j.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/ReposTab-Cfj6Q5sH.js +2 -0
- package/extensions/dashboard-client/dist/assets/ReposTab-Cfj6Q5sH.js.map +1 -0
- package/extensions/dashboard-client/dist/assets/{SessionsTab-DZC2-GCn.js → SessionsTab-DXDTCi3r.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{SessionsTab-DZC2-GCn.js.map → SessionsTab-DXDTCi3r.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/SetupTab-mMlfunJa.js +2 -0
- package/extensions/dashboard-client/dist/assets/SetupTab-mMlfunJa.js.map +1 -0
- package/extensions/dashboard-client/dist/assets/TimeSavedCard-Cw1dJ4e9.js +2 -0
- package/extensions/dashboard-client/dist/assets/TimeSavedCard-Cw1dJ4e9.js.map +1 -0
- package/extensions/dashboard-client/dist/assets/{TopicsTab-01G71hv1.js → TopicsTab-BAw972BV.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{TopicsTab-01G71hv1.js.map → TopicsTab-BAw972BV.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/{TurnsTab-DLRg0LZT.js → TurnsTab-Cf5mGIdl.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{TurnsTab-DLRg0LZT.js.map → TurnsTab-Cf5mGIdl.js.map} +1 -1
- package/extensions/dashboard-client/dist/assets/format-COjDIVGj.js +2 -0
- package/extensions/dashboard-client/dist/assets/format-COjDIVGj.js.map +1 -0
- package/extensions/dashboard-client/dist/assets/{index-BX0bcgLu.js → index-4gQ7auad.js} +10 -10
- package/extensions/dashboard-client/dist/assets/index-4gQ7auad.js.map +1 -0
- package/extensions/dashboard-client/dist/assets/pricing-CvE4NllQ.js +2 -0
- package/extensions/dashboard-client/dist/assets/pricing-CvE4NllQ.js.map +1 -0
- package/extensions/dashboard-client/dist/assets/{useSSE-BBYt5UPB.js → useSSE-DNgMuyP6.js} +2 -2
- package/extensions/dashboard-client/dist/assets/{useSSE-BBYt5UPB.js.map → useSSE-DNgMuyP6.js.map} +1 -1
- package/extensions/dashboard-client/dist/index.html +1 -1
- package/extensions/dashboard-client/src/App.tsx +4 -0
- package/extensions/dashboard-client/src/api/client.ts +14 -0
- package/extensions/dashboard-client/src/components/ActiveReposTable.tsx +21 -12
- package/extensions/dashboard-client/src/components/ProviderCacheCard.tsx +56 -0
- package/extensions/dashboard-client/src/components/SavingsByModelTable.tsx +38 -57
- package/extensions/dashboard-client/src/tabs/CacheTab.tsx +1 -0
- package/extensions/dashboard-client/src/tabs/SetupTab.tsx +355 -0
- package/extensions/dashboard-client/tsconfig.json +3 -2
- package/extensions/dashboard-client/vite.config.ts +2 -0
- package/extensions/dashboard-server/api-contracts/endpoints.ts +36 -3
- package/extensions/dashboard-server/api-contracts/index.ts +7 -0
- package/extensions/dashboard-server/api-contracts/memory.ts +27 -0
- package/extensions/dashboard-server/api-contracts/multi-repo.ts +231 -231
- package/extensions/dashboard-server/api-contracts/provider-cache.ts +37 -0
- package/extensions/dashboard-server/api-contracts/setup.ts +58 -0
- package/extensions/dashboard-server/index-reader.ts +138 -121
- package/extensions/dashboard-server/routes-cache.ts +161 -85
- package/extensions/dashboard-server/routes-memory.ts +63 -0
- package/extensions/dashboard-server/routes-repo.ts +36 -36
- package/extensions/dashboard-server/routes-setup.ts +181 -0
- package/extensions/dashboard-server/routes.ts +2 -0
- package/extensions/dashboard-server/server.ts +6 -0
- package/extensions/mega-commands.ts +211 -1
- package/extensions/mega-config.ts +10 -0
- package/extensions/mega-events/agent-handlers.ts +20 -4
- package/extensions/mega-events/compact-handlers.ts +1 -0
- package/extensions/mega-events/context-handler.ts +45 -110
- package/extensions/mega-events/context-hwm.ts +85 -0
- package/extensions/mega-events/error-classifier.ts +15 -4
- package/extensions/mega-events/mirror-append.ts +155 -0
- package/extensions/mega-events/outage-advisor.ts +11 -5
- package/extensions/mega-events/perf-handler.ts +79 -5
- package/extensions/mega-events/recall-tail.ts +88 -0
- package/extensions/mega-events/session-handlers.ts +14 -7
- package/extensions/mega-runtime/helpers.ts +12 -0
- package/extensions/mega-runtime/reset-runtime.ts +5 -0
- package/extensions/mega-runtime/runtime.ts +6 -0
- package/package.json +5 -2
- package/src/embedder.ts +42 -2
- package/src/memoryStats.ts +107 -0
- package/src/prefix-break.ts +83 -0
- package/src/pricing.ts +2 -2
- package/src/store/sqlite/perf-samples.ts +215 -22
- package/src/store/turns/memory-store.ts +10 -1
- package/src/store/turns/sqlite-store.ts +27 -15
- package/src/store/turns/types.ts +21 -0
- package/src/store/vectorIndex.ts +33 -4
- package/dist/extensions/conflict-scan.test.js +0 -115
- package/dist/extensions/dashboard-server/api-contracts.test.js +0 -884
- package/dist/extensions/dashboard-server/html.test.js +0 -52
- package/dist/extensions/dashboard-server/perf-server.test.js +0 -80
- package/dist/extensions/dashboard-server/routes-cache.test.js +0 -248
- package/dist/extensions/dashboard-server/server.test.js +0 -120
- package/dist/extensions/dashboard-server-s32.test.js +0 -181
- package/dist/extensions/dashboard-server.test.js +0 -339
- package/dist/extensions/mega-cache-replay.test.js +0 -400
- package/dist/extensions/mega-compact-s38.test.js +0 -1383
- package/dist/extensions/mega-compact.test.js +0 -1112
- package/dist/extensions/mega-events.test.js +0 -47
- package/dist/extensions/mega-game-cmds.test.js +0 -163
- package/dist/extensions/mega-runtime/snapshot.test.js +0 -127
- package/dist/extensions/mega-runtime/state.test.js +0 -266
- package/dist/extensions/mega-runtime/widget.test.js +0 -343
- package/dist/extensions/mega-shutdown-widget.test.js +0 -121
- package/dist/extensions/mega-teamrun.test.js +0 -156
- package/dist/extensions/mega-trim.test.js +0 -58
- package/dist/extensions/mega-turn-store.test.js +0 -68
- package/dist/src/boundary.test.js +0 -170
- package/dist/src/compact.test.js +0 -78
- package/dist/src/config/themes.test.js +0 -94
- package/dist/src/dedup/dedup.test.js +0 -41
- package/dist/src/dedup/l1.test.js +0 -50
- package/dist/src/dedup/raptor/buildHistory.test.js +0 -292
- package/dist/src/dedup/raptor/multilevel-serve.test.js +0 -229
- package/dist/src/dedup/raptor/multilevel.test.js +0 -238
- package/dist/src/dedup/raptor/promote.test.js +0 -69
- package/dist/src/dedup/raptor/raptor.test.js +0 -248
- package/dist/src/dedup/raptor/retrieval.test.js +0 -95
- package/dist/src/dedup/raptor/serve-gate.test.js +0 -298
- package/dist/src/dedup/sprint12.test.js +0 -219
- package/dist/src/dedup-engine.test.js +0 -472
- package/dist/src/driftDetection.test.js +0 -87
- package/dist/src/e2e.test.js +0 -698
- package/dist/src/engine.test.js +0 -111
- package/dist/src/extractive.test.js +0 -147
- package/dist/src/fork.test.js +0 -81
- package/dist/src/game/scoring.test.js +0 -98
- package/dist/src/httpEmbedder.test.js +0 -277
- package/dist/src/importance.test.js +0 -372
- package/dist/src/intent.test.js +0 -78
- package/dist/src/log.test.js +0 -42
- package/dist/src/mechanical-fix.test.js +0 -65
- package/dist/src/memory.test.js +0 -70
- package/dist/src/memoryConsolidate.test.js +0 -38
- package/dist/src/memoryOps.test.js +0 -129
- package/dist/src/memoryRecall.test.js +0 -171
- package/dist/src/memoryRoundtrip.test.js +0 -137
- package/dist/src/metrics/turns.test.js +0 -152
- package/dist/src/mirror/mirror.test.js +0 -185
- package/dist/src/raptor-inject-summaries.test.js +0 -162
- package/dist/src/ratio.bench.test.js +0 -897
- package/dist/src/recall.integration.test.js +0 -77
- package/dist/src/recall.test.js +0 -379
- package/dist/src/sprint14.test.js +0 -219
- package/dist/src/sprint4x-rag-verification.test.js +0 -93
- package/dist/src/store/compression.test.js +0 -139
- package/dist/src/store/memoryIndex.test.js +0 -51
- package/dist/src/store/migrate.test.js +0 -139
- package/dist/src/store/pgOpenGuard.test.js +0 -74
- package/dist/src/store/phase01.test.js +0 -81
- package/dist/src/store/phase04.test.js +0 -54
- package/dist/src/store/sprint10.test.js +0 -186
- package/dist/src/store/sqlite/game-achievements.test.js +0 -67
- package/dist/src/store/sqlite/game-scores.test.js +0 -106
- package/dist/src/store/sqlite/game-state.test.js +0 -76
- package/dist/src/store/sqlite/global-index.test.js +0 -136
- package/dist/src/store/sqlite/mechanical-fix.test.js +0 -146
- package/dist/src/store/sqlite/perf-samples.test.js +0 -146
- package/dist/src/store/sqlite/raptor.test.js +0 -106
- package/dist/src/store/sqlite/turns.test.js +0 -183
- package/dist/src/store/sqlite.cachehit.test.js +0 -55
- package/dist/src/store/sqlite.dbmaint.test.js +0 -158
- package/dist/src/store/sqlite.dbmirror.test.js +0 -184
- package/dist/src/store/turns/contract-compliance.test.js +0 -428
- package/dist/src/store/turns/memory-store.test.js +0 -9
- package/dist/src/store/turns/migrations.test.js +0 -138
- package/dist/src/store/turns/sqlite-store.test.js +0 -144
- package/dist/src/store/vectorIndex.test.js +0 -123
- package/dist/src/store.test.js +0 -161
- package/dist/src/supersede.test.js +0 -36
- package/dist/src/topics/cluster.test.js +0 -150
- package/dist/src/topics/store.test.js +0 -117
- package/dist/src/types.test.js +0 -9
- package/dist/src/vector-search-cache.test.js +0 -157
- package/dist/src/vectorStore.test.js +0 -479
- package/dist/src/wiki.test.js +0 -171
- package/extensions/conflict-scan.test.ts +0 -129
- package/extensions/dashboard-client/dist/assets/AchievementsTab-DjxfYrDc.js +0 -2
- package/extensions/dashboard-client/dist/assets/CacheTab-Dnpv94wq.js +0 -2
- package/extensions/dashboard-client/dist/assets/CacheTab-Dnpv94wq.js.map +0 -1
- package/extensions/dashboard-client/dist/assets/OverviewTab-D4kGvsiQ.js +0 -2
- package/extensions/dashboard-client/dist/assets/ReposTab-C0Wnrf2u.js +0 -2
- package/extensions/dashboard-client/dist/assets/ReposTab-C0Wnrf2u.js.map +0 -1
- package/extensions/dashboard-client/dist/assets/TimeSavedCard-UqljSyP-.js +0 -2
- package/extensions/dashboard-client/dist/assets/TimeSavedCard-UqljSyP-.js.map +0 -1
- package/extensions/dashboard-client/dist/assets/index-BX0bcgLu.js.map +0 -1
- package/extensions/dashboard-server/api-contracts.test.ts +0 -1065
- package/extensions/dashboard-server/html.test.ts +0 -62
- package/extensions/dashboard-server/perf-server.test.ts +0 -101
- package/extensions/dashboard-server/routes-cache.test.ts +0 -302
- package/extensions/dashboard-server/server.test.ts +0 -131
- package/extensions/dashboard-server-s32.test.ts +0 -195
- package/extensions/dashboard-server.test.ts +0 -382
- package/extensions/mega-cache-replay.test.ts +0 -526
- package/extensions/mega-compact-s38.test.ts +0 -1433
- package/extensions/mega-compact.test.ts +0 -1509
- package/extensions/mega-events.test.ts +0 -55
- package/extensions/mega-game-cmds.test.ts +0 -197
- package/extensions/mega-runtime/snapshot.test.ts +0 -139
- package/extensions/mega-runtime/state.test.ts +0 -262
- package/extensions/mega-runtime/widget.test.ts +0 -468
- package/extensions/mega-shutdown-widget.test.ts +0 -141
- package/extensions/mega-teamrun.test.ts +0 -176
- package/extensions/mega-trim.test.ts +0 -64
- package/extensions/mega-turn-store.test.ts +0 -108
- package/src/boundary.test.ts +0 -187
- package/src/compact.test.ts +0 -99
- package/src/config/themes.test.ts +0 -116
- package/src/dedup/dedup.test.ts +0 -46
- package/src/dedup/l1.test.ts +0 -57
- package/src/dedup/raptor/buildHistory.test.ts +0 -353
- package/src/dedup/raptor/multilevel-serve.test.ts +0 -273
- package/src/dedup/raptor/multilevel.test.ts +0 -325
- package/src/dedup/raptor/promote.test.ts +0 -82
- package/src/dedup/raptor/raptor.test.ts +0 -297
- package/src/dedup/raptor/retrieval.test.ts +0 -118
- package/src/dedup/raptor/serve-gate.test.ts +0 -348
- package/src/dedup/sprint12.test.ts +0 -242
- package/src/dedup-engine.test.ts +0 -670
- package/src/driftDetection.test.ts +0 -100
- package/src/e2e.test.ts +0 -843
- package/src/engine.test.ts +0 -123
- package/src/extractive.test.ts +0 -174
- package/src/fork.test.ts +0 -94
- package/src/game/scoring.test.ts +0 -103
- package/src/httpEmbedder.test.ts +0 -286
- package/src/importance.test.ts +0 -538
- package/src/intent.test.ts +0 -87
- package/src/log.test.ts +0 -47
- package/src/mechanical-fix.test.ts +0 -70
- package/src/memory.test.ts +0 -92
- package/src/memoryConsolidate.test.ts +0 -47
- package/src/memoryOps.test.ts +0 -148
- package/src/memoryRecall.test.ts +0 -194
- package/src/memoryRoundtrip.test.ts +0 -155
- package/src/metrics/turns.test.ts +0 -165
- package/src/mirror/mirror.test.ts +0 -240
- package/src/raptor-inject-summaries.test.ts +0 -228
- package/src/ratio.bench.test.ts +0 -1316
- package/src/recall.integration.test.ts +0 -96
- package/src/recall.test.ts +0 -467
- package/src/sprint14.test.ts +0 -245
- package/src/sprint4x-rag-verification.test.ts +0 -119
- package/src/store/compression.test.ts +0 -168
- package/src/store/memoryIndex.test.ts +0 -61
- package/src/store/migrate.test.ts +0 -158
- package/src/store/pgOpenGuard.test.ts +0 -89
- package/src/store/phase01.test.ts +0 -88
- package/src/store/phase04.test.ts +0 -58
- package/src/store/sprint10.test.ts +0 -214
- package/src/store/sqlite/game-achievements.test.ts +0 -80
- package/src/store/sqlite/game-scores.test.ts +0 -132
- package/src/store/sqlite/game-state.test.ts +0 -89
- package/src/store/sqlite/global-index.test.ts +0 -222
- package/src/store/sqlite/mechanical-fix.test.ts +0 -162
- package/src/store/sqlite/perf-samples.test.ts +0 -169
- package/src/store/sqlite/raptor.test.ts +0 -139
- package/src/store/sqlite/turns.test.ts +0 -218
- package/src/store/sqlite.cachehit.test.ts +0 -68
- package/src/store/sqlite.dbmaint.test.ts +0 -193
- package/src/store/sqlite.dbmirror.test.ts +0 -229
- package/src/store/turns/contract-compliance.test.ts +0 -562
- package/src/store/turns/memory-store.test.ts +0 -15
- package/src/store/turns/migrations.test.ts +0 -161
- package/src/store/turns/sqlite-store.test.ts +0 -161
- package/src/store/vectorIndex.test.ts +0 -140
- package/src/store.test.ts +0 -191
- package/src/supersede.test.ts +0 -42
- package/src/topics/cluster.test.ts +0 -176
- package/src/topics/store.test.ts +0 -132
- package/src/types.test.ts +0 -10
- package/src/vector-search-cache.test.ts +0 -190
- package/src/vectorStore.test.ts +0 -533
- package/src/wiki.test.ts +0 -217
|
@@ -1,238 +0,0 @@
|
|
|
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
|
-
import { test } from "node:test";
|
|
9
|
-
import assert from "node:assert/strict";
|
|
10
|
-
import { TrigramEmbedder } from "../../embedder.js";
|
|
11
|
-
import { buildRaptorTree } from "./tree.js";
|
|
12
|
-
import { scoreTreeLevels, expandLeafDescendants, deduplicateMultilevelHits, multilevelRetrieval, buildChildParentIndex, } from "./multilevel.js";
|
|
13
|
-
function msg(text) {
|
|
14
|
-
return { role: "user", text };
|
|
15
|
-
}
|
|
16
|
-
/** Build N distinct leaves with deterministic content. */
|
|
17
|
-
function makeLeaves(n, embedder = new TrigramEmbedder()) {
|
|
18
|
-
const leaves = [];
|
|
19
|
-
for (let i = 0; i < n; i++) {
|
|
20
|
-
const text = `topic ${i % 7}: the module ${i} validated the session token and refreshed the cache for region ${i}`;
|
|
21
|
-
leaves.push({
|
|
22
|
-
id: `leaf_${i}`,
|
|
23
|
-
messages: [msg(text)],
|
|
24
|
-
sourceText: text,
|
|
25
|
-
embedding: embedder.embed(text),
|
|
26
|
-
});
|
|
27
|
-
}
|
|
28
|
-
return leaves;
|
|
29
|
-
}
|
|
30
|
-
// ── test: scoreTreeLevels returns nodes at all levels ────────────────────────
|
|
31
|
-
test("scoreTreeLevels returns results at multiple tree levels", () => {
|
|
32
|
-
const embedder = new TrigramEmbedder();
|
|
33
|
-
const leaves = makeLeaves(50);
|
|
34
|
-
const tree = buildRaptorTree(leaves, { embedder, clustersPerLevel: 4 });
|
|
35
|
-
const hits = scoreTreeLevels("the auth module validates the session token", tree, {
|
|
36
|
-
embedder,
|
|
37
|
-
});
|
|
38
|
-
assert.ok(hits.length > 0, "should return hits");
|
|
39
|
-
// Should include both leaf (level 0) and cluster (level ≥ 1) hits.
|
|
40
|
-
const levels = new Set(hits.map((h) => h.level));
|
|
41
|
-
assert.ok(levels.has(0), "should have leaf-level hits");
|
|
42
|
-
if (tree.levels > 1) {
|
|
43
|
-
const hasCluster = [...levels].some((l) => l >= 1);
|
|
44
|
-
assert.ok(hasCluster, "should have cluster-level hits for multi-level tree");
|
|
45
|
-
}
|
|
46
|
-
// All hits should have valid scores.
|
|
47
|
-
for (const h of hits) {
|
|
48
|
-
assert.ok(h.score >= 0 && h.score <= 1, `score ${h.score} out of range`);
|
|
49
|
-
assert.ok(h.rawScore >= 0 && h.rawScore <= 1, `rawScore ${h.rawScore} out of range`);
|
|
50
|
-
assert.ok(h.score <= h.rawScore, "weighted score <= raw score (level weights ≤ 1)");
|
|
51
|
-
}
|
|
52
|
-
// Hits should be sorted by score descending.
|
|
53
|
-
for (let i = 1; i < hits.length; i++) {
|
|
54
|
-
assert.ok(hits[i - 1].score >= hits[i].score, `hits not sorted: hit[${i - 1}].score=${hits[i - 1].score} < hit[${i}].score=${hits[i].score}`);
|
|
55
|
-
}
|
|
56
|
-
});
|
|
57
|
-
// ── test: level weights affect scoring ───────────────────────────────────────
|
|
58
|
-
test("level weights shift scores: higher weight for level → higher weighted score", () => {
|
|
59
|
-
const embedder = new TrigramEmbedder();
|
|
60
|
-
const leaves = makeLeaves(50);
|
|
61
|
-
const tree = buildRaptorTree(leaves, { embedder, clustersPerLevel: 4 });
|
|
62
|
-
const query = "the auth module validates the session token";
|
|
63
|
-
// Uniform weights: all levels scored equally.
|
|
64
|
-
const uniform = scoreTreeLevels(query, tree, {
|
|
65
|
-
embedder,
|
|
66
|
-
levelWeights: [1.0, 1.0, 1.0, 1.0, 1.0],
|
|
67
|
-
});
|
|
68
|
-
// Penalized weights: higher levels penalized.
|
|
69
|
-
const penalized = scoreTreeLevels(query, tree, {
|
|
70
|
-
embedder,
|
|
71
|
-
levelWeights: [1.0, 0.1, 0.1, 0.1, 0.1],
|
|
72
|
-
});
|
|
73
|
-
// With penalized weights, cluster-level hits should score lower.
|
|
74
|
-
const clusterUniform = uniform.filter((h) => h.level >= 1);
|
|
75
|
-
const clusterPenalized = penalized.filter((h) => h.level >= 1);
|
|
76
|
-
if (clusterUniform.length > 0 && clusterPenalized.length > 0) {
|
|
77
|
-
const avgUniform = clusterUniform.reduce((s, h) => s + h.score, 0) / clusterUniform.length;
|
|
78
|
-
const avgPenalized = clusterPenalized.reduce((s, h) => s + h.score, 0) / clusterPenalized.length;
|
|
79
|
-
assert.ok(avgPenalized < avgUniform, `penalized cluster avg (${avgPenalized.toFixed(3)}) should be < uniform (${avgUniform.toFixed(3)})`);
|
|
80
|
-
}
|
|
81
|
-
});
|
|
82
|
-
// ── test: expandLeafDescendants adds leaf hits ──────────────────────────────
|
|
83
|
-
test("expandLeafDescendants adds leaf descendants for cluster hits", () => {
|
|
84
|
-
const embedder = new TrigramEmbedder();
|
|
85
|
-
const leaves = makeLeaves(50);
|
|
86
|
-
const tree = buildRaptorTree(leaves, { embedder, clustersPerLevel: 4 });
|
|
87
|
-
const query = "the auth module validates the session token";
|
|
88
|
-
const scored = scoreTreeLevels(query, tree, { embedder });
|
|
89
|
-
const qv = embedder.embed(query);
|
|
90
|
-
// Take only cluster hits (level ≥ 1).
|
|
91
|
-
const clusterHits = scored.filter((h) => !h.isLeaf).slice(0, 3);
|
|
92
|
-
assert.ok(clusterHits.length > 0, "should have cluster hits");
|
|
93
|
-
const expanded = expandLeafDescendants(clusterHits, tree, 5, // maxPerCluster
|
|
94
|
-
embedder, qv);
|
|
95
|
-
// Expanded set should include leaf hits.
|
|
96
|
-
const leafHits = expanded.filter((h) => h.isLeaf);
|
|
97
|
-
assert.ok(leafHits.length > 0, "should have expanded leaf hits");
|
|
98
|
-
assert.ok(expanded.length > clusterHits.length, `expanded (${expanded.length}) should be > cluster hits (${clusterHits.length})`);
|
|
99
|
-
// No duplicate ids.
|
|
100
|
-
const ids = new Set(expanded.map((h) => h.nodeId));
|
|
101
|
-
assert.equal(ids.size, expanded.length, "no duplicate node ids");
|
|
102
|
-
});
|
|
103
|
-
// ── test: deduplicateMultilevelHits removes cluster when leaves present ─────
|
|
104
|
-
test("deduplicateMultilevelHits removes cluster hits when leaf children are present", () => {
|
|
105
|
-
const embedder = new TrigramEmbedder();
|
|
106
|
-
const leaves = makeLeaves(50);
|
|
107
|
-
const tree = buildRaptorTree(leaves, { embedder, clustersPerLevel: 4 });
|
|
108
|
-
const query = "the auth module validates the session token";
|
|
109
|
-
const scored = scoreTreeLevels(query, tree, { embedder });
|
|
110
|
-
// Take a cluster hit and its leaf children.
|
|
111
|
-
const cluster = scored.find((h) => !h.isLeaf);
|
|
112
|
-
assert.ok(cluster, "should have a cluster hit");
|
|
113
|
-
const leafChildren = cluster.leafIds.slice(0, 2).map((lid) => ({
|
|
114
|
-
nodeId: lid,
|
|
115
|
-
level: 0,
|
|
116
|
-
score: 0.5,
|
|
117
|
-
rawScore: 0.5,
|
|
118
|
-
isLeaf: true,
|
|
119
|
-
leafIds: [lid],
|
|
120
|
-
summary: "",
|
|
121
|
-
embedding: cluster.embedding,
|
|
122
|
-
}));
|
|
123
|
-
const mixed = [cluster, ...leafChildren];
|
|
124
|
-
const deduped = deduplicateMultilevelHits(mixed);
|
|
125
|
-
// Cluster should be removed because its leaf children are present.
|
|
126
|
-
assert.ok(!deduped.find((h) => h.nodeId === cluster.nodeId), "cluster hit should be removed when leaf children are present");
|
|
127
|
-
assert.equal(deduped.length, leafChildren.length, "only leaf hits remain");
|
|
128
|
-
});
|
|
129
|
-
test("deduplicateMultilevelHits keeps cluster hits when no leaf children present", () => {
|
|
130
|
-
const clusterHit = {
|
|
131
|
-
nodeId: "cluster_1",
|
|
132
|
-
level: 1,
|
|
133
|
-
score: 0.8,
|
|
134
|
-
rawScore: 0.8,
|
|
135
|
-
isLeaf: false,
|
|
136
|
-
leafIds: ["leaf_1", "leaf_2"],
|
|
137
|
-
summary: "summarized content",
|
|
138
|
-
embedding: [1, 0, 0],
|
|
139
|
-
};
|
|
140
|
-
const deduped = deduplicateMultilevelHits([clusterHit]);
|
|
141
|
-
assert.equal(deduped.length, 1, "cluster should be kept when no leaf children present");
|
|
142
|
-
assert.equal(deduped[0].nodeId, "cluster_1");
|
|
143
|
-
});
|
|
144
|
-
// ── test: multilevelRetrieval returns cluster + leaf mix ────────────────────
|
|
145
|
-
test("multilevelRetrieval returns a mix of cluster and leaf hits", () => {
|
|
146
|
-
const embedder = new TrigramEmbedder();
|
|
147
|
-
const leaves = makeLeaves(50);
|
|
148
|
-
const tree = buildRaptorTree(leaves, { embedder, clustersPerLevel: 4 });
|
|
149
|
-
const hits = multilevelRetrieval("the auth module validates the session token", tree, {
|
|
150
|
-
embedder,
|
|
151
|
-
k: 5,
|
|
152
|
-
leafExpansion: true,
|
|
153
|
-
maxLeafExpansion: 3,
|
|
154
|
-
});
|
|
155
|
-
assert.ok(hits.length > 0, "should return hits");
|
|
156
|
-
assert.ok(hits.length <= 5, "should respect k=5");
|
|
157
|
-
// Should include leaf hits.
|
|
158
|
-
const leafHits = hits.filter((h) => h.isLeaf);
|
|
159
|
-
assert.ok(leafHits.length > 0, "should include leaf hits");
|
|
160
|
-
// All hits should have valid properties.
|
|
161
|
-
for (const h of hits) {
|
|
162
|
-
assert.ok(h.nodeId, "hit should have nodeId");
|
|
163
|
-
assert.ok(typeof h.level === "number", "hit should have numeric level");
|
|
164
|
-
assert.ok(h.score >= 0, "hit score should be non-negative");
|
|
165
|
-
assert.ok(Array.isArray(h.leafIds), "hit should have leafIds array");
|
|
166
|
-
}
|
|
167
|
-
});
|
|
168
|
-
test("multilevelRetrieval respects k parameter", () => {
|
|
169
|
-
const embedder = new TrigramEmbedder();
|
|
170
|
-
const leaves = makeLeaves(100);
|
|
171
|
-
const tree = buildRaptorTree(leaves, { embedder, clustersPerLevel: 8 });
|
|
172
|
-
for (const k of [1, 3, 5, 10]) {
|
|
173
|
-
const hits = multilevelRetrieval("the auth module validates the session token", tree, {
|
|
174
|
-
embedder,
|
|
175
|
-
k,
|
|
176
|
-
});
|
|
177
|
-
assert.ok(hits.length <= k, `k=${k}: got ${hits.length} hits, should be ≤ ${k}`);
|
|
178
|
-
}
|
|
179
|
-
});
|
|
180
|
-
test("multilevelRetrieval returns empty for empty tree", () => {
|
|
181
|
-
const embedder = new TrigramEmbedder();
|
|
182
|
-
const emptyTree = { nodes: new Map(), rootId: null, levels: 0, timedOut: false };
|
|
183
|
-
const hits = multilevelRetrieval("any query", emptyTree, { embedder });
|
|
184
|
-
assert.deepEqual(hits, []);
|
|
185
|
-
});
|
|
186
|
-
test("multilevelRetrieval with leafExpansion=false skips leaf expansion", () => {
|
|
187
|
-
const embedder = new TrigramEmbedder();
|
|
188
|
-
const leaves = makeLeaves(50);
|
|
189
|
-
const tree = buildRaptorTree(leaves, { embedder, clustersPerLevel: 4 });
|
|
190
|
-
const hits = multilevelRetrieval("the auth module validates the session token", tree, {
|
|
191
|
-
embedder,
|
|
192
|
-
k: 5,
|
|
193
|
-
leafExpansion: false,
|
|
194
|
-
});
|
|
195
|
-
assert.ok(hits.length > 0, "should still return hits");
|
|
196
|
-
// With leaf expansion off and tree having multiple levels, we may get
|
|
197
|
-
// cluster hits that are NOT expanded. The mix depends on tree structure.
|
|
198
|
-
// Just verify we got valid results.
|
|
199
|
-
for (const h of hits) {
|
|
200
|
-
assert.ok(h.nodeId, "hit should have nodeId");
|
|
201
|
-
assert.ok(h.score >= 0, "hit score should be non-negative");
|
|
202
|
-
}
|
|
203
|
-
});
|
|
204
|
-
// ── test: buildChildParentIndex matches linear-scan parent ────────────────────
|
|
205
|
-
test("buildChildParentIndex (multilevel): index-derived parent matches linear-scan for each leaf", () => {
|
|
206
|
-
// Hand-built tree: 8 leaves under 2 level-1 nodes under 1 root.
|
|
207
|
-
const r1_0 = {
|
|
208
|
-
id: "r1_0", level: 1, parentId: null,
|
|
209
|
-
children: ["leaf_0", "leaf_1", "leaf_2", "leaf_3"],
|
|
210
|
-
summary: "cluster A", embedding: [1, 0, 0],
|
|
211
|
-
qualityMarker: "low", tokenEstimate: 10,
|
|
212
|
-
};
|
|
213
|
-
const r1_1 = {
|
|
214
|
-
id: "r1_1", level: 1, parentId: null,
|
|
215
|
-
children: ["leaf_4", "leaf_5", "leaf_6", "leaf_7"],
|
|
216
|
-
summary: "cluster B", embedding: [0, 1, 0],
|
|
217
|
-
qualityMarker: "low", tokenEstimate: 10,
|
|
218
|
-
};
|
|
219
|
-
const root = {
|
|
220
|
-
id: "root", level: 2, parentId: null,
|
|
221
|
-
children: ["leaf_0", "leaf_1", "leaf_2", "leaf_3",
|
|
222
|
-
"leaf_4", "leaf_5", "leaf_6", "leaf_7"],
|
|
223
|
-
summary: "root", embedding: [0.5, 0.5, 0],
|
|
224
|
-
qualityMarker: "low", tokenEstimate: 20,
|
|
225
|
-
};
|
|
226
|
-
const nodes = new Map([
|
|
227
|
-
["r1_0", r1_0], ["r1_1", r1_1], ["root", root],
|
|
228
|
-
]);
|
|
229
|
-
const tree = { nodes, rootId: "root", levels: 3, timedOut: false };
|
|
230
|
-
const index = buildChildParentIndex(tree);
|
|
231
|
-
const leafIds = ["leaf_0", "leaf_1", "leaf_2", "leaf_3",
|
|
232
|
-
"leaf_4", "leaf_5", "leaf_6", "leaf_7"];
|
|
233
|
-
for (const lid of leafIds) {
|
|
234
|
-
const linearParent = [...tree.nodes.values()].find((n) => n.children.includes(lid));
|
|
235
|
-
const indexParent = index.get(lid);
|
|
236
|
-
assert.equal(indexParent?.id ?? null, linearParent?.id ?? null, `leaf ${lid}: index parent (${indexParent?.id}) != linear parent (${linearParent?.id})`);
|
|
237
|
-
}
|
|
238
|
-
});
|
|
@@ -1,69 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* promote.test.ts — Fix D: RAPTOR tree served by vectorStore.search.
|
|
3
|
-
*
|
|
4
|
-
* Asserts that, when a RAPTOR tree has been built + persisted for a session,
|
|
5
|
-
* VectorStore.search returns the tree's staged-expansion hits (broader, O(log n)
|
|
6
|
-
* coverage) merged with the flat hits — so the dormant tree becomes the live
|
|
7
|
-
* recall surface. No network: default extractive summarizer + trigram embedder.
|
|
8
|
-
*/
|
|
9
|
-
import { test } from "node:test";
|
|
10
|
-
import assert from "node:assert/strict";
|
|
11
|
-
import { mkdtempSync, rmSync } from "node:fs";
|
|
12
|
-
import { tmpdir } from "node:os";
|
|
13
|
-
import { join } from "node:path";
|
|
14
|
-
import { VectorStore, vectorList, vectorSearch } from "../../vectorStore.js";
|
|
15
|
-
import { runRaptor } from "./index.js";
|
|
16
|
-
import { compactSession } from "../../engine.js";
|
|
17
|
-
import { Logger } from "../../log.js";
|
|
18
|
-
import { loadDedupConfig } from "../../config/dedup.js";
|
|
19
|
-
import { listRaptorNodes } from "../../store/sqlite.js";
|
|
20
|
-
const baseTmp = mkdtempSync(join(tmpdir(), "mc-promote-"));
|
|
21
|
-
let counter = 0;
|
|
22
|
-
function raptorConfig() {
|
|
23
|
-
return { ...loadDedupConfig(), RAPTOR_ENABLED: true };
|
|
24
|
-
}
|
|
25
|
-
function msg(text, toolName) {
|
|
26
|
-
return toolName ? { role: "assistant", text, toolName, input: text, output: text } : { role: "user", text };
|
|
27
|
-
}
|
|
28
|
-
const SESS = "sess_promote";
|
|
29
|
-
test("Fix D: vectorStore.search serves a persisted RAPTOR tree (broader recall)", () => {
|
|
30
|
-
const stateDir = join(baseTmp, `run-${counter++}`);
|
|
31
|
-
const s = new VectorStore({ dedupSim: 0.9, stateDir, config: raptorConfig() });
|
|
32
|
-
// Persist several distinct checkpoints.
|
|
33
|
-
for (let i = 1; i <= 5; i++) {
|
|
34
|
-
compactSession({ sessionId: SESS, messages: [msg(`topic alpha wire ${i} and bootstrap sequence`), msg(`ok ${i}`, "Edit")], keepFrom: 2, timestamp: i }, s);
|
|
35
|
-
}
|
|
36
|
-
// No tree yet → flat search only, returns hits, no RAPTOR coverage.
|
|
37
|
-
assert.equal(listRaptorNodes(SESS, stateDir).length, 0, "no tree initially");
|
|
38
|
-
const flat = vectorSearch(s, SESS, "alpha wire bootstrap", 3);
|
|
39
|
-
assert.ok(flat.length > 0, "flat search returns hits");
|
|
40
|
-
// Build + persist a RAPTOR tree for the session (mirrors runCompact refresh).
|
|
41
|
-
const all = vectorList(s, SESS);
|
|
42
|
-
const leaves = all.map((cp) => ({
|
|
43
|
-
id: cp.checkpointId,
|
|
44
|
-
messages: [],
|
|
45
|
-
sourceText: cp.normalizedText ?? cp.summary ?? cp.regionHash,
|
|
46
|
-
embedding: cp.embedding,
|
|
47
|
-
}));
|
|
48
|
-
const tree = runRaptor(leaves, { stateDir, sessionId: SESS, logger: new Logger() });
|
|
49
|
-
assert.ok(tree && listRaptorNodes(SESS, stateDir).length > 0, "tree persisted");
|
|
50
|
-
// With the tree live + RAPTOR_ENABLED, search still returns hits and now
|
|
51
|
-
// exercises the RAPTOR-served path without regression.
|
|
52
|
-
const withTree = vectorSearch(s, SESS, "alpha wire bootstrap", 3);
|
|
53
|
-
assert.ok(withTree.length > 0, "search returns hits with RAPTOR promoted");
|
|
54
|
-
// Every returned hit is a real checkpoint in the session.
|
|
55
|
-
for (const h of withTree) {
|
|
56
|
-
assert.ok(all.some((cp) => cp.checkpointId === h.checkpoint.checkpointId), "hit is a real checkpoint");
|
|
57
|
-
}
|
|
58
|
-
});
|
|
59
|
-
test("Fix D: search still works for a session with <2 leaves (no tree)", () => {
|
|
60
|
-
const stateDir = join(baseTmp, `run-${counter++}`);
|
|
61
|
-
const s = new VectorStore({ dedupSim: 0.9, stateDir, config: raptorConfig() });
|
|
62
|
-
compactSession({ sessionId: SESS, messages: [msg("only one topic here"), msg("ok", "Edit")], keepFrom: 2, timestamp: 1 }, s);
|
|
63
|
-
const r = vectorSearch(s, SESS, "only one topic", 3);
|
|
64
|
-
assert.ok(r.length > 0, "single-checkpoint search still works (no tree)");
|
|
65
|
-
assert.equal(listRaptorNodes(SESS, stateDir).length, 0, "no tree built for <2 leaves");
|
|
66
|
-
});
|
|
67
|
-
test("cleanup", () => {
|
|
68
|
-
rmSync(baseTmp, { recursive: true, force: true });
|
|
69
|
-
});
|
|
@@ -1,248 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* raptor.test.ts — hermetic unit tests for the Sprint 13 RAPTOR module.
|
|
3
|
-
*
|
|
4
|
-
* No network: the default summarizer is deterministic extractive, and Ollama is
|
|
5
|
-
* only reached when MEGACOMPACT_RAPTOR_MODEL is set (never here). Retrieval from
|
|
6
|
-
* the live store is never touched (shadow mode), so recallAndInline output is
|
|
7
|
-
* unchanged by construction.
|
|
8
|
-
*/
|
|
9
|
-
import { test } from "node:test";
|
|
10
|
-
import assert from "node:assert/strict";
|
|
11
|
-
import { mkdtempSync, rmSync } from "node:fs";
|
|
12
|
-
import { tmpdir } from "node:os";
|
|
13
|
-
import { join } from "node:path";
|
|
14
|
-
import { TrigramEmbedder } from "../../embedder.js";
|
|
15
|
-
import { kmeanspp } from "./kmeans.js";
|
|
16
|
-
import { applyHallucinationGuardrails, sourceTokenSet, extractEntities, makeUngroundedSummary, } from "./guardrails.js";
|
|
17
|
-
import { buildRaptorTree } from "./tree.js";
|
|
18
|
-
import { stagedExpansion } from "./retrieval.js";
|
|
19
|
-
import { runRaptor } from "./index.js";
|
|
20
|
-
import { Logger } from "../../log.js";
|
|
21
|
-
import { listRaptorNodes, clearRaptorNodes, closeStore, } from "../../store/sqlite.js";
|
|
22
|
-
const baseTmp = mkdtempSync(join(tmpdir(), "mc-raptor-"));
|
|
23
|
-
function msg(text) {
|
|
24
|
-
return { role: "user", text };
|
|
25
|
-
}
|
|
26
|
-
/** Build N distinct leaves with deterministic content. */
|
|
27
|
-
function makeLeaves(n, embedder = new TrigramEmbedder()) {
|
|
28
|
-
const leaves = [];
|
|
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
|
-
// --- kmeans: near-zero-variance merge guard ---------------------------------
|
|
41
|
-
test("kmeanspp merges identical points into a single cluster (QA #11)", () => {
|
|
42
|
-
const p = [1, 0, 0];
|
|
43
|
-
const points = [p, p, p, p, p];
|
|
44
|
-
const r = kmeanspp(points, 3, { seed: 1 });
|
|
45
|
-
assert.equal(r.k, 1);
|
|
46
|
-
assert.deepEqual(r.assignments, [0, 0, 0, 0, 0]);
|
|
47
|
-
});
|
|
48
|
-
test("kmeanspp separates two well-separated clusters", () => {
|
|
49
|
-
const a = [1, 0, 0];
|
|
50
|
-
const b = [0, 1, 0];
|
|
51
|
-
const points = [a, a, a, b, b, b];
|
|
52
|
-
const r = kmeanspp(points, 2, { seed: 7 });
|
|
53
|
-
assert.equal(r.k, 2);
|
|
54
|
-
// All the a's share one assignment, all the b's another.
|
|
55
|
-
const firstGroup = r.assignments[0];
|
|
56
|
-
const secondGroup = r.assignments[3];
|
|
57
|
-
assert.notEqual(firstGroup, secondGroup);
|
|
58
|
-
for (let i = 0; i < 3; i++)
|
|
59
|
-
assert.equal(r.assignments[i], firstGroup);
|
|
60
|
-
for (let i = 3; i < 6; i++)
|
|
61
|
-
assert.equal(r.assignments[i], secondGroup);
|
|
62
|
-
});
|
|
63
|
-
// --- guardrails: catch hallucination (QA #16) ------------------------------
|
|
64
|
-
test("guardrails flag an un-grounded entity as extractive_fallback", () => {
|
|
65
|
-
const embedder = new TrigramEmbedder();
|
|
66
|
-
const realSource = "the auth module validates the session token";
|
|
67
|
-
const summary = makeUngroundedSummary(realSource, "ZkPhant0mCorp");
|
|
68
|
-
const sources = [realSource];
|
|
69
|
-
const r = applyHallucinationGuardrails({
|
|
70
|
-
summary,
|
|
71
|
-
sources,
|
|
72
|
-
centroid: embedder.embed(realSource),
|
|
73
|
-
embedder,
|
|
74
|
-
sourceTokens: sourceTokenSet(sources),
|
|
75
|
-
});
|
|
76
|
-
assert.equal(r.marker, "extractive_fallback");
|
|
77
|
-
assert.equal(r.grounded, false);
|
|
78
|
-
});
|
|
79
|
-
test("guardrails pass a faithful, grounded summary", () => {
|
|
80
|
-
const embedder = new TrigramEmbedder();
|
|
81
|
-
const src = "the auth module validates the session token and refreshes the cache";
|
|
82
|
-
const summary = "the auth module validates the session token";
|
|
83
|
-
const sources = [src];
|
|
84
|
-
const r = applyHallucinationGuardrails({
|
|
85
|
-
summary,
|
|
86
|
-
sources,
|
|
87
|
-
centroid: embedder.embed(src),
|
|
88
|
-
embedder,
|
|
89
|
-
sourceTokens: sourceTokenSet(sources),
|
|
90
|
-
});
|
|
91
|
-
assert.equal(r.grounded, true);
|
|
92
|
-
assert.ok(r.marker === "high" || r.marker === "low");
|
|
93
|
-
assert.notEqual(r.marker, "extractive_fallback");
|
|
94
|
-
});
|
|
95
|
-
test("extractEntities lowercases candidate tokens", () => {
|
|
96
|
-
const e = extractEntities("The AuthModule validates the token_abc 42 times");
|
|
97
|
-
assert.ok(e.includes("authmodule"));
|
|
98
|
-
assert.ok(e.includes("token_abc"));
|
|
99
|
-
});
|
|
100
|
-
// --- tree: <10 leaves → single node -----------------------------------------
|
|
101
|
-
test("tree with <10 leaves yields a single root node", () => {
|
|
102
|
-
const leaves = makeLeaves(5);
|
|
103
|
-
const tree = buildRaptorTree(leaves, { embedder: new TrigramEmbedder() });
|
|
104
|
-
assert.equal(tree.nodes.size, 1);
|
|
105
|
-
assert.equal(tree.rootId, "r0_0");
|
|
106
|
-
assert.equal(tree.levels, 1);
|
|
107
|
-
assert.equal(tree.timedOut, false);
|
|
108
|
-
});
|
|
109
|
-
// --- tree: 1K fixture builds within budget ----------------------------------
|
|
110
|
-
test("tree builds within 5s on a 1000-leaf fixture", () => {
|
|
111
|
-
const leaves = makeLeaves(1000);
|
|
112
|
-
const t0 = Date.now();
|
|
113
|
-
const tree = buildRaptorTree(leaves, {
|
|
114
|
-
embedder: new TrigramEmbedder(),
|
|
115
|
-
budgetMs: 5000,
|
|
116
|
-
clustersPerLevel: 8,
|
|
117
|
-
});
|
|
118
|
-
const elapsed = Date.now() - t0;
|
|
119
|
-
assert.ok(elapsed < 5000, `build took ${elapsed}ms (over 5s budget)`);
|
|
120
|
-
assert.ok(tree.nodes.size > 1, "expected a multi-level tree");
|
|
121
|
-
assert.ok(tree.rootId !== null);
|
|
122
|
-
});
|
|
123
|
-
// --- tree: budget timeout → extractive fallback root ------------------------
|
|
124
|
-
test("tree respects the budget: a tiny budget forces an extractive fallback root", () => {
|
|
125
|
-
const leaves = makeLeaves(200);
|
|
126
|
-
const tree = buildRaptorTree(leaves, {
|
|
127
|
-
embedder: new TrigramEmbedder(),
|
|
128
|
-
budgetMs: 0, // forces immediate timeout on the first level
|
|
129
|
-
clustersPerLevel: 4,
|
|
130
|
-
});
|
|
131
|
-
assert.equal(tree.timedOut, true);
|
|
132
|
-
assert.equal(tree.rootId, "r99_0");
|
|
133
|
-
assert.ok(tree.nodes.has("r99_0"));
|
|
134
|
-
});
|
|
135
|
-
// --- extractiveFallbackRoot returns levels: 100 ------------------------------
|
|
136
|
-
test("extractiveFallbackRoot returns levels: 100 (via zero budget)", () => {
|
|
137
|
-
const leaves = makeLeaves(50);
|
|
138
|
-
const tree = buildRaptorTree(leaves, {
|
|
139
|
-
embedder: new TrigramEmbedder(),
|
|
140
|
-
budgetMs: 0, // forces extractive fallback on first within() check
|
|
141
|
-
clustersPerLevel: 4,
|
|
142
|
-
});
|
|
143
|
-
assert.equal(tree.timedOut, true);
|
|
144
|
-
assert.equal(tree.levels, 100, "extractive fallback root must report levels: 100");
|
|
145
|
-
assert.ok(tree.rootId, "fallback root has a rootId");
|
|
146
|
-
const root = tree.nodes.get(tree.rootId);
|
|
147
|
-
assert.ok(root, "fallback root node exists in nodes map");
|
|
148
|
-
assert.equal(root.level, 99, "fallback root node level is 99");
|
|
149
|
-
assert.equal(root.parentId, null, "fallback root parentId is null");
|
|
150
|
-
});
|
|
151
|
-
// --- parentId population on a multi-level tree --------------------------------
|
|
152
|
-
test("buildRaptorTree populates parentId for non-root internal nodes, root keeps null", () => {
|
|
153
|
-
const embedder = new TrigramEmbedder();
|
|
154
|
-
// >= 10 leaves with clustersPerLevel small enough to produce 2 levels
|
|
155
|
-
// of internal nodes (level-1 cluster nodes + level-2 root via collapse).
|
|
156
|
-
const leaves = makeLeaves(20);
|
|
157
|
-
const tree = buildRaptorTree(leaves, { embedder, clustersPerLevel: 4 });
|
|
158
|
-
// Must have at least 2 levels of internal nodes.
|
|
159
|
-
assert.ok(tree.levels >= 2, `expected >= 2 levels, got ${tree.levels}`);
|
|
160
|
-
assert.ok(tree.rootId, "tree must have a root");
|
|
161
|
-
// The root keeps parentId null.
|
|
162
|
-
const root = tree.nodes.get(tree.rootId);
|
|
163
|
-
assert.ok(root, "root node in map");
|
|
164
|
-
assert.equal(root.parentId, null, "root parentId must be null");
|
|
165
|
-
// Every non-root internal node must have a non-null parentId pointing to
|
|
166
|
-
// another node in the tree (its parent).
|
|
167
|
-
let nonRootCount = 0;
|
|
168
|
-
for (const node of tree.nodes.values()) {
|
|
169
|
-
if (node.id === tree.rootId)
|
|
170
|
-
continue;
|
|
171
|
-
nonRootCount++;
|
|
172
|
-
assert.ok(node.parentId !== null, `non-root node ${node.id} must have non-null parentId`);
|
|
173
|
-
assert.ok(tree.nodes.has(node.parentId), `parentId ${node.parentId} of node ${node.id} must exist in tree`);
|
|
174
|
-
assert.notEqual(node.parentId, node.id, `node ${node.id} must not be its own parent`);
|
|
175
|
-
}
|
|
176
|
-
assert.ok(nonRootCount > 0, "tree must have at least one non-root internal node");
|
|
177
|
-
});
|
|
178
|
-
// --- retrieval: staged expansion returns leaf ids ---------------------------
|
|
179
|
-
test("stagedExpansion returns diversified leaf ids for a query", () => {
|
|
180
|
-
const leaves = makeLeaves(20);
|
|
181
|
-
const tree = buildRaptorTree(leaves, { embedder: new TrigramEmbedder(), clustersPerLevel: 4 });
|
|
182
|
-
const hits = stagedExpansion("the auth module validates the session token", tree, {
|
|
183
|
-
embedder: new TrigramEmbedder(),
|
|
184
|
-
k: 3,
|
|
185
|
-
topM: 3,
|
|
186
|
-
});
|
|
187
|
-
assert.ok(hits.length > 0);
|
|
188
|
-
assert.ok(hits.length <= 3);
|
|
189
|
-
// All returned ids are raw leaf ids (not internal node ids).
|
|
190
|
-
for (const id of hits)
|
|
191
|
-
assert.ok(id.startsWith("leaf_"));
|
|
192
|
-
});
|
|
193
|
-
// --- shadow mode: builds + persists, never alters retrieval -----------------
|
|
194
|
-
test("runRaptor builds + persists a shadow tree without throwing", () => {
|
|
195
|
-
const dir = join(baseTmp, `shadow-${Math.floor(performance.now())}`);
|
|
196
|
-
const leaves = makeLeaves(40);
|
|
197
|
-
const logger = new Logger({
|
|
198
|
-
enabled: true,
|
|
199
|
-
now: () => 0,
|
|
200
|
-
path: join(dir, "events.log"),
|
|
201
|
-
});
|
|
202
|
-
const tree = runRaptor(leaves, {
|
|
203
|
-
stateDir: dir,
|
|
204
|
-
sessionId: "sess_raptor",
|
|
205
|
-
embedder: new TrigramEmbedder(),
|
|
206
|
-
logger,
|
|
207
|
-
});
|
|
208
|
-
assert.ok(tree !== null);
|
|
209
|
-
// Tree was persisted to raptor_nodes.
|
|
210
|
-
const stored = listRaptorNodes("sess_raptor", dir);
|
|
211
|
-
assert.ok(stored.length > 0, "shadow tree should be persisted");
|
|
212
|
-
// Quality markers are valid values.
|
|
213
|
-
for (const n of stored) {
|
|
214
|
-
assert.ok(["high", "low", "extractive_fallback"].includes(n.qualityMarker) || n.qualityMarker === "low");
|
|
215
|
-
}
|
|
216
|
-
clearRaptorNodes("sess_raptor", dir);
|
|
217
|
-
closeStore(dir);
|
|
218
|
-
});
|
|
219
|
-
test("shadow mode does NOT change recallAndInline output (separation)", () => {
|
|
220
|
-
// The orchestrator persists to raptor_nodes only. The live store's
|
|
221
|
-
// recallAndInline path (vectorStore.search) reads context_chunks, never
|
|
222
|
-
// raptor_nodes, so building a RAPTOR tree is observably independent.
|
|
223
|
-
const dir = join(baseTmp, `sep-${Math.floor(performance.now())}`);
|
|
224
|
-
const leaves = makeLeaves(15);
|
|
225
|
-
const before = listRaptorNodes("sess_sep", dir);
|
|
226
|
-
runRaptor(leaves, {
|
|
227
|
-
stateDir: dir,
|
|
228
|
-
sessionId: "sess_sep",
|
|
229
|
-
embedder: new TrigramEmbedder(),
|
|
230
|
-
});
|
|
231
|
-
const after = listRaptorNodes("sess_sep", dir);
|
|
232
|
-
// Building RAPTOR only ever writes raptor_nodes; context_chunks is untouched.
|
|
233
|
-
assert.deepEqual(before, []);
|
|
234
|
-
assert.ok(after.length > 0);
|
|
235
|
-
clearRaptorNodes("sess_sep", dir);
|
|
236
|
-
closeStore(dir);
|
|
237
|
-
});
|
|
238
|
-
// --- eval: redundancy reduction ≥ 15% (nodes << leaves) ---------------------
|
|
239
|
-
test("eval: RAPTOR reduces node count substantially vs flat (≥15%)", () => {
|
|
240
|
-
const leaves = makeLeaves(100);
|
|
241
|
-
const tree = buildRaptorTree(leaves, { embedder: new TrigramEmbedder(), clustersPerLevel: 8 });
|
|
242
|
-
const reduction = 1 - tree.nodes.size / leaves.length;
|
|
243
|
-
assert.ok(reduction >= 0.15, `redundancy reduction ${reduction.toFixed(2)} < 0.15`);
|
|
244
|
-
});
|
|
245
|
-
// --- cleanup ----------------------------------------------------------------
|
|
246
|
-
test("RAPTOR cleanup", () => {
|
|
247
|
-
rmSync(baseTmp, { recursive: true, force: true });
|
|
248
|
-
});
|
|
@@ -1,95 +0,0 @@
|
|
|
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
|
-
import { test } from "node:test";
|
|
12
|
-
import assert from "node:assert/strict";
|
|
13
|
-
import { buildChildParentIndex } from "./retrieval.js";
|
|
14
|
-
/** Build a minimal hand-crafted RaptorTree with 2 levels of internal nodes. */
|
|
15
|
-
function handBuiltTree() {
|
|
16
|
-
// 8 leaves (leaf_0..leaf_7) under 2 level-1 nodes, under 1 root.
|
|
17
|
-
const r1_0 = {
|
|
18
|
-
id: "r1_0",
|
|
19
|
-
level: 1,
|
|
20
|
-
parentId: null, // will be set by builder in production, but not needed here
|
|
21
|
-
children: ["leaf_0", "leaf_1", "leaf_2", "leaf_3"],
|
|
22
|
-
summary: "cluster A",
|
|
23
|
-
embedding: [1, 0, 0],
|
|
24
|
-
qualityMarker: "low",
|
|
25
|
-
tokenEstimate: 10,
|
|
26
|
-
};
|
|
27
|
-
const r1_1 = {
|
|
28
|
-
id: "r1_1",
|
|
29
|
-
level: 1,
|
|
30
|
-
parentId: null,
|
|
31
|
-
children: ["leaf_4", "leaf_5", "leaf_6", "leaf_7"],
|
|
32
|
-
summary: "cluster B",
|
|
33
|
-
embedding: [0, 1, 0],
|
|
34
|
-
qualityMarker: "low",
|
|
35
|
-
tokenEstimate: 10,
|
|
36
|
-
};
|
|
37
|
-
const root = {
|
|
38
|
-
id: "root",
|
|
39
|
-
level: 2,
|
|
40
|
-
parentId: null,
|
|
41
|
-
children: [
|
|
42
|
-
"leaf_0", "leaf_1", "leaf_2", "leaf_3",
|
|
43
|
-
"leaf_4", "leaf_5", "leaf_6", "leaf_7",
|
|
44
|
-
],
|
|
45
|
-
summary: "root summary",
|
|
46
|
-
embedding: [0.5, 0.5, 0],
|
|
47
|
-
qualityMarker: "low",
|
|
48
|
-
tokenEstimate: 20,
|
|
49
|
-
};
|
|
50
|
-
const nodes = new Map([
|
|
51
|
-
["r1_0", r1_0],
|
|
52
|
-
["r1_1", r1_1],
|
|
53
|
-
["root", root],
|
|
54
|
-
]);
|
|
55
|
-
return { nodes, rootId: "root", levels: 3, timedOut: false };
|
|
56
|
-
}
|
|
57
|
-
test("buildChildParentIndex: index-derived parent matches linear-scan parent for each leaf", () => {
|
|
58
|
-
const tree = handBuiltTree();
|
|
59
|
-
const leafIds = [
|
|
60
|
-
"leaf_0", "leaf_1", "leaf_2", "leaf_3",
|
|
61
|
-
"leaf_4", "leaf_5", "leaf_6", "leaf_7",
|
|
62
|
-
];
|
|
63
|
-
const index = buildChildParentIndex(tree);
|
|
64
|
-
for (const lid of leafIds) {
|
|
65
|
-
// Old linear-scan semantics: find the first node whose children include lid.
|
|
66
|
-
const linearParent = [...tree.nodes.values()].find((n) => n.children.includes(lid));
|
|
67
|
-
// Index-derived parent.
|
|
68
|
-
const indexParent = index.get(lid);
|
|
69
|
-
// Both must agree.
|
|
70
|
-
assert.equal(indexParent?.id ?? null, linearParent?.id ?? null, `leaf ${lid}: index parent (${indexParent?.id}) != linear parent (${linearParent?.id})`);
|
|
71
|
-
}
|
|
72
|
-
});
|
|
73
|
-
test("buildChildParentIndex: first writer wins (no overwrite for shared leaf)", () => {
|
|
74
|
-
// If two internal nodes both list the same leaf id in their children, the
|
|
75
|
-
// index keeps the FIRST one encountered — matching the find() semantics
|
|
76
|
-
// which also returns the first match.
|
|
77
|
-
const r1_0 = {
|
|
78
|
-
id: "r1_0", level: 1, parentId: null,
|
|
79
|
-
children: ["leaf_0", "leaf_1"],
|
|
80
|
-
summary: "A", embedding: [1, 0], qualityMarker: "low", tokenEstimate: 5,
|
|
81
|
-
};
|
|
82
|
-
const r1_1 = {
|
|
83
|
-
id: "r1_1", level: 1, parentId: null,
|
|
84
|
-
children: ["leaf_0", "leaf_2"], // leaf_0 shared with r1_0
|
|
85
|
-
summary: "B", embedding: [0, 1], qualityMarker: "low", tokenEstimate: 5,
|
|
86
|
-
};
|
|
87
|
-
const nodes = new Map([["r1_0", r1_0], ["r1_1", r1_1]]);
|
|
88
|
-
const tree = { nodes, rootId: null, levels: 2, timedOut: false };
|
|
89
|
-
const index = buildChildParentIndex(tree);
|
|
90
|
-
// leaf_0 appears in both r1_0 and r1_1. The index and find() both return
|
|
91
|
-
// whichever comes first in iteration order.
|
|
92
|
-
const linearParent = [...tree.nodes.values()].find((n) => n.children.includes("leaf_0"));
|
|
93
|
-
const indexParent = index.get("leaf_0");
|
|
94
|
-
assert.equal(indexParent?.id ?? null, linearParent?.id ?? null, "first-writer wins: index and linear scan agree on shared leaf");
|
|
95
|
-
});
|