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/doctor.js
CHANGED
|
@@ -1,64 +1,142 @@
|
|
|
1
1
|
import { getDb, DB_PATH } from "./db.js";
|
|
2
2
|
import { statSync, existsSync } from "fs";
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
// Unit names the watcher has shipped under: the repo's unit file and the
|
|
4
|
+
// older name still used on the origin VPS.
|
|
5
|
+
const WATCHER_UNITS = ["nox-mem-watcher.service", "nox-mem-watch.service"];
|
|
6
|
+
/**
|
|
7
|
+
* Two groups, deliberately:
|
|
8
|
+
* core — the store, FTS5 and embeddings. A ❌ here means ingest/search is broken.
|
|
9
|
+
* optional — integrations only some commands use (Ollama for consolidate /
|
|
10
|
+
* kg-extract, Notion, the systemd watcher). Absent ⇒ ⚪, never ❌:
|
|
11
|
+
* a fresh install without them is healthy.
|
|
12
|
+
*
|
|
13
|
+
* `--quiet` prints only core problems and exits 1 iff a core check failed —
|
|
14
|
+
* the contract scripts/test.sh relies on.
|
|
15
|
+
*/
|
|
16
|
+
export async function doctor(opts = {}) {
|
|
17
|
+
const core = [];
|
|
18
|
+
const optional = [];
|
|
5
19
|
// 1. SQLite database
|
|
6
20
|
try {
|
|
7
21
|
const db = getDb();
|
|
8
22
|
const version = db.prepare("SELECT value FROM meta WHERE key = 'schema_version'").get();
|
|
9
|
-
|
|
23
|
+
core.push({ name: "SQLite DB", status: "✅", detail: `schema v${version?.value || "?"}, ${formatSize(DB_PATH)} at ${DB_PATH}` });
|
|
10
24
|
// 2. FTS5 index
|
|
11
|
-
|
|
25
|
+
// chunks_fts is an external-content table: COUNT(*) on it reads the CONTENT
|
|
26
|
+
// table (chunks), so "indexed == chunks" held by construction and this check
|
|
27
|
+
// could never fire. The docsize shadow table has one row per document the
|
|
28
|
+
// index actually holds — measured: after an FTS 'delete' it drops to 0 while
|
|
29
|
+
// COUNT(*) on chunks_fts still reports every chunk (2026-09-28).
|
|
30
|
+
const hasDocsize = db.prepare("SELECT 1 FROM sqlite_master WHERE name = 'chunks_fts_docsize'").get() !== undefined;
|
|
31
|
+
const ftsCount = db.prepare(`SELECT COUNT(*) as c FROM ${hasDocsize ? "chunks_fts_docsize" : "chunks_fts"}`).get().c;
|
|
12
32
|
const chunkCount = db.prepare("SELECT COUNT(*) as c FROM chunks").get().c;
|
|
13
33
|
const ftsOk = ftsCount === chunkCount;
|
|
14
|
-
|
|
15
|
-
// 3.
|
|
34
|
+
core.push({ name: "FTS5 Index", status: ftsOk ? "✅" : "⚠️", detail: `${ftsCount} indexed / ${chunkCount} chunks${ftsOk ? "" : ` — MISMATCH, rebuild the FTS index: sqlite3 "${DB_PATH}" "INSERT INTO chunks_fts(chunks_fts) VALUES('rebuild')"`}` });
|
|
35
|
+
// 3. Embeddings (semantic search). Missing key is a degraded mode, not a failure:
|
|
36
|
+
// search falls back to FTS5.
|
|
37
|
+
const hasKey = Boolean(process.env.NOX_EMBEDDING_API_KEY || process.env.NOX_EMBED_API_KEY || process.env.GEMINI_API_KEY || process.env.OPENAI_API_KEY);
|
|
38
|
+
let embedded = 0;
|
|
39
|
+
try {
|
|
40
|
+
const { ensureVecTable, countEmbedded } = await import("./embed.js");
|
|
41
|
+
ensureVecTable(db);
|
|
42
|
+
embedded = countEmbedded(db);
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
// sqlite-vec not loadable — reported through the detail below
|
|
46
|
+
}
|
|
47
|
+
if (!hasKey) {
|
|
48
|
+
core.push({ name: "Embeddings", status: "⚠️", detail: `no GEMINI_API_KEY — search is keyword-only (FTS5); ${embedded}/${chunkCount} embedded` });
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
const full = embedded >= chunkCount;
|
|
52
|
+
core.push({ name: "Embeddings", status: full ? "✅" : "⚠️", detail: `${embedded}/${chunkCount} embedded${full ? "" : " — run nox-mem vectorize"}` });
|
|
53
|
+
}
|
|
54
|
+
// 4. Consolidated files
|
|
16
55
|
const consolidated = db.prepare("SELECT COUNT(*) as c FROM consolidated_files WHERE status = 1").get().c;
|
|
17
56
|
const failed = db.prepare("SELECT COUNT(*) as c FROM consolidated_files WHERE status = -1").get().c;
|
|
18
57
|
const pending = db.prepare("SELECT COUNT(DISTINCT source_file) as c FROM chunks WHERE chunk_type = 'daily' AND source_file NOT IN (SELECT source_file FROM consolidated_files)").get().c;
|
|
19
|
-
|
|
20
|
-
//
|
|
58
|
+
core.push({ name: "Consolidation", status: failed > 0 ? "⚠️" : "✅", detail: `${consolidated} done, ${pending} pending, ${failed} failed` });
|
|
59
|
+
// 5. Last consolidation
|
|
21
60
|
const lastCon = db.prepare("SELECT value FROM meta WHERE key = 'last_consolidation'").get();
|
|
22
|
-
|
|
61
|
+
core.push({ name: "Last consolidation", status: "ℹ️", detail: lastCon?.value ?? "never" });
|
|
23
62
|
}
|
|
24
63
|
catch (err) {
|
|
25
|
-
|
|
64
|
+
core.push({ name: "SQLite DB", status: "❌", detail: `${err}` });
|
|
26
65
|
}
|
|
27
|
-
//
|
|
66
|
+
// ── Optional integrations ──────────────────────────────────────────────────
|
|
67
|
+
// Ollama — used by consolidate / kg-extract only
|
|
28
68
|
try {
|
|
29
69
|
const response = await fetch("http://127.0.0.1:11434/api/tags", { signal: AbortSignal.timeout(5000) });
|
|
30
70
|
if (response.ok) {
|
|
31
71
|
const data = (await response.json());
|
|
32
72
|
const models = data.models.map((m) => m.name).join(", ");
|
|
33
|
-
|
|
73
|
+
optional.push({ name: "Ollama", status: "✅", detail: `running, models: ${models}` });
|
|
34
74
|
}
|
|
35
75
|
else {
|
|
36
|
-
|
|
76
|
+
optional.push({ name: "Ollama", status: "⚠️", detail: `HTTP ${response.status}` });
|
|
37
77
|
}
|
|
38
78
|
}
|
|
39
79
|
catch {
|
|
40
|
-
|
|
80
|
+
optional.push({ name: "Ollama", status: "⚪", detail: "not running (optional — used by consolidate and kg-extract)" });
|
|
41
81
|
}
|
|
42
|
-
//
|
|
82
|
+
// Notion token
|
|
43
83
|
const notionTokenPath = process.env.NOX_NOTION_TOKEN_PATH ?? "/root/.config/notion/api_key";
|
|
44
84
|
const notionTokenExists = existsSync(notionTokenPath);
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
85
|
+
optional.push({
|
|
86
|
+
name: "Notion token",
|
|
87
|
+
status: notionTokenExists ? "✅" : "⚪",
|
|
88
|
+
detail: notionTokenExists ? `found at ${notionTokenPath}` : "not configured (optional — set NOX_NOTION_TOKEN_PATH to enable)",
|
|
89
|
+
});
|
|
90
|
+
// File watcher (systemd). No systemd, or unit not installed ⇒ optional/absent.
|
|
91
|
+
// Installed but not active ⇒ ⚠️, because someone meant to run it.
|
|
92
|
+
optional.push(await watcherCheck());
|
|
93
|
+
// An FTS/chunks mismatch is ⚠️ on screen (fixable with reindex) but it breaks
|
|
94
|
+
// search, so scripts relying on --quiet must see it as a failure.
|
|
95
|
+
const coreFailed = core.some((c) => c.status === "❌" || (c.name === "FTS5 Index" && c.status !== "✅"));
|
|
96
|
+
if (opts.quiet) {
|
|
97
|
+
for (const check of core.filter((c) => c.status === "❌" || c.status === "⚠️")) {
|
|
98
|
+
console.error(` ${check.status} ${check.name}: ${check.detail}`);
|
|
99
|
+
}
|
|
52
100
|
}
|
|
53
|
-
|
|
54
|
-
|
|
101
|
+
else {
|
|
102
|
+
console.log("\n🩺 nox-mem doctor\n");
|
|
103
|
+
console.log(" Core");
|
|
104
|
+
for (const check of core)
|
|
105
|
+
console.log(` ${check.status} ${check.name}: ${check.detail}`);
|
|
106
|
+
console.log("\n Optional integrations (⚪ = not set up, fine to skip)");
|
|
107
|
+
for (const check of optional)
|
|
108
|
+
console.log(` ${check.status} ${check.name}: ${check.detail}`);
|
|
109
|
+
console.log("");
|
|
110
|
+
}
|
|
111
|
+
if (coreFailed)
|
|
112
|
+
process.exitCode = 1;
|
|
113
|
+
}
|
|
114
|
+
async function watcherCheck() {
|
|
115
|
+
const { execFileSync } = await import("child_process");
|
|
116
|
+
const run = (args) => {
|
|
117
|
+
try {
|
|
118
|
+
return execFileSync("systemctl", args, { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] }).trim();
|
|
119
|
+
}
|
|
120
|
+
catch (err) {
|
|
121
|
+
// `systemctl is-active` exits non-zero for inactive units but still prints the state
|
|
122
|
+
const out = err.stdout;
|
|
123
|
+
return typeof out === "string" ? out.trim() : null;
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
if (run(["--version"]) === null) {
|
|
127
|
+
return { name: "File watcher", status: "⚪", detail: "no systemd (optional — run `nox-mem watch` in a terminal instead)" };
|
|
128
|
+
}
|
|
129
|
+
for (const unit of WATCHER_UNITS) {
|
|
130
|
+
const state = run(["is-active", unit]);
|
|
131
|
+
if (state === "active")
|
|
132
|
+
return { name: "File watcher", status: "✅", detail: `${unit} active` };
|
|
55
133
|
}
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
134
|
+
for (const unit of WATCHER_UNITS) {
|
|
135
|
+
const loaded = run(["show", "-p", "LoadState", "--value", unit]);
|
|
136
|
+
if (loaded === "loaded")
|
|
137
|
+
return { name: "File watcher", status: "⚠️", detail: `${unit} installed but not active` };
|
|
60
138
|
}
|
|
61
|
-
|
|
139
|
+
return { name: "File watcher", status: "⚪", detail: "not installed (optional — see nox-mem-watcher.service)" };
|
|
62
140
|
}
|
|
63
141
|
function formatSize(path) {
|
|
64
142
|
try {
|
package/dist/index.js
CHANGED
|
@@ -18,6 +18,7 @@ import { getNoiseStats, isNoise } from "./noise-filter.js";
|
|
|
18
18
|
import { distillSessions } from "./session-distill.js";
|
|
19
19
|
import { startWatch } from "./watch.js";
|
|
20
20
|
import { VERSION } from "./version.js";
|
|
21
|
+
import { parseTemporalFilter, TemporalParseError } from "./lib/dates.js";
|
|
21
22
|
const program = new Command();
|
|
22
23
|
program.name("nox-mem").description("Nox Supermem — search, consolidate, recover").version(VERSION);
|
|
23
24
|
program
|
|
@@ -25,16 +26,48 @@ program
|
|
|
25
26
|
.description("Search memory (FTS5 + boost + recency)")
|
|
26
27
|
.option("-n, --limit <n>", "Number of results", "5")
|
|
27
28
|
.option("--no-hybrid", "Disable semantic search (FTS5 only)")
|
|
29
|
+
.option("--as-of <date>", "Only chunks that existed at <date> (ISO 8601 or relative: 15m, 2h, 7d, 1w)")
|
|
30
|
+
.option("--changed-since <date>", "Only chunks created/updated after <date> (ISO 8601 or relative)")
|
|
28
31
|
.action(async (query, opts) => {
|
|
32
|
+
let filter;
|
|
33
|
+
try {
|
|
34
|
+
filter = parseTemporalFilter({ asOf: opts.asOf, changedSince: opts.changedSince });
|
|
35
|
+
}
|
|
36
|
+
catch (err) {
|
|
37
|
+
if (!(err instanceof TemporalParseError))
|
|
38
|
+
throw err;
|
|
39
|
+
console.error(`error: ${err.message}`);
|
|
40
|
+
process.exitCode = 2;
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
29
43
|
if (opts.hybrid) {
|
|
30
|
-
const results = await searchHybrid(query, parseInt(opts.limit, 10));
|
|
44
|
+
const results = await searchHybrid(query, parseInt(opts.limit, 10), true, filter);
|
|
31
45
|
console.log(formatResults(results));
|
|
32
46
|
}
|
|
33
47
|
else {
|
|
34
|
-
console.log(formatResults(search(query, parseInt(opts.limit, 10))));
|
|
48
|
+
console.log(formatResults(search(query, parseInt(opts.limit, 10), true, filter)));
|
|
35
49
|
}
|
|
36
50
|
closeDb();
|
|
37
51
|
});
|
|
52
|
+
// `answer` keeps its own argv parser (src/cli/answer.ts, P1 T8), so commander
|
|
53
|
+
// only routes to it and hands over the raw argv after the subcommand name.
|
|
54
|
+
program
|
|
55
|
+
.command("answer")
|
|
56
|
+
.description("Grounded answer with citations over memory (needs GEMINI_API_KEY; see `nox-mem answer --help`)")
|
|
57
|
+
.argument("[question...]")
|
|
58
|
+
.allowUnknownOption(true)
|
|
59
|
+
.helpOption(false)
|
|
60
|
+
.action(async () => {
|
|
61
|
+
const { runCli } = await import("./cli/answer.js");
|
|
62
|
+
const argv = process.argv.slice(process.argv.indexOf("answer") + 1);
|
|
63
|
+
const code = await runCli({
|
|
64
|
+
argv,
|
|
65
|
+
stdout: (line) => console.log(line),
|
|
66
|
+
stderr: (line) => console.error(line),
|
|
67
|
+
});
|
|
68
|
+
closeDb();
|
|
69
|
+
process.exitCode = code;
|
|
70
|
+
});
|
|
38
71
|
program
|
|
39
72
|
.command("vectorize")
|
|
40
73
|
.description("Build/update vector index for all chunks (semantic search)")
|
|
@@ -78,10 +111,26 @@ program
|
|
|
78
111
|
});
|
|
79
112
|
program
|
|
80
113
|
.command("reindex")
|
|
81
|
-
.description("Rebuild
|
|
82
|
-
.
|
|
83
|
-
|
|
84
|
-
|
|
114
|
+
.description("Rebuild the index from $OPENCLAW_WORKSPACE/memory and /shared (refuses if that source is missing)")
|
|
115
|
+
.option("--dry-run", "Print what would be reindexed as JSON; does not touch the DB")
|
|
116
|
+
.action(async (opts) => {
|
|
117
|
+
try {
|
|
118
|
+
const result = await reindex({ dryRun: opts.dryRun });
|
|
119
|
+
if (!opts.dryRun)
|
|
120
|
+
console.log(`[INFO] Reindexed ${result.files} files, ${result.chunks} chunks`);
|
|
121
|
+
}
|
|
122
|
+
catch (err) {
|
|
123
|
+
const name = err.name;
|
|
124
|
+
if (name === "ReindexSourceMissingError" || name === "ReindexWipeDetectedError") {
|
|
125
|
+
console.error(err.message);
|
|
126
|
+
process.exitCode = 1;
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
throw err;
|
|
130
|
+
}
|
|
131
|
+
finally {
|
|
132
|
+
closeDb();
|
|
133
|
+
}
|
|
85
134
|
});
|
|
86
135
|
program
|
|
87
136
|
.command("primer")
|
|
@@ -126,10 +175,11 @@ program
|
|
|
126
175
|
});
|
|
127
176
|
program
|
|
128
177
|
.command("doctor")
|
|
129
|
-
.description("Diagnostic check —
|
|
130
|
-
.
|
|
178
|
+
.description("Diagnostic check — core (SQLite, FTS5, embeddings) + optional integrations (Ollama, Notion, watcher)")
|
|
179
|
+
.option("--quiet", "Print only core problems; exit 1 if a core check fails")
|
|
180
|
+
.action(async (opts) => {
|
|
131
181
|
const { doctor } = await import("./doctor.js");
|
|
132
|
-
await doctor();
|
|
182
|
+
await doctor({ quiet: opts.quiet });
|
|
133
183
|
closeDb();
|
|
134
184
|
});
|
|
135
185
|
program
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/lib/dates.ts — flexible date parsing for the temporal search filter (P3).
|
|
3
|
+
*
|
|
4
|
+
* Accepted:
|
|
5
|
+
* ISO 8601 date: "2026-05-01" (start of day UTC; end of day for as-of)
|
|
6
|
+
* ISO 8601 full: "2026-05-01T12:00:00Z" (no offset ⇒ UTC)
|
|
7
|
+
* Relative: "15m" | "2h" | "7d" | "1w" (that long before `nowMs`)
|
|
8
|
+
*
|
|
9
|
+
* "1mo" is deliberately unsupported (months have no fixed length) — use "30d".
|
|
10
|
+
* Throws TemporalParseError on anything else, so surfaces can answer 400 / exit 2
|
|
11
|
+
* instead of silently searching without the filter.
|
|
12
|
+
*/
|
|
13
|
+
export class TemporalParseError extends Error {
|
|
14
|
+
constructor(message) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.name = "TemporalParseError";
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
const RELATIVE_RE = /^(\d+)(m|h|d|w)$/i;
|
|
20
|
+
const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
|
|
21
|
+
// Requires at least YYYY-MM-DDTHH:MM so bare numbers or "May 1" are rejected
|
|
22
|
+
// (Date.parse accepts both, with locale-dependent results).
|
|
23
|
+
const ISO_FULL_RE = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/;
|
|
24
|
+
const HAS_OFFSET_RE = /(Z|[+-]\d{2}:?\d{2})$/i;
|
|
25
|
+
const UNIT_MS = {
|
|
26
|
+
m: 60_000,
|
|
27
|
+
h: 3_600_000,
|
|
28
|
+
d: 86_400_000,
|
|
29
|
+
w: 604_800_000,
|
|
30
|
+
};
|
|
31
|
+
export function parseFlexibleDate(input, nowMs = Date.now(), opts = {}) {
|
|
32
|
+
const trimmed = String(input ?? "").trim();
|
|
33
|
+
if (!trimmed)
|
|
34
|
+
throw new TemporalParseError("temporal: empty date string");
|
|
35
|
+
const rel = RELATIVE_RE.exec(trimmed);
|
|
36
|
+
if (rel) {
|
|
37
|
+
const n = parseInt(rel[1], 10);
|
|
38
|
+
return new Date(nowMs - n * UNIT_MS[rel[2].toLowerCase()]);
|
|
39
|
+
}
|
|
40
|
+
let normalised = null;
|
|
41
|
+
if (DATE_ONLY_RE.test(trimmed)) {
|
|
42
|
+
// "as of 2026-01-10" reads as "by the end of that day"; "since 2026-01-10"
|
|
43
|
+
// as "from its start". Both in UTC.
|
|
44
|
+
normalised = opts.dateOnlyAs === "end" ? `${trimmed}T23:59:59.999Z` : `${trimmed}T00:00:00Z`;
|
|
45
|
+
}
|
|
46
|
+
else if (ISO_FULL_RE.test(trimmed)) {
|
|
47
|
+
// No offset ⇒ UTC, same as date-only (JS would otherwise read it as local time).
|
|
48
|
+
normalised = HAS_OFFSET_RE.test(trimmed) ? trimmed : `${trimmed}Z`;
|
|
49
|
+
}
|
|
50
|
+
const d = normalised ? new Date(normalised) : null;
|
|
51
|
+
if (!d || isNaN(d.getTime())) {
|
|
52
|
+
throw new TemporalParseError(`temporal: cannot parse date "${input}". ` +
|
|
53
|
+
`Accepted: ISO 8601 ("2026-05-01" or "2026-05-01T00:00:00Z") ` +
|
|
54
|
+
`or relative ("15m", "2h", "7d", "1w"). "1mo" is not supported — use "30d".`);
|
|
55
|
+
}
|
|
56
|
+
return d;
|
|
57
|
+
}
|
|
58
|
+
/** Parses the raw strings each surface receives; undefined/empty means "not set". */
|
|
59
|
+
export function parseTemporalFilter(raw, nowMs = Date.now()) {
|
|
60
|
+
const filter = {};
|
|
61
|
+
if (raw.asOf != null && String(raw.asOf).trim() !== "") {
|
|
62
|
+
filter.asOf = parseFlexibleDate(raw.asOf, nowMs, { dateOnlyAs: "end" });
|
|
63
|
+
}
|
|
64
|
+
if (raw.changedSince != null && String(raw.changedSince).trim() !== "") {
|
|
65
|
+
filter.changedSince = parseFlexibleDate(raw.changedSince, nowMs);
|
|
66
|
+
}
|
|
67
|
+
return filter.asOf || filter.changedSince ? filter : undefined;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* SQL fragment over the `chunks` alias `c` (semantics: docs/PRIMITIVES.md §3).
|
|
71
|
+
*
|
|
72
|
+
* asOf: created_at IS NULL (legacy rows count as "always existed")
|
|
73
|
+
* OR created_at <= asOf
|
|
74
|
+
* changedSince: updated_at > since OR created_at > since
|
|
75
|
+
*
|
|
76
|
+
* Both sides go through datetime(): the columns hold `datetime('now')` text
|
|
77
|
+
* ("YYYY-MM-DD HH:MM:SS") while the bound value is ISO ("...T...Z"), and a
|
|
78
|
+
* plain string comparison between the two formats is wrong (' ' < 'T').
|
|
79
|
+
* There is no soft-delete column in the schema, so no deleted_at leg.
|
|
80
|
+
*
|
|
81
|
+
* Returns null when the filter is empty so callers keep their exact SQL.
|
|
82
|
+
*/
|
|
83
|
+
export function buildTemporalClause(filter) {
|
|
84
|
+
if (!filter || (!filter.asOf && !filter.changedSince))
|
|
85
|
+
return null;
|
|
86
|
+
const parts = [];
|
|
87
|
+
const params = [];
|
|
88
|
+
if (filter.asOf) {
|
|
89
|
+
parts.push("(c.created_at IS NULL OR datetime(c.created_at) <= datetime(?))");
|
|
90
|
+
params.push(filter.asOf.toISOString());
|
|
91
|
+
}
|
|
92
|
+
if (filter.changedSince) {
|
|
93
|
+
const ts = filter.changedSince.toISOString();
|
|
94
|
+
parts.push("(datetime(c.updated_at) > datetime(?) OR datetime(c.created_at) > datetime(?))");
|
|
95
|
+
params.push(ts, ts);
|
|
96
|
+
}
|
|
97
|
+
return { sql: parts.join(" AND "), params };
|
|
98
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/lib/db-path.ts — the ONE place the database path is resolved.
|
|
3
|
+
*
|
|
4
|
+
* db.ts (which opens the DB) and op-audit.ts (which snapshots it before a
|
|
5
|
+
* destructive op) used to resolve the path separately. With no env set they
|
|
6
|
+
* disagreed: db.ts fell back to `<package>/nox-mem.db` while op-audit assumed
|
|
7
|
+
* `/root/.openclaw/workspace/tools/nox-mem/nox-mem.db` — the snapshot protected
|
|
8
|
+
* a different file than the op mutated (same class as incident 2026-05-25).
|
|
9
|
+
*
|
|
10
|
+
* Priority:
|
|
11
|
+
* 1. NOX_DB_PATH explicit override
|
|
12
|
+
* 2. $OPENCLAW_WORKSPACE/tools/nox-mem/nox-mem.db origin deployments
|
|
13
|
+
* 3. <package root>/nox-mem.db, ONLY IF IT EXISTS legacy: keeps every existing
|
|
14
|
+
* install (the VPS tree, 3.3.0 users) on the file it already uses
|
|
15
|
+
* 4. ~/.nox-mem/nox.db new standalone default
|
|
16
|
+
*
|
|
17
|
+
* Step 4 replaces the old unconditional step 3: for `npm install -g`, the package
|
|
18
|
+
* root is inside node_modules, and `npm update -g` replaces that directory —
|
|
19
|
+
* taking the database with it.
|
|
20
|
+
*/
|
|
21
|
+
import { existsSync } from "fs";
|
|
22
|
+
import { homedir } from "os";
|
|
23
|
+
import { dirname, join, resolve, sep } from "path";
|
|
24
|
+
import { fileURLToPath } from "url";
|
|
25
|
+
/** `<package root>` = parent of dist/ (compiled) or src/ (ts). */
|
|
26
|
+
const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
|
|
27
|
+
export const LEGACY_DB_PATH = resolve(PACKAGE_ROOT, "nox-mem.db");
|
|
28
|
+
export const DEFAULT_STANDALONE_DB_PATH = join(homedir(), ".nox-mem", "nox.db");
|
|
29
|
+
export function resolveDbPathWithSource(env = process.env, exists = existsSync) {
|
|
30
|
+
if (env.NOX_DB_PATH)
|
|
31
|
+
return { path: resolve(env.NOX_DB_PATH), source: "NOX_DB_PATH" };
|
|
32
|
+
if (env.OPENCLAW_WORKSPACE) {
|
|
33
|
+
return { path: resolve(env.OPENCLAW_WORKSPACE, "tools", "nox-mem", "nox-mem.db"), source: "OPENCLAW_WORKSPACE" };
|
|
34
|
+
}
|
|
35
|
+
if (exists(LEGACY_DB_PATH))
|
|
36
|
+
return { path: LEGACY_DB_PATH, source: "legacy-package" };
|
|
37
|
+
return { path: DEFAULT_STANDALONE_DB_PATH, source: "standalone-default" };
|
|
38
|
+
}
|
|
39
|
+
export function resolveDbPath() {
|
|
40
|
+
return resolveDbPathWithSource().path;
|
|
41
|
+
}
|
|
42
|
+
/** True when the path sits inside a node_modules tree (wiped by npm update/uninstall). */
|
|
43
|
+
export function isInsideNodeModules(p) {
|
|
44
|
+
return resolve(p).split(sep).includes("node_modules");
|
|
45
|
+
}
|
package/dist/lib/op-audit.js
CHANGED
|
@@ -47,7 +47,7 @@ import { existsSync, mkdirSync, renameSync, statSync, unlinkSync, chmodSync, rea
|
|
|
47
47
|
import { join, resolve, dirname } from 'node:path';
|
|
48
48
|
import { randomUUID } from 'node:crypto';
|
|
49
49
|
import Database from 'better-sqlite3';
|
|
50
|
-
import { getDb } from '../db.js';
|
|
50
|
+
import { getDb, DB_PATH as DB_OPENED_PATH } from '../db.js';
|
|
51
51
|
// Standalone decoupling (2026-06-15): ALLOWED_PREFIXES + snapshot dir are now CONFIGURABLE
|
|
52
52
|
// so a non-origin operator can run nox-mem outside /root/.openclaw without weakening the
|
|
53
53
|
// path-validation guard. Origin VPS behavior is preserved exactly: when none of the new
|
|
@@ -97,6 +97,12 @@ function computeAllowedPrefixes() {
|
|
|
97
97
|
if (ws && !resolve(ws).startsWith('/root/.openclaw')) {
|
|
98
98
|
prefixes.add(normalizePrefix(join(resolve(ws), 'tools', 'nox-mem')));
|
|
99
99
|
}
|
|
100
|
+
// No env at all: the DB is either the legacy <package>/nox-mem.db or the
|
|
101
|
+
// standalone default ~/.nox-mem/nox.db — neither is attacker-chosen, so allow
|
|
102
|
+
// its directory (same trust as dirname(NOX_DB_PATH) above).
|
|
103
|
+
if (!process.env.NOX_DB_PATH && !ws) {
|
|
104
|
+
prefixes.add(normalizePrefix(dirname(DB_OPENED_PATH)));
|
|
105
|
+
}
|
|
100
106
|
return Array.from(prefixes);
|
|
101
107
|
}
|
|
102
108
|
const ALLOWED_PREFIXES = computeAllowedPrefixes();
|
|
@@ -112,11 +118,9 @@ function computeDefaultSnapshotDir() {
|
|
|
112
118
|
}
|
|
113
119
|
// Standalone: prefer NOX_MEM_DIR, else the active DB's own directory (always allowlisted —
|
|
114
120
|
// it's dirname(NOX_DB_PATH) or the OPENCLAW_WORKSPACE-derived nox-mem dir), else cwd.
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
? dirname(dbPath)
|
|
119
|
-
: resolve(process.cwd());
|
|
121
|
+
// (cwd is no longer a fallback: the DB dir is always known and allowlisted, and
|
|
122
|
+
// a snapshot scattered into whatever directory the command ran from is lost.)
|
|
123
|
+
const base = process.env.NOX_MEM_DIR ? resolve(process.env.NOX_MEM_DIR) : dirname(dbPath);
|
|
120
124
|
return join(base, '.nox-snapshots');
|
|
121
125
|
}
|
|
122
126
|
// P2 fix (2026-05-27, task #21) — DB_PATH agora respeita OPENCLAW_WORKSPACE como db.ts faz.
|
|
@@ -131,13 +135,16 @@ function computeDefaultSnapshotDir() {
|
|
|
131
135
|
// 1. NOX_DB_PATH (explicit override — eval/test isolation)
|
|
132
136
|
// 2. OPENCLAW_WORKSPACE-derived path (production agent workspaces)
|
|
133
137
|
// 3. Hardcoded main DB (default last resort)
|
|
138
|
+
//
|
|
139
|
+
// 2026-09-28: resolution now lives in lib/db-path.ts and is shared with db.ts.
|
|
140
|
+
// The old step 3 here was the hardcoded main DB while db.ts fell back to
|
|
141
|
+
// <package>/nox-mem.db — with no env set the snapshot covered a different file
|
|
142
|
+
// than the op mutated. On the origin tree both paths are the same file, so the
|
|
143
|
+
// VPS resolves exactly as before.
|
|
134
144
|
function resolveDbPath() {
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
if (ws)
|
|
139
|
-
return resolve(ws, 'tools', 'nox-mem', 'nox-mem.db');
|
|
140
|
-
return '/root/.openclaw/workspace/tools/nox-mem/nox-mem.db';
|
|
145
|
+
// The very value db.ts resolved and opens — not a second resolution, so a
|
|
146
|
+
// legacy file created/removed in between cannot split them (TOCTOU).
|
|
147
|
+
return DB_OPENED_PATH;
|
|
141
148
|
}
|
|
142
149
|
const DB_PATH = resolveDbPath();
|
|
143
150
|
// W2-2 (audit cleanup 04-26): validate DB_PATH at module load — symetric trust w/ snapshot dir.
|
package/dist/lib/reranker.js
CHANGED
|
@@ -92,7 +92,10 @@ async function getRerankerFn() {
|
|
|
92
92
|
throw cachedFactoryError;
|
|
93
93
|
try {
|
|
94
94
|
// Dynamic import: Node ESM, evita carga em paths off-mode.
|
|
95
|
-
|
|
95
|
+
// Specifier held in a variable so tsc does not require the optional
|
|
96
|
+
// dependency at build time; a clone without it still type-checks.
|
|
97
|
+
const xenovaSpecifier = "@xenova/transformers";
|
|
98
|
+
const t = await import(xenovaSpecifier);
|
|
96
99
|
// BGE-reranker-base é cross-encoder. xenova text-classification pipeline NÃO
|
|
97
100
|
// suporta text_pair (passa pares como string única → tokenizer ignora pair).
|
|
98
101
|
// Usar API low-level: AutoTokenizer + AutoModelForSequenceClassification com
|
package/dist/mcp-server.js
CHANGED
|
@@ -14,6 +14,7 @@ import { getStats } from "./stats.js";
|
|
|
14
14
|
import { primer } from "./primer.js";
|
|
15
15
|
import { createInterface } from "readline";
|
|
16
16
|
import { VERSION } from "./version.js";
|
|
17
|
+
import { parseTemporalFilter } from "./lib/dates.js";
|
|
17
18
|
const SERVER_INFO = {
|
|
18
19
|
name: "nox-mem",
|
|
19
20
|
version: VERSION,
|
|
@@ -27,6 +28,8 @@ const TOOLS = [
|
|
|
27
28
|
properties: {
|
|
28
29
|
query: { type: "string", description: "Search query (natural language or keywords)" },
|
|
29
30
|
limit: { type: "number", description: "Max results (default 5, max 20)", default: 5 },
|
|
31
|
+
as_of: { type: "string", description: "Time-travel: only chunks that existed at this date (ISO 8601 like 2026-05-01, or relative like 7d, 2h, 1w)" },
|
|
32
|
+
changed_since: { type: "string", description: "Recency window: only chunks created or updated after this date (ISO 8601 or relative)" },
|
|
30
33
|
},
|
|
31
34
|
required: ["query"],
|
|
32
35
|
},
|
|
@@ -230,7 +233,12 @@ async function handleRequest(req) {
|
|
|
230
233
|
case "nox_mem_search": {
|
|
231
234
|
const query = args.query;
|
|
232
235
|
const limit = Math.min(Number(args.limit) || 5, 20);
|
|
233
|
-
|
|
236
|
+
// Parse errors throw and reach the client as isError — never an unfiltered search.
|
|
237
|
+
const filter = parseTemporalFilter({
|
|
238
|
+
asOf: args.as_of,
|
|
239
|
+
changedSince: args.changed_since,
|
|
240
|
+
});
|
|
241
|
+
const results = await searchHybrid(query, limit, true, filter);
|
|
234
242
|
text = formatResults(results);
|
|
235
243
|
break;
|
|
236
244
|
}
|
package/dist/reindex-errors.js
CHANGED
|
@@ -19,3 +19,29 @@ export class ReindexWipeDetectedError extends Error {
|
|
|
19
19
|
this.ratio = ratio;
|
|
20
20
|
}
|
|
21
21
|
}
|
|
22
|
+
/**
|
|
23
|
+
* Thrown BEFORE any mutation when the rebuild source cannot be what the caller
|
|
24
|
+
* thinks it is: no source directory exists, or the scan found no file while
|
|
25
|
+
* the DB holds chunks. Without this, a reindex on a machine without
|
|
26
|
+
* $OPENCLAW_WORKSPACE scanned nothing and then deleted every chunk as "orphan";
|
|
27
|
+
* the ratio guard only fired after the DELETE (2026-09-28).
|
|
28
|
+
*/
|
|
29
|
+
export class ReindexSourceMissingError extends Error {
|
|
30
|
+
roots;
|
|
31
|
+
preCount;
|
|
32
|
+
reason;
|
|
33
|
+
constructor(roots, preCount, reason) {
|
|
34
|
+
super(`[reindex] REFUSED before touching the DB: ` +
|
|
35
|
+
(reason === "no-files"
|
|
36
|
+
? `found 0 files under ${roots.join(", ")} while the DB holds ${preCount} chunks. `
|
|
37
|
+
: `no source directory exists (looked for ${roots.join(", ")}) while the DB holds ${preCount} chunks. `) +
|
|
38
|
+
`reindex rebuilds ONLY from $OPENCLAW_WORKSPACE/memory and $OPENCLAW_WORKSPACE/shared ` +
|
|
39
|
+
`(OPENCLAW_WORKSPACE=${process.env.OPENCLAW_WORKSPACE ?? "<unset>"}); running it now would delete every chunk. ` +
|
|
40
|
+
`Standalone installs that add notes with \`nox-mem ingest <file>\` do not need reindex. ` +
|
|
41
|
+
`Set NOX_REINDEX_ALLOW_WIPE=1 ONLY if emptying the DB is intended.`);
|
|
42
|
+
this.name = "ReindexSourceMissingError";
|
|
43
|
+
this.roots = roots;
|
|
44
|
+
this.preCount = preCount;
|
|
45
|
+
this.reason = reason;
|
|
46
|
+
}
|
|
47
|
+
}
|