nox-mem 3.5.2 → 3.7.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
@@ -4,7 +4,7 @@ import { TIER_BOOST } from "./tier-manager.js";
4
4
  import { expandQuery } from "./search-expansion.js";
5
5
  import { dedupe } from "./search-dedup.js";
6
6
  import { calculateSalience, calculateSalienceLegacy, getSalienceMode } from "./salience.js";
7
- import { rerankByTemporalProximity, logTemporalProbe } from "./temporal-retrieval.js";
7
+ import { rerankByTemporalProximity, logTemporalProbe, temporalQueryKind } from "./temporal-retrieval.js";
8
8
  import { countQueryEntities } from "./query-entity-count.js";
9
9
  import { buildTemporalClause } from "./lib/dates.js";
10
10
  // ─── Boost configuration (Fase 1.7a + A-boost-stack-wiring 2026-05-19) ────────
@@ -556,7 +556,19 @@ export async function searchSemantic(query, limit = 5, trackAccess = true, filte
556
556
  function rrfScore(rank, k = 60) {
557
557
  return 1 / (k + rank + 1);
558
558
  }
559
- function logTelemetry(query, variantsCount, resultsCount, hasSemantic, latencyMs, skipReason, top) {
559
+ export function telemetryCaller(caller, trackAccess) {
560
+ const clean = (v, fallback) => {
561
+ const t = (v ?? "").trim().toLowerCase();
562
+ if (!t)
563
+ return fallback;
564
+ return /^[a-z0-9_.-]{1,40}$/.test(t) ? t : "invalid";
565
+ };
566
+ const agent = clean(caller.agent, "unknown");
567
+ return `${trackAccess ? clean(caller.surface, "unknown") : "probe"}:${agent}`;
568
+ }
569
+ function logTelemetry(query, variantsCount, resultsCount, hasSemantic, latencyMs, skipReason, top,
570
+ /** Already normalised by `telemetryCaller`. */
571
+ requestingAgent) {
560
572
  try {
561
573
  const db = getDb();
562
574
  const hash = createHash("sha1").update(query).digest("hex").substring(0, 16);
@@ -567,14 +579,16 @@ function logTelemetry(query, variantsCount, resultsCount, hasSemantic, latencyMs
567
579
  const comId = (top ?? []).filter((r) => typeof r.id === "number");
568
580
  const ids = comId.length ? JSON.stringify(comId.map((r) => r.id)) : null;
569
581
  const scores = comId.length ? JSON.stringify(comId.map((r) => r.score)) : null;
570
- 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)
571
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(hash, words, variantsCount, resultsCount, hasSemantic ? 1 : 0, latencyMs, skipReason || null, ids, scores);
582
+ const agent = requestingAgent ?? telemetryCaller({}, true);
583
+ const temporal = temporalQueryKind(query);
584
+ 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, requesting_agent, was_temporal_query)
585
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(hash, words, variantsCount, resultsCount, hasSemantic ? 1 : 0, latencyMs, skipReason || null, ids, scores, agent, temporal);
572
586
  }
573
587
  catch {
574
588
  // telemetria nunca derruba a search
575
589
  }
576
590
  }
577
- export async function searchHybrid(query, limit = 5, trackAccess = true, filter) {
591
+ export async function searchHybrid(query, limit = 5, trackAccess = true, filter, caller = {}) {
578
592
  const t0 = Date.now();
579
593
  const perVariantLimit = limit * 2;
580
594
  // Kick off original-query searches IMMEDIATELY and expansion in parallel.
@@ -629,7 +643,7 @@ export async function searchHybrid(query, limit = 5, trackAccess = true, filter)
629
643
  .map(({ rrfScore: s, saw_semantic: _, ...r }) => ({ ...r, score: Math.round(s * 1000 * 100) / 100 }));
630
644
  const final = dedupe(preDedup, limit);
631
645
  const hasSemantic = final.some((r) => r.match_type === "semantic" || r.match_type === "hybrid");
632
- logTelemetry(query, variants.length, final.length, hasSemantic, Date.now() - t0, expansion.reason, final);
646
+ logTelemetry(query, variants.length, final.length, hasSemantic, Date.now() - t0, expansion.reason, final, telemetryCaller(caller, trackAccess));
633
647
  // D49 Phase 1 — temporal proximity rerank, shadow-mode opt-in.
634
648
  // Only activates if NOX_TEMPORAL_PATH=shadow|active. In shadow mode the
635
649
  // module computes the would-be rerank report but does NOT mutate `final`;
@@ -5,7 +5,8 @@
5
5
  import { readFileSync, writeFileSync, existsSync } from "fs";
6
6
  import { resolve } from "path";
7
7
  import { getDb } from "./db.js";
8
- const WORKSPACE = process.env.OPENCLAW_WORKSPACE || "/root/.openclaw/workspace";
8
+ import { workspaceRoot } from "./lib/workspace.js";
9
+ const WORKSPACE = workspaceRoot();
9
10
  export function updateSessionState() {
10
11
  const sessionPath = resolve(WORKSPACE, "memory", "SESSION-STATE.md");
11
12
  const db = getDb();
@@ -7,7 +7,8 @@
7
7
  import { getDb } from "./db.js";
8
8
  import Database from "better-sqlite3";
9
9
  import { resolve } from "path";
10
- const WORKSPACE = process.env.OPENCLAW_WORKSPACE ?? "/root/.openclaw/workspace";
10
+ import { workspaceRoot } from "./lib/workspace.js";
11
+ const WORKSPACE = workspaceRoot();
11
12
  const SHARED_DB = resolve(WORKSPACE, "tools/nox-mem/shared-memory.db");
12
13
  // NOX_AGENTS_DIR: base directory where agent sub-dirs live.
13
14
  // NOX_AGENTS: comma-separated list of agent names to include (no spaces).
@@ -168,6 +168,24 @@ export function detectTemporal(query, nowMs = Date.now()) {
168
168
  }
169
169
  return { isTemporal: false, anchor: null, anchorRange: null, signalSource: null };
170
170
  }
171
+ /**
172
+ * Value of `search_telemetry.was_temporal_query` (schema v20).
173
+ *
174
+ * 0 — no temporal expression
175
+ * 1 — temporal word only, no date ("when", "last", "deploy") → no anchor
176
+ * 2 — a date in the query (ISO, month, year) → the only class a proximity
177
+ * rerank could use
178
+ *
179
+ * Measures how often real searches carry a temporal expression, which is what
180
+ * would justify reopening the implicit temporal rerank. Runs on every search
181
+ * regardless of NOX_TEMPORAL_PATH: regex over the query, results untouched.
182
+ */
183
+ export function temporalQueryKind(query) {
184
+ const { isTemporal, signalSource } = detectTemporal(query);
185
+ if (!isTemporal)
186
+ return 0;
187
+ return signalSource === "adverbial" ? 1 : 2;
188
+ }
171
189
  // ─── Proximity delta ──────────────────────────────────────────────────────────
172
190
  //
173
191
  // Gaussiana truncada: bump máximo de +0.5 em Δdays=0, decai exponencialmente.
package/dist/watch.js CHANGED
@@ -3,12 +3,17 @@
3
3
  *
4
4
  * Monitors memory files across all 6 agent workspaces.
5
5
  * On change: debounce 2s → ingest file → log.
6
+ * On a path that no longer exists (delete, or the old side of a rename):
7
+ * tombstone its chunks — they stay, marked for review (lib/tombstone.ts).
6
8
  * Skips: binary files, .db, .json session files, tmp files.
7
9
  */
8
- import { watch, statSync, existsSync } from "fs";
9
- import { resolve, extname } from "path";
10
+ import { watch, statSync, existsSync, readdirSync } from "fs";
11
+ import { resolve, extname, relative } from "path";
10
12
  import { routeIngest } from "./lib/ingest-router.js";
11
- const WORKSPACE = process.env.OPENCLAW_WORKSPACE ?? "/root/.openclaw/workspace";
13
+ import { getDb } from "./db.js";
14
+ import { tombstoneFile, tombstonePrefix } from "./lib/tombstone.js";
15
+ import { workspaceRoot } from "./lib/workspace.js";
16
+ const WORKSPACE = workspaceRoot();
12
17
  // NOX_WATCH_DIRS: comma-separated list of ABSOLUTE paths to watch.
13
18
  // If unset, falls back to the default OpenClaw workspace layout below.
14
19
  // Example: NOX_WATCH_DIRS=/data/memory,/data/shared
@@ -60,9 +65,23 @@ function shouldProcess(filepath) {
60
65
  // Debounce map: filepath → timer
61
66
  const debounceMap = new Map();
62
67
  const DEBOUNCE_MS = 2000;
68
+ function tombstoneMissing(filepath) {
69
+ const rel = relative(WORKSPACE, filepath);
70
+ if (rel.startsWith(".."))
71
+ return; // NOX_WATCH_DIRS outside the workspace: no source_file to match
72
+ try {
73
+ const r = tombstoneFile(getDb(), rel, existsSync(filepath), "deleted");
74
+ if (r.status === "tombstoned") {
75
+ console.log(`[WATCH] ${new Date().toISOString()} tombstoned ${r.chunks} chunks ← ${rel} (kept; review with: nox-mem tombstones)`);
76
+ }
77
+ }
78
+ catch (err) {
79
+ console.error(`[WATCH] Error tombstoning ${filepath}: ${err instanceof Error ? err.message : String(err)}`);
80
+ }
81
+ }
63
82
  async function processFile(filepath) {
64
83
  if (!existsSync(filepath))
65
- return; // deleted
84
+ return tombstoneMissing(filepath); // deleted or renamed away
66
85
  try {
67
86
  const stat = statSync(filepath);
68
87
  if (!stat.isFile())
@@ -72,8 +91,10 @@ async function processFile(filepath) {
72
91
  if (stat.size > 5 * 1024 * 1024)
73
92
  return; // skip > 5MB
74
93
  const result = await routeIngest(filepath);
75
- if (result && result.chunks > 0) {
76
- console.log(`[WATCH] ${new Date().toISOString()} +${result.chunks} chunks ← ${filepath.replace(WORKSPACE, "")}`);
94
+ const changed = (result.inserted?.length ?? 0) + (result.deleted ?? 0) + (result.adopted ?? 0);
95
+ if (result && changed > 0) {
96
+ console.log(`[WATCH] ${new Date().toISOString()} +${result.inserted?.length ?? 0} new, -${result.deleted ?? 0} removed, ` +
97
+ `${result.kept ?? 0} kept, ${result.adopted ?? 0} adopted ← ${filepath.replace(WORKSPACE, "")}`);
77
98
  }
78
99
  }
79
100
  catch (err) {
@@ -93,6 +114,42 @@ function debounceIngest(filepath) {
93
114
  }, DEBOUNCE_MS);
94
115
  debounceMap.set(filepath, timer);
95
116
  }
117
+ function walkFiles(dir) {
118
+ const out = [];
119
+ try {
120
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
121
+ const p = resolve(dir, e.name);
122
+ if (e.isDirectory())
123
+ out.push(...walkFiles(p));
124
+ else if (e.isFile() && shouldProcess(p))
125
+ out.push(p);
126
+ }
127
+ }
128
+ catch { }
129
+ return out;
130
+ }
131
+ function debounceTombstoneDir(dirpath) {
132
+ const key = `dir:${dirpath}`;
133
+ const existing = debounceMap.get(key);
134
+ if (existing)
135
+ clearTimeout(existing);
136
+ debounceMap.set(key, setTimeout(() => {
137
+ debounceMap.delete(key);
138
+ if (existsSync(dirpath))
139
+ return;
140
+ const rel = relative(WORKSPACE, dirpath);
141
+ if (rel.startsWith("..") || rel === "")
142
+ return;
143
+ try {
144
+ const r = tombstonePrefix(getDb(), rel, (p) => existsSync(resolve(WORKSPACE, p)), "deleted");
145
+ if (r.files > 0)
146
+ console.log(`[WATCH] ${new Date().toISOString()} tombstoned ${r.files} files (${r.chunks} chunks kept) ← ${rel}/`);
147
+ }
148
+ catch (err) {
149
+ console.error(`[WATCH] Error tombstoning ${dirpath}/: ${err instanceof Error ? err.message : String(err)}`);
150
+ }
151
+ }, DEBOUNCE_MS));
152
+ }
96
153
  export function startWatch(verbose = false) {
97
154
  let watcherCount = 0;
98
155
  const started = [];
@@ -107,8 +164,25 @@ export function startWatch(verbose = false) {
107
164
  if (!filename)
108
165
  return;
109
166
  const filepath = resolve(dir, filename);
110
- if (!shouldProcess(filepath))
167
+ if (SKIP_PATTERNS.some((p) => p.test(filepath)))
168
+ return;
169
+ if (!shouldProcess(filepath)) {
170
+ // A directory moved in arrives as ONE event: ingest what is inside it.
171
+ // A path without an allowed extension that is gone may have been a
172
+ // directory moved out or removed: tombstone what was stored under it.
173
+ let isDir = false;
174
+ try {
175
+ isDir = statSync(filepath).isDirectory();
176
+ }
177
+ catch { }
178
+ if (isDir)
179
+ walkFiles(filepath).forEach(debounceIngest);
180
+ // (no extname test: a directory may be named `projeto.v1`; a path that
181
+ // was never a directory simply matches nothing under its prefix)
182
+ else if (!existsSync(filepath))
183
+ debounceTombstoneDir(filepath);
111
184
  return;
185
+ }
112
186
  debounceIngest(filepath);
113
187
  });
114
188
  watcherCount++;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nox-mem",
3
- "version": "3.5.2",
3
+ "version": "3.7.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",