nox-mem 3.2.1 → 3.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/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__/session-distill-sources.test.js +98 -0
- package/dist/__tests__/telemetry-per-chunk.test.js +110 -0
- package/dist/__tests__/temporal-filter.test.js +117 -0
- package/dist/api-server.js +43 -2
- package/dist/db.js +55 -10
- 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 +98 -18
- package/dist/session-distill.js +73 -24
- package/package.json +8 -6
|
@@ -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");
|
|
@@ -137,12 +138,20 @@ async function handleRequest(req, res) {
|
|
|
137
138
|
// that never cleaned vec_chunk_map), silently claiming embeddings we don't have.
|
|
138
139
|
let embedded = 0;
|
|
139
140
|
let embeddingOrphans = 0;
|
|
141
|
+
let indexOnly = -1;
|
|
140
142
|
try {
|
|
141
143
|
const sqliteVec = await import("sqlite-vec");
|
|
142
144
|
sqliteVec.load(db);
|
|
143
145
|
embedded = db.prepare("SELECT COUNT(DISTINCT m.chunk_id) as c FROM vec_chunk_map m INNER JOIN chunks c ON c.id = m.chunk_id").get().c;
|
|
144
146
|
const totalMap = db.prepare("SELECT COUNT(*) as c FROM vec_chunk_map").get().c;
|
|
145
147
|
embeddingOrphans = Math.max(0, totalMap - embedded);
|
|
148
|
+
try {
|
|
149
|
+
const idx = db.prepare("SELECT COUNT(*) AS c FROM vec_chunks_rowids").get().c;
|
|
150
|
+
indexOnly = Math.max(0, idx - totalMap);
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
indexOnly = -1;
|
|
154
|
+
}
|
|
146
155
|
}
|
|
147
156
|
catch {
|
|
148
157
|
try {
|
|
@@ -259,7 +268,22 @@ async function handleRequest(req, res) {
|
|
|
259
268
|
json(res, {
|
|
260
269
|
chunks: { total, types },
|
|
261
270
|
consolidation: { done: consolidated.c, failed: failed.c, last: lastCon.d },
|
|
262
|
-
|
|
271
|
+
/**
|
|
272
|
+
* ⚠️ `orphans` é `totalMap − embedded`: derivado do MAP, logo cego para um
|
|
273
|
+
* vetor que perdeu a linha de map. `indexOnly` fecha esse ângulo lendo a
|
|
274
|
+
* shadow table `vec_chunks_rowids` direto — ela é tabela normal e não
|
|
275
|
+
* exige o módulo vec0 carregado, ao contrário de `vec_chunks`.
|
|
276
|
+
*
|
|
277
|
+
* Medido num deploy de produção em 2026-08-27: `orphans: 0` com
|
|
278
|
+
* `indexOnly: 2074` — 2.074 vetores válidos no índice, inalcançáveis pela
|
|
279
|
+
* busca e invisíveis a TODA ferramenta existente, porque as três (este
|
|
280
|
+
* campo, o `prune-orphan-vectors` e o alerta que os consome) partem do
|
|
281
|
+
* map. Um guarda cujo predicado exige o dado que falta não cobre a falta
|
|
282
|
+
* desse dado.
|
|
283
|
+
*
|
|
284
|
+
* −1 = shadow table ausente (vec0 nunca criado), que NÃO é zero.
|
|
285
|
+
*/
|
|
286
|
+
vectorCoverage: { embedded, total, orphans: embeddingOrphans, indexOnly },
|
|
263
287
|
knowledgeGraph: { entities: kgEntities, relations: kgRelations },
|
|
264
288
|
retentionDistribution,
|
|
265
289
|
archiveCandidates,
|
|
@@ -358,22 +382,39 @@ async function handleRequest(req, res) {
|
|
|
358
382
|
let qText;
|
|
359
383
|
let limitStr;
|
|
360
384
|
let trackStr;
|
|
385
|
+
let asOfStr;
|
|
386
|
+
let changedSinceStr;
|
|
361
387
|
if (req.method === "POST") {
|
|
362
388
|
const body = await readJson(req);
|
|
363
389
|
qText = body.q ?? body.query;
|
|
364
390
|
limitStr = body.limit !== undefined ? String(body.limit) : undefined;
|
|
365
391
|
trackStr = body.track !== undefined ? String(body.track) : undefined;
|
|
392
|
+
asOfStr = body.as_of;
|
|
393
|
+
changedSinceStr = body.changed_since;
|
|
366
394
|
}
|
|
367
395
|
else {
|
|
368
396
|
const q = parseQuery(url);
|
|
369
397
|
qText = q.q ?? q.query;
|
|
370
398
|
limitStr = q.limit;
|
|
371
399
|
trackStr = q.track;
|
|
400
|
+
asOfStr = q.as_of;
|
|
401
|
+
changedSinceStr = q.changed_since;
|
|
372
402
|
}
|
|
373
403
|
if (!qText) {
|
|
374
404
|
json(res, { error: "q parameter required (POST body or GET query string, field name: q or query)" }, 400);
|
|
375
405
|
break;
|
|
376
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
|
+
}
|
|
377
418
|
const limit = parseInt(limitStr || "10");
|
|
378
419
|
// D1 (2026-06-07): healthchecks/canary pass ?track=false so automated
|
|
379
420
|
// probes don't inflate access_count → salience feedback loop. Default
|
|
@@ -382,7 +423,7 @@ async function handleRequest(req, res) {
|
|
|
382
423
|
// E12 (2026-05-04): propagate requesting agent from header
|
|
383
424
|
const agentHeader = req.headers["x-agent-name"];
|
|
384
425
|
const requestingAgent = (Array.isArray(agentHeader) ? agentHeader[0] : agentHeader) ?? process.env.NOX_AGENT_NAME;
|
|
385
|
-
const results = await searchHybrid(qText, limit, trackAccess);
|
|
426
|
+
const results = await searchHybrid(qText, limit, trackAccess, temporalFilter);
|
|
386
427
|
// E03a (2026-05-02): SPO injection envelope. Mode shadow → compute+log only.
|
|
387
428
|
// Mode active → surface vaultFacts in response. Mode off → no compute.
|
|
388
429
|
const vf = getVaultFacts(qText, getDb());
|
package/dist/db.js
CHANGED
|
@@ -4,24 +4,28 @@ 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
|
-
|
|
24
|
-
const SCHEMA_VERSION = 18;
|
|
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");
|
|
28
|
+
const SCHEMA_VERSION = 19;
|
|
25
29
|
// ────────────────────────────────────────────────────────────────────────────
|
|
26
30
|
// Large-DB ingest guard (postmortem 2026-05-19)
|
|
27
31
|
// ────────────────────────────────────────────────────────────────────────────
|
|
@@ -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");
|
|
@@ -178,10 +190,39 @@ function ensureSchema(db) {
|
|
|
178
190
|
migrateToV7(db);
|
|
179
191
|
if (currentVersion < 18)
|
|
180
192
|
migrateToV8(db);
|
|
193
|
+
if (currentVersion < 19)
|
|
194
|
+
migrateToV9(db);
|
|
181
195
|
db.prepare("INSERT OR REPLACE INTO meta (key, value, updated_at) VALUES ('schema_version', ?, datetime('now'))").run(String(SCHEMA_VERSION));
|
|
182
196
|
// Keep PRAGMA user_version in sync so op-audit and tests can rely on it.
|
|
183
197
|
db.pragma(`user_version = ${SCHEMA_VERSION}`);
|
|
184
198
|
}
|
|
199
|
+
function migrateToV9(db) {
|
|
200
|
+
// v19 — per-chunk search telemetry.
|
|
201
|
+
//
|
|
202
|
+
// The v6 telemetry row records the SHAPE of a search (how many results, how
|
|
203
|
+
// fast, whether semantic fired) but not WHICH chunks came back. That is
|
|
204
|
+
// enough to answer "is search healthy?" and not enough to answer "what has
|
|
205
|
+
// this memory ever actually served?" — a question about the retrieval
|
|
206
|
+
// surface, which is what an agent's context is really made of.
|
|
207
|
+
//
|
|
208
|
+
// ⚠️ PRIVACY BOUNDARY, deliberate and load-bearing: this adds the chunk IDs
|
|
209
|
+
// and their scores. It does NOT add the raw query text. `query_hash` stays
|
|
210
|
+
// the only representation of the query (see the v6 comment below), and the
|
|
211
|
+
// test `telemetry-per-chunk.test.ts` reads the INSERT statement out of
|
|
212
|
+
// search.ts and fails if `query_text` ever appears in it. IDs are internal
|
|
213
|
+
// rowids of content the operator already owns; the query string is the one
|
|
214
|
+
// field that can carry a third party's words.
|
|
215
|
+
//
|
|
216
|
+
// Per-column try/catch keeps this idempotent on DBs patched out of band.
|
|
217
|
+
try {
|
|
218
|
+
db.exec(`ALTER TABLE search_telemetry ADD COLUMN top_chunk_ids TEXT`);
|
|
219
|
+
}
|
|
220
|
+
catch { }
|
|
221
|
+
try {
|
|
222
|
+
db.exec(`ALTER TABLE search_telemetry ADD COLUMN top_scores TEXT`);
|
|
223
|
+
}
|
|
224
|
+
catch { }
|
|
225
|
+
}
|
|
185
226
|
function migrateToV8(db) {
|
|
186
227
|
// Standalone consolidation of the column additions that the canonical engine
|
|
187
228
|
// introduced across schema v8–v18 (typed retention, pain-weighting, entity
|
|
@@ -318,7 +359,11 @@ function migrateToV6(db) {
|
|
|
318
359
|
results_count INTEGER NOT NULL DEFAULT 0,
|
|
319
360
|
has_semantic INTEGER NOT NULL DEFAULT 0,
|
|
320
361
|
latency_ms INTEGER NOT NULL DEFAULT 0,
|
|
321
|
-
expansion_skipped_reason TEXT
|
|
362
|
+
expansion_skipped_reason TEXT,
|
|
363
|
+
-- v19 (ver migrateToV9): quais chunks a busca devolveu, e com que score.
|
|
364
|
+
-- JSON array, ou NULL quando nenhum resultado trouxe id.
|
|
365
|
+
top_chunk_ids TEXT,
|
|
366
|
+
top_scores TEXT
|
|
322
367
|
);
|
|
323
368
|
CREATE INDEX IF NOT EXISTS idx_search_telemetry_ts ON search_telemetry(ts DESC);
|
|
324
369
|
`);
|
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
|