pi-mega-compact 0.8.20 → 0.8.21
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 +6 -0
- package/dist/extensions/dashboard-client/src/hooks/useApi.js +51 -0
- package/dist/extensions/dashboard-client/src/hooks/useSSE.js +63 -0
- package/dist/extensions/mega-compact-s38.test.js +28 -2
- package/dist/extensions/mega-events/agent-handlers.js +16 -0
- package/dist/extensions/mega-events/error-classifier.js +8 -3
- package/extensions/dashboard-client/package-lock.json +1 -1
- package/extensions/dashboard-client/package.json +1 -1
- package/extensions/mega-compact-s38.test.ts +32 -2
- package/extensions/mega-events/agent-handlers.ts +15 -0
- package/extensions/mega-events/error-classifier.ts +8 -2
- package/package.json +1 -1
- package/dist/extensions/dashboard-server/helpers.js +0 -37
- package/dist/extensions/dashboard-server/html/all-repos-tab.js +0 -26
- package/dist/extensions/dashboard-server/html/body-open.js +0 -23
- package/dist/extensions/dashboard-server/html/current-repo-tab.js +0 -130
- package/dist/extensions/dashboard-server/html/head-open.js +0 -16
- package/dist/extensions/dashboard-server/html/high-score-tab.js +0 -25
- package/dist/extensions/dashboard-server/html/repo-detail-modal.js +0 -26
- package/dist/extensions/dashboard-server/html/script.js +0 -259
- package/dist/extensions/dashboard-server/html/styles.js +0 -103
- package/dist/extensions/dashboard-server/html/summary-tab.js +0 -19
- package/dist/extensions/dashboard-server/html-template.js +0 -41
- package/dist/src/store/sqlite/connection.js +0 -35
- package/dist/src/store/sqlite/index-store.js +0 -167
- package/dist/src/store/sqlite/memory.js +0 -54
- package/dist/src/store/sqlite/minhash-lsh.js +0 -47
- package/dist/src/store/sqlite/sessions.js +0 -39
- package/dist/src/store/sqlite/transaction.js +0 -19
- package/dist/src/vectorStore/add.js +0 -260
- package/dist/src/vectorStore/dedup.js +0 -52
- package/dist/src/vectorStore/index.js +0 -10
- package/dist/src/vectorStore/queries.js +0 -83
- package/dist/src/vectorStore/search.js +0 -95
- package/dist/src/vectorStore/session.js +0 -19
- package/dist/src/vectorStore/store.js +0 -105
- package/dist/src/vectorStore/types.js +0 -6
- package/dist/src/vectorStore/utils.js +0 -23
|
@@ -1,54 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Durable "save to memory" store (taken over from memory extensions).
|
|
3
|
-
*
|
|
4
|
-
* One SQLite store for user-saved memories, scoped by repo. Mirrors the
|
|
5
|
-
* lessons/sessions pattern: all state lives in SQLite from day one. All queries
|
|
6
|
-
* are parameterized (PREVENT-002).
|
|
7
|
-
*/
|
|
8
|
-
import { getStateDir } from "../../store.js";
|
|
9
|
-
import { openStore } from "./connection.js";
|
|
10
|
-
/** Save a memory to the current repo's store. Returns the new row id. */
|
|
11
|
-
export function addMemory(memory, repo, stateDir = getStateDir()) {
|
|
12
|
-
const db = openStore(stateDir);
|
|
13
|
-
const now = Math.floor(Date.now() / 1000);
|
|
14
|
-
const res = db
|
|
15
|
-
.prepare(`INSERT INTO memories(repo, kind, content, tags, created_at, last_recalled_at)
|
|
16
|
-
VALUES(?, ?, ?, ?, ?, NULL)`)
|
|
17
|
-
.run(repo ?? null, memory.kind ?? "note", memory.content, JSON.stringify(memory.tags ?? []), now);
|
|
18
|
-
return Number(res.lastInsertRowid);
|
|
19
|
-
}
|
|
20
|
-
/** List recent memories for a repo (or all repos when repo is null). */
|
|
21
|
-
export function listMemories(repo, limit = 50, stateDir = getStateDir()) {
|
|
22
|
-
const db = openStore(stateDir);
|
|
23
|
-
const rows = repo
|
|
24
|
-
? db.prepare("SELECT * FROM memories WHERE repo = ? ORDER BY created_at DESC LIMIT ?").all(repo, limit)
|
|
25
|
-
: db.prepare("SELECT * FROM memories ORDER BY created_at DESC LIMIT ?").all(limit);
|
|
26
|
-
return rows.map(mapMemoryRow);
|
|
27
|
-
}
|
|
28
|
-
/** Substring search across content + tags. */
|
|
29
|
-
export function searchMemories(query, repo = null, limit = 50, stateDir = getStateDir()) {
|
|
30
|
-
const db = openStore(stateDir);
|
|
31
|
-
const like = `%${query}%`;
|
|
32
|
-
const rows = repo
|
|
33
|
-
? db.prepare("SELECT * FROM memories WHERE repo = ? AND (content LIKE ? OR tags LIKE ?) ORDER BY created_at DESC LIMIT ?").all(repo, like, like, limit)
|
|
34
|
-
: db.prepare("SELECT * FROM memories WHERE content LIKE ? OR tags LIKE ? ORDER BY created_at DESC LIMIT ?").all(like, like, limit);
|
|
35
|
-
return rows.map(mapMemoryRow);
|
|
36
|
-
}
|
|
37
|
-
/** Mark a memory as recalled (updates last_recalled_at). Returns true if found. */
|
|
38
|
-
export function recallMemory(id, stateDir = getStateDir()) {
|
|
39
|
-
const db = openStore(stateDir);
|
|
40
|
-
const now = Math.floor(Date.now() / 1000);
|
|
41
|
-
const res = db.prepare("UPDATE memories SET last_recalled_at = ? WHERE id = ?").run(now, id);
|
|
42
|
-
return res.changes > 0;
|
|
43
|
-
}
|
|
44
|
-
function mapMemoryRow(row) {
|
|
45
|
-
return {
|
|
46
|
-
id: row.id,
|
|
47
|
-
repo: row.repo ?? null,
|
|
48
|
-
kind: row.kind ?? "note",
|
|
49
|
-
content: row.content ?? "",
|
|
50
|
-
tags: row.tags ? JSON.parse(row.tags) : [],
|
|
51
|
-
createdAt: row.created_at ?? 0,
|
|
52
|
-
lastRecalledAt: row.last_recalled_at ?? null,
|
|
53
|
-
};
|
|
54
|
-
}
|
|
@@ -1,47 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Sprint 11: MinHash signatures + LSH bucket persistence and candidate lookup.
|
|
3
|
-
*
|
|
4
|
-
* All queries are parameterized (PREVENT-002) — never string-concatenated.
|
|
5
|
-
*/
|
|
6
|
-
import { getStateDir, normalizeSessionId } from "../../store.js";
|
|
7
|
-
import { openStore } from "./connection.js";
|
|
8
|
-
import { withTx } from "./transaction.js";
|
|
9
|
-
/** Persist a checkpoint's MinHash signature (idempotent by chunk_id + version). */
|
|
10
|
-
export function upsertMinhashSignature(chunkId, sessionId, signatureVersion, signatures, stateDir = getStateDir()) {
|
|
11
|
-
const db = openStore(stateDir);
|
|
12
|
-
const sid = normalizeSessionId(sessionId);
|
|
13
|
-
db.prepare(`INSERT INTO minhash_signatures(chunk_id, session_id, signature_version, signatures)
|
|
14
|
-
VALUES(?, ?, ?, ?)
|
|
15
|
-
ON CONFLICT(chunk_id, signature_version) DO UPDATE SET
|
|
16
|
-
session_id=excluded.session_id, signatures=excluded.signatures`).run(chunkId, sid, signatureVersion, JSON.stringify(signatures));
|
|
17
|
-
}
|
|
18
|
-
/** Persist LSH bucket memberships for a chunk (one row per bucket key). */
|
|
19
|
-
export function insertLshBuckets(chunkId, sessionId, signatureVersion, bucketKeys, stateDir = getStateDir()) {
|
|
20
|
-
const db = openStore(stateDir);
|
|
21
|
-
const sid = normalizeSessionId(sessionId);
|
|
22
|
-
const del = db.prepare("DELETE FROM dedup_lsh_buckets WHERE chunk_id = ?");
|
|
23
|
-
const ins = db.prepare("INSERT OR IGNORE INTO dedup_lsh_buckets(bucket_key, chunk_id, session_id, signature_version) VALUES(?, ?, ?, ?)");
|
|
24
|
-
withTx(db, () => {
|
|
25
|
-
del.run(chunkId);
|
|
26
|
-
for (const key of bucketKeys)
|
|
27
|
-
ins.run(key, chunkId, sid, signatureVersion);
|
|
28
|
-
});
|
|
29
|
-
}
|
|
30
|
-
/**
|
|
31
|
-
* Candidate chunk_ids sharing any LSH bucket with `bucketKeys`, scoped to the
|
|
32
|
-
* session, capped at `limit`. Single query (no N loops) — QA #15 amplification
|
|
33
|
-
* guard. Returns DISTINCT chunk_ids excluding `excludeChunkId` (the new row).
|
|
34
|
-
*/
|
|
35
|
-
export function lshCandidateChunks(bucketKeys, sessionId, excludeChunkId, stateDir = getStateDir(), limit = 100) {
|
|
36
|
-
if (bucketKeys.length === 0)
|
|
37
|
-
return [];
|
|
38
|
-
const db = openStore(stateDir);
|
|
39
|
-
const sid = normalizeSessionId(sessionId);
|
|
40
|
-
const placeholders = bucketKeys.map(() => "?").join(",");
|
|
41
|
-
const rows = db
|
|
42
|
-
.prepare(`SELECT DISTINCT chunk_id FROM dedup_lsh_buckets
|
|
43
|
-
WHERE bucket_key IN (${placeholders}) AND session_id = ? AND chunk_id != ?
|
|
44
|
-
LIMIT ?`)
|
|
45
|
-
.all(...bucketKeys, sid, excludeChunkId, limit);
|
|
46
|
-
return rows.map((r) => r.chunk_id);
|
|
47
|
-
}
|
|
@@ -1,39 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Future-feature foundation: resume sessions, daily activity log, lessons learned.
|
|
3
|
-
*
|
|
4
|
-
* Scaffolded tables + minimal helpers so all store data lives in SQLite from
|
|
5
|
-
* day one. Full UI/recall for these lands in later sprints. All queries are
|
|
6
|
-
* parameterized (PREVENT-002).
|
|
7
|
-
*/
|
|
8
|
-
import { getStateDir, normalizeSessionId } from "../../store.js";
|
|
9
|
-
import { openStore } from "./connection.js";
|
|
10
|
-
/** Upsert a `sessions` row (resume + per-repo session history). */
|
|
11
|
-
export function touchSession(sessionId, repo, stateDir = getStateDir()) {
|
|
12
|
-
const db = openStore(stateDir);
|
|
13
|
-
const sid = normalizeSessionId(sessionId);
|
|
14
|
-
const existing = db
|
|
15
|
-
.prepare("SELECT started_at FROM sessions WHERE session_id = ?")
|
|
16
|
-
.get(sid);
|
|
17
|
-
const now = Math.floor(Date.now() / 1000);
|
|
18
|
-
if (!existing) {
|
|
19
|
-
db.prepare(`INSERT INTO sessions(session_id, repo, started_at, last_compacted_at, status)
|
|
20
|
-
VALUES(?, ?, ?, ?, 'active')`).run(sid, repo ?? null, now, now);
|
|
21
|
-
}
|
|
22
|
-
else {
|
|
23
|
-
db.prepare("UPDATE sessions SET last_compacted_at = ?, repo = COALESCE(?, repo), status = 'active' WHERE session_id = ?").run(now, repo ?? null, sid);
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
-
/** Append a `daily_log` entry (day = YYYY-MM-DD, local-naive from Date). */
|
|
27
|
-
export function logDaily(sessionId, event, detail, tokensSaved, stateDir = getStateDir()) {
|
|
28
|
-
const db = openStore(stateDir);
|
|
29
|
-
const day = new Date().toISOString().slice(0, 10);
|
|
30
|
-
const now = Math.floor(Date.now() / 1000);
|
|
31
|
-
db.prepare(`INSERT INTO daily_log(day, session_id, event, detail, tokens_saved, ts)
|
|
32
|
-
VALUES(?, ?, ?, ?, ?, ?)`).run(day, normalizeSessionId(sessionId), event, detail ?? null, tokensSaved, now);
|
|
33
|
-
}
|
|
34
|
-
/** Append a `lessons` entry (future lessons-learned browse/recall). */
|
|
35
|
-
export function addLesson(sessionId, repo, lesson, stateDir = getStateDir()) {
|
|
36
|
-
const db = openStore(stateDir);
|
|
37
|
-
const now = Math.floor(Date.now() / 1000);
|
|
38
|
-
db.prepare(`INSERT INTO lessons(session_id, repo, lesson, ts) VALUES(?, ?, ?, ?)`).run(normalizeSessionId(sessionId), repo ?? null, lesson, now);
|
|
39
|
-
}
|
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Transaction wrapper using SAVEPOINT so it nests safely under an outer
|
|
3
|
-
* transaction (unlike `BEGIN`, which SQLite rejects when one is already open).
|
|
4
|
-
*
|
|
5
|
-
* Mirrors better-sqlite3's `db.transaction(fn)` semantics — callers that wrap a
|
|
6
|
-
* batch in withTx (e.g. backfill) can still call helpers that also use withTx.
|
|
7
|
-
*/
|
|
8
|
-
export function withTx(db, fn) {
|
|
9
|
-
db.exec("SAVEPOINT mc_tx");
|
|
10
|
-
try {
|
|
11
|
-
fn();
|
|
12
|
-
db.exec("RELEASE mc_tx");
|
|
13
|
-
}
|
|
14
|
-
catch (e) {
|
|
15
|
-
db.exec("ROLLBACK TO mc_tx");
|
|
16
|
-
db.exec("RELEASE mc_tx");
|
|
17
|
-
throw e;
|
|
18
|
-
}
|
|
19
|
-
}
|
|
@@ -1,260 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* vectorStore/add.ts — Add/insert operations: the dedup cascade and L1 lookup.
|
|
3
|
-
*/
|
|
4
|
-
import { createHash } from "node:crypto";
|
|
5
|
-
import { cosineSimilarity } from "../embedder.js";
|
|
6
|
-
import { normalizeSessionId, compressSmart } from "../store.js";
|
|
7
|
-
import { computeContentDigest } from "../dedup/digest.js";
|
|
8
|
-
import { minhashSignature, SIGNATURE_VERSION, NUM_HASHES } from "../dedup/l1-minhash.js";
|
|
9
|
-
import { lshBands } from "../dedup/l1-lsh.js";
|
|
10
|
-
import { isNearDuplicate } from "../dedup/l1-verify.js";
|
|
11
|
-
import { openBloom, saveBloom } from "../store/bloom.js";
|
|
12
|
-
import { listCheckpoints, nextCheckpointId, upsertCheckpoint, loadSessionState, saveSessionState, upsertMinhashSignature, insertLshBuckets, lshCandidateChunks, bumpDedupStats, addTokensSaved, } from "../store/sqlite.js";
|
|
13
|
-
import { computeRegionHash, recordDecision } from "./utils.js";
|
|
14
|
-
/**
|
|
15
|
-
* L1 near-duplicate lookup: MinHash → LSH candidate retrieval → trigram verify.
|
|
16
|
-
* Returns the matching checkpoint or undefined. Bounded by a 100-candidate cap
|
|
17
|
-
* and a 20ms verify budget (QA #7/#15) so it never hangs a large session.
|
|
18
|
-
*/
|
|
19
|
-
export function findL1Duplicate(ctx, sessionId, regionText, all) {
|
|
20
|
-
if (all.length === 0)
|
|
21
|
-
return undefined;
|
|
22
|
-
const sig = minhashSignature(regionText);
|
|
23
|
-
if (sig.length !== NUM_HASHES)
|
|
24
|
-
return undefined;
|
|
25
|
-
const bands = lshBands(sig, sessionId, SIGNATURE_VERSION);
|
|
26
|
-
// Cheap candidate retrieval (single query, capped). Exclude nothing yet —
|
|
27
|
-
// the new checkpoint has no id, so pass a sentinel that never matches.
|
|
28
|
-
const candidateIds = lshCandidateChunks(bands, sessionId, "__new__", ctx.stateDir, 100);
|
|
29
|
-
if (candidateIds.length === 0)
|
|
30
|
-
return undefined;
|
|
31
|
-
const byId = new Map(all.map((cp) => [cp.checkpointId, cp]));
|
|
32
|
-
const VERIFY_BUDGET_MS = 20;
|
|
33
|
-
const start = Date.now();
|
|
34
|
-
for (const id of candidateIds) {
|
|
35
|
-
if (Date.now() - start > VERIFY_BUDGET_MS)
|
|
36
|
-
break; // QA #15: abort → "not dup"
|
|
37
|
-
const cand = byId.get(id);
|
|
38
|
-
if (!cand)
|
|
39
|
-
continue;
|
|
40
|
-
const candText = cand.normalizedText ?? cand.summary ?? "";
|
|
41
|
-
if (isNearDuplicate(regionText, candText))
|
|
42
|
-
return cand;
|
|
43
|
-
}
|
|
44
|
-
return undefined;
|
|
45
|
-
}
|
|
46
|
-
/**
|
|
47
|
-
* Add a checkpoint. Dedup cascade:
|
|
48
|
-
* 1. regionHash exact match (legacy, backward-compat)
|
|
49
|
-
* 2. summaryHash exact match (new: catches same-topic incremental compactions)
|
|
50
|
-
* 3. content similarity ≥ dedupSim (catches near-identical summaries)
|
|
51
|
-
* 4. If none match → create new checkpoint
|
|
52
|
-
*/
|
|
53
|
-
export function addToStore(ctx, input) {
|
|
54
|
-
const t0 = Date.now();
|
|
55
|
-
const sessionId = normalizeSessionId(input.sessionId);
|
|
56
|
-
const regionHash = computeRegionHash(input.regionText);
|
|
57
|
-
const all = listCheckpoints(sessionId, ctx.stateDir);
|
|
58
|
-
// Honest "tokens saved" base for this region. For a deduped add the whole
|
|
59
|
-
// original region is discarded (nothing new stored); for a new checkpoint
|
|
60
|
-
// we persist (orig − stored). Falls back to stored when orig is unknown.
|
|
61
|
-
const origTokens = input.originalTokenEstimate ?? input.tokenEstimate ?? 0;
|
|
62
|
-
const cfg = ctx.cfg;
|
|
63
|
-
// Live per-tier progress hook (Phase 1). Sync + optional; fired at each tier
|
|
64
|
-
// so the UI can paint "L0 ✓ → L1 ✓ → L2 0.91 → stored" during a compaction.
|
|
65
|
-
const onTier = input.onTier;
|
|
66
|
-
// Tracks whether a tier matched while in MARK_ONLY (record-but-don't-collapse),
|
|
67
|
-
// and which tier.
|
|
68
|
-
let markOnly = null;
|
|
69
|
-
// 0. L0 content-hash dedup (Sprint 9) — catches identical content arriving
|
|
70
|
-
// under different regionText. Normalization handles case/whitespace/ANSI so
|
|
71
|
-
// variants collapse to one row. Dual-hash guards a single-hash collision.
|
|
72
|
-
// Sprint 10: bloom is the accelerator — a miss means "definitely new" and
|
|
73
|
-
// skips the scan; a hit is only a candidate, confirmed against `all` below.
|
|
74
|
-
// Gated by L0_ENABLED (Sprint 14). MARK_ONLY_L0 records the decision but
|
|
75
|
-
// does not collapse — the new region is still stored.
|
|
76
|
-
onTier?.({ tier: "L0", status: "scanning" });
|
|
77
|
-
const digest = computeContentDigest(input.regionText);
|
|
78
|
-
const bloom = openBloom(ctx.stateDir);
|
|
79
|
-
if (cfg.L0_ENABLED && bloom.maybeHas(digest.contentHash)) {
|
|
80
|
-
const contentMatch = all.find((cp) => cp.contentHash === digest.contentHash &&
|
|
81
|
-
cp.contentHash2 === digest.contentHash2);
|
|
82
|
-
if (contentMatch) {
|
|
83
|
-
if (cfg.MARK_ONLY_L0) {
|
|
84
|
-
markOnly = "L0"; // Record-but-don't-collapse: fall through.
|
|
85
|
-
}
|
|
86
|
-
else {
|
|
87
|
-
contentMatch.timestamp = input.timestamp;
|
|
88
|
-
upsertCheckpoint(contentMatch, ctx.stateDir);
|
|
89
|
-
bumpDedupStats(true, ctx.stateDir);
|
|
90
|
-
// Deduped: whole original region discarded, nothing new stored.
|
|
91
|
-
addTokensSaved(origTokens, ctx.stateDir);
|
|
92
|
-
const r = { checkpoint: contentMatch, deduped: true, reason: "contentHash" };
|
|
93
|
-
recordDecision(ctx, "L0", "deduped", "contentHash", Date.now() - t0);
|
|
94
|
-
onTier?.({ tier: "L0", status: "deduped", detail: "contentHash" });
|
|
95
|
-
return r;
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
// 1. Legacy regionHash dedup (backward-compat) — part of L0 tier gating.
|
|
100
|
-
if (cfg.L0_ENABLED) {
|
|
101
|
-
const regionMatch = all.find((cp) => cp.regionHash === regionHash);
|
|
102
|
-
if (regionMatch) {
|
|
103
|
-
if (cfg.MARK_ONLY_L0) {
|
|
104
|
-
markOnly = "L0"; // fall through
|
|
105
|
-
}
|
|
106
|
-
else {
|
|
107
|
-
bumpDedupStats(true, ctx.stateDir);
|
|
108
|
-
// Deduped: whole original region discarded, nothing new stored.
|
|
109
|
-
addTokensSaved(origTokens, ctx.stateDir);
|
|
110
|
-
const r = { checkpoint: regionMatch, deduped: true, reason: "regionHash" };
|
|
111
|
-
recordDecision(ctx, "L0", "deduped", "regionHash", Date.now() - t0);
|
|
112
|
-
onTier?.({ tier: "L0", status: "deduped", detail: "regionHash" });
|
|
113
|
-
return r;
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
// 2. SummaryHash dedup — catches same-topic incremental compactions.
|
|
118
|
-
// Full 64-hex SHA-256 (was 16-hex in Sprint 8 — collision-prone).
|
|
119
|
-
const summaryHash = input.topicSummary
|
|
120
|
-
? createHash("sha256").update(input.topicSummary).digest("hex")
|
|
121
|
-
: undefined;
|
|
122
|
-
if (summaryHash && cfg.L0_ENABLED) {
|
|
123
|
-
const summaryMatch = all.find((cp) => cp.summaryHash === summaryHash);
|
|
124
|
-
if (summaryMatch) {
|
|
125
|
-
if (cfg.MARK_ONLY_L0) {
|
|
126
|
-
markOnly = "L0"; // fall through
|
|
127
|
-
}
|
|
128
|
-
else {
|
|
129
|
-
summaryMatch.timestamp = input.timestamp;
|
|
130
|
-
upsertCheckpoint(summaryMatch, ctx.stateDir);
|
|
131
|
-
bumpDedupStats(true, ctx.stateDir);
|
|
132
|
-
// Deduped: whole original region discarded, nothing new stored.
|
|
133
|
-
addTokensSaved(origTokens, ctx.stateDir);
|
|
134
|
-
const r = { checkpoint: summaryMatch, deduped: true, reason: "summaryHash" };
|
|
135
|
-
recordDecision(ctx, "L0", "deduped", "summaryHash", Date.now() - t0);
|
|
136
|
-
onTier?.({ tier: "L0", status: "deduped", detail: "summaryHash" });
|
|
137
|
-
return r;
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
// L0 did not collapse this region.
|
|
142
|
-
onTier?.({ tier: "L0", status: "passed" });
|
|
143
|
-
// 2b. L1 MinHash/LSH near-duplicate dedup (Sprint 11) — catches one-word
|
|
144
|
-
// edits / rewordings that L0's exact hash misses. Cheap LSH bucket
|
|
145
|
-
// retrieval → trigram verification (pg_trgm-equivalent) as the final gate.
|
|
146
|
-
// Gated by L1_ENABLED (Sprint 14); MARK_ONLY_L1 records but doesn't collapse.
|
|
147
|
-
onTier?.({ tier: "L1", status: "scanning" });
|
|
148
|
-
if (cfg.L1_ENABLED) {
|
|
149
|
-
const l1 = findL1Duplicate(ctx, sessionId, input.regionText, all);
|
|
150
|
-
if (l1 && !cfg.MARK_ONLY_L1) {
|
|
151
|
-
l1.timestamp = input.timestamp;
|
|
152
|
-
upsertCheckpoint(l1, ctx.stateDir);
|
|
153
|
-
bumpDedupStats(true, ctx.stateDir);
|
|
154
|
-
const r = { checkpoint: l1, deduped: true, reason: "l1MinHash" };
|
|
155
|
-
recordDecision(ctx, "L1", "deduped", "l1MinHash", Date.now() - t0);
|
|
156
|
-
onTier?.({ tier: "L1", status: "deduped", detail: "l1MinHash" });
|
|
157
|
-
return r;
|
|
158
|
-
}
|
|
159
|
-
if (l1 && cfg.MARK_ONLY_L1)
|
|
160
|
-
markOnly = "L1";
|
|
161
|
-
}
|
|
162
|
-
onTier?.({ tier: "L1", status: "passed" });
|
|
163
|
-
// 3. L2 semantic dedup — catches near-identical / semantically-similar regions
|
|
164
|
-
// via cosine over the embedding. topicSummary is used for summaryHash dedup
|
|
165
|
-
// (tier 2); the vector index is keyed on the original region for backward-
|
|
166
|
-
// compat search semantics. Threshold from cfg (L2_COSINE trigram honest
|
|
167
|
-
// firing point). QA #13 timeout guard: if the O(n) scan exceeds the budget,
|
|
168
|
-
// degrade to "store without dedup this pass" so we never lose a checkpoint.
|
|
169
|
-
// Gated by L2_ENABLED (Sprint 14); MARK_ONLY_L2 records but doesn't collapse.
|
|
170
|
-
const SIMILARITY_BUDGET_MS = cfg.SIMILARITY_BUDGET_MS;
|
|
171
|
-
const simThreshold = ctx.l2Threshold; // from cfg.L2_COSINE (default 0.85 trigram)
|
|
172
|
-
const embedding = ctx.embedder.embed(input.regionText);
|
|
173
|
-
onTier?.({ tier: "L2", status: "scanning" });
|
|
174
|
-
if (cfg.L2_ENABLED && all.length > 0) {
|
|
175
|
-
const start = Date.now();
|
|
176
|
-
let timedOut = false;
|
|
177
|
-
const nearest = all.reduce((best, cp) => {
|
|
178
|
-
if (!timedOut && Date.now() - start > SIMILARITY_BUDGET_MS)
|
|
179
|
-
timedOut = true;
|
|
180
|
-
if (timedOut)
|
|
181
|
-
return best;
|
|
182
|
-
const sim = cosineSimilarity(embedding, cp.embedding);
|
|
183
|
-
return sim > best.sim ? { checkpoint: cp, sim } : best;
|
|
184
|
-
}, { checkpoint: all[0], sim: -1 });
|
|
185
|
-
if (!timedOut && nearest.sim >= simThreshold) {
|
|
186
|
-
if (!cfg.MARK_ONLY_L2) {
|
|
187
|
-
// Near-identical — update timestamp on existing checkpoint
|
|
188
|
-
nearest.checkpoint.timestamp = input.timestamp;
|
|
189
|
-
upsertCheckpoint(nearest.checkpoint, ctx.stateDir);
|
|
190
|
-
bumpDedupStats(true, ctx.stateDir);
|
|
191
|
-
// Deduped: whole original region discarded, nothing new stored.
|
|
192
|
-
addTokensSaved(origTokens, ctx.stateDir);
|
|
193
|
-
const r = { checkpoint: nearest.checkpoint, deduped: true, reason: "contentSimilarity" };
|
|
194
|
-
recordDecision(ctx, "L2", "deduped", "contentSimilarity", Date.now() - t0);
|
|
195
|
-
onTier?.({ tier: "L2", status: "deduped", detail: nearest.sim.toFixed(2) });
|
|
196
|
-
return r;
|
|
197
|
-
}
|
|
198
|
-
markOnly = "L2";
|
|
199
|
-
}
|
|
200
|
-
onTier?.({ tier: "L2", status: "passed", detail: `best ${nearest.sim.toFixed(2)}` });
|
|
201
|
-
}
|
|
202
|
-
// 4. Genuinely new — create checkpoint
|
|
203
|
-
const checkpointId = nextCheckpointId(sessionId, ctx.stateDir);
|
|
204
|
-
const checkpoint = {
|
|
205
|
-
checkpointId,
|
|
206
|
-
sessionId,
|
|
207
|
-
summary: input.summary,
|
|
208
|
-
topicSummary: input.topicSummary,
|
|
209
|
-
summaryHash,
|
|
210
|
-
keyDecisions: input.keyDecisions ?? [],
|
|
211
|
-
nextSteps: input.nextSteps ?? [],
|
|
212
|
-
filesModified: input.filesModified ?? [],
|
|
213
|
-
tokenEstimate: input.tokenEstimate ?? 0,
|
|
214
|
-
originalTokenEstimate: input.originalTokenEstimate,
|
|
215
|
-
regionHash,
|
|
216
|
-
contentHash: digest.contentHash,
|
|
217
|
-
contentHash2: digest.contentHash2,
|
|
218
|
-
contentHashVersion: digest.contentHashVersion,
|
|
219
|
-
normalizedText: digest.normalizedText,
|
|
220
|
-
compressedOriginal: compressSmart(Buffer.from(input.regionText, "utf-8"), input.compressionPressure),
|
|
221
|
-
embedding,
|
|
222
|
-
timestamp: input.timestamp,
|
|
223
|
-
};
|
|
224
|
-
// Persistence is SQLite (store/sqlite.ts). upsertCheckpoint keeps the
|
|
225
|
-
// idempotent-by-id semantics the old JSON append implied.
|
|
226
|
-
upsertCheckpoint(checkpoint, ctx.stateDir);
|
|
227
|
-
// Cumulative "tokens saved" counter (per-repo SQLite meta). For a NEW
|
|
228
|
-
// checkpoint the saved amount is (original − stored); for a deduped add the
|
|
229
|
-
// whole original region is discarded (handled in the deduped return paths
|
|
230
|
-
// below). Survives sessions and travels with the repo.
|
|
231
|
-
const stored = input.tokenEstimate ?? 0;
|
|
232
|
-
addTokensSaved(Math.max(0, origTokens - stored), ctx.stateDir);
|
|
233
|
-
// L1: persist this checkpoint's MinHash signature + LSH buckets so future
|
|
234
|
-
// near-duplicate inserts can find it. Deterministic given the seed.
|
|
235
|
-
const sig = minhashSignature(input.regionText);
|
|
236
|
-
upsertMinhashSignature(checkpointId, sessionId, SIGNATURE_VERSION, sig, ctx.stateDir);
|
|
237
|
-
insertLshBuckets(checkpointId, sessionId, SIGNATURE_VERSION, lshBands(sig, sessionId, SIGNATURE_VERSION), ctx.stateDir);
|
|
238
|
-
// Bloom accelerator: record the new content_hash so a future add() can short-
|
|
239
|
-
// circuit the scan on a hit (still confirmed by the SELECT-based `all` above).
|
|
240
|
-
bloom.add(digest.contentHash);
|
|
241
|
-
saveBloom(ctx.stateDir);
|
|
242
|
-
// Track the region hash in session state for fast sentinel checks.
|
|
243
|
-
const state = loadSessionState(sessionId, ctx.stateDir);
|
|
244
|
-
if (!state.storedRegionHashes.includes(regionHash)) {
|
|
245
|
-
state.storedRegionHashes.push(regionHash);
|
|
246
|
-
saveSessionState(sessionId, state, ctx.stateDir);
|
|
247
|
-
}
|
|
248
|
-
// A new checkpoint. If a tier matched while MARK_ONLY, record that (the
|
|
249
|
-
// decision fired but we intentionally did not collapse).
|
|
250
|
-
if (markOnly) {
|
|
251
|
-
recordDecision(ctx, markOnly, "mark_only", "mark_only", Date.now() - t0);
|
|
252
|
-
}
|
|
253
|
-
else {
|
|
254
|
-
recordDecision(ctx, "L0", "new", undefined, Date.now() - t0);
|
|
255
|
-
}
|
|
256
|
-
// Cumulative store-wide dedup accounting (attempt, not collapsed).
|
|
257
|
-
bumpDedupStats(false, ctx.stateDir);
|
|
258
|
-
onTier?.({ tier: "new", status: "stored" });
|
|
259
|
-
return { checkpoint, deduped: false };
|
|
260
|
-
}
|
|
@@ -1,52 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* vectorStore/dedup.ts — SemDeDup cleanup and dedup sentinel check.
|
|
3
|
-
*/
|
|
4
|
-
import { cosineSimilarity } from "../embedder.js";
|
|
5
|
-
import { normalizeSessionId } from "../store.js";
|
|
6
|
-
import { listCheckpoints, setDedupStatus, loadSessionState } from "../store/sqlite.js";
|
|
7
|
-
import { computeRegionHash } from "./utils.js";
|
|
8
|
-
/**
|
|
9
|
-
* SemDeDup offline cleanup (Sprint 12, QA #17): within a session, mark the
|
|
10
|
-
* lower-quality row of any pair scoring cosine > `threshold` as
|
|
11
|
-
* `dedup_status='removed'` (kept, not deleted — retrieval excludes it). Keeps
|
|
12
|
-
* the row with the higher `tokenEstimate` (more context preserved). Runs as a
|
|
13
|
-
* single scan; idempotent (re-running skips already-removed rows).
|
|
14
|
-
*
|
|
15
|
-
* Returns the number of rows marked removed.
|
|
16
|
-
*/
|
|
17
|
-
export function semDedupStore(ctx, sessionId, threshold) {
|
|
18
|
-
const sid = normalizeSessionId(sessionId);
|
|
19
|
-
const cps = listCheckpoints(sid, ctx.stateDir).filter((c) => c.dedupStatus !== "removed");
|
|
20
|
-
let removed = 0;
|
|
21
|
-
for (let i = 0; i < cps.length; i++) {
|
|
22
|
-
for (let j = i + 1; j < cps.length; j++) {
|
|
23
|
-
const a = cps[i];
|
|
24
|
-
const b = cps[j];
|
|
25
|
-
if (a.dedupStatus === "removed" || b.dedupStatus === "removed")
|
|
26
|
-
continue;
|
|
27
|
-
if (cosineSimilarity(a.embedding, b.embedding) > threshold) {
|
|
28
|
-
// Keep the higher-tokenEstimate row; remove the other.
|
|
29
|
-
const keep = a.tokenEstimate >= b.tokenEstimate ? a : b;
|
|
30
|
-
const drop = keep === a ? b : a;
|
|
31
|
-
setDedupStatus(drop.checkpointId, sid, "removed", ctx.stateDir);
|
|
32
|
-
drop.dedupStatus = "removed";
|
|
33
|
-
removed++;
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
return removed;
|
|
38
|
-
}
|
|
39
|
-
/**
|
|
40
|
-
* Dedup sentinel check: has this region already been stored/represented?
|
|
41
|
-
* Consulted by both the persist path and the recall/inline path.
|
|
42
|
-
*/
|
|
43
|
-
export function dedupeCheck(ctx, sessionId, regionHashOrText, isText = false) {
|
|
44
|
-
const sid = normalizeSessionId(sessionId);
|
|
45
|
-
const hash = isText
|
|
46
|
-
? computeRegionHash(regionHashOrText)
|
|
47
|
-
: regionHashOrText;
|
|
48
|
-
const state = loadSessionState(sid, ctx.stateDir);
|
|
49
|
-
if (state.storedRegionHashes.includes(hash))
|
|
50
|
-
return true;
|
|
51
|
-
return listCheckpoints(sid, ctx.stateDir).some((c) => c.regionHash === hash);
|
|
52
|
-
}
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* vectorStore/index.ts — Barrel re-export for the vector store sub-modules.
|
|
3
|
-
*
|
|
4
|
-
* All public symbols previously exported from the monolithic `vectorStore.ts`
|
|
5
|
-
* are re-exported here so existing imports (`from "./vectorStore.js"`) continue
|
|
6
|
-
* to work unchanged.
|
|
7
|
-
*/
|
|
8
|
-
export { L2_ENABLED } from "./types.js";
|
|
9
|
-
export { computeRegionHash } from "./utils.js";
|
|
10
|
-
export { VectorStore } from "./store.js";
|
|
@@ -1,83 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* vectorStore/queries.ts — Read-only queries: list, topSimilar, stats, repoStats,
|
|
3
|
-
* dataInvariant, similarity.
|
|
4
|
-
*/
|
|
5
|
-
import { cosineSimilarity } from "../embedder.js";
|
|
6
|
-
import { normalizeSessionId } from "../store.js";
|
|
7
|
-
import { listCheckpoints, loadSessionState, getDedupStats, repoStats as repoStatsFromStore, dataInvariantStats, } from "../store/sqlite.js";
|
|
8
|
-
/** All checkpoints for a session (sorted by checkpointId). */
|
|
9
|
-
export function listSession(ctx, sessionId) {
|
|
10
|
-
return listCheckpoints(normalizeSessionId(sessionId), ctx.stateDir);
|
|
11
|
-
}
|
|
12
|
-
/** Convenience for a raw vector cosine (exposed for tests). */
|
|
13
|
-
export function similarityScore(a, b) {
|
|
14
|
-
return cosineSimilarity(a, b);
|
|
15
|
-
}
|
|
16
|
-
/**
|
|
17
|
-
* Return the n most similar checkpoints to the current (most recent) checkpoint
|
|
18
|
-
* by cosine similarity. Returns fewer than n if the session has fewer checkpoints.
|
|
19
|
-
* The current checkpoint itself is excluded from results.
|
|
20
|
-
*/
|
|
21
|
-
export function topSimilarSession(ctx, sessionId, n) {
|
|
22
|
-
const sid = normalizeSessionId(sessionId);
|
|
23
|
-
const checkpoints = listCheckpoints(sid, ctx.stateDir);
|
|
24
|
-
if (checkpoints.length <= 1)
|
|
25
|
-
return [];
|
|
26
|
-
// Find the most recent checkpoint (by checkpointId, which is sequential)
|
|
27
|
-
const ordered = [...checkpoints].sort((a, b) => a.checkpointId.localeCompare(b.checkpointId));
|
|
28
|
-
const current = ordered[ordered.length - 1];
|
|
29
|
-
// Score all other checkpoints by similarity to current
|
|
30
|
-
const scored = ordered
|
|
31
|
-
.filter((cp) => cp.checkpointId !== current.checkpointId)
|
|
32
|
-
.map((cp) => ({
|
|
33
|
-
checkpoint: cp,
|
|
34
|
-
score: cosineSimilarity(current.embedding, cp.embedding),
|
|
35
|
-
}))
|
|
36
|
-
.sort((a, b) => b.score - a.score);
|
|
37
|
-
return scored.slice(0, n);
|
|
38
|
-
}
|
|
39
|
-
/**
|
|
40
|
-
* Store statistics for status reporting / logging. Returns counts + the last
|
|
41
|
-
* (highest-numbered) checkpoint, or nulls when the session is empty.
|
|
42
|
-
*/
|
|
43
|
-
export function statsSession(ctx, sessionId) {
|
|
44
|
-
const sid = normalizeSessionId(sessionId);
|
|
45
|
-
const cps = listCheckpoints(sid, ctx.stateDir);
|
|
46
|
-
const state = loadSessionState(sid, ctx.stateDir);
|
|
47
|
-
const ordered = [...cps].sort((a, b) => a.checkpointId.localeCompare(b.checkpointId));
|
|
48
|
-
const last = ordered[ordered.length - 1];
|
|
49
|
-
const injected = state.injectedCheckpointIds.length;
|
|
50
|
-
const ds = getDedupStats(ctx.stateDir);
|
|
51
|
-
const sessionTok = cps.reduce((s, c) => s + (c.tokenEstimate ?? 0), 0);
|
|
52
|
-
const sessionOrig = cps.reduce((s, c) => s + (c.originalTokenEstimate ?? 0), 0);
|
|
53
|
-
// Per-session "tokens saved" = Σ(original − stored) over this session's
|
|
54
|
-
// stored checkpoints. Deduped adds (whole region discarded, nothing stored)
|
|
55
|
-
// are counted in the repo-wide meta counter via repoStats(); the per-session
|
|
56
|
-
// DB sum here covers the rows that exist.
|
|
57
|
-
const sessionSaved = cps.reduce((s, c) => s + Math.max(0, (c.originalTokenEstimate ?? 0) - (c.tokenEstimate ?? 0)), 0);
|
|
58
|
-
return {
|
|
59
|
-
checkpointCount: cps.length,
|
|
60
|
-
totalTokenEstimate: sessionTok,
|
|
61
|
-
lastCheckpointId: last?.checkpointId,
|
|
62
|
-
lastSummary: last?.summary,
|
|
63
|
-
injectedCount: injected,
|
|
64
|
-
dedupHitRate: cps.length === 0 ? 0 : injected / cps.length,
|
|
65
|
-
storageDedupRate: ds.attempts === 0 ? 0 : ds.deduped / ds.attempts,
|
|
66
|
-
tokensSaved: sessionSaved,
|
|
67
|
-
originalTokens: sessionOrig,
|
|
68
|
-
dedupAttempts: ds.attempts,
|
|
69
|
-
dedupCollapsed: ds.deduped,
|
|
70
|
-
};
|
|
71
|
-
}
|
|
72
|
-
/**
|
|
73
|
-
* Repo-wide stats — aggregates every session in this store (one per repo).
|
|
74
|
-
* Cumulative, resumable, cross-device. Surfaces the dashboard's "Repo …"
|
|
75
|
-
* figures; distinct from {@link statsSession} (per-session).
|
|
76
|
-
*/
|
|
77
|
-
export function repoStatsStore(ctx) {
|
|
78
|
-
return repoStatsFromStore(ctx.stateDir);
|
|
79
|
-
}
|
|
80
|
-
/** Data-safety invariant (Phase 0): regions retained vs bytes permanently deleted. */
|
|
81
|
-
export function dataInvariantStore(ctx) {
|
|
82
|
-
return dataInvariantStats(ctx.stateDir);
|
|
83
|
-
}
|
|
@@ -1,95 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* vectorStore/search.ts — Semantic search and RAPTOR integration.
|
|
3
|
-
*/
|
|
4
|
-
import { cosineSimilarity } from "../embedder.js";
|
|
5
|
-
import { normalizeSessionId } from "../store.js";
|
|
6
|
-
import { mmrRerank } from "../dedup/mmr.js";
|
|
7
|
-
import { topK } from "../dedup/topk.js";
|
|
8
|
-
import { listCheckpoints } from "../store/sqlite.js";
|
|
9
|
-
import { rehydrateRaptorTree } from "../dedup/raptor/index.js";
|
|
10
|
-
import { stagedExpansion } from "../dedup/raptor/retrieval.js";
|
|
11
|
-
/**
|
|
12
|
-
* Serve the RAPTOR tree for a query (Fix D): rehydrate the persisted tree and
|
|
13
|
-
* return its staged-expansion leaf hits as SearchHits. Returns [] when no tree
|
|
14
|
-
* exists (small sessions — flat search remains the path). Best-effort/non-fatal.
|
|
15
|
-
*/
|
|
16
|
-
export function raptorSearchHits(ctx, sid, query, k) {
|
|
17
|
-
try {
|
|
18
|
-
const tree = rehydrateRaptorTree(sid, ctx.stateDir);
|
|
19
|
-
if (!tree || !tree.rootId)
|
|
20
|
-
return [];
|
|
21
|
-
const leafIds = stagedExpansion(query, tree, {
|
|
22
|
-
embedder: ctx.embedder,
|
|
23
|
-
k,
|
|
24
|
-
topM: ctx.cfg.RAPTOR_CLUSTERS_PER_LEVEL,
|
|
25
|
-
mmrLambda: ctx.cfg.MMR_LAMBDA,
|
|
26
|
-
});
|
|
27
|
-
if (leafIds.length === 0)
|
|
28
|
-
return [];
|
|
29
|
-
const all = listCheckpoints(sid, ctx.stateDir).filter((cp) => cp.dedupStatus !== "removed");
|
|
30
|
-
const qv = ctx.embedder.embed(query);
|
|
31
|
-
const hits = [];
|
|
32
|
-
for (const id of leafIds) {
|
|
33
|
-
const cp = all.find((c) => c.checkpointId === id);
|
|
34
|
-
if (cp)
|
|
35
|
-
hits.push({ checkpoint: cp, score: cosineSimilarity(qv, cp.embedding) });
|
|
36
|
-
}
|
|
37
|
-
return hits;
|
|
38
|
-
}
|
|
39
|
-
catch {
|
|
40
|
-
return [];
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
/**
|
|
44
|
-
* Semantic search within a session's checkpoints. Returns top-K by cosine
|
|
45
|
-
* similarity, diversified via MMR (QA #10) so a cluster of near-identical
|
|
46
|
-
* hits yields at most a few distinct-relevance results.
|
|
47
|
-
*
|
|
48
|
-
* Heap-based top-K (QA #4, O(N log k)) replaces the old full sort; MMR then
|
|
49
|
-
* reranks the candidate window for diversity.
|
|
50
|
-
*/
|
|
51
|
-
export function searchStore(ctx, sessionId, query, k = 3) {
|
|
52
|
-
const sid = normalizeSessionId(sessionId);
|
|
53
|
-
const checkpoints = listCheckpoints(sid, ctx.stateDir).filter((cp) => cp.dedupStatus !== "removed");
|
|
54
|
-
if (checkpoints.length === 0)
|
|
55
|
-
return [];
|
|
56
|
-
const qv = ctx.embedder.embed(query);
|
|
57
|
-
const scored = checkpoints.map((cp) => ({
|
|
58
|
-
checkpoint: cp,
|
|
59
|
-
score: cosineSimilarity(qv, cp.embedding),
|
|
60
|
-
}));
|
|
61
|
-
// Heap top-K over a widened window (2k) so MMR has diverse candidates.
|
|
62
|
-
const window = topK(scored.map((h) => ({ item: h, score: h.score })), Math.max(k * 2, k)).map((s) => s.item);
|
|
63
|
-
// MMR (QA #10) is part of the L2 semantic tier: skip it when L2 is disabled
|
|
64
|
-
// (Sprint 14 flag), returning the plain relevance-ranked window instead.
|
|
65
|
-
if (!ctx.cfg.L2_ENABLED)
|
|
66
|
-
return window.slice(0, k);
|
|
67
|
-
// Fix D: when RAPTOR is promoted, ALSO recall high-level tree summaries and
|
|
68
|
-
// merge them with the flat hits via MMR so RAPTOR + flat don't double-cover.
|
|
69
|
-
// RAPTOR returns fewer, broader hits (O(log n) high-level nodes) than the
|
|
70
|
-
// O(n) flat leaves, tightening the block at read time.
|
|
71
|
-
if (ctx.cfg.RAPTOR_ENABLED) {
|
|
72
|
-
const raptorHits = raptorSearchHits(ctx, sid, query, k);
|
|
73
|
-
if (raptorHits.length > 0) {
|
|
74
|
-
const merged = [...window];
|
|
75
|
-
for (const rh of raptorHits) {
|
|
76
|
-
if (!merged.some((m) => m.checkpoint.checkpointId === rh.checkpoint.checkpointId)) {
|
|
77
|
-
merged.push(rh);
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
const mmrItems = merged.map((h) => ({
|
|
81
|
-
item: h,
|
|
82
|
-
vector: h.checkpoint.embedding,
|
|
83
|
-
relevance: h.score,
|
|
84
|
-
}));
|
|
85
|
-
return mmrRerank(mmrItems, k, ctx.cfg.MMR_LAMBDA);
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
const mmrItems = window.map((h) => ({
|
|
89
|
-
item: h,
|
|
90
|
-
vector: h.checkpoint.embedding,
|
|
91
|
-
relevance: h.score,
|
|
92
|
-
}));
|
|
93
|
-
const ranked = mmrRerank(mmrItems, k, ctx.cfg.MMR_LAMBDA);
|
|
94
|
-
return ranked;
|
|
95
|
-
}
|