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/README.md
CHANGED
|
@@ -189,8 +189,11 @@ All destructive operations (reindex, consolidate, compact, crystallize, kg-prune
|
|
|
189
189
|
After install, verify the engine is healthy:
|
|
190
190
|
|
|
191
191
|
```bash
|
|
192
|
-
#
|
|
193
|
-
|
|
192
|
+
nox-mem doctor # Core must be ✅/⚠️; ⚪ under "Optional integrations" is fine
|
|
193
|
+
nox-mem doctor --quiet # scripts: prints only core problems, exits 1 if one failed
|
|
194
|
+
|
|
195
|
+
# Start the API server
|
|
196
|
+
nox-mem-api &
|
|
194
197
|
|
|
195
198
|
# Check vector coverage (should be close to 1.0). Code default port is 18800.
|
|
196
199
|
curl -s "http://127.0.0.1:${NOX_API_PORT:-18800}/api/health" | jq .vectorCoverage
|
|
@@ -204,17 +207,36 @@ A `vectorCoverage` value below 0.99 means some chunks are not yet embedded — r
|
|
|
204
207
|
|
|
205
208
|
```
|
|
206
209
|
nox-mem search "query" — hybrid search (FTS5 + semantic + RRF)
|
|
207
|
-
nox-mem
|
|
208
|
-
nox-mem
|
|
210
|
+
nox-mem search "q" --as-of 2026-05-01 — time-travel: chunks that existed then
|
|
211
|
+
nox-mem search "q" --changed-since 7d — recency window (15m, 2h, 7d, 1w or ISO)
|
|
212
|
+
NOX_FTS_OR_FALLBACK=auto|on|off — FTS5 OR retry (stopwords dropped) when the AND query finds nothing; auto (default) = only when no GEMINI_API_KEY/OPENAI_API_KEY is set, so natural-language questions work on keyless installs and keyed setups are unchanged
|
|
213
|
+
nox-mem answer "question" — grounded answer with citations (needs GEMINI_API_KEY)
|
|
214
|
+
nox-mem ingest <file> — ingest a markdown or entity file (one file per call)
|
|
215
|
+
nox-mem reindex — rebuild the index from $OPENCLAW_WORKSPACE (see warning below)
|
|
209
216
|
nox-mem vectorize — embed any unembedded chunks
|
|
210
217
|
nox-mem stats — chunk/entity/vector counts
|
|
211
218
|
nox-mem kg-build — extract knowledge graph entities
|
|
212
219
|
nox-mem reflect — surface high-salience insights
|
|
213
|
-
|
|
214
|
-
|
|
220
|
+
nox-mem-api — start HTTP API on $NOX_API_PORT (code default 18800)
|
|
221
|
+
nox-mem-mcp — start MCP server over stdio (20 tools, for agents)
|
|
222
|
+
nox-mem doctor — health check (core + optional integrations)
|
|
215
223
|
nox-mem --help — full command reference
|
|
216
224
|
```
|
|
217
225
|
|
|
226
|
+
Wire the MCP server into Claude Code:
|
|
227
|
+
|
|
228
|
+
```bash
|
|
229
|
+
claude mcp add nox-mem -e NOX_DB_PATH="$HOME/.nox-mem/nox.db" -e GEMINI_API_KEY="$GEMINI_API_KEY" -- nox-mem-mcp
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
The temporal filter is also on HTTP (`?as_of=` / `?changed_since=` on `/api/search`, or the same keys in a POST body) and MCP (`as_of` / `changed_since` on `nox_mem_search`). It is a hard SQL pre-filter on `created_at` / `updated_at` (ingestion time), not a ranking boost. `as_of` answers *which chunks existed then*, not *what they said then*: there is no version history, so a chunk edited after the date comes back with its current text. A bare date means the whole day in UTC (`--as-of 2026-05-01` includes 23:59 that day; `--changed-since 2026-05-01` starts at 00:00); a time without an offset is read as UTC. An unparseable date is an error on every surface (exit 2 / HTTP 400 / MCP `isError`), never a silently unfiltered search.
|
|
233
|
+
|
|
234
|
+
> ⚠️ **`reindex` rebuilds only from `$OPENCLAW_WORKSPACE/memory` and `/shared`** (default workspace `/root/.openclaw/workspace`). If that source is missing or empty while the DB holds chunks, it **refuses before touching the DB**; if the rebuild would drop more than 10% of the chunks, it refuses before deleting anything (`NOX_REINDEX_MIN_RETENTION_RATIO`, override `NOX_REINDEX_ALLOW_WIPE=1`). Chunks ingested from outside the workspace are still treated as orphans by a reindex that does run. Preview with `nox-mem reindex --dry-run`. On a standalone install that adds notes with `nox-mem ingest <file>` you normally do not need `reindex`.
|
|
235
|
+
|
|
236
|
+
> **Where the database lives.** `NOX_DB_PATH` if set; else `$OPENCLAW_WORKSPACE/tools/nox-mem/nox-mem.db`; else an existing `<package>/nox-mem.db` (installs from ≤3.4 keep working — with a warning if it sits inside `node_modules`, which `npm update -g` replaces); else `~/.nox-mem/nox.db`. `nox-mem doctor` prints the resolved path.
|
|
237
|
+
|
|
238
|
+
> Without embeddings, search is FTS5 keyword search, which requires every term to match: prefer keywords (`"zebra migration"`) over full questions (`"when was the zebra migration?"`) until you run `vectorize`.
|
|
239
|
+
|
|
218
240
|
---
|
|
219
241
|
|
|
220
242
|
## sqlite-vec and platform binaries
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// FTS5 OR fallback — natural-language questions on keyless installs.
|
|
2
|
+
//
|
|
3
|
+
// FTS5 ANDs a space-separated query, so "when was the zebra migration" matches
|
|
4
|
+
// nothing unless every filler word is in the chunk. search() retries with an OR
|
|
5
|
+
// of the content terms, but ONLY when the AND query returned zero rows, and only
|
|
6
|
+
// when NOX_FTS_OR_FALLBACK allows it (auto = no embedding key in the env).
|
|
7
|
+
//
|
|
8
|
+
// The DB is isolated with NOX_DB_PATH in a mkdtemp BEFORE db.js is imported.
|
|
9
|
+
//
|
|
10
|
+
// Run: npm test (or: npx tsc -p tsconfig.test.json && node --test dist/__tests__/fts-or-fallback.test.js)
|
|
11
|
+
import { test, before, after, beforeEach } from "node:test";
|
|
12
|
+
import assert from "node:assert/strict";
|
|
13
|
+
import { mkdtempSync, rmSync } from "fs";
|
|
14
|
+
import { tmpdir } from "os";
|
|
15
|
+
import { join } from "path";
|
|
16
|
+
import { parseTemporalFilter } from "../lib/dates.js";
|
|
17
|
+
const TMP_ROOT = mkdtempSync(join(process.env.NOX_TEST_TMP_ROOT || tmpdir(), "nox-mem-fts-or-test-"));
|
|
18
|
+
process.env.NOX_DB_PATH = join(TMP_ROOT, "test.db");
|
|
19
|
+
delete process.env.GEMINI_API_KEY;
|
|
20
|
+
delete process.env.OPENAI_API_KEY;
|
|
21
|
+
delete process.env.NOX_FTS_OR_FALLBACK;
|
|
22
|
+
delete process.env.NOX_EMBEDDING_API_KEY;
|
|
23
|
+
delete process.env.NOX_EMBED_API_KEY;
|
|
24
|
+
const NOW = Date.parse("2026-09-28T12:00:00Z");
|
|
25
|
+
const QUESTION = "when was the zebra migration";
|
|
26
|
+
let getDb, closeDb, search, buildFtsOrQuery, ftsOrFallbackEnabled;
|
|
27
|
+
before(async () => {
|
|
28
|
+
({ getDb, closeDb } = await import("../db.js"));
|
|
29
|
+
({ search, buildFtsOrQuery, ftsOrFallbackEnabled } = await import("../search.js"));
|
|
30
|
+
const db = getDb();
|
|
31
|
+
const ins = db.prepare(`INSERT INTO chunks (source_file, chunk_type, chunk_text, source_date, created_at, updated_at)
|
|
32
|
+
VALUES (?, 'other', ?, NULL, ?, ?)`);
|
|
33
|
+
// The chunk the question must find (none of when/was/the is in it).
|
|
34
|
+
ins.run("zebra.md", "zebra migration yesterday", "2026-09-01 08:00:00", "2026-09-01 08:00:00");
|
|
35
|
+
// AND-vs-OR discriminator: "aardvark tunnel" ANDs to fig.md only; OR would add fig2.md.
|
|
36
|
+
ins.run("fig.md", "aardvark tunnel survey", "2026-09-01 08:00:00", "2026-09-01 08:00:00");
|
|
37
|
+
ins.run("fig2.md", "aardvark burrow notes", "2026-09-01 08:00:00", "2026-09-01 08:00:00");
|
|
38
|
+
// Temporal pair for the OR branch: same words, different age.
|
|
39
|
+
ins.run("quokka-old.md", "quokka census results", "2026-01-10 08:00:00", "2026-01-10 08:00:00");
|
|
40
|
+
ins.run("quokka-new.md", "quokka census results", "2026-09-26T10:00:00.000Z", "2026-09-26T10:00:00.000Z");
|
|
41
|
+
});
|
|
42
|
+
after(() => {
|
|
43
|
+
closeDb();
|
|
44
|
+
rmSync(TMP_ROOT, { recursive: true, force: true });
|
|
45
|
+
});
|
|
46
|
+
// Each test sets exactly the env it needs; the gate must be read per call.
|
|
47
|
+
beforeEach(() => {
|
|
48
|
+
delete process.env.GEMINI_API_KEY;
|
|
49
|
+
delete process.env.OPENAI_API_KEY;
|
|
50
|
+
delete process.env.NOX_FTS_OR_FALLBACK;
|
|
51
|
+
});
|
|
52
|
+
const files = (rs) => rs.map((r) => r.source_file).sort();
|
|
53
|
+
// ─── helpers ─────────────────────────────────────────────────────────────────
|
|
54
|
+
test("buildFtsOrQuery: stopwords out, terms quoted, ORed, deduplicated", () => {
|
|
55
|
+
assert.equal(buildFtsOrQuery(QUESTION), '"zebra" OR "migration"');
|
|
56
|
+
assert.equal(buildFtsOrQuery("Zebra zebra ZEBRA migration"), '"Zebra" OR "migration"');
|
|
57
|
+
assert.equal(buildFtsOrQuery("quando foi a migração da zebra"), '"migração" OR "zebra"');
|
|
58
|
+
});
|
|
59
|
+
test("buildFtsOrQuery: only stopwords ⇒ null; embedded quotes are doubled", () => {
|
|
60
|
+
assert.equal(buildFtsOrQuery("what is the"), null);
|
|
61
|
+
assert.equal(buildFtsOrQuery("o que é"), null);
|
|
62
|
+
assert.equal(buildFtsOrQuery('a"b'), '"a""b"');
|
|
63
|
+
});
|
|
64
|
+
test("ftsOrFallbackEnabled: gate matrix", () => {
|
|
65
|
+
assert.equal(ftsOrFallbackEnabled({}), true);
|
|
66
|
+
// Any key the embedding provider resolves counts as "has embeddings".
|
|
67
|
+
assert.equal(ftsOrFallbackEnabled({ NOX_EMBEDDING_API_KEY: "k" }), false);
|
|
68
|
+
assert.equal(ftsOrFallbackEnabled({ NOX_EMBED_API_KEY: "k" }), false);
|
|
69
|
+
assert.equal(ftsOrFallbackEnabled({ NOX_FTS_OR_FALLBACK: "auto" }), true);
|
|
70
|
+
assert.equal(ftsOrFallbackEnabled({ GEMINI_API_KEY: "k" }), false);
|
|
71
|
+
assert.equal(ftsOrFallbackEnabled({ OPENAI_API_KEY: "k" }), false);
|
|
72
|
+
assert.equal(ftsOrFallbackEnabled({ NOX_FTS_OR_FALLBACK: "on", GEMINI_API_KEY: "k" }), true);
|
|
73
|
+
assert.equal(ftsOrFallbackEnabled({ NOX_FTS_OR_FALLBACK: "off" }), false);
|
|
74
|
+
});
|
|
75
|
+
// ─── search() ────────────────────────────────────────────────────────────────
|
|
76
|
+
test("(1) auto, no key: a natural-language question finds the chunk", () => {
|
|
77
|
+
assert.deepEqual(files(search(QUESTION, 10, false)), ["zebra.md"]);
|
|
78
|
+
});
|
|
79
|
+
test("(2) auto WITH an embedding key in the env: same question returns [] as before", () => {
|
|
80
|
+
process.env.GEMINI_API_KEY = "test-key";
|
|
81
|
+
assert.deepEqual(search(QUESTION, 10, false), []);
|
|
82
|
+
delete process.env.GEMINI_API_KEY;
|
|
83
|
+
process.env.OPENAI_API_KEY = "test-key";
|
|
84
|
+
assert.deepEqual(search(QUESTION, 10, false), []);
|
|
85
|
+
});
|
|
86
|
+
test("(3) off: [] even without a key", () => {
|
|
87
|
+
process.env.NOX_FTS_OR_FALLBACK = "off";
|
|
88
|
+
assert.deepEqual(search(QUESTION, 10, false), []);
|
|
89
|
+
});
|
|
90
|
+
test("on: forces the fallback even with a key", () => {
|
|
91
|
+
process.env.NOX_FTS_OR_FALLBACK = "on";
|
|
92
|
+
process.env.GEMINI_API_KEY = "test-key";
|
|
93
|
+
assert.deepEqual(files(search(QUESTION, 10, false)), ["zebra.md"]);
|
|
94
|
+
});
|
|
95
|
+
test("(4) AND already hits: result identical (order and scores) with the fallback on and off", () => {
|
|
96
|
+
process.env.NOX_FTS_OR_FALLBACK = "on";
|
|
97
|
+
const on = search("aardvark tunnel", 10, false);
|
|
98
|
+
process.env.NOX_FTS_OR_FALLBACK = "off";
|
|
99
|
+
const off = search("aardvark tunnel", 10, false);
|
|
100
|
+
assert.deepEqual(files(off), ["fig.md"]); // OR would also have pulled fig2.md
|
|
101
|
+
assert.deepEqual(on, off);
|
|
102
|
+
});
|
|
103
|
+
test("(5) stopwords only: no fallback, even forced on", () => {
|
|
104
|
+
process.env.NOX_FTS_OR_FALLBACK = "on";
|
|
105
|
+
assert.deepEqual(search("what was the", 10, false), []);
|
|
106
|
+
assert.deepEqual(search("o que é a", 10, false), []);
|
|
107
|
+
});
|
|
108
|
+
test("(6) the temporal filter is honoured on the OR branch", () => {
|
|
109
|
+
const q = "when was the quokka census";
|
|
110
|
+
assert.deepEqual(files(search(q, 10, false)), ["quokka-new.md", "quokka-old.md"]);
|
|
111
|
+
const since = parseTemporalFilter({ changedSince: "7d" }, NOW);
|
|
112
|
+
assert.deepEqual(files(search(q, 10, false, since)), ["quokka-new.md"]);
|
|
113
|
+
const asOf = parseTemporalFilter({ asOf: "2026-02-01" }, NOW);
|
|
114
|
+
assert.deepEqual(files(search(q, 10, false, asOf)), ["quokka-old.md"]);
|
|
115
|
+
});
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// reindex on a DB that the pre-2026-09-28 reindex already doubled, plus the
|
|
2
|
+
// adversarial-review findings on PR #29 (GLM + DeepSeek):
|
|
3
|
+
// - the retention guard measured ROWS, so cleaning 2N → N read as a 50% wipe
|
|
4
|
+
// and the first reindex after the fix was refused forever;
|
|
5
|
+
// - among duplicates, the kept row must be the one holding the embedding;
|
|
6
|
+
// - an edited file replaces content, it is not a loss;
|
|
7
|
+
// - --dry-run must not write;
|
|
8
|
+
// - the legacy DB path must equal the one db.ts used before the refactor.
|
|
9
|
+
//
|
|
10
|
+
// Run: npm test (or: npx tsc -p tsconfig.test.json && node --test dist/__tests__/reindex-dedup.test.js)
|
|
11
|
+
import { test, before, after } from "node:test";
|
|
12
|
+
import assert from "node:assert/strict";
|
|
13
|
+
import { mkdtempSync, mkdirSync, realpathSync, rmSync, writeFileSync } from "fs";
|
|
14
|
+
import { tmpdir } from "os";
|
|
15
|
+
import { dirname, join, resolve } from "path";
|
|
16
|
+
import { fileURLToPath } from "url";
|
|
17
|
+
import { LEGACY_DB_PATH } from "../lib/db-path.js";
|
|
18
|
+
const TMP_ROOT = realpathSync(mkdtempSync(join(process.env.NOX_TEST_TMP_ROOT || tmpdir(), "nox-mem-dedup-test-")));
|
|
19
|
+
const WS = join(TMP_ROOT, "ws");
|
|
20
|
+
const MEM = join(WS, "memory");
|
|
21
|
+
mkdirSync(MEM, { recursive: true });
|
|
22
|
+
mkdirSync(join(WS, "tools", "nox-mem"), { recursive: true });
|
|
23
|
+
delete process.env.NOX_DB_PATH;
|
|
24
|
+
delete process.env.NOX_REINDEX_ALLOW_WIPE;
|
|
25
|
+
// Hermetic: with an embedding key in the caller's env, ingest auto-vectorizes
|
|
26
|
+
// (real API calls, and every row gets a vector), which changes which duplicate
|
|
27
|
+
// counts as "the embedded one". Tests never spend on embeddings.
|
|
28
|
+
for (const k of ["GEMINI_API_KEY", "OPENAI_API_KEY", "NOX_EMBEDDING_API_KEY", "NOX_EMBED_API_KEY"])
|
|
29
|
+
delete process.env[k];
|
|
30
|
+
process.env.OPENCLAW_WORKSPACE = WS;
|
|
31
|
+
let getDb, closeDb, reindex, routeIngest;
|
|
32
|
+
const N = 20;
|
|
33
|
+
const count = () => getDb().prepare("SELECT COUNT(*) AS c FROM chunks").get().c;
|
|
34
|
+
before(async () => {
|
|
35
|
+
({ getDb, closeDb } = await import("../db.js"));
|
|
36
|
+
({ reindex } = await import("../reindex.js"));
|
|
37
|
+
({ routeIngest } = await import("../lib/ingest-router.js"));
|
|
38
|
+
for (let i = 1; i <= N; i++)
|
|
39
|
+
writeFileSync(join(MEM, `n${i}.md`), `# N${i}\nnote number ${i} about topic${i}.\n`);
|
|
40
|
+
for (let i = 1; i <= N; i++)
|
|
41
|
+
await routeIngest(join(MEM, `n${i}.md`));
|
|
42
|
+
});
|
|
43
|
+
after(() => {
|
|
44
|
+
closeDb();
|
|
45
|
+
rmSync(TMP_ROOT, { recursive: true, force: true });
|
|
46
|
+
});
|
|
47
|
+
test("legacy DB path is the one db.ts used before the refactor (<package>/nox-mem.db)", () => {
|
|
48
|
+
// this file compiles to dist/__tests__/…; db.ts compiled to dist/db.js and used resolve(dist, "..", "nox-mem.db")
|
|
49
|
+
const dist = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
|
50
|
+
assert.equal(LEGACY_DB_PATH, resolve(dist, "..", "nox-mem.db"));
|
|
51
|
+
});
|
|
52
|
+
test("--dry-run does not write", async () => {
|
|
53
|
+
const pre = count();
|
|
54
|
+
const maxId = getDb().prepare("SELECT MAX(id) AS m FROM chunks").get().m;
|
|
55
|
+
await reindex({ dryRun: true });
|
|
56
|
+
assert.equal(count(), pre);
|
|
57
|
+
assert.equal(getDb().prepare("SELECT MAX(id) AS m FROM chunks").get().m, maxId);
|
|
58
|
+
});
|
|
59
|
+
test("an already-doubled DB is cleaned (2N → N), not refused, and keeps the embedded copy", async () => {
|
|
60
|
+
const db = getDb();
|
|
61
|
+
db.exec("INSERT INTO chunks (source_file, chunk_type, chunk_text, source_date) SELECT source_file, chunk_type, chunk_text, source_date FROM chunks");
|
|
62
|
+
assert.equal(count(), 2 * N);
|
|
63
|
+
// Mark the HIGHER-id copy of n7 as the embedded one; lowest-id-wins alone would drop it.
|
|
64
|
+
const copies = db.prepare("SELECT id FROM chunks WHERE chunk_text LIKE '%number 7 about%' ORDER BY id").all();
|
|
65
|
+
assert.equal(copies.length, 2);
|
|
66
|
+
db.exec("CREATE TABLE IF NOT EXISTS vec_chunk_map (vec_rowid INTEGER PRIMARY KEY, chunk_id INTEGER NOT NULL UNIQUE)");
|
|
67
|
+
db.prepare("INSERT INTO vec_chunk_map (vec_rowid, chunk_id) VALUES (?, ?)").run(900001, copies[1].id);
|
|
68
|
+
await reindex();
|
|
69
|
+
assert.equal(count(), N, "one row per distinct content");
|
|
70
|
+
const left = db.prepare("SELECT id FROM chunks WHERE chunk_text LIKE '%number 7 about%'").all();
|
|
71
|
+
assert.deepEqual(left.map((r) => r.id), [copies[1].id], "the copy with the embedding survives");
|
|
72
|
+
});
|
|
73
|
+
test("editing many files is replacement, not loss (guard stays quiet)", async () => {
|
|
74
|
+
// Rewrite half the corpus: every chunk of those files changes fingerprint.
|
|
75
|
+
for (let i = 1; i <= N / 2; i++)
|
|
76
|
+
writeFileSync(join(MEM, `n${i}.md`), `# N${i}\nnote number ${i} REWRITTEN.\n`);
|
|
77
|
+
await reindex();
|
|
78
|
+
assert.equal(count(), N);
|
|
79
|
+
assert.equal(getDb().prepare("SELECT COUNT(*) AS c FROM chunks WHERE chunk_text LIKE '%REWRITTEN%'").get().c, N / 2);
|
|
80
|
+
});
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
// reindex safety (2026-09-28) — measured on a clean npm install before the fix:
|
|
2
|
+
// 1. no $OPENCLAW_WORKSPACE ⇒ the scan found 0 files ⇒ every chunk was deleted
|
|
3
|
+
// as an "orphan"; the retention guard threw only AFTER the DELETE;
|
|
4
|
+
// 2. every reindex kept both the old row and the fresh copy of unchanged
|
|
5
|
+
// content (10 chunks → 20).
|
|
6
|
+
// Also covers the shared DB path resolver (db.ts and op-audit must agree).
|
|
7
|
+
//
|
|
8
|
+
// Run: npm test (or: npx tsc -p tsconfig.test.json && node --test dist/__tests__/reindex-safety.test.js)
|
|
9
|
+
import { test, before, after } from "node:test";
|
|
10
|
+
import assert from "node:assert/strict";
|
|
11
|
+
import { mkdtempSync, mkdirSync, realpathSync, rmSync, writeFileSync, unlinkSync } from "fs";
|
|
12
|
+
import { tmpdir, homedir } from "os";
|
|
13
|
+
import { join } from "path";
|
|
14
|
+
import { resolveDbPathWithSource, LEGACY_DB_PATH, DEFAULT_STANDALONE_DB_PATH, isInsideNodeModules, } from "../lib/db-path.js";
|
|
15
|
+
// realpath: op-audit refuses snapshot dirs reached through a symlink (macOS /tmp → /private/tmp).
|
|
16
|
+
const TMP_ROOT = realpathSync(mkdtempSync(join(process.env.NOX_TEST_TMP_ROOT || tmpdir(), "nox-mem-reindex-test-")));
|
|
17
|
+
const WS = join(TMP_ROOT, "ws");
|
|
18
|
+
const MEM = join(WS, "memory");
|
|
19
|
+
mkdirSync(MEM, { recursive: true });
|
|
20
|
+
mkdirSync(join(WS, "tools", "nox-mem"), { recursive: true });
|
|
21
|
+
// DB derives from the workspace, as on the origin deployment (op-audit rejects a
|
|
22
|
+
// NOX_DB_PATH that disagrees with OPENCLAW_WORKSPACE).
|
|
23
|
+
delete process.env.NOX_DB_PATH;
|
|
24
|
+
delete process.env.NOX_REINDEX_ALLOW_WIPE;
|
|
25
|
+
// Hermetic: with an embedding key in the caller's env, ingest auto-vectorizes
|
|
26
|
+
// (real API calls, and every row gets a vector), which changes which duplicate
|
|
27
|
+
// counts as "the embedded one". Tests never spend on embeddings.
|
|
28
|
+
for (const k of ["GEMINI_API_KEY", "OPENAI_API_KEY", "NOX_EMBEDDING_API_KEY", "NOX_EMBED_API_KEY"])
|
|
29
|
+
delete process.env[k];
|
|
30
|
+
process.env.OPENCLAW_WORKSPACE = WS;
|
|
31
|
+
const DB = join(WS, "tools", "nox-mem", "nox-mem.db");
|
|
32
|
+
// ─── DB path resolver (pure) ─────────────────────────────────────────────────
|
|
33
|
+
test("db-path: NOX_DB_PATH wins", () => {
|
|
34
|
+
const r = resolveDbPathWithSource({ NOX_DB_PATH: "/x/y.db", OPENCLAW_WORKSPACE: "/ws" }, () => true);
|
|
35
|
+
assert.deepEqual(r, { path: "/x/y.db", source: "NOX_DB_PATH" });
|
|
36
|
+
});
|
|
37
|
+
test("db-path: OPENCLAW_WORKSPACE next (origin layout unchanged)", () => {
|
|
38
|
+
const r = resolveDbPathWithSource({ OPENCLAW_WORKSPACE: "/root/.openclaw/workspace" }, () => false);
|
|
39
|
+
assert.deepEqual(r, { path: "/root/.openclaw/workspace/tools/nox-mem/nox-mem.db", source: "OPENCLAW_WORKSPACE" });
|
|
40
|
+
});
|
|
41
|
+
test("db-path: existing legacy <package>/nox-mem.db is kept (no silent move of live data)", () => {
|
|
42
|
+
const r = resolveDbPathWithSource({}, (p) => p === LEGACY_DB_PATH);
|
|
43
|
+
assert.deepEqual(r, { path: LEGACY_DB_PATH, source: "legacy-package" });
|
|
44
|
+
});
|
|
45
|
+
test("db-path: fresh install defaults to ~/.nox-mem/nox.db, not the package dir", () => {
|
|
46
|
+
const r = resolveDbPathWithSource({}, () => false);
|
|
47
|
+
assert.equal(r.source, "standalone-default");
|
|
48
|
+
assert.equal(r.path, join(homedir(), ".nox-mem", "nox.db"));
|
|
49
|
+
assert.equal(r.path, DEFAULT_STANDALONE_DB_PATH);
|
|
50
|
+
assert.equal(isInsideNodeModules(r.path), false);
|
|
51
|
+
});
|
|
52
|
+
test("db-path: node_modules detection", () => {
|
|
53
|
+
assert.equal(isInsideNodeModules("/usr/lib/node_modules/nox-mem/nox-mem.db"), true);
|
|
54
|
+
assert.equal(isInsideNodeModules("/home/u/.nox-mem/nox.db"), false);
|
|
55
|
+
});
|
|
56
|
+
// ─── reindex against a real workspace ────────────────────────────────────────
|
|
57
|
+
let getDb, closeDb, reindex, assertReindexSource;
|
|
58
|
+
let ReindexSourceMissingError, ReindexWipeDetectedError, routeIngest;
|
|
59
|
+
const count = () => getDb().prepare("SELECT COUNT(*) AS c FROM chunks").get().c;
|
|
60
|
+
const ids = () => getDb().prepare("SELECT group_concat(id) AS g FROM (SELECT id FROM chunks ORDER BY id)").get().g;
|
|
61
|
+
before(async () => {
|
|
62
|
+
({ getDb, closeDb } = await import("../db.js"));
|
|
63
|
+
({ reindex, assertReindexSource, ReindexSourceMissingError, ReindexWipeDetectedError } = await import("../reindex.js"));
|
|
64
|
+
({ routeIngest } = await import("../lib/ingest-router.js"));
|
|
65
|
+
for (let i = 1; i <= 10; i++)
|
|
66
|
+
writeFileSync(join(MEM, `n${i}.md`), `# N${i}\nnote number ${i} about topic${i}.\n`);
|
|
67
|
+
for (let i = 1; i <= 10; i++)
|
|
68
|
+
await routeIngest(join(MEM, `n${i}.md`));
|
|
69
|
+
assert.equal(getDb().prepare("SELECT 1").get() !== undefined, true);
|
|
70
|
+
});
|
|
71
|
+
after(() => {
|
|
72
|
+
closeDb();
|
|
73
|
+
rmSync(TMP_ROOT, { recursive: true, force: true });
|
|
74
|
+
});
|
|
75
|
+
test("reindex: unchanged content is not duplicated and keeps its ids", async () => {
|
|
76
|
+
const before = ids();
|
|
77
|
+
assert.equal(count(), 10);
|
|
78
|
+
await reindex();
|
|
79
|
+
assert.equal(count(), 10, "one reindex must not double the corpus");
|
|
80
|
+
await reindex();
|
|
81
|
+
assert.equal(count(), 10);
|
|
82
|
+
assert.equal(ids(), before, "old rows (with their embeddings) are the ones kept");
|
|
83
|
+
});
|
|
84
|
+
test("reindex: edited file replaces its chunk, new file is added", async () => {
|
|
85
|
+
writeFileSync(join(MEM, "n1.md"), "# N1\nnote number 1 EDITED.\n");
|
|
86
|
+
writeFileSync(join(MEM, "n11.md"), "# N11\nbrand new note eleven.\n");
|
|
87
|
+
await reindex();
|
|
88
|
+
const q = (like) => getDb().prepare("SELECT COUNT(*) AS c FROM chunks WHERE chunk_text LIKE ?").get(like).c;
|
|
89
|
+
assert.equal(q("%EDITED%"), 1);
|
|
90
|
+
assert.equal(q("%number 1 about%"), 0);
|
|
91
|
+
assert.equal(q("%eleven%"), 1);
|
|
92
|
+
assert.equal(count(), 11);
|
|
93
|
+
});
|
|
94
|
+
test("reindex: retention guard refuses BEFORE deleting (rows survive the throw)", async () => {
|
|
95
|
+
for (const i of [2, 3, 4, 5, 6])
|
|
96
|
+
unlinkSync(join(MEM, `n${i}.md`));
|
|
97
|
+
const pre = count();
|
|
98
|
+
await assert.rejects(() => reindex(), (e) => e instanceof ReindexWipeDetectedError);
|
|
99
|
+
assert.ok(count() >= pre, `no chunk may be deleted when the guard fires (pre=${pre}, now=${count()})`);
|
|
100
|
+
});
|
|
101
|
+
test("assertReindexSource: refuses when no source dir exists and the DB has chunks", () => {
|
|
102
|
+
// The workspace path is captured at import, so empty the fixture instead.
|
|
103
|
+
rmSync(MEM, { recursive: true, force: true });
|
|
104
|
+
assert.throws(() => assertReindexSource(5), (e) => e instanceof ReindexSourceMissingError && /no source directory/.test(e.message));
|
|
105
|
+
assert.doesNotThrow(() => assertReindexSource(0), "an empty DB has nothing to lose");
|
|
106
|
+
});
|
|
107
|
+
test("assertReindexSource: refuses when the source dir exists but holds no file", () => {
|
|
108
|
+
mkdirSync(MEM, { recursive: true });
|
|
109
|
+
assert.throws(() => assertReindexSource(5), (e) => e instanceof ReindexSourceMissingError && /found 0 files/.test(e.message));
|
|
110
|
+
});
|
|
111
|
+
test("reindex: refusal leaves every chunk in place", async () => {
|
|
112
|
+
const pre = count();
|
|
113
|
+
assert.ok(pre > 0);
|
|
114
|
+
await assert.rejects(() => reindex(), (e) => e instanceof ReindexSourceMissingError);
|
|
115
|
+
assert.equal(count(), pre);
|
|
116
|
+
});
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// P3 — temporal filter (--as-of / --changed-since) as a hard SQL pre-filter.
|
|
2
|
+
//
|
|
3
|
+
// Covers the parser, the SQL fragment, and the real search() path against a
|
|
4
|
+
// throwaway DB, including the two traps the staged P3 patch had:
|
|
5
|
+
// - `created_at` holds datetime('now') text ("YYYY-MM-DD HH:MM:SS") while the
|
|
6
|
+
// bound value is ISO ("...T...Z"); a raw string comparison gets it wrong;
|
|
7
|
+
// - there is no deleted_at column, so a clause that names it fails at runtime.
|
|
8
|
+
//
|
|
9
|
+
// Run: npm test (or: npx tsc -p tsconfig.test.json && node --test dist/__tests__/temporal-filter.test.js)
|
|
10
|
+
import { test, before, after } from "node:test";
|
|
11
|
+
import assert from "node:assert/strict";
|
|
12
|
+
import { mkdtempSync, rmSync } from "fs";
|
|
13
|
+
import { tmpdir } from "os";
|
|
14
|
+
import { join } from "path";
|
|
15
|
+
import { parseFlexibleDate, parseTemporalFilter, buildTemporalClause, TemporalParseError, } from "../lib/dates.js";
|
|
16
|
+
const TMP_ROOT = mkdtempSync(join(process.env.NOX_TEST_TMP_ROOT || tmpdir(), "nox-mem-temporal-test-"));
|
|
17
|
+
process.env.NOX_DB_PATH = join(TMP_ROOT, "test.db");
|
|
18
|
+
delete process.env.GEMINI_API_KEY;
|
|
19
|
+
delete process.env.OPENAI_API_KEY;
|
|
20
|
+
const NOW = Date.parse("2026-09-28T12:00:00Z");
|
|
21
|
+
// ─── parser ──────────────────────────────────────────────────────────────────
|
|
22
|
+
test("parseFlexibleDate: date-only is midnight UTC", () => {
|
|
23
|
+
assert.equal(parseFlexibleDate("2026-05-01", NOW).toISOString(), "2026-05-01T00:00:00.000Z");
|
|
24
|
+
});
|
|
25
|
+
test("parseFlexibleDate: full ISO", () => {
|
|
26
|
+
assert.equal(parseFlexibleDate("2026-05-01T10:30:00Z", NOW).toISOString(), "2026-05-01T10:30:00.000Z");
|
|
27
|
+
assert.equal(parseFlexibleDate("2026-05-01T10:30:00-03:00", NOW).toISOString(), "2026-05-01T13:30:00.000Z");
|
|
28
|
+
});
|
|
29
|
+
test("parseFlexibleDate: ISO without offset is UTC, not local time", () => {
|
|
30
|
+
assert.equal(parseFlexibleDate("2026-05-01T10:30:00", NOW).toISOString(), "2026-05-01T10:30:00.000Z");
|
|
31
|
+
});
|
|
32
|
+
test("parseTemporalFilter: date-only as-of is END of day, changed-since START of day", () => {
|
|
33
|
+
const f = parseTemporalFilter({ asOf: "2026-05-01", changedSince: "2026-05-01" }, NOW);
|
|
34
|
+
assert.equal(f.asOf.toISOString(), "2026-05-01T23:59:59.999Z");
|
|
35
|
+
assert.equal(f.changedSince.toISOString(), "2026-05-01T00:00:00.000Z");
|
|
36
|
+
});
|
|
37
|
+
test("parseFlexibleDate: relative units count back from now", () => {
|
|
38
|
+
assert.equal(parseFlexibleDate("15m", NOW).getTime(), NOW - 15 * 60_000);
|
|
39
|
+
assert.equal(parseFlexibleDate("2h", NOW).getTime(), NOW - 2 * 3_600_000);
|
|
40
|
+
assert.equal(parseFlexibleDate("7d", NOW).getTime(), NOW - 7 * 86_400_000);
|
|
41
|
+
assert.equal(parseFlexibleDate("1w", NOW).getTime(), NOW - 7 * 86_400_000);
|
|
42
|
+
assert.equal(parseFlexibleDate("7D", NOW).getTime(), NOW - 7 * 86_400_000);
|
|
43
|
+
});
|
|
44
|
+
test("parseFlexibleDate: rejects what Date.parse would guess at", () => {
|
|
45
|
+
for (const bad of ["", " ", "1mo", "yesterday", "May 1", "12345", "2026-13-45", "7x"]) {
|
|
46
|
+
assert.throws(() => parseFlexibleDate(bad, NOW), TemporalParseError, `should reject ${JSON.stringify(bad)}`);
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
test("parseTemporalFilter: nothing set ⇒ undefined (callers keep the unfiltered path)", () => {
|
|
50
|
+
assert.equal(parseTemporalFilter({}, NOW), undefined);
|
|
51
|
+
assert.equal(parseTemporalFilter({ asOf: "", changedSince: undefined }, NOW), undefined);
|
|
52
|
+
assert.equal(parseTemporalFilter({ asOf: null, changedSince: null }, NOW), undefined);
|
|
53
|
+
});
|
|
54
|
+
test("parseTemporalFilter: a bad value throws instead of being dropped", () => {
|
|
55
|
+
assert.throws(() => parseTemporalFilter({ asOf: "2026-05-01", changedSince: "soon" }, NOW), TemporalParseError);
|
|
56
|
+
});
|
|
57
|
+
// ─── SQL fragment ────────────────────────────────────────────────────────────
|
|
58
|
+
test("buildTemporalClause: empty filter ⇒ null, so the search SQL is unchanged", () => {
|
|
59
|
+
assert.equal(buildTemporalClause(undefined), null);
|
|
60
|
+
assert.equal(buildTemporalClause({}), null);
|
|
61
|
+
});
|
|
62
|
+
test("buildTemporalClause: never references deleted_at (column does not exist)", () => {
|
|
63
|
+
const c = buildTemporalClause({ asOf: new Date(NOW), changedSince: new Date(NOW) });
|
|
64
|
+
assert.doesNotMatch(c.sql, /deleted_at/);
|
|
65
|
+
assert.equal(c.params.length, 3);
|
|
66
|
+
});
|
|
67
|
+
// ─── search() against a real schema ──────────────────────────────────────────
|
|
68
|
+
let getDb, closeDb, search, searchSemantic;
|
|
69
|
+
before(async () => {
|
|
70
|
+
({ getDb, closeDb } = await import("../db.js"));
|
|
71
|
+
({ search, searchSemantic } = await import("../search.js"));
|
|
72
|
+
const db = getDb();
|
|
73
|
+
const ins = db.prepare(`INSERT INTO chunks (source_file, chunk_type, chunk_text, source_date, created_at, updated_at)
|
|
74
|
+
VALUES (?, 'other', ?, NULL, ?, ?)`);
|
|
75
|
+
// created_at in the format SQLite's DEFAULT writes…
|
|
76
|
+
ins.run("old.md", "zebra migration notes, first draft", "2026-01-10 08:00:00", "2026-01-10 08:00:00");
|
|
77
|
+
// …a row edited long after it was created…
|
|
78
|
+
ins.run("edited.md", "zebra migration notes, revised", "2026-01-15 08:00:00", "2026-09-27 09:00:00");
|
|
79
|
+
// …a recent row stored as ISO…
|
|
80
|
+
ins.run("new.md", "zebra migration notes, final", "2026-09-26T10:00:00.000Z", "2026-09-26T10:00:00.000Z");
|
|
81
|
+
// …and a legacy row with no created_at at all.
|
|
82
|
+
ins.run("legacy.md", "zebra migration notes, legacy import", null, null);
|
|
83
|
+
});
|
|
84
|
+
after(() => {
|
|
85
|
+
closeDb();
|
|
86
|
+
rmSync(TMP_ROOT, { recursive: true, force: true });
|
|
87
|
+
});
|
|
88
|
+
const files = (rs) => rs.map((r) => r.source_file).sort();
|
|
89
|
+
test("search: no filter returns every match (baseline)", () => {
|
|
90
|
+
assert.deepEqual(files(search("zebra", 10, false)), ["edited.md", "legacy.md", "new.md", "old.md"]);
|
|
91
|
+
});
|
|
92
|
+
test("search: as-of keeps what existed then, plus legacy rows (spec: NULL = always existed)", () => {
|
|
93
|
+
const f = parseTemporalFilter({ asOf: "2026-02-01" }, NOW);
|
|
94
|
+
assert.deepEqual(files(search("zebra", 10, false, f)), ["edited.md", "legacy.md", "old.md"]);
|
|
95
|
+
});
|
|
96
|
+
test("search: as-of compares datetimes, not strings ('2026-01-10 08:00:00' vs '2026-01-10T…')", () => {
|
|
97
|
+
// String comparison would say "2026-01-10 08:00:00" <= "2026-01-10T06:00:00.000Z"
|
|
98
|
+
// (space sorts before 'T') and wrongly keep old.md, created at 08:00.
|
|
99
|
+
const f = parseTemporalFilter({ asOf: "2026-01-10T06:00:00Z" }, NOW);
|
|
100
|
+
assert.deepEqual(files(search("zebra", 10, false, f)), ["legacy.md"]);
|
|
101
|
+
});
|
|
102
|
+
test("search: date-only as-of includes rows created later that same day", () => {
|
|
103
|
+
const f = parseTemporalFilter({ asOf: "2026-01-10" }, NOW);
|
|
104
|
+
assert.deepEqual(files(search("zebra", 10, false, f)), ["legacy.md", "old.md"]);
|
|
105
|
+
});
|
|
106
|
+
test("search: changed-since picks created OR updated after the date", () => {
|
|
107
|
+
const f = parseTemporalFilter({ changedSince: "7d" }, NOW);
|
|
108
|
+
assert.deepEqual(files(search("zebra", 10, false, f)), ["edited.md", "new.md"]);
|
|
109
|
+
});
|
|
110
|
+
test("search: both flags AND together", () => {
|
|
111
|
+
const f = parseTemporalFilter({ asOf: "2026-02-01", changedSince: "7d" }, NOW);
|
|
112
|
+
assert.deepEqual(files(search("zebra", 10, false, f)), ["edited.md"]);
|
|
113
|
+
});
|
|
114
|
+
test("searchSemantic: the FTS fallback (empty vector index) keeps the filter", async () => {
|
|
115
|
+
const f = parseTemporalFilter({ changedSince: "7d" }, NOW);
|
|
116
|
+
assert.deepEqual(files(await searchSemantic("zebra", 10, false, f)), ["edited.md", "new.md"]);
|
|
117
|
+
});
|
package/dist/api-server.js
CHANGED
|
@@ -18,6 +18,7 @@ import { applyCorsHeaders, handlePreflight } from "./api/cors.js";
|
|
|
18
18
|
import { safeErrorMessage } from "./lib/api/safe-error-message.js";
|
|
19
19
|
import { registerWireUpRoutes } from "./api/wire-up.js";
|
|
20
20
|
import { handleBrief } from "./api/brief.js";
|
|
21
|
+
import { parseTemporalFilter, TemporalParseError } from "./lib/dates.js";
|
|
21
22
|
import { handleIngestEvent } from "./api/ingest-event.js";
|
|
22
23
|
import { handleObsHealth, handleObsRecentOps, handleObsCanaryTail, } from "./observability.js";
|
|
23
24
|
const PORT = parseInt(process.env.NOX_API_PORT || "18800");
|
|
@@ -381,22 +382,39 @@ async function handleRequest(req, res) {
|
|
|
381
382
|
let qText;
|
|
382
383
|
let limitStr;
|
|
383
384
|
let trackStr;
|
|
385
|
+
let asOfStr;
|
|
386
|
+
let changedSinceStr;
|
|
384
387
|
if (req.method === "POST") {
|
|
385
388
|
const body = await readJson(req);
|
|
386
389
|
qText = body.q ?? body.query;
|
|
387
390
|
limitStr = body.limit !== undefined ? String(body.limit) : undefined;
|
|
388
391
|
trackStr = body.track !== undefined ? String(body.track) : undefined;
|
|
392
|
+
asOfStr = body.as_of;
|
|
393
|
+
changedSinceStr = body.changed_since;
|
|
389
394
|
}
|
|
390
395
|
else {
|
|
391
396
|
const q = parseQuery(url);
|
|
392
397
|
qText = q.q ?? q.query;
|
|
393
398
|
limitStr = q.limit;
|
|
394
399
|
trackStr = q.track;
|
|
400
|
+
asOfStr = q.as_of;
|
|
401
|
+
changedSinceStr = q.changed_since;
|
|
395
402
|
}
|
|
396
403
|
if (!qText) {
|
|
397
404
|
json(res, { error: "q parameter required (POST body or GET query string, field name: q or query)" }, 400);
|
|
398
405
|
break;
|
|
399
406
|
}
|
|
407
|
+
// P3: an unparseable date is a 400, never a silently unfiltered search.
|
|
408
|
+
let temporalFilter;
|
|
409
|
+
try {
|
|
410
|
+
temporalFilter = parseTemporalFilter({ asOf: asOfStr, changedSince: changedSinceStr });
|
|
411
|
+
}
|
|
412
|
+
catch (err) {
|
|
413
|
+
if (!(err instanceof TemporalParseError))
|
|
414
|
+
throw err;
|
|
415
|
+
json(res, { error: err.message }, 400);
|
|
416
|
+
break;
|
|
417
|
+
}
|
|
400
418
|
const limit = parseInt(limitStr || "10");
|
|
401
419
|
// D1 (2026-06-07): healthchecks/canary pass ?track=false so automated
|
|
402
420
|
// probes don't inflate access_count → salience feedback loop. Default
|
|
@@ -405,7 +423,7 @@ async function handleRequest(req, res) {
|
|
|
405
423
|
// E12 (2026-05-04): propagate requesting agent from header
|
|
406
424
|
const agentHeader = req.headers["x-agent-name"];
|
|
407
425
|
const requestingAgent = (Array.isArray(agentHeader) ? agentHeader[0] : agentHeader) ?? process.env.NOX_AGENT_NAME;
|
|
408
|
-
const results = await searchHybrid(qText, limit, trackAccess);
|
|
426
|
+
const results = await searchHybrid(qText, limit, trackAccess, temporalFilter);
|
|
409
427
|
// E03a (2026-05-02): SPO injection envelope. Mode shadow → compute+log only.
|
|
410
428
|
// Mode active → surface vaultFacts in response. Mode off → no compute.
|
|
411
429
|
const vf = getVaultFacts(qText, getDb());
|
package/dist/db.js
CHANGED
|
@@ -4,23 +4,27 @@ import { fileURLToPath } from "url";
|
|
|
4
4
|
import { copyFileSync, existsSync, mkdirSync, readdirSync, unlinkSync } from "fs";
|
|
5
5
|
// @ts-ignore - sqlite-vec ships no type declarations for this helper
|
|
6
6
|
import { getLoadablePath as vecLoadablePath } from "sqlite-vec";
|
|
7
|
+
import { resolveDbPathWithSource, isInsideNodeModules } from "./lib/db-path.js";
|
|
8
|
+
let _warnedNodeModules = false;
|
|
7
9
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
8
10
|
const _ws = process.env.OPENCLAW_WORKSPACE;
|
|
9
|
-
// DB path resolution — priority order (postmortem 2026-05-19 fix)
|
|
11
|
+
// DB path resolution — priority order (postmortem 2026-05-19 fix), now shared
|
|
12
|
+
// with op-audit via src/lib/db-path.ts so the pre-op snapshot always covers the
|
|
13
|
+
// file this module opens:
|
|
10
14
|
// 1. NOX_DB_PATH env var (explicit override for eval/test isolation)
|
|
11
15
|
// 2. OPENCLAW_WORKSPACE-derived canonical path (production default)
|
|
12
|
-
// 3.
|
|
16
|
+
// 3. <package root>/nox-mem.db, only if it already exists (legacy installs)
|
|
17
|
+
// 4. ~/.nox-mem/nox.db (standalone default — never inside node_modules)
|
|
13
18
|
//
|
|
14
19
|
// WARNING: Before this fix, only OPENCLAW_WORKSPACE was consulted. Any caller
|
|
15
20
|
// that set NOX_DB_PATH (e.g. G3 eval orchestrator, run_locomo_ablations.sh)
|
|
16
21
|
// was silently ignored — `nox-mem ingest` always wrote to the production DB.
|
|
17
22
|
// Root cause of the 2026-05-19 wipe incident (500 eval chunks → prod).
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
export const BACKUP_DIR = _ws ? resolve(_ws, "tools", "nox-mem", "backups") : resolve(__dirname, "..", "backups");
|
|
23
|
+
const _resolvedDb = resolveDbPathWithSource();
|
|
24
|
+
export const DB_PATH = _resolvedDb.path;
|
|
25
|
+
// Backups live next to the DB. For the legacy package path this is the same
|
|
26
|
+
// directory as before (<package root>/backups); it only moves for new installs.
|
|
27
|
+
export const BACKUP_DIR = _ws ? resolve(_ws, "tools", "nox-mem", "backups") : resolve(dirname(DB_PATH), "backups");
|
|
24
28
|
const SCHEMA_VERSION = 19;
|
|
25
29
|
// ────────────────────────────────────────────────────────────────────────────
|
|
26
30
|
// Large-DB ingest guard (postmortem 2026-05-19)
|
|
@@ -57,6 +61,14 @@ let _db = null;
|
|
|
57
61
|
export function getDb() {
|
|
58
62
|
if (_db && _db.open)
|
|
59
63
|
return _db;
|
|
64
|
+
if (_resolvedDb.source === "standalone-default") {
|
|
65
|
+
mkdirSync(dirname(DB_PATH), { recursive: true });
|
|
66
|
+
}
|
|
67
|
+
else if (_resolvedDb.source === "legacy-package" && isInsideNodeModules(DB_PATH) && !_warnedNodeModules) {
|
|
68
|
+
_warnedNodeModules = true;
|
|
69
|
+
console.error(`[nox-mem] WARNING: database is inside node_modules (${DB_PATH}); \`npm update -g\` replaces that directory. ` +
|
|
70
|
+
`Move it and set NOX_DB_PATH, e.g.: mkdir -p ~/.nox-mem && mv "${DB_PATH}" ~/.nox-mem/nox.db && export NOX_DB_PATH=~/.nox-mem/nox.db`);
|
|
71
|
+
}
|
|
60
72
|
_db = new Database(DB_PATH);
|
|
61
73
|
_db.pragma("journal_mode = WAL");
|
|
62
74
|
_db.pragma("foreign_keys = ON");
|