nox-mem 3.3.0 → 3.5.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 +82 -31
- package/dist/api/answer.js +22 -0
- package/dist/api-server.js +22 -3
- package/dist/cli/answer.js +39 -1
- package/dist/db.js +47 -24
- package/dist/doctor.js +108 -29
- package/dist/embed.js +53 -3
- package/dist/index.js +73 -17
- package/dist/lib/answer/index.js +3 -2
- package/dist/lib/answer/retrieval.js +6 -4
- package/dist/lib/answer/temporal.js +51 -0
- package/dist/lib/api-port.js +16 -0
- package/dist/lib/dates.js +98 -0
- package/dist/lib/db-path.js +57 -0
- package/dist/lib/ingest-many.js +49 -0
- package/dist/lib/op-audit.js +19 -12
- package/dist/lib/reranker.js +4 -1
- package/dist/mcp/tools/answer.js +23 -0
- package/dist/mcp-server.js +45 -6
- package/dist/reflect.js +2 -2
- package/dist/reindex-errors.js +45 -0
- package/dist/reindex.js +116 -23
- package/dist/search.js +111 -16
- package/package.json +7 -2
- package/prompts/consolidate.txt +13 -0
- package/prompts/digest.txt +5 -0
- package/dist/__tests__/brief-diversity.test.js +0 -266
- package/dist/__tests__/brief.test.js +0 -287
- package/dist/__tests__/churn.test.js +0 -66
- package/dist/__tests__/edge-typing.test.js +0 -99
- package/dist/__tests__/ingest-event.test.js +0 -151
- package/dist/__tests__/op-audit-e2e.test.js +0 -130
- package/dist/__tests__/pragma-alignment.test.js +0 -123
- package/dist/__tests__/reranker.test.js +0 -326
- package/dist/__tests__/retention.test.js +0 -99
- package/dist/__tests__/search-track-access.test.js +0 -49
- package/dist/__tests__/session-distill-sources.test.js +0 -98
- package/dist/__tests__/spo-injection.test.js +0 -172
- package/dist/__tests__/telemetry-per-chunk.test.js +0 -110
- package/dist/__tests__/temporal-detector.test.js +0 -103
- package/dist/lib/answer/__tests__/e2e-gemini.test.js +0 -229
- package/dist/lib/answer/__tests__/integration-sqlite.test.js +0 -388
- package/dist/lib/answer/__tests__/integration.test.js +0 -347
- package/dist/lib/answer/__tests__/prompt.test.js +0 -117
- package/dist/lib/answer/__tests__/t5-t10.test.js +0 -501
- package/dist/lib/api/__tests__/safe-error-message.test.js +0 -155
- package/dist/lib/auth/__tests__/localhost-guard.test.js +0 -144
- package/dist/lib/error-sanitizer/__tests__/sanitize.test.js +0 -354
- package/dist/lib/events/__tests__/bus.test.js +0 -208
- package/dist/lib/op-audit-extension/__tests__/ran-at-guard.test.js +0 -109
- package/dist/lib/regex-extract/__tests__/extractor.test.js +0 -197
- package/dist/lib/regex-extract/__tests__/frontmatter.test.js +0 -75
- package/dist/lib/regex-extract/__tests__/ingest-router-l4.test.js +0 -139
- package/dist/lib/regex-extract/__tests__/production-wire.test.js +0 -177
- package/dist/lib/regex-extract/__tests__/reconcile.test.js +0 -170
- package/dist/lib/regex-extract/__tests__/strip-code.test.js +0 -36
- package/dist/privacy/__tests__/filter.test.js +0 -352
- package/dist/providers/__tests__/conformance-extended.test.js +0 -249
- package/dist/providers/__tests__/conformance.test.js +0 -98
- package/dist/providers/__tests__/cost-cap.test.js +0 -151
- package/dist/providers/__tests__/e2e-real.test.js +0 -79
- package/dist/providers/__tests__/factory.test.js +0 -80
- package/dist/providers/__tests__/fallback.test.js +0 -223
- package/dist/providers/__tests__/gemini.test.js +0 -191
- package/dist/providers/__tests__/health.test.js +0 -128
- package/dist/providers/__tests__/telemetry.test.js +0 -219
|
@@ -0,0 +1,57 @@
|
|
|
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, mkdirSync } 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
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* mkdir -p the directory that will hold the database, mode 0700 (the DB holds
|
|
48
|
+
* the user's notes). No-op when it already exists, so an existing directory's
|
|
49
|
+
* permissions are never changed. Returns true when it created anything.
|
|
50
|
+
*/
|
|
51
|
+
export function ensureDbParentDir(dbPath) {
|
|
52
|
+
const dir = dirname(resolve(dbPath));
|
|
53
|
+
if (existsSync(dir))
|
|
54
|
+
return false;
|
|
55
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
56
|
+
return true;
|
|
57
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ingest-many.ts — `nox-mem ingest <files...>`: ingest every path given.
|
|
3
|
+
*
|
|
4
|
+
* The command used to take a single `<file>`, so `nox-mem ingest notes/*.md`
|
|
5
|
+
* indexed the first match and silently dropped the rest. Now each path is
|
|
6
|
+
* ingested in order; a path that cannot be ingested (a directory, a missing
|
|
7
|
+
* file, a parse error) is reported by name and does NOT stop the others. The
|
|
8
|
+
* caller exits non-zero if any path failed.
|
|
9
|
+
*/
|
|
10
|
+
import { statSync } from "node:fs";
|
|
11
|
+
/** Why a path is not ingestable before we even try, or null when it looks fine. */
|
|
12
|
+
function preflight(path) {
|
|
13
|
+
let st;
|
|
14
|
+
try {
|
|
15
|
+
st = statSync(path);
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return "no such file";
|
|
19
|
+
}
|
|
20
|
+
if (st.isDirectory()) {
|
|
21
|
+
return "is a directory, not a file (pass files, e.g. nox-mem ingest dir/*.md)";
|
|
22
|
+
}
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
export async function ingestMany(paths, deps) {
|
|
26
|
+
let ok = 0;
|
|
27
|
+
let failed = 0;
|
|
28
|
+
for (const path of paths) {
|
|
29
|
+
const problem = preflight(path);
|
|
30
|
+
if (problem) {
|
|
31
|
+
deps.error(`[ERROR] ${path}: ${problem}`);
|
|
32
|
+
failed++;
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
try {
|
|
36
|
+
const r = await deps.ingestOne(path);
|
|
37
|
+
deps.log(`[INFO] Ingested ${path}: ${r.chunks} chunks (kind=${r.kind}, via=${r.routedTo})`);
|
|
38
|
+
ok++;
|
|
39
|
+
}
|
|
40
|
+
catch (err) {
|
|
41
|
+
deps.error(`[ERROR] ${path}: ${err instanceof Error ? err.message : String(err)}`);
|
|
42
|
+
failed++;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (paths.length > 1 || failed > 0) {
|
|
46
|
+
deps.log(`[INFO] ingest: ${ok} ingested, ${failed} failed (of ${paths.length})`);
|
|
47
|
+
}
|
|
48
|
+
return { ok, failed };
|
|
49
|
+
}
|
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/tools/answer.js
CHANGED
|
@@ -22,6 +22,8 @@
|
|
|
22
22
|
*/
|
|
23
23
|
import { answer as defaultAnswer, AnswerError } from "../../lib/answer/index.js";
|
|
24
24
|
import { recordAnswer, } from "../../lib/answer/telemetry.js";
|
|
25
|
+
import { resolveTemporalFilter } from "../../lib/answer/temporal.js";
|
|
26
|
+
import { TemporalParseError } from "../../lib/dates.js";
|
|
25
27
|
// ─── Input schema ─────────────────────────────────────────────────────────
|
|
26
28
|
export const INPUT_SCHEMA = {
|
|
27
29
|
type: "object",
|
|
@@ -33,6 +35,14 @@ export const INPUT_SCHEMA = {
|
|
|
33
35
|
model: { type: "string" },
|
|
34
36
|
temperature: { type: "number", minimum: 0, maximum: 1 },
|
|
35
37
|
no_citations: { type: "boolean", default: false },
|
|
38
|
+
as_of: {
|
|
39
|
+
type: "string",
|
|
40
|
+
description: "Time-travel: only chunks that existed at this date (ISO 8601 like 2026-05-01, or relative like 7d, 2h, 1w)",
|
|
41
|
+
},
|
|
42
|
+
changed_since: {
|
|
43
|
+
type: "string",
|
|
44
|
+
description: "Recency window: only chunks created or updated after this date (ISO 8601 or relative)",
|
|
45
|
+
},
|
|
36
46
|
},
|
|
37
47
|
required: ["question"],
|
|
38
48
|
additionalProperties: false,
|
|
@@ -90,6 +100,17 @@ export function parseInput(input) {
|
|
|
90
100
|
}
|
|
91
101
|
parsed.noCitations = o.no_citations;
|
|
92
102
|
}
|
|
103
|
+
// An unparseable date is invalid_input (isError), never a silently unfiltered answer.
|
|
104
|
+
try {
|
|
105
|
+
const temporal = resolveTemporalFilter({ asOf: o.as_of, changedSince: o.changed_since });
|
|
106
|
+
if (temporal !== undefined)
|
|
107
|
+
parsed.temporal = temporal;
|
|
108
|
+
}
|
|
109
|
+
catch (err) {
|
|
110
|
+
if (err instanceof TemporalParseError)
|
|
111
|
+
throw new McpInputError(err.message);
|
|
112
|
+
throw err;
|
|
113
|
+
}
|
|
93
114
|
return parsed;
|
|
94
115
|
}
|
|
95
116
|
// ─── Handler factory ──────────────────────────────────────────────────────
|
|
@@ -131,6 +152,8 @@ export const noxMemAnswerTool = {
|
|
|
131
152
|
opts.model = parsed.model;
|
|
132
153
|
if (parsed.temperature !== undefined)
|
|
133
154
|
opts.temperature = parsed.temperature;
|
|
155
|
+
if (parsed.temporal !== undefined)
|
|
156
|
+
opts.temporal = parsed.temporal;
|
|
134
157
|
const run = ctx?.answer ?? defaultAnswer;
|
|
135
158
|
try {
|
|
136
159
|
const res = await run(opts);
|
package/dist/mcp-server.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
/**
|
|
3
3
|
* nox-mem MCP Server — exposes memory tools via Model Context Protocol (stdio)
|
|
4
|
-
* Tools: search, stats, primer, ingest
|
|
4
|
+
* Tools: search, stats, primer, ingest, answer, ... (see TOOLS below)
|
|
5
5
|
*/
|
|
6
6
|
import { closeDb } from "./db.js";
|
|
7
7
|
import { searchHybrid, formatResults } from "./search.js";
|
|
@@ -14,6 +14,8 @@ 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";
|
|
18
|
+
import { noxMemAnswerTool } from "./mcp/tools/answer.js";
|
|
17
19
|
const SERVER_INFO = {
|
|
18
20
|
name: "nox-mem",
|
|
19
21
|
version: VERSION,
|
|
@@ -27,6 +29,8 @@ const TOOLS = [
|
|
|
27
29
|
properties: {
|
|
28
30
|
query: { type: "string", description: "Search query (natural language or keywords)" },
|
|
29
31
|
limit: { type: "number", description: "Max results (default 5, max 20)", default: 5 },
|
|
32
|
+
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)" },
|
|
33
|
+
changed_since: { type: "string", description: "Recency window: only chunks created or updated after this date (ISO 8601 or relative)" },
|
|
30
34
|
},
|
|
31
35
|
required: ["query"],
|
|
32
36
|
},
|
|
@@ -196,7 +200,14 @@ const TOOLS = [
|
|
|
196
200
|
},
|
|
197
201
|
required: ["title", "steps"],
|
|
198
202
|
},
|
|
199
|
-
}
|
|
203
|
+
},
|
|
204
|
+
// `nox_mem_answer`: definition + handler live in src/mcp/tools/answer.ts (single code
|
|
205
|
+
// path shared with the CLI and POST /api/answer via lib/answer). Only registered here.
|
|
206
|
+
{
|
|
207
|
+
name: noxMemAnswerTool.name,
|
|
208
|
+
description: noxMemAnswerTool.description,
|
|
209
|
+
inputSchema: noxMemAnswerTool.inputSchema,
|
|
210
|
+
},
|
|
200
211
|
];
|
|
201
212
|
function sendResponse(id, result) {
|
|
202
213
|
const msg = JSON.stringify({ jsonrpc: "2.0", id, result });
|
|
@@ -224,13 +235,32 @@ async function handleRequest(req) {
|
|
|
224
235
|
case "tools/call": {
|
|
225
236
|
const toolName = params?.name;
|
|
226
237
|
const args = (params?.arguments ?? {});
|
|
238
|
+
// The answer tool returns a ready CallToolResult ({content, isError?}): invalid input,
|
|
239
|
+
// a missing GEMINI_API_KEY (llm_error) and every AnswerError come back as isError.
|
|
240
|
+
if (toolName === noxMemAnswerTool.name) {
|
|
241
|
+
try {
|
|
242
|
+
sendResponse(id, await noxMemAnswerTool.handler(args));
|
|
243
|
+
}
|
|
244
|
+
catch (err) {
|
|
245
|
+
sendResponse(id, {
|
|
246
|
+
content: [{ type: "text", text: "Error: " + err.message }],
|
|
247
|
+
isError: true,
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
break;
|
|
251
|
+
}
|
|
227
252
|
try {
|
|
228
253
|
let text;
|
|
229
254
|
switch (toolName) {
|
|
230
255
|
case "nox_mem_search": {
|
|
231
256
|
const query = args.query;
|
|
232
257
|
const limit = Math.min(Number(args.limit) || 5, 20);
|
|
233
|
-
|
|
258
|
+
// Parse errors throw and reach the client as isError — never an unfiltered search.
|
|
259
|
+
const filter = parseTemporalFilter({
|
|
260
|
+
asOf: args.as_of,
|
|
261
|
+
changedSince: args.changed_since,
|
|
262
|
+
});
|
|
263
|
+
const results = await searchHybrid(query, limit, true, filter);
|
|
234
264
|
text = formatResults(results);
|
|
235
265
|
break;
|
|
236
266
|
}
|
|
@@ -377,16 +407,25 @@ async function handleRequest(req) {
|
|
|
377
407
|
}
|
|
378
408
|
}
|
|
379
409
|
const rl = createInterface({ input: process.stdin });
|
|
410
|
+
// In-flight requests. stdin closing (e.g. `printf '...' | nox-mem-mcp`) must not
|
|
411
|
+
// cut off async tools (answer, search, reflect) before they respond.
|
|
412
|
+
const pending = new Set();
|
|
380
413
|
rl.on("line", (line) => {
|
|
414
|
+
let req;
|
|
381
415
|
try {
|
|
382
|
-
|
|
383
|
-
handleRequest(req);
|
|
416
|
+
req = JSON.parse(line);
|
|
384
417
|
}
|
|
385
418
|
catch {
|
|
386
419
|
sendError(null, -32700, "Parse error");
|
|
420
|
+
return;
|
|
387
421
|
}
|
|
422
|
+
const p = handleRequest(req)
|
|
423
|
+
.catch((err) => sendError(req?.id ?? null, -32603, err.message))
|
|
424
|
+
.finally(() => pending.delete(p));
|
|
425
|
+
pending.add(p);
|
|
388
426
|
});
|
|
389
|
-
rl.on("close", () => {
|
|
427
|
+
rl.on("close", async () => {
|
|
428
|
+
await Promise.allSettled([...pending]);
|
|
390
429
|
closeDb();
|
|
391
430
|
process.exit(0);
|
|
392
431
|
});
|
package/dist/reflect.js
CHANGED
|
@@ -9,7 +9,7 @@ import { getDb } from "./db.js";
|
|
|
9
9
|
import { search, searchHybrid } from "./search.js";
|
|
10
10
|
import { queryEntity, listDecisions } from "./knowledge-graph.js";
|
|
11
11
|
import { findPath } from "./cross-agent-v2.js";
|
|
12
|
-
import { embedText } from "./embed.js";
|
|
12
|
+
import { embedText, queryEmbedTimeoutMs } from "./embed.js";
|
|
13
13
|
import { selectLLMProviderWithFallback, MissingKeyError } from "./providers/index.js";
|
|
14
14
|
const MAX_EVIDENCE_CHARS = 2000;
|
|
15
15
|
const CACHE_TTL_HOURS = 24;
|
|
@@ -219,7 +219,7 @@ export async function reflect(question, options = {}) {
|
|
|
219
219
|
const haveEmbeds = db.prepare("SELECT COUNT(*) AS c FROM reflect_cache WHERE query_embedding IS NOT NULL AND datetime(created_at, '+' || ttl_hours || ' hours') > datetime('now')").get().c;
|
|
220
220
|
if (haveEmbeds > 0)
|
|
221
221
|
try {
|
|
222
|
-
const queryEmbed = await embedText(question);
|
|
222
|
+
const queryEmbed = await embedText(question, { timeoutMs: queryEmbedTimeoutMs() });
|
|
223
223
|
// LIMIT 500 ORDER BY most recent — bounds scan; semantic_hit_count desc keeps hot entries
|
|
224
224
|
const candidates = db.prepare(`SELECT query_hash, query, response, evidence_sources, query_embedding
|
|
225
225
|
FROM reflect_cache
|
package/dist/reindex-errors.js
CHANGED
|
@@ -19,3 +19,48 @@ 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
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Thrown BEFORE any mutation when the DB being rebuilt is not the DB of the
|
|
50
|
+
* workspace being scanned. With NOX_DB_PATH set and OPENCLAW_WORKSPACE unset,
|
|
51
|
+
* reindex scanned the default /root/.openclaw/workspace and treated every
|
|
52
|
+
* chunk of the NOX_DB_PATH database that did not come from there as an orphan.
|
|
53
|
+
* (With both set and disagreeing, op-audit already aborts — incident 2026-05-25.)
|
|
54
|
+
*/
|
|
55
|
+
export class ReindexWorkspaceMismatchError extends Error {
|
|
56
|
+
dbPath;
|
|
57
|
+
workspaceDbPath;
|
|
58
|
+
constructor(dbPath, workspaceDbPath) {
|
|
59
|
+
super(`[reindex] REFUSED before touching the DB: NOX_DB_PATH=${dbPath} is not the database of the workspace ` +
|
|
60
|
+
`reindex would scan (OPENCLAW_WORKSPACE unset ⇒ default workspace, whose DB is ${workspaceDbPath}). ` +
|
|
61
|
+
`Set OPENCLAW_WORKSPACE to the workspace that owns this DB, or unset NOX_DB_PATH.`);
|
|
62
|
+
this.name = "ReindexWorkspaceMismatchError";
|
|
63
|
+
this.dbPath = dbPath;
|
|
64
|
+
this.workspaceDbPath = workspaceDbPath;
|
|
65
|
+
}
|
|
66
|
+
}
|
package/dist/reindex.js
CHANGED
|
@@ -36,11 +36,11 @@
|
|
|
36
36
|
import { getDb } from "./db.js";
|
|
37
37
|
import { withOpAudit } from "./lib/op-audit.js";
|
|
38
38
|
import { routeIngest } from "./lib/ingest-router.js";
|
|
39
|
-
import { readdirSync } from "fs";
|
|
39
|
+
import { existsSync, readdirSync } from "fs";
|
|
40
40
|
import { createHash } from "crypto";
|
|
41
41
|
import { join, resolve } from "path";
|
|
42
|
-
import { ReindexWipeDetectedError, MIN_RETENTION_RATIO } from "./reindex-errors.js";
|
|
43
|
-
export { ReindexWipeDetectedError } from "./reindex-errors.js";
|
|
42
|
+
import { ReindexWipeDetectedError, ReindexSourceMissingError, ReindexWorkspaceMismatchError, MIN_RETENTION_RATIO } from "./reindex-errors.js";
|
|
43
|
+
export { ReindexWipeDetectedError, ReindexSourceMissingError, ReindexWorkspaceMismatchError } from "./reindex-errors.js";
|
|
44
44
|
const WORKSPACE = process.env.OPENCLAW_WORKSPACE || "/root/.openclaw/workspace";
|
|
45
45
|
// Layer 4: tunable safety thresholds (env-overridable for emergency operations).
|
|
46
46
|
// MIN_RETENTION_RATIO imported from reindex-errors.ts (single source of truth).
|
|
@@ -64,6 +64,47 @@ function findFiles(dir, extensions) {
|
|
|
64
64
|
}
|
|
65
65
|
return results;
|
|
66
66
|
}
|
|
67
|
+
/** The directories reindex rebuilds from, in scan order. */
|
|
68
|
+
export function reindexRoots() {
|
|
69
|
+
return [resolve(WORKSPACE, "memory"), resolve(WORKSPACE, "shared")];
|
|
70
|
+
}
|
|
71
|
+
function collectReindexFiles() {
|
|
72
|
+
const [memoryRoot, sharedRoot] = reindexRoots();
|
|
73
|
+
return {
|
|
74
|
+
memoryFiles: findFiles(memoryRoot, [".md", ".json"]),
|
|
75
|
+
sharedFiles: findFiles(sharedRoot, [".md"]),
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Refuses (throws) when reindex has nothing trustworthy to rebuild from.
|
|
80
|
+
* Only fires in wipe conditions — a deployment whose workspace holds files
|
|
81
|
+
* passes untouched. Overridable with NOX_REINDEX_ALLOW_WIPE=1.
|
|
82
|
+
*/
|
|
83
|
+
export function assertReindexSource(preCount) {
|
|
84
|
+
// The DB must belong to the workspace being scanned. Only reachable with
|
|
85
|
+
// NOX_DB_PATH set and OPENCLAW_WORKSPACE unset (both set and disagreeing is
|
|
86
|
+
// already refused by op-audit). NOX_DB_PATH pointing at the default
|
|
87
|
+
// workspace's own DB — how origin crons call it — passes.
|
|
88
|
+
if (process.env.NOX_DB_PATH && !process.env.OPENCLAW_WORKSPACE) {
|
|
89
|
+
const dbPath = resolve(process.env.NOX_DB_PATH);
|
|
90
|
+
const workspaceDbPath = resolve(WORKSPACE, "tools", "nox-mem", "nox-mem.db");
|
|
91
|
+
if (dbPath !== workspaceDbPath)
|
|
92
|
+
throw new ReindexWorkspaceMismatchError(dbPath, workspaceDbPath);
|
|
93
|
+
}
|
|
94
|
+
if (ALLOW_WIPE)
|
|
95
|
+
return;
|
|
96
|
+
const roots = reindexRoots();
|
|
97
|
+
const existing = roots.filter((r) => existsSync(r));
|
|
98
|
+
if (existing.length === 0) {
|
|
99
|
+
if (preCount > 0)
|
|
100
|
+
throw new ReindexSourceMissingError(roots, preCount, "no-source-dir");
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
const { memoryFiles, sharedFiles } = collectReindexFiles();
|
|
104
|
+
const found = memoryFiles.length + sharedFiles.length;
|
|
105
|
+
if (found === 0 && preCount > 0)
|
|
106
|
+
throw new ReindexSourceMissingError(existing, preCount, "no-files");
|
|
107
|
+
}
|
|
67
108
|
// Content-addressed fingerprint for UPSERT identity.
|
|
68
109
|
// (source_file, sha256(chunk_text)) is stable across reindex runs as long as the
|
|
69
110
|
// chunker output is deterministic for the same input file. The schema's autoincrement
|
|
@@ -103,6 +144,11 @@ async function _reindexImpl() {
|
|
|
103
144
|
}
|
|
104
145
|
// ── Phase 1: snapshot pre-state ────────────────────────────────────────────
|
|
105
146
|
const preCount = db.prepare("SELECT COUNT(*) AS c FROM chunks").get().c;
|
|
147
|
+
// ── Phase 0 guard (read-only so far): the rebuild source must exist ────────
|
|
148
|
+
// Measured 2026-09-28 on a clean npm install: no $OPENCLAW_WORKSPACE ⇒ the scan
|
|
149
|
+
// found 0 files ⇒ every chunk became an "orphan" and was deleted; the ratio
|
|
150
|
+
// guard below then threw — after the DELETE. Refuse here, before any write.
|
|
151
|
+
assertReindexSource(preCount);
|
|
106
152
|
// Tolerant select: schema may lack some columns on older DBs (pre-v10).
|
|
107
153
|
// `SELECT *` would force coupling; instead probe column existence.
|
|
108
154
|
const cols = new Set(db.prepare("PRAGMA table_info(chunks)").all().map((r) => r.name));
|
|
@@ -124,10 +170,35 @@ async function _reindexImpl() {
|
|
|
124
170
|
].join(", ");
|
|
125
171
|
const oldChunks = db.prepare(`SELECT ${selectCols} FROM chunks`).all();
|
|
126
172
|
// Build content fingerprint -> oldChunk index.
|
|
173
|
+
// One representative per content fingerprint. When the DB already holds
|
|
174
|
+
// duplicates (every reindex before 2026-09-28 doubled unchanged content), the
|
|
175
|
+
// kept representative is the one WITH an embedding, then the lowest id — the
|
|
176
|
+
// other copies become orphans and are removed, and dropping one without a
|
|
177
|
+
// vector must never cost the one that has it.
|
|
178
|
+
let embeddedIds = new Set();
|
|
179
|
+
try {
|
|
180
|
+
embeddedIds = new Set(db.prepare("SELECT chunk_id FROM vec_chunk_map").all().map((r) => r.chunk_id));
|
|
181
|
+
}
|
|
182
|
+
catch {
|
|
183
|
+
/* no vector map yet (fresh / keyless install) — every row is equal */
|
|
184
|
+
}
|
|
185
|
+
const better = (a, b) => {
|
|
186
|
+
const ae = embeddedIds.has(a.id), be = embeddedIds.has(b.id);
|
|
187
|
+
if (ae !== be)
|
|
188
|
+
return ae ? a : b;
|
|
189
|
+
return a.id <= b.id ? a : b;
|
|
190
|
+
};
|
|
127
191
|
const oldByFingerprint = new Map();
|
|
128
192
|
for (const row of oldChunks) {
|
|
129
|
-
|
|
193
|
+
const fp = chunkFingerprint(row.source_file, row.chunk_text);
|
|
194
|
+
const cur = oldByFingerprint.get(fp);
|
|
195
|
+
oldByFingerprint.set(fp, cur ? better(cur, row) : row);
|
|
130
196
|
}
|
|
197
|
+
// Retention is measured on DISTINCT content, not rows: removing a redundant
|
|
198
|
+
// copy of content that is still present is not a loss. Measured on rows, a DB
|
|
199
|
+
// doubled by the old bug (2N → N) read as a 50% wipe and the cleanup reindex
|
|
200
|
+
// was refused forever.
|
|
201
|
+
const preDistinct = oldByFingerprint.size;
|
|
131
202
|
console.log(`[reindex] Phase 1: snapshotted ${oldChunks.length} existing chunks`);
|
|
132
203
|
// ── Phase 2: ingest new chunks into a staging set ──────────────────────────
|
|
133
204
|
// Strategy: do NOT delete first. Let routeIngest INSERT new chunks alongside old ones.
|
|
@@ -136,8 +207,8 @@ async function _reindexImpl() {
|
|
|
136
207
|
//
|
|
137
208
|
// To distinguish "old" vs "new" rows we capture max(id) before any ingest.
|
|
138
209
|
const maxIdBefore = db.prepare("SELECT COALESCE(MAX(id), 0) AS m FROM chunks").get().m;
|
|
139
|
-
|
|
140
|
-
const sharedFiles =
|
|
210
|
+
// Same scan as assertReindexSource — one definition of "the source".
|
|
211
|
+
const { memoryFiles, sharedFiles } = collectReindexFiles();
|
|
141
212
|
const allFiles = [...memoryFiles, ...sharedFiles];
|
|
142
213
|
let totalChunksIngested = 0;
|
|
143
214
|
const fileErrors = [];
|
|
@@ -161,24 +232,28 @@ async function _reindexImpl() {
|
|
|
161
232
|
const newChunks = db
|
|
162
233
|
.prepare("SELECT id, source_file, chunk_text FROM chunks WHERE id > ?")
|
|
163
234
|
.all(maxIdBefore);
|
|
164
|
-
// For each new chunk, look up by fingerprint
|
|
165
|
-
const updateNewMetadata = db.prepare(`
|
|
166
|
-
UPDATE chunks
|
|
167
|
-
SET tier = COALESCE(?, tier),
|
|
168
|
-
access_count = COALESCE(?, access_count),
|
|
169
|
-
importance = COALESCE(?, importance),
|
|
170
|
-
last_accessed_at = COALESCE(?, last_accessed_at)
|
|
171
|
-
WHERE id = ?
|
|
172
|
-
`);
|
|
235
|
+
// For each new chunk, look up by fingerprint: unchanged content keeps the old row.
|
|
173
236
|
const seenOldIds = new Set();
|
|
174
237
|
let inheritedCount = 0;
|
|
238
|
+
// A new row whose fingerprint matches an old row is the SAME content: keep the
|
|
239
|
+
// old row (it already holds the embedding, a stable id and its metadata) and
|
|
240
|
+
// drop the fresh copy. Before 2026-09-28 both were kept, so every reindex left
|
|
241
|
+
// each unchanged chunk twice (measured: 10 chunks -> 20 after one reindex).
|
|
242
|
+
// Only the fresh copy (id > maxIdBefore) is ever deleted here — never old data.
|
|
243
|
+
const dropNewDuplicate = db.prepare("DELETE FROM chunks WHERE id = ? AND id > ?");
|
|
244
|
+
let newDuplicatesDropped = 0;
|
|
175
245
|
const mergeTxn = db.transaction(() => {
|
|
176
246
|
for (const nc of newChunks) {
|
|
177
247
|
const fp = chunkFingerprint(nc.source_file, nc.chunk_text);
|
|
178
248
|
const oldRow = oldByFingerprint.get(fp);
|
|
179
249
|
if (oldRow) {
|
|
250
|
+
if (seenOldIds.has(oldRow.id)) {
|
|
251
|
+
// Second new copy of the same content in this run: keep the first.
|
|
252
|
+
newDuplicatesDropped += dropNewDuplicate.run(nc.id, maxIdBefore).changes;
|
|
253
|
+
continue;
|
|
254
|
+
}
|
|
180
255
|
seenOldIds.add(oldRow.id);
|
|
181
|
-
|
|
256
|
+
newDuplicatesDropped += dropNewDuplicate.run(nc.id, maxIdBefore).changes;
|
|
182
257
|
inheritedCount++;
|
|
183
258
|
}
|
|
184
259
|
}
|
|
@@ -189,6 +264,22 @@ async function _reindexImpl() {
|
|
|
189
264
|
// If fileErrors is non-empty AND would cause a wipe, the Layer 4 invariant
|
|
190
265
|
// check below will throw and roll back.
|
|
191
266
|
const orphanIds = oldChunks.map((r) => r.id).filter((id) => !seenOldIds.has(id));
|
|
267
|
+
// Layer 4, moved IN FRONT of the delete: project the post-count and refuse if
|
|
268
|
+
// it would breach the retention ratio. The post-delete check below stays as a
|
|
269
|
+
// second leg, but by then the rows are already gone (no auto-restore).
|
|
270
|
+
// Distinct content that will remain after the delete (kept old rows + new
|
|
271
|
+
// rows). An edited file replaces content — it is not a loss — so this counts
|
|
272
|
+
// what will be present, not which old fingerprints survived.
|
|
273
|
+
const orphanSet = new Set(orphanIds);
|
|
274
|
+
const projectedFps = new Set();
|
|
275
|
+
for (const r of db.prepare("SELECT id, source_file, chunk_text FROM chunks").all()) {
|
|
276
|
+
if (!orphanSet.has(r.id))
|
|
277
|
+
projectedFps.add(chunkFingerprint(r.source_file, r.chunk_text));
|
|
278
|
+
}
|
|
279
|
+
const projectedDistinct = projectedFps.size;
|
|
280
|
+
if (preDistinct > 0 && projectedDistinct / preDistinct < MIN_RETENTION_RATIO && !ALLOW_WIPE) {
|
|
281
|
+
throw new ReindexWipeDetectedError(preDistinct, projectedDistinct, MIN_RETENTION_RATIO);
|
|
282
|
+
}
|
|
192
283
|
let orphanedDeleted = 0;
|
|
193
284
|
if (orphanIds.length > 0) {
|
|
194
285
|
const deleteOrphan = db.prepare("DELETE FROM chunks WHERE id = ?");
|
|
@@ -211,13 +302,16 @@ async function _reindexImpl() {
|
|
|
211
302
|
// ── Layer 4: invariant check ────────────────────────────────────────────────
|
|
212
303
|
// Compute retention ratio. If we lost more than (1 - MIN_RETENTION_RATIO) of chunks,
|
|
213
304
|
// assume wipe-class failure and throw — withOpAudit failure path will preserve snapshot.
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
305
|
+
// Second leg, measured on the DB itself after the delete: distinct content present.
|
|
306
|
+
const retainedDistinct = new Set(db.prepare("SELECT source_file, chunk_text FROM chunks").all()
|
|
307
|
+
.map((r) => chunkFingerprint(r.source_file, r.chunk_text))).size;
|
|
308
|
+
const ratio = preDistinct === 0 ? 1 : retainedDistinct / preDistinct;
|
|
309
|
+
if (preDistinct > 0 && ratio < MIN_RETENTION_RATIO && !ALLOW_WIPE) {
|
|
310
|
+
throw new ReindexWipeDetectedError(preDistinct, retainedDistinct, MIN_RETENTION_RATIO);
|
|
217
311
|
}
|
|
218
312
|
console.log(`[reindex] DONE files=${allFiles.length} pre=${preCount} post=${postCount} ` +
|
|
219
313
|
`ratio=${(ratio * 100).toFixed(1)}% inherited=${inheritedCount} ` +
|
|
220
|
-
`orphans-deleted=${orphanedDeleted} ingest-errors=${fileErrors.length}`);
|
|
314
|
+
`orphans-deleted=${orphanedDeleted} new-duplicates-dropped=${newDuplicatesDropped} ingest-errors=${fileErrors.length}`);
|
|
221
315
|
if (fileErrors.length > 0) {
|
|
222
316
|
console.error(`[reindex] ${fileErrors.length} files failed; first 5:`);
|
|
223
317
|
for (const fe of fileErrors.slice(0, 5))
|
|
@@ -229,7 +323,7 @@ async function _reindexImpl() {
|
|
|
229
323
|
preCount,
|
|
230
324
|
postCount,
|
|
231
325
|
upserted: inheritedCount,
|
|
232
|
-
inserted: newChunks.length -
|
|
326
|
+
inserted: newChunks.length - newDuplicatesDropped,
|
|
233
327
|
preserved: inheritedCount,
|
|
234
328
|
orphaned: orphanedDeleted,
|
|
235
329
|
};
|
|
@@ -237,8 +331,7 @@ async function _reindexImpl() {
|
|
|
237
331
|
export async function reindex(opts) {
|
|
238
332
|
if (opts?.dryRun) {
|
|
239
333
|
const db = getDb();
|
|
240
|
-
const memoryFiles =
|
|
241
|
-
const sharedFiles = findFiles(resolve(WORKSPACE, "shared"), [".md"]);
|
|
334
|
+
const { memoryFiles, sharedFiles } = collectReindexFiles();
|
|
242
335
|
const allFiles = [...memoryFiles, ...sharedFiles];
|
|
243
336
|
const currentChunks = db.prepare("SELECT COUNT(*) AS c FROM chunks").get().c;
|
|
244
337
|
const entityFiles = allFiles.filter((f) => f.includes("/memory/entities/")).length;
|