nox-mem 3.2.1 → 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/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
- export function search(query, limit = 5, trackAccess = true) {
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
- let rows;
316
- try {
317
- rows = db.prepare(`
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(sanitized);
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
- const rows = semanticSearch(db, queryEmbedding, limit * 2);
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,38 +528,44 @@ 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) ───────────
461
535
  function rrfScore(rank, k = 60) {
462
536
  return 1 / (k + rank + 1);
463
537
  }
464
- function logTelemetry(query, variantsCount, resultsCount, hasSemantic, latencyMs, skipReason) {
538
+ function logTelemetry(query, variantsCount, resultsCount, hasSemantic, latencyMs, skipReason, top) {
465
539
  try {
466
540
  const db = getDb();
467
541
  const hash = createHash("sha1").update(query).digest("hex").substring(0, 16);
468
542
  const words = query.trim().split(/\s+/).filter(Boolean).length;
469
- db.prepare(`INSERT INTO search_telemetry (query_hash, query_words, variants_count, results_count, has_semantic, latency_ms, expansion_skipped_reason)
470
- VALUES (?, ?, ?, ?, ?, ?, ?)`).run(hash, words, variantsCount, resultsCount, hasSemantic ? 1 : 0, latencyMs, skipReason || null);
543
+ // `id` é opcional em SearchResult: filtrar ANTES de serializar, senão as duas
544
+ // colunas ficam desalinhadas (um `undefined` vira `null` em `ids` mas o score
545
+ // correspondente permanece em `scores`, e o par deixa de ser um par).
546
+ const comId = (top ?? []).filter((r) => typeof r.id === "number");
547
+ const ids = comId.length ? JSON.stringify(comId.map((r) => r.id)) : null;
548
+ const scores = comId.length ? JSON.stringify(comId.map((r) => r.score)) : null;
549
+ db.prepare(`INSERT INTO search_telemetry (query_hash, query_words, variants_count, results_count, has_semantic, latency_ms, expansion_skipped_reason, top_chunk_ids, top_scores)
550
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(hash, words, variantsCount, resultsCount, hasSemantic ? 1 : 0, latencyMs, skipReason || null, ids, scores);
471
551
  }
472
552
  catch {
473
553
  // telemetria nunca derruba a search
474
554
  }
475
555
  }
476
- export async function searchHybrid(query, limit = 5, trackAccess = true) {
556
+ export async function searchHybrid(query, limit = 5, trackAccess = true, filter) {
477
557
  const t0 = Date.now();
478
558
  const perVariantLimit = limit * 2;
479
559
  // Kick off original-query searches IMMEDIATELY and expansion in parallel.
480
560
  // Total time = max(expansion + variantFTS, originalFTS+semantic) — does not block
481
561
  // the original search behind a 500-1500ms Gemini call.
482
- const originalFtsPromise = Promise.resolve(search(query.trim(), perVariantLimit, trackAccess));
483
- 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);
484
564
  const expansionPromise = expandQuery(query);
485
565
  const expansion = await expansionPromise;
486
566
  const variants = expansion.variants;
487
567
  // Variants (excluding the original, which is already running) → FTS only.
488
- 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)));
489
569
  const allBatches = await Promise.all([
490
570
  originalFtsPromise,
491
571
  ...extraVariantFtsPromises,
@@ -528,7 +608,7 @@ export async function searchHybrid(query, limit = 5, trackAccess = true) {
528
608
  .map(({ rrfScore: s, saw_semantic: _, ...r }) => ({ ...r, score: Math.round(s * 1000 * 100) / 100 }));
529
609
  const final = dedupe(preDedup, limit);
530
610
  const hasSemantic = final.some((r) => r.match_type === "semantic" || r.match_type === "hybrid");
531
- logTelemetry(query, variants.length, final.length, hasSemantic, Date.now() - t0, expansion.reason);
611
+ logTelemetry(query, variants.length, final.length, hasSemantic, Date.now() - t0, expansion.reason, final);
532
612
  // D49 Phase 1 — temporal proximity rerank, shadow-mode opt-in.
533
613
  // Only activates if NOX_TEMPORAL_PATH=shadow|active. In shadow mode the
534
614
  // module computes the would-be rerank report but does NOT mutate `final`;
@@ -12,6 +12,7 @@
12
12
  */
13
13
  import { readdirSync, readFileSync, existsSync, statSync } from "fs";
14
14
  import { resolve } from "path";
15
+ import { homedir } from "os";
15
16
  import { getDb } from "./db.js";
16
17
  import { isNoise } from "./noise-filter.js";
17
18
  import { isDuplicate } from "./dedup.js";
@@ -27,7 +28,46 @@ const AGENTS_DIR = process.env.NOX_AGENTS_DIR ?? resolve(WORKSPACE, "agents");
27
28
  // Standalone operators: set to "" or omit (no agent sessions to distill).
28
29
  const DEFAULT_AGENTS = process.env.NOX_AGENTS
29
30
  ? process.env.NOX_AGENTS.split(",").map(s => s.trim()).filter(Boolean)
30
- : ["nox", "forge", "atlas", "cipher", "boris", "lex"];
31
+ : ["main", "nox", "forge", "atlas", "cipher", "boris", "lex"];
32
+ // NOX_CLAUDE_PROJECTS_DIR: where the Claude CLI keeps session transcripts.
33
+ // Agents that run under the Claude CLI no longer write to <agents>/<id>/sessions/;
34
+ // the CLI stores each session under <projectsDir>/<slug>, where <slug> is the
35
+ // session cwd with "/" and "." replaced by "-" (/root/.openclaw/workspace ->
36
+ // -root--openclaw-workspace). Both locations are read: the legacy dir still
37
+ // holds sessions predating the switch.
38
+ //
39
+ // When unset, the CLI home is DISCOVERED rather than assumed: ~/.claude is the
40
+ // default, but a team account uses ~/.claude-<team>, and a host can have several
41
+ // at once (one deployment had three, and reading only one silently skipped the
42
+ // busiest). Discovery also avoids requiring an env var that a long-lived daemon
43
+ // would only pick up after a restart.
44
+ export function claudeProjectSlug(cwd) {
45
+ return cwd.replace(/[/.]/g, "-");
46
+ }
47
+ export function claudeProjectsDirs() {
48
+ const explicit = process.env.NOX_CLAUDE_PROJECTS_DIR;
49
+ if (explicit)
50
+ return [explicit];
51
+ const home = homedir();
52
+ try {
53
+ return readdirSync(home)
54
+ .filter((d) => d === ".claude" || d.startsWith(".claude-"))
55
+ .map((d) => resolve(home, d, "projects"))
56
+ .filter((d) => existsSync(d));
57
+ }
58
+ catch {
59
+ return [];
60
+ }
61
+ }
62
+ export function sessionDirsFor(agentId) {
63
+ // "main" runs in the workspace root; every other agent in agents/<id>.
64
+ const cwd = agentId === "main" ? WORKSPACE : resolve(AGENTS_DIR, agentId);
65
+ const slug = claudeProjectSlug(cwd);
66
+ return [
67
+ resolve(AGENTS_DIR, agentId, "sessions"),
68
+ ...claudeProjectsDirs().map((d) => resolve(d, slug)),
69
+ ];
70
+ }
31
71
  // ─── Schema ──────────────────────────────────────────────────────────────────
32
72
  export function ensureDistillTable(db) {
33
73
  db.exec(`
@@ -46,39 +86,40 @@ function listUnprocessedSessions(db, agentIds, lookbackDays) {
46
86
  const cutoff = new Date(Date.now() - lookbackDays * 24 * 60 * 60 * 1000).toISOString();
47
87
  const sessions = [];
48
88
  for (const agentId of agentIds) {
49
- const sessionsDir = resolve(AGENTS_DIR, agentId, "sessions");
50
- if (!existsSync(sessionsDir))
51
- continue;
52
- let files;
53
- try {
54
- files = readdirSync(sessionsDir).filter((f) => f.endsWith(".jsonl"));
55
- }
56
- catch {
57
- continue;
58
- }
59
- for (const file of files) {
60
- const sessionKey = `${agentId}:${file.replace(".jsonl", "")}`;
61
- // Skip already processed
62
- const already = db.prepare("SELECT id FROM session_distill_log WHERE session_key = ?").get(sessionKey);
63
- if (already)
89
+ for (const sessionsDir of sessionDirsFor(agentId)) {
90
+ if (!existsSync(sessionsDir))
64
91
  continue;
65
- // Check file modification time against lookback
66
- const filePath = resolve(sessionsDir, file);
92
+ let files;
67
93
  try {
68
- const { mtimeMs } = statSync(filePath);
69
- if (new Date(mtimeMs).toISOString() < cutoff)
70
- continue;
94
+ files = readdirSync(sessionsDir).filter((f) => f.endsWith(".jsonl"));
71
95
  }
72
96
  catch {
73
97
  continue;
74
98
  }
75
- sessions.push({ agentId, sessionFile: filePath, sessionKey });
99
+ for (const file of files) {
100
+ const sessionKey = `${agentId}:${file.replace(".jsonl", "")}`;
101
+ // Skip already processed
102
+ const already = db.prepare("SELECT id FROM session_distill_log WHERE session_key = ?").get(sessionKey);
103
+ if (already)
104
+ continue;
105
+ // Check file modification time against lookback
106
+ const filePath = resolve(sessionsDir, file);
107
+ try {
108
+ const { mtimeMs } = statSync(filePath);
109
+ if (new Date(mtimeMs).toISOString() < cutoff)
110
+ continue;
111
+ }
112
+ catch {
113
+ continue;
114
+ }
115
+ sessions.push({ agentId, sessionFile: filePath, sessionKey });
116
+ }
76
117
  }
77
118
  }
78
119
  return sessions;
79
120
  }
80
121
  // ─── Message extraction ───────────────────────────────────────────────────────
81
- function extractMessages(sessionFile) {
122
+ export function extractMessages(sessionFile) {
82
123
  const messages = [];
83
124
  let content;
84
125
  try {
@@ -97,7 +138,15 @@ function extractMessages(sessionFile) {
97
138
  catch {
98
139
  continue;
99
140
  }
100
- if (event.type !== "message" || !event.message)
141
+ // Two transcript schemas in the wild: the OpenClaw one tags events as
142
+ // type "message", while Claude CLI transcripts tag them "user"/"assistant".
143
+ // Accepting only the former dropped every line of the latter with no error
144
+ // and no log — measured 0 lines of type "message" in a current transcript.
145
+ if (!event.message)
146
+ continue;
147
+ if (event.type !== "message" &&
148
+ event.type !== "user" &&
149
+ event.type !== "assistant")
101
150
  continue;
102
151
  const { role, content: contentParts } = event.message;
103
152
  if (role !== "user" && role !== "assistant")
package/package.json CHANGED
@@ -1,18 +1,18 @@
1
1
  {
2
2
  "name": "nox-mem",
3
- "version": "3.2.1",
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",
7
7
  "author": "Luiz Antonio Busnello (Toto)",
8
- "homepage": "https://github.com/totobusnello/nox-supermem#readme",
8
+ "homepage": "https://github.com/totobusnello/nox-mem#readme",
9
9
  "repository": {
10
10
  "type": "git",
11
- "url": "git+https://github.com/totobusnello/nox-supermem.git",
11
+ "url": "git+https://github.com/totobusnello/nox-mem.git",
12
12
  "directory": "nox-mem"
13
13
  },
14
14
  "bugs": {
15
- "url": "https://github.com/totobusnello/nox-supermem/issues"
15
+ "url": "https://github.com/totobusnello/nox-mem/issues"
16
16
  },
17
17
  "keywords": [
18
18
  "agent-memory",
@@ -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",
@@ -53,7 +55,7 @@
53
55
  "test:op-audit": "node --test dist/__tests__/op-audit-e2e.test.js"
54
56
  },
55
57
  "dependencies": {
56
- "better-sqlite3": "^11.0.0",
58
+ "better-sqlite3": "^12.11.1",
57
59
  "commander": "^12.0.0",
58
60
  "sqlite-vec": "^0.1.10-alpha.1"
59
61
  },