nox-mem 3.4.0 → 3.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +62 -33
- package/dist/api/answer.js +22 -0
- package/dist/api-server.js +4 -14
- package/dist/cli/answer.js +39 -1
- package/dist/db.js +31 -20
- package/dist/doctor.js +5 -4
- package/dist/embed.js +53 -3
- package/dist/index.js +16 -10
- 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/db-path.js +13 -1
- package/dist/lib/ingest-many.js +49 -0
- package/dist/lib/query-params.js +19 -0
- package/dist/mcp/tools/answer.js +23 -0
- package/dist/mcp-server.js +36 -5
- package/dist/reflect.js +2 -2
- package/dist/reindex-errors.js +19 -0
- package/dist/reindex.js +12 -2
- package/dist/search.js +27 -6
- package/package.json +4 -1
- 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__/fts-or-fallback.test.js +0 -115
- 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__/reindex-dedup.test.js +0 -80
- package/dist/__tests__/reindex-safety.test.js +0 -116
- 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/__tests__/temporal-filter.test.js +0 -117
- 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,501 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* src/lib/answer/__tests__/t5-t10.test.ts
|
|
3
|
-
*
|
|
4
|
-
* P1 T5-T10 integration tests:
|
|
5
|
-
* - T5: citation accuracy on golden Q/A set (validation harness)
|
|
6
|
-
* - T6: hallucination_after_retry telemetry hook fires
|
|
7
|
-
* - T7: telemetry insert/query (privacy: question_hash only, no raw)
|
|
8
|
-
* - T8: CLI argv parsing + render (human + json) + exit codes
|
|
9
|
-
* - T9: HTTP body validation + status codes + headers
|
|
10
|
-
* - T10: MCP tool input schema + result envelope
|
|
11
|
-
*
|
|
12
|
-
* Runner: node:test (node --test). Zero network — MockProvider only.
|
|
13
|
-
* Target: 15+ cases (we land 25 below).
|
|
14
|
-
*/
|
|
15
|
-
import { describe, it, beforeEach } from "node:test";
|
|
16
|
-
import assert from "node:assert/strict";
|
|
17
|
-
import { __setRawSearchForTests, MockProvider, AnswerError, } from "../index.js";
|
|
18
|
-
import { answer as realAnswer } from "../index.js";
|
|
19
|
-
import { hashQuestion, mapFailureReason, estimateCost, recordAnswer, InMemoryTelemetryStore, INSERT_SQL, } from "../telemetry.js";
|
|
20
|
-
import { parseArgs, renderHuman, renderJson, runCli, HELP_TEXT, CliArgError, } from "../../../cli/answer.js";
|
|
21
|
-
import { handleAnswerRequest, validateBody, statusFromReason, REQUEST_SCHEMA, } from "../../../api/answer.js";
|
|
22
|
-
import { noxMemAnswerTool, parseInput, INPUT_SCHEMA, } from "../../../mcp/tools/answer.js";
|
|
23
|
-
// ─── Fixtures ──────────────────────────────────────────────────────────────
|
|
24
|
-
function goldenChunks() {
|
|
25
|
-
return [
|
|
26
|
-
{
|
|
27
|
-
chunk_id: 1001,
|
|
28
|
-
file_path: "memory/entities/feedback/salience.md",
|
|
29
|
-
line_range: "L5-L9",
|
|
30
|
-
content: "Salience formula: salience = recency × pain × importance.",
|
|
31
|
-
content_hash: "h-salience",
|
|
32
|
-
score: 0.91,
|
|
33
|
-
},
|
|
34
|
-
{
|
|
35
|
-
chunk_id: 1002,
|
|
36
|
-
file_path: "memory/entities/decision/d41.md",
|
|
37
|
-
content: "D41 #1: default model gemini-2.5-flash-lite.",
|
|
38
|
-
content_hash: "h-d41",
|
|
39
|
-
score: 0.87,
|
|
40
|
-
},
|
|
41
|
-
{
|
|
42
|
-
chunk_id: 1003,
|
|
43
|
-
file_path: "memory/entities/lesson/never-sed.md",
|
|
44
|
-
content: "Never sed -i on .db files — corrupts page boundaries.",
|
|
45
|
-
content_hash: "h-sed",
|
|
46
|
-
score: 0.73,
|
|
47
|
-
},
|
|
48
|
-
];
|
|
49
|
-
}
|
|
50
|
-
function bindFixture() {
|
|
51
|
-
__setRawSearchForTests(async (_q, _k) => goldenChunks());
|
|
52
|
-
}
|
|
53
|
-
function bindEmpty() {
|
|
54
|
-
__setRawSearchForTests(async () => []);
|
|
55
|
-
}
|
|
56
|
-
beforeEach(() => bindFixture());
|
|
57
|
-
function answerWith(text) {
|
|
58
|
-
return (opts) => {
|
|
59
|
-
const o = {
|
|
60
|
-
...opts,
|
|
61
|
-
providerOverride: new MockProvider([text], 1),
|
|
62
|
-
};
|
|
63
|
-
return realAnswer(o);
|
|
64
|
-
};
|
|
65
|
-
}
|
|
66
|
-
// ─── T5 — citation accuracy on golden subset ───────────────────────────────
|
|
67
|
-
describe("T5 citation accuracy (golden subset)", () => {
|
|
68
|
-
it("resolves cited markers to real chunk_ids in order of first appearance", async () => {
|
|
69
|
-
const llmText = "Salience uses [chunk_1]. The default model is per [chunk_2].";
|
|
70
|
-
const run = answerWith(llmText);
|
|
71
|
-
const res = await run({ question: "What is salience?" });
|
|
72
|
-
assert.strictEqual(res.citations.length, 2);
|
|
73
|
-
assert.strictEqual(res.citations[0]?.marker_id, "chunk_1");
|
|
74
|
-
assert.strictEqual(res.citations[0]?.chunk_id, 1001);
|
|
75
|
-
assert.strictEqual(res.citations[1]?.marker_id, "chunk_2");
|
|
76
|
-
assert.strictEqual(res.citations[1]?.chunk_id, 1002);
|
|
77
|
-
});
|
|
78
|
-
it("dedupes repeated markers (same marker cited twice = one citation)", async () => {
|
|
79
|
-
const run = answerWith("[chunk_1] and again [chunk_1] and [chunk_2].");
|
|
80
|
-
const res = await run({ question: "anything" });
|
|
81
|
-
const ids = res.citations.map((c) => c.marker_id);
|
|
82
|
-
assert.deepStrictEqual(ids, ["chunk_1", "chunk_2"]);
|
|
83
|
-
});
|
|
84
|
-
it("citation snippets are ≤200 chars + line_range preserved", async () => {
|
|
85
|
-
const run = answerWith("[chunk_1] - salience.");
|
|
86
|
-
const res = await run({ question: "salience?" });
|
|
87
|
-
assert.ok(res.citations[0].snippet.length <= 200);
|
|
88
|
-
assert.strictEqual(res.citations[0].line_range, "L5-L9");
|
|
89
|
-
});
|
|
90
|
-
});
|
|
91
|
-
// ─── T6 — hallucination_after_retry telemetry hook ─────────────────────────
|
|
92
|
-
describe("T6 hallucination_after_retry telemetry", () => {
|
|
93
|
-
it("records telemetry row with failed_reason='hallucinated_citation' (mapped)", async () => {
|
|
94
|
-
const store = new InMemoryTelemetryStore();
|
|
95
|
-
// Mock LLM hallucinates twice → AnswerError with reason='hallucination_after_retry'.
|
|
96
|
-
const hallucinator = new MockProvider(["[chunk_99]", "[chunk_42]"], 0);
|
|
97
|
-
try {
|
|
98
|
-
await realAnswer({
|
|
99
|
-
question: "Adversarial",
|
|
100
|
-
providerOverride: hallucinator,
|
|
101
|
-
});
|
|
102
|
-
assert.fail("should have thrown");
|
|
103
|
-
}
|
|
104
|
-
catch (err) {
|
|
105
|
-
assert.ok(err instanceof AnswerError);
|
|
106
|
-
assert.strictEqual(err.reason, "hallucination_after_retry");
|
|
107
|
-
// Caller (CLI/HTTP/MCP) is responsible for recording on failure — simulate:
|
|
108
|
-
recordAnswer(store, {
|
|
109
|
-
question: "Adversarial",
|
|
110
|
-
citationCount: 0,
|
|
111
|
-
metadata: {
|
|
112
|
-
latency_ms: err.metadata.latency_ms ?? 0,
|
|
113
|
-
tokens_in: 0,
|
|
114
|
-
tokens_out: 0,
|
|
115
|
-
provider: "mock",
|
|
116
|
-
model: "gemini-2.5-flash-lite",
|
|
117
|
-
retrieval_count: 3,
|
|
118
|
-
fallback_used: true,
|
|
119
|
-
failed_reason: err.reason,
|
|
120
|
-
},
|
|
121
|
-
sessionId: "test-session",
|
|
122
|
-
});
|
|
123
|
-
}
|
|
124
|
-
assert.strictEqual(store.rows.length, 1);
|
|
125
|
-
assert.strictEqual(store.rows[0].failed_reason, "hallucinated_citation");
|
|
126
|
-
assert.strictEqual(store.rows[0].fallback_used, 1);
|
|
127
|
-
assert.strictEqual(store.rows[0].session_id, "test-session");
|
|
128
|
-
});
|
|
129
|
-
});
|
|
130
|
-
// ─── T7 — telemetry module ─────────────────────────────────────────────────
|
|
131
|
-
describe("T7 telemetry — hashing + mapping + insert", () => {
|
|
132
|
-
it("hashQuestion returns deterministic sha256[:16]", () => {
|
|
133
|
-
const a = hashQuestion("What is the salience formula?");
|
|
134
|
-
const b = hashQuestion("What is the salience formula?");
|
|
135
|
-
const c = hashQuestion("Different question");
|
|
136
|
-
assert.strictEqual(a, b);
|
|
137
|
-
assert.notStrictEqual(a, c);
|
|
138
|
-
assert.strictEqual(a.length, 16);
|
|
139
|
-
assert.match(a, /^[0-9a-f]{16}$/);
|
|
140
|
-
});
|
|
141
|
-
it("mapFailureReason maps broad lib reasons to v11 alphabet", () => {
|
|
142
|
-
assert.strictEqual(mapFailureReason("hallucinated_citation"), "hallucinated_citation");
|
|
143
|
-
assert.strictEqual(mapFailureReason("hallucination_after_retry"), "hallucinated_citation");
|
|
144
|
-
assert.strictEqual(mapFailureReason("llm_error"), "provider_down");
|
|
145
|
-
assert.strictEqual(mapFailureReason("llm_timeout"), "provider_down");
|
|
146
|
-
assert.strictEqual(mapFailureReason("retrieval_empty"), null);
|
|
147
|
-
assert.strictEqual(mapFailureReason("invalid_input"), null);
|
|
148
|
-
assert.strictEqual(mapFailureReason(undefined), null);
|
|
149
|
-
});
|
|
150
|
-
it("estimateCost honours flash-lite price table; 0 for unknown model", () => {
|
|
151
|
-
const cost = estimateCost("gemini-2.5-flash-lite", 1_000_000, 1_000_000);
|
|
152
|
-
// 0.10 + 0.40 = 0.50 USD for 1M in + 1M out
|
|
153
|
-
assert.strictEqual(cost, 0.5);
|
|
154
|
-
assert.strictEqual(estimateCost("nonexistent-model", 10000, 10000), 0);
|
|
155
|
-
assert.strictEqual(estimateCost("gemini-2.5-flash-lite", 0, 0), 0);
|
|
156
|
-
});
|
|
157
|
-
it("recordAnswer inserts row; NEVER stores raw question text", () => {
|
|
158
|
-
const store = new InMemoryTelemetryStore();
|
|
159
|
-
const row = recordAnswer(store, {
|
|
160
|
-
question: "What is the salience formula?",
|
|
161
|
-
citationCount: 2,
|
|
162
|
-
metadata: {
|
|
163
|
-
latency_ms: 123,
|
|
164
|
-
tokens_in: 100,
|
|
165
|
-
tokens_out: 50,
|
|
166
|
-
provider: "gemini",
|
|
167
|
-
model: "gemini-2.5-flash-lite",
|
|
168
|
-
retrieval_count: 3,
|
|
169
|
-
fallback_used: false,
|
|
170
|
-
},
|
|
171
|
-
sessionId: "s-1",
|
|
172
|
-
now: () => 1715000000000,
|
|
173
|
-
});
|
|
174
|
-
assert.strictEqual(store.rows.length, 1);
|
|
175
|
-
assert.strictEqual(row.question_hash.length, 16);
|
|
176
|
-
// Critical: no raw question text anywhere in serialized row
|
|
177
|
-
const serialized = JSON.stringify(row);
|
|
178
|
-
assert.ok(!serialized.includes("salience"), "raw question must not leak");
|
|
179
|
-
assert.ok(!serialized.includes("formula"), "raw question must not leak");
|
|
180
|
-
assert.strictEqual(row.timestamp_ms, 1715000000000);
|
|
181
|
-
assert.strictEqual(row.fallback_used, 0);
|
|
182
|
-
assert.strictEqual(row.cost_estimate_usd >= 0, true);
|
|
183
|
-
});
|
|
184
|
-
it("recordAnswer swallows store errors (telemetry must NOT break the call)", () => {
|
|
185
|
-
const brokenStore = {
|
|
186
|
-
insert() {
|
|
187
|
-
throw new Error("disk full");
|
|
188
|
-
},
|
|
189
|
-
};
|
|
190
|
-
// Should not throw.
|
|
191
|
-
const row = recordAnswer(brokenStore, {
|
|
192
|
-
question: "q",
|
|
193
|
-
citationCount: 0,
|
|
194
|
-
metadata: {
|
|
195
|
-
latency_ms: 1,
|
|
196
|
-
tokens_in: 0,
|
|
197
|
-
tokens_out: 0,
|
|
198
|
-
provider: "mock",
|
|
199
|
-
model: "mock",
|
|
200
|
-
retrieval_count: 0,
|
|
201
|
-
fallback_used: false,
|
|
202
|
-
},
|
|
203
|
-
});
|
|
204
|
-
assert.ok(row.question_hash.length === 16);
|
|
205
|
-
});
|
|
206
|
-
it("INSERT_SQL contains exactly the v11 columns in canonical order", () => {
|
|
207
|
-
assert.match(INSERT_SQL, /INTO answer_telemetry/);
|
|
208
|
-
assert.match(INSERT_SQL, /@question_hash/);
|
|
209
|
-
assert.match(INSERT_SQL, /@cost_estimate_usd/);
|
|
210
|
-
// Forbid raw-text columns
|
|
211
|
-
assert.ok(!INSERT_SQL.includes("@question_text"));
|
|
212
|
-
assert.ok(!INSERT_SQL.includes("@answer_text"));
|
|
213
|
-
});
|
|
214
|
-
});
|
|
215
|
-
// ─── T8 — CLI ─────────────────────────────────────────────────────────────
|
|
216
|
-
describe("T8 CLI — parseArgs + render + runCli", () => {
|
|
217
|
-
it("parses positional question + numeric flags", () => {
|
|
218
|
-
const p = parseArgs([
|
|
219
|
-
"--top-k", "12", "--max-tokens", "500", "--temperature", "0.3",
|
|
220
|
-
"What", "is", "salience?",
|
|
221
|
-
]);
|
|
222
|
-
assert.strictEqual(p.question, "What is salience?");
|
|
223
|
-
assert.strictEqual(p.topK, 12);
|
|
224
|
-
assert.strictEqual(p.maxTokens, 500);
|
|
225
|
-
assert.strictEqual(p.temperature, 0.3);
|
|
226
|
-
assert.strictEqual(p.showCitations, true);
|
|
227
|
-
});
|
|
228
|
-
it("--json flag flips render; --no-cite suppresses citation block", () => {
|
|
229
|
-
const p = parseArgs(["--json", "--no-cite", "Q"]);
|
|
230
|
-
assert.strictEqual(p.json, true);
|
|
231
|
-
assert.strictEqual(p.showCitations, false);
|
|
232
|
-
assert.strictEqual(p.stripMarkers, false);
|
|
233
|
-
});
|
|
234
|
-
it("--no-citations strips markers from answer body", () => {
|
|
235
|
-
const p = parseArgs(["--no-citations", "Q"]);
|
|
236
|
-
assert.strictEqual(p.stripMarkers, true);
|
|
237
|
-
const res = {
|
|
238
|
-
answer: "Salience [chunk_1] is recency × pain × importance [chunk_2].",
|
|
239
|
-
citations: [],
|
|
240
|
-
metadata: {
|
|
241
|
-
latency_ms: 10, tokens_in: 5, tokens_out: 5,
|
|
242
|
-
provider: "mock", model: "mock", retrieval_count: 2, fallback_used: false,
|
|
243
|
-
},
|
|
244
|
-
};
|
|
245
|
-
const out = renderJson(res, p);
|
|
246
|
-
assert.ok(!out.includes("[chunk_1]"));
|
|
247
|
-
assert.ok(!out.includes("[chunk_2]"));
|
|
248
|
-
});
|
|
249
|
-
it("rejects unknown flag + missing question", () => {
|
|
250
|
-
assert.throws(() => parseArgs(["--bogus", "Q"]), CliArgError);
|
|
251
|
-
assert.throws(() => parseArgs([]), CliArgError);
|
|
252
|
-
assert.throws(() => parseArgs(["--top-k"]), CliArgError);
|
|
253
|
-
assert.throws(() => parseArgs(["--top-k", "abc", "Q"]), CliArgError);
|
|
254
|
-
});
|
|
255
|
-
it("--help prints HELP_TEXT and exits 0", async () => {
|
|
256
|
-
const lines = [];
|
|
257
|
-
const code = await runCli({
|
|
258
|
-
argv: ["--help"],
|
|
259
|
-
stdout: (s) => lines.push(s),
|
|
260
|
-
stderr: () => { },
|
|
261
|
-
});
|
|
262
|
-
assert.strictEqual(code, 0);
|
|
263
|
-
assert.ok(lines[0].includes("nox-mem answer"));
|
|
264
|
-
assert.ok(HELP_TEXT.includes("--top-k"));
|
|
265
|
-
});
|
|
266
|
-
it("runCli happy path emits human render + exit 0 + writes telemetry", async () => {
|
|
267
|
-
const store = new InMemoryTelemetryStore();
|
|
268
|
-
const out = [];
|
|
269
|
-
const code = await runCli({
|
|
270
|
-
argv: ["What is salience?"],
|
|
271
|
-
stdout: (s) => out.push(s),
|
|
272
|
-
stderr: () => { },
|
|
273
|
-
runAnswer: answerWith("Salience is [chunk_1]."),
|
|
274
|
-
telemetryStore: store,
|
|
275
|
-
});
|
|
276
|
-
assert.strictEqual(code, 0);
|
|
277
|
-
assert.ok(out[0].includes("Salience is"));
|
|
278
|
-
assert.ok(out[0].includes("Citations:"));
|
|
279
|
-
assert.ok(out[0].includes("chunk_1"));
|
|
280
|
-
assert.strictEqual(store.rows.length, 1);
|
|
281
|
-
assert.strictEqual(store.rows[0].failed_reason, null);
|
|
282
|
-
assert.strictEqual(store.rows[0].citation_count, 1);
|
|
283
|
-
});
|
|
284
|
-
it("runCli on AnswerError(hallucination_after_retry) exits 4 + telemetry row written", async () => {
|
|
285
|
-
const store = new InMemoryTelemetryStore();
|
|
286
|
-
const err = [];
|
|
287
|
-
const code = await runCli({
|
|
288
|
-
argv: ["bad question"],
|
|
289
|
-
stdout: () => { },
|
|
290
|
-
stderr: (s) => err.push(s),
|
|
291
|
-
runAnswer: () => {
|
|
292
|
-
return realAnswer({
|
|
293
|
-
question: "bad question",
|
|
294
|
-
providerOverride: new MockProvider(["[chunk_99]", "[chunk_42]"], 0),
|
|
295
|
-
});
|
|
296
|
-
},
|
|
297
|
-
telemetryStore: store,
|
|
298
|
-
});
|
|
299
|
-
assert.strictEqual(code, 4);
|
|
300
|
-
assert.ok(err.join("\n").includes("hallucination_after_retry"));
|
|
301
|
-
assert.strictEqual(store.rows.length, 1);
|
|
302
|
-
assert.strictEqual(store.rows[0].failed_reason, "hallucinated_citation");
|
|
303
|
-
});
|
|
304
|
-
it("runCli on bad argv exits 2 with stderr help", async () => {
|
|
305
|
-
const err = [];
|
|
306
|
-
const code = await runCli({
|
|
307
|
-
argv: ["--unknown-flag", "Q"],
|
|
308
|
-
stdout: () => { },
|
|
309
|
-
stderr: (s) => err.push(s),
|
|
310
|
-
});
|
|
311
|
-
assert.strictEqual(code, 2);
|
|
312
|
-
assert.ok(err.join("").includes("unknown flag"));
|
|
313
|
-
});
|
|
314
|
-
it("renderHuman includes metadata footer with model + latency + retrieved", () => {
|
|
315
|
-
const res = {
|
|
316
|
-
answer: "Body [chunk_1]",
|
|
317
|
-
citations: [
|
|
318
|
-
{ chunk_id: 1, marker_id: "chunk_1", file_path: "a.md", snippet: "x" },
|
|
319
|
-
],
|
|
320
|
-
metadata: {
|
|
321
|
-
latency_ms: 42, tokens_in: 5, tokens_out: 5,
|
|
322
|
-
provider: "mock", model: "gemini-2.5-flash-lite",
|
|
323
|
-
retrieval_count: 1, fallback_used: false,
|
|
324
|
-
},
|
|
325
|
-
};
|
|
326
|
-
const p = parseArgs(["Q"]);
|
|
327
|
-
const out = renderHuman(res, p);
|
|
328
|
-
assert.ok(out.includes("model=gemini-2.5-flash-lite"));
|
|
329
|
-
assert.ok(out.includes("latency=42ms"));
|
|
330
|
-
assert.ok(out.includes("retrieved=1"));
|
|
331
|
-
assert.ok(out.includes("cited=1"));
|
|
332
|
-
});
|
|
333
|
-
});
|
|
334
|
-
// ─── T9 — HTTP ─────────────────────────────────────────────────────────────
|
|
335
|
-
describe("T9 HTTP — validateBody + handleAnswerRequest", () => {
|
|
336
|
-
it("validateBody accepts a minimal valid body", () => {
|
|
337
|
-
const r = validateBody({ question: "hello" });
|
|
338
|
-
assert.strictEqual(r.question, "hello");
|
|
339
|
-
});
|
|
340
|
-
it("validateBody rejects missing/empty/oversize question", () => {
|
|
341
|
-
assert.throws(() => validateBody({}));
|
|
342
|
-
assert.throws(() => validateBody({ question: " " }));
|
|
343
|
-
assert.throws(() => validateBody({ question: "x".repeat(2001) }));
|
|
344
|
-
assert.throws(() => validateBody({ question: 123 }));
|
|
345
|
-
assert.throws(() => validateBody(null));
|
|
346
|
-
assert.throws(() => validateBody([]));
|
|
347
|
-
});
|
|
348
|
-
it("validateBody rejects wrong types on optional fields", () => {
|
|
349
|
-
assert.throws(() => validateBody({ question: "q", top_k: "8" }));
|
|
350
|
-
assert.throws(() => validateBody({ question: "q", temperature: "0.3" }));
|
|
351
|
-
assert.throws(() => validateBody({ question: "q", no_citations: 1 }));
|
|
352
|
-
});
|
|
353
|
-
it("statusFromReason maps reasons to kickoff §6 codes", () => {
|
|
354
|
-
assert.strictEqual(statusFromReason("retrieval_empty"), 503);
|
|
355
|
-
assert.strictEqual(statusFromReason("hallucination_after_retry"), 422);
|
|
356
|
-
assert.strictEqual(statusFromReason("llm_timeout"), 504);
|
|
357
|
-
assert.strictEqual(statusFromReason("llm_error"), 502);
|
|
358
|
-
assert.strictEqual(statusFromReason("invalid_input"), 400);
|
|
359
|
-
assert.strictEqual(statusFromReason("unauthorized"), 401);
|
|
360
|
-
});
|
|
361
|
-
it("handleAnswerRequest 200 happy path includes citations + headers", async () => {
|
|
362
|
-
const store = new InMemoryTelemetryStore();
|
|
363
|
-
const out = await handleAnswerRequest({
|
|
364
|
-
body: { question: "salience?" },
|
|
365
|
-
headers: { "x-trace-id": "trace-abc" },
|
|
366
|
-
answer: answerWith("Salience [chunk_1]"),
|
|
367
|
-
telemetryStore: store,
|
|
368
|
-
});
|
|
369
|
-
assert.strictEqual(out.status, 200);
|
|
370
|
-
assert.strictEqual(out.headers["X-Trace-Id"], "trace-abc");
|
|
371
|
-
assert.strictEqual(out.headers["X-Model-Used"], "gemini-2.5-flash-lite");
|
|
372
|
-
const body = out.body;
|
|
373
|
-
assert.strictEqual(body.citations.length, 1);
|
|
374
|
-
assert.strictEqual(body.trace_id, "trace-abc");
|
|
375
|
-
assert.strictEqual(store.rows.length, 1);
|
|
376
|
-
});
|
|
377
|
-
it("handleAnswerRequest 400 on invalid body shape", async () => {
|
|
378
|
-
const out = await handleAnswerRequest({
|
|
379
|
-
body: { not_question: "x" },
|
|
380
|
-
answer: () => Promise.reject(new Error("should not call")),
|
|
381
|
-
});
|
|
382
|
-
assert.strictEqual(out.status, 400);
|
|
383
|
-
assert.strictEqual(out.body.reason, "invalid_body");
|
|
384
|
-
});
|
|
385
|
-
it("handleAnswerRequest 422 on hallucination_after_retry + telemetry written", async () => {
|
|
386
|
-
const store = new InMemoryTelemetryStore();
|
|
387
|
-
const out = await handleAnswerRequest({
|
|
388
|
-
body: { question: "adv" },
|
|
389
|
-
answer: () => realAnswer({
|
|
390
|
-
question: "adv",
|
|
391
|
-
providerOverride: new MockProvider(["[chunk_99]", "[chunk_42]"], 0),
|
|
392
|
-
}),
|
|
393
|
-
telemetryStore: store,
|
|
394
|
-
});
|
|
395
|
-
assert.strictEqual(out.status, 422);
|
|
396
|
-
const body = out.body;
|
|
397
|
-
assert.strictEqual(body.reason, "hallucination_after_retry");
|
|
398
|
-
assert.strictEqual(store.rows.length, 1);
|
|
399
|
-
assert.strictEqual(store.rows[0].failed_reason, "hallucinated_citation");
|
|
400
|
-
});
|
|
401
|
-
it("handleAnswerRequest 401 when authCheck fails", async () => {
|
|
402
|
-
const out = await handleAnswerRequest({
|
|
403
|
-
body: { question: "q" },
|
|
404
|
-
authCheck: () => false,
|
|
405
|
-
answer: () => Promise.reject(new Error("should not call")),
|
|
406
|
-
});
|
|
407
|
-
assert.strictEqual(out.status, 401);
|
|
408
|
-
assert.strictEqual(out.body.reason, "unauthorized");
|
|
409
|
-
});
|
|
410
|
-
it("handleAnswerRequest 503 on retrieval_empty (lib short-circuit)", async () => {
|
|
411
|
-
bindEmpty();
|
|
412
|
-
const out = await handleAnswerRequest({
|
|
413
|
-
body: { question: "nothing matches" },
|
|
414
|
-
answer: realAnswer,
|
|
415
|
-
});
|
|
416
|
-
assert.strictEqual(out.status, 503);
|
|
417
|
-
const body = out.body;
|
|
418
|
-
assert.strictEqual(body.metadata.failed_reason, "retrieval_empty");
|
|
419
|
-
assert.ok(body.answer.includes("no memory matches"));
|
|
420
|
-
});
|
|
421
|
-
it("REQUEST_SCHEMA matches kickoff §5 surface", () => {
|
|
422
|
-
assert.deepStrictEqual(REQUEST_SCHEMA.required, ["question"]);
|
|
423
|
-
const props = REQUEST_SCHEMA.properties;
|
|
424
|
-
assert.strictEqual(props.question?.type, "string");
|
|
425
|
-
assert.strictEqual(props.top_k?.type, "integer");
|
|
426
|
-
assert.strictEqual(props.temperature?.type, "number");
|
|
427
|
-
assert.strictEqual(REQUEST_SCHEMA.additionalProperties, false);
|
|
428
|
-
});
|
|
429
|
-
it("no_citations strips inline [chunk_N] markers but keeps citations array", async () => {
|
|
430
|
-
const out = await handleAnswerRequest({
|
|
431
|
-
body: { question: "q", no_citations: true },
|
|
432
|
-
answer: answerWith("Salience is [chunk_1] for recency."),
|
|
433
|
-
});
|
|
434
|
-
assert.strictEqual(out.status, 200);
|
|
435
|
-
const body = out.body;
|
|
436
|
-
assert.ok(!body.answer.includes("[chunk_1]"));
|
|
437
|
-
assert.strictEqual(body.citations.length, 1);
|
|
438
|
-
});
|
|
439
|
-
});
|
|
440
|
-
// ─── T10 — MCP ─────────────────────────────────────────────────────────────
|
|
441
|
-
describe("T10 MCP — nox_mem_answer tool", () => {
|
|
442
|
-
it("tool metadata matches contract", () => {
|
|
443
|
-
assert.strictEqual(noxMemAnswerTool.name, "nox_mem_answer");
|
|
444
|
-
assert.ok(noxMemAnswerTool.description.includes("nox-mem corpus"));
|
|
445
|
-
assert.ok(noxMemAnswerTool.description.includes("[chunk_N]"));
|
|
446
|
-
const schema = INPUT_SCHEMA;
|
|
447
|
-
assert.deepStrictEqual(schema.required, ["question"]);
|
|
448
|
-
assert.strictEqual(schema.properties.question?.maxLength, 2000);
|
|
449
|
-
assert.strictEqual(schema.additionalProperties, false);
|
|
450
|
-
});
|
|
451
|
-
it("parseInput rejects malformed input", () => {
|
|
452
|
-
assert.throws(() => parseInput(null));
|
|
453
|
-
assert.throws(() => parseInput({}));
|
|
454
|
-
assert.throws(() => parseInput({ question: "" }));
|
|
455
|
-
assert.throws(() => parseInput({ question: "x".repeat(2001) }));
|
|
456
|
-
assert.throws(() => parseInput({ question: "q", top_k: "8" }));
|
|
457
|
-
});
|
|
458
|
-
it("handler happy path returns content[0].text as JSON with citations", async () => {
|
|
459
|
-
const store = new InMemoryTelemetryStore();
|
|
460
|
-
const res = await noxMemAnswerTool.handler({ question: "salience?" }, {
|
|
461
|
-
sessionId: "s-mcp",
|
|
462
|
-
telemetryStore: store,
|
|
463
|
-
answer: answerWith("Salience is [chunk_1]."),
|
|
464
|
-
});
|
|
465
|
-
assert.strictEqual(res.isError, undefined);
|
|
466
|
-
assert.strictEqual(res.content.length, 1);
|
|
467
|
-
assert.strictEqual(res.content[0].type, "text");
|
|
468
|
-
const payload = JSON.parse(res.content[0].text);
|
|
469
|
-
assert.ok(payload.answer.includes("Salience"));
|
|
470
|
-
assert.strictEqual(payload.citations.length, 1);
|
|
471
|
-
assert.strictEqual(payload.citations[0].chunk_id, 1001);
|
|
472
|
-
assert.strictEqual(store.rows.length, 1);
|
|
473
|
-
assert.strictEqual(store.rows[0].session_id, "s-mcp");
|
|
474
|
-
});
|
|
475
|
-
it("handler hallucination_after_retry returns isError:true + telemetry row", async () => {
|
|
476
|
-
const store = new InMemoryTelemetryStore();
|
|
477
|
-
const res = await noxMemAnswerTool.handler({ question: "adv" }, {
|
|
478
|
-
telemetryStore: store,
|
|
479
|
-
answer: () => realAnswer({
|
|
480
|
-
question: "adv",
|
|
481
|
-
providerOverride: new MockProvider(["[chunk_99]", "[chunk_42]"], 0),
|
|
482
|
-
}),
|
|
483
|
-
});
|
|
484
|
-
assert.strictEqual(res.isError, true);
|
|
485
|
-
const payload = JSON.parse(res.content[0].text);
|
|
486
|
-
assert.strictEqual(payload.reason, "hallucination_after_retry");
|
|
487
|
-
assert.strictEqual(store.rows.length, 1);
|
|
488
|
-
assert.strictEqual(store.rows[0].failed_reason, "hallucinated_citation");
|
|
489
|
-
});
|
|
490
|
-
it("handler invalid input returns isError:true with reason=invalid_input", async () => {
|
|
491
|
-
const res = await noxMemAnswerTool.handler({ no_question: true });
|
|
492
|
-
assert.strictEqual(res.isError, true);
|
|
493
|
-
const payload = JSON.parse(res.content[0].text);
|
|
494
|
-
assert.strictEqual(payload.reason, "invalid_input");
|
|
495
|
-
});
|
|
496
|
-
it("handler no_citations strips markers from emitted answer", async () => {
|
|
497
|
-
const res = await noxMemAnswerTool.handler({ question: "q", no_citations: true }, { answer: answerWith("Salience is [chunk_1] for recency.") });
|
|
498
|
-
const payload = JSON.parse(res.content[0].text);
|
|
499
|
-
assert.ok(!payload.answer.includes("[chunk_1]"));
|
|
500
|
-
});
|
|
501
|
-
});
|
|
@@ -1,155 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* G12 — safeErrorMessage tests.
|
|
3
|
-
*/
|
|
4
|
-
import { describe, it } from "node:test";
|
|
5
|
-
import assert from "node:assert/strict";
|
|
6
|
-
import { safeErrorMessage, buildSafeErrorBody, checkErrorPassthroughAtBoot, } from "../safe-error-message.js";
|
|
7
|
-
import { safeError500, safeConflict409, safeMark500 } from "../error-leak-fix.js";
|
|
8
|
-
// ── stripping ───────────────────────────────────────────────────────────────
|
|
9
|
-
describe("safeErrorMessage — path stripping", () => {
|
|
10
|
-
it("strips /Users/... with line:col suffix", () => {
|
|
11
|
-
const { message } = safeErrorMessage(new Error("SQLITE_ERROR at /Users/lab/Claude/Projetos/memoria-nox/db.ts:42:15"));
|
|
12
|
-
assert.equal(message.includes("/Users"), false);
|
|
13
|
-
assert.equal(message.includes("<path>"), true);
|
|
14
|
-
});
|
|
15
|
-
it("strips /root/... (linux prod)", () => {
|
|
16
|
-
const { message } = safeErrorMessage(new Error("ENOENT: no such file '/root/.openclaw/workspace/tools/nox-mem/foo.db'"));
|
|
17
|
-
assert.equal(message.includes("/root"), false);
|
|
18
|
-
});
|
|
19
|
-
it("strips /var, /opt, /tmp, /home", () => {
|
|
20
|
-
for (const p of ["/var/lib/foo", "/opt/nox/bar", "/tmp/x.db", "/home/u/y.db"]) {
|
|
21
|
-
const { message } = safeErrorMessage(new Error(`failed at ${p}`));
|
|
22
|
-
assert.equal(message.includes(p), false, `should strip ${p}`);
|
|
23
|
-
}
|
|
24
|
-
});
|
|
25
|
-
});
|
|
26
|
-
describe("safeErrorMessage — DB / secret stripping", () => {
|
|
27
|
-
it("strips sqlite:// connection strings", () => {
|
|
28
|
-
const { message } = safeErrorMessage(new Error("Connection failed: sqlite:///var/lib/foo.db"));
|
|
29
|
-
assert.equal(message.includes("<dburl>") || message.includes("<path>"), true);
|
|
30
|
-
assert.equal(message.includes("sqlite:///var"), false);
|
|
31
|
-
});
|
|
32
|
-
it("strips ENV=value patterns", () => {
|
|
33
|
-
// gitleaks-safe fixture: obviously-synthetic test token built from
|
|
34
|
-
// joined non-secret tokens. Verifies the regex matches ENV=value.
|
|
35
|
-
const fixtureToken = ["EXAMPLE", "PLACEHOLDER", "DUMMY"].join("_");
|
|
36
|
-
const { message } = safeErrorMessage(new Error(`config error NOX_API_TOKEN=${fixtureToken} not accepted`));
|
|
37
|
-
assert.equal(message.includes(fixtureToken), false);
|
|
38
|
-
assert.equal(message.includes("NOX_API_TOKEN=<redacted>"), true);
|
|
39
|
-
});
|
|
40
|
-
it("strips Bearer tokens", () => {
|
|
41
|
-
const { message } = safeErrorMessage(new Error("Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.abc.def failed"));
|
|
42
|
-
assert.equal(message.includes("eyJhbGci"), false);
|
|
43
|
-
assert.match(message, /Bearer <redacted>/);
|
|
44
|
-
});
|
|
45
|
-
it("strips long opaque tokens (32+ chars)", () => {
|
|
46
|
-
const { message } = safeErrorMessage(new Error("token aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa invalid"));
|
|
47
|
-
assert.match(message, /<token>/);
|
|
48
|
-
});
|
|
49
|
-
});
|
|
50
|
-
describe("safeErrorMessage — fallback + cap", () => {
|
|
51
|
-
it("returns fallback when stripping leaves empty", () => {
|
|
52
|
-
const { message } = safeErrorMessage(new Error("/Users/lab/foo/bar.ts:1:1"));
|
|
53
|
-
// After stripping, only <path> remains → fallback kicks in.
|
|
54
|
-
assert.equal(message, "internal_error");
|
|
55
|
-
});
|
|
56
|
-
it("respects custom fallback", () => {
|
|
57
|
-
const { message } = safeErrorMessage(new Error("/root/x"), { fallback: "boom" });
|
|
58
|
-
assert.equal(message, "boom");
|
|
59
|
-
});
|
|
60
|
-
it("caps to maxLength with ellipsis", () => {
|
|
61
|
-
// Use a stripping-resistant payload: natural-language words separated by
|
|
62
|
-
// spaces, none long enough to match <token>. Verifies the maxLength cap
|
|
63
|
-
// rather than stripping behavior.
|
|
64
|
-
const longMsg = "alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma tau upsilon phi chi psi omega ".repeat(5);
|
|
65
|
-
const { message } = safeErrorMessage(new Error(longMsg), { maxLength: 50 });
|
|
66
|
-
assert.equal(message.length, 50);
|
|
67
|
-
assert.equal(message.endsWith("..."), true);
|
|
68
|
-
});
|
|
69
|
-
});
|
|
70
|
-
describe("safeErrorMessage — input shape", () => {
|
|
71
|
-
it("accepts plain string", () => {
|
|
72
|
-
const { message } = safeErrorMessage("plain string error");
|
|
73
|
-
assert.equal(message, "plain string error");
|
|
74
|
-
});
|
|
75
|
-
it("accepts {message: string} duck type", () => {
|
|
76
|
-
const { message } = safeErrorMessage({ message: "duck error" });
|
|
77
|
-
assert.equal(message, "duck error");
|
|
78
|
-
});
|
|
79
|
-
it("falls back to String(e) for arbitrary objects", () => {
|
|
80
|
-
const { message } = safeErrorMessage({ foo: "bar" });
|
|
81
|
-
assert.equal(typeof message, "string");
|
|
82
|
-
assert.equal(message.length > 0, true);
|
|
83
|
-
});
|
|
84
|
-
it("each call yields a unique correlationId (UUIDv4 shape)", () => {
|
|
85
|
-
const r1 = safeErrorMessage("e1");
|
|
86
|
-
const r2 = safeErrorMessage("e2");
|
|
87
|
-
assert.notEqual(r1.correlationId, r2.correlationId);
|
|
88
|
-
assert.match(r1.correlationId, /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
|
|
89
|
-
});
|
|
90
|
-
});
|
|
91
|
-
describe("passthrough mode", () => {
|
|
92
|
-
it("returns raw message when passthrough=true", () => {
|
|
93
|
-
const { message } = safeErrorMessage(new Error("/Users/lab/sensitive"), { passthrough: true });
|
|
94
|
-
assert.equal(message, "/Users/lab/sensitive");
|
|
95
|
-
});
|
|
96
|
-
it("checkErrorPassthroughAtBoot returns true + warns when env=1", () => {
|
|
97
|
-
let warned = false;
|
|
98
|
-
const r = checkErrorPassthroughAtBoot({ warn: () => { warned = true; } }, { NOX_ERROR_PASSTHROUGH: "1" });
|
|
99
|
-
assert.equal(r, true);
|
|
100
|
-
assert.equal(warned, true);
|
|
101
|
-
});
|
|
102
|
-
it("checkErrorPassthroughAtBoot returns false when env unset", () => {
|
|
103
|
-
let warned = false;
|
|
104
|
-
const r = checkErrorPassthroughAtBoot({ warn: () => { warned = true; } }, {});
|
|
105
|
-
assert.equal(r, false);
|
|
106
|
-
assert.equal(warned, false);
|
|
107
|
-
});
|
|
108
|
-
});
|
|
109
|
-
// ── buildSafeErrorBody / adoption helpers ──────────────────────────────────
|
|
110
|
-
describe("buildSafeErrorBody", () => {
|
|
111
|
-
it("invokes onLog with raw + correlationId, returns sanitized body", () => {
|
|
112
|
-
const logs = [];
|
|
113
|
-
const body = buildSafeErrorBody(new Error("/Users/lab/whatever:1:1"), {
|
|
114
|
-
onLog: (info) => logs.push(info),
|
|
115
|
-
});
|
|
116
|
-
assert.equal(typeof body.correlation_id, "string");
|
|
117
|
-
assert.equal(body.error, "internal_error");
|
|
118
|
-
assert.equal(logs.length, 1);
|
|
119
|
-
assert.equal(logs[0].correlationId, body.correlation_id);
|
|
120
|
-
});
|
|
121
|
-
});
|
|
122
|
-
// ── adoption: safeError500 / safeConflict409 / safeMark500 ──────────────────
|
|
123
|
-
describe("safeError500 (drop-in for hooks.ts)", () => {
|
|
124
|
-
it("returns { error, correlation_id } and logs raw", () => {
|
|
125
|
-
const logs = [];
|
|
126
|
-
const body = safeError500(new Error("/Users/secret"), {
|
|
127
|
-
onLog: (info) => logs.push(info),
|
|
128
|
-
context: "hooks.recent",
|
|
129
|
-
});
|
|
130
|
-
assert.equal(body.error, "internal_error");
|
|
131
|
-
assert.equal(typeof body.correlation_id, "string");
|
|
132
|
-
assert.equal(logs[0].context, "hooks.recent");
|
|
133
|
-
});
|
|
134
|
-
it("preserves clean error message when nothing to strip", () => {
|
|
135
|
-
const body = safeError500(new Error("invalid_argument"), {
|
|
136
|
-
onLog: () => { },
|
|
137
|
-
});
|
|
138
|
-
assert.equal(body.error, "invalid_argument");
|
|
139
|
-
});
|
|
140
|
-
});
|
|
141
|
-
describe("safeConflict409", () => {
|
|
142
|
-
it("emits { error: resolution_failed, message, correlation_id }", () => {
|
|
143
|
-
const body = safeConflict409(new Error("/root/x.db"), { onLog: () => { } });
|
|
144
|
-
assert.equal(body.error, "resolution_failed");
|
|
145
|
-
assert.equal(body.message, "internal_error");
|
|
146
|
-
assert.equal(typeof body.correlation_id, "string");
|
|
147
|
-
});
|
|
148
|
-
});
|
|
149
|
-
describe("safeMark500", () => {
|
|
150
|
-
it("strips SQL fragment leak (R-L3-3)", () => {
|
|
151
|
-
const body = safeMark500(new Error("SQLITE_ERROR: near \"WHERE id = 42 AND col = 'sensitive'\": at /var/lib/x.db:1"), { onLog: () => { } });
|
|
152
|
-
assert.equal(body.error.includes("/var"), false);
|
|
153
|
-
assert.equal(typeof body.correlation_id, "string");
|
|
154
|
-
});
|
|
155
|
-
});
|