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.
Files changed (66) hide show
  1. package/README.md +82 -31
  2. package/dist/api/answer.js +22 -0
  3. package/dist/api-server.js +22 -3
  4. package/dist/cli/answer.js +39 -1
  5. package/dist/db.js +47 -24
  6. package/dist/doctor.js +108 -29
  7. package/dist/embed.js +53 -3
  8. package/dist/index.js +73 -17
  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/dates.js +98 -0
  14. package/dist/lib/db-path.js +57 -0
  15. package/dist/lib/ingest-many.js +49 -0
  16. package/dist/lib/op-audit.js +19 -12
  17. package/dist/lib/reranker.js +4 -1
  18. package/dist/mcp/tools/answer.js +23 -0
  19. package/dist/mcp-server.js +45 -6
  20. package/dist/reflect.js +2 -2
  21. package/dist/reindex-errors.js +45 -0
  22. package/dist/reindex.js +116 -23
  23. package/dist/search.js +111 -16
  24. package/package.json +7 -2
  25. package/prompts/consolidate.txt +13 -0
  26. package/prompts/digest.txt +5 -0
  27. package/dist/__tests__/brief-diversity.test.js +0 -266
  28. package/dist/__tests__/brief.test.js +0 -287
  29. package/dist/__tests__/churn.test.js +0 -66
  30. package/dist/__tests__/edge-typing.test.js +0 -99
  31. package/dist/__tests__/ingest-event.test.js +0 -151
  32. package/dist/__tests__/op-audit-e2e.test.js +0 -130
  33. package/dist/__tests__/pragma-alignment.test.js +0 -123
  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/lib/answer/__tests__/e2e-gemini.test.js +0 -229
  42. package/dist/lib/answer/__tests__/integration-sqlite.test.js +0 -388
  43. package/dist/lib/answer/__tests__/integration.test.js +0 -347
  44. package/dist/lib/answer/__tests__/prompt.test.js +0 -117
  45. package/dist/lib/answer/__tests__/t5-t10.test.js +0 -501
  46. package/dist/lib/api/__tests__/safe-error-message.test.js +0 -155
  47. package/dist/lib/auth/__tests__/localhost-guard.test.js +0 -144
  48. package/dist/lib/error-sanitizer/__tests__/sanitize.test.js +0 -354
  49. package/dist/lib/events/__tests__/bus.test.js +0 -208
  50. package/dist/lib/op-audit-extension/__tests__/ran-at-guard.test.js +0 -109
  51. package/dist/lib/regex-extract/__tests__/extractor.test.js +0 -197
  52. package/dist/lib/regex-extract/__tests__/frontmatter.test.js +0 -75
  53. package/dist/lib/regex-extract/__tests__/ingest-router-l4.test.js +0 -139
  54. package/dist/lib/regex-extract/__tests__/production-wire.test.js +0 -177
  55. package/dist/lib/regex-extract/__tests__/reconcile.test.js +0 -170
  56. package/dist/lib/regex-extract/__tests__/strip-code.test.js +0 -36
  57. package/dist/privacy/__tests__/filter.test.js +0 -352
  58. package/dist/providers/__tests__/conformance-extended.test.js +0 -249
  59. package/dist/providers/__tests__/conformance.test.js +0 -98
  60. package/dist/providers/__tests__/cost-cap.test.js +0 -151
  61. package/dist/providers/__tests__/e2e-real.test.js +0 -79
  62. package/dist/providers/__tests__/factory.test.js +0 -80
  63. package/dist/providers/__tests__/fallback.test.js +0 -223
  64. package/dist/providers/__tests__/gemini.test.js +0 -191
  65. package/dist/providers/__tests__/health.test.js +0 -128
  66. package/dist/providers/__tests__/telemetry.test.js +0 -219
@@ -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
- });
@@ -1,49 +0,0 @@
1
- // D1 — canary access_count contamination fix (2026-06-07).
2
- // O healthcheck semantic-canary roda /api/search 2×/h e, via searchHybrid,
3
- // incrementava access_count de dezenas de chunks por chamada — inflando a
4
- // salience de um punhado de chunks (feedback loop). recordAccess() agora
5
- // respeita um flag `enabled`; healthchecks passam enabled=false.
6
- //
7
- // Run: cd tools/nox-mem && npx tsc && node --test dist/__tests__/search-track-access.test.js
8
- import { test } from "node:test";
9
- import assert from "node:assert/strict";
10
- import Database from "better-sqlite3";
11
- import { _internals } from "../search.js";
12
- function makeDb() {
13
- const db = new Database(":memory:");
14
- db.exec(`
15
- CREATE TABLE chunks (
16
- id INTEGER PRIMARY KEY,
17
- access_count INTEGER DEFAULT 0,
18
- last_accessed_at TEXT
19
- );
20
- INSERT INTO chunks (id, access_count) VALUES (1, 0), (2, 5), (3, 0);
21
- `);
22
- return db;
23
- }
24
- test("recordAccess: enabled=false não toca access_count nem last_accessed_at", () => {
25
- const db = makeDb();
26
- _internals.recordAccess(db, [1, 2, 3], false);
27
- const rows = db.prepare("SELECT id, access_count, last_accessed_at FROM chunks ORDER BY id").all();
28
- assert.deepEqual(rows.map((r) => r.access_count), [0, 5, 0]);
29
- assert.ok(rows.every((r) => r.last_accessed_at === null));
30
- db.close();
31
- });
32
- test("recordAccess: enabled=true incrementa apenas os ids dados (preserva default)", () => {
33
- const db = makeDb();
34
- _internals.recordAccess(db, [1, 3], true);
35
- const rows = db.prepare("SELECT id, access_count, last_accessed_at FROM chunks ORDER BY id").all();
36
- assert.deepEqual(rows.map((r) => r.access_count), [1, 5, 1]); // id=2 intocado
37
- assert.notEqual(rows[0].last_accessed_at, null);
38
- assert.equal(rows[1].last_accessed_at, null);
39
- assert.notEqual(rows[2].last_accessed_at, null);
40
- db.close();
41
- });
42
- test("recordAccess: ids vazios / undefined é no-op seguro", () => {
43
- const db = makeDb();
44
- _internals.recordAccess(db, [], true);
45
- _internals.recordAccess(db, [undefined, undefined], true);
46
- const rows = db.prepare("SELECT access_count FROM chunks ORDER BY id").all();
47
- assert.deepEqual(rows.map((r) => r.access_count), [0, 5, 0]);
48
- db.close();
49
- });
@@ -1,98 +0,0 @@
1
- // Guards for the two things a VPS migration moved at once: WHERE agent session
2
- // transcripts live, and WHAT SHAPE they have. Both failures are silent — the
3
- // old path simply reports "No unprocessed sessions found" with exit 0, and the
4
- // old schema check drops every line of a Claude CLI transcript without an
5
- // error. One deployment ran 28 days that way with its cron marked "ok".
6
- //
7
- // Run: npx tsc && node --test dist/__tests__/session-distill-sources.test.js
8
- import { test } from "node:test";
9
- import assert from "node:assert/strict";
10
- import { mkdtempSync, writeFileSync } from "node:fs";
11
- import { tmpdir } from "node:os";
12
- import { resolve } from "node:path";
13
- import { claudeProjectSlug, claudeProjectsDirs, sessionDirsFor, extractMessages, } from "../session-distill.js";
14
- function writeTranscript(lines) {
15
- const dir = mkdtempSync(resolve(tmpdir(), "nox-distill-"));
16
- const file = resolve(dir, "session.jsonl");
17
- writeFileSync(file, lines.map((l) => JSON.stringify(l)).join("\n"), "utf-8");
18
- return file;
19
- }
20
- const CLI_LINES = [
21
- { type: "queue-operation", op: "enqueue" },
22
- { type: "attachment", path: "/tmp/x.png" },
23
- { type: "user", message: { role: "user", content: "por que o distill parou de rodar" } },
24
- {
25
- type: "assistant",
26
- message: {
27
- role: "assistant",
28
- content: [
29
- { type: "text", text: "porque as sessoes mudaram de endereco" },
30
- { type: "tool_use", name: "Bash", input: {} },
31
- ],
32
- },
33
- },
34
- ];
35
- test("Claude CLI transcripts (type user/assistant) are read", () => {
36
- const msgs = extractMessages(writeTranscript(CLI_LINES));
37
- assert.equal(msgs.length, 2, "both turns must survive");
38
- assert.deepEqual(msgs.map((m) => m.role), ["user", "assistant"]);
39
- // Only the text part is kept; tool_use carries no prose to distill.
40
- assert.equal(msgs[1].text, "porque as sessoes mudaram de endereco");
41
- });
42
- test("legacy OpenClaw transcripts (type message) still are read", () => {
43
- const msgs = extractMessages(writeTranscript([
44
- { type: "message", message: { role: "user", content: "pergunta legada" } },
45
- { type: "message", message: { role: "assistant", content: "resposta legada" } },
46
- ]));
47
- assert.equal(msgs.length, 2);
48
- });
49
- test("unknown event types and heartbeat noise stay out", () => {
50
- const msgs = extractMessages(writeTranscript([
51
- { type: "summary", message: { role: "user", content: "nao e um turno de conversa" } },
52
- { type: "user", message: { role: "user", content: "HEARTBEAT_OK" } },
53
- { type: "user", message: { role: "user", content: "[cron:eod] disparo" } },
54
- { type: "user", message: { role: "user", content: "ok" } },
55
- { type: "user", content: "sem o campo message" },
56
- ]));
57
- assert.equal(msgs.length, 0);
58
- });
59
- test("slug derivation matches the Claude CLI layout", () => {
60
- // The CLI replaces both "/" and "." with "-", so the leading slash and the
61
- // dotted dir collapse into the doubled dash seen on disk.
62
- assert.equal(claudeProjectSlug("/root/.openclaw/workspace"), "-root--openclaw-workspace");
63
- assert.equal(claudeProjectSlug("/root/.openclaw/workspace/agents/forge"), "-root--openclaw-workspace-agents-forge");
64
- });
65
- test("an explicit NOX_CLAUDE_PROJECTS_DIR wins over discovery", () => {
66
- const prev = process.env.NOX_CLAUDE_PROJECTS_DIR;
67
- process.env.NOX_CLAUDE_PROJECTS_DIR = "/somewhere/projects";
68
- try {
69
- assert.deepEqual(claudeProjectsDirs(), ["/somewhere/projects"]);
70
- const dirs = sessionDirsFor("forge");
71
- // Legacy dir first, then the CLI one — the legacy dir still holds sessions
72
- // predating the switch, so neither may be dropped.
73
- assert.equal(dirs.length, 2);
74
- assert.match(dirs[0], /agents\/forge\/sessions$/);
75
- assert.equal(dirs[1], "/somewhere/projects/-root--openclaw-workspace-agents-forge");
76
- }
77
- finally {
78
- if (prev === undefined)
79
- delete process.env.NOX_CLAUDE_PROJECTS_DIR;
80
- else
81
- process.env.NOX_CLAUDE_PROJECTS_DIR = prev;
82
- }
83
- });
84
- test("the main agent maps to the workspace root, not to agents/main", () => {
85
- const prev = process.env.NOX_CLAUDE_PROJECTS_DIR;
86
- process.env.NOX_CLAUDE_PROJECTS_DIR = "/p";
87
- try {
88
- const cli = sessionDirsFor("main")[1];
89
- assert.equal(cli, "/p/-root--openclaw-workspace");
90
- assert.doesNotMatch(cli, /agents-main/);
91
- }
92
- finally {
93
- if (prev === undefined)
94
- delete process.env.NOX_CLAUDE_PROJECTS_DIR;
95
- else
96
- process.env.NOX_CLAUDE_PROJECTS_DIR = prev;
97
- }
98
- });
@@ -1,172 +0,0 @@
1
- // E03a tests — SPO injection unit tests.
2
- // Run: cd /root/.openclaw/workspace/tools/nox-mem && npx tsc &&
3
- // node --test dist/__tests__/spo-injection.test.js
4
- import { test, before, after } from "node:test";
5
- import assert from "node:assert/strict";
6
- import { mkdtempSync, rmSync } from "node:fs";
7
- import { join } from "node:path";
8
- import { tmpdir } from "node:os";
9
- import Database from "better-sqlite3";
10
- import { extractCandidateEntities, lookupTopK, formatVaultFacts, pickBudget, applyBudget, estimateTokens, getVaultFacts, } from "../lib/spo-injection.js";
11
- // Portable tmpdir — /var/backups is root-only (VPS); os.tmpdir() works on
12
- // Mac/CI/non-root too. Previously this threw EACCES at module load outside the VPS,
13
- // failing the whole file before any test ran.
14
- const TMP_ROOT = mkdtempSync(join(tmpdir(), "nox-mem-spo-test-"));
15
- const TEST_DB = join(TMP_ROOT, "spo-test.db");
16
- let db;
17
- before(() => {
18
- db = new Database(TEST_DB);
19
- db.exec(`
20
- CREATE TABLE kg_entities (
21
- id INTEGER PRIMARY KEY AUTOINCREMENT,
22
- name TEXT NOT NULL,
23
- created_at TEXT DEFAULT (datetime('now'))
24
- );
25
- CREATE TABLE kg_relations (
26
- id INTEGER PRIMARY KEY AUTOINCREMENT,
27
- source_entity_id INTEGER NOT NULL,
28
- relation_type TEXT NOT NULL,
29
- target_entity_id INTEGER NOT NULL,
30
- evidence_chunk_id INTEGER,
31
- confidence REAL DEFAULT 0.8,
32
- relation_reason TEXT DEFAULT "unknown",
33
- created_at TEXT DEFAULT (datetime('now')),
34
- FOREIGN KEY (source_entity_id) REFERENCES kg_entities(id),
35
- FOREIGN KEY (target_entity_id) REFERENCES kg_entities(id)
36
- );
37
- `);
38
- // Seed entities
39
- const insE = db.prepare("INSERT INTO kg_entities (name) VALUES (?)");
40
- const noxId = insE.run("nox-mem").lastInsertRowid;
41
- const totoId = insE.run("Toto").lastInsertRowid;
42
- const geminiId = insE.run("gemini-2.5-flash-lite").lastInsertRowid;
43
- const sqliteId = insE.run("sqlite-vec").lastInsertRowid;
44
- const fts5Id = insE.run("FTS5").lastInsertRowid;
45
- // Seed relations
46
- const insR = db.prepare("INSERT INTO kg_relations (source_entity_id, relation_type, target_entity_id, confidence) VALUES (?, ?, ?, ?)");
47
- insR.run(noxId, "default_model", geminiId, 0.95);
48
- insR.run(noxId, "depends_on", sqliteId, 0.9);
49
- insR.run(noxId, "depends_on", fts5Id, 0.9);
50
- insR.run(totoId, "owns", noxId, 0.85);
51
- insR.run(geminiId, "provider", noxId, null); // null confidence
52
- });
53
- after(() => {
54
- db.close();
55
- rmSync(TMP_ROOT, { recursive: true, force: true });
56
- });
57
- // ─────────────────────────────────────────────────────────────────────
58
- // Cenário 1: extract entities
59
- // ─────────────────────────────────────────────────────────────────────
60
- test("extractCandidateEntities: matches case-insensitive exact tokens", () => {
61
- const ents = extractCandidateEntities("qual modelo do Nox-Mem hoje", db);
62
- assert.deepEqual(ents.sort(), ["nox-mem"]);
63
- });
64
- test("extractCandidateEntities: returns empty when no token matches", () => {
65
- const ents = extractCandidateEntities("xyz totalmente desconhecido", db);
66
- assert.deepEqual(ents, []);
67
- });
68
- test("extractCandidateEntities: skips tokens shorter than 2 chars", () => {
69
- const ents = extractCandidateEntities("a b nox-mem c", db);
70
- assert.deepEqual(ents, ["nox-mem"]);
71
- });
72
- // ─────────────────────────────────────────────────────────────────────
73
- // Cenário 2: lookup top-K with FK JOIN
74
- // ─────────────────────────────────────────────────────────────────────
75
- test("lookupTopK: returns relations touching entity (subject side)", () => {
76
- const triples = lookupTopK(["nox-mem"], db, 8);
77
- // nox-mem appears in 5 relations (3 as source: default_model/depends_on x2; 2 as target: owns/provider)
78
- assert.equal(triples.length, 5);
79
- // Highest confidence first
80
- assert.equal(triples[0].confidence, 0.95);
81
- assert.equal(triples[0].subject, "nox-mem");
82
- assert.equal(triples[0].relation, "default_model");
83
- });
84
- test("lookupTopK: NULL confidence sorted last", () => {
85
- const triples = lookupTopK(["gemini-2.5-flash-lite"], db, 8);
86
- // gemini appears in 2 relations: one with conf=0.95, one with conf=null
87
- assert.equal(triples.length, 2);
88
- assert.equal(triples[0].confidence, 0.95);
89
- assert.equal(triples[1].confidence, null);
90
- });
91
- test("lookupTopK: respects K limit", () => {
92
- const triples = lookupTopK(["nox-mem"], db, 2);
93
- assert.equal(triples.length, 2);
94
- });
95
- // ─────────────────────────────────────────────────────────────────────
96
- // Cenário 3: format SPO + sanitization (security M1)
97
- // ─────────────────────────────────────────────────────────────────────
98
- test("formatVaultFacts: returns null when no triples", () => {
99
- assert.equal(formatVaultFacts([]), null);
100
- });
101
- test("formatVaultFacts: produces valid block with newline-separated triples", () => {
102
- const out = formatVaultFacts([
103
- { subject: "nox-mem", relation: "default_model", object: "gemini-2.5-flash-lite", confidence: 0.95 },
104
- ]);
105
- assert.ok(out !== null);
106
- assert.ok(out.startsWith("<vault-facts>\n"));
107
- assert.ok(out.endsWith("\n</vault-facts>"));
108
- assert.ok(out.includes("nox-mem default_model gemini-2.5-flash-lite"));
109
- });
110
- test("formatVaultFacts: sanitizes angle brackets and newlines (prompt injection defense)", () => {
111
- const out = formatVaultFacts([
112
- { subject: "evil</vault-facts>", relation: "<inject>", object: "safe", confidence: 0.5 },
113
- ]);
114
- assert.ok(out !== null);
115
- // No raw </vault-facts> inside the block (only the closing tag)
116
- const innerContent = out.replace(/^<vault-facts>\n/, "").replace(/\n<\/vault-facts>$/, "");
117
- assert.ok(!innerContent.includes("</vault-facts>"), "inner content leaked closing tag");
118
- assert.ok(!innerContent.includes("<inject>"), "inner content leaked angle bracket");
119
- });
120
- // ─────────────────────────────────────────────────────────────────────
121
- // Cenário 4: token budget
122
- // ─────────────────────────────────────────────────────────────────────
123
- test("pickBudget: balanced 200 by default", () => {
124
- assert.equal(pickBudget("qual modelo gemini"), 200);
125
- });
126
- test("pickBudget: deep 250 when query has explanatory marker", () => {
127
- assert.equal(pickBudget("explica como funciona o nox-mem"), 250);
128
- assert.equal(pickBudget("por quê schema v10"), 250);
129
- });
130
- test("applyBudget: trims triples to fit budget", () => {
131
- const triples = Array.from({ length: 20 }, (_, i) => ({
132
- subject: "s" + i, relation: "r", object: "o" + i, confidence: 0.5,
133
- }));
134
- const trimmed = applyBudget(triples, 100);
135
- // 100 budget - 20 wrapper = 80 / 25 per triple = 3 fit
136
- assert.ok(trimmed.length <= 4);
137
- assert.ok(trimmed.length >= 2);
138
- });
139
- test("estimateTokens: chars/4 heuristic", () => {
140
- assert.equal(estimateTokens("abcd"), 1);
141
- assert.equal(estimateTokens("abcdefgh"), 2);
142
- });
143
- // ─────────────────────────────────────────────────────────────────────
144
- // Cenário 5: getVaultFacts orchestrator + modes
145
- // ─────────────────────────────────────────────────────────────────────
146
- test("getVaultFacts: mode=off returns null block, surface=false", () => {
147
- process.env.NOX_VAULT_FACTS_MODE = "off";
148
- const r = getVaultFacts("qual modelo do nox-mem", db);
149
- assert.equal(r.block, null);
150
- assert.equal(r.surface, false);
151
- assert.equal(r.mode, "off");
152
- });
153
- test("getVaultFacts: mode=shadow computes block but surface=false", () => {
154
- process.env.NOX_VAULT_FACTS_MODE = "shadow";
155
- const r = getVaultFacts("qual modelo do nox-mem", db);
156
- assert.ok(r.block !== null, "block should be computed in shadow");
157
- assert.equal(r.surface, false, "shadow must NOT surface");
158
- assert.ok(r.triples > 0);
159
- });
160
- test("getVaultFacts: mode=active surfaces non-null block", () => {
161
- process.env.NOX_VAULT_FACTS_MODE = "active";
162
- const r = getVaultFacts("qual modelo do nox-mem", db);
163
- assert.ok(r.block !== null);
164
- assert.equal(r.surface, true);
165
- });
166
- test("getVaultFacts: empty query → no entities → block=null", () => {
167
- process.env.NOX_VAULT_FACTS_MODE = "active";
168
- const r = getVaultFacts("xyz desconhecido", db);
169
- assert.equal(r.block, null);
170
- assert.equal(r.surface, false);
171
- assert.equal(r.entities, 0);
172
- });
@@ -1,110 +0,0 @@
1
- // v19 — telemetria por chunk (`top_chunk_ids` / `top_scores`).
2
- //
3
- // Dois grupos de asserção, com propósitos diferentes:
4
- //
5
- // (A) schema — a coluna existe tanto num install limpo quanto num DB legado
6
- // que já estava em v18. Um `ALTER TABLE` só no caminho de migração deixa
7
- // o install limpo sem a coluna; um `CREATE TABLE` só no caminho novo
8
- // deixa o DB existente sem ela. Os dois caminhos são testados separados
9
- // porque falham separado.
10
- //
11
- // (B) privacidade — o INSERT de `search.ts` NÃO pode conter `query_text`.
12
- // Isso não é preferência de estilo: `db.ts` declara, no comentário do v6,
13
- // que "não armazenamos texto cru da query por privacidade". A coluna
14
- // `query_text` existe em alguns DBs por reconciliação de drift de schema,
15
- // e existir não é autorização para escrever. Este teste lê o fonte e
16
- // morde se alguém a reintroduzir — inclusive eu, que já fiz exatamente
17
- // isso uma vez.
18
- //
19
- // Run: npm run build && node --test dist/__tests__/telemetry-per-chunk.test.js
20
- import { test, before, after } from "node:test";
21
- import assert from "node:assert/strict";
22
- import { mkdtempSync, rmSync, readFileSync } from "node:fs";
23
- import { join, dirname, resolve } from "node:path";
24
- import { fileURLToPath } from "node:url";
25
- import { tmpdir } from "node:os";
26
- import Database from "better-sqlite3";
27
- const TMP_ROOT = mkdtempSync(join(process.env.NOX_TEST_TMP_ROOT || tmpdir(), "nox-mem-telemetry-test-"));
28
- const TEST_DB = join(TMP_ROOT, "fresh.db");
29
- process.env.NOX_DB_PATH = TEST_DB;
30
- // dist/__tests__/ → ../../../src/search.ts
31
- const SRC = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..", "src");
32
- let getDb;
33
- let closeDb;
34
- before(async () => {
35
- const m = await import("../db.js");
36
- getDb = m.getDb;
37
- closeDb = m.closeDb;
38
- });
39
- after(() => {
40
- try {
41
- closeDb();
42
- }
43
- catch { /* ignore */ }
44
- rmSync(TMP_ROOT, { recursive: true, force: true });
45
- });
46
- const colunas = (db, tabela) => db.pragma(`table_info(${tabela})`).map((c) => c.name);
47
- test("A1 — install limpo cria search_telemetry já com as duas colunas", () => {
48
- const cols = colunas(getDb(), "search_telemetry");
49
- assert.ok(cols.includes("top_chunk_ids"), `top_chunk_ids ausente: ${cols.join(", ")}`);
50
- assert.ok(cols.includes("top_scores"), `top_scores ausente: ${cols.join(", ")}`);
51
- closeDb();
52
- });
53
- test("A2 — DB legado parado em v18 ganha as colunas ao reabrir", async () => {
54
- const legado = join(TMP_ROOT, "v18.db");
55
- // Reconstrói o estado v6/v18: a tabela SEM as colunas novas, e o meta dizendo 18.
56
- const raw = new Database(legado);
57
- raw.exec(`
58
- CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT, updated_at TEXT);
59
- CREATE TABLE search_telemetry (
60
- id INTEGER PRIMARY KEY AUTOINCREMENT,
61
- ts TEXT NOT NULL DEFAULT (datetime('now')),
62
- query_hash TEXT NOT NULL,
63
- query_words INTEGER NOT NULL,
64
- variants_count INTEGER NOT NULL DEFAULT 1,
65
- results_count INTEGER NOT NULL DEFAULT 0,
66
- has_semantic INTEGER NOT NULL DEFAULT 0,
67
- latency_ms INTEGER NOT NULL DEFAULT 0,
68
- expansion_skipped_reason TEXT
69
- );
70
- INSERT INTO meta (key, value) VALUES ('schema_version', '18');
71
- `);
72
- const antes = raw.pragma("table_info(search_telemetry)").map((c) => c.name);
73
- assert.ok(!antes.includes("top_chunk_ids"), "pré-condição do teste quebrou: legado já tinha a coluna");
74
- raw.close();
75
- process.env.NOX_DB_PATH = legado;
76
- // Especificador em variável: precisa de uma instância NOVA do módulo (db.js
77
- // memoiza a conexão em escopo de módulo), e o `?v18` faz o loader tratar como
78
- // outra entrada de cache. Literal aqui faria o tsc tentar resolver o arquivo.
79
- const espec = "../db.js?v18";
80
- const m = (await import(espec));
81
- const db = m.getDb();
82
- const depois = colunas(db, "search_telemetry");
83
- assert.ok(depois.includes("top_chunk_ids") && depois.includes("top_scores"), depois.join(", "));
84
- // E a migração não perdeu as colunas antigas.
85
- assert.ok(depois.includes("query_hash") && depois.includes("expansion_skipped_reason"));
86
- m.closeDb();
87
- process.env.NOX_DB_PATH = TEST_DB;
88
- });
89
- test("B1 — o INSERT de telemetria NÃO grava o texto cru da query", () => {
90
- const fonte = readFileSync(join(SRC, "search.ts"), "utf8");
91
- const m = fonte.match(/INSERT INTO search_telemetry \(([^)]*)\)/);
92
- assert.ok(m, "não achei o INSERT INTO search_telemetry em search.ts");
93
- const escritas = m[1].split(",").map((s) => s.trim());
94
- assert.ok(!escritas.includes("query_text"), `regressão de privacidade: ${escritas.join(", ")}`);
95
- assert.ok(escritas.includes("query_hash"), "o hash é a ÚNICA representação da query que pode ser gravada");
96
- assert.ok(escritas.includes("top_chunk_ids") && escritas.includes("top_scores"), escritas.join(", "));
97
- });
98
- test("B2 — a lista de colunas do INSERT casa com o número de parâmetros", () => {
99
- // Defeito mecânico clássico: adicionar coluna e esquecer o `?`, ou o argumento
100
- // do `.run()`. O SQLite aceita a discrepância de argumento em silêncio em
101
- // alguns casos, e a coluna nova fica NULL para sempre — que é indistinguível
102
- // de "a feature não foi usada".
103
- const fonte = readFileSync(join(SRC, "search.ts"), "utf8");
104
- const bloco = fonte.slice(fonte.indexOf("INSERT INTO search_telemetry"));
105
- const cols = bloco.match(/INSERT INTO search_telemetry \(([^)]*)\)/)[1].split(",").length;
106
- const placeholders = bloco.match(/VALUES \(([^)]*)\)/)[1].split(",").length;
107
- const args = bloco.slice(bloco.indexOf(".run(")).match(/\.run\(([^;]*)\)/)[1].split(",").length;
108
- assert.equal(placeholders, cols, `${cols} colunas mas ${placeholders} placeholders`);
109
- assert.equal(args, cols, `${cols} colunas mas ${args} argumentos no .run()`);
110
- });
@@ -1,103 +0,0 @@
1
- // E13 — Temporal-aware Ranking tests.
2
- // Spec: memoria-nox/specs/2026-05-06-E13-temporal-aware-ranking.md
3
- //
4
- // Run: cd /root/.openclaw/workspace/tools/nox-mem && npx tsc &&
5
- // node --test dist/__tests__/temporal-detector.test.js
6
- import { test, beforeEach } from "node:test";
7
- import assert from "node:assert/strict";
8
- import { isTemporalQuery, effectiveSectionBoost, getOverride, getMode, SECTION_BOOST_TEMPORAL, } from "../lib/temporal-detector.js";
9
- beforeEach(() => {
10
- delete process.env.NOX_TEMPORAL_BOOST_MODE;
11
- delete process.env.NOX_TEMPORAL_BOOST_LOG;
12
- });
13
- // ─────────────────────────────────────────────────────────────────────
14
- // 1. detector positive cases (PT-BR triggers)
15
- // ─────────────────────────────────────────────────────────────────────
16
- test("isTemporalQuery: 'quando o salience foi ativado' → true", () => {
17
- assert.equal(isTemporalQuery("quando o salience foi ativado"), true);
18
- });
19
- test("isTemporalQuery: 'primeira lição do incident' → true", () => {
20
- assert.equal(isTemporalQuery("primeira lição do incident"), true);
21
- });
22
- test("isTemporalQuery: 'ativado' single token → true", () => {
23
- assert.equal(isTemporalQuery("ativado"), true);
24
- });
25
- test("isTemporalQuery: ISO date '2026-04-25' in query → true", () => {
26
- assert.equal(isTemporalQuery("query com 2026-04-25 contexto"), true);
27
- });
28
- test("isTemporalQuery: 'Quando subiu schema v12?' (case-insensitive) → true", () => {
29
- assert.equal(isTemporalQuery("Quando subiu schema v12?"), true);
30
- });
31
- // ─────────────────────────────────────────────────────────────────────
32
- // 2. detector negative cases
33
- // ─────────────────────────────────────────────────────────────────────
34
- test("isTemporalQuery: 'o que é nox-mem' → false (factual)", () => {
35
- assert.equal(isTemporalQuery("o que é nox-mem"), false);
36
- });
37
- test("isTemporalQuery: 'relação entre A e B' → false", () => {
38
- assert.equal(isTemporalQuery("relação entre A e B"), false);
39
- });
40
- test("isTemporalQuery: empty/short query → false", () => {
41
- assert.equal(isTemporalQuery(""), false);
42
- assert.equal(isTemporalQuery("ab"), false);
43
- });
44
- // Edge: "deployment" sozinho NÃO bate (precisa "deployado/deployed/deployamento")
45
- test("isTemporalQuery: 'deployment automatizado' → false (radical sem modifier)", () => {
46
- assert.equal(isTemporalQuery("deployment automatizado"), false);
47
- });
48
- // ─────────────────────────────────────────────────────────────────────
49
- // 3. effectiveSectionBoost — override só em mode=active
50
- // ─────────────────────────────────────────────────────────────────────
51
- test("effectiveSectionBoost: mode=off retorna baseline (sem override)", () => {
52
- // baseline timeline = 0.8; override seria 1.4
53
- const v = effectiveSectionBoost(0.8, "timeline", true, "off");
54
- assert.equal(v, 0.8);
55
- });
56
- test("effectiveSectionBoost: mode=shadow retorna baseline (não muta)", () => {
57
- const v = effectiveSectionBoost(0.8, "timeline", true, "shadow");
58
- assert.equal(v, 0.8);
59
- });
60
- test("effectiveSectionBoost: mode=active + isTemporal + section=timeline → 1.4 override", () => {
61
- const v = effectiveSectionBoost(0.8, "timeline", true, "active");
62
- assert.equal(v, 1.4);
63
- });
64
- test("effectiveSectionBoost: mode=active + isTemporal + section=compiled → 1.0 (neutro)", () => {
65
- const v = effectiveSectionBoost(2.0, "compiled", true, "active");
66
- assert.equal(v, 1.0);
67
- });
68
- test("effectiveSectionBoost: mode=active mas isTemporal=false → baseline preservado", () => {
69
- const v = effectiveSectionBoost(2.0, "compiled", false, "active");
70
- assert.equal(v, 2.0);
71
- });
72
- test("effectiveSectionBoost: section=null → baseline retornado", () => {
73
- const v = effectiveSectionBoost(1.0, null, true, "active");
74
- assert.equal(v, 1.0);
75
- });
76
- // ─────────────────────────────────────────────────────────────────────
77
- // 4. getMode env reader (off/shadow/active fallback)
78
- // ─────────────────────────────────────────────────────────────────────
79
- test("getMode: default off quando env unset", () => {
80
- delete process.env.NOX_TEMPORAL_BOOST_MODE;
81
- assert.equal(getMode(), "off");
82
- });
83
- test("getMode: lowercase shadow", () => {
84
- process.env.NOX_TEMPORAL_BOOST_MODE = "SHADOW";
85
- assert.equal(getMode(), "shadow");
86
- });
87
- test("getMode: invalid value → off fallback", () => {
88
- process.env.NOX_TEMPORAL_BOOST_MODE = "garbage";
89
- assert.equal(getMode(), "off");
90
- });
91
- // ─────────────────────────────────────────────────────────────────────
92
- // 5. getOverride pure lookup
93
- // ─────────────────────────────────────────────────────────────────────
94
- test("getOverride: timeline → 1.4", () => {
95
- assert.equal(getOverride("timeline"), 1.4);
96
- });
97
- test("getOverride: section desconhecida → null", () => {
98
- assert.equal(getOverride("xyz"), null);
99
- });
100
- test("SECTION_BOOST_TEMPORAL: invariants — timeline>compiled>frontmatter", () => {
101
- assert.ok(SECTION_BOOST_TEMPORAL.timeline > SECTION_BOOST_TEMPORAL.compiled);
102
- assert.ok(SECTION_BOOST_TEMPORAL.compiled > SECTION_BOOST_TEMPORAL.frontmatter);
103
- });