nox-mem 3.4.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.
Files changed (67) hide show
  1. package/README.md +62 -33
  2. package/dist/api/answer.js +22 -0
  3. package/dist/api-server.js +3 -2
  4. package/dist/cli/answer.js +39 -1
  5. package/dist/db.js +31 -20
  6. package/dist/doctor.js +5 -4
  7. package/dist/embed.js +53 -3
  8. package/dist/index.js +16 -10
  9. package/dist/lib/answer/index.js +3 -2
  10. package/dist/lib/answer/retrieval.js +6 -4
  11. package/dist/lib/answer/temporal.js +51 -0
  12. package/dist/lib/api-port.js +16 -0
  13. package/dist/lib/db-path.js +13 -1
  14. package/dist/lib/ingest-many.js +49 -0
  15. package/dist/mcp/tools/answer.js +23 -0
  16. package/dist/mcp-server.js +36 -5
  17. package/dist/reflect.js +2 -2
  18. package/dist/reindex-errors.js +19 -0
  19. package/dist/reindex.js +12 -2
  20. package/dist/search.js +27 -6
  21. package/package.json +4 -1
  22. package/prompts/consolidate.txt +13 -0
  23. package/prompts/digest.txt +5 -0
  24. package/dist/__tests__/brief-diversity.test.js +0 -266
  25. package/dist/__tests__/brief.test.js +0 -287
  26. package/dist/__tests__/churn.test.js +0 -66
  27. package/dist/__tests__/edge-typing.test.js +0 -99
  28. package/dist/__tests__/fts-or-fallback.test.js +0 -115
  29. package/dist/__tests__/ingest-event.test.js +0 -151
  30. package/dist/__tests__/op-audit-e2e.test.js +0 -130
  31. package/dist/__tests__/pragma-alignment.test.js +0 -123
  32. package/dist/__tests__/reindex-dedup.test.js +0 -80
  33. package/dist/__tests__/reindex-safety.test.js +0 -116
  34. package/dist/__tests__/reranker.test.js +0 -326
  35. package/dist/__tests__/retention.test.js +0 -99
  36. package/dist/__tests__/search-track-access.test.js +0 -49
  37. package/dist/__tests__/session-distill-sources.test.js +0 -98
  38. package/dist/__tests__/spo-injection.test.js +0 -172
  39. package/dist/__tests__/telemetry-per-chunk.test.js +0 -110
  40. package/dist/__tests__/temporal-detector.test.js +0 -103
  41. package/dist/__tests__/temporal-filter.test.js +0 -117
  42. package/dist/lib/answer/__tests__/e2e-gemini.test.js +0 -229
  43. package/dist/lib/answer/__tests__/integration-sqlite.test.js +0 -388
  44. package/dist/lib/answer/__tests__/integration.test.js +0 -347
  45. package/dist/lib/answer/__tests__/prompt.test.js +0 -117
  46. package/dist/lib/answer/__tests__/t5-t10.test.js +0 -501
  47. package/dist/lib/api/__tests__/safe-error-message.test.js +0 -155
  48. package/dist/lib/auth/__tests__/localhost-guard.test.js +0 -144
  49. package/dist/lib/error-sanitizer/__tests__/sanitize.test.js +0 -354
  50. package/dist/lib/events/__tests__/bus.test.js +0 -208
  51. package/dist/lib/op-audit-extension/__tests__/ran-at-guard.test.js +0 -109
  52. package/dist/lib/regex-extract/__tests__/extractor.test.js +0 -197
  53. package/dist/lib/regex-extract/__tests__/frontmatter.test.js +0 -75
  54. package/dist/lib/regex-extract/__tests__/ingest-router-l4.test.js +0 -139
  55. package/dist/lib/regex-extract/__tests__/production-wire.test.js +0 -177
  56. package/dist/lib/regex-extract/__tests__/reconcile.test.js +0 -170
  57. package/dist/lib/regex-extract/__tests__/strip-code.test.js +0 -36
  58. package/dist/privacy/__tests__/filter.test.js +0 -352
  59. package/dist/providers/__tests__/conformance-extended.test.js +0 -249
  60. package/dist/providers/__tests__/conformance.test.js +0 -98
  61. package/dist/providers/__tests__/cost-cap.test.js +0 -151
  62. package/dist/providers/__tests__/e2e-real.test.js +0 -79
  63. package/dist/providers/__tests__/factory.test.js +0 -80
  64. package/dist/providers/__tests__/fallback.test.js +0 -223
  65. package/dist/providers/__tests__/gemini.test.js +0 -191
  66. package/dist/providers/__tests__/health.test.js +0 -128
  67. package/dist/providers/__tests__/telemetry.test.js +0 -219
@@ -1,80 +0,0 @@
1
- // reindex on a DB that the pre-2026-09-28 reindex already doubled, plus the
2
- // adversarial-review findings on PR #29 (GLM + DeepSeek):
3
- // - the retention guard measured ROWS, so cleaning 2N → N read as a 50% wipe
4
- // and the first reindex after the fix was refused forever;
5
- // - among duplicates, the kept row must be the one holding the embedding;
6
- // - an edited file replaces content, it is not a loss;
7
- // - --dry-run must not write;
8
- // - the legacy DB path must equal the one db.ts used before the refactor.
9
- //
10
- // Run: npm test (or: npx tsc -p tsconfig.test.json && node --test dist/__tests__/reindex-dedup.test.js)
11
- import { test, before, after } from "node:test";
12
- import assert from "node:assert/strict";
13
- import { mkdtempSync, mkdirSync, realpathSync, rmSync, writeFileSync } from "fs";
14
- import { tmpdir } from "os";
15
- import { dirname, join, resolve } from "path";
16
- import { fileURLToPath } from "url";
17
- import { LEGACY_DB_PATH } from "../lib/db-path.js";
18
- const TMP_ROOT = realpathSync(mkdtempSync(join(process.env.NOX_TEST_TMP_ROOT || tmpdir(), "nox-mem-dedup-test-")));
19
- const WS = join(TMP_ROOT, "ws");
20
- const MEM = join(WS, "memory");
21
- mkdirSync(MEM, { recursive: true });
22
- mkdirSync(join(WS, "tools", "nox-mem"), { recursive: true });
23
- delete process.env.NOX_DB_PATH;
24
- delete process.env.NOX_REINDEX_ALLOW_WIPE;
25
- // Hermetic: with an embedding key in the caller's env, ingest auto-vectorizes
26
- // (real API calls, and every row gets a vector), which changes which duplicate
27
- // counts as "the embedded one". Tests never spend on embeddings.
28
- for (const k of ["GEMINI_API_KEY", "OPENAI_API_KEY", "NOX_EMBEDDING_API_KEY", "NOX_EMBED_API_KEY"])
29
- delete process.env[k];
30
- process.env.OPENCLAW_WORKSPACE = WS;
31
- let getDb, closeDb, reindex, routeIngest;
32
- const N = 20;
33
- const count = () => getDb().prepare("SELECT COUNT(*) AS c FROM chunks").get().c;
34
- before(async () => {
35
- ({ getDb, closeDb } = await import("../db.js"));
36
- ({ reindex } = await import("../reindex.js"));
37
- ({ routeIngest } = await import("../lib/ingest-router.js"));
38
- for (let i = 1; i <= N; i++)
39
- writeFileSync(join(MEM, `n${i}.md`), `# N${i}\nnote number ${i} about topic${i}.\n`);
40
- for (let i = 1; i <= N; i++)
41
- await routeIngest(join(MEM, `n${i}.md`));
42
- });
43
- after(() => {
44
- closeDb();
45
- rmSync(TMP_ROOT, { recursive: true, force: true });
46
- });
47
- test("legacy DB path is the one db.ts used before the refactor (<package>/nox-mem.db)", () => {
48
- // this file compiles to dist/__tests__/…; db.ts compiled to dist/db.js and used resolve(dist, "..", "nox-mem.db")
49
- const dist = resolve(dirname(fileURLToPath(import.meta.url)), "..");
50
- assert.equal(LEGACY_DB_PATH, resolve(dist, "..", "nox-mem.db"));
51
- });
52
- test("--dry-run does not write", async () => {
53
- const pre = count();
54
- const maxId = getDb().prepare("SELECT MAX(id) AS m FROM chunks").get().m;
55
- await reindex({ dryRun: true });
56
- assert.equal(count(), pre);
57
- assert.equal(getDb().prepare("SELECT MAX(id) AS m FROM chunks").get().m, maxId);
58
- });
59
- test("an already-doubled DB is cleaned (2N → N), not refused, and keeps the embedded copy", async () => {
60
- const db = getDb();
61
- db.exec("INSERT INTO chunks (source_file, chunk_type, chunk_text, source_date) SELECT source_file, chunk_type, chunk_text, source_date FROM chunks");
62
- assert.equal(count(), 2 * N);
63
- // Mark the HIGHER-id copy of n7 as the embedded one; lowest-id-wins alone would drop it.
64
- const copies = db.prepare("SELECT id FROM chunks WHERE chunk_text LIKE '%number 7 about%' ORDER BY id").all();
65
- assert.equal(copies.length, 2);
66
- db.exec("CREATE TABLE IF NOT EXISTS vec_chunk_map (vec_rowid INTEGER PRIMARY KEY, chunk_id INTEGER NOT NULL UNIQUE)");
67
- db.prepare("INSERT INTO vec_chunk_map (vec_rowid, chunk_id) VALUES (?, ?)").run(900001, copies[1].id);
68
- await reindex();
69
- assert.equal(count(), N, "one row per distinct content");
70
- const left = db.prepare("SELECT id FROM chunks WHERE chunk_text LIKE '%number 7 about%'").all();
71
- assert.deepEqual(left.map((r) => r.id), [copies[1].id], "the copy with the embedding survives");
72
- });
73
- test("editing many files is replacement, not loss (guard stays quiet)", async () => {
74
- // Rewrite half the corpus: every chunk of those files changes fingerprint.
75
- for (let i = 1; i <= N / 2; i++)
76
- writeFileSync(join(MEM, `n${i}.md`), `# N${i}\nnote number ${i} REWRITTEN.\n`);
77
- await reindex();
78
- assert.equal(count(), N);
79
- assert.equal(getDb().prepare("SELECT COUNT(*) AS c FROM chunks WHERE chunk_text LIKE '%REWRITTEN%'").get().c, N / 2);
80
- });
@@ -1,116 +0,0 @@
1
- // reindex safety (2026-09-28) — measured on a clean npm install before the fix:
2
- // 1. no $OPENCLAW_WORKSPACE ⇒ the scan found 0 files ⇒ every chunk was deleted
3
- // as an "orphan"; the retention guard threw only AFTER the DELETE;
4
- // 2. every reindex kept both the old row and the fresh copy of unchanged
5
- // content (10 chunks → 20).
6
- // Also covers the shared DB path resolver (db.ts and op-audit must agree).
7
- //
8
- // Run: npm test (or: npx tsc -p tsconfig.test.json && node --test dist/__tests__/reindex-safety.test.js)
9
- import { test, before, after } from "node:test";
10
- import assert from "node:assert/strict";
11
- import { mkdtempSync, mkdirSync, realpathSync, rmSync, writeFileSync, unlinkSync } from "fs";
12
- import { tmpdir, homedir } from "os";
13
- import { join } from "path";
14
- import { resolveDbPathWithSource, LEGACY_DB_PATH, DEFAULT_STANDALONE_DB_PATH, isInsideNodeModules, } from "../lib/db-path.js";
15
- // realpath: op-audit refuses snapshot dirs reached through a symlink (macOS /tmp → /private/tmp).
16
- const TMP_ROOT = realpathSync(mkdtempSync(join(process.env.NOX_TEST_TMP_ROOT || tmpdir(), "nox-mem-reindex-test-")));
17
- const WS = join(TMP_ROOT, "ws");
18
- const MEM = join(WS, "memory");
19
- mkdirSync(MEM, { recursive: true });
20
- mkdirSync(join(WS, "tools", "nox-mem"), { recursive: true });
21
- // DB derives from the workspace, as on the origin deployment (op-audit rejects a
22
- // NOX_DB_PATH that disagrees with OPENCLAW_WORKSPACE).
23
- delete process.env.NOX_DB_PATH;
24
- delete process.env.NOX_REINDEX_ALLOW_WIPE;
25
- // Hermetic: with an embedding key in the caller's env, ingest auto-vectorizes
26
- // (real API calls, and every row gets a vector), which changes which duplicate
27
- // counts as "the embedded one". Tests never spend on embeddings.
28
- for (const k of ["GEMINI_API_KEY", "OPENAI_API_KEY", "NOX_EMBEDDING_API_KEY", "NOX_EMBED_API_KEY"])
29
- delete process.env[k];
30
- process.env.OPENCLAW_WORKSPACE = WS;
31
- const DB = join(WS, "tools", "nox-mem", "nox-mem.db");
32
- // ─── DB path resolver (pure) ─────────────────────────────────────────────────
33
- test("db-path: NOX_DB_PATH wins", () => {
34
- const r = resolveDbPathWithSource({ NOX_DB_PATH: "/x/y.db", OPENCLAW_WORKSPACE: "/ws" }, () => true);
35
- assert.deepEqual(r, { path: "/x/y.db", source: "NOX_DB_PATH" });
36
- });
37
- test("db-path: OPENCLAW_WORKSPACE next (origin layout unchanged)", () => {
38
- const r = resolveDbPathWithSource({ OPENCLAW_WORKSPACE: "/root/.openclaw/workspace" }, () => false);
39
- assert.deepEqual(r, { path: "/root/.openclaw/workspace/tools/nox-mem/nox-mem.db", source: "OPENCLAW_WORKSPACE" });
40
- });
41
- test("db-path: existing legacy <package>/nox-mem.db is kept (no silent move of live data)", () => {
42
- const r = resolveDbPathWithSource({}, (p) => p === LEGACY_DB_PATH);
43
- assert.deepEqual(r, { path: LEGACY_DB_PATH, source: "legacy-package" });
44
- });
45
- test("db-path: fresh install defaults to ~/.nox-mem/nox.db, not the package dir", () => {
46
- const r = resolveDbPathWithSource({}, () => false);
47
- assert.equal(r.source, "standalone-default");
48
- assert.equal(r.path, join(homedir(), ".nox-mem", "nox.db"));
49
- assert.equal(r.path, DEFAULT_STANDALONE_DB_PATH);
50
- assert.equal(isInsideNodeModules(r.path), false);
51
- });
52
- test("db-path: node_modules detection", () => {
53
- assert.equal(isInsideNodeModules("/usr/lib/node_modules/nox-mem/nox-mem.db"), true);
54
- assert.equal(isInsideNodeModules("/home/u/.nox-mem/nox.db"), false);
55
- });
56
- // ─── reindex against a real workspace ────────────────────────────────────────
57
- let getDb, closeDb, reindex, assertReindexSource;
58
- let ReindexSourceMissingError, ReindexWipeDetectedError, routeIngest;
59
- const count = () => getDb().prepare("SELECT COUNT(*) AS c FROM chunks").get().c;
60
- const ids = () => getDb().prepare("SELECT group_concat(id) AS g FROM (SELECT id FROM chunks ORDER BY id)").get().g;
61
- before(async () => {
62
- ({ getDb, closeDb } = await import("../db.js"));
63
- ({ reindex, assertReindexSource, ReindexSourceMissingError, ReindexWipeDetectedError } = await import("../reindex.js"));
64
- ({ routeIngest } = await import("../lib/ingest-router.js"));
65
- for (let i = 1; i <= 10; i++)
66
- writeFileSync(join(MEM, `n${i}.md`), `# N${i}\nnote number ${i} about topic${i}.\n`);
67
- for (let i = 1; i <= 10; i++)
68
- await routeIngest(join(MEM, `n${i}.md`));
69
- assert.equal(getDb().prepare("SELECT 1").get() !== undefined, true);
70
- });
71
- after(() => {
72
- closeDb();
73
- rmSync(TMP_ROOT, { recursive: true, force: true });
74
- });
75
- test("reindex: unchanged content is not duplicated and keeps its ids", async () => {
76
- const before = ids();
77
- assert.equal(count(), 10);
78
- await reindex();
79
- assert.equal(count(), 10, "one reindex must not double the corpus");
80
- await reindex();
81
- assert.equal(count(), 10);
82
- assert.equal(ids(), before, "old rows (with their embeddings) are the ones kept");
83
- });
84
- test("reindex: edited file replaces its chunk, new file is added", async () => {
85
- writeFileSync(join(MEM, "n1.md"), "# N1\nnote number 1 EDITED.\n");
86
- writeFileSync(join(MEM, "n11.md"), "# N11\nbrand new note eleven.\n");
87
- await reindex();
88
- const q = (like) => getDb().prepare("SELECT COUNT(*) AS c FROM chunks WHERE chunk_text LIKE ?").get(like).c;
89
- assert.equal(q("%EDITED%"), 1);
90
- assert.equal(q("%number 1 about%"), 0);
91
- assert.equal(q("%eleven%"), 1);
92
- assert.equal(count(), 11);
93
- });
94
- test("reindex: retention guard refuses BEFORE deleting (rows survive the throw)", async () => {
95
- for (const i of [2, 3, 4, 5, 6])
96
- unlinkSync(join(MEM, `n${i}.md`));
97
- const pre = count();
98
- await assert.rejects(() => reindex(), (e) => e instanceof ReindexWipeDetectedError);
99
- assert.ok(count() >= pre, `no chunk may be deleted when the guard fires (pre=${pre}, now=${count()})`);
100
- });
101
- test("assertReindexSource: refuses when no source dir exists and the DB has chunks", () => {
102
- // The workspace path is captured at import, so empty the fixture instead.
103
- rmSync(MEM, { recursive: true, force: true });
104
- assert.throws(() => assertReindexSource(5), (e) => e instanceof ReindexSourceMissingError && /no source directory/.test(e.message));
105
- assert.doesNotThrow(() => assertReindexSource(0), "an empty DB has nothing to lose");
106
- });
107
- test("assertReindexSource: refuses when the source dir exists but holds no file", () => {
108
- mkdirSync(MEM, { recursive: true });
109
- assert.throws(() => assertReindexSource(5), (e) => e instanceof ReindexSourceMissingError && /found 0 files/.test(e.message));
110
- });
111
- test("reindex: refusal leaves every chunk in place", async () => {
112
- const pre = count();
113
- assert.ok(pre > 0);
114
- await assert.rejects(() => reindex(), (e) => e instanceof ReindexSourceMissingError);
115
- assert.equal(count(), pre);
116
- });
@@ -1,326 +0,0 @@
1
- // D01 — Cross-encoder Reranker tests.
2
- // Spec: memoria-nox/specs/2026-05-07-D01-cross-encoder-reranker.md
3
- //
4
- // Run: cd /root/.openclaw/workspace/tools/nox-mem && npx tsc &&
5
- // node --test dist/__tests__/reranker.test.js
6
- import { test, before, after, beforeEach } from "node:test";
7
- import assert from "node:assert/strict";
8
- import { mkdtempSync, rmSync } from "node:fs";
9
- import { tmpdir } from "node:os";
10
- import { join } from "node:path";
11
- // Use OS tmp (cross-platform). VPS test pode override via NOX_TEST_TMP_ROOT.
12
- const TMP_BASE = process.env.NOX_TEST_TMP_ROOT || tmpdir();
13
- const TMP_ROOT = mkdtempSync(join(TMP_BASE, "nox-mem-reranker-test-"));
14
- const TEST_DB = join(TMP_ROOT, "test.db");
15
- process.env.NOX_DB_PATH = TEST_DB;
16
- let getDb, closeDb;
17
- let rerank;
18
- let __setRerankerFnForTesting;
19
- let computePositionChanges;
20
- let computeLiftScore;
21
- let getMode, getTopKIn, getTopKOut;
22
- before(async () => {
23
- const dbMod = await import("../db.js");
24
- const rrMod = await import("../lib/reranker.js");
25
- getDb = dbMod.getDb;
26
- closeDb = dbMod.closeDb;
27
- rerank = rrMod.rerank;
28
- __setRerankerFnForTesting = rrMod.__setRerankerFnForTesting;
29
- computePositionChanges = rrMod.computePositionChanges;
30
- computeLiftScore = rrMod.computeLiftScore;
31
- getMode = rrMod.getMode;
32
- getTopKIn = rrMod.getTopKIn;
33
- getTopKOut = rrMod.getTopKOut;
34
- // Bootstrap schema.
35
- const db = getDb();
36
- const v = db.prepare("PRAGMA user_version").get().user_version;
37
- assert.equal(v >= 16, true, `expected schema ≥16, got ${v}`);
38
- // NOTE (core kit): the search_telemetry reranker_* columns belonged to the
39
- // telemetry-persistence plumbing that was trimmed from the public package.
40
- // The reranker engine under test (rerank / computePositionChanges /
41
- // computeLiftScore / mode parsing) is pure and does not depend on that
42
- // schema, so the column assertion was dropped with the telemetry collector.
43
- });
44
- beforeEach(() => {
45
- // Reset env entre tests
46
- delete process.env.NOX_RERANKER_MODE;
47
- delete process.env.NOX_RERANKER_TOP_K_IN;
48
- delete process.env.NOX_RERANKER_TOP_K_OUT;
49
- delete process.env.NOX_RERANKER_TIMEOUT_MS;
50
- delete process.env.NOX_RERANKER_LOG;
51
- __setRerankerFnForTesting(null);
52
- });
53
- after(() => {
54
- __setRerankerFnForTesting(null);
55
- closeDb();
56
- rmSync(TMP_ROOT, { recursive: true, force: true });
57
- });
58
- // ─────────────────────────────────────────────────────────────────────────
59
- // Test fixtures
60
- // ─────────────────────────────────────────────────────────────────────────
61
- function makeCandidates(n) {
62
- const out = [];
63
- for (let i = 0; i < n; i++) {
64
- out.push({
65
- id: i + 1,
66
- score: 100 - i,
67
- rrfScore: 100 - i,
68
- chunk_text: `chunk text ${i + 1}: content about item ${i + 1}`,
69
- source_file: `file-${i + 1}.md`,
70
- chunk_type: "concept",
71
- source_date: null,
72
- });
73
- }
74
- return out;
75
- }
76
- // Mock fn: REAL inversão (idx 0 → score baixo, idx N-1 → score alto).
77
- // Sorted desc pelo reranker → ordem invertida em relação ao input.
78
- function makeReverseRerankerFn() {
79
- return async (pairs) => {
80
- return pairs.map((_, i) => ({ score: i / pairs.length }));
81
- };
82
- }
83
- // ─────────────────────────────────────────────────────────────────────────
84
- // 1. mode=off: rerank não chamado, retorna candidates intactos
85
- // ─────────────────────────────────────────────────────────────────────────
86
- test("rerank: mode=off bypass — fn não chamada, retorna candidates intactos", async () => {
87
- process.env.NOX_RERANKER_MODE = "off";
88
- let called = false;
89
- __setRerankerFnForTesting(async () => {
90
- called = true;
91
- return [];
92
- });
93
- const cands = makeCandidates(5);
94
- const { results, summary } = await rerank("test query", cands, 3);
95
- assert.equal(called, false, "fn should not be called in off mode");
96
- assert.equal(results.length, 3);
97
- assert.equal(results[0].id, 1);
98
- assert.equal(results[2].id, 3);
99
- assert.equal(summary.mode, "off");
100
- assert.equal(summary.positionChanges, 0);
101
- });
102
- // ─────────────────────────────────────────────────────────────────────────
103
- // 2. mode=shadow: fn chamada, telemetria, ranking original retornado
104
- // ─────────────────────────────────────────────────────────────────────────
105
- test("rerank: mode=shadow — fn chamada, retorna ORIGINAL top-K (não muta)", async () => {
106
- process.env.NOX_RERANKER_MODE = "shadow";
107
- __setRerankerFnForTesting(makeReverseRerankerFn());
108
- const cands = makeCandidates(5);
109
- const { results, summary } = await rerank("test query", cands, 3);
110
- // Reranker invertido reordenaria pra [5,4,3,2,1] mas shadow retorna ORIGINAL
111
- assert.equal(results.length, 3);
112
- assert.equal(results[0].id, 1, "shadow preserves original top");
113
- assert.equal(results[1].id, 2);
114
- assert.equal(results[2].id, 3);
115
- assert.equal(summary.mode, "shadow");
116
- assert.equal(summary.failed, false);
117
- assert.equal(summary.topKOut, 3);
118
- // Position changes computed entre orig top-3 [1,2,3] vs new top-3 [5,4,3]:
119
- // id=1 saiu (orig:0, new:undef) → 1 change
120
- // id=2 saiu (orig:1, new:undef) → 1 change
121
- // id=3 ficou (orig:2, new:2) → 0 change
122
- // id=4 entrou (orig:undef, new:1) → 1 change
123
- // id=5 entrou (orig:undef, new:0) → 1 change
124
- // Total: 4 changes (id=3 unchanged).
125
- assert.equal(summary.positionChanges, 4, `expected 4, got ${summary.positionChanges}`);
126
- });
127
- // ─────────────────────────────────────────────────────────────────────────
128
- // 3. mode=active: fn chamada, ranking substituído pelo reranker
129
- // ─────────────────────────────────────────────────────────────────────────
130
- test("rerank: mode=active — substitui ranking pelo output do reranker", async () => {
131
- process.env.NOX_RERANKER_MODE = "active";
132
- // Reverse mock: idx N-1 ganha score máximo → top-3 do reranker = [5,4,3]
133
- __setRerankerFnForTesting(makeReverseRerankerFn());
134
- const cands = makeCandidates(5);
135
- const { results, summary } = await rerank("test query", cands, 3);
136
- assert.equal(results.length, 3);
137
- assert.equal(results[0].id, 5, "active mode: highest reranker score wins");
138
- assert.equal(results[1].id, 4);
139
- assert.equal(results[2].id, 3);
140
- assert.equal(summary.mode, "active");
141
- assert.equal(summary.failed, false);
142
- });
143
- // ─────────────────────────────────────────────────────────────────────────
144
- // 4. computePositionChanges helper
145
- // ─────────────────────────────────────────────────────────────────────────
146
- test("computePositionChanges: pos 0↔1 → 2 changes", () => {
147
- const orig = [
148
- { id: 1, chunk_text: "" },
149
- { id: 2, chunk_text: "" },
150
- { id: 3, chunk_text: "" },
151
- ];
152
- const next = [
153
- { id: 2, chunk_text: "" },
154
- { id: 1, chunk_text: "" },
155
- { id: 3, chunk_text: "" },
156
- ];
157
- assert.equal(computePositionChanges(orig, next), 2);
158
- });
159
- test("computePositionChanges: ranking idêntico → 0", () => {
160
- const cands = makeCandidates(3);
161
- assert.equal(computePositionChanges(cands, cands), 0);
162
- });
163
- test("computePositionChanges: disjoint → 6 changes (3 left + 3 entered)", () => {
164
- const orig = [
165
- { id: 1, chunk_text: "" },
166
- { id: 2, chunk_text: "" },
167
- { id: 3, chunk_text: "" },
168
- ];
169
- const next = [
170
- { id: 4, chunk_text: "" },
171
- { id: 5, chunk_text: "" },
172
- { id: 6, chunk_text: "" },
173
- ];
174
- assert.equal(computePositionChanges(orig, next), 6);
175
- });
176
- // ─────────────────────────────────────────────────────────────────────────
177
- // 5. computeLiftScore helper
178
- // ─────────────────────────────────────────────────────────────────────────
179
- test("computeLiftScore: identical ranking → 0", () => {
180
- const cands = makeCandidates(5);
181
- assert.equal(computeLiftScore(cands, cands), 0);
182
- });
183
- test("computeLiftScore: swap pos 0↔4 em K=5 → 8/(5*5) = 0.32", () => {
184
- const orig = [
185
- { id: 1, chunk_text: "" },
186
- { id: 2, chunk_text: "" },
187
- { id: 3, chunk_text: "" },
188
- { id: 4, chunk_text: "" },
189
- { id: 5, chunk_text: "" },
190
- ];
191
- const next = [
192
- { id: 5, chunk_text: "" },
193
- { id: 2, chunk_text: "" },
194
- { id: 3, chunk_text: "" },
195
- { id: 4, chunk_text: "" },
196
- { id: 1, chunk_text: "" },
197
- ];
198
- // allIds=5; deltas: id=1 |0-4|=4, id=5 |4-0|=4, ids 2,3,4 = 0. sum=8.
199
- // norm = 8 / (5 * 5) = 0.32
200
- const lift = computeLiftScore(orig, next);
201
- assert.equal(Math.abs(lift - 0.32) < 0.001, true, `expected 0.32, got ${lift}`);
202
- });
203
- test("computeLiftScore: disjoint sets → 1 (max lift)", () => {
204
- const orig = [{ id: 1, chunk_text: "" }, { id: 2, chunk_text: "" }];
205
- const next = [{ id: 3, chunk_text: "" }, { id: 4, chunk_text: "" }];
206
- assert.equal(computeLiftScore(orig, next), 1);
207
- });
208
- // ─────────────────────────────────────────────────────────────────────────
209
- // 6. fail-open: rerank fn lança → retorna candidates originais, summary.failed
210
- // ─────────────────────────────────────────────────────────────────────────
211
- test("rerank: fail-open — fn throws → retorna originais, summary.failed=true", async () => {
212
- process.env.NOX_RERANKER_MODE = "active";
213
- __setRerankerFnForTesting(async () => {
214
- throw new Error("simulated ONNX crash");
215
- });
216
- const cands = makeCandidates(5);
217
- const { results, summary } = await rerank("test query", cands, 3);
218
- assert.equal(results.length, 3);
219
- assert.equal(results[0].id, 1, "fail-open returns original ranking");
220
- assert.equal(results[1].id, 2);
221
- assert.equal(results[2].id, 3);
222
- assert.equal(summary.failed, true);
223
- assert.ok(summary.failureReason);
224
- assert.ok(summary.failureReason.includes("simulated"));
225
- });
226
- // ─────────────────────────────────────────────────────────────────────────
227
- // 7. timeout: fn excede NOX_RERANKER_TIMEOUT_MS → fail-open
228
- // ─────────────────────────────────────────────────────────────────────────
229
- test("rerank: timeout — fn lenta excede timeout → fail-open", async () => {
230
- process.env.NOX_RERANKER_MODE = "active";
231
- process.env.NOX_RERANKER_TIMEOUT_MS = "100";
232
- __setRerankerFnForTesting(async (pairs) => {
233
- await new Promise((r) => setTimeout(r, 500));
234
- return pairs.map(() => ({ score: 0.5 }));
235
- });
236
- const cands = makeCandidates(5);
237
- const t0 = Date.now();
238
- const { results, summary } = await rerank("test query", cands, 3);
239
- const elapsed = Date.now() - t0;
240
- assert.equal(results[0].id, 1, "timeout fail-open returns original ranking");
241
- assert.equal(summary.failed, true);
242
- assert.ok(summary.failureReason && summary.failureReason.includes("timeout"));
243
- assert.ok(elapsed < 400, `should bail before fn completes (got ${elapsed}ms)`);
244
- });
245
- // ─────────────────────────────────────────────────────────────────────────
246
- // 8. K_IN clip: candidates < K_IN → reranker vê todos (não pad)
247
- // ─────────────────────────────────────────────────────────────────────────
248
- test("rerank: K_IN clip — candidates.length < K_IN → fn recebe todos", async () => {
249
- process.env.NOX_RERANKER_MODE = "active";
250
- process.env.NOX_RERANKER_TOP_K_IN = "50";
251
- let receivedCount = -1;
252
- __setRerankerFnForTesting(async (pairs) => {
253
- receivedCount = pairs.length;
254
- return pairs.map(() => ({ score: 0.5 }));
255
- });
256
- const cands = makeCandidates(20);
257
- await rerank("test query", cands, 10);
258
- assert.equal(receivedCount, 20, "fn should see all 20 candidates (not padded to 50)");
259
- });
260
- // ─────────────────────────────────────────────────────────────────────────
261
- // 9. K_OUT clip
262
- // ─────────────────────────────────────────────────────────────────────────
263
- test("rerank: K_OUT clip — candidates=50 + K_OUT=10 → final.length=10", async () => {
264
- process.env.NOX_RERANKER_MODE = "active";
265
- __setRerankerFnForTesting(async (pairs) => pairs.map((_, i) => ({ score: 1 - i / pairs.length })));
266
- const cands = makeCandidates(50);
267
- const { results, summary } = await rerank("test query", cands, 10);
268
- assert.equal(results.length, 10);
269
- assert.equal(summary.topKOut, 10);
270
- });
271
- // ─────────────────────────────────────────────────────────────────────────
272
- // 10. empty candidates → no-op, latency=0
273
- // ─────────────────────────────────────────────────────────────────────────
274
- test("rerank: candidates vazio → no-op, latency baixa", async () => {
275
- process.env.NOX_RERANKER_MODE = "active";
276
- let called = false;
277
- __setRerankerFnForTesting(async () => {
278
- called = true;
279
- return [];
280
- });
281
- const { results, summary } = await rerank("test query", [], 10);
282
- assert.equal(results.length, 0);
283
- assert.equal(called, false, "fn should not be called for empty candidates");
284
- assert.equal(summary.failed, false);
285
- assert.ok(summary.latencyMs < 50, `latency should be small (got ${summary.latencyMs}ms)`);
286
- });
287
- // ─────────────────────────────────────────────────────────────────────────
288
- // 11. shadow mode preserves rrfScore-style rank metadata; only summary differs
289
- // ─────────────────────────────────────────────────────────────────────────
290
- test("rerank: shadow mode — summary captura lift mas resultados intactos", async () => {
291
- process.env.NOX_RERANKER_MODE = "shadow";
292
- __setRerankerFnForTesting(async (pairs) =>
293
- // Inverte completamente: idx 0 → score 0, idx N-1 → score 1
294
- pairs.map((_, i) => ({ score: i / pairs.length })));
295
- const cands = makeCandidates(5);
296
- const { results, summary } = await rerank("test query", cands, 3);
297
- // Shadow: results = original top-3 = [1,2,3]
298
- assert.equal(results[0].id, 1);
299
- assert.equal(results[1].id, 2);
300
- assert.equal(results[2].id, 3);
301
- // Summary captura o que TERIA sido: position changes >0
302
- assert.equal(summary.mode, "shadow");
303
- assert.ok(summary.positionChanges > 0, `expected position_changes>0, got ${summary.positionChanges}`);
304
- assert.ok(summary.liftScore > 0, `expected liftScore>0, got ${summary.liftScore}`);
305
- });
306
- // ─────────────────────────────────────────────────────────────────────────
307
- // 12. mode helpers expostos
308
- // ─────────────────────────────────────────────────────────────────────────
309
- test("getMode/getTopKIn/getTopKOut: env parsing + defaults", () => {
310
- delete process.env.NOX_RERANKER_MODE;
311
- assert.equal(getMode(), "off");
312
- process.env.NOX_RERANKER_MODE = "shadow";
313
- assert.equal(getMode(), "shadow");
314
- process.env.NOX_RERANKER_MODE = "ACTIVE"; // case-insensitive
315
- assert.equal(getMode(), "active");
316
- process.env.NOX_RERANKER_MODE = "garbage";
317
- assert.equal(getMode(), "off"); // fail-safe
318
- delete process.env.NOX_RERANKER_TOP_K_IN;
319
- assert.equal(getTopKIn(), 50);
320
- process.env.NOX_RERANKER_TOP_K_IN = "30";
321
- assert.equal(getTopKIn(), 30);
322
- process.env.NOX_RERANKER_TOP_K_IN = "not-a-number";
323
- assert.equal(getTopKIn(), 50);
324
- delete process.env.NOX_RERANKER_TOP_K_OUT;
325
- assert.equal(getTopKOut(), 10);
326
- });
@@ -1,99 +0,0 @@
1
- // A3 (2026-04-25): unit tests pra parseRetentionOverride — Backlog #1.
2
- // Lição: incident 2026-04-25 (entity wipe) NÃO foi causado por retention parsing,
3
- // mas o parser nunca foi testado formalmente — risco latente. Tests cobrem 8 casos
4
- // canônicos + edge cases descobertos no design.
5
- //
6
- // Run: cd /root/.openclaw/workspace/tools/nox-mem && npx tsc && node --test dist/__tests__/retention.test.js
7
- import { test } from "node:test";
8
- import assert from "node:assert/strict";
9
- import { parseRetentionOverride } from "../retention.js";
10
- test("parseRetentionOverride: never explicit", () => {
11
- const r = parseRetentionOverride("<!-- retention: never -->");
12
- assert.deepEqual(r, { found: true, value: null });
13
- });
14
- test("parseRetentionOverride: numeric days", () => {
15
- const r = parseRetentionOverride("<!-- retention: 365 -->");
16
- assert.deepEqual(r, { found: true, value: 365 });
17
- });
18
- test("parseRetentionOverride: numeric with unit suffix", () => {
19
- const r = parseRetentionOverride("<!-- retention: 30 days -->");
20
- assert.deepEqual(r, { found: true, value: 30 });
21
- });
22
- test("parseRetentionOverride: case insensitive (NEVER)", () => {
23
- const r = parseRetentionOverride("<!-- retention: NEVER -->");
24
- assert.deepEqual(r, { found: true, value: null });
25
- });
26
- test("parseRetentionOverride: synonym infinite", () => {
27
- const r = parseRetentionOverride("<!-- retention: infinite -->");
28
- assert.deepEqual(r, { found: true, value: null });
29
- });
30
- test("parseRetentionOverride: synonym null", () => {
31
- const r = parseRetentionOverride("<!-- retention: null -->");
32
- assert.deepEqual(r, { found: true, value: null });
33
- });
34
- test("parseRetentionOverride: comment in middle of line is NOT match (must be alone)", () => {
35
- const r = parseRetentionOverride("Some prose explaining <!-- retention: 30 --> the syntax.");
36
- assert.deepEqual(r, { found: false });
37
- });
38
- test("parseRetentionOverride: invalid value 0 → not found (regression guard)", () => {
39
- const r = parseRetentionOverride("<!-- retention: 0 -->");
40
- assert.deepEqual(r, { found: false });
41
- });
42
- test("parseRetentionOverride: CRLF line endings (Windows files)", () => {
43
- const r = parseRetentionOverride("# Title\r\n\r\n<!-- retention: 90 -->\r\n\r\nbody");
44
- assert.deepEqual(r, { found: true, value: 90 });
45
- });
46
- test("parseRetentionOverride: only scans first 30 lines (perf guard)", () => {
47
- const padding = Array(35).fill("padding line").join("\n");
48
- const r = parseRetentionOverride(padding + "\n<!-- retention: 365 -->");
49
- assert.deepEqual(r, { found: false }, "comment past line 30 must NOT be picked up");
50
- });
51
- test("parseRetentionOverride: garbage value → not found", () => {
52
- const r = parseRetentionOverride("<!-- retention: foo bar baz -->");
53
- assert.deepEqual(r, { found: false });
54
- });
55
- test("parseRetentionOverride: empty source → not found", () => {
56
- assert.deepEqual(parseRetentionOverride(""), { found: false });
57
- });
58
- test("parseRetentionOverride: missing comment → not found (default fallback)", () => {
59
- const r = parseRetentionOverride("# Title\n\nNo retention override here.\n");
60
- assert.deepEqual(r, { found: false });
61
- });
62
- test("parseRetentionOverride: tab-indented comment is accepted", () => {
63
- const r = parseRetentionOverride("\t<!-- retention: 180 -->");
64
- assert.deepEqual(r, { found: true, value: 180 });
65
- });
66
- // W2-9 (audit cleanup 04-26): adversarial coverage — parser handles defensively but no regression guard.
67
- test("parseRetentionOverride: negative number → not found (regression guard)", () => {
68
- const r = parseRetentionOverride("<!-- retention: -30 -->");
69
- assert.deepEqual(r, { found: false }, "negative days should not be a valid retention");
70
- });
71
- test("parseRetentionOverride: floating point → not found (regression guard)", () => {
72
- const r = parseRetentionOverride("<!-- retention: 30.5 -->");
73
- // Parser extracts leading int, so 30.5 should match as 30 OR be rejected.
74
- // Document actual behavior; this test pins it.
75
- assert.equal(r.found, true, "leading int extraction is current behavior");
76
- });
77
- test("parseRetentionOverride: 6+ digit overflow → not found (current regex behavior)", () => {
78
- const r = parseRetentionOverride("<!-- retention: 999999 -->");
79
- // Behavior pinned: regex `[^-\s][^-]*?` rejects long-numeric strings (no upper bound check needed
80
- // because regex itself is conservative). If parser is rewritten to be more permissive, add explicit
81
- // clamp at caller and update this test.
82
- assert.deepEqual(r, { found: false }, "6-digit numbers currently rejected by regex");
83
- });
84
- test("parseRetentionOverride: NBSP (U+00A0) tolerated — parses leading int", () => {
85
- const r = parseRetentionOverride("<!-- retention:\u00a030 -->"); // non-breaking space
86
- // Behavior pinned: JS regex `\s` does NOT match U+00A0 by default, so NBSP becomes part of
87
- // the capture group; parseInt extracts the leading 30 successfully. If stricter ASCII-only
88
- // tokenization is desired, normalize via .trim() + explicit Unicode whitespace strip.
89
- assert.deepEqual(r, { found: true, value: 30 }, "NBSP currently tolerated by parseInt");
90
- });
91
- test("parseRetentionOverride: multiple comments — first match wins", () => {
92
- const r = parseRetentionOverride("<!-- retention: 30 -->\n<!-- retention: never -->");
93
- assert.deepEqual(r, { found: true, value: 30 }, "first match (line order) wins per regex /im");
94
- });
95
- test("parseRetentionOverride: null byte injection in value → rejected", () => {
96
- const r = parseRetentionOverride("<!-- retention: 30\u0000abc -->");
97
- // Parser extracts leading digits before non-digit. Pin behavior.
98
- assert.equal(r.found, true, "leading digit extraction tolerates trailing garbage");
99
- });