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.
Files changed (68) hide show
  1. package/README.md +62 -33
  2. package/dist/api/answer.js +22 -0
  3. package/dist/api-server.js +4 -14
  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/lib/query-params.js +19 -0
  16. package/dist/mcp/tools/answer.js +23 -0
  17. package/dist/mcp-server.js +36 -5
  18. package/dist/reflect.js +2 -2
  19. package/dist/reindex-errors.js +19 -0
  20. package/dist/reindex.js +12 -2
  21. package/dist/search.js +27 -6
  22. package/package.json +4 -1
  23. package/prompts/consolidate.txt +13 -0
  24. package/prompts/digest.txt +5 -0
  25. package/dist/__tests__/brief-diversity.test.js +0 -266
  26. package/dist/__tests__/brief.test.js +0 -287
  27. package/dist/__tests__/churn.test.js +0 -66
  28. package/dist/__tests__/edge-typing.test.js +0 -99
  29. package/dist/__tests__/fts-or-fallback.test.js +0 -115
  30. package/dist/__tests__/ingest-event.test.js +0 -151
  31. package/dist/__tests__/op-audit-e2e.test.js +0 -130
  32. package/dist/__tests__/pragma-alignment.test.js +0 -123
  33. package/dist/__tests__/reindex-dedup.test.js +0 -80
  34. package/dist/__tests__/reindex-safety.test.js +0 -116
  35. package/dist/__tests__/reranker.test.js +0 -326
  36. package/dist/__tests__/retention.test.js +0 -99
  37. package/dist/__tests__/search-track-access.test.js +0 -49
  38. package/dist/__tests__/session-distill-sources.test.js +0 -98
  39. package/dist/__tests__/spo-injection.test.js +0 -172
  40. package/dist/__tests__/telemetry-per-chunk.test.js +0 -110
  41. package/dist/__tests__/temporal-detector.test.js +0 -103
  42. package/dist/__tests__/temporal-filter.test.js +0 -117
  43. package/dist/lib/answer/__tests__/e2e-gemini.test.js +0 -229
  44. package/dist/lib/answer/__tests__/integration-sqlite.test.js +0 -388
  45. package/dist/lib/answer/__tests__/integration.test.js +0 -347
  46. package/dist/lib/answer/__tests__/prompt.test.js +0 -117
  47. package/dist/lib/answer/__tests__/t5-t10.test.js +0 -501
  48. package/dist/lib/api/__tests__/safe-error-message.test.js +0 -155
  49. package/dist/lib/auth/__tests__/localhost-guard.test.js +0 -144
  50. package/dist/lib/error-sanitizer/__tests__/sanitize.test.js +0 -354
  51. package/dist/lib/events/__tests__/bus.test.js +0 -208
  52. package/dist/lib/op-audit-extension/__tests__/ran-at-guard.test.js +0 -109
  53. package/dist/lib/regex-extract/__tests__/extractor.test.js +0 -197
  54. package/dist/lib/regex-extract/__tests__/frontmatter.test.js +0 -75
  55. package/dist/lib/regex-extract/__tests__/ingest-router-l4.test.js +0 -139
  56. package/dist/lib/regex-extract/__tests__/production-wire.test.js +0 -177
  57. package/dist/lib/regex-extract/__tests__/reconcile.test.js +0 -170
  58. package/dist/lib/regex-extract/__tests__/strip-code.test.js +0 -36
  59. package/dist/privacy/__tests__/filter.test.js +0 -352
  60. package/dist/providers/__tests__/conformance-extended.test.js +0 -249
  61. package/dist/providers/__tests__/conformance.test.js +0 -98
  62. package/dist/providers/__tests__/cost-cap.test.js +0 -151
  63. package/dist/providers/__tests__/e2e-real.test.js +0 -79
  64. package/dist/providers/__tests__/factory.test.js +0 -80
  65. package/dist/providers/__tests__/fallback.test.js +0 -223
  66. package/dist/providers/__tests__/gemini.test.js +0 -191
  67. package/dist/providers/__tests__/health.test.js +0 -128
  68. package/dist/providers/__tests__/telemetry.test.js +0 -219
@@ -1,191 +0,0 @@
1
- /**
2
- * gemini.test.ts — Gemini providers mock-based tests (no real API).
3
- *
4
- * Cases (10):
5
- * - GeminiEmbedding: happy path 1 input → 1 vector of dim 3072
6
- * - GeminiEmbedding: batch 3 inputs → 3 vectors in order
7
- * - GeminiEmbedding: HTTP 401 → throws with REDACTED key (T14.6 secret hygiene)
8
- * - GeminiEmbedding: dim mismatch in response → throws clear error
9
- * - GeminiEmbedding: healthCheck happy path → ok=true with latencyMs
10
- * - GeminiEmbedding: healthCheck 503 → ok=false, error contains 503
11
- * - GeminiLLM: happy path returns text + tokensIn + tokensOut + latencyMs
12
- * - GeminiLLM: system+user combined into body correctly
13
- * - GeminiLLM: throws when `user` empty
14
- * - GeminiLLM: MissingKeyError when GEMINI_API_KEY absent
15
- */
16
- import { test, describe } from "node:test";
17
- import { strict as assert } from "node:assert";
18
- import { GeminiEmbeddingProvider, redactSecrets } from "../embedding/gemini.js";
19
- import { GeminiLLMProvider } from "../llm/gemini.js";
20
- import { MissingKeyError } from "../types.js";
21
- const FAKE_KEY = "AIzaTESTtestTESTtestTESTtestTESTtest";
22
- /** Build a fake fetchFn that returns the given body or status. */
23
- function makeFetch(opts) {
24
- const status = opts.status ?? 200;
25
- const statusText = opts.statusText ?? "OK";
26
- return async () => ({
27
- ok: status >= 200 && status < 300,
28
- status,
29
- statusText,
30
- text: async () => opts.textBody ?? JSON.stringify(opts.body ?? {}),
31
- json: async () => opts.body ?? {},
32
- });
33
- }
34
- function vectorOfDim(d, fill = 0.1) {
35
- const a = [];
36
- for (let i = 0; i < d; i++)
37
- a.push(fill);
38
- return a;
39
- }
40
- describe("GeminiEmbeddingProvider (mock)", () => {
41
- test("single embed returns Float32Array of dim 3072", async () => {
42
- const p = new GeminiEmbeddingProvider({
43
- apiKey: FAKE_KEY,
44
- fetchFn: makeFetch({
45
- body: { embeddings: [{ values: vectorOfDim(3072) }] },
46
- }),
47
- });
48
- const out = await p.embed(["hello world"]);
49
- assert.equal(out.length, 1);
50
- const v0 = out[0];
51
- assert.ok(v0 instanceof Float32Array);
52
- assert.equal(v0?.length, 3072);
53
- // Float32 has 23-bit mantissa: 0.1 round-trips as 0.10000000149011612.
54
- assert.equal(v0?.[0], Math.fround(0.1));
55
- });
56
- test("batch embed: 3 inputs → 3 vectors in order", async () => {
57
- const p = new GeminiEmbeddingProvider({
58
- apiKey: FAKE_KEY,
59
- fetchFn: makeFetch({
60
- body: {
61
- embeddings: [
62
- { values: vectorOfDim(3072, 0.1) },
63
- { values: vectorOfDim(3072, 0.2) },
64
- { values: vectorOfDim(3072, 0.3) },
65
- ],
66
- },
67
- }),
68
- });
69
- const out = await p.embed(["a", "b", "c"]);
70
- assert.equal(out.length, 3);
71
- assert.equal(out[0]?.[0], Math.fround(0.1));
72
- assert.equal(out[1]?.[0], Math.fround(0.2));
73
- assert.equal(out[2]?.[0], Math.fround(0.3));
74
- });
75
- test("HTTP 401 surfaces redacted error (no API key in message)", async () => {
76
- const upstream = `error: API_KEY_INVALID: AIza${"x".repeat(35)}`;
77
- const p = new GeminiEmbeddingProvider({
78
- apiKey: FAKE_KEY,
79
- fetchFn: makeFetch({ status: 401, statusText: "Unauthorized", textBody: upstream }),
80
- });
81
- await assert.rejects(p.embed(["hi"]), (err) => {
82
- assert.match(err.message, /HTTP 401/);
83
- // CRITICAL: the redacted message MUST NOT contain the raw key.
84
- assert.equal(err.message.includes(FAKE_KEY), false);
85
- assert.match(err.message, /AIza<REDACTED>/);
86
- return true;
87
- });
88
- });
89
- test("dim mismatch in upstream → throws clear error", async () => {
90
- const p = new GeminiEmbeddingProvider({
91
- apiKey: FAKE_KEY,
92
- fetchFn: makeFetch({
93
- body: { embeddings: [{ values: vectorOfDim(1536) }] }, // wrong dim
94
- }),
95
- });
96
- await assert.rejects(p.embed(["hi"]), /dim mismatch/);
97
- });
98
- test("healthCheck ok path", async () => {
99
- const p = new GeminiEmbeddingProvider({
100
- apiKey: FAKE_KEY,
101
- fetchFn: makeFetch({ body: { name: "models/gemini-embedding-001" } }),
102
- });
103
- const s = await p.healthCheck();
104
- assert.equal(s.ok, true);
105
- assert.equal(typeof s.latencyMs, "number");
106
- assert.equal(s.error, undefined);
107
- });
108
- test("healthCheck 503 → ok=false with HTTP 503 in error", async () => {
109
- const p = new GeminiEmbeddingProvider({
110
- apiKey: FAKE_KEY,
111
- fetchFn: makeFetch({ status: 503, statusText: "Service Unavailable" }),
112
- });
113
- const s = await p.healthCheck();
114
- assert.equal(s.ok, false);
115
- assert.match(s.error ?? "", /503/);
116
- });
117
- });
118
- describe("GeminiLLMProvider (mock)", () => {
119
- test("happy path returns text + tokensIn/tokensOut + latencyMs", async () => {
120
- const p = new GeminiLLMProvider({
121
- apiKey: FAKE_KEY,
122
- fetchFn: makeFetch({
123
- body: {
124
- candidates: [
125
- { content: { parts: [{ text: "Hello there!" }] } },
126
- ],
127
- usageMetadata: { promptTokenCount: 5, candidatesTokenCount: 3 },
128
- },
129
- }),
130
- });
131
- const out = await p.complete({ user: "Hi" });
132
- assert.equal(out.text, "Hello there!");
133
- assert.equal(out.tokensIn, 5);
134
- assert.equal(out.tokensOut, 3);
135
- assert.equal(typeof out.latencyMs, "number");
136
- });
137
- test("system+user assembled correctly (captured via fetch interceptor)", async () => {
138
- let capturedBody;
139
- const interceptor = async (_url, init) => {
140
- capturedBody = init?.body;
141
- return {
142
- ok: true,
143
- status: 200,
144
- statusText: "OK",
145
- text: async () => "{}",
146
- json: async () => ({
147
- candidates: [{ content: { parts: [{ text: "ok" }] } }],
148
- usageMetadata: { promptTokenCount: 1, candidatesTokenCount: 1 },
149
- }),
150
- };
151
- };
152
- const p = new GeminiLLMProvider({ apiKey: FAKE_KEY, fetchFn: interceptor });
153
- await p.complete({ system: "be brief", user: "two plus two?" });
154
- assert.ok(capturedBody, "fetch body must be captured");
155
- const parsed = JSON.parse(capturedBody ?? "{}");
156
- assert.equal(parsed.system_instruction?.parts?.[0]?.text, "be brief");
157
- assert.equal(parsed.contents?.[0]?.parts?.[0]?.text, "two plus two?");
158
- });
159
- test("rejects empty `user` prompt with clear error", async () => {
160
- const p = new GeminiLLMProvider({
161
- apiKey: FAKE_KEY,
162
- fetchFn: makeFetch({ body: {} }),
163
- });
164
- await assert.rejects(p.complete({ user: "" }), /`user` is required/);
165
- });
166
- test("MissingKeyError when GEMINI_API_KEY absent", () => {
167
- const origKey = process.env.GEMINI_API_KEY;
168
- delete process.env.GEMINI_API_KEY;
169
- try {
170
- assert.throws(() => new GeminiLLMProvider({ fetchFn: makeFetch({ body: {} }) }), MissingKeyError);
171
- }
172
- finally {
173
- if (origKey !== undefined)
174
- process.env.GEMINI_API_KEY = origKey;
175
- }
176
- });
177
- });
178
- describe("redactSecrets", () => {
179
- test("redacts gemini AIza..., openai sk-..., Bearer tokens, key= params", () => {
180
- const inp = "AIzaABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghi " +
181
- "sk-AAABBBCCCDDDEEEFFFGGGHHHIII " +
182
- "Bearer abcdefghijklmnopqrstuvwxyzABCDEF " +
183
- "key=AAABBBCCCDDDEEEFFFGGGHHHIII";
184
- const out = redactSecrets(inp);
185
- assert.equal(out.includes("AIzaABCDEFG"), false);
186
- assert.equal(out.includes("sk-AAA"), false);
187
- assert.equal(out.includes("Bearer abcd"), false);
188
- assert.equal(out.includes("key=AAAB"), false);
189
- assert.match(out, /AIza<REDACTED>/);
190
- });
191
- });
@@ -1,128 +0,0 @@
1
- /**
2
- * health.test.ts — T8 bootProviderHealth.
3
- *
4
- * Cases (6):
5
- * 1. happy path: both providers OK → allOk=true, no throw
6
- * 2. fail-fast on embedding down → throws ProviderHealthError
7
- * 3. soft-warn on embedding down → no throw, onWarn invoked
8
- * 4. fail-fast on LLM down → throws, mentions provider name
9
- * 5. timeout: hung healthCheck → ok=false within timeoutMs
10
- * 6. soft-warn from NOX_PROVIDER_HEALTH_FAIL_FAST=0 env override
11
- */
12
- import { test, describe } from "node:test";
13
- import { strict as assert } from "node:assert";
14
- import { bootProviderHealth, ProviderHealthError } from "../index.js";
15
- const FAKE_KEY = "AIzaTESTtestTESTtestTESTtestTESTtest";
16
- /** Tiny in-memory stub that lets us control healthCheck outcome. */
17
- class FakeEmbedding {
18
- status;
19
- name;
20
- dimensions = 3072;
21
- maxTokens = 2048;
22
- costPerMillionTokens = 0.15;
23
- constructor(name, status) {
24
- this.status = status;
25
- this.name = name;
26
- }
27
- async embed(_t) {
28
- return [];
29
- }
30
- async healthCheck() {
31
- return this.status;
32
- }
33
- }
34
- class FakeLLM {
35
- status;
36
- name;
37
- model = "fake-model";
38
- contextWindow = 100_000;
39
- constructor(name, status) {
40
- this.status = status;
41
- this.name = name;
42
- }
43
- async complete() {
44
- return { text: "", tokensIn: 0, tokensOut: 0, latencyMs: 0 };
45
- }
46
- async healthCheck() {
47
- return this.status;
48
- }
49
- }
50
- /** A provider whose healthCheck never resolves — to test timeout. */
51
- class HangingEmbedding {
52
- name = "hanger";
53
- dimensions = 3072;
54
- maxTokens = 2048;
55
- costPerMillionTokens = 0.15;
56
- async embed(_t) {
57
- return [];
58
- }
59
- healthCheck() {
60
- return new Promise(() => {
61
- /* never resolves */
62
- });
63
- }
64
- }
65
- describe("bootProviderHealth (T8)", () => {
66
- test("happy path: both OK → allOk=true, report populated", async () => {
67
- const e = new FakeEmbedding("gemini", { ok: true, latencyMs: 10 });
68
- const l = new FakeLLM("gemini", { ok: true, latencyMs: 12 });
69
- const report = await bootProviderHealth({
70
- embedding: e,
71
- llm: l,
72
- failFast: true,
73
- });
74
- assert.equal(report.allOk, true);
75
- assert.equal(report.embedding?.ok, true);
76
- assert.equal(report.llm?.ok, true);
77
- assert.equal(report.embedding?.providerName, "gemini");
78
- assert.equal(report.llm?.providerName, "gemini");
79
- });
80
- test("fail-fast embedding down → throws ProviderHealthError", async () => {
81
- const e = new FakeEmbedding("gemini", { ok: false, error: "401" });
82
- const l = new FakeLLM("gemini", { ok: true });
83
- await assert.rejects(bootProviderHealth({ embedding: e, llm: l, failFast: true }), ProviderHealthError);
84
- });
85
- test("soft-warn embedding down → no throw, onWarn invoked", async () => {
86
- const e = new FakeEmbedding("openai", { ok: false, error: "stub" });
87
- const l = new FakeLLM("gemini", { ok: true });
88
- const warnings = [];
89
- const report = await bootProviderHealth({
90
- embedding: e,
91
- llm: l,
92
- failFast: false,
93
- onWarn: (w) => warnings.push(w),
94
- });
95
- assert.equal(report.allOk, false);
96
- assert.equal(warnings.length, 1);
97
- assert.equal(warnings[0]?.providerName, "openai");
98
- assert.equal(warnings[0]?.kind, "embedding");
99
- });
100
- test("fail-fast LLM down → throws and report includes llm.providerName", async () => {
101
- const e = new FakeEmbedding("gemini", { ok: true });
102
- const l = new FakeLLM("anthropic", { ok: false, error: "stub" });
103
- await assert.rejects(bootProviderHealth({ embedding: e, llm: l, failFast: true }), ProviderHealthError);
104
- });
105
- test("timeout: hung healthCheck returns ok=false within budget", async () => {
106
- const e = new HangingEmbedding();
107
- const t0 = Date.now();
108
- const report = await bootProviderHealth({
109
- embedding: e,
110
- failFast: false,
111
- timeoutMs: 50,
112
- });
113
- const elapsed = Date.now() - t0;
114
- assert.equal(report.embedding?.ok, false);
115
- assert.match(report.embedding?.error ?? "", /timeout/i);
116
- // Allow generous slack but assert nowhere near 5s default.
117
- assert.ok(elapsed < 1000, `elapsed ${elapsed}ms should be < 1000`);
118
- });
119
- test("NOX_PROVIDER_HEALTH_FAIL_FAST=0 env → soft-warn mode", async () => {
120
- const e = new FakeEmbedding("openai", { ok: false, error: "stub" });
121
- const report = await bootProviderHealth({
122
- embedding: e,
123
- env: { NOX_PROVIDER_HEALTH_FAIL_FAST: "0", GEMINI_API_KEY: FAKE_KEY },
124
- });
125
- assert.equal(report.allOk, false);
126
- // No throw because env disabled fail-fast.
127
- });
128
- });
@@ -1,219 +0,0 @@
1
- /**
2
- * telemetry.test.ts — ProviderTelemetry queue + aggregation (T12).
3
- *
4
- * Cases (9):
5
- * 1. recordProviderCall enqueues a row with correct fields
6
- * 2. row.error_kind has secrets redacted (API key pattern stripped)
7
- * 3. row never contains prompt text (privacy invariant)
8
- * 4. queue drain flushes all rows via writeFn
9
- * 5. queue overflow: capacity exceeded → oldest entries dropped
10
- * 6. writeFn error does NOT propagate to caller
11
- * 7. aggregateCosts: last24h totals computed correctly
12
- * 8. aggregateCosts: rows older than 24h excluded
13
- * 9. aggregateCosts: per-provider breakdown populated
14
- */
15
- import { test, describe } from "node:test";
16
- import { strict as assert } from "node:assert";
17
- import { TelemetryQueue, recordProviderCall, setDefaultQueue, getDefaultQueue, aggregateCosts, } from "../telemetry.js";
18
- // ─── Helpers ──────────────────────────────────────────────────────────────────
19
- function makeQueue(rows = [], capacity) {
20
- return new TelemetryQueue({
21
- writeFn: async (row) => {
22
- rows.push(row);
23
- },
24
- capacity,
25
- });
26
- }
27
- // ─── Tests ────────────────────────────────────────────────────────────────────
28
- describe("recordProviderCall — enqueue + field mapping", () => {
29
- test("enqueues a row with correct fields", async () => {
30
- const rows = [];
31
- const q = makeQueue(rows);
32
- const prevQueue = getDefaultQueue();
33
- setDefaultQueue(q);
34
- recordProviderCall({
35
- provider_id: "gemini",
36
- model: "gemini-2.5-flash-lite",
37
- kind: "llm",
38
- tokens_in: 100,
39
- tokens_out: 50,
40
- cost_usd: 0.00015,
41
- latency_ms: 123,
42
- ok: true,
43
- caller: "kg-extract",
44
- session_id: "sess-001",
45
- });
46
- await q.drain();
47
- setDefaultQueue(prevQueue);
48
- assert.equal(rows.length, 1);
49
- const row = rows[0];
50
- assert.ok(row, "row should exist");
51
- assert.equal(row?.provider_id, "gemini");
52
- assert.equal(row?.model, "gemini-2.5-flash-lite");
53
- assert.equal(row?.kind, "llm");
54
- assert.equal(row?.tokens_in, 100);
55
- assert.equal(row?.tokens_out, 50);
56
- assert.equal(row?.ok, 1);
57
- assert.equal(row?.caller, "kg-extract");
58
- assert.equal(row?.session_id, "sess-001");
59
- assert.equal(typeof row?.ts, "number");
60
- assert.ok((row?.ts ?? 0) > 0);
61
- });
62
- test("error_kind has secrets redacted (API key pattern stripped)", async () => {
63
- const rows = [];
64
- const q = makeQueue(rows);
65
- const prevQueue = getDefaultQueue();
66
- setDefaultQueue(q);
67
- recordProviderCall({
68
- provider_id: "gemini",
69
- model: "gemini-2.5-flash-lite",
70
- kind: "llm",
71
- latency_ms: 50,
72
- ok: false,
73
- errorRaw: "401 Unauthorized: key=AIzaABCDEFGHIJKLMNOPQRSTUVWXYZ12345 is invalid",
74
- });
75
- await q.drain();
76
- setDefaultQueue(prevQueue);
77
- assert.equal(rows.length, 1);
78
- const row = rows[0];
79
- assert.ok(row?.error_kind, "error_kind should be set");
80
- // Key should be redacted.
81
- assert.equal(row?.error_kind?.includes("AIzaABCDEFGHIJKLMN"), false);
82
- assert.match(row?.error_kind ?? "", /REDACTED|401/);
83
- });
84
- test("row does NOT contain prompt text (privacy invariant)", async () => {
85
- const rows = [];
86
- const q = makeQueue(rows);
87
- const prevQueue = getDefaultQueue();
88
- setDefaultQueue(q);
89
- const secretPrompt = "CONFIDENTIAL_PROMPT_CONTENT_DO_NOT_LOG_XYZ";
90
- recordProviderCall({
91
- provider_id: "gemini",
92
- model: "gemini-2.5-flash-lite",
93
- kind: "llm",
94
- latency_ms: 10,
95
- ok: true,
96
- caller: "reflect",
97
- // NOTE: no `user` field — prompt is never passed here by design.
98
- });
99
- await q.drain();
100
- setDefaultQueue(prevQueue);
101
- const rowStr = JSON.stringify(rows[0] ?? {});
102
- // The secret prompt was never passed so it cannot appear.
103
- assert.equal(rowStr.includes(secretPrompt), false);
104
- });
105
- });
106
- describe("TelemetryQueue — drain + overflow + error isolation", () => {
107
- test("drain flushes all rows via writeFn", async () => {
108
- const rows = [];
109
- const q = makeQueue(rows);
110
- for (let i = 0; i < 10; i++) {
111
- q.enqueue({
112
- ts: Date.now(),
113
- provider_id: "gemini",
114
- model: "m",
115
- kind: "embedding",
116
- tokens_in: i,
117
- tokens_out: 0,
118
- cost_usd: 0,
119
- latency_ms: 1,
120
- ok: 1,
121
- });
122
- }
123
- await q.drain();
124
- assert.equal(rows.length, 10);
125
- });
126
- test("queue overflow: oldest entries dropped when capacity exceeded", async () => {
127
- const written = [];
128
- const q = new TelemetryQueue({
129
- writeFn: async (row) => { written.push(row); },
130
- capacity: 3,
131
- });
132
- // Enqueue 5 items — oldest 2 should be dropped.
133
- for (let i = 0; i < 5; i++) {
134
- q.enqueue({
135
- ts: i,
136
- provider_id: `p${i}`,
137
- model: "m",
138
- kind: "llm",
139
- tokens_in: 0,
140
- tokens_out: 0,
141
- cost_usd: 0,
142
- latency_ms: 1,
143
- ok: 1,
144
- });
145
- }
146
- await q.drain();
147
- // capacity=3 means at most 3 survive; p0 and p1 were pushed out.
148
- // Check that we didn't write more than 3 rows.
149
- assert.ok(written.length <= 3, `expected ≤3 rows, got ${written.length}`);
150
- // The surviving rows should be among the later-inserted ones.
151
- const writtenIds = written.map((r) => r.provider_id);
152
- // p0 or p1 may have been evicted; p4 must survive.
153
- assert.ok(writtenIds.includes("p4"), "most recent entry should survive overflow");
154
- });
155
- test("writeFn error does NOT propagate to recordProviderCall", async () => {
156
- let errorCaught = null;
157
- const q = new TelemetryQueue({
158
- writeFn: async () => {
159
- throw new Error("DB write failed");
160
- },
161
- onError: (err) => {
162
- errorCaught = err;
163
- },
164
- });
165
- const prevQueue = getDefaultQueue();
166
- setDefaultQueue(q);
167
- // Must not throw.
168
- assert.doesNotThrow(() => {
169
- recordProviderCall({
170
- provider_id: "gemini",
171
- model: "m",
172
- kind: "llm",
173
- latency_ms: 1,
174
- ok: true,
175
- });
176
- });
177
- await q.drain();
178
- setDefaultQueue(prevQueue);
179
- // Error was captured by onError, not propagated.
180
- assert.ok(errorCaught instanceof Error);
181
- assert.match(errorCaught.message, /DB write failed/);
182
- });
183
- });
184
- describe("aggregateCosts — statistics", () => {
185
- const nowMs = 1_000_000_000_000;
186
- const hour = 3_600_000;
187
- test("last24h totals computed correctly", () => {
188
- const rows = [
189
- { ts: nowMs - hour, provider_id: "gemini", model: "m", kind: "llm", tokens_in: 0, tokens_out: 0, cost_usd: 1.50, latency_ms: 10, ok: 1 },
190
- { ts: nowMs - 2 * hour, provider_id: "openai", model: "m", kind: "llm", tokens_in: 0, tokens_out: 0, cost_usd: 0.75, latency_ms: 10, ok: 1 },
191
- ];
192
- const agg = aggregateCosts(rows, nowMs);
193
- assert.ok(Math.abs(agg.last24hUsd - 2.25) < 0.001);
194
- assert.equal(agg.last24hCalls, 2);
195
- assert.equal(agg.last24hSuccessRate, 1);
196
- });
197
- test("rows older than 24h excluded", () => {
198
- const rows = [
199
- { ts: nowMs - 25 * hour, provider_id: "gemini", model: "m", kind: "llm", tokens_in: 0, tokens_out: 0, cost_usd: 100.00, latency_ms: 10, ok: 1 },
200
- { ts: nowMs - hour, provider_id: "gemini", model: "m", kind: "llm", tokens_in: 0, tokens_out: 0, cost_usd: 0.10, latency_ms: 10, ok: 1 },
201
- ];
202
- const agg = aggregateCosts(rows, nowMs);
203
- assert.ok(Math.abs(agg.last24hUsd - 0.10) < 0.001, `expected ~0.10, got ${agg.last24hUsd}`);
204
- assert.equal(agg.last24hCalls, 1);
205
- });
206
- test("per-provider breakdown populated", () => {
207
- const rows = [
208
- { ts: nowMs - hour, provider_id: "gemini", model: "m", kind: "llm", tokens_in: 0, tokens_out: 0, cost_usd: 1.00, latency_ms: 10, ok: 1 },
209
- { ts: nowMs - hour, provider_id: "gemini", model: "m", kind: "llm", tokens_in: 0, tokens_out: 0, cost_usd: 2.00, latency_ms: 10, ok: 1 },
210
- { ts: nowMs - hour, provider_id: "openai", model: "m", kind: "llm", tokens_in: 0, tokens_out: 0, cost_usd: 0.50, latency_ms: 10, ok: 0 },
211
- ];
212
- const agg = aggregateCosts(rows, nowMs);
213
- assert.ok(agg.byProvider["gemini"], "gemini in byProvider");
214
- assert.ok(Math.abs((agg.byProvider["gemini"]?.usd ?? 0) - 3.00) < 0.001);
215
- assert.equal(agg.byProvider["gemini"]?.calls, 2);
216
- assert.equal(agg.byProvider["openai"]?.calls, 1);
217
- assert.ok(Math.abs(agg.last24hSuccessRate - (2 / 3)) < 0.01);
218
- });
219
- });