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
package/dist/search.js CHANGED
@@ -6,6 +6,7 @@ import { dedupe } from "./search-dedup.js";
6
6
  import { calculateSalience, calculateSalienceLegacy, getSalienceMode } from "./salience.js";
7
7
  import { rerankByTemporalProximity, logTemporalProbe } from "./temporal-retrieval.js";
8
8
  import { countQueryEntities } from "./query-entity-count.js";
9
+ import { buildTemporalClause } from "./lib/dates.js";
9
10
  // ─── Boost configuration (Fase 1.7a + A-boost-stack-wiring 2026-05-19) ────────
10
11
  //
11
12
  // G3 ablation (PR #146, 2026-05-19) proved every boost below was INERT in the
@@ -305,16 +306,81 @@ function recordAccess(db, ids, enabled) {
305
306
  const placeholders = valid.map(() => "?").join(",");
306
307
  db.prepare(`UPDATE chunks SET access_count = access_count + 1, last_accessed_at = ? WHERE id IN (${placeholders})`).run(ts, ...valid);
307
308
  }
308
- export function search(query, limit = 5, trackAccess = true) {
309
+ // ─── FTS5 OR fallback (keyless installs) ─────────────────────────────────────
310
+ //
311
+ // FTS5 reads a space-separated query as an AND of every term, so a natural
312
+ // language question ("when was the zebra migration") matches nothing unless
313
+ // every filler word is in the chunk. With embeddings the semantic branch covers
314
+ // that; without a key it does not. When — and only when — the AND query returns
315
+ // zero rows, search() retries with an OR of the content terms.
316
+ //
317
+ // Gate NOX_FTS_OR_FALLBACK: "on" always, "off" never, unset/"auto" only when the
318
+ // RESOLVED embedding provider has no key (production has one ⇒ unchanged there).
319
+ // Read at call time, never frozen at import, so it stays testable in-process.
320
+ const FTS_STOPWORDS = new Set([
321
+ // EN
322
+ "the", "a", "an", "of", "to", "in", "on", "at", "for", "is", "was", "are", "were",
323
+ "be", "been", "do", "does", "did", "what", "when", "where", "who", "why", "how",
324
+ "which", "that", "this", "with", "from", "and", "or", "not",
325
+ // PT
326
+ "o", "a", "os", "as", "um", "uma", "de", "do", "da", "dos", "das", "em", "no", "na",
327
+ "nos", "nas", "para", "por", "com", "que", "qual", "quando", "onde", "quem", "como",
328
+ "se", "é", "foi", "são", "era", "ser", "e", "ou", "não",
329
+ ]);
330
+ export function ftsOrFallbackEnabled(env = process.env) {
331
+ const mode = (env.NOX_FTS_OR_FALLBACK ?? "auto").trim().toLowerCase();
332
+ if (mode === "on")
333
+ return true;
334
+ if (mode === "off")
335
+ return false;
336
+ return !hasResolvedEmbeddingKey(env);
337
+ }
338
+ /**
339
+ * True when the embedding provider that selectEmbeddingProvider() would resolve
340
+ * (NOX_EMBEDDING_PROVIDER, alias NOX_EMBED_PROVIDER, default "gemini") has the
341
+ * key it needs. Only THAT provider's key counts: a stray OPENAI_API_KEY in the
342
+ * shell of someone on the default gemini provider must not switch the fallback
343
+ * off, because search would then have neither embeddings nor OR. "voyage" is a
344
+ * stub that cannot embed and unknown names throw, so neither has a usable key.
345
+ * Key names mirror src/providers/index.ts.
346
+ */
347
+ function hasResolvedEmbeddingKey(env) {
348
+ const provider = (env.NOX_EMBEDDING_PROVIDER || env.NOX_EMBED_PROVIDER || "gemini").trim().toLowerCase();
349
+ const generic = env.NOX_EMBEDDING_API_KEY || env.NOX_EMBED_API_KEY;
350
+ switch (provider) {
351
+ case "gemini":
352
+ return Boolean(generic || env.GEMINI_API_KEY);
353
+ case "openai":
354
+ return Boolean(generic || env.OPENAI_API_KEY);
355
+ default:
356
+ return false;
357
+ }
358
+ }
359
+ /** OR expression of the non-stopword terms, each double-quoted; null if none is left. */
360
+ export function buildFtsOrQuery(sanitized) {
361
+ const seen = new Set();
362
+ const terms = [];
363
+ for (const raw of sanitized.split(/\s+/)) {
364
+ const t = raw.toLowerCase();
365
+ if (!t || FTS_STOPWORDS.has(t) || seen.has(t))
366
+ continue;
367
+ seen.add(t);
368
+ terms.push(`"${raw.replace(/"/g, '""')}"`);
369
+ }
370
+ return terms.length > 0 ? terms.join(" OR ") : null;
371
+ }
372
+ export function search(query, limit = 5, trackAccess = true, filter) {
309
373
  const db = getDb();
310
374
  const sanitized = query.replace(/[^\p{L}\p{N}\s]/gu, " ").replace(/\s+/g, " ").trim();
311
375
  if (!sanitized)
312
376
  return [];
313
377
  // G10d: compute entity count once per query (amortised via cache, <1ms hot path).
314
378
  const { count: queryEntityCount } = countQueryEntities(query, db);
315
- let rows;
316
- try {
317
- rows = db.prepare(`
379
+ // P3 temporal filter: hard SQL pre-filter, applied before LIMIT so the 20
380
+ // candidates are drawn from the allowed window. Never a ranking term.
381
+ // Without a filter the statement is byte-identical to the unfiltered one.
382
+ const temporal = buildTemporalClause(filter);
383
+ const runFts = (match) => db.prepare(`
318
384
  SELECT c.id, c.source_file, c.chunk_type, c.chunk_text, c.source_date,
319
385
  c.tier, c.source_type, c.section, c.section_boost,
320
386
  c.pain, c.importance, c.retention_days, c.created_at, c.last_accessed_at,
@@ -322,13 +388,29 @@ export function search(query, limit = 5, trackAccess = true) {
322
388
  bm25(chunks_fts, 1.0, 0.5, 0.5) as rank
323
389
  FROM chunks_fts
324
390
  JOIN chunks c ON c.id = chunks_fts.rowid
325
- WHERE chunks_fts MATCH ?
391
+ WHERE chunks_fts MATCH ?${temporal ? ` AND ${temporal.sql}` : ""}
326
392
  ORDER BY rank LIMIT 20
327
- `).all(sanitized);
393
+ `).all(match, ...(temporal?.params ?? []));
394
+ let rows;
395
+ try {
396
+ rows = runFts(sanitized);
328
397
  }
329
398
  catch {
330
399
  return [];
331
400
  }
401
+ // OR fallback: only when the AND query found nothing, so an existing result
402
+ // set is never reordered or extended. Same temporal fragment and params.
403
+ if (rows.length === 0 && ftsOrFallbackEnabled()) {
404
+ const orQuery = buildFtsOrQuery(sanitized);
405
+ if (orQuery) {
406
+ try {
407
+ rows = runFts(orQuery);
408
+ }
409
+ catch {
410
+ return [];
411
+ }
412
+ }
413
+ }
332
414
  const now = new Date();
333
415
  const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
334
416
  .toISOString().split("T")[0];
@@ -367,21 +449,34 @@ export function search(query, limit = 5, trackAccess = true) {
367
449
  recordAccess(db, results.map((r) => r.id), trackAccess);
368
450
  return results;
369
451
  }
370
- export async function searchSemantic(query, limit = 5, trackAccess = true) {
452
+ export async function searchSemantic(query, limit = 5, trackAccess = true, filter) {
453
+ const temporal = buildTemporalClause(filter);
371
454
  try {
372
- const { embedText, semanticSearch, ensureVecTable, countEmbedded } = await import("./embed.js");
455
+ const { embedText, semanticSearch, ensureVecTable, countEmbedded, queryEmbedTimeoutMs } = await import("./embed.js");
373
456
  const db = getDb();
374
457
  ensureVecTable(db);
375
458
  // Check if index has any embeddings
376
459
  const vecCount = countEmbedded(db);
377
460
  if (vecCount === 0) {
378
461
  console.error("[WARN] Vector index empty — run 'nox-mem vectorize' first. Falling back to FTS5.");
379
- return search(query, limit, trackAccess);
462
+ return search(query, limit, trackAccess, filter);
380
463
  }
381
464
  // G10d: compute entity count once per query (shared cache with FTS path).
382
465
  const { count: queryEntityCount } = countQueryEntities(query, db);
383
- const queryEmbedding = await embedText(query);
384
- const rows = semanticSearch(db, queryEmbedding, limit * 2);
466
+ // Bounded: a slow provider falls back to FTS5 through the catch below.
467
+ const queryEmbedding = await embedText(query, { timeoutMs: queryEmbedTimeoutMs() });
468
+ // vec0 KNN cannot take a WHERE on chunk columns, so the temporal filter is
469
+ // applied to the KNN candidates. Over-fetch when filtering, otherwise a
470
+ // narrow window would leave the top-k almost empty.
471
+ // Capped: the candidate ids go into an IN (...) list, and an uncapped
472
+ // `?limit=5000` would ask for 100k bound variables (SQLite max 32766).
473
+ const knnK = temporal ? Math.max(limit * 2, Math.min(Math.max(limit * 20, 200), 2000)) : limit * 2;
474
+ let rows = semanticSearch(db, queryEmbedding, knnK);
475
+ if (temporal && rows.length > 0) {
476
+ const ids = rows.map((r) => r.chunk_id).filter(Boolean);
477
+ const allowed = new Set(db.prepare(`SELECT c.id FROM chunks c WHERE c.id IN (${ids.map(() => "?").join(",")}) AND ${temporal.sql}`).all(...ids, ...temporal.params).map((r) => r.id));
478
+ rows = rows.filter((r) => allowed.has(r.chunk_id)).slice(0, limit * 2);
479
+ }
385
480
  if (rows.length === 0)
386
481
  return [];
387
482
  // Fetch boost-stack columns in one shot.
@@ -454,7 +549,7 @@ export async function searchSemantic(query, limit = 5, trackAccess = true) {
454
549
  catch (err) {
455
550
  // Fallback to FTS if vector index not ready
456
551
  console.error("[WARN] Semantic search failed, falling back to FTS:", err.message);
457
- return search(query, limit, trackAccess);
552
+ return search(query, limit, trackAccess, filter);
458
553
  }
459
554
  }
460
555
  // ─── Hybrid search (FTS5 + semantic, expanded, RRF-fused, deduped) ───────────
@@ -479,19 +574,19 @@ function logTelemetry(query, variantsCount, resultsCount, hasSemantic, latencyMs
479
574
  // telemetria nunca derruba a search
480
575
  }
481
576
  }
482
- export async function searchHybrid(query, limit = 5, trackAccess = true) {
577
+ export async function searchHybrid(query, limit = 5, trackAccess = true, filter) {
483
578
  const t0 = Date.now();
484
579
  const perVariantLimit = limit * 2;
485
580
  // Kick off original-query searches IMMEDIATELY and expansion in parallel.
486
581
  // Total time = max(expansion + variantFTS, originalFTS+semantic) — does not block
487
582
  // the original search behind a 500-1500ms Gemini call.
488
- const originalFtsPromise = Promise.resolve(search(query.trim(), perVariantLimit, trackAccess));
489
- const semPromise = searchSemantic(query.trim(), perVariantLimit * 2, trackAccess);
583
+ const originalFtsPromise = Promise.resolve(search(query.trim(), perVariantLimit, trackAccess, filter));
584
+ const semPromise = searchSemantic(query.trim(), perVariantLimit * 2, trackAccess, filter);
490
585
  const expansionPromise = expandQuery(query);
491
586
  const expansion = await expansionPromise;
492
587
  const variants = expansion.variants;
493
588
  // Variants (excluding the original, which is already running) → FTS only.
494
- const extraVariantFtsPromises = variants.slice(1).map((v) => Promise.resolve(search(v, perVariantLimit, trackAccess)));
589
+ const extraVariantFtsPromises = variants.slice(1).map((v) => Promise.resolve(search(v, perVariantLimit, trackAccess, filter)));
495
590
  const allBatches = await Promise.all([
496
591
  originalFtsPromise,
497
592
  ...extraVariantFtsPromises,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nox-mem",
3
- "version": "3.3.0",
3
+ "version": "3.5.0",
4
4
  "description": "Pain-weighted hybrid memory engine: FTS5 + semantic search + knowledge graph, self-hosted on any Linux VPS.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -38,10 +38,15 @@
38
38
  "node": ">=20"
39
39
  },
40
40
  "bin": {
41
- "nox-mem": "dist/index.js"
41
+ "nox-mem": "dist/index.js",
42
+ "nox-mem-mcp": "dist/mcp-server.js",
43
+ "nox-mem-api": "dist/api-server.js"
42
44
  },
43
45
  "files": [
44
46
  "dist",
47
+ "!dist/**/__tests__/**",
48
+ "!dist/**/*.test.js",
49
+ "prompts",
45
50
  "README.md",
46
51
  "LICENSE"
47
52
  ],
@@ -0,0 +1,13 @@
1
+ Extraia do texto abaixo todos os fatos relevantes.
2
+ Retorne APENAS um JSON com esta estrutura exata:
3
+ {
4
+ "decisions": [{"text": "descrição da decisão", "permanent": true}],
5
+ "lessons": [{"text": "descrição da lição", "type": "strategic"}],
6
+ "people": [{"name": "Nome Completo", "info": "informação relevante"}],
7
+ "projects": [{"name": "Nome Projeto", "update": "atualização"}],
8
+ "pending": [{"text": "descrição", "owner": "quem", "deadline": "quando"}]
9
+ }
10
+ Use arrays vazios se não houver itens daquela categoria.
11
+ Tipo de lessons: "strategic" para permanentes, "tactical" para temporárias.
12
+ Texto:
13
+ ---
@@ -0,0 +1,5 @@
1
+ Resuma a semana em 3-5 bullets objetivos.
2
+ Inclua: decisões-chave, lições aprendidas, progresso de projetos, pendências.
3
+ Formato: Markdown com bullets. Máximo 500 palavras. Português direto.
4
+ Dados da semana:
5
+ ---
@@ -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
- });