nox-mem 3.4.0 → 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +62 -33
  2. package/dist/api/answer.js +22 -0
  3. package/dist/api-server.js +3 -2
  4. package/dist/cli/answer.js +39 -1
  5. package/dist/db.js +31 -20
  6. package/dist/doctor.js +5 -4
  7. package/dist/embed.js +53 -3
  8. package/dist/index.js +16 -10
  9. package/dist/lib/answer/index.js +3 -2
  10. package/dist/lib/answer/retrieval.js +6 -4
  11. package/dist/lib/answer/temporal.js +51 -0
  12. package/dist/lib/api-port.js +16 -0
  13. package/dist/lib/db-path.js +13 -1
  14. package/dist/lib/ingest-many.js +49 -0
  15. package/dist/mcp/tools/answer.js +23 -0
  16. package/dist/mcp-server.js +36 -5
  17. package/dist/reflect.js +2 -2
  18. package/dist/reindex-errors.js +19 -0
  19. package/dist/reindex.js +12 -2
  20. package/dist/search.js +27 -6
  21. package/package.json +4 -1
  22. package/prompts/consolidate.txt +13 -0
  23. package/prompts/digest.txt +5 -0
  24. package/dist/__tests__/brief-diversity.test.js +0 -266
  25. package/dist/__tests__/brief.test.js +0 -287
  26. package/dist/__tests__/churn.test.js +0 -66
  27. package/dist/__tests__/edge-typing.test.js +0 -99
  28. package/dist/__tests__/fts-or-fallback.test.js +0 -115
  29. package/dist/__tests__/ingest-event.test.js +0 -151
  30. package/dist/__tests__/op-audit-e2e.test.js +0 -130
  31. package/dist/__tests__/pragma-alignment.test.js +0 -123
  32. package/dist/__tests__/reindex-dedup.test.js +0 -80
  33. package/dist/__tests__/reindex-safety.test.js +0 -116
  34. package/dist/__tests__/reranker.test.js +0 -326
  35. package/dist/__tests__/retention.test.js +0 -99
  36. package/dist/__tests__/search-track-access.test.js +0 -49
  37. package/dist/__tests__/session-distill-sources.test.js +0 -98
  38. package/dist/__tests__/spo-injection.test.js +0 -172
  39. package/dist/__tests__/telemetry-per-chunk.test.js +0 -110
  40. package/dist/__tests__/temporal-detector.test.js +0 -103
  41. package/dist/__tests__/temporal-filter.test.js +0 -117
  42. package/dist/lib/answer/__tests__/e2e-gemini.test.js +0 -229
  43. package/dist/lib/answer/__tests__/integration-sqlite.test.js +0 -388
  44. package/dist/lib/answer/__tests__/integration.test.js +0 -347
  45. package/dist/lib/answer/__tests__/prompt.test.js +0 -117
  46. package/dist/lib/answer/__tests__/t5-t10.test.js +0 -501
  47. package/dist/lib/api/__tests__/safe-error-message.test.js +0 -155
  48. package/dist/lib/auth/__tests__/localhost-guard.test.js +0 -144
  49. package/dist/lib/error-sanitizer/__tests__/sanitize.test.js +0 -354
  50. package/dist/lib/events/__tests__/bus.test.js +0 -208
  51. package/dist/lib/op-audit-extension/__tests__/ran-at-guard.test.js +0 -109
  52. package/dist/lib/regex-extract/__tests__/extractor.test.js +0 -197
  53. package/dist/lib/regex-extract/__tests__/frontmatter.test.js +0 -75
  54. package/dist/lib/regex-extract/__tests__/ingest-router-l4.test.js +0 -139
  55. package/dist/lib/regex-extract/__tests__/production-wire.test.js +0 -177
  56. package/dist/lib/regex-extract/__tests__/reconcile.test.js +0 -170
  57. package/dist/lib/regex-extract/__tests__/strip-code.test.js +0 -36
  58. package/dist/privacy/__tests__/filter.test.js +0 -352
  59. package/dist/providers/__tests__/conformance-extended.test.js +0 -249
  60. package/dist/providers/__tests__/conformance.test.js +0 -98
  61. package/dist/providers/__tests__/cost-cap.test.js +0 -151
  62. package/dist/providers/__tests__/e2e-real.test.js +0 -79
  63. package/dist/providers/__tests__/factory.test.js +0 -80
  64. package/dist/providers/__tests__/fallback.test.js +0 -223
  65. package/dist/providers/__tests__/gemini.test.js +0 -191
  66. package/dist/providers/__tests__/health.test.js +0 -128
  67. package/dist/providers/__tests__/telemetry.test.js +0 -219
@@ -1,266 +0,0 @@
1
- // D2 — testes do brief diversity/novelty term (re-rank pós-salience).
2
- // Spec: memoria-nox specs/2026-06-07-D2-brief-diversity-term.md
3
- //
4
- // Run: cd tools/nox-mem && npx tsc && node --test dist/__tests__/brief-diversity.test.js
5
- import { test } from "node:test";
6
- import assert from "node:assert/strict";
7
- import Database from "better-sqlite3";
8
- import { noveltyPenalty, briefScore, diffBriefs, diversityConfigFromEnv, DIVERSITY_DEFAULTS, } from "../api/brief-diversity.js";
9
- import { buildBrief, buildBriefDiverse, serveCounts, handleBrief, ensureBriefLog, _resetBriefLogMemo, } from "../api/brief.js";
10
- const CFG = { mode: "active", ...DIVERSITY_DEFAULTS };
11
- // ─── makeDb (espelha brief.test.ts) ──────────────────────────────────────────
12
- function makeDb() {
13
- const db = new Database(":memory:");
14
- db.exec(`
15
- CREATE TABLE chunks (
16
- id INTEGER PRIMARY KEY,
17
- source_file TEXT NOT NULL,
18
- chunk_text TEXT NOT NULL,
19
- chunk_type TEXT NOT NULL DEFAULT 'other',
20
- source_type TEXT,
21
- tier TEXT DEFAULT 'peripheral',
22
- pain REAL DEFAULT 0.2,
23
- importance REAL DEFAULT 0.5,
24
- retention_days INTEGER,
25
- source_date TEXT,
26
- created_at TEXT DEFAULT (datetime('now')),
27
- updated_at TEXT DEFAULT (datetime('now')),
28
- last_accessed_at TEXT,
29
- access_count INTEGER DEFAULT 0
30
- );
31
- `);
32
- _resetBriefLogMemo();
33
- return db;
34
- }
35
- /** Insere chunks; created_at/updated_at aceitam SQL via marcador __SQL__. */
36
- function seed(db, rows) {
37
- for (const r of rows) {
38
- const created = r.created_at ?? "2026-06-01 00:00:00";
39
- db.prepare(`INSERT INTO chunks (source_file, chunk_text, pain, importance, access_count, created_at, updated_at)
40
- VALUES (?, ?, ?, ?, ?, ${created.startsWith("datetime(") ? created : "?"}, ${created.startsWith("datetime(") ? created : "?"})`).run(...(created.startsWith("datetime(")
41
- ? [r.source_file, r.chunk_text ?? "conteúdo", r.pain ?? 0.2, r.importance ?? 0.5, r.access_count ?? 0]
42
- : [r.source_file, r.chunk_text ?? "conteúdo", r.pain ?? 0.2, r.importance ?? 0.5, r.access_count ?? 0, created, created]));
43
- }
44
- }
45
- /** Loga N serves de um chunk a `offsetHours` atrás no brief_log. */
46
- function logServes(db, chunkId, n, offsetHours = 1) {
47
- ensureBriefLog(db);
48
- const ins = db.prepare(`INSERT INTO brief_log (chunk_id, scope, served_at) VALUES (?, 'global', datetime('now', ?))`);
49
- for (let i = 0; i < n; i++)
50
- ins.run(chunkId, `-${offsetHours} hours`);
51
- }
52
- // ─── noveltyPenalty (puro) ───────────────────────────────────────────────────
53
- test("penalty: high-pain floor (pain ≥ painFloor) ⇒ 0 imune", () => {
54
- assert.equal(noveltyPenalty(99999, 0.9, CFG), 0);
55
- assert.equal(noveltyPenalty(99999, 0.95, CFG), 0);
56
- assert.ok(noveltyPenalty(99999, 0.89, CFG) > 0, "pain abaixo do floor não é imune");
57
- });
58
- test("penalty: n_serves 0 ⇒ 0 (nada servido, nada penaliza)", () => {
59
- assert.equal(noveltyPenalty(0, 0.2, CFG), 0);
60
- });
61
- test("penalty: cresce em log e satura em pMax", () => {
62
- const p5 = noveltyPenalty(5, 0.2, CFG);
63
- const p10 = noveltyPenalty(10, 0.2, CFG);
64
- assert.ok(p10 > p5 && p5 > 0, "monotônico antes do cap");
65
- // satura: servir 100× ≈ servir 2000× (ambos batem pMax)
66
- assert.equal(noveltyPenalty(100, 0.2, CFG), CFG.pMax);
67
- assert.equal(noveltyPenalty(2000, 0.2, CFG), CFG.pMax);
68
- });
69
- test("briefScore: salience − penalty", () => {
70
- const s = briefScore(0.5, 0, 0.2, CFG); // sem serves
71
- assert.equal(s, 0.5);
72
- assert.ok(briefScore(0.5, 100, 0.2, CFG) < 0.5, "muito servido desce");
73
- });
74
- // ─── diversityConfigFromEnv ──────────────────────────────────────────────────
75
- test("config: default off + calibração D3", () => {
76
- const c = diversityConfigFromEnv({});
77
- assert.equal(c.mode, "off");
78
- assert.equal(c.painFloor, 0.9);
79
- assert.equal(c.freshSlots, 2);
80
- assert.equal(c.windowSql, "-72 hours");
81
- });
82
- test("config: env override (mode/lambda/window/slots)", () => {
83
- const c = diversityConfigFromEnv({
84
- NOX_BRIEF_DIVERSITY: "shadow",
85
- NOX_BRIEF_DIV_LAMBDA: "0.1",
86
- NOX_BRIEF_DIV_WINDOW_HOURS: "24",
87
- NOX_BRIEF_DIV_FRESH_SLOTS: "3",
88
- });
89
- assert.equal(c.mode, "shadow");
90
- assert.equal(c.lambda, 0.1);
91
- assert.equal(c.windowSql, "-24 hours");
92
- assert.equal(c.freshSlots, 3);
93
- });
94
- test("config: mode inválido ⇒ off (fail-safe)", () => {
95
- assert.equal(diversityConfigFromEnv({ NOX_BRIEF_DIVERSITY: "ON" }).mode, "off");
96
- });
97
- // ─── diffBriefs ──────────────────────────────────────────────────────────────
98
- test("diff: would_enter/leave corretos", () => {
99
- const d = diffBriefs([1, 2, 3], [1, 4, 3], [4]);
100
- assert.deepEqual(d.would_enter, [4]);
101
- assert.deepEqual(d.would_leave, [2]);
102
- assert.deepEqual(d.fresh_added, [4]);
103
- assert.equal(d.churn, 1);
104
- });
105
- // ─── serveCounts (query brief_log) ───────────────────────────────────────────
106
- test("serveCounts: conta na janela, ignora fora dela", () => {
107
- const db = makeDb();
108
- seed(db, [{ source_file: "x/a.md" }, { source_file: "x/b.md" }]);
109
- logServes(db, 1, 5, 1); // 5 serves há 1h (dentro de 72h)
110
- logServes(db, 1, 3, 100); // 3 serves há 100h (fora)
111
- logServes(db, 2, 2, 1);
112
- const counts = serveCounts(db, [1, 2], "-72 hours");
113
- assert.equal(counts.get(1), 5, "só os de dentro da janela");
114
- assert.equal(counts.get(2), 2);
115
- });
116
- test("serveCounts: fail-open com ids vazios", () => {
117
- const db = makeDb();
118
- assert.equal(serveCounts(db, [], "-72 hours").size, 0);
119
- });
120
- // ─── buildBriefDiverse (A: novelty penalty) ──────────────────────────────────
121
- test("A: chunk muito-servido desce, abre espaço pro menos-servido (mesma salience)", () => {
122
- const db = makeDb();
123
- // dois chunks ~salience igual (mesma importance/pain/age), textos distintos
124
- seed(db, [
125
- { source_file: "x/muito.md", chunk_text: "tópico alfa muito repetido no brief", importance: 0.6 },
126
- { source_file: "x/pouco.md", chunk_text: "tópico beta raramente servido ainda", importance: 0.6 },
127
- ]);
128
- logServes(db, 1, 500, 1); // chunk 1 servido 500× na janela
129
- const { current, alt } = buildBriefDiverse(db, { scope: "x", n: 1, format: "json" }, CFG, Date.now());
130
- // current (salience pura): empate → ordem de salience/updated_at
131
- // alt: penalty derruba o muito-servido ⇒ o pouco-servido vence
132
- assert.equal(alt.items[0].id, 2, "novelty penalty promove o menos-servido");
133
- assert.ok(current.items.length === 1 && alt.items.length === 1);
134
- });
135
- test("A: high-pain floor — incident crítico muito-servido NÃO é deslocado", () => {
136
- const db = makeDb();
137
- seed(db, [
138
- { source_file: "x/incident.md", chunk_text: "incident gateway fratricide produção", importance: 0.6, pain: 0.95 },
139
- { source_file: "x/novo.md", chunk_text: "nota recente qualquer sem pain", importance: 0.6, pain: 0.2 },
140
- ]);
141
- logServes(db, 1, 500, 1); // incident servidíssimo
142
- const { alt } = buildBriefDiverse(db, { scope: "x", n: 1, format: "json" }, CFG, Date.now());
143
- assert.equal(alt.items[0].id, 1, "high-pain≥0.9 imune ao penalty (floor)");
144
- });
145
- test("FLOOR vs freshness: high-pain do brief atual NÃO é expulso pelo slot B", () => {
146
- const db = makeDb();
147
- // A/C/D regulares high-salience; B high-pain pain=1.0 na 4ª posição. source_date
148
- // abril (não vira fresh candidate) + last_accessed recente (recency alta).
149
- // Sem o floor, o freshness slot (reduz mainTarget) empurraria B pra fora.
150
- const ins = db.prepare(`INSERT INTO chunks (source_file, chunk_text, importance, pain, access_count, source_date, last_accessed_at, created_at, updated_at)
151
- VALUES (?, ?, ?, ?, 40, '2026-04-01', datetime('now','-1 days'), '2026-04-01 00:00:00', datetime('now','-1 days'))`);
152
- ins.run("x/a.md", "decisão alfa gateway fallback chain", 0.95, 0.2); // id1
153
- ins.run("x/c.md", "schema migração vacuum backup atômico", 0.85, 0.2); // id2
154
- ins.run("x/d.md", "rollback deploy regression noturno", 0.8, 0.2); // id3
155
- ins.run("x/incident.md", "incident fratricide produção crítico down", 0.6, 1.0); // id4 high-pain
156
- db.prepare(`INSERT INTO chunks (source_file, chunk_text, importance, pain, access_count, created_at, updated_at)
157
- VALUES ('x/fresco.md', 'achado novo relevante desta semana', 0.75, 0.2, 0, datetime('now','-1 days'), datetime('now','-1 days'))`).run(); // id5 fresh
158
- const cfg = { ...CFG, freshSlots: 1 };
159
- const { current, alt } = buildBriefDiverse(db, { scope: "x", n: 4, format: "json" }, cfg, Date.now());
160
- assert.ok(current.items.map((i) => i.id).includes(4), "high-pain está no brief atual (top-4)");
161
- assert.ok(alt.items.map((i) => i.id).includes(4), "FLOOR: high-pain preservado apesar do freshness slot");
162
- });
163
- // ─── buildBriefDiverse (B: freshness slot) ───────────────────────────────────
164
- /** Insere 4 dominantes high-salience (source_date recente ⇒ recency alta;
165
- * importance/pain/access máximos) que ocupam folgado os slots por salience.
166
- * recencyComponent usa last_accessed_at ?? source_date — daí o source_date. */
167
- function seedDominants(db) {
168
- // Dominantes = conteúdo ANTIGO (source_date abril ⇒ fora do freshness pool)
169
- // mas MUITO acessado (last_accessed_at recente ⇒ recency alta ⇒ salience
170
- // domina os slots por salience). Espelha o real: incidents/decisões velhas
171
- // que perpetuam o brief. Textos DISTINTOS pra não colapsarem por near-dup.
172
- const texts = [
173
- "gateway fratricide produção fallback chain",
174
- "schema migração vacuum encrypted backup atômico",
175
- "rollback deploy noturno regression boost multiplicativo",
176
- "vetorização embeddings gemini prepaid canary depleted",
177
- ];
178
- // pain 0.5 (NÃO high-pain) — dominam por importance+recency, mas não viram
179
- // pinned do floor (senão encheriam o brief e barrariam o teste de freshness).
180
- const ins = db.prepare(`INSERT INTO chunks (source_file, chunk_text, importance, pain, access_count, source_date, last_accessed_at, created_at, updated_at)
181
- VALUES (?, ?, 0.95, 0.5, 50, '2026-04-01', datetime('now','-1 days'), '2026-04-01 00:00:00', datetime('now','-1 days'))`);
182
- texts.forEach((t, i) => ins.run(`x/dom${i + 1}.md`, t));
183
- }
184
- test("B: novidade recente relevante não-servida entra no freshness slot", () => {
185
- const db = makeDb();
186
- seedDominants(db); // ids 1-4, salience alta, source_date recente
187
- // fresco: passa FRESH_MIN_IMP, recente, source_date null ⇒ recency neutra 0.5
188
- db.prepare(`INSERT INTO chunks (source_file, chunk_text, importance, pain, access_count, created_at, updated_at)
189
- VALUES ('x/fresco.md', 'achado novo relevante desta semana', 0.75, 0.2, 0, datetime('now','-1 days'), datetime('now','-1 days'))`).run(); // id 5
190
- const cfg = { ...CFG, freshSlots: 1 };
191
- const { current, alt } = buildBriefDiverse(db, { scope: "x", n: 3, format: "json" }, cfg, Date.now());
192
- const curIds = current.items.map((i) => i.id);
193
- const altIds = alt.items.map((i) => i.id);
194
- assert.ok(!curIds.includes(5), "fresco fica fora do brief atual (4 dominantes > fresco)");
195
- assert.ok(altIds.includes(5), "fresco entra via freshness slot no alt");
196
- });
197
- test("B: lixo recente (importance baixo) NÃO entra no freshness slot", () => {
198
- const db = makeDb();
199
- seedDominants(db); // ids 1-4 dominam os 3 slots
200
- db.prepare(`INSERT INTO chunks (source_file, chunk_text, importance, pain, access_count, created_at, updated_at)
201
- VALUES ('x/lixo.md', 'ruído recente irrelevante', 0.3, 0.2, 0, datetime('now','-1 days'), datetime('now','-1 days'))`).run(); // id 5
202
- const cfg = { ...CFG, freshSlots: 1 };
203
- const { alt } = buildBriefDiverse(db, { scope: "x", n: 3, format: "json" }, cfg, Date.now());
204
- assert.ok(!alt.items.map((i) => i.id).includes(5), "lixo abaixo de FRESH_MIN_IMP não vira freshness candidate");
205
- });
206
- // ─── handleBrief (shadow/active/off via env) ─────────────────────────────────
207
- function withEnv(vars, fn) {
208
- const saved = {};
209
- for (const k of Object.keys(vars)) {
210
- saved[k] = process.env[k];
211
- process.env[k] = vars[k];
212
- }
213
- try {
214
- fn();
215
- }
216
- finally {
217
- for (const k of Object.keys(vars)) {
218
- if (saved[k] === undefined)
219
- delete process.env[k];
220
- else
221
- process.env[k] = saved[k];
222
- }
223
- }
224
- }
225
- test("shadow: surface = brief ATUAL (não muda o que é servido)", () => {
226
- const db = makeDb();
227
- seed(db, [
228
- { source_file: "x/muito.md", chunk_text: "tópico alfa muito servido", importance: 0.6 },
229
- { source_file: "x/pouco.md", chunk_text: "tópico beta pouco servido", importance: 0.6 },
230
- ]);
231
- logServes(db, 1, 500, 1);
232
- const baseline = buildBrief(db, { scope: "x", n: 1, format: "json" });
233
- withEnv({ NOX_BRIEF_DIVERSITY: "shadow" }, () => {
234
- const out = handleBrief(db, { scope: "x", n: "1" });
235
- assert.equal(out.status, 200);
236
- assert.deepEqual(out.body.items.map((i) => i.id), baseline.items.map((i) => i.id), "shadow serve o brief atual, não o alt");
237
- });
238
- });
239
- test("active: surface = alt (penalty/freshness aplicados)", () => {
240
- const db = makeDb();
241
- seed(db, [
242
- { source_file: "x/muito.md", chunk_text: "tópico alfa muito servido aqui", importance: 0.6 },
243
- { source_file: "x/pouco.md", chunk_text: "tópico beta pouco servido aqui", importance: 0.6 },
244
- ]);
245
- logServes(db, 1, 500, 1);
246
- withEnv({ NOX_BRIEF_DIVERSITY: "active" }, () => {
247
- const out = handleBrief(db, { scope: "x", n: "1" });
248
- assert.equal(out.body.items[0].id, 2, "active serve o menos-servido");
249
- });
250
- });
251
- test("off (default): caminho v1.2 intocado", () => {
252
- const db = makeDb();
253
- seed(db, [{ source_file: "x/a.md", chunk_text: "conteúdo a" }, { source_file: "x/b.md", chunk_text: "conteúdo b" }]);
254
- const baseline = buildBrief(db, { scope: "x", n: 2, format: "json" });
255
- const out = handleBrief(db, { scope: "x", n: "2" });
256
- assert.deepEqual(out.body.items.map((i) => i.id), baseline.items.map((i) => i.id));
257
- });
258
- test("fail-open: erro no caminho diverso não derruba o priming", () => {
259
- const db = makeDb();
260
- seed(db, [{ source_file: "x/a.md", chunk_text: "conteúdo a" }]);
261
- // brief_log inexistente força erro nas queries de diversidade → cai pro atual
262
- withEnv({ NOX_BRIEF_DIVERSITY: "active" }, () => {
263
- const out = handleBrief(db, { scope: "x", n: "1" });
264
- assert.equal(out.status, 200, "serve mesmo com diversidade falhando");
265
- });
266
- });
@@ -1,287 +0,0 @@
1
- // F1 — testes do GET /api/brief (Session Priming Loop fase 1).
2
- // Spec: memoria-nox specs/2026-06-04-F1-api-brief-implementation.md (T5).
3
- //
4
- // Run: cd tools/nox-mem && npx tsc && node --test dist/__tests__/brief.test.js
5
- import { test } from "node:test";
6
- import assert from "node:assert/strict";
7
- import Database from "better-sqlite3";
8
- import { parseBriefParams, scopePatterns, extractOneLiner, titleFromSourceFile, buildBrief, renderBriefText, handleBrief, _resetBriefLogMemo, tokenSignature, isNearDup, } from "../api/brief.js";
9
- // ─── Fixture ─────────────────────────────────────────────────────────────────
10
- const NOW = Date.parse("2026-06-04T12:00:00Z");
11
- function makeDb() {
12
- const db = new Database(":memory:");
13
- db.exec(`
14
- CREATE TABLE chunks (
15
- id INTEGER PRIMARY KEY,
16
- source_file TEXT NOT NULL,
17
- chunk_text TEXT NOT NULL,
18
- chunk_type TEXT NOT NULL DEFAULT 'other',
19
- source_type TEXT,
20
- tier TEXT DEFAULT 'peripheral',
21
- pain REAL DEFAULT 0.2,
22
- importance REAL DEFAULT 0.5,
23
- retention_days INTEGER,
24
- source_date TEXT,
25
- created_at TEXT DEFAULT (datetime('now')),
26
- updated_at TEXT DEFAULT (datetime('now')),
27
- last_accessed_at TEXT,
28
- access_count INTEGER DEFAULT 0
29
- );
30
- `);
31
- _resetBriefLogMemo();
32
- return db;
33
- }
34
- function seed(db, rows) {
35
- const ins = db.prepare(`
36
- INSERT INTO chunks (source_file, chunk_text, chunk_type, pain, importance,
37
- access_count, created_at, updated_at, source_date)
38
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
39
- `);
40
- for (const r of rows) {
41
- ins.run(r.source_file, r.chunk_text ?? "conteúdo padrão", r.chunk_type ?? "other", r.pain ?? 0.2, r.importance ?? 0.5, r.access_count ?? 0, r.created_at ?? "2026-06-01 00:00:00", r.updated_at ?? "2026-06-01 00:00:00", r.source_date ?? null);
42
- }
43
- }
44
- // ─── parseBriefParams ────────────────────────────────────────────────────────
45
- test("params: scope obrigatório", () => {
46
- const r = parseBriefParams({});
47
- assert.equal(r.ok, false);
48
- });
49
- test("params: scope malformado rejeitado", () => {
50
- for (const bad of ["a%b", "../etc", "a b", "-inicio"]) {
51
- const r = parseBriefParams({ scope: bad });
52
- assert.equal(r.ok, false, `esperava rejeitar: ${bad}`);
53
- }
54
- });
55
- test("brief: underscore no scope é escapado no LIKE — a_b não casa aXb", () => {
56
- const db = makeDb();
57
- seed(db, [
58
- { source_file: "a_b/doc.md", chunk_text: "scope certo" },
59
- { source_file: "aXb/doc.md", chunk_text: "wildcard leak" },
60
- ]);
61
- const r = buildBrief(db, { scope: "a_b", n: 10, format: "json" }, NOW);
62
- assert.equal(r.items.length, 1);
63
- assert.equal(r.items[0].one_liner, "scope certo");
64
- });
65
- test("params: defaults n=10 format=json", () => {
66
- const r = parseBriefParams({ scope: "NUVIVI" });
67
- assert.ok(r.ok);
68
- if (r.ok) {
69
- assert.equal(r.params.n, 10);
70
- assert.equal(r.params.format, "json");
71
- }
72
- });
73
- test("params: n cap em 25", () => {
74
- const r = parseBriefParams({ scope: "NUVIVI", n: "999" });
75
- assert.ok(r.ok && r.params.n === 25);
76
- });
77
- test("params: since 30d/24h/2w aceitos, lixo rejeitado", () => {
78
- assert.ok(parseBriefParams({ scope: "x", since: "30d" }).ok);
79
- assert.ok(parseBriefParams({ scope: "x", since: "24h" }).ok);
80
- assert.ok(parseBriefParams({ scope: "x", since: "2w" }).ok);
81
- assert.equal(parseBriefParams({ scope: "x", since: "amanhã" }).ok, false);
82
- });
83
- // ─── scopePatterns ───────────────────────────────────────────────────────────
84
- test("scopePatterns: scope vira 4 namespaces; agent adiciona sessions/", () => {
85
- const p = scopePatterns("memoria-nox", "cipher");
86
- assert.ok(p.includes("memory/mac-docs/memoria-nox/%"));
87
- assert.ok(p.includes("shared/imports/Claude/Projetos/memoria-nox/%"));
88
- assert.ok(p.includes("sessions/cipher/%"));
89
- assert.equal(p.length, 5);
90
- });
91
- test("scopePatterns: global sem filtro de path", () => {
92
- assert.equal(scopePatterns("global").length, 0);
93
- assert.deepEqual(scopePatterns("global", "atlas"), ["sessions/atlas/%"]);
94
- });
95
- // ─── extractOneLiner / titleFromSourceFile ───────────────────────────────────
96
- test("one_liner: pula frontmatter e vazias, strip heading, cap 140", () => {
97
- assert.equal(extractOneLiner("---\n\n## Título Forte\ncorpo"), "Título Forte");
98
- assert.equal(extractOneLiner("- **item** bold"), "item bold");
99
- assert.equal(extractOneLiner(""), "");
100
- const longo = "x".repeat(300);
101
- assert.equal(extractOneLiner(longo).length, 140);
102
- });
103
- test("title: basename sem extensão", () => {
104
- assert.equal(titleFromSourceFile("memory/mac-docs/NUVIVI/relatorio-q2.md"), "relatorio-q2");
105
- });
106
- // ─── v1.1 polish (gate T7: quirks observados em prod) ───────────────────────
107
- test("v1.1 one_liner: strip de tags HTML (docs OCR/import)", () => {
108
- assert.equal(extractOneLiner("<u>CONTRATO DE COMPRA</u> e venda de ações"), "CONTRATO DE COMPRA e venda de ações");
109
- // linha só de tags é pulada
110
- assert.equal(extractOneLiner("<div><br/></div>\nconteúdo real"), "conteúdo real");
111
- });
112
- test("v1.1 age_days: usa source_date (idade do conteúdo), não updated_at tocado por cron", () => {
113
- const db = makeDb();
114
- seed(db, [{
115
- source_file: "x/doc-abril.md",
116
- source_date: "2026-04-21",
117
- created_at: "2026-05-25 00:00:00", // re-ingest pós-restore
118
- updated_at: "2026-06-04 01:00:00", // cron noturno tocou
119
- }]);
120
- const r = buildBrief(db, { scope: "x", n: 1, format: "json" }, NOW);
121
- assert.equal(r.items[0].age_days, 44); // 2026-04-21 → 2026-06-04
122
- });
123
- test("v1.1 dedup: cópia idêntica não gasta slot; próximo único preenche", () => {
124
- const db = makeDb();
125
- seed(db, [
126
- { source_file: "x/design-merge.md", chunk_text: "## Design de merge\ncorpo", importance: 0.9 },
127
- { source_file: "y/design-merge.md", chunk_text: "## Design de merge\ncorpo", importance: 0.8 }, // dupe (mesmo title+one_liner)
128
- { source_file: "x/outro-doc.md", chunk_text: "## Outro doc\ncorpo", importance: 0.3 },
129
- ]);
130
- const r = buildBrief(db, { scope: "global", n: 2, format: "json" }, NOW);
131
- assert.equal(r.items.length, 2);
132
- assert.equal(r.items[0].title, "design-merge");
133
- assert.equal(r.items[1].title, "outro-doc"); // dupe pulado, único entrou
134
- assert.ok(r.items[0].salience >= r.items[1].salience);
135
- });
136
- // ─── buildBrief ──────────────────────────────────────────────────────────────
137
- test("brief: filtra por scope — não vaza namespace alheio", () => {
138
- const db = makeDb();
139
- seed(db, [
140
- { source_file: "memory/mac-docs/NUVIVI/a.md", chunk_text: "doc nuvini" },
141
- { source_file: "memory/mac-docs/PESSOAL/b.md", chunk_text: "doc pessoal" },
142
- { source_file: "sessions/cipher/s1.md", chunk_text: "sessão cipher" },
143
- ]);
144
- const r = buildBrief(db, { scope: "NUVIVI", n: 10, format: "json" }, NOW);
145
- assert.equal(r.items.length, 1);
146
- assert.equal(r.items[0].one_liner, "doc nuvini");
147
- });
148
- test("brief: agent compõe em união com scope", () => {
149
- const db = makeDb();
150
- seed(db, [
151
- { source_file: "memory/mac-docs/NUVIVI/a.md" },
152
- { source_file: "sessions/cipher/s1.md" },
153
- { source_file: "sessions/atlas/s2.md" },
154
- ]);
155
- const r = buildBrief(db, { scope: "NUVIVI", agent: "cipher", n: 10, format: "json" }, NOW);
156
- assert.equal(r.items.length, 2); // NUVIVI + cipher; atlas fora
157
- });
158
- test("brief: ranking por salience — importance alta + acessado vence default antigo", () => {
159
- const db = makeDb();
160
- // chunk_texts distintos: corpos idênticos colapsariam por near-dup (v1.2a, correto)
161
- seed(db, [
162
- { source_file: "x/baixo.md", chunk_text: "registro antigo irrelevante sem acesso", importance: 0.1, pain: 0.2, access_count: 0, updated_at: "2025-01-01 00:00:00" },
163
- { source_file: "x/alto.md", chunk_text: "decisão crítica recente muito consultada", importance: 0.95, pain: 0.9, access_count: 40, updated_at: "2026-06-03 00:00:00" },
164
- ]);
165
- const r = buildBrief(db, { scope: "x", n: 2, format: "json" }, NOW);
166
- assert.equal(r.items[0].title, "alto");
167
- assert.ok(r.items[0].salience > r.items[1].salience);
168
- });
169
- test("brief: n limita itens; scope vazio = 200 com items []", () => {
170
- const db = makeDb();
171
- seed(db, [
172
- { source_file: "x/1.md" }, { source_file: "x/2.md" }, { source_file: "x/3.md" },
173
- ]);
174
- assert.equal(buildBrief(db, { scope: "x", n: 2, format: "json" }, NOW).items.length, 2);
175
- assert.equal(buildBrief(db, { scope: "inexistente", n: 5, format: "json" }, NOW).items.length, 0);
176
- });
177
- test("brief: since exclui updated_at antigo", () => {
178
- const db = makeDb();
179
- seed(db, [
180
- { source_file: "x/velho.md", updated_at: "2026-01-01 00:00:00" },
181
- { source_file: "x/novo.md" }, // default 2026-06-01 — mas since usa datetime('now') real;
182
- ]);
183
- // novo: updated_at = agora (insert com datetime explícito recente não dá — usar now real)
184
- db.prepare("UPDATE chunks SET updated_at = datetime('now') WHERE source_file = ?").run("x/novo.md");
185
- const r = buildBrief(db, { scope: "x", n: 10, format: "json", sinceSql: "-30 days" }, NOW);
186
- assert.equal(r.items.length, 1);
187
- assert.equal(r.items[0].title, "novo");
188
- });
189
- // ─── renderBriefText ─────────────────────────────────────────────────────────
190
- test("text: header + linhas no formato pointer; respeita budget", () => {
191
- const db = makeDb();
192
- seed(db, [{ source_file: "x/a.md", chunk_text: "## Lição\ncorpo", chunk_type: "lesson", pain: 0.9 }]);
193
- const r = buildBrief(db, { scope: "x", n: 5, format: "text" }, NOW);
194
- const txt = renderBriefText(r);
195
- assert.match(txt, /^# nox-mem brief — scope=x/);
196
- assert.match(txt, /\[lesson\|pain 0\.9\|\d+d\] a — Lição \(chk \d+\)/);
197
- });
198
- test("text: budget de ~1200 tokens trunca antes de n", () => {
199
- const db = makeDb();
200
- const rows = [];
201
- for (let i = 0; i < 25; i++) {
202
- rows.push({ source_file: `x/${"t".repeat(120)}-${i}.md`, chunk_text: "y".repeat(400) });
203
- }
204
- seed(db, rows);
205
- const r = buildBrief(db, { scope: "x", n: 25, format: "text" }, NOW);
206
- const txt = renderBriefText(r);
207
- assert.ok(txt.length / 4 <= 1300, `texto estourou budget: ~${Math.ceil(txt.length / 4)} tokens`);
208
- assert.ok(txt.split("\n").length - 2 < 25, "deveria truncar antes de 25 itens");
209
- });
210
- // ─── handleBrief (integração + invariantes) ──────────────────────────────────
211
- test("handle: 400 em scope ausente/inválido", () => {
212
- const db = makeDb();
213
- assert.equal(handleBrief(db, {}).status, 400);
214
- assert.equal(handleBrief(db, { scope: "a%b" }).status, 400);
215
- });
216
- test("handle: serve brief, loga em brief_log e NÃO toca access_count", () => {
217
- const db = makeDb();
218
- seed(db, [
219
- { source_file: "memory/mac-docs/NUVIVI/a.md", access_count: 7 },
220
- { source_file: "memory/mac-docs/NUVIVI/b.md", access_count: 0 },
221
- ]);
222
- const out = handleBrief(db, { scope: "NUVIVI" });
223
- assert.equal(out.status, 200);
224
- const logged = db.prepare("SELECT COUNT(*) c FROM brief_log WHERE scope='NUVIVI'").get();
225
- assert.equal(logged.c, 2);
226
- // Invariante central (§2.3): access_count orgânico permanece intocado.
227
- const counts = db.prepare("SELECT access_count FROM chunks ORDER BY id").all();
228
- assert.deepEqual(counts.map((r) => r.access_count), [7, 0]);
229
- });
230
- // ─── v1.2 (gate F3 real: brief do Nox) ───────────────────────────────────────
231
- test("v1.2a near-dup: variantes HEARTBEAT colapsam; itens distintos não", () => {
232
- const a = tokenSignature("nota", "Ler HEARTBEAT.md do workspace e seguir estritamente");
233
- const b = tokenSignature("nota", "Seguir HEARTBEAT.md estritamente, sem inferir tarefas");
234
- const c = tokenSignature("nota", "Contrato Malvas x Treviso x GLPG pendente");
235
- assert.ok(isNearDup(a, b), "variantes HEARTBEAT deveriam colapsar");
236
- assert.ok(!isNearDup(a, c), "itens distintos não podem colapsar");
237
- });
238
- test("v1.2a brief: só 1 variante HEARTBEAT sobrevive; slots vão pra itens novos", () => {
239
- const db = makeDb();
240
- seed(db, [
241
- { source_file: "x/n1.md", chunk_text: "Ler HEARTBEAT.md do workspace e seguir estritamente", importance: 0.9 },
242
- { source_file: "x/n2.md", chunk_text: "Seguir HEARTBEAT.md estritamente, sem inferir ou repetir tarefas", importance: 0.85 },
243
- { source_file: "x/n3.md", chunk_text: "Usar agents/nox/HEARTBEAT.md exatamente como está, seguir estritamente", importance: 0.8 },
244
- { source_file: "x/n4.md", chunk_text: "Contrato Malvas x Treviso x GLPG pendente", importance: 0.3 },
245
- { source_file: "x/n5.md", chunk_text: "Invoice Aspen dezembro janeiro — Sylinc", importance: 0.25 },
246
- ]);
247
- const r = buildBrief(db, { scope: "x", n: 3, format: "json" }, NOW);
248
- const liners = r.items.map((i) => i.one_liner);
249
- assert.equal(liners.filter((l) => l.includes("HEARTBEAT")).length, 1, "só 1 HEARTBEAT");
250
- assert.ok(liners.some((l) => l.includes("Malvas")));
251
- assert.ok(liners.some((l) => l.includes("Aspen")));
252
- });
253
- test("v1.2b união: agent traz sessions E itens globais high-salience", () => {
254
- const db = makeDb();
255
- seed(db, [
256
- // pool do agente (sessions/nox)
257
- { source_file: "sessions/nox/s1.md", chunk_text: "Pendência alfa do nox", importance: 0.7 },
258
- { source_file: "sessions/nox/s2.md", chunk_text: "Pendência beta do nox", importance: 0.65 },
259
- { source_file: "sessions/nox/s3.md", chunk_text: "Pendência gama do nox", importance: 0.6 },
260
- // pool global (alta salience — lições/incidents)
261
- { source_file: "memory/lessons/incident-x.md", chunk_text: "Lição incident gateway crítica", importance: 0.95, pain: 0.9, access_count: 50 },
262
- { source_file: "memory/lessons/regra-y.md", chunk_text: "Regra crítica de produção zeta", importance: 0.9, pain: 0.8, access_count: 30 },
263
- ]);
264
- const r = buildBrief(db, { scope: "global", agent: "nox", n: 4, format: "json" }, NOW);
265
- const fromAgent = r.items.filter((i) => i.one_liner.includes("nox")).length;
266
- const fromGlobal = r.items.filter((i) => i.one_liner.includes("incident") || i.one_liner.includes("Regra")).length;
267
- assert.ok(fromAgent >= 2, `esperava ≥2 do agente, veio ${fromAgent}`);
268
- assert.ok(fromGlobal >= 2, `esperava ≥2 globais, veio ${fromGlobal}`);
269
- });
270
- test("v1.2b backfill: pool global magro ⇒ agente preenche o resto", () => {
271
- const db = makeDb();
272
- seed(db, [
273
- { source_file: "sessions/lex/s1.md", chunk_text: "Item um do lex" },
274
- { source_file: "sessions/lex/s2.md", chunk_text: "Item dois do lex" },
275
- { source_file: "sessions/lex/s3.md", chunk_text: "Item três do lex" },
276
- { source_file: "sessions/lex/s4.md", chunk_text: "Item quatro do lex" },
277
- ]);
278
- const r = buildBrief(db, { scope: "global", agent: "lex", n: 4, format: "json" }, NOW);
279
- assert.equal(r.items.length, 4, "backfill deve completar os 4 slots só com o agente");
280
- });
281
- test("handle: format=text retorna text/plain pronto pra hook", () => {
282
- const db = makeDb();
283
- seed(db, [{ source_file: "sessions/cipher/s.md", chunk_text: "## Estado\nok" }]);
284
- const out = handleBrief(db, { scope: "global", agent: "cipher", format: "text" });
285
- assert.equal(out.status, 200);
286
- assert.ok("text" in out && out.text.startsWith("# nox-mem brief — scope=global agent=cipher"));
287
- });
@@ -1,66 +0,0 @@
1
- // Item 2 plano Cipher simbiose — churn detection por embedding KNN.
2
- // Spec: memoria-nox specs/2026-06-05-cipher-simbiose-itens-1-2-3.md (Task 4).
3
- //
4
- // Run: cd tools/nox-mem && npx tsc && node --test dist/__tests__/churn.test.js
5
- import { test } from "node:test";
6
- import assert from "node:assert/strict";
7
- import Database from "better-sqlite3";
8
- import * as sqliteVec from "sqlite-vec";
9
- import { detectChurn, churnReportMd } from "../churn.js";
10
- const DIMS = 8;
11
- function mkDb() {
12
- const db = new Database(":memory:");
13
- sqliteVec.load(db);
14
- db.exec(`
15
- CREATE TABLE chunks (id INTEGER PRIMARY KEY, source_file TEXT, chunk_text TEXT, chunk_type TEXT, created_at TEXT);
16
- CREATE VIRTUAL TABLE vec_chunks USING vec0(embedding float[${DIMS}]);
17
- CREATE TABLE vec_chunk_map (vec_rowid INTEGER PRIMARY KEY, chunk_id INTEGER);
18
- `);
19
- return db;
20
- }
21
- function insert(db, id, text, createdAt, emb, type = "team") {
22
- db.prepare("INSERT INTO chunks (id, source_file, chunk_text, chunk_type, created_at) VALUES (?,?,?,?,?)")
23
- .run(id, `src-${id}.md`, text, type, createdAt);
24
- const r = db.prepare("INSERT INTO vec_chunks (embedding) VALUES (?)").run(JSON.stringify(emb));
25
- db.prepare("INSERT INTO vec_chunk_map (vec_rowid, chunk_id) VALUES (?,?)").run(r.lastInsertRowid, id);
26
- }
27
- // vetor unitário 8d parametrizado por x — e(1.00) ≈ e(1.02), ortogonal a e(-5)
28
- function e(x) {
29
- const v = [x, 1, 0, 0, 0, 0, 0, 0];
30
- const n = Math.hypot(...v);
31
- return v.map((a) => a / n);
32
- }
33
- test("detectChurn flaga re-decisão (novo similar a antigo) e ignora tópico novo", () => {
34
- const db = mkDb();
35
- insert(db, 1, "Decisão: porta API 18802", "2026-04-01 00:00:00", e(1.0)); // antigo, tópico T
36
- insert(db, 2, "Re-decisão: porta API mantida", "2026-06-01 12:00:00", e(1.02)); // novo ≈ T → churn
37
- insert(db, 3, "Decisão: tema ortogonal", "2026-06-02 09:00:00", e(-5)); // novo, sem par → não
38
- const pairs = detectChurn(db, { since: "2026-05-01T00:00:00Z", threshold: 0.8, k: 5 });
39
- assert.equal(pairs.length, 1);
40
- assert.equal(pairs[0].newChunkId, 2);
41
- assert.equal(pairs[0].oldChunkId, 1);
42
- assert.ok(pairs[0].similarity >= 0.8, `sim=${pairs[0].similarity}`);
43
- });
44
- test("detectChurn ignora pares novo↔novo (só vizinho antigo conta)", () => {
45
- const db = mkDb();
46
- insert(db, 10, "Novo A sobre tópico Z", "2026-06-01 10:00:00", e(3.0));
47
- insert(db, 11, "Novo B sobre tópico Z", "2026-06-02 10:00:00", e(3.05));
48
- const pairs = detectChurn(db, { since: "2026-05-01T00:00:00Z", threshold: 0.8, k: 5 });
49
- assert.equal(pairs.length, 0);
50
- });
51
- test("detectChurn respeita filtro de types quando passado", () => {
52
- const db = mkDb();
53
- insert(db, 20, "Decisão antiga", "2026-04-01 00:00:00", e(2.0), "decision");
54
- insert(db, 21, "Re-decisão nova", "2026-06-01 00:00:00", e(2.02), "daily");
55
- const all = detectChurn(db, { since: "2026-05-01T00:00:00Z", threshold: 0.8 });
56
- assert.equal(all.length, 1); // sem filtro: pega
57
- const onlyDecision = detectChurn(db, { since: "2026-05-01T00:00:00Z", threshold: 0.8, types: ["decision"] });
58
- assert.equal(onlyDecision.length, 0); // novo é daily → fora do filtro
59
- });
60
- test("churnReportMd renderiza pares e caso vazio", () => {
61
- const md = churnReportMd([], "2026-05-01T00:00:00Z");
62
- assert.match(md, /Nenhum churn/);
63
- const md2 = churnReportMd([{ newChunkId: 2, newFile: "a.md", newText: "Re-decisão: porta API", newCreatedAt: "2026-06-01 12:00:00", oldChunkId: 1, oldFile: "b.md", oldText: "Decisão: porta API", oldCreatedAt: "2026-04-01 00:00:00", similarity: 0.97 }], "2026-05-01T00:00:00Z");
64
- assert.match(md2, /0\.97/);
65
- assert.match(md2, /#2/);
66
- });