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
|
@@ -1,130 +0,0 @@
|
|
|
1
|
-
// E2E test (W2-extra 2026-04-26): _reindexImpl + withOpAudit integration.
|
|
2
|
-
// Lição: bug B2 (closeDb mid-function) escapou do audit duplo porque smoke só cobriu
|
|
3
|
-
// happy-path standalone. Este test exercita a integração que levou ao bug:
|
|
4
|
-
// withOpAudit wrappa fn() que muta DB usando o MESMO singleton — qualquer closeDb
|
|
5
|
-
// mid-op invalida o handle de UPDATE final → row stuck running.
|
|
6
|
-
//
|
|
7
|
-
// Run: cd /root/.openclaw/workspace/tools/nox-mem && npx tsc &&
|
|
8
|
-
// node --test dist/__tests__/op-audit-e2e.test.js
|
|
9
|
-
//
|
|
10
|
-
// IMPORTANT: este test usa NOX_DB_PATH temp em /var/backups/nox-mem-test/ (allowlist OK).
|
|
11
|
-
// Snapshot dir override via NOX_PRE_OP_SNAPSHOT_DIR também em /var/backups/nox-mem-test/.
|
|
12
|
-
import { test, before, after } from "node:test";
|
|
13
|
-
import assert from "node:assert/strict";
|
|
14
|
-
import { mkdtempSync, rmSync, existsSync, readdirSync, realpathSync } from "node:fs";
|
|
15
|
-
import { join } from "node:path";
|
|
16
|
-
import { tmpdir } from "node:os";
|
|
17
|
-
const TMP_ROOT = realpathSync(mkdtempSync(join(process.env.NOX_TEST_TMP_ROOT || tmpdir(), "nox-mem-test-")));
|
|
18
|
-
const TEST_DB = join(TMP_ROOT, "test.db");
|
|
19
|
-
const TEST_SNAP_DIR = join(TMP_ROOT, "snapshots");
|
|
20
|
-
// Set env BEFORE importing op-audit (module-load validation reads NOX_DB_PATH).
|
|
21
|
-
process.env.NOX_DB_PATH = TEST_DB;
|
|
22
|
-
process.env.NOX_PRE_OP_SNAPSHOT_DIR = TEST_SNAP_DIR;
|
|
23
|
-
// Fix 2026-05-01: setupDb não pode pré-criar tabela chunks com schema v1 minimal porque
|
|
24
|
-
// conflita com migrations cumulativas (source_date, pain, section, etc adicionados em v3+).
|
|
25
|
-
// Em vez disso, deixar ensureSchema (em db.ts.getDb) construir schema v10 completo via NOX_DB_PATH override.
|
|
26
|
-
const setupDb = async () => {
|
|
27
|
-
const { getDb, closeDb } = await import("../db.js");
|
|
28
|
-
const db = getDb();
|
|
29
|
-
db.exec(`
|
|
30
|
-
INSERT INTO chunks (source_file, chunk_text, chunk_type, tier, access_count, importance)
|
|
31
|
-
VALUES
|
|
32
|
-
('memory/test.md', 'sample chunk text 1', 'daily', 'core', 5, 0.8),
|
|
33
|
-
('memory/test.md', 'sample chunk text 2', 'daily', 'peripheral', 0, 0.5);
|
|
34
|
-
`);
|
|
35
|
-
closeDb();
|
|
36
|
-
};
|
|
37
|
-
before(async () => {
|
|
38
|
-
await setupDb();
|
|
39
|
-
});
|
|
40
|
-
after(() => {
|
|
41
|
-
// Cleanup: rmSync recursive remove temp dir + snapshots
|
|
42
|
-
try {
|
|
43
|
-
rmSync(TMP_ROOT, { recursive: true, force: true });
|
|
44
|
-
}
|
|
45
|
-
catch { /* best-effort */ }
|
|
46
|
-
});
|
|
47
|
-
test("E2E: withOpAudit success path — INSERT row, fn runs, UPDATE final fires", async () => {
|
|
48
|
-
// Reset singleton (db.ts) and lib state via dynamic import after env set
|
|
49
|
-
const opAudit = await import("../lib/op-audit.js");
|
|
50
|
-
const { getDb, closeDb } = await import("../db.js");
|
|
51
|
-
const result = await opAudit.withOpAudit("test-success", async () => {
|
|
52
|
-
const db = getDb();
|
|
53
|
-
const inserted = db.prepare("INSERT INTO chunks (source_file, chunk_text, chunk_type) VALUES (?, ?, ?)").run("e2e/added.md", "added by e2e", "test");
|
|
54
|
-
return { affected_rows: Number(inserted.changes), notes: "e2e success path" };
|
|
55
|
-
});
|
|
56
|
-
assert.equal(result.affected_rows, 1);
|
|
57
|
-
// Verify ops_audit row was INSERTED then UPDATED to status='success'
|
|
58
|
-
const db = getDb();
|
|
59
|
-
const row = db.prepare("SELECT op_name, status, affected_rows, snapshot_path, snapshot_bytes, schema_user_version, pid, error_message FROM ops_audit WHERE op_name = ?").get("test-success");
|
|
60
|
-
assert.ok(row, "ops_audit row exists");
|
|
61
|
-
assert.equal(row.status, "success", "status should be success");
|
|
62
|
-
assert.equal(row.affected_rows, 1);
|
|
63
|
-
assert.ok(row.snapshot_path && typeof row.snapshot_path === "string" && row.snapshot_path.length > 0, "snapshot_path populated");
|
|
64
|
-
assert.ok(typeof row.snapshot_bytes === "number" && row.snapshot_bytes > 0, "snapshot_bytes populated");
|
|
65
|
-
assert.equal(row.error_message, null, "no error on success path");
|
|
66
|
-
// Verify snapshot file actually exists on disk
|
|
67
|
-
assert.ok(existsSync(row.snapshot_path), "snapshot file on disk");
|
|
68
|
-
closeDb();
|
|
69
|
-
});
|
|
70
|
-
test("E2E: withOpAudit failure path — row marked failed, snapshot preserved", async () => {
|
|
71
|
-
const opAudit = await import("../lib/op-audit.js");
|
|
72
|
-
const { getDb, closeDb } = await import("../db.js");
|
|
73
|
-
await assert.rejects(opAudit.withOpAudit("test-failure", async () => {
|
|
74
|
-
throw new Error("intentional e2e failure");
|
|
75
|
-
}), /intentional e2e failure/, "withOpAudit propagates fn error");
|
|
76
|
-
const db = getDb();
|
|
77
|
-
const row = db.prepare("SELECT status, error_message, snapshot_path FROM ops_audit WHERE op_name = ?").get("test-failure");
|
|
78
|
-
assert.ok(row, "failure row exists");
|
|
79
|
-
assert.equal(row.status, "failed");
|
|
80
|
-
assert.match(row.error_message, /intentional e2e failure/);
|
|
81
|
-
assert.ok(existsSync(row.snapshot_path), "snapshot preserved on failure (recovery path)");
|
|
82
|
-
closeDb();
|
|
83
|
-
});
|
|
84
|
-
test("E2E REGRESSION GUARD (B2): closeDb mid-op throws, fail-loud not silent", async () => {
|
|
85
|
-
// This test catches the B2 bug class: if anyone adds closeDb() inside an op wrapped by
|
|
86
|
-
// withOpAudit, the final UPDATE on ops_audit must FAIL LOUD (throw), not silently leave
|
|
87
|
-
// the row stuck in 'running' state. Fix B2 (2026-04-26) removed mid-op closeDb from
|
|
88
|
-
// _reindexImpl; this test ensures the wrapper itself reacts correctly if a future caller
|
|
89
|
-
// re-introduces the anti-pattern.
|
|
90
|
-
const opAudit = await import("../lib/op-audit.js");
|
|
91
|
-
const { getDb, closeDb } = await import("../db.js");
|
|
92
|
-
// Simulate the B2 anti-pattern: fn() calls closeDb() mid-op. The expected behavior is
|
|
93
|
-
// that withOpAudit's UPDATE final throws (DB closed) — propagating loudly.
|
|
94
|
-
await assert.rejects(opAudit.withOpAudit("test-b2-regression", async () => {
|
|
95
|
-
const db = getDb();
|
|
96
|
-
db.prepare("INSERT INTO chunks (source_file, chunk_text, chunk_type) VALUES (?, ?, ?)").run("b2/test.md", "before close", "test");
|
|
97
|
-
closeDb(); // anti-pattern
|
|
98
|
-
return { affected_rows: 1, notes: "b2 anti-pattern" };
|
|
99
|
-
}), /database connection is not open|closed/i, "withOpAudit must surface the closed-DB error, not silently leave row in 'running'");
|
|
100
|
-
closeDb();
|
|
101
|
-
});
|
|
102
|
-
test("E2E: opFn returning undefined throws (W2-11 validation)", async () => {
|
|
103
|
-
const opAudit = await import("../lib/op-audit.js");
|
|
104
|
-
const { closeDb } = await import("../db.js");
|
|
105
|
-
await assert.rejects(
|
|
106
|
-
// @ts-expect-error testing runtime check intentionally
|
|
107
|
-
opAudit.withOpAudit("test-bad-fn", async () => undefined), /opFn must return OpResult object/, "type validation throws");
|
|
108
|
-
closeDb();
|
|
109
|
-
});
|
|
110
|
-
test("E2E: snapshot path enforces ALLOWED_PREFIXES (SEC HIGH #2 + W2-2)", async () => {
|
|
111
|
-
// Validates that getValidatedSnapshotDir + DB_PATH module-load both honor allowlist.
|
|
112
|
-
// Module already loaded with valid paths; just sanity check structural invariants.
|
|
113
|
-
const snapshots = readdirSync(TEST_SNAP_DIR);
|
|
114
|
-
for (const f of snapshots) {
|
|
115
|
-
assert.ok(f.match(/^test-[a-z0-9-]+-\d{14}-\d+-[a-f0-9]{32}\.db$/), `snapshot filename matches new full-uuid format: ${f}`);
|
|
116
|
-
}
|
|
117
|
-
});
|
|
118
|
-
test("E2E: ops_audit append-only — DELETE blocked (W2-1 trigger)", async () => {
|
|
119
|
-
const { getDb, closeDb } = await import("../db.js");
|
|
120
|
-
const db = getDb();
|
|
121
|
-
assert.throws(() => db.prepare("DELETE FROM ops_audit WHERE id IN (SELECT id FROM ops_audit LIMIT 1)").run(), /append-only/i, "DELETE on ops_audit must be blocked");
|
|
122
|
-
closeDb();
|
|
123
|
-
});
|
|
124
|
-
test("E2E: ops_audit append-only — UPDATE on terminal row blocked (W2-1 trigger)", async () => {
|
|
125
|
-
const { getDb, closeDb } = await import("../db.js");
|
|
126
|
-
const db = getDb();
|
|
127
|
-
// First success op above set status='success'. Try to tamper.
|
|
128
|
-
assert.throws(() => db.prepare("UPDATE ops_audit SET notes = 'tampered' WHERE status = 'success'").run(), /immutable/i, "UPDATE on terminal-status row must be blocked");
|
|
129
|
-
closeDb();
|
|
130
|
-
});
|
|
@@ -1,123 +0,0 @@
|
|
|
1
|
-
// Regression tests (2026-05-02 audit follow-up): cobre 3 bugs da sessão 2026-05-01:
|
|
2
|
-
// #1 NOX_DB_PATH precedence (db.ts honra env > OPENCLAW_WORKSPACE > __dirname)
|
|
3
|
-
// #2 PRAGMA user_version idempotente + alinhado com meta.schema_version (ensureSchema patch)
|
|
4
|
-
// #3 trg_chunks_delete_cascade limpa vec_chunks/vec_chunk_map em DELETE
|
|
5
|
-
//
|
|
6
|
-
// Run: cd /root/.openclaw/workspace/tools/nox-mem && npx tsc &&
|
|
7
|
-
// node --test dist/__tests__/pragma-alignment.test.js
|
|
8
|
-
import { test, before, after } from "node:test";
|
|
9
|
-
import assert from "node:assert/strict";
|
|
10
|
-
import { mkdtempSync, rmSync, existsSync } from "node:fs";
|
|
11
|
-
import { join } from "node:path";
|
|
12
|
-
import { tmpdir } from "node:os";
|
|
13
|
-
const TMP_ROOT = mkdtempSync(join(process.env.NOX_TEST_TMP_ROOT || tmpdir(), "nox-mem-pragma-test-"));
|
|
14
|
-
const TEST_DB = join(TMP_ROOT, "test.db");
|
|
15
|
-
// Set BEFORE importing db (module-load reads env).
|
|
16
|
-
process.env.NOX_DB_PATH = TEST_DB;
|
|
17
|
-
let getDb;
|
|
18
|
-
let closeDb;
|
|
19
|
-
let SCHEMA_VERSION;
|
|
20
|
-
before(async () => {
|
|
21
|
-
const dbModule = await import("../db.js");
|
|
22
|
-
getDb = dbModule.getDb;
|
|
23
|
-
closeDb = dbModule.closeDb;
|
|
24
|
-
// SCHEMA_VERSION not exported — derive from a fresh ensureSchema run
|
|
25
|
-
const db = getDb();
|
|
26
|
-
const row = db.prepare("SELECT value FROM meta WHERE key = 'schema_version'").get();
|
|
27
|
-
SCHEMA_VERSION = parseInt(row.value, 10);
|
|
28
|
-
closeDb();
|
|
29
|
-
});
|
|
30
|
-
after(() => {
|
|
31
|
-
try {
|
|
32
|
-
closeDb();
|
|
33
|
-
}
|
|
34
|
-
catch { /* ignore */ }
|
|
35
|
-
rmSync(TMP_ROOT, { recursive: true, force: true });
|
|
36
|
-
});
|
|
37
|
-
// ─────────────────────────────────────────────────────────────────────
|
|
38
|
-
// #1 NOX_DB_PATH precedence
|
|
39
|
-
// ─────────────────────────────────────────────────────────────────────
|
|
40
|
-
test("NOX_DB_PATH env honored over OPENCLAW_WORKSPACE", () => {
|
|
41
|
-
closeDb();
|
|
42
|
-
const db = getDb();
|
|
43
|
-
// DB created at NOX_DB_PATH path?
|
|
44
|
-
assert.ok(existsSync(TEST_DB), `DB not created at NOX_DB_PATH=${TEST_DB}`);
|
|
45
|
-
// Sanity: schema is built (meta table exists)
|
|
46
|
-
const tables = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='meta'").get();
|
|
47
|
-
assert.ok(tables, "meta table missing — ensureSchema did not run");
|
|
48
|
-
closeDb();
|
|
49
|
-
});
|
|
50
|
-
// ─────────────────────────────────────────────────────────────────────
|
|
51
|
-
// #2 PRAGMA user_version aligned + idempotent
|
|
52
|
-
// ─────────────────────────────────────────────────────────────────────
|
|
53
|
-
test("PRAGMA user_version equals meta.schema_version after ensureSchema", () => {
|
|
54
|
-
const db = getDb();
|
|
55
|
-
const pragma = db.prepare("PRAGMA user_version").get();
|
|
56
|
-
const meta = db.prepare("SELECT value FROM meta WHERE key='schema_version'").get();
|
|
57
|
-
assert.equal(pragma.user_version, parseInt(meta.value, 10), `PRAGMA user_version=${pragma.user_version} != meta.schema_version=${meta.value}`);
|
|
58
|
-
assert.equal(pragma.user_version, SCHEMA_VERSION, `PRAGMA != SCHEMA_VERSION constant`);
|
|
59
|
-
closeDb();
|
|
60
|
-
});
|
|
61
|
-
test("PRAGMA user_version stable across re-open (idempotent)", () => {
|
|
62
|
-
const db1 = getDb();
|
|
63
|
-
const v1 = db1.prepare("PRAGMA user_version").get().user_version;
|
|
64
|
-
closeDb();
|
|
65
|
-
const db2 = getDb();
|
|
66
|
-
const v2 = db2.prepare("PRAGMA user_version").get().user_version;
|
|
67
|
-
assert.equal(v1, v2, `PRAGMA drifted between opens: ${v1} → ${v2}`);
|
|
68
|
-
assert.notEqual(v1, 0, `PRAGMA user_version=0 — bug regressed (ensureSchema did not bump)`);
|
|
69
|
-
closeDb();
|
|
70
|
-
});
|
|
71
|
-
test("PRAGMA user_version reflects bump after manual override (recovery scenario)", () => {
|
|
72
|
-
const db = getDb();
|
|
73
|
-
// Simulate the 2026-05-01 bug: manually set PRAGMA to 0 (legacy DB scenario)
|
|
74
|
-
db.exec("PRAGMA user_version = 0");
|
|
75
|
-
const before = db.prepare("PRAGMA user_version").get().user_version;
|
|
76
|
-
assert.equal(before, 0, "test setup failed");
|
|
77
|
-
closeDb();
|
|
78
|
-
// Re-open triggers ensureSchema which should re-bump
|
|
79
|
-
const db2 = getDb();
|
|
80
|
-
const after = db2.prepare("PRAGMA user_version").get().user_version;
|
|
81
|
-
assert.equal(after, SCHEMA_VERSION, `ensureSchema did not re-align PRAGMA after manual reset`);
|
|
82
|
-
closeDb();
|
|
83
|
-
});
|
|
84
|
-
// ─────────────────────────────────────────────────────────────────────
|
|
85
|
-
// #3 trg_chunks_delete_cascade clears vec tables
|
|
86
|
-
// ─────────────────────────────────────────────────────────────────────
|
|
87
|
-
test("trg_chunks_delete_cascade trigger exists (skipped if vec0 ext absent)", (t) => {
|
|
88
|
-
const db = getDb();
|
|
89
|
-
const trg = db.prepare("SELECT name FROM sqlite_master WHERE type='trigger' AND name='trg_chunks_delete_cascade'").get();
|
|
90
|
-
if (!trg) {
|
|
91
|
-
// Trigger is created at runtime when vec0 extension loads.
|
|
92
|
-
// Test DB without vec0 ext won't have it — skip rather than false-fail.
|
|
93
|
-
closeDb();
|
|
94
|
-
t.skip("trigger created runtime via vec0 ext — not present in test DB");
|
|
95
|
-
return;
|
|
96
|
-
}
|
|
97
|
-
assert.ok(trg);
|
|
98
|
-
closeDb();
|
|
99
|
-
});
|
|
100
|
-
test("DELETE chunk cleans vec_chunk_map entry (cascade)", () => {
|
|
101
|
-
const db = getDb();
|
|
102
|
-
// Insert minimal chunk
|
|
103
|
-
const insert = db.prepare("INSERT INTO chunks (source_file, chunk_text, chunk_type) VALUES (?, ?, ?)");
|
|
104
|
-
const result = insert.run("/tmp/test-cascade.md", "test content for cascade", "test");
|
|
105
|
-
const chunkId = result.lastInsertRowid;
|
|
106
|
-
// Insert mock vec_chunk_map row (skip vec_chunks INSERT — requires vec0 ext)
|
|
107
|
-
try {
|
|
108
|
-
db.prepare("INSERT INTO vec_chunk_map (chunk_id, vec_id) VALUES (?, ?)").run(chunkId, 999);
|
|
109
|
-
}
|
|
110
|
-
catch (e) {
|
|
111
|
-
// vec_chunk_map may not exist in test DB if vec0 ext not loaded — skip gracefully
|
|
112
|
-
if (e.message.includes("no such table")) {
|
|
113
|
-
closeDb();
|
|
114
|
-
return; // test passes (table absent in test env, prod has it)
|
|
115
|
-
}
|
|
116
|
-
throw e;
|
|
117
|
-
}
|
|
118
|
-
// Delete chunk → trigger should cascade
|
|
119
|
-
db.prepare("DELETE FROM chunks WHERE id = ?").run(chunkId);
|
|
120
|
-
const orphan = db.prepare("SELECT chunk_id FROM vec_chunk_map WHERE chunk_id = ?").get(chunkId);
|
|
121
|
-
assert.equal(orphan, undefined, `vec_chunk_map row not cleaned for chunk_id=${chunkId} — cascade trigger broken`);
|
|
122
|
-
closeDb();
|
|
123
|
-
});
|
|
@@ -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
|
-
});
|