nox-mem 3.4.0 → 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +62 -33
  2. package/dist/api/answer.js +22 -0
  3. package/dist/api-server.js +3 -2
  4. package/dist/cli/answer.js +39 -1
  5. package/dist/db.js +31 -20
  6. package/dist/doctor.js +5 -4
  7. package/dist/embed.js +53 -3
  8. package/dist/index.js +16 -10
  9. package/dist/lib/answer/index.js +3 -2
  10. package/dist/lib/answer/retrieval.js +6 -4
  11. package/dist/lib/answer/temporal.js +51 -0
  12. package/dist/lib/api-port.js +16 -0
  13. package/dist/lib/db-path.js +13 -1
  14. package/dist/lib/ingest-many.js +49 -0
  15. package/dist/mcp/tools/answer.js +23 -0
  16. package/dist/mcp-server.js +36 -5
  17. package/dist/reflect.js +2 -2
  18. package/dist/reindex-errors.js +19 -0
  19. package/dist/reindex.js +12 -2
  20. package/dist/search.js +27 -6
  21. package/package.json +4 -1
  22. package/prompts/consolidate.txt +13 -0
  23. package/prompts/digest.txt +5 -0
  24. package/dist/__tests__/brief-diversity.test.js +0 -266
  25. package/dist/__tests__/brief.test.js +0 -287
  26. package/dist/__tests__/churn.test.js +0 -66
  27. package/dist/__tests__/edge-typing.test.js +0 -99
  28. package/dist/__tests__/fts-or-fallback.test.js +0 -115
  29. package/dist/__tests__/ingest-event.test.js +0 -151
  30. package/dist/__tests__/op-audit-e2e.test.js +0 -130
  31. package/dist/__tests__/pragma-alignment.test.js +0 -123
  32. package/dist/__tests__/reindex-dedup.test.js +0 -80
  33. package/dist/__tests__/reindex-safety.test.js +0 -116
  34. package/dist/__tests__/reranker.test.js +0 -326
  35. package/dist/__tests__/retention.test.js +0 -99
  36. package/dist/__tests__/search-track-access.test.js +0 -49
  37. package/dist/__tests__/session-distill-sources.test.js +0 -98
  38. package/dist/__tests__/spo-injection.test.js +0 -172
  39. package/dist/__tests__/telemetry-per-chunk.test.js +0 -110
  40. package/dist/__tests__/temporal-detector.test.js +0 -103
  41. package/dist/__tests__/temporal-filter.test.js +0 -117
  42. package/dist/lib/answer/__tests__/e2e-gemini.test.js +0 -229
  43. package/dist/lib/answer/__tests__/integration-sqlite.test.js +0 -388
  44. package/dist/lib/answer/__tests__/integration.test.js +0 -347
  45. package/dist/lib/answer/__tests__/prompt.test.js +0 -117
  46. package/dist/lib/answer/__tests__/t5-t10.test.js +0 -501
  47. package/dist/lib/api/__tests__/safe-error-message.test.js +0 -155
  48. package/dist/lib/auth/__tests__/localhost-guard.test.js +0 -144
  49. package/dist/lib/error-sanitizer/__tests__/sanitize.test.js +0 -354
  50. package/dist/lib/events/__tests__/bus.test.js +0 -208
  51. package/dist/lib/op-audit-extension/__tests__/ran-at-guard.test.js +0 -109
  52. package/dist/lib/regex-extract/__tests__/extractor.test.js +0 -197
  53. package/dist/lib/regex-extract/__tests__/frontmatter.test.js +0 -75
  54. package/dist/lib/regex-extract/__tests__/ingest-router-l4.test.js +0 -139
  55. package/dist/lib/regex-extract/__tests__/production-wire.test.js +0 -177
  56. package/dist/lib/regex-extract/__tests__/reconcile.test.js +0 -170
  57. package/dist/lib/regex-extract/__tests__/strip-code.test.js +0 -36
  58. package/dist/privacy/__tests__/filter.test.js +0 -352
  59. package/dist/providers/__tests__/conformance-extended.test.js +0 -249
  60. package/dist/providers/__tests__/conformance.test.js +0 -98
  61. package/dist/providers/__tests__/cost-cap.test.js +0 -151
  62. package/dist/providers/__tests__/e2e-real.test.js +0 -79
  63. package/dist/providers/__tests__/factory.test.js +0 -80
  64. package/dist/providers/__tests__/fallback.test.js +0 -223
  65. package/dist/providers/__tests__/gemini.test.js +0 -191
  66. package/dist/providers/__tests__/health.test.js +0 -128
  67. package/dist/providers/__tests__/telemetry.test.js +0 -219
@@ -1,352 +0,0 @@
1
- /**
2
- * privacy/__tests__/filter.test.ts
3
- *
4
- * Test suite for the privacy redaction pipeline.
5
- * Runner: node:test (node --test)
6
- *
7
- * All secret values here are SYNTHETIC / official test vectors.
8
- * No real credentials are present.
9
- *
10
- * gitleaks:allow — test fixtures only; all values are synthetic or official test vectors.
11
- */
12
- import { describe, it } from "node:test";
13
- import assert from "node:assert/strict";
14
- import { redact } from "../filter.js";
15
- import { stripPrivateTags } from "../tag-parser.js";
16
- import { luhn } from "../patterns.js";
17
- // ─── Helper ─────────────────────────────────────────────────────────────────
18
- function assertRedacted(text, expectedKind, desc) {
19
- const result = redact(text);
20
- assert.ok(result.redactionCount > 0, `${desc ?? expectedKind}: expected redaction, got none. text="${text}"`);
21
- assert.ok(result.kinds.includes(expectedKind), `${desc ?? expectedKind}: expected kind "${expectedKind}", got [${result.kinds.join(", ")}]`);
22
- assert.ok(!result.text.includes(text.substring(0, 12)) || result.text.includes("[REDACTED"), `${desc ?? expectedKind}: raw secret still visible in output`);
23
- }
24
- function assertNotRedacted(text, desc) {
25
- const result = redact(text);
26
- assert.strictEqual(result.redactionCount, 0, `${desc ?? "negative case"}: expected no redaction, got ${result.redactionCount} for text="${text}"`);
27
- }
28
- // ─── Positive cases — one per pattern ────────────────────────────────────────
29
- describe("AWS access key id", () => {
30
- it("matches canonical AKIA format", () => {
31
- assertRedacted("key_id=AKIAIOSFODNN7EXAMPLE", "aws-access-key-id");
32
- });
33
- it("matches embedded in sentence", () => {
34
- assertRedacted("Access key: AKIAI44QH8DHBEXAMPLE was rotated.", "aws-access-key-id");
35
- });
36
- it("replaces with correct placeholder", () => {
37
- const { text } = redact("AKIAIOSFODNN7EXAMPLE");
38
- assert.ok(text.includes("[REDACTED:aws-access-key-id]"));
39
- });
40
- });
41
- describe("AWS secret access key", () => {
42
- it("matches env-var style assignment", () => {
43
- assertRedacted("aws_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", "aws-secret-key");
44
- });
45
- it("matches uppercase env name", () => {
46
- assertRedacted("AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", "aws-secret-key");
47
- });
48
- });
49
- describe("Anthropic API key", () => {
50
- it("matches sk-ant prefix", () => {
51
- assertRedacted("sk-ant-test-EXAMPLEKEY1234567890abcdefghij", "anthropic-key");
52
- });
53
- it("matches api03 variant", () => {
54
- assertRedacted("sk-ant-api03-EXAMPLEKEY1234567890abcdefghijklmnopqr", "anthropic-key");
55
- });
56
- it("matches in config line", () => {
57
- assertRedacted('ANTHROPIC_API_KEY="sk-ant-test-EXAMPLEKEY1234567890abcdefghij"', "env-secret");
58
- });
59
- });
60
- describe("OpenAI API key", () => {
61
- it("matches sk- prefix", () => {
62
- assertRedacted("sk-EXAMPLEKEY1234567890abcdefghij", "openai-key");
63
- });
64
- it("matches sk-proj variant", () => {
65
- assertRedacted("sk-proj-EXAMPLEKEY1234567890abcde", "openai-key");
66
- });
67
- it("does NOT match sk-ant- as OpenAI key", () => {
68
- const { kinds } = redact("sk-ant-test-EXAMPLEKEY1234567890abcdefghij");
69
- assert.ok(!kinds.includes("openai-key"), "sk-ant- should not fire openai-key pattern");
70
- });
71
- });
72
- describe("Gemini API key", () => {
73
- it("matches AIza prefix with 35 trailing chars", () => {
74
- assertRedacted("AIzaSyEXAMPLEKEY1234567890abcdefghij123", "gemini-key"); // gitleaks:allow
75
- });
76
- it("matches inline in code comment", () => {
77
- assertRedacted("// key = AIzaSyEXAMPLEKEY1234567890abcdefghij123 (test)", // gitleaks:allow
78
- "gemini-key");
79
- });
80
- });
81
- describe("GitHub tokens", () => {
82
- it("matches ghp_ prefix", () => {
83
- assertRedacted("ghp_EXAMPLETOKEN1234567890abcdefghij", "github-token");
84
- });
85
- it("matches gho_ prefix", () => {
86
- assertRedacted("gho_EXAMPLETOKEN1234567890abcdefghij", "github-token");
87
- });
88
- it("matches ghs_ prefix", () => {
89
- assertRedacted("ghs_EXAMPLETOKEN1234567890abcdefghij", "github-token");
90
- });
91
- it("matches ghu_ prefix", () => {
92
- assertRedacted("ghu_EXAMPLETOKEN1234567890abcdefghij", "github-token");
93
- });
94
- it("matches github_pat_ prefix", () => {
95
- assertRedacted("github_pat_EXAMPLETOKEN1234567890abcdef", "github-token");
96
- });
97
- });
98
- describe("Slack tokens", () => {
99
- it("matches xoxb- (bot token)", () => {
100
- assertRedacted("xoxb-EXAMPLE-TOKEN-1234567890", "slack-token");
101
- });
102
- it("matches xoxp- (user token)", () => {
103
- assertRedacted("xoxp-EXAMPLE-TOKEN-1234567890abcdef", "slack-token");
104
- });
105
- it("matches xoxa- prefix", () => {
106
- assertRedacted("xoxa-EXAMPLE-TOKEN-1234567890", "slack-token");
107
- });
108
- });
109
- describe("Discord bot token", () => {
110
- it("matches M + 23 chars . 6 chars . 27 chars format", () => {
111
- // Exact structure: M + 23 word chars (24 total) . 6 chars . 27 chars
112
- // Synthetic safe token (all repeat chars — not a real bot token)
113
- assertRedacted("Mkkkkkkkkkkkkkkkkkkkkkkk.AAAAAA.BBBBBBBBBBBBBBBBBBBBBBBBBBB", "discord-token");
114
- });
115
- });
116
- describe("JWT", () => {
117
- it("matches standard three-part eyJ... token", () => {
118
- const jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9" +
119
- ".eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ" +
120
- ".SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";
121
- assertRedacted(jwt, "jwt");
122
- });
123
- it("replaces JWT in Authorization header (both kinds fire)", () => {
124
- const jwt = "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ1c2VyMTIzIn0.SIGNATURE_EXAMPLE_123456"; // gitleaks:allow
125
- const text = `Authorization: Bearer ${jwt}`;
126
- const { redactionCount } = redact(text);
127
- assert.ok(redactionCount > 0, "auth header or JWT must fire");
128
- });
129
- });
130
- describe("PEM private key", () => {
131
- it("matches RSA private key block", () => {
132
- const pem = [
133
- "-----BEGIN RSA PRIVATE KEY-----",
134
- "MIIEpAIBAAKCAQEAEXAMPLEKEY1234567890abcdefghijklmnopqrstuvwxyz==",
135
- "-----END RSA PRIVATE KEY-----",
136
- ].join("\n");
137
- assertRedacted(pem, "pem-private-key");
138
- });
139
- it("matches generic PRIVATE KEY block", () => {
140
- const pem = [
141
- "-----BEGIN PRIVATE KEY-----", // gitleaks:allow
142
- "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcEXAMPLE==",
143
- "-----END PRIVATE KEY-----",
144
- ].join("\n");
145
- assertRedacted(pem, "pem-private-key");
146
- });
147
- it("matches EC PRIVATE KEY block", () => {
148
- const pem = "-----BEGIN EC PRIVATE KEY-----\nMHQCAQEEIEXAMPLE==\n-----END EC PRIVATE KEY-----";
149
- assertRedacted(pem, "pem-private-key");
150
- });
151
- });
152
- describe("Bearer/Basic auth header", () => {
153
- it("matches Bearer token", () => {
154
- assertRedacted("Authorization: Bearer mysecrettoken1234567890ab", "auth-header");
155
- });
156
- it("matches Basic base64", () => {
157
- assertRedacted("Authorization: Basic dXNlcjpFWEFNUExFUEFTU1dPUkQ=", "auth-header");
158
- });
159
- it("matches Token form", () => {
160
- assertRedacted("Authorization: Token EXAMPLETOKEN1234567890abcdef", "auth-header");
161
- });
162
- it("is case-insensitive for authorization keyword", () => {
163
- assertRedacted("authorization: Bearer mysecrettoken1234567890ab", "auth-header");
164
- });
165
- });
166
- describe(".env-style secrets", () => {
167
- it("matches PASSWORD=", () => {
168
- assertRedacted("PASSWORD=s3cr3tP@ssw0rd!", "env-secret");
169
- });
170
- it("matches SECRET=", () => {
171
- assertRedacted("MY_SECRET=supersecretvalue123", "env-secret");
172
- });
173
- it("matches TOKEN=", () => {
174
- assertRedacted("GITHUB_TOKEN=ghp_EXAMPLETOKEN1234567890abcdefghij", "env-secret");
175
- });
176
- it("matches API_KEY=", () => {
177
- assertRedacted("GEMINI_API_KEY=AIzaSyEXAMPLEKEY1234567890abcdefghij123", "env-secret"); // gitleaks:allow
178
- });
179
- it("matches with export prefix", () => {
180
- assertRedacted("export SECRET=mysecretvalue123", "env-secret");
181
- });
182
- it("matches quoted value", () => {
183
- assertRedacted('DB_PASSWORD="my-secret-db-pass"', "env-secret");
184
- });
185
- });
186
- describe("Credit card (Luhn-validated)", () => {
187
- it("matches Visa test number (Luhn-valid)", () => {
188
- assertRedacted("4532015112830366", "credit-card");
189
- });
190
- it("matches formatted CC with spaces", () => {
191
- assertRedacted("4532 0151 1283 0366", "credit-card");
192
- });
193
- it("matches Mastercard test number", () => {
194
- assertRedacted("5425233430109903", "credit-card");
195
- });
196
- it("does NOT redact Luhn-invalid 16-digit strings (e.g., hashes)", () => {
197
- // This is a random 16-digit string that fails Luhn
198
- const notACard = "1234567890123456"; // fails Luhn
199
- const { kinds } = redact(notACard);
200
- assert.ok(!kinds.includes("credit-card"), "Luhn-invalid string should not be redacted as CC");
201
- });
202
- });
203
- // ─── <private> tag handling ───────────────────────────────────────────────────
204
- describe("<private> tag stripping", () => {
205
- it("strips basic private tag", () => {
206
- const result = redact("before <private>secret content here</private> after");
207
- assert.ok(result.text.includes("[REDACTED:user-marked]"), "user-marked replacement missing");
208
- assert.ok(!result.text.includes("secret content here"), "tag content still visible");
209
- assert.ok(result.kinds.includes("user-marked"));
210
- assert.strictEqual(result.redactionCount, 1);
211
- });
212
- it("strips multiline private tag", () => {
213
- const text = "Header\n<private>\nline1\nline2\nline3\n</private>\nFooter";
214
- const { text: out, redactionCount } = redact(text);
215
- assert.strictEqual(redactionCount, 1);
216
- assert.ok(out.includes("[REDACTED:user-marked]"));
217
- assert.ok(!out.includes("line1"));
218
- });
219
- it("strips multiple private tags", () => {
220
- const text = "a<private>x</private>b<private>y</private>c";
221
- const { redactionCount, kinds } = redact(text);
222
- assert.strictEqual(redactionCount, 2);
223
- assert.ok(kinds.includes("user-marked"));
224
- });
225
- it("strips regex secrets inside private tags (tag wins, runs first)", () => {
226
- const secret = "AKIAIOSFODNN7EXAMPLE";
227
- const text = `<private>${secret}</private>`;
228
- const { text: out, kinds } = redact(text);
229
- // Should be user-marked, not aws-access-key-id (tag stripped it first)
230
- assert.ok(out.includes("[REDACTED:user-marked]"));
231
- assert.ok(!out.includes(secret));
232
- assert.ok(kinds.includes("user-marked"));
233
- });
234
- it("handles private tags with surrounding regex secrets", () => {
235
- const text = `key=sk-EXAMPLEKEY1234567890abcdefghij <private>my personal note</private>`;
236
- const { redactionCount, kinds } = redact(text);
237
- assert.ok(redactionCount >= 2, "both OpenAI key and user-marked should fire");
238
- assert.ok(kinds.includes("user-marked"));
239
- assert.ok(kinds.includes("openai-key"));
240
- });
241
- it("case-insensitive tag matching", () => {
242
- const { redactionCount } = redact("<PRIVATE>secret</PRIVATE>");
243
- assert.strictEqual(redactionCount, 1);
244
- });
245
- });
246
- // ─── Negative cases — should NOT be redacted ─────────────────────────────────
247
- describe("Negative cases (no false positives)", () => {
248
- it("UUID is not flagged as credit card", () => {
249
- // UUID has 32 hex chars, not 16 decimal digits
250
- assertNotRedacted("550e8400-e29b-41d4-a716-446655440000", "UUID");
251
- });
252
- it("SHA256 hash is not flagged", () => {
253
- assertNotRedacted("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "SHA256 hash");
254
- });
255
- it("innocent base64 of JSON is not flagged", () => {
256
- // base64 of {"hello":"world"} — looks like base64 but is not a secret
257
- const b64 = Buffer.from('{"hello":"world","count":42}').toString("base64");
258
- assertNotRedacted(b64, "innocent base64 JSON");
259
- });
260
- it("code variable named 'mySecret' is not flagged (no = assignment)", () => {
261
- assertNotRedacted("const mySecret = computeHash(data);", "code variable");
262
- });
263
- it("short token-looking string under threshold is not flagged", () => {
264
- // sk- with only 5 chars after — too short for OpenAI pattern (requires 20+)
265
- assertNotRedacted("sk-abc12", "short sk- string");
266
- });
267
- it("code identifier 'AKTION_KEY' is not flagged as AWS key (wrong prefix)", () => {
268
- assertNotRedacted("AKTION_KEY=production", "AKTION_KEY env var");
269
- });
270
- it("UUID-like 32 hex string without separators is not flagged as CC", () => {
271
- // 32 chars hex, not 16 decimal digits
272
- assertNotRedacted("a3f5c8d2e1b4a9f6c3d7e2b5a8f1c4d7", "32-char hex without separators");
273
- });
274
- it("ordinary sentence with word 'secret' in prose is not flagged", () => {
275
- assertNotRedacted("The secret to great coffee is the grind size.", "prose with 'secret' word");
276
- });
277
- it("Luhn-invalid 16-digit number (random phone-like) is not redacted", () => {
278
- // 5500000000000001 — fails Luhn (chosen to be plausible but invalid)
279
- const { kinds } = redact("5500000000000001");
280
- assert.ok(!kinds.includes("credit-card"), "Luhn-invalid not redacted as CC");
281
- });
282
- });
283
- // ─── Telemetry shape ──────────────────────────────────────────────────────────
284
- describe("Telemetry shape", () => {
285
- it("returns correct redactionCount for single pattern", () => {
286
- const { redactionCount, kinds } = redact("AKIAIOSFODNN7EXAMPLE");
287
- assert.strictEqual(redactionCount, 1);
288
- assert.deepStrictEqual(kinds, ["aws-access-key-id"]);
289
- });
290
- it("returns deduplicated kinds for repeated pattern", () => {
291
- const text = "AKIAIOSFODNN7EXAMPLE and AKIAI44QH8DHBEXAMPLE";
292
- const { redactionCount, kinds } = redact(text);
293
- assert.strictEqual(redactionCount, 2);
294
- // kinds should be deduplicated (only one entry for aws-access-key-id)
295
- assert.strictEqual(kinds.filter(k => k === "aws-access-key-id").length, 1);
296
- });
297
- it("accumulates multiple kinds", () => {
298
- const text = [
299
- "AKIAIOSFODNN7EXAMPLE",
300
- "ghp_EXAMPLETOKEN1234567890abcdefghij",
301
- "<private>hidden</private>",
302
- ].join(" ");
303
- const { redactionCount, kinds } = redact(text);
304
- assert.ok(redactionCount >= 3, `expected ≥3 redactions, got ${redactionCount}`);
305
- assert.ok(kinds.includes("aws-access-key-id"));
306
- assert.ok(kinds.includes("github-token"));
307
- assert.ok(kinds.includes("user-marked"));
308
- });
309
- it("returns empty kinds and zero count for clean text", () => {
310
- const { redactionCount, kinds, text } = redact("This is a normal chunk of text.");
311
- assert.strictEqual(redactionCount, 0);
312
- assert.deepStrictEqual(kinds, []);
313
- assert.strictEqual(text, "This is a normal chunk of text.");
314
- });
315
- it("text field is returned unchanged when nothing redacted", () => {
316
- const input = "Hello world — no secrets here.";
317
- const { text } = redact(input);
318
- assert.strictEqual(text, input);
319
- });
320
- });
321
- // ─── Luhn standalone tests ────────────────────────────────────────────────────
322
- describe("Luhn algorithm", () => {
323
- it("validates Visa test number", () => {
324
- assert.ok(luhn("4532015112830366"));
325
- });
326
- it("validates Mastercard test number", () => {
327
- assert.ok(luhn("5425233430109903"));
328
- });
329
- it("rejects invalid CC (digit sum not divisible by 10)", () => {
330
- // 1111111111111111 — fails Luhn (sum = 8+1+8+1+8+1+8+1+8+1+8+1+8+1+8+1 = not %10)
331
- assert.ok(!luhn("1111111111111111"));
332
- });
333
- it("rejects sequential digits", () => {
334
- assert.ok(!luhn("1234567890123456"));
335
- });
336
- });
337
- // ─── tag-parser standalone tests ──────────────────────────────────────────────
338
- describe("stripPrivateTags standalone", () => {
339
- it("returns tagCount=0 for text without tags", () => {
340
- const { tagCount, text } = stripPrivateTags("no tags here");
341
- assert.strictEqual(tagCount, 0);
342
- assert.strictEqual(text, "no tags here");
343
- });
344
- it("handles adjacent tags", () => {
345
- const { tagCount } = stripPrivateTags("<private>a</private><private>b</private>");
346
- assert.strictEqual(tagCount, 2);
347
- });
348
- it("handles whitespace inside tags", () => {
349
- const { text } = stripPrivateTags("<private> \n </private>");
350
- assert.ok(text.includes("[REDACTED:user-marked]"));
351
- });
352
- });
@@ -1,249 +0,0 @@
1
- /**
2
- * conformance-extended.test.ts — Extended conformance suite across all providers (T13).
3
- *
4
- * Verifies that the abstraction is actually abstract: identical input → same shape
5
- * output, modulo content. Callers must not depend on provider-specific quirks.
6
- *
7
- * Cases (14):
8
- * Embedding conformance (5):
9
- * 1. gemini: embed empty array → [] (no network call shape)
10
- * 2. all embedding providers: embed() returns Float32Array[] or throws NotImplementedError
11
- * 3. all embedding providers: healthCheck() returns HealthStatus shape (ok + optional error + optional latencyMs)
12
- * 4. all embedding providers: dimensions and maxTokens are positive integers
13
- * 5. all embedding providers: costPerMillionTokens is a non-negative number
14
- *
15
- * LLM conformance (5):
16
- * 6. all LLM providers: complete() returns CompleteResult shape or throws NotImplementedError
17
- * 7. all LLM providers: healthCheck() returns HealthStatus shape
18
- * 8. all LLM providers: name, model, contextWindow are non-empty strings/positive numbers
19
- * 9. gemini: complete() result has all required fields (text, tokensIn, tokensOut, latencyMs)
20
- * 10. stub providers: NotImplementedError from complete() names the provider
21
- *
22
- * Chain conformance (2):
23
- * 11. LLMFallbackChain exposes LLMProvider interface (name, model, contextWindow, complete, healthCheck)
24
- * 12. CostCappedProvider exposes LLMProvider interface
25
- *
26
- * Secret hygiene (2):
27
- * 13. stub errors do NOT contain API key patterns
28
- * 14. telemetry row shapes conform to ProviderTelemetryRow (all required fields present)
29
- */
30
- import { test, describe } from "node:test";
31
- import { strict as assert } from "node:assert";
32
- import { GeminiEmbeddingProvider } from "../embedding/gemini.js";
33
- import { OpenAIEmbeddingProvider } from "../embedding/openai.js";
34
- import { VoyageEmbeddingProvider } from "../embedding/voyage.js";
35
- import { GeminiLLMProvider } from "../llm/gemini.js";
36
- import { OpenAILLMProvider } from "../llm/openai.js";
37
- import { AnthropicLLMProvider } from "../llm/anthropic.js";
38
- import { NotImplementedError, MissingKeyError } from "../types.js";
39
- import { LLMFallbackChain } from "../llm/chain.js";
40
- import { CostCappedProvider } from "../../lib/cost-cap.js";
41
- const FAKE_KEY = "AIzaTESTtestTESTtestTESTtestTESTtest";
42
- /** Mock fetch that always returns a fixed embed response. */
43
- function mockEmbedFetch(dim) {
44
- const values = Array.from({ length: dim }, (_, i) => i / dim);
45
- return async () => ({
46
- ok: true, status: 200, statusText: "OK",
47
- text: async () => "{}",
48
- json: async () => ({ embeddings: [{ values }] }),
49
- });
50
- }
51
- /** Mock fetch for Gemini LLM. */
52
- function mockLLMFetch() {
53
- return async () => ({
54
- ok: true, status: 200, statusText: "OK",
55
- text: async () => "{}",
56
- json: async () => ({
57
- candidates: [{ content: { parts: [{ text: "response" }] } }],
58
- usageMetadata: { promptTokenCount: 10, candidatesTokenCount: 5 },
59
- }),
60
- });
61
- }
62
- // OpenAI is a live provider: apiKey:"" forces the deterministic no-credentials
63
- // path (MissingKeyError) so the conformance loops never consult the ambient
64
- // OPENAI_API_KEY env var nor make a network call.
65
- const ALL_EMBEDDING_PROVIDERS = [
66
- new GeminiEmbeddingProvider({ apiKey: FAKE_KEY, fetchFn: mockEmbedFetch(3072) }),
67
- new OpenAIEmbeddingProvider({ apiKey: "" }),
68
- new VoyageEmbeddingProvider(),
69
- ];
70
- const ALL_LLM_PROVIDERS = [
71
- new GeminiLLMProvider({ apiKey: FAKE_KEY, fetchFn: mockLLMFetch() }),
72
- new OpenAILLMProvider({ apiKey: "" }),
73
- new AnthropicLLMProvider(),
74
- ];
75
- // ─── Embedding conformance ────────────────────────────────────────────────────
76
- describe("EmbeddingProvider conformance — all providers", () => {
77
- test("gemini: embed([]) returns empty array without network call", async () => {
78
- const p = new GeminiEmbeddingProvider({ apiKey: FAKE_KEY, fetchFn: mockEmbedFetch(3072) });
79
- const result = await p.embed([]);
80
- assert.deepEqual(result, []);
81
- });
82
- test("all providers: embed() returns Float32Array[] or NotImplementedError/MissingKeyError", async () => {
83
- for (const p of ALL_EMBEDDING_PROVIDERS) {
84
- try {
85
- const result = await p.embed(["test input"]);
86
- assert.ok(Array.isArray(result), `${p.name}: embed() should return array`);
87
- if (result.length > 0) {
88
- assert.ok(result[0] instanceof Float32Array, `${p.name}: each element should be Float32Array`);
89
- }
90
- }
91
- catch (err) {
92
- // Stubs throw NotImplementedError; live providers (OpenAI) without a key
93
- // surface MissingKeyError. Both are acceptable conformance outcomes.
94
- assert.ok(err instanceof NotImplementedError || err instanceof MissingKeyError, `${p.name}: only NotImplementedError/MissingKeyError allowed, got: ${err}`);
95
- }
96
- }
97
- });
98
- test("all providers: healthCheck() returns HealthStatus shape", async () => {
99
- for (const p of ALL_EMBEDDING_PROVIDERS) {
100
- const status = await p.healthCheck();
101
- assert.equal(typeof status.ok, "boolean", `${p.name}: ok must be boolean`);
102
- if (status.latencyMs !== undefined) {
103
- assert.equal(typeof status.latencyMs, "number", `${p.name}: latencyMs must be number`);
104
- }
105
- if (!status.ok) {
106
- assert.ok(status.error && status.error.length > 0, `${p.name}: ok=false must have non-empty error`);
107
- }
108
- }
109
- });
110
- test("all providers: dimensions and maxTokens are positive integers", () => {
111
- for (const p of ALL_EMBEDDING_PROVIDERS) {
112
- assert.ok(Number.isInteger(p.dimensions) && p.dimensions > 0, `${p.name}: dimensions=${p.dimensions} must be positive integer`);
113
- assert.ok(Number.isInteger(p.maxTokens) && p.maxTokens > 0, `${p.name}: maxTokens=${p.maxTokens} must be positive integer`);
114
- }
115
- });
116
- test("all providers: costPerMillionTokens is non-negative number", () => {
117
- for (const p of ALL_EMBEDDING_PROVIDERS) {
118
- assert.equal(typeof p.costPerMillionTokens, "number", `${p.name}: costPerMillionTokens must be number`);
119
- assert.ok(p.costPerMillionTokens >= 0, `${p.name}: costPerMillionTokens=${p.costPerMillionTokens} must be >= 0`);
120
- }
121
- });
122
- });
123
- // ─── LLM conformance ─────────────────────────────────────────────────────────
124
- describe("LLMProvider conformance — all providers", () => {
125
- test("all providers: complete() returns CompleteResult shape or NotImplementedError/MissingKeyError", async () => {
126
- for (const p of ALL_LLM_PROVIDERS) {
127
- try {
128
- const result = await p.complete({ user: "hello" });
129
- assert.equal(typeof result.text, "string", `${p.name}: text must be string`);
130
- assert.equal(typeof result.tokensIn, "number", `${p.name}: tokensIn must be number`);
131
- assert.equal(typeof result.tokensOut, "number", `${p.name}: tokensOut must be number`);
132
- assert.equal(typeof result.latencyMs, "number", `${p.name}: latencyMs must be number`);
133
- }
134
- catch (err) {
135
- // Stubs throw NotImplementedError; live providers (OpenAI) without a key
136
- // surface MissingKeyError. Both are acceptable conformance outcomes.
137
- assert.ok(err instanceof NotImplementedError || err instanceof MissingKeyError, `${p.name}: only NotImplementedError/MissingKeyError allowed from complete(), got: ${err}`);
138
- }
139
- }
140
- });
141
- test("all providers: healthCheck() returns HealthStatus shape", async () => {
142
- for (const p of ALL_LLM_PROVIDERS) {
143
- const status = await p.healthCheck();
144
- assert.equal(typeof status.ok, "boolean", `${p.name}: ok must be boolean`);
145
- if (!status.ok) {
146
- assert.ok(status.error && status.error.length > 0, `${p.name}: ok=false must have non-empty error`);
147
- }
148
- }
149
- });
150
- test("all providers: name, model, contextWindow have correct types", () => {
151
- for (const p of ALL_LLM_PROVIDERS) {
152
- assert.equal(typeof p.name, "string", `name must be string`);
153
- assert.ok(p.name.length > 0, `${p.name}: name must be non-empty`);
154
- assert.equal(typeof p.model, "string");
155
- assert.ok(p.model.length > 0, `${p.name}: model must be non-empty`);
156
- assert.ok(typeof p.contextWindow === "number" && p.contextWindow > 0, `${p.name}: contextWindow must be positive number`);
157
- }
158
- });
159
- test("gemini: complete() result has all required fields", async () => {
160
- const p = new GeminiLLMProvider({ apiKey: FAKE_KEY, fetchFn: mockLLMFetch() });
161
- const result = await p.complete({ user: "ping", system: "be brief", maxTokens: 10 });
162
- assert.equal(result.text, "response");
163
- assert.equal(result.tokensIn, 10);
164
- assert.equal(result.tokensOut, 5);
165
- assert.ok(result.latencyMs >= 0);
166
- });
167
- test("stub providers: NotImplementedError names the provider", async () => {
168
- // OpenAI is a live provider now (throws MissingKeyError, not
169
- // NotImplementedError) — only Anthropic remains a NotImplementedError stub.
170
- const stubs = [new AnthropicLLMProvider()];
171
- for (const p of stubs) {
172
- let err;
173
- try {
174
- await p.complete({ user: "hi" });
175
- }
176
- catch (e) {
177
- err = e;
178
- }
179
- assert.ok(err instanceof NotImplementedError, `${p.name}: should throw NotImplementedError`);
180
- // Error message should name the provider.
181
- assert.ok(err?.message.includes(p.name), `NotImplementedError message should include "${p.name}": got "${err?.message}"`);
182
- }
183
- });
184
- });
185
- // ─── Chain / wrapper conformance ─────────────────────────────────────────────
186
- describe("Chain/wrapper LLMProvider conformance", () => {
187
- test("LLMFallbackChain exposes LLMProvider interface", () => {
188
- const primary = new GeminiLLMProvider({ apiKey: FAKE_KEY, fetchFn: mockLLMFetch() });
189
- const chain = new LLMFallbackChain({ primary, fallbacks: [] });
190
- assert.equal(typeof chain.name, "string");
191
- assert.equal(typeof chain.model, "string");
192
- assert.ok(chain.contextWindow > 0);
193
- assert.equal(typeof chain.complete, "function");
194
- assert.equal(typeof chain.healthCheck, "function");
195
- });
196
- test("CostCappedProvider exposes LLMProvider interface", () => {
197
- const primary = new GeminiLLMProvider({ apiKey: FAKE_KEY, fetchFn: mockLLMFetch() });
198
- const capped = new CostCappedProvider({ provider: primary, capUsd: 50 });
199
- assert.equal(typeof capped.name, "string");
200
- assert.equal(typeof capped.model, "string");
201
- assert.ok(capped.contextWindow > 0);
202
- assert.equal(typeof capped.complete, "function");
203
- assert.equal(typeof capped.healthCheck, "function");
204
- });
205
- });
206
- // ─── Secret hygiene ───────────────────────────────────────────────────────────
207
- describe("Secret hygiene conformance", () => {
208
- test("stub errors do NOT contain API key patterns", async () => {
209
- const stubs = [
210
- new OpenAIEmbeddingProvider({ apiKey: "" }),
211
- new VoyageEmbeddingProvider(),
212
- new OpenAILLMProvider({ apiKey: "" }),
213
- new AnthropicLLMProvider(),
214
- ];
215
- const keyPattern = /AIza[A-Za-z0-9_-]{20,}|sk-[A-Za-z0-9_-]{20,}|Bearer\s+[A-Za-z0-9._-]{20,}/;
216
- for (const p of stubs) {
217
- const status = await p.healthCheck();
218
- if (status.error) {
219
- assert.ok(!keyPattern.test(status.error), `${p.name}: healthCheck error should not contain key pattern`);
220
- }
221
- }
222
- });
223
- test("ProviderTelemetryRow shape: all required fields present", () => {
224
- // Verify the type contract by constructing a valid row and checking fields.
225
- const row = {
226
- ts: Date.now(),
227
- provider_id: "gemini",
228
- model: "gemini-2.5-flash-lite",
229
- kind: "llm",
230
- tokens_in: 10,
231
- tokens_out: 5,
232
- cost_usd: 0.001,
233
- latency_ms: 50,
234
- ok: 1,
235
- caller: "kg-extract",
236
- session_id: "s1",
237
- };
238
- // All required fields present.
239
- assert.equal(typeof row.ts, "number");
240
- assert.equal(typeof row.provider_id, "string");
241
- assert.equal(typeof row.model, "string");
242
- assert.ok(row.kind === "embedding" || row.kind === "llm");
243
- assert.equal(typeof row.tokens_in, "number");
244
- assert.equal(typeof row.tokens_out, "number");
245
- assert.equal(typeof row.cost_usd, "number");
246
- assert.equal(typeof row.latency_ms, "number");
247
- assert.ok(row.ok === 0 || row.ok === 1);
248
- });
249
- });