nox-mem 3.3.0 → 3.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +82 -31
- package/dist/api/answer.js +22 -0
- package/dist/api-server.js +22 -3
- package/dist/cli/answer.js +39 -1
- package/dist/db.js +47 -24
- package/dist/doctor.js +108 -29
- package/dist/embed.js +53 -3
- package/dist/index.js +73 -17
- package/dist/lib/answer/index.js +3 -2
- package/dist/lib/answer/retrieval.js +6 -4
- package/dist/lib/answer/temporal.js +51 -0
- package/dist/lib/api-port.js +16 -0
- package/dist/lib/dates.js +98 -0
- package/dist/lib/db-path.js +57 -0
- package/dist/lib/ingest-many.js +49 -0
- package/dist/lib/op-audit.js +19 -12
- package/dist/lib/reranker.js +4 -1
- package/dist/mcp/tools/answer.js +23 -0
- package/dist/mcp-server.js +45 -6
- package/dist/reflect.js +2 -2
- package/dist/reindex-errors.js +45 -0
- package/dist/reindex.js +116 -23
- package/dist/search.js +111 -16
- package/package.json +7 -2
- package/prompts/consolidate.txt +13 -0
- package/prompts/digest.txt +5 -0
- package/dist/__tests__/brief-diversity.test.js +0 -266
- package/dist/__tests__/brief.test.js +0 -287
- package/dist/__tests__/churn.test.js +0 -66
- package/dist/__tests__/edge-typing.test.js +0 -99
- package/dist/__tests__/ingest-event.test.js +0 -151
- package/dist/__tests__/op-audit-e2e.test.js +0 -130
- package/dist/__tests__/pragma-alignment.test.js +0 -123
- package/dist/__tests__/reranker.test.js +0 -326
- package/dist/__tests__/retention.test.js +0 -99
- package/dist/__tests__/search-track-access.test.js +0 -49
- package/dist/__tests__/session-distill-sources.test.js +0 -98
- package/dist/__tests__/spo-injection.test.js +0 -172
- package/dist/__tests__/telemetry-per-chunk.test.js +0 -110
- package/dist/__tests__/temporal-detector.test.js +0 -103
- package/dist/lib/answer/__tests__/e2e-gemini.test.js +0 -229
- package/dist/lib/answer/__tests__/integration-sqlite.test.js +0 -388
- package/dist/lib/answer/__tests__/integration.test.js +0 -347
- package/dist/lib/answer/__tests__/prompt.test.js +0 -117
- package/dist/lib/answer/__tests__/t5-t10.test.js +0 -501
- package/dist/lib/api/__tests__/safe-error-message.test.js +0 -155
- package/dist/lib/auth/__tests__/localhost-guard.test.js +0 -144
- package/dist/lib/error-sanitizer/__tests__/sanitize.test.js +0 -354
- package/dist/lib/events/__tests__/bus.test.js +0 -208
- package/dist/lib/op-audit-extension/__tests__/ran-at-guard.test.js +0 -109
- package/dist/lib/regex-extract/__tests__/extractor.test.js +0 -197
- package/dist/lib/regex-extract/__tests__/frontmatter.test.js +0 -75
- package/dist/lib/regex-extract/__tests__/ingest-router-l4.test.js +0 -139
- package/dist/lib/regex-extract/__tests__/production-wire.test.js +0 -177
- package/dist/lib/regex-extract/__tests__/reconcile.test.js +0 -170
- package/dist/lib/regex-extract/__tests__/strip-code.test.js +0 -36
- package/dist/privacy/__tests__/filter.test.js +0 -352
- package/dist/providers/__tests__/conformance-extended.test.js +0 -249
- package/dist/providers/__tests__/conformance.test.js +0 -98
- package/dist/providers/__tests__/cost-cap.test.js +0 -151
- package/dist/providers/__tests__/e2e-real.test.js +0 -79
- package/dist/providers/__tests__/factory.test.js +0 -80
- package/dist/providers/__tests__/fallback.test.js +0 -223
- package/dist/providers/__tests__/gemini.test.js +0 -191
- package/dist/providers/__tests__/health.test.js +0 -128
- package/dist/providers/__tests__/telemetry.test.js +0 -219
|
@@ -1,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
|
-
});
|
|
@@ -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,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
|
-
});
|