nox-mem 3.4.0 → 3.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +62 -33
- package/dist/api/answer.js +22 -0
- package/dist/api-server.js +3 -2
- 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/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,229 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* src/lib/answer/__tests__/e2e-gemini.test.ts — P1 T12.
|
|
3
|
-
*
|
|
4
|
-
* **GATED** end-to-end tests against the real Gemini API. SKIPPED unless
|
|
5
|
-
* `NOX_E2E_GEMINI=1` is set in the environment AND `GEMINI_API_KEY` is
|
|
6
|
-
* present.
|
|
7
|
-
*
|
|
8
|
-
* Cost cap: hardcoded `MAX_TOKENS_TEST = 200` on every call. Total run
|
|
9
|
-
* (4 tests × ~250 tokens in + 200 tokens out, flash-lite pricing
|
|
10
|
-
* $0.10/M in + $0.40/M out) ≈ $0.0004 — well under the $0.01 budget.
|
|
11
|
-
*
|
|
12
|
-
* Coverage when active (4 tests):
|
|
13
|
-
* E2E-01 real Gemini call returns non-empty answer + at least one citation
|
|
14
|
-
* E2E-02 citations resolve to real chunk_ids from the synthetic fixture
|
|
15
|
-
* E2E-03 telemetry row written; model = 'gemini-2.5-flash-lite'
|
|
16
|
-
* E2E-04 adversarial out-of-corpus question yields "no memory matches" via retrieval_empty
|
|
17
|
-
*
|
|
18
|
-
* When gated off, ONE skip-marker test runs that logs the gate reason —
|
|
19
|
-
* keeps the report honest ("test skipped because NOX_E2E_GEMINI != 1").
|
|
20
|
-
*
|
|
21
|
-
* The Gemini provider is wired inline here using the public REST endpoint
|
|
22
|
-
* (no SDK dependency required — keeps staged-P1 installable without
|
|
23
|
-
* `@google/genai` in the dev dep set). Replace with the SDK in the VPS
|
|
24
|
-
* apply step if/when A3 provider abstraction merges.
|
|
25
|
-
*/
|
|
26
|
-
import { describe, it, before, after } from "node:test";
|
|
27
|
-
import assert from "node:assert/strict";
|
|
28
|
-
import Database from "better-sqlite3";
|
|
29
|
-
import { answer as realAnswer, __setRawSearchForTests, } from "../index.js";
|
|
30
|
-
import { recordAnswer, INSERT_SQL, } from "../telemetry.js";
|
|
31
|
-
// ─── Gating ────────────────────────────────────────────────────────────────
|
|
32
|
-
const GATE_ON = process.env.NOX_E2E_GEMINI === "1";
|
|
33
|
-
const API_KEY = process.env.GEMINI_API_KEY ?? "";
|
|
34
|
-
const ACTIVE = GATE_ON && API_KEY.length > 0;
|
|
35
|
-
const MAX_TOKENS_TEST = 200;
|
|
36
|
-
const MODEL = "gemini-2.5-flash-lite";
|
|
37
|
-
// ─── Skip-marker stub ──────────────────────────────────────────────────────
|
|
38
|
-
describe("T12 E2E Gemini — gating", () => {
|
|
39
|
-
it("gate is honoured (active iff NOX_E2E_GEMINI=1 AND GEMINI_API_KEY set)", () => {
|
|
40
|
-
if (!ACTIVE) {
|
|
41
|
-
const reason = !GATE_ON
|
|
42
|
-
? "NOX_E2E_GEMINI != 1"
|
|
43
|
-
: "GEMINI_API_KEY empty";
|
|
44
|
-
// node:test prints this in default reporter; humans see why we skipped.
|
|
45
|
-
process.stdout.write(`[T12] SKIPPED real-Gemini suite — reason: ${reason}\n`);
|
|
46
|
-
assert.ok(true, "skip path");
|
|
47
|
-
return;
|
|
48
|
-
}
|
|
49
|
-
process.stdout.write("[T12] real-Gemini suite ACTIVE — running 4 tests against API\n");
|
|
50
|
-
assert.ok(API_KEY.length > 0);
|
|
51
|
-
});
|
|
52
|
-
});
|
|
53
|
-
class GeminiRestProvider {
|
|
54
|
-
apiKey;
|
|
55
|
-
maxTokensCap;
|
|
56
|
-
name = "gemini";
|
|
57
|
-
constructor(apiKey, maxTokensCap = MAX_TOKENS_TEST) {
|
|
58
|
-
this.apiKey = apiKey;
|
|
59
|
-
this.maxTokensCap = maxTokensCap;
|
|
60
|
-
}
|
|
61
|
-
async complete(opts) {
|
|
62
|
-
const t0 = Date.now();
|
|
63
|
-
const url = `https://generativelanguage.googleapis.com/v1beta/models/` +
|
|
64
|
-
`${opts.model}:generateContent?key=${this.apiKey}`;
|
|
65
|
-
const body = {
|
|
66
|
-
systemInstruction: { parts: [{ text: opts.system }] },
|
|
67
|
-
contents: [{ role: "user", parts: [{ text: opts.user }] }],
|
|
68
|
-
generationConfig: {
|
|
69
|
-
temperature: opts.temperature,
|
|
70
|
-
maxOutputTokens: Math.min(opts.maxTokens, this.maxTokensCap),
|
|
71
|
-
},
|
|
72
|
-
};
|
|
73
|
-
const resp = await fetch(url, {
|
|
74
|
-
method: "POST",
|
|
75
|
-
headers: { "Content-Type": "application/json" },
|
|
76
|
-
body: JSON.stringify(body),
|
|
77
|
-
});
|
|
78
|
-
if (!resp.ok) {
|
|
79
|
-
throw new Error(`Gemini HTTP ${resp.status}: ${await resp.text()}`);
|
|
80
|
-
}
|
|
81
|
-
const data = (await resp.json());
|
|
82
|
-
const text = data.candidates?.[0]?.content?.parts?.[0]?.text?.trim() ?? "";
|
|
83
|
-
return {
|
|
84
|
-
text,
|
|
85
|
-
tokensIn: data.usageMetadata?.promptTokenCount ?? 0,
|
|
86
|
-
tokensOut: data.usageMetadata?.candidatesTokenCount ?? 0,
|
|
87
|
-
latencyMs: Date.now() - t0,
|
|
88
|
-
};
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
// ─── Synthetic corpus (no real DB needed for E2E quality smoke) ────────────
|
|
92
|
-
const E2E_CHUNKS = [
|
|
93
|
-
{
|
|
94
|
-
chunk_id: 9001,
|
|
95
|
-
file_path: "memory/entities/decision/d41.md",
|
|
96
|
-
line_range: "L1-L5",
|
|
97
|
-
content: "Decision D41 #1 — Default model for the nox-mem answer primitive " +
|
|
98
|
-
"is gemini-2.5-flash-lite. Rationale: cost optimized vs quality. " +
|
|
99
|
-
"Override with NOX_ANSWER_MODEL or --model flag.",
|
|
100
|
-
content_hash: "h-d41",
|
|
101
|
-
score: 0.95,
|
|
102
|
-
},
|
|
103
|
-
{
|
|
104
|
-
chunk_id: 9002,
|
|
105
|
-
file_path: "memory/entities/feedback/salience.md",
|
|
106
|
-
line_range: "L1-L3",
|
|
107
|
-
content: "Salience formula in nox-mem is salience = recency × pain × " +
|
|
108
|
-
"importance. Exposed via /api/health.salience.",
|
|
109
|
-
content_hash: "h-sal",
|
|
110
|
-
score: 0.9,
|
|
111
|
-
},
|
|
112
|
-
{
|
|
113
|
-
chunk_id: 9003,
|
|
114
|
-
file_path: "memory/entities/lesson/never-sed.md",
|
|
115
|
-
line_range: "L1-L2",
|
|
116
|
-
content: "Never use sed -i on SQLite .db files — it corrupts page boundaries. " +
|
|
117
|
-
"Filter file lists by extension before sweeps.",
|
|
118
|
-
content_hash: "h-sed",
|
|
119
|
-
score: 0.8,
|
|
120
|
-
},
|
|
121
|
-
];
|
|
122
|
-
// ─── Telemetry adapter (real SQLite in-memory) ─────────────────────────────
|
|
123
|
-
class Sqlite3TelemetryStore {
|
|
124
|
-
db;
|
|
125
|
-
stmt;
|
|
126
|
-
constructor(db) {
|
|
127
|
-
this.db = db;
|
|
128
|
-
this.stmt = db.prepare(INSERT_SQL);
|
|
129
|
-
}
|
|
130
|
-
insert(row) {
|
|
131
|
-
this.stmt.run(row);
|
|
132
|
-
}
|
|
133
|
-
latest() {
|
|
134
|
-
return this.db
|
|
135
|
-
.prepare("SELECT * FROM answer_telemetry ORDER BY id DESC LIMIT 1")
|
|
136
|
-
.get();
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
const SCHEMA_V11 = `
|
|
140
|
-
CREATE TABLE IF NOT EXISTS answer_telemetry (
|
|
141
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
142
|
-
question_hash TEXT NOT NULL, session_id TEXT,
|
|
143
|
-
timestamp_ms INTEGER NOT NULL, provider TEXT NOT NULL, model TEXT NOT NULL,
|
|
144
|
-
retrieval_count INTEGER NOT NULL, citation_count INTEGER NOT NULL,
|
|
145
|
-
tokens_in INTEGER, tokens_out INTEGER, latency_ms INTEGER NOT NULL,
|
|
146
|
-
fallback_used INTEGER NOT NULL DEFAULT 0, failed_reason TEXT,
|
|
147
|
-
cost_estimate_usd REAL NOT NULL DEFAULT 0,
|
|
148
|
-
CHECK (failed_reason IS NULL OR failed_reason IN
|
|
149
|
-
('hallucinated_citation', 'provider_down', 'token_budget'))
|
|
150
|
-
);
|
|
151
|
-
`;
|
|
152
|
-
// ─── Active suite (only if gated on) ───────────────────────────────────────
|
|
153
|
-
if (ACTIVE) {
|
|
154
|
-
describe("T12 E2E Gemini — real API calls (flash-lite, capped)", () => {
|
|
155
|
-
let db;
|
|
156
|
-
let store;
|
|
157
|
-
let provider;
|
|
158
|
-
before(() => {
|
|
159
|
-
db = new Database(":memory:");
|
|
160
|
-
db.exec(SCHEMA_V11);
|
|
161
|
-
store = new Sqlite3TelemetryStore(db);
|
|
162
|
-
provider = new GeminiRestProvider(API_KEY, MAX_TOKENS_TEST);
|
|
163
|
-
__setRawSearchForTests(async () => E2E_CHUNKS);
|
|
164
|
-
});
|
|
165
|
-
after(() => {
|
|
166
|
-
db.close();
|
|
167
|
-
});
|
|
168
|
-
it("E2E-01 returns non-empty answer with ≥1 citation", async () => {
|
|
169
|
-
const res = await realAnswer({
|
|
170
|
-
question: "What is the default model for the answer primitive?",
|
|
171
|
-
providerOverride: provider,
|
|
172
|
-
maxTokens: MAX_TOKENS_TEST,
|
|
173
|
-
temperature: 0,
|
|
174
|
-
});
|
|
175
|
-
assert.ok(res.answer.length > 0, "answer text non-empty");
|
|
176
|
-
assert.ok(res.citations.length >= 1, "≥1 citation parsed");
|
|
177
|
-
});
|
|
178
|
-
it("E2E-02 citation resolves to a real chunk_id from fixture", async () => {
|
|
179
|
-
const res = await realAnswer({
|
|
180
|
-
question: "What is the salience formula in nox-mem?",
|
|
181
|
-
providerOverride: provider,
|
|
182
|
-
maxTokens: MAX_TOKENS_TEST,
|
|
183
|
-
temperature: 0,
|
|
184
|
-
});
|
|
185
|
-
assert.ok(res.citations.length >= 1);
|
|
186
|
-
const validIds = new Set(E2E_CHUNKS.map((c) => c.chunk_id));
|
|
187
|
-
for (const c of res.citations) {
|
|
188
|
-
assert.ok(validIds.has(c.chunk_id), `citation chunk_id=${c.chunk_id} not in fixture`);
|
|
189
|
-
}
|
|
190
|
-
});
|
|
191
|
-
it("E2E-03 telemetry row persists with model=gemini-2.5-flash-lite", async () => {
|
|
192
|
-
const question = "Never use what on .db files?";
|
|
193
|
-
const res = await realAnswer({
|
|
194
|
-
question,
|
|
195
|
-
providerOverride: provider,
|
|
196
|
-
maxTokens: MAX_TOKENS_TEST,
|
|
197
|
-
temperature: 0,
|
|
198
|
-
});
|
|
199
|
-
recordAnswer(store, {
|
|
200
|
-
question,
|
|
201
|
-
citationCount: res.citations.length,
|
|
202
|
-
metadata: res.metadata,
|
|
203
|
-
sessionId: "e2e-03",
|
|
204
|
-
});
|
|
205
|
-
const row = store.latest();
|
|
206
|
-
assert.strictEqual(row.model, MODEL);
|
|
207
|
-
assert.strictEqual(row.session_id, "e2e-03");
|
|
208
|
-
assert.ok((row.tokens_in ?? 0) > 0, "real tokens reported");
|
|
209
|
-
assert.ok((row.tokens_out ?? 0) > 0, "real tokens reported");
|
|
210
|
-
assert.ok(row.cost_estimate_usd > 0, "real cost estimate > 0");
|
|
211
|
-
});
|
|
212
|
-
it("E2E-04 empty retrieval → canonical 'no memory matches' (no real LLM spend)", async () => {
|
|
213
|
-
__setRawSearchForTests(async () => []);
|
|
214
|
-
const res = await realAnswer({
|
|
215
|
-
question: "What is the capital of Mars?",
|
|
216
|
-
providerOverride: provider,
|
|
217
|
-
maxTokens: MAX_TOKENS_TEST,
|
|
218
|
-
temperature: 0,
|
|
219
|
-
});
|
|
220
|
-
assert.match(res.answer, /no memory matches/i);
|
|
221
|
-
assert.strictEqual(res.citations.length, 0);
|
|
222
|
-
assert.strictEqual(res.metadata.failed_reason, "retrieval_empty");
|
|
223
|
-
assert.strictEqual(res.metadata.tokens_in, 0);
|
|
224
|
-
assert.strictEqual(res.metadata.tokens_out, 0);
|
|
225
|
-
// restore for any subsequent tests
|
|
226
|
-
__setRawSearchForTests(async () => E2E_CHUNKS);
|
|
227
|
-
});
|
|
228
|
-
});
|
|
229
|
-
}
|
|
@@ -1,388 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* src/lib/answer/__tests__/integration-sqlite.test.ts — P1 T11.
|
|
3
|
-
*
|
|
4
|
-
* End-to-end integration against a REAL `better-sqlite3` in-memory database
|
|
5
|
-
* with the v11 `answer_telemetry` schema applied. NO mocking of the DB
|
|
6
|
-
* (lesson from feedback memory: integration tests that mock the DB are
|
|
7
|
-
* useless — they catch nothing real).
|
|
8
|
-
*
|
|
9
|
-
* Pipeline exercised per call:
|
|
10
|
-
* question → retrieval (fixture stub) → prompt → MockProvider LLM →
|
|
11
|
-
* citation parse → telemetry INSERT into real SQLite → query back
|
|
12
|
-
*
|
|
13
|
-
* Coverage (10 tests):
|
|
14
|
-
* IT-01 happy path persists row with failed_reason=NULL
|
|
15
|
-
* IT-02 retrieval_empty path persists row with failed_reason=NULL (canonical message)
|
|
16
|
-
* IT-03 hallucination retry SUCCESS persists row with fallback_used=1, failed_reason=NULL
|
|
17
|
-
* IT-04 hallucination_after_retry persists row with failed_reason='hallucinated_citation'
|
|
18
|
-
* IT-05 llm_error persists row with failed_reason='provider_down'
|
|
19
|
-
* IT-06 invalid_input does NOT persist (lib throws before lazy provider build)
|
|
20
|
-
* IT-07 question_hash is sha256[:16], never raw text
|
|
21
|
-
* IT-08 timestamp_ms is monotonic + populated
|
|
22
|
-
* IT-09 cost_estimate_usd > 0 for flash-lite model, = 0 for unknown
|
|
23
|
-
* IT-10 CHECK constraint blocks invalid failed_reason values
|
|
24
|
-
*/
|
|
25
|
-
import { describe, it, beforeEach, afterEach } from "node:test";
|
|
26
|
-
import assert from "node:assert/strict";
|
|
27
|
-
import Database from "better-sqlite3";
|
|
28
|
-
import { answer as realAnswer, AnswerError, __setRawSearchForTests, MockProvider, } from "../index.js";
|
|
29
|
-
import { recordAnswer, INSERT_SQL, } from "../telemetry.js";
|
|
30
|
-
// ─── v11 schema (canonical for staged-P1 INSERT_SQL alignment) ─────────────
|
|
31
|
-
//
|
|
32
|
-
// CHECK constraint matches mapFailureReason() codomain:
|
|
33
|
-
// ('hallucinated_citation', 'provider_down', 'token_budget') OR NULL.
|
|
34
|
-
const SCHEMA_V11 = `
|
|
35
|
-
CREATE TABLE IF NOT EXISTS answer_telemetry (
|
|
36
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
37
|
-
question_hash TEXT NOT NULL,
|
|
38
|
-
session_id TEXT,
|
|
39
|
-
timestamp_ms INTEGER NOT NULL,
|
|
40
|
-
provider TEXT NOT NULL,
|
|
41
|
-
model TEXT NOT NULL,
|
|
42
|
-
retrieval_count INTEGER NOT NULL,
|
|
43
|
-
citation_count INTEGER NOT NULL,
|
|
44
|
-
tokens_in INTEGER,
|
|
45
|
-
tokens_out INTEGER,
|
|
46
|
-
latency_ms INTEGER NOT NULL,
|
|
47
|
-
fallback_used INTEGER NOT NULL DEFAULT 0,
|
|
48
|
-
failed_reason TEXT,
|
|
49
|
-
cost_estimate_usd REAL NOT NULL DEFAULT 0,
|
|
50
|
-
CHECK (failed_reason IS NULL OR failed_reason IN
|
|
51
|
-
('hallucinated_citation', 'provider_down', 'token_budget'))
|
|
52
|
-
);
|
|
53
|
-
|
|
54
|
-
CREATE INDEX IF NOT EXISTS idx_answer_telemetry_timestamp
|
|
55
|
-
ON answer_telemetry(timestamp_ms);
|
|
56
|
-
CREATE INDEX IF NOT EXISTS idx_answer_telemetry_failed
|
|
57
|
-
ON answer_telemetry(failed_reason)
|
|
58
|
-
WHERE failed_reason IS NOT NULL;
|
|
59
|
-
`;
|
|
60
|
-
// ─── Real SQLite-backed TelemetryStore (test-only adapter) ─────────────────
|
|
61
|
-
class Sqlite3TelemetryStore {
|
|
62
|
-
db;
|
|
63
|
-
stmt;
|
|
64
|
-
constructor(db) {
|
|
65
|
-
this.db = db;
|
|
66
|
-
this.stmt = db.prepare(INSERT_SQL);
|
|
67
|
-
}
|
|
68
|
-
insert(row) {
|
|
69
|
-
this.stmt.run(row);
|
|
70
|
-
}
|
|
71
|
-
count() {
|
|
72
|
-
const r = this.db
|
|
73
|
-
.prepare("SELECT COUNT(*) as c FROM answer_telemetry")
|
|
74
|
-
.get();
|
|
75
|
-
return r.c;
|
|
76
|
-
}
|
|
77
|
-
latest() {
|
|
78
|
-
return this.db
|
|
79
|
-
.prepare("SELECT * FROM answer_telemetry ORDER BY id DESC LIMIT 1")
|
|
80
|
-
.get();
|
|
81
|
-
}
|
|
82
|
-
byFailure(reason) {
|
|
83
|
-
if (reason === null) {
|
|
84
|
-
return this.db
|
|
85
|
-
.prepare("SELECT * FROM answer_telemetry WHERE failed_reason IS NULL")
|
|
86
|
-
.all();
|
|
87
|
-
}
|
|
88
|
-
return this.db
|
|
89
|
-
.prepare("SELECT * FROM answer_telemetry WHERE failed_reason = ?")
|
|
90
|
-
.all(reason);
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
// ─── Fixtures (synthetic chunks) ───────────────────────────────────────────
|
|
94
|
-
function fixtureChunks() {
|
|
95
|
-
return [
|
|
96
|
-
{
|
|
97
|
-
chunk_id: 5001,
|
|
98
|
-
file_path: "memory/entities/decision/d41.md",
|
|
99
|
-
line_range: "L10-L20",
|
|
100
|
-
content: "D41 #1: default model is gemini-2.5-flash-lite per Toto.",
|
|
101
|
-
content_hash: "h-d41",
|
|
102
|
-
score: 0.94,
|
|
103
|
-
},
|
|
104
|
-
{
|
|
105
|
-
chunk_id: 5002,
|
|
106
|
-
file_path: "memory/entities/feedback/salience.md",
|
|
107
|
-
content: "Salience formula: recency × pain × importance.",
|
|
108
|
-
content_hash: "h-sal",
|
|
109
|
-
score: 0.88,
|
|
110
|
-
},
|
|
111
|
-
{
|
|
112
|
-
chunk_id: 5003,
|
|
113
|
-
file_path: "memory/entities/lesson/never-sed.md",
|
|
114
|
-
content: "Never sed -i on .db files — corrupts page boundaries.",
|
|
115
|
-
content_hash: "h-sed",
|
|
116
|
-
score: 0.71,
|
|
117
|
-
},
|
|
118
|
-
];
|
|
119
|
-
}
|
|
120
|
-
function bindFixture() {
|
|
121
|
-
__setRawSearchForTests(async () => fixtureChunks());
|
|
122
|
-
}
|
|
123
|
-
function bindEmpty() {
|
|
124
|
-
__setRawSearchForTests(async () => []);
|
|
125
|
-
}
|
|
126
|
-
// ─── Test scaffolding ──────────────────────────────────────────────────────
|
|
127
|
-
let db;
|
|
128
|
-
let store;
|
|
129
|
-
beforeEach(() => {
|
|
130
|
-
db = new Database(":memory:");
|
|
131
|
-
db.exec(SCHEMA_V11);
|
|
132
|
-
store = new Sqlite3TelemetryStore(db);
|
|
133
|
-
bindFixture();
|
|
134
|
-
});
|
|
135
|
-
afterEach(() => {
|
|
136
|
-
db.close();
|
|
137
|
-
});
|
|
138
|
-
function answerWith(text) {
|
|
139
|
-
return (opts) => realAnswer({
|
|
140
|
-
...opts,
|
|
141
|
-
providerOverride: new MockProvider([text], 0),
|
|
142
|
-
});
|
|
143
|
-
}
|
|
144
|
-
// ─── IT-01 happy path persists row ────────────────────────────────────────
|
|
145
|
-
describe("T11 integration — real SQLite v11 schema", () => {
|
|
146
|
-
it("IT-01 happy path inserts row with failed_reason NULL", async () => {
|
|
147
|
-
const res = await answerWith("Salience is [chunk_1] formula.")({
|
|
148
|
-
question: "What is salience?",
|
|
149
|
-
});
|
|
150
|
-
recordAnswer(store, {
|
|
151
|
-
question: "What is salience?",
|
|
152
|
-
citationCount: res.citations.length,
|
|
153
|
-
metadata: res.metadata,
|
|
154
|
-
sessionId: "sess-it-01",
|
|
155
|
-
});
|
|
156
|
-
assert.strictEqual(store.count(), 1);
|
|
157
|
-
const row = store.latest();
|
|
158
|
-
assert.strictEqual(row.failed_reason, null);
|
|
159
|
-
assert.strictEqual(row.fallback_used, 0);
|
|
160
|
-
assert.strictEqual(row.session_id, "sess-it-01");
|
|
161
|
-
assert.strictEqual(row.citation_count, 1);
|
|
162
|
-
assert.strictEqual(row.retrieval_count, 3);
|
|
163
|
-
assert.strictEqual(row.model, "gemini-2.5-flash-lite");
|
|
164
|
-
assert.ok(row.timestamp_ms > 0);
|
|
165
|
-
assert.ok(row.latency_ms >= 0);
|
|
166
|
-
});
|
|
167
|
-
// ─── IT-02 retrieval_empty persists ─────────────────────────────────────
|
|
168
|
-
it("IT-02 retrieval_empty short-circuit persists row (failed_reason NULL after mapping)", async () => {
|
|
169
|
-
bindEmpty();
|
|
170
|
-
const res = await realAnswer({
|
|
171
|
-
question: "Nothing matches",
|
|
172
|
-
providerOverride: new MockProvider([], 0),
|
|
173
|
-
});
|
|
174
|
-
assert.match(res.answer, /no memory matches/i);
|
|
175
|
-
recordAnswer(store, {
|
|
176
|
-
question: "Nothing matches",
|
|
177
|
-
citationCount: 0,
|
|
178
|
-
metadata: res.metadata,
|
|
179
|
-
sessionId: "sess-it-02",
|
|
180
|
-
});
|
|
181
|
-
const row = store.latest();
|
|
182
|
-
// mapFailureReason('retrieval_empty') → null (not an SQL failure column)
|
|
183
|
-
assert.strictEqual(row.failed_reason, null);
|
|
184
|
-
assert.strictEqual(row.retrieval_count, 0);
|
|
185
|
-
assert.strictEqual(row.citation_count, 0);
|
|
186
|
-
assert.strictEqual(row.tokens_in, 0);
|
|
187
|
-
assert.strictEqual(row.tokens_out, 0);
|
|
188
|
-
});
|
|
189
|
-
// ─── IT-03 retry success ────────────────────────────────────────────────
|
|
190
|
-
it("IT-03 hallucination retry SUCCESS persists row with fallback_used=1, failed_reason NULL", async () => {
|
|
191
|
-
const provider = new MockProvider([
|
|
192
|
-
"Bad [chunk_99] first attempt.",
|
|
193
|
-
"Good [chunk_1] retry attempt.",
|
|
194
|
-
], 0);
|
|
195
|
-
const res = await realAnswer({
|
|
196
|
-
question: "Which model is default?",
|
|
197
|
-
providerOverride: provider,
|
|
198
|
-
});
|
|
199
|
-
recordAnswer(store, {
|
|
200
|
-
question: "Which model is default?",
|
|
201
|
-
citationCount: res.citations.length,
|
|
202
|
-
metadata: res.metadata,
|
|
203
|
-
sessionId: "sess-it-03",
|
|
204
|
-
});
|
|
205
|
-
const row = store.latest();
|
|
206
|
-
assert.strictEqual(row.failed_reason, null);
|
|
207
|
-
assert.strictEqual(row.fallback_used, 1);
|
|
208
|
-
assert.strictEqual(row.citation_count, 1);
|
|
209
|
-
assert.strictEqual(res.metadata.retry_count, 1);
|
|
210
|
-
});
|
|
211
|
-
// ─── IT-04 hallucination_after_retry ────────────────────────────────────
|
|
212
|
-
it("IT-04 hallucination_after_retry persists row with failed_reason='hallucinated_citation'", async () => {
|
|
213
|
-
const provider = new MockProvider(["[chunk_99] first", "[chunk_42] retry"], 0);
|
|
214
|
-
try {
|
|
215
|
-
await realAnswer({
|
|
216
|
-
question: "Adversarial",
|
|
217
|
-
providerOverride: provider,
|
|
218
|
-
});
|
|
219
|
-
assert.fail("expected AnswerError");
|
|
220
|
-
}
|
|
221
|
-
catch (err) {
|
|
222
|
-
assert.ok(err instanceof AnswerError);
|
|
223
|
-
assert.strictEqual(err.reason, "hallucination_after_retry");
|
|
224
|
-
recordAnswer(store, {
|
|
225
|
-
question: "Adversarial",
|
|
226
|
-
citationCount: 0,
|
|
227
|
-
metadata: {
|
|
228
|
-
latency_ms: err.metadata.latency_ms ?? 0,
|
|
229
|
-
tokens_in: 0,
|
|
230
|
-
tokens_out: 0,
|
|
231
|
-
provider: "mock",
|
|
232
|
-
model: "gemini-2.5-flash-lite",
|
|
233
|
-
retrieval_count: 3,
|
|
234
|
-
fallback_used: true,
|
|
235
|
-
failed_reason: err.reason,
|
|
236
|
-
},
|
|
237
|
-
sessionId: "sess-it-04",
|
|
238
|
-
});
|
|
239
|
-
}
|
|
240
|
-
const rows = store.byFailure("hallucinated_citation");
|
|
241
|
-
assert.strictEqual(rows.length, 1);
|
|
242
|
-
assert.strictEqual(rows[0].fallback_used, 1);
|
|
243
|
-
});
|
|
244
|
-
// ─── IT-05 llm_error → provider_down ────────────────────────────────────
|
|
245
|
-
it("IT-05 llm_error persists row with failed_reason='provider_down'", async () => {
|
|
246
|
-
const provider = new MockProvider([], 0);
|
|
247
|
-
provider.throwNext(new Error("ETIMEDOUT"));
|
|
248
|
-
try {
|
|
249
|
-
await realAnswer({
|
|
250
|
-
question: "Network down",
|
|
251
|
-
providerOverride: provider,
|
|
252
|
-
});
|
|
253
|
-
assert.fail("expected AnswerError");
|
|
254
|
-
}
|
|
255
|
-
catch (err) {
|
|
256
|
-
assert.ok(err instanceof AnswerError);
|
|
257
|
-
assert.strictEqual(err.reason, "llm_error");
|
|
258
|
-
recordAnswer(store, {
|
|
259
|
-
question: "Network down",
|
|
260
|
-
citationCount: 0,
|
|
261
|
-
metadata: {
|
|
262
|
-
latency_ms: 5,
|
|
263
|
-
tokens_in: 0,
|
|
264
|
-
tokens_out: 0,
|
|
265
|
-
provider: "mock",
|
|
266
|
-
model: "gemini-2.5-flash-lite",
|
|
267
|
-
retrieval_count: 3,
|
|
268
|
-
fallback_used: false,
|
|
269
|
-
failed_reason: err.reason,
|
|
270
|
-
},
|
|
271
|
-
});
|
|
272
|
-
}
|
|
273
|
-
const rows = store.byFailure("provider_down");
|
|
274
|
-
assert.strictEqual(rows.length, 1);
|
|
275
|
-
});
|
|
276
|
-
// ─── IT-06 invalid_input does NOT call telemetry (caller bug) ───────────
|
|
277
|
-
it("IT-06 invalid_input throws before any telemetry write", async () => {
|
|
278
|
-
try {
|
|
279
|
-
await realAnswer({ question: "" });
|
|
280
|
-
assert.fail("expected invalid_input");
|
|
281
|
-
}
|
|
282
|
-
catch (err) {
|
|
283
|
-
assert.ok(err instanceof AnswerError);
|
|
284
|
-
assert.strictEqual(err.reason, "invalid_input");
|
|
285
|
-
}
|
|
286
|
-
// Caller (CLI/HTTP/MCP) may choose to record; lib doesn't auto-record.
|
|
287
|
-
// We assert that no spurious row appeared on the store from the lib call.
|
|
288
|
-
assert.strictEqual(store.count(), 0);
|
|
289
|
-
});
|
|
290
|
-
// ─── IT-07 question_hash privacy ────────────────────────────────────────
|
|
291
|
-
it("IT-07 question_hash is sha256[:16] and never leaks raw text", async () => {
|
|
292
|
-
const secret = "What is my API key SUPER_SECRET_HERE?";
|
|
293
|
-
const res = await answerWith("safe [chunk_1]")({ question: secret });
|
|
294
|
-
recordAnswer(store, {
|
|
295
|
-
question: secret,
|
|
296
|
-
citationCount: res.citations.length,
|
|
297
|
-
metadata: res.metadata,
|
|
298
|
-
});
|
|
299
|
-
const row = store.latest();
|
|
300
|
-
assert.strictEqual(row.question_hash.length, 16);
|
|
301
|
-
assert.match(row.question_hash, /^[0-9a-f]{16}$/);
|
|
302
|
-
// Critical: the persisted serialization MUST NOT contain raw text.
|
|
303
|
-
const serialized = JSON.stringify(row);
|
|
304
|
-
assert.ok(!serialized.includes("SUPER_SECRET_HERE"));
|
|
305
|
-
assert.ok(!serialized.includes("API key"));
|
|
306
|
-
});
|
|
307
|
-
// ─── IT-08 timestamp monotonic ──────────────────────────────────────────
|
|
308
|
-
it("IT-08 timestamp_ms populated + monotonically non-decreasing across calls", async () => {
|
|
309
|
-
for (let i = 0; i < 3; i++) {
|
|
310
|
-
const res = await answerWith(`call ${i} [chunk_1]`)({
|
|
311
|
-
question: `Q${i}`,
|
|
312
|
-
});
|
|
313
|
-
recordAnswer(store, {
|
|
314
|
-
question: `Q${i}`,
|
|
315
|
-
citationCount: res.citations.length,
|
|
316
|
-
metadata: res.metadata,
|
|
317
|
-
});
|
|
318
|
-
// tiny delay so wall-clock ms advances
|
|
319
|
-
await new Promise((r) => setTimeout(r, 2));
|
|
320
|
-
}
|
|
321
|
-
const rows = db
|
|
322
|
-
.prepare("SELECT timestamp_ms FROM answer_telemetry ORDER BY id ASC")
|
|
323
|
-
.all();
|
|
324
|
-
assert.strictEqual(rows.length, 3);
|
|
325
|
-
assert.ok(rows[0].timestamp_ms <= rows[1].timestamp_ms);
|
|
326
|
-
assert.ok(rows[1].timestamp_ms <= rows[2].timestamp_ms);
|
|
327
|
-
});
|
|
328
|
-
// ─── IT-09 cost_estimate_usd ────────────────────────────────────────────
|
|
329
|
-
it("IT-09 cost_estimate_usd > 0 for flash-lite, = 0 for unknown model", async () => {
|
|
330
|
-
// First insert: real-shaped metadata (model=gemini-2.5-flash-lite via default).
|
|
331
|
-
const res = await answerWith("[chunk_1]")({ question: "cost?" });
|
|
332
|
-
// Override model in metadata copy to trigger price-table hit/miss.
|
|
333
|
-
recordAnswer(store, {
|
|
334
|
-
question: "cost-known",
|
|
335
|
-
citationCount: 0,
|
|
336
|
-
metadata: { ...res.metadata, model: "gemini-2.5-flash-lite", tokens_in: 1000, tokens_out: 500 },
|
|
337
|
-
});
|
|
338
|
-
recordAnswer(store, {
|
|
339
|
-
question: "cost-unknown",
|
|
340
|
-
citationCount: 0,
|
|
341
|
-
metadata: { ...res.metadata, model: "unknown-xyz", tokens_in: 1000, tokens_out: 500 },
|
|
342
|
-
});
|
|
343
|
-
const rows = db
|
|
344
|
-
.prepare("SELECT model, cost_estimate_usd FROM answer_telemetry ORDER BY id ASC")
|
|
345
|
-
.all();
|
|
346
|
-
assert.ok(rows[0].cost_estimate_usd > 0);
|
|
347
|
-
assert.strictEqual(rows[1].cost_estimate_usd, 0);
|
|
348
|
-
});
|
|
349
|
-
// ─── IT-10 CHECK constraint enforces enum ───────────────────────────────
|
|
350
|
-
it("IT-10 v11 CHECK constraint blocks bogus failed_reason values", () => {
|
|
351
|
-
// Bypass mapFailureReason to write a forbidden value directly — must throw.
|
|
352
|
-
assert.throws(() => {
|
|
353
|
-
db.prepare(INSERT_SQL).run({
|
|
354
|
-
question_hash: "0000000000000000",
|
|
355
|
-
session_id: null,
|
|
356
|
-
timestamp_ms: Date.now(),
|
|
357
|
-
provider: "mock",
|
|
358
|
-
model: "mock",
|
|
359
|
-
retrieval_count: 0,
|
|
360
|
-
citation_count: 0,
|
|
361
|
-
tokens_in: 0,
|
|
362
|
-
tokens_out: 0,
|
|
363
|
-
latency_ms: 1,
|
|
364
|
-
fallback_used: 0,
|
|
365
|
-
failed_reason: "not_a_valid_enum_value",
|
|
366
|
-
cost_estimate_usd: 0,
|
|
367
|
-
});
|
|
368
|
-
}, /CHECK constraint failed/);
|
|
369
|
-
// Valid enums work.
|
|
370
|
-
db.prepare(INSERT_SQL).run({
|
|
371
|
-
question_hash: "1111111111111111",
|
|
372
|
-
session_id: null,
|
|
373
|
-
timestamp_ms: Date.now(),
|
|
374
|
-
provider: "mock",
|
|
375
|
-
model: "mock",
|
|
376
|
-
retrieval_count: 0,
|
|
377
|
-
citation_count: 0,
|
|
378
|
-
tokens_in: 0,
|
|
379
|
-
tokens_out: 0,
|
|
380
|
-
latency_ms: 1,
|
|
381
|
-
fallback_used: 0,
|
|
382
|
-
failed_reason: "token_budget",
|
|
383
|
-
cost_estimate_usd: 0,
|
|
384
|
-
});
|
|
385
|
-
const ok = store.byFailure("token_budget");
|
|
386
|
-
assert.strictEqual(ok.length, 1);
|
|
387
|
-
});
|
|
388
|
-
});
|