nox-mem 3.3.0 → 3.4.0
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 +28 -6
- package/dist/__tests__/fts-or-fallback.test.js +115 -0
- package/dist/__tests__/reindex-dedup.test.js +80 -0
- package/dist/__tests__/reindex-safety.test.js +116 -0
- package/dist/__tests__/temporal-filter.test.js +117 -0
- package/dist/api-server.js +19 -1
- package/dist/db.js +20 -8
- package/dist/doctor.js +107 -29
- package/dist/index.js +59 -9
- package/dist/lib/dates.js +98 -0
- package/dist/lib/db-path.js +45 -0
- package/dist/lib/op-audit.js +19 -12
- package/dist/lib/reranker.js +4 -1
- package/dist/mcp-server.js +9 -1
- package/dist/reindex-errors.js +26 -0
- package/dist/reindex.js +106 -23
- package/dist/search.js +88 -14
- package/package.json +4 -2
package/dist/reindex.js
CHANGED
|
@@ -36,11 +36,11 @@
|
|
|
36
36
|
import { getDb } from "./db.js";
|
|
37
37
|
import { withOpAudit } from "./lib/op-audit.js";
|
|
38
38
|
import { routeIngest } from "./lib/ingest-router.js";
|
|
39
|
-
import { readdirSync } from "fs";
|
|
39
|
+
import { existsSync, readdirSync } from "fs";
|
|
40
40
|
import { createHash } from "crypto";
|
|
41
41
|
import { join, resolve } from "path";
|
|
42
|
-
import { ReindexWipeDetectedError, MIN_RETENTION_RATIO } from "./reindex-errors.js";
|
|
43
|
-
export { ReindexWipeDetectedError } from "./reindex-errors.js";
|
|
42
|
+
import { ReindexWipeDetectedError, ReindexSourceMissingError, MIN_RETENTION_RATIO } from "./reindex-errors.js";
|
|
43
|
+
export { ReindexWipeDetectedError, ReindexSourceMissingError } from "./reindex-errors.js";
|
|
44
44
|
const WORKSPACE = process.env.OPENCLAW_WORKSPACE || "/root/.openclaw/workspace";
|
|
45
45
|
// Layer 4: tunable safety thresholds (env-overridable for emergency operations).
|
|
46
46
|
// MIN_RETENTION_RATIO imported from reindex-errors.ts (single source of truth).
|
|
@@ -64,6 +64,37 @@ function findFiles(dir, extensions) {
|
|
|
64
64
|
}
|
|
65
65
|
return results;
|
|
66
66
|
}
|
|
67
|
+
/** The directories reindex rebuilds from, in scan order. */
|
|
68
|
+
export function reindexRoots() {
|
|
69
|
+
return [resolve(WORKSPACE, "memory"), resolve(WORKSPACE, "shared")];
|
|
70
|
+
}
|
|
71
|
+
function collectReindexFiles() {
|
|
72
|
+
const [memoryRoot, sharedRoot] = reindexRoots();
|
|
73
|
+
return {
|
|
74
|
+
memoryFiles: findFiles(memoryRoot, [".md", ".json"]),
|
|
75
|
+
sharedFiles: findFiles(sharedRoot, [".md"]),
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Refuses (throws) when reindex has nothing trustworthy to rebuild from.
|
|
80
|
+
* Only fires in wipe conditions — a deployment whose workspace holds files
|
|
81
|
+
* passes untouched. Overridable with NOX_REINDEX_ALLOW_WIPE=1.
|
|
82
|
+
*/
|
|
83
|
+
export function assertReindexSource(preCount) {
|
|
84
|
+
if (ALLOW_WIPE)
|
|
85
|
+
return;
|
|
86
|
+
const roots = reindexRoots();
|
|
87
|
+
const existing = roots.filter((r) => existsSync(r));
|
|
88
|
+
if (existing.length === 0) {
|
|
89
|
+
if (preCount > 0)
|
|
90
|
+
throw new ReindexSourceMissingError(roots, preCount, "no-source-dir");
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
const { memoryFiles, sharedFiles } = collectReindexFiles();
|
|
94
|
+
const found = memoryFiles.length + sharedFiles.length;
|
|
95
|
+
if (found === 0 && preCount > 0)
|
|
96
|
+
throw new ReindexSourceMissingError(existing, preCount, "no-files");
|
|
97
|
+
}
|
|
67
98
|
// Content-addressed fingerprint for UPSERT identity.
|
|
68
99
|
// (source_file, sha256(chunk_text)) is stable across reindex runs as long as the
|
|
69
100
|
// chunker output is deterministic for the same input file. The schema's autoincrement
|
|
@@ -103,6 +134,11 @@ async function _reindexImpl() {
|
|
|
103
134
|
}
|
|
104
135
|
// ── Phase 1: snapshot pre-state ────────────────────────────────────────────
|
|
105
136
|
const preCount = db.prepare("SELECT COUNT(*) AS c FROM chunks").get().c;
|
|
137
|
+
// ── Phase 0 guard (read-only so far): the rebuild source must exist ────────
|
|
138
|
+
// Measured 2026-09-28 on a clean npm install: no $OPENCLAW_WORKSPACE ⇒ the scan
|
|
139
|
+
// found 0 files ⇒ every chunk became an "orphan" and was deleted; the ratio
|
|
140
|
+
// guard below then threw — after the DELETE. Refuse here, before any write.
|
|
141
|
+
assertReindexSource(preCount);
|
|
106
142
|
// Tolerant select: schema may lack some columns on older DBs (pre-v10).
|
|
107
143
|
// `SELECT *` would force coupling; instead probe column existence.
|
|
108
144
|
const cols = new Set(db.prepare("PRAGMA table_info(chunks)").all().map((r) => r.name));
|
|
@@ -124,10 +160,35 @@ async function _reindexImpl() {
|
|
|
124
160
|
].join(", ");
|
|
125
161
|
const oldChunks = db.prepare(`SELECT ${selectCols} FROM chunks`).all();
|
|
126
162
|
// Build content fingerprint -> oldChunk index.
|
|
163
|
+
// One representative per content fingerprint. When the DB already holds
|
|
164
|
+
// duplicates (every reindex before 2026-09-28 doubled unchanged content), the
|
|
165
|
+
// kept representative is the one WITH an embedding, then the lowest id — the
|
|
166
|
+
// other copies become orphans and are removed, and dropping one without a
|
|
167
|
+
// vector must never cost the one that has it.
|
|
168
|
+
let embeddedIds = new Set();
|
|
169
|
+
try {
|
|
170
|
+
embeddedIds = new Set(db.prepare("SELECT chunk_id FROM vec_chunk_map").all().map((r) => r.chunk_id));
|
|
171
|
+
}
|
|
172
|
+
catch {
|
|
173
|
+
/* no vector map yet (fresh / keyless install) — every row is equal */
|
|
174
|
+
}
|
|
175
|
+
const better = (a, b) => {
|
|
176
|
+
const ae = embeddedIds.has(a.id), be = embeddedIds.has(b.id);
|
|
177
|
+
if (ae !== be)
|
|
178
|
+
return ae ? a : b;
|
|
179
|
+
return a.id <= b.id ? a : b;
|
|
180
|
+
};
|
|
127
181
|
const oldByFingerprint = new Map();
|
|
128
182
|
for (const row of oldChunks) {
|
|
129
|
-
|
|
183
|
+
const fp = chunkFingerprint(row.source_file, row.chunk_text);
|
|
184
|
+
const cur = oldByFingerprint.get(fp);
|
|
185
|
+
oldByFingerprint.set(fp, cur ? better(cur, row) : row);
|
|
130
186
|
}
|
|
187
|
+
// Retention is measured on DISTINCT content, not rows: removing a redundant
|
|
188
|
+
// copy of content that is still present is not a loss. Measured on rows, a DB
|
|
189
|
+
// doubled by the old bug (2N → N) read as a 50% wipe and the cleanup reindex
|
|
190
|
+
// was refused forever.
|
|
191
|
+
const preDistinct = oldByFingerprint.size;
|
|
131
192
|
console.log(`[reindex] Phase 1: snapshotted ${oldChunks.length} existing chunks`);
|
|
132
193
|
// ── Phase 2: ingest new chunks into a staging set ──────────────────────────
|
|
133
194
|
// Strategy: do NOT delete first. Let routeIngest INSERT new chunks alongside old ones.
|
|
@@ -136,8 +197,8 @@ async function _reindexImpl() {
|
|
|
136
197
|
//
|
|
137
198
|
// To distinguish "old" vs "new" rows we capture max(id) before any ingest.
|
|
138
199
|
const maxIdBefore = db.prepare("SELECT COALESCE(MAX(id), 0) AS m FROM chunks").get().m;
|
|
139
|
-
|
|
140
|
-
const sharedFiles =
|
|
200
|
+
// Same scan as assertReindexSource — one definition of "the source".
|
|
201
|
+
const { memoryFiles, sharedFiles } = collectReindexFiles();
|
|
141
202
|
const allFiles = [...memoryFiles, ...sharedFiles];
|
|
142
203
|
let totalChunksIngested = 0;
|
|
143
204
|
const fileErrors = [];
|
|
@@ -161,24 +222,28 @@ async function _reindexImpl() {
|
|
|
161
222
|
const newChunks = db
|
|
162
223
|
.prepare("SELECT id, source_file, chunk_text FROM chunks WHERE id > ?")
|
|
163
224
|
.all(maxIdBefore);
|
|
164
|
-
// For each new chunk, look up by fingerprint
|
|
165
|
-
const updateNewMetadata = db.prepare(`
|
|
166
|
-
UPDATE chunks
|
|
167
|
-
SET tier = COALESCE(?, tier),
|
|
168
|
-
access_count = COALESCE(?, access_count),
|
|
169
|
-
importance = COALESCE(?, importance),
|
|
170
|
-
last_accessed_at = COALESCE(?, last_accessed_at)
|
|
171
|
-
WHERE id = ?
|
|
172
|
-
`);
|
|
225
|
+
// For each new chunk, look up by fingerprint: unchanged content keeps the old row.
|
|
173
226
|
const seenOldIds = new Set();
|
|
174
227
|
let inheritedCount = 0;
|
|
228
|
+
// A new row whose fingerprint matches an old row is the SAME content: keep the
|
|
229
|
+
// old row (it already holds the embedding, a stable id and its metadata) and
|
|
230
|
+
// drop the fresh copy. Before 2026-09-28 both were kept, so every reindex left
|
|
231
|
+
// each unchanged chunk twice (measured: 10 chunks -> 20 after one reindex).
|
|
232
|
+
// Only the fresh copy (id > maxIdBefore) is ever deleted here — never old data.
|
|
233
|
+
const dropNewDuplicate = db.prepare("DELETE FROM chunks WHERE id = ? AND id > ?");
|
|
234
|
+
let newDuplicatesDropped = 0;
|
|
175
235
|
const mergeTxn = db.transaction(() => {
|
|
176
236
|
for (const nc of newChunks) {
|
|
177
237
|
const fp = chunkFingerprint(nc.source_file, nc.chunk_text);
|
|
178
238
|
const oldRow = oldByFingerprint.get(fp);
|
|
179
239
|
if (oldRow) {
|
|
240
|
+
if (seenOldIds.has(oldRow.id)) {
|
|
241
|
+
// Second new copy of the same content in this run: keep the first.
|
|
242
|
+
newDuplicatesDropped += dropNewDuplicate.run(nc.id, maxIdBefore).changes;
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
180
245
|
seenOldIds.add(oldRow.id);
|
|
181
|
-
|
|
246
|
+
newDuplicatesDropped += dropNewDuplicate.run(nc.id, maxIdBefore).changes;
|
|
182
247
|
inheritedCount++;
|
|
183
248
|
}
|
|
184
249
|
}
|
|
@@ -189,6 +254,22 @@ async function _reindexImpl() {
|
|
|
189
254
|
// If fileErrors is non-empty AND would cause a wipe, the Layer 4 invariant
|
|
190
255
|
// check below will throw and roll back.
|
|
191
256
|
const orphanIds = oldChunks.map((r) => r.id).filter((id) => !seenOldIds.has(id));
|
|
257
|
+
// Layer 4, moved IN FRONT of the delete: project the post-count and refuse if
|
|
258
|
+
// it would breach the retention ratio. The post-delete check below stays as a
|
|
259
|
+
// second leg, but by then the rows are already gone (no auto-restore).
|
|
260
|
+
// Distinct content that will remain after the delete (kept old rows + new
|
|
261
|
+
// rows). An edited file replaces content — it is not a loss — so this counts
|
|
262
|
+
// what will be present, not which old fingerprints survived.
|
|
263
|
+
const orphanSet = new Set(orphanIds);
|
|
264
|
+
const projectedFps = new Set();
|
|
265
|
+
for (const r of db.prepare("SELECT id, source_file, chunk_text FROM chunks").all()) {
|
|
266
|
+
if (!orphanSet.has(r.id))
|
|
267
|
+
projectedFps.add(chunkFingerprint(r.source_file, r.chunk_text));
|
|
268
|
+
}
|
|
269
|
+
const projectedDistinct = projectedFps.size;
|
|
270
|
+
if (preDistinct > 0 && projectedDistinct / preDistinct < MIN_RETENTION_RATIO && !ALLOW_WIPE) {
|
|
271
|
+
throw new ReindexWipeDetectedError(preDistinct, projectedDistinct, MIN_RETENTION_RATIO);
|
|
272
|
+
}
|
|
192
273
|
let orphanedDeleted = 0;
|
|
193
274
|
if (orphanIds.length > 0) {
|
|
194
275
|
const deleteOrphan = db.prepare("DELETE FROM chunks WHERE id = ?");
|
|
@@ -211,13 +292,16 @@ async function _reindexImpl() {
|
|
|
211
292
|
// ── Layer 4: invariant check ────────────────────────────────────────────────
|
|
212
293
|
// Compute retention ratio. If we lost more than (1 - MIN_RETENTION_RATIO) of chunks,
|
|
213
294
|
// assume wipe-class failure and throw — withOpAudit failure path will preserve snapshot.
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
295
|
+
// Second leg, measured on the DB itself after the delete: distinct content present.
|
|
296
|
+
const retainedDistinct = new Set(db.prepare("SELECT source_file, chunk_text FROM chunks").all()
|
|
297
|
+
.map((r) => chunkFingerprint(r.source_file, r.chunk_text))).size;
|
|
298
|
+
const ratio = preDistinct === 0 ? 1 : retainedDistinct / preDistinct;
|
|
299
|
+
if (preDistinct > 0 && ratio < MIN_RETENTION_RATIO && !ALLOW_WIPE) {
|
|
300
|
+
throw new ReindexWipeDetectedError(preDistinct, retainedDistinct, MIN_RETENTION_RATIO);
|
|
217
301
|
}
|
|
218
302
|
console.log(`[reindex] DONE files=${allFiles.length} pre=${preCount} post=${postCount} ` +
|
|
219
303
|
`ratio=${(ratio * 100).toFixed(1)}% inherited=${inheritedCount} ` +
|
|
220
|
-
`orphans-deleted=${orphanedDeleted} ingest-errors=${fileErrors.length}`);
|
|
304
|
+
`orphans-deleted=${orphanedDeleted} new-duplicates-dropped=${newDuplicatesDropped} ingest-errors=${fileErrors.length}`);
|
|
221
305
|
if (fileErrors.length > 0) {
|
|
222
306
|
console.error(`[reindex] ${fileErrors.length} files failed; first 5:`);
|
|
223
307
|
for (const fe of fileErrors.slice(0, 5))
|
|
@@ -229,7 +313,7 @@ async function _reindexImpl() {
|
|
|
229
313
|
preCount,
|
|
230
314
|
postCount,
|
|
231
315
|
upserted: inheritedCount,
|
|
232
|
-
inserted: newChunks.length -
|
|
316
|
+
inserted: newChunks.length - newDuplicatesDropped,
|
|
233
317
|
preserved: inheritedCount,
|
|
234
318
|
orphaned: orphanedDeleted,
|
|
235
319
|
};
|
|
@@ -237,8 +321,7 @@ async function _reindexImpl() {
|
|
|
237
321
|
export async function reindex(opts) {
|
|
238
322
|
if (opts?.dryRun) {
|
|
239
323
|
const db = getDb();
|
|
240
|
-
const memoryFiles =
|
|
241
|
-
const sharedFiles = findFiles(resolve(WORKSPACE, "shared"), [".md"]);
|
|
324
|
+
const { memoryFiles, sharedFiles } = collectReindexFiles();
|
|
242
325
|
const allFiles = [...memoryFiles, ...sharedFiles];
|
|
243
326
|
const currentChunks = db.prepare("SELECT COUNT(*) AS c FROM chunks").get().c;
|
|
244
327
|
const entityFiles = allFiles.filter((f) => f.includes("/memory/entities/")).length;
|
package/dist/search.js
CHANGED
|
@@ -6,6 +6,7 @@ import { dedupe } from "./search-dedup.js";
|
|
|
6
6
|
import { calculateSalience, calculateSalienceLegacy, getSalienceMode } from "./salience.js";
|
|
7
7
|
import { rerankByTemporalProximity, logTemporalProbe } from "./temporal-retrieval.js";
|
|
8
8
|
import { countQueryEntities } from "./query-entity-count.js";
|
|
9
|
+
import { buildTemporalClause } from "./lib/dates.js";
|
|
9
10
|
// ─── Boost configuration (Fase 1.7a + A-boost-stack-wiring 2026-05-19) ────────
|
|
10
11
|
//
|
|
11
12
|
// G3 ablation (PR #146, 2026-05-19) proved every boost below was INERT in the
|
|
@@ -305,16 +306,61 @@ function recordAccess(db, ids, enabled) {
|
|
|
305
306
|
const placeholders = valid.map(() => "?").join(",");
|
|
306
307
|
db.prepare(`UPDATE chunks SET access_count = access_count + 1, last_accessed_at = ? WHERE id IN (${placeholders})`).run(ts, ...valid);
|
|
307
308
|
}
|
|
308
|
-
|
|
309
|
+
// ─── FTS5 OR fallback (keyless installs) ─────────────────────────────────────
|
|
310
|
+
//
|
|
311
|
+
// FTS5 reads a space-separated query as an AND of every term, so a natural
|
|
312
|
+
// language question ("when was the zebra migration") matches nothing unless
|
|
313
|
+
// every filler word is in the chunk. With embeddings the semantic branch covers
|
|
314
|
+
// that; without a key it does not. When — and only when — the AND query returns
|
|
315
|
+
// zero rows, search() retries with an OR of the content terms.
|
|
316
|
+
//
|
|
317
|
+
// Gate NOX_FTS_OR_FALLBACK: "on" always, "off" never, unset/"auto" only when no
|
|
318
|
+
// embedding key is in the environment (production has one ⇒ unchanged there).
|
|
319
|
+
// Read at call time, never frozen at import, so it stays testable in-process.
|
|
320
|
+
const FTS_STOPWORDS = new Set([
|
|
321
|
+
// EN
|
|
322
|
+
"the", "a", "an", "of", "to", "in", "on", "at", "for", "is", "was", "are", "were",
|
|
323
|
+
"be", "been", "do", "does", "did", "what", "when", "where", "who", "why", "how",
|
|
324
|
+
"which", "that", "this", "with", "from", "and", "or", "not",
|
|
325
|
+
// PT
|
|
326
|
+
"o", "a", "os", "as", "um", "uma", "de", "do", "da", "dos", "das", "em", "no", "na",
|
|
327
|
+
"nos", "nas", "para", "por", "com", "que", "qual", "quando", "onde", "quem", "como",
|
|
328
|
+
"se", "é", "foi", "são", "era", "ser", "e", "ou", "não",
|
|
329
|
+
]);
|
|
330
|
+
export function ftsOrFallbackEnabled(env = process.env) {
|
|
331
|
+
const mode = (env.NOX_FTS_OR_FALLBACK ?? "auto").trim().toLowerCase();
|
|
332
|
+
if (mode === "on")
|
|
333
|
+
return true;
|
|
334
|
+
if (mode === "off")
|
|
335
|
+
return false;
|
|
336
|
+
// Same key names the embedding provider resolves (src/providers/index.ts).
|
|
337
|
+
return !env.NOX_EMBEDDING_API_KEY && !env.NOX_EMBED_API_KEY && !env.GEMINI_API_KEY && !env.OPENAI_API_KEY;
|
|
338
|
+
}
|
|
339
|
+
/** OR expression of the non-stopword terms, each double-quoted; null if none is left. */
|
|
340
|
+
export function buildFtsOrQuery(sanitized) {
|
|
341
|
+
const seen = new Set();
|
|
342
|
+
const terms = [];
|
|
343
|
+
for (const raw of sanitized.split(/\s+/)) {
|
|
344
|
+
const t = raw.toLowerCase();
|
|
345
|
+
if (!t || FTS_STOPWORDS.has(t) || seen.has(t))
|
|
346
|
+
continue;
|
|
347
|
+
seen.add(t);
|
|
348
|
+
terms.push(`"${raw.replace(/"/g, '""')}"`);
|
|
349
|
+
}
|
|
350
|
+
return terms.length > 0 ? terms.join(" OR ") : null;
|
|
351
|
+
}
|
|
352
|
+
export function search(query, limit = 5, trackAccess = true, filter) {
|
|
309
353
|
const db = getDb();
|
|
310
354
|
const sanitized = query.replace(/[^\p{L}\p{N}\s]/gu, " ").replace(/\s+/g, " ").trim();
|
|
311
355
|
if (!sanitized)
|
|
312
356
|
return [];
|
|
313
357
|
// G10d: compute entity count once per query (amortised via cache, <1ms hot path).
|
|
314
358
|
const { count: queryEntityCount } = countQueryEntities(query, db);
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
359
|
+
// P3 temporal filter: hard SQL pre-filter, applied before LIMIT so the 20
|
|
360
|
+
// candidates are drawn from the allowed window. Never a ranking term.
|
|
361
|
+
// Without a filter the statement is byte-identical to the unfiltered one.
|
|
362
|
+
const temporal = buildTemporalClause(filter);
|
|
363
|
+
const runFts = (match) => db.prepare(`
|
|
318
364
|
SELECT c.id, c.source_file, c.chunk_type, c.chunk_text, c.source_date,
|
|
319
365
|
c.tier, c.source_type, c.section, c.section_boost,
|
|
320
366
|
c.pain, c.importance, c.retention_days, c.created_at, c.last_accessed_at,
|
|
@@ -322,13 +368,29 @@ export function search(query, limit = 5, trackAccess = true) {
|
|
|
322
368
|
bm25(chunks_fts, 1.0, 0.5, 0.5) as rank
|
|
323
369
|
FROM chunks_fts
|
|
324
370
|
JOIN chunks c ON c.id = chunks_fts.rowid
|
|
325
|
-
WHERE chunks_fts MATCH ?
|
|
371
|
+
WHERE chunks_fts MATCH ?${temporal ? ` AND ${temporal.sql}` : ""}
|
|
326
372
|
ORDER BY rank LIMIT 20
|
|
327
|
-
`).all(
|
|
373
|
+
`).all(match, ...(temporal?.params ?? []));
|
|
374
|
+
let rows;
|
|
375
|
+
try {
|
|
376
|
+
rows = runFts(sanitized);
|
|
328
377
|
}
|
|
329
378
|
catch {
|
|
330
379
|
return [];
|
|
331
380
|
}
|
|
381
|
+
// OR fallback: only when the AND query found nothing, so an existing result
|
|
382
|
+
// set is never reordered or extended. Same temporal fragment and params.
|
|
383
|
+
if (rows.length === 0 && ftsOrFallbackEnabled()) {
|
|
384
|
+
const orQuery = buildFtsOrQuery(sanitized);
|
|
385
|
+
if (orQuery) {
|
|
386
|
+
try {
|
|
387
|
+
rows = runFts(orQuery);
|
|
388
|
+
}
|
|
389
|
+
catch {
|
|
390
|
+
return [];
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
}
|
|
332
394
|
const now = new Date();
|
|
333
395
|
const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
|
|
334
396
|
.toISOString().split("T")[0];
|
|
@@ -367,7 +429,8 @@ export function search(query, limit = 5, trackAccess = true) {
|
|
|
367
429
|
recordAccess(db, results.map((r) => r.id), trackAccess);
|
|
368
430
|
return results;
|
|
369
431
|
}
|
|
370
|
-
export async function searchSemantic(query, limit = 5, trackAccess = true) {
|
|
432
|
+
export async function searchSemantic(query, limit = 5, trackAccess = true, filter) {
|
|
433
|
+
const temporal = buildTemporalClause(filter);
|
|
371
434
|
try {
|
|
372
435
|
const { embedText, semanticSearch, ensureVecTable, countEmbedded } = await import("./embed.js");
|
|
373
436
|
const db = getDb();
|
|
@@ -376,12 +439,23 @@ export async function searchSemantic(query, limit = 5, trackAccess = true) {
|
|
|
376
439
|
const vecCount = countEmbedded(db);
|
|
377
440
|
if (vecCount === 0) {
|
|
378
441
|
console.error("[WARN] Vector index empty — run 'nox-mem vectorize' first. Falling back to FTS5.");
|
|
379
|
-
return search(query, limit, trackAccess);
|
|
442
|
+
return search(query, limit, trackAccess, filter);
|
|
380
443
|
}
|
|
381
444
|
// G10d: compute entity count once per query (shared cache with FTS path).
|
|
382
445
|
const { count: queryEntityCount } = countQueryEntities(query, db);
|
|
383
446
|
const queryEmbedding = await embedText(query);
|
|
384
|
-
|
|
447
|
+
// vec0 KNN cannot take a WHERE on chunk columns, so the temporal filter is
|
|
448
|
+
// applied to the KNN candidates. Over-fetch when filtering, otherwise a
|
|
449
|
+
// narrow window would leave the top-k almost empty.
|
|
450
|
+
// Capped: the candidate ids go into an IN (...) list, and an uncapped
|
|
451
|
+
// `?limit=5000` would ask for 100k bound variables (SQLite max 32766).
|
|
452
|
+
const knnK = temporal ? Math.max(limit * 2, Math.min(Math.max(limit * 20, 200), 2000)) : limit * 2;
|
|
453
|
+
let rows = semanticSearch(db, queryEmbedding, knnK);
|
|
454
|
+
if (temporal && rows.length > 0) {
|
|
455
|
+
const ids = rows.map((r) => r.chunk_id).filter(Boolean);
|
|
456
|
+
const allowed = new Set(db.prepare(`SELECT c.id FROM chunks c WHERE c.id IN (${ids.map(() => "?").join(",")}) AND ${temporal.sql}`).all(...ids, ...temporal.params).map((r) => r.id));
|
|
457
|
+
rows = rows.filter((r) => allowed.has(r.chunk_id)).slice(0, limit * 2);
|
|
458
|
+
}
|
|
385
459
|
if (rows.length === 0)
|
|
386
460
|
return [];
|
|
387
461
|
// Fetch boost-stack columns in one shot.
|
|
@@ -454,7 +528,7 @@ export async function searchSemantic(query, limit = 5, trackAccess = true) {
|
|
|
454
528
|
catch (err) {
|
|
455
529
|
// Fallback to FTS if vector index not ready
|
|
456
530
|
console.error("[WARN] Semantic search failed, falling back to FTS:", err.message);
|
|
457
|
-
return search(query, limit, trackAccess);
|
|
531
|
+
return search(query, limit, trackAccess, filter);
|
|
458
532
|
}
|
|
459
533
|
}
|
|
460
534
|
// ─── Hybrid search (FTS5 + semantic, expanded, RRF-fused, deduped) ───────────
|
|
@@ -479,19 +553,19 @@ function logTelemetry(query, variantsCount, resultsCount, hasSemantic, latencyMs
|
|
|
479
553
|
// telemetria nunca derruba a search
|
|
480
554
|
}
|
|
481
555
|
}
|
|
482
|
-
export async function searchHybrid(query, limit = 5, trackAccess = true) {
|
|
556
|
+
export async function searchHybrid(query, limit = 5, trackAccess = true, filter) {
|
|
483
557
|
const t0 = Date.now();
|
|
484
558
|
const perVariantLimit = limit * 2;
|
|
485
559
|
// Kick off original-query searches IMMEDIATELY and expansion in parallel.
|
|
486
560
|
// Total time = max(expansion + variantFTS, originalFTS+semantic) — does not block
|
|
487
561
|
// the original search behind a 500-1500ms Gemini call.
|
|
488
|
-
const originalFtsPromise = Promise.resolve(search(query.trim(), perVariantLimit, trackAccess));
|
|
489
|
-
const semPromise = searchSemantic(query.trim(), perVariantLimit * 2, trackAccess);
|
|
562
|
+
const originalFtsPromise = Promise.resolve(search(query.trim(), perVariantLimit, trackAccess, filter));
|
|
563
|
+
const semPromise = searchSemantic(query.trim(), perVariantLimit * 2, trackAccess, filter);
|
|
490
564
|
const expansionPromise = expandQuery(query);
|
|
491
565
|
const expansion = await expansionPromise;
|
|
492
566
|
const variants = expansion.variants;
|
|
493
567
|
// Variants (excluding the original, which is already running) → FTS only.
|
|
494
|
-
const extraVariantFtsPromises = variants.slice(1).map((v) => Promise.resolve(search(v, perVariantLimit, trackAccess)));
|
|
568
|
+
const extraVariantFtsPromises = variants.slice(1).map((v) => Promise.resolve(search(v, perVariantLimit, trackAccess, filter)));
|
|
495
569
|
const allBatches = await Promise.all([
|
|
496
570
|
originalFtsPromise,
|
|
497
571
|
...extraVariantFtsPromises,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nox-mem",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.4.0",
|
|
4
4
|
"description": "Pain-weighted hybrid memory engine: FTS5 + semantic search + knowledge graph, self-hosted on any Linux VPS.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -38,7 +38,9 @@
|
|
|
38
38
|
"node": ">=20"
|
|
39
39
|
},
|
|
40
40
|
"bin": {
|
|
41
|
-
"nox-mem": "dist/index.js"
|
|
41
|
+
"nox-mem": "dist/index.js",
|
|
42
|
+
"nox-mem-mcp": "dist/mcp-server.js",
|
|
43
|
+
"nox-mem-api": "dist/api-server.js"
|
|
42
44
|
},
|
|
43
45
|
"files": [
|
|
44
46
|
"dist",
|