nox-mem 3.4.0 → 3.5.1

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 (68) hide show
  1. package/README.md +62 -33
  2. package/dist/api/answer.js +22 -0
  3. package/dist/api-server.js +4 -14
  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/lib/query-params.js +19 -0
  16. package/dist/mcp/tools/answer.js +23 -0
  17. package/dist/mcp-server.js +36 -5
  18. package/dist/reflect.js +2 -2
  19. package/dist/reindex-errors.js +19 -0
  20. package/dist/reindex.js +12 -2
  21. package/dist/search.js +27 -6
  22. package/package.json +4 -1
  23. package/prompts/consolidate.txt +13 -0
  24. package/prompts/digest.txt +5 -0
  25. package/dist/__tests__/brief-diversity.test.js +0 -266
  26. package/dist/__tests__/brief.test.js +0 -287
  27. package/dist/__tests__/churn.test.js +0 -66
  28. package/dist/__tests__/edge-typing.test.js +0 -99
  29. package/dist/__tests__/fts-or-fallback.test.js +0 -115
  30. package/dist/__tests__/ingest-event.test.js +0 -151
  31. package/dist/__tests__/op-audit-e2e.test.js +0 -130
  32. package/dist/__tests__/pragma-alignment.test.js +0 -123
  33. package/dist/__tests__/reindex-dedup.test.js +0 -80
  34. package/dist/__tests__/reindex-safety.test.js +0 -116
  35. package/dist/__tests__/reranker.test.js +0 -326
  36. package/dist/__tests__/retention.test.js +0 -99
  37. package/dist/__tests__/search-track-access.test.js +0 -49
  38. package/dist/__tests__/session-distill-sources.test.js +0 -98
  39. package/dist/__tests__/spo-injection.test.js +0 -172
  40. package/dist/__tests__/telemetry-per-chunk.test.js +0 -110
  41. package/dist/__tests__/temporal-detector.test.js +0 -103
  42. package/dist/__tests__/temporal-filter.test.js +0 -117
  43. package/dist/lib/answer/__tests__/e2e-gemini.test.js +0 -229
  44. package/dist/lib/answer/__tests__/integration-sqlite.test.js +0 -388
  45. package/dist/lib/answer/__tests__/integration.test.js +0 -347
  46. package/dist/lib/answer/__tests__/prompt.test.js +0 -117
  47. package/dist/lib/answer/__tests__/t5-t10.test.js +0 -501
  48. package/dist/lib/api/__tests__/safe-error-message.test.js +0 -155
  49. package/dist/lib/auth/__tests__/localhost-guard.test.js +0 -144
  50. package/dist/lib/error-sanitizer/__tests__/sanitize.test.js +0 -354
  51. package/dist/lib/events/__tests__/bus.test.js +0 -208
  52. package/dist/lib/op-audit-extension/__tests__/ran-at-guard.test.js +0 -109
  53. package/dist/lib/regex-extract/__tests__/extractor.test.js +0 -197
  54. package/dist/lib/regex-extract/__tests__/frontmatter.test.js +0 -75
  55. package/dist/lib/regex-extract/__tests__/ingest-router-l4.test.js +0 -139
  56. package/dist/lib/regex-extract/__tests__/production-wire.test.js +0 -177
  57. package/dist/lib/regex-extract/__tests__/reconcile.test.js +0 -170
  58. package/dist/lib/regex-extract/__tests__/strip-code.test.js +0 -36
  59. package/dist/privacy/__tests__/filter.test.js +0 -352
  60. package/dist/providers/__tests__/conformance-extended.test.js +0 -249
  61. package/dist/providers/__tests__/conformance.test.js +0 -98
  62. package/dist/providers/__tests__/cost-cap.test.js +0 -151
  63. package/dist/providers/__tests__/e2e-real.test.js +0 -79
  64. package/dist/providers/__tests__/factory.test.js +0 -80
  65. package/dist/providers/__tests__/fallback.test.js +0 -223
  66. package/dist/providers/__tests__/gemini.test.js +0 -191
  67. package/dist/providers/__tests__/health.test.js +0 -128
  68. package/dist/providers/__tests__/telemetry.test.js +0 -219
@@ -1,99 +0,0 @@
1
- // E05 — Edge typing tests.
2
- // Cobre: schema v12 migration, normalizeRelationReason enum guard, SPO surface reason.
3
- //
4
- // Run: cd /root/.openclaw/workspace/tools/nox-mem && npx tsc &&
5
- // node --test dist/__tests__/edge-typing.test.js
6
- import { test, before, after } from "node:test";
7
- import assert from "node:assert/strict";
8
- import { mkdtempSync, rmSync } from "node:fs";
9
- import { join } from "node:path";
10
- import { tmpdir } from "node:os";
11
- import { VALID_RELATION_REASONS, normalizeRelationReason, } from "../kg-llm.js";
12
- const TMP_ROOT = mkdtempSync(join(process.env.NOX_TEST_TMP_ROOT || tmpdir(), "nox-mem-edge-test-"));
13
- const TEST_DB = join(TMP_ROOT, "test.db");
14
- process.env.NOX_DB_PATH = TEST_DB;
15
- let getDb, closeDb;
16
- let lookupTopK;
17
- before(async () => {
18
- const dbMod = await import("../db.js");
19
- const spoMod = await import("../lib/spo-injection.js");
20
- getDb = dbMod.getDb;
21
- closeDb = dbMod.closeDb;
22
- lookupTopK = spoMod.lookupTopK;
23
- getDb(); // triggers ensureSchema → v12
24
- });
25
- after(() => {
26
- try {
27
- closeDb();
28
- }
29
- catch { /* ignore */ }
30
- rmSync(TMP_ROOT, { recursive: true, force: true });
31
- });
32
- // ─────────────────────────────────────────────────────────────────────
33
- // Enum guard
34
- // ─────────────────────────────────────────────────────────────────────
35
- test("VALID_RELATION_REASONS has exactly 7 closed values", () => {
36
- assert.equal(VALID_RELATION_REASONS.length, 7);
37
- assert.deepEqual([...VALID_RELATION_REASONS].sort(), ["depends_on", "derived_from", "extends", "mentions", "opposes", "replaces", "unknown"].sort());
38
- });
39
- test("normalizeRelationReason: passes valid lowercase", () => {
40
- assert.equal(normalizeRelationReason("depends_on"), "depends_on");
41
- assert.equal(normalizeRelationReason("extends"), "extends");
42
- });
43
- test("normalizeRelationReason: case-insensitive + trims whitespace", () => {
44
- assert.equal(normalizeRelationReason(" Depends_On "), "depends_on");
45
- assert.equal(normalizeRelationReason("REPLACES"), "replaces");
46
- });
47
- test("normalizeRelationReason: invalid string → unknown", () => {
48
- assert.equal(normalizeRelationReason("foo"), "unknown");
49
- assert.equal(normalizeRelationReason("requires"), "unknown");
50
- });
51
- test("normalizeRelationReason: non-string → unknown", () => {
52
- assert.equal(normalizeRelationReason(null), "unknown");
53
- assert.equal(normalizeRelationReason(undefined), "unknown");
54
- assert.equal(normalizeRelationReason(123), "unknown");
55
- assert.equal(normalizeRelationReason({}), "unknown");
56
- });
57
- // ─────────────────────────────────────────────────────────────────────
58
- // Schema v12 migration
59
- // ─────────────────────────────────────────────────────────────────────
60
- test("schema v12: PRAGMA user_version >= 12 (additive forward-compat)", () => {
61
- const db = getDb();
62
- const v = db.prepare("PRAGMA user_version").get().user_version;
63
- assert.ok(v >= 12, `expected >=12, got ${v}`);
64
- });
65
- test("schema v12: kg_relations.relation_reason column exists", () => {
66
- const db = getDb();
67
- const cols = db.prepare("PRAGMA table_info(kg_relations)").all();
68
- const names = cols.map((c) => c.name);
69
- assert.ok(names.includes("relation_reason"), `cols: ${names.join(",")}`);
70
- });
71
- test("schema v12: idx_kg_relations_reason index exists", () => {
72
- const db = getDb();
73
- const idx = db.prepare("SELECT name FROM sqlite_master WHERE type='index' AND name='idx_kg_relations_reason'").get();
74
- assert.ok(idx, "idx_kg_relations_reason missing");
75
- });
76
- test("schema v12: default 'unknown' applied to new INSERT without reason", () => {
77
- const db = getDb();
78
- const insE = db.prepare("INSERT INTO kg_entities (name, entity_type) VALUES (?, ?)");
79
- const e1 = insE.run("test_a", "concept").lastInsertRowid;
80
- const e2 = insE.run("test_b", "concept").lastInsertRowid;
81
- // Insert WITHOUT reason — should default to 'unknown'
82
- db.prepare("INSERT INTO kg_relations (source_entity_id, relation_type, target_entity_id) VALUES (?, ?, ?)").run(e1, "uses", e2);
83
- const row = db.prepare("SELECT relation_reason FROM kg_relations WHERE source_entity_id=? AND target_entity_id=?").get(e1, e2);
84
- assert.equal(row.relation_reason, "unknown");
85
- });
86
- // ─────────────────────────────────────────────────────────────────────
87
- // SPO injection surfaces reason
88
- // ─────────────────────────────────────────────────────────────────────
89
- test("lookupTopK: returns reason field in triples", () => {
90
- const db = getDb();
91
- const insE = db.prepare("INSERT INTO kg_entities (name, entity_type) VALUES (?, ?)");
92
- const ax = insE.run("alpha", "tool").lastInsertRowid;
93
- const bx = insE.run("beta", "tool").lastInsertRowid;
94
- db.prepare("INSERT INTO kg_relations (source_entity_id, relation_type, target_entity_id, confidence, relation_reason) VALUES (?, ?, ?, ?, ?)").run(ax, "depends_on", bx, 0.9, "depends_on");
95
- const triples = lookupTopK(["alpha"], db, 5);
96
- const found = triples.find((t) => t.subject === "alpha" && t.object === "beta");
97
- assert.ok(found);
98
- assert.equal(found.reason, "depends_on");
99
- });
@@ -1,115 +0,0 @@
1
- // FTS5 OR fallback — natural-language questions on keyless installs.
2
- //
3
- // FTS5 ANDs a space-separated query, so "when was the zebra migration" matches
4
- // nothing unless every filler word is in the chunk. search() retries with an OR
5
- // of the content terms, but ONLY when the AND query returned zero rows, and only
6
- // when NOX_FTS_OR_FALLBACK allows it (auto = no embedding key in the env).
7
- //
8
- // The DB is isolated with NOX_DB_PATH in a mkdtemp BEFORE db.js is imported.
9
- //
10
- // Run: npm test (or: npx tsc -p tsconfig.test.json && node --test dist/__tests__/fts-or-fallback.test.js)
11
- import { test, before, after, beforeEach } from "node:test";
12
- import assert from "node:assert/strict";
13
- import { mkdtempSync, rmSync } from "fs";
14
- import { tmpdir } from "os";
15
- import { join } from "path";
16
- import { parseTemporalFilter } from "../lib/dates.js";
17
- const TMP_ROOT = mkdtempSync(join(process.env.NOX_TEST_TMP_ROOT || tmpdir(), "nox-mem-fts-or-test-"));
18
- process.env.NOX_DB_PATH = join(TMP_ROOT, "test.db");
19
- delete process.env.GEMINI_API_KEY;
20
- delete process.env.OPENAI_API_KEY;
21
- delete process.env.NOX_FTS_OR_FALLBACK;
22
- delete process.env.NOX_EMBEDDING_API_KEY;
23
- delete process.env.NOX_EMBED_API_KEY;
24
- const NOW = Date.parse("2026-09-28T12:00:00Z");
25
- const QUESTION = "when was the zebra migration";
26
- let getDb, closeDb, search, buildFtsOrQuery, ftsOrFallbackEnabled;
27
- before(async () => {
28
- ({ getDb, closeDb } = await import("../db.js"));
29
- ({ search, buildFtsOrQuery, ftsOrFallbackEnabled } = await import("../search.js"));
30
- const db = getDb();
31
- const ins = db.prepare(`INSERT INTO chunks (source_file, chunk_type, chunk_text, source_date, created_at, updated_at)
32
- VALUES (?, 'other', ?, NULL, ?, ?)`);
33
- // The chunk the question must find (none of when/was/the is in it).
34
- ins.run("zebra.md", "zebra migration yesterday", "2026-09-01 08:00:00", "2026-09-01 08:00:00");
35
- // AND-vs-OR discriminator: "aardvark tunnel" ANDs to fig.md only; OR would add fig2.md.
36
- ins.run("fig.md", "aardvark tunnel survey", "2026-09-01 08:00:00", "2026-09-01 08:00:00");
37
- ins.run("fig2.md", "aardvark burrow notes", "2026-09-01 08:00:00", "2026-09-01 08:00:00");
38
- // Temporal pair for the OR branch: same words, different age.
39
- ins.run("quokka-old.md", "quokka census results", "2026-01-10 08:00:00", "2026-01-10 08:00:00");
40
- ins.run("quokka-new.md", "quokka census results", "2026-09-26T10:00:00.000Z", "2026-09-26T10:00:00.000Z");
41
- });
42
- after(() => {
43
- closeDb();
44
- rmSync(TMP_ROOT, { recursive: true, force: true });
45
- });
46
- // Each test sets exactly the env it needs; the gate must be read per call.
47
- beforeEach(() => {
48
- delete process.env.GEMINI_API_KEY;
49
- delete process.env.OPENAI_API_KEY;
50
- delete process.env.NOX_FTS_OR_FALLBACK;
51
- });
52
- const files = (rs) => rs.map((r) => r.source_file).sort();
53
- // ─── helpers ─────────────────────────────────────────────────────────────────
54
- test("buildFtsOrQuery: stopwords out, terms quoted, ORed, deduplicated", () => {
55
- assert.equal(buildFtsOrQuery(QUESTION), '"zebra" OR "migration"');
56
- assert.equal(buildFtsOrQuery("Zebra zebra ZEBRA migration"), '"Zebra" OR "migration"');
57
- assert.equal(buildFtsOrQuery("quando foi a migração da zebra"), '"migração" OR "zebra"');
58
- });
59
- test("buildFtsOrQuery: only stopwords ⇒ null; embedded quotes are doubled", () => {
60
- assert.equal(buildFtsOrQuery("what is the"), null);
61
- assert.equal(buildFtsOrQuery("o que é"), null);
62
- assert.equal(buildFtsOrQuery('a"b'), '"a""b"');
63
- });
64
- test("ftsOrFallbackEnabled: gate matrix", () => {
65
- assert.equal(ftsOrFallbackEnabled({}), true);
66
- // Any key the embedding provider resolves counts as "has embeddings".
67
- assert.equal(ftsOrFallbackEnabled({ NOX_EMBEDDING_API_KEY: "k" }), false);
68
- assert.equal(ftsOrFallbackEnabled({ NOX_EMBED_API_KEY: "k" }), false);
69
- assert.equal(ftsOrFallbackEnabled({ NOX_FTS_OR_FALLBACK: "auto" }), true);
70
- assert.equal(ftsOrFallbackEnabled({ GEMINI_API_KEY: "k" }), false);
71
- assert.equal(ftsOrFallbackEnabled({ OPENAI_API_KEY: "k" }), false);
72
- assert.equal(ftsOrFallbackEnabled({ NOX_FTS_OR_FALLBACK: "on", GEMINI_API_KEY: "k" }), true);
73
- assert.equal(ftsOrFallbackEnabled({ NOX_FTS_OR_FALLBACK: "off" }), false);
74
- });
75
- // ─── search() ────────────────────────────────────────────────────────────────
76
- test("(1) auto, no key: a natural-language question finds the chunk", () => {
77
- assert.deepEqual(files(search(QUESTION, 10, false)), ["zebra.md"]);
78
- });
79
- test("(2) auto WITH an embedding key in the env: same question returns [] as before", () => {
80
- process.env.GEMINI_API_KEY = "test-key";
81
- assert.deepEqual(search(QUESTION, 10, false), []);
82
- delete process.env.GEMINI_API_KEY;
83
- process.env.OPENAI_API_KEY = "test-key";
84
- assert.deepEqual(search(QUESTION, 10, false), []);
85
- });
86
- test("(3) off: [] even without a key", () => {
87
- process.env.NOX_FTS_OR_FALLBACK = "off";
88
- assert.deepEqual(search(QUESTION, 10, false), []);
89
- });
90
- test("on: forces the fallback even with a key", () => {
91
- process.env.NOX_FTS_OR_FALLBACK = "on";
92
- process.env.GEMINI_API_KEY = "test-key";
93
- assert.deepEqual(files(search(QUESTION, 10, false)), ["zebra.md"]);
94
- });
95
- test("(4) AND already hits: result identical (order and scores) with the fallback on and off", () => {
96
- process.env.NOX_FTS_OR_FALLBACK = "on";
97
- const on = search("aardvark tunnel", 10, false);
98
- process.env.NOX_FTS_OR_FALLBACK = "off";
99
- const off = search("aardvark tunnel", 10, false);
100
- assert.deepEqual(files(off), ["fig.md"]); // OR would also have pulled fig2.md
101
- assert.deepEqual(on, off);
102
- });
103
- test("(5) stopwords only: no fallback, even forced on", () => {
104
- process.env.NOX_FTS_OR_FALLBACK = "on";
105
- assert.deepEqual(search("what was the", 10, false), []);
106
- assert.deepEqual(search("o que é a", 10, false), []);
107
- });
108
- test("(6) the temporal filter is honoured on the OR branch", () => {
109
- const q = "when was the quokka census";
110
- assert.deepEqual(files(search(q, 10, false)), ["quokka-new.md", "quokka-old.md"]);
111
- const since = parseTemporalFilter({ changedSince: "7d" }, NOW);
112
- assert.deepEqual(files(search(q, 10, false, since)), ["quokka-new.md"]);
113
- const asOf = parseTemporalFilter({ asOf: "2026-02-01" }, NOW);
114
- assert.deepEqual(files(search(q, 10, false, asOf)), ["quokka-old.md"]);
115
- });
@@ -1,151 +0,0 @@
1
- // F4b — testes do POST /api/ingest-event (Session Priming Loop, Fluxo D).
2
- // Spec: memoria-nox specs/2026-06-04-session-priming-loop.md §7 Fluxo D.
3
- //
4
- // Run: cd tools/nox-mem && npx tsc && node --test dist/__tests__/ingest-event.test.js
5
- import { test } from "node:test";
6
- import assert from "node:assert/strict";
7
- import Database from "better-sqlite3";
8
- import { parseIngestEvent, redactSecrets, handleIngestEvent, } from "../api/ingest-event.js";
9
- function makeDb() {
10
- const db = new Database(":memory:");
11
- db.exec(`
12
- CREATE TABLE chunks (
13
- id INTEGER PRIMARY KEY,
14
- source_file TEXT NOT NULL,
15
- chunk_text TEXT NOT NULL,
16
- chunk_type TEXT NOT NULL DEFAULT 'other',
17
- source_date TEXT,
18
- retention_days INTEGER,
19
- pain REAL DEFAULT 0.2,
20
- importance REAL DEFAULT 0.5,
21
- access_count INTEGER DEFAULT 0,
22
- created_at TEXT DEFAULT (datetime('now')),
23
- updated_at TEXT DEFAULT (datetime('now')),
24
- metadata TEXT
25
- );
26
- `);
27
- return db;
28
- }
29
- const VALID = {
30
- kind: "session_end",
31
- session_id: "22759044-5115-4b3c-923a-78600ffb9b75",
32
- scope: "memoria-nox",
33
- host: "mac",
34
- content: "## Resumo\nF4b implementado e testado.",
35
- };
36
- // ─── Validação ───────────────────────────────────────────────────────────────
37
- test("parse: kind não suportado / session_id inválido / content vazio → erro", () => {
38
- assert.equal(parseIngestEvent({ ...VALID, kind: "tool_use" }).ok, false);
39
- assert.equal(parseIngestEvent({ ...VALID, session_id: "a b" }).ok, false);
40
- assert.equal(parseIngestEvent({ ...VALID, content: " " }).ok, false);
41
- assert.equal(parseIngestEvent(null).ok, false);
42
- assert.equal(parseIngestEvent([1]).ok, false);
43
- });
44
- test("parse: content > 16KB rejeitado", () => {
45
- const r = parseIngestEvent({ ...VALID, content: "x".repeat(17 * 1024) });
46
- assert.equal(r.ok, false);
47
- });
48
- test("parse: scope/host opcionais mas validados quando presentes", () => {
49
- assert.ok(parseIngestEvent({ ...VALID, scope: undefined, host: undefined }).ok);
50
- assert.equal(parseIngestEvent({ ...VALID, scope: "a b" }).ok, false);
51
- assert.equal(parseIngestEvent({ ...VALID, host: "MAC!" }).ok, false);
52
- });
53
- // ─── Redaction ───────────────────────────────────────────────────────────────
54
- test("redaction: keys conhecidas viram [REDACTED] com count", () => {
55
- const dirty = [
56
- "key google AIzaSyBnyA1s81RyTkQAvs6jX0000000000000000",
57
- "formato novo AQ.Ab8RN6L8iAZBLSS8hy40000000000000000000000",
58
- "openai sk-abcdefghij1234567890ABCDEFGHIJ",
59
- "github ghp_abcdefghijklmnopqrstuvwxyz123456",
60
- "header Authorization: Bearer abc.def-ghi_jkl~mno+pqr/stu=123456",
61
- ].join("\n");
62
- const { clean, count } = redactSecrets(dirty);
63
- assert.ok(count >= 5, `esperava ≥5 redactions, veio ${count}`);
64
- assert.ok(!clean.includes("AIzaSy"), "AIza vazou");
65
- assert.ok(!clean.includes("AQ.Ab8"), "AQ. vazou");
66
- assert.ok(!clean.includes("sk-abcdefghij"), "sk- vazou");
67
- assert.ok(clean.includes("[REDACTED]"));
68
- });
69
- test("redaction: texto limpo passa intacto com count 0", () => {
70
- const { clean, count } = redactSecrets("digest normal sem segredos, AQ e sk soltos não casam");
71
- assert.equal(count, 0);
72
- assert.ok(clean.includes("digest normal"));
73
- });
74
- // ─── Handler ─────────────────────────────────────────────────────────────────
75
- test("handle: happy path — chunk daily/90d no namespace events/ com metadata", () => {
76
- const db = makeDb();
77
- const out = handleIngestEvent(db, VALID);
78
- assert.equal(out.status, 201);
79
- const body = out.body;
80
- assert.ok(body.ingested && body.chunk_id > 0);
81
- const row = db
82
- .prepare("SELECT * FROM chunks WHERE id = ?")
83
- .get(body.chunk_id);
84
- assert.equal(row.chunk_type, "daily");
85
- assert.equal(row.retention_days, 90);
86
- assert.ok(row.source_file.startsWith("events/mac/memoria-nox/"));
87
- assert.ok(row.chunk_text.startsWith("## Session digest — memoria-nox"));
88
- const meta = JSON.parse(row.metadata);
89
- assert.equal(meta.session_id, VALID.session_id);
90
- assert.equal(meta.kind, "session_end");
91
- assert.equal(meta.source, "ingest-event");
92
- });
93
- test("handle: dedup por session_id — re-POST idempotente, 1 chunk só", () => {
94
- const db = makeDb();
95
- const first = handleIngestEvent(db, VALID);
96
- const second = handleIngestEvent(db, { ...VALID, content: "conteúdo diferente no retry" });
97
- assert.equal(first.status, 201);
98
- assert.equal(second.status, 200);
99
- assert.deepEqual(second.body.deduped, true);
100
- const n = db.prepare("SELECT COUNT(*) c FROM chunks").get();
101
- assert.equal(n.c, 1);
102
- });
103
- test("handle: redaction aplicada no chunk persistido + count no response", () => {
104
- const db = makeDb();
105
- const out = handleIngestEvent(db, {
106
- ...VALID,
107
- session_id: "sessao-com-segredo",
108
- content: "vazou a key AIzaSyBnyA1s81RyTkQAvs6jX0000000000000000 no digest",
109
- });
110
- assert.equal(out.status, 201);
111
- assert.equal(out.body.redaction_count, 1);
112
- const row = db
113
- .prepare("SELECT chunk_text FROM chunks WHERE json_extract(metadata,'$.session_id')='sessao-com-segredo'")
114
- .get();
115
- assert.ok(!row.chunk_text.includes("AIzaSy"));
116
- assert.ok(row.chunk_text.includes("[REDACTED]"));
117
- });
118
- test("handle: 400 em body inválido", () => {
119
- const db = makeDb();
120
- assert.equal(handleIngestEvent(db, { kind: "session_end" }).status, 400);
121
- assert.equal(handleIngestEvent(db, "string").status, 400);
122
- });
123
- // ─── pre_compact (sessões longas compactam N×) ──────────────────────────────
124
- test("pre_compact: múltiplas compactions da MESMA sessão ingerem (seq distinto)", () => {
125
- const db = makeDb();
126
- const base = { ...VALID, kind: "pre_compact", session_id: "sessao-longa-1" };
127
- const a = handleIngestEvent(db, { ...base, seq: "1780620001", content: "digest compaction 1" });
128
- const b = handleIngestEvent(db, { ...base, seq: "1780629999", content: "digest compaction 2" });
129
- assert.equal(a.status, 201);
130
- assert.equal(b.status, 201);
131
- const n = db.prepare("SELECT COUNT(*) c FROM chunks").get();
132
- assert.equal(n.c, 2);
133
- const row = db.prepare("SELECT source_file, chunk_text FROM chunks ORDER BY id LIMIT 1").get();
134
- assert.ok(row.source_file.includes("sessao-longa-1-1780620001"));
135
- assert.ok(row.chunk_text.startsWith("## Compaction digest"));
136
- });
137
- test("pre_compact: mesmo seq = dedup idempotente; seq inválido = 400", () => {
138
- const db = makeDb();
139
- const base = { ...VALID, kind: "pre_compact", session_id: "sessao-longa-2", seq: "1780620001" };
140
- assert.equal(handleIngestEvent(db, base).status, 201);
141
- assert.equal(handleIngestEvent(db, base).body.deduped, true);
142
- assert.equal(handleIngestEvent(db, { ...base, seq: "a b!" }).status, 400);
143
- });
144
- test("pre_compact não colide com session_end da mesma sessão (kinds distintos)", () => {
145
- const db = makeDb();
146
- const sid = "sessao-mista";
147
- assert.equal(handleIngestEvent(db, { ...VALID, session_id: sid, kind: "pre_compact", seq: "111" }).status, 201);
148
- assert.equal(handleIngestEvent(db, { ...VALID, session_id: sid }).status, 201);
149
- const n = db.prepare("SELECT COUNT(*) c FROM chunks").get();
150
- assert.equal(n.c, 2);
151
- });
@@ -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
- });