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,98 +0,0 @@
1
- /**
2
- * conformance.test.ts — interface conformance for all 5 providers.
3
- *
4
- * Each provider MUST:
5
- * - expose the locked readonly fields (name, model | dimensions etc.)
6
- * - return a HealthStatus-shaped object from healthCheck()
7
- * - live providers (OpenAI) surface MissingKeyError on the work method when
8
- * no credentials are present; remaining stubs throw NotImplementedError
9
- *
10
- * Cases:
11
- * - GeminiEmbedding readonly fields (name/dim/max/cost)
12
- * - GeminiLLM readonly fields (name/model/contextWindow)
13
- * - OpenAIEmbedding (live) throws MissingKeyError on embed() without a key
14
- * - OpenAILLM (live) throws MissingKeyError on complete() without a key
15
- * - AnthropicLLM stub throws NotImplementedError on complete()
16
- * - VoyageEmbedding stub throws NotImplementedError on embed()
17
- * - All providers return ok=false with error from healthCheck()
18
- * - Provider healthCheck() never throws (returns ok=false instead)
19
- * - Conformance shape for HealthStatus (ok required, error iff !ok)
20
- */
21
- import { test, describe } from "node:test";
22
- import { strict as assert } from "node:assert";
23
- import { GeminiEmbeddingProvider } from "../embedding/gemini.js";
24
- import { GeminiLLMProvider } from "../llm/gemini.js";
25
- import { OpenAIEmbeddingProvider } from "../embedding/openai.js";
26
- import { OpenAILLMProvider } from "../llm/openai.js";
27
- import { AnthropicLLMProvider } from "../llm/anthropic.js";
28
- import { VoyageEmbeddingProvider } from "../embedding/voyage.js";
29
- import { NotImplementedError, MissingKeyError } from "../types.js";
30
- const FAKE_KEY = "AIzaTESTtestTESTtestTESTtestTESTtest";
31
- describe("Gemini provider readonly fields", () => {
32
- test("embedding: name/dimensions/maxTokens/costPerMillionTokens locked", () => {
33
- const p = new GeminiEmbeddingProvider({ apiKey: FAKE_KEY });
34
- assert.equal(p.name, "gemini");
35
- assert.equal(p.dimensions, 3072);
36
- assert.ok(p.maxTokens >= 2048);
37
- assert.ok(p.costPerMillionTokens > 0);
38
- });
39
- test("llm: name/model/contextWindow locked (D41 default = flash-lite)", () => {
40
- const p = new GeminiLLMProvider({ apiKey: FAKE_KEY });
41
- assert.equal(p.name, "gemini");
42
- assert.equal(p.model, "gemini-2.5-flash-lite");
43
- assert.ok(p.contextWindow >= 1_000_000);
44
- });
45
- });
46
- describe("Provider work methods reject without credentials", () => {
47
- // apiKey:"" forces the no-credentials path deterministically (the `??`
48
- // resolution treats "" as a present-but-empty key, so the ambient
49
- // OPENAI_API_KEY env var is never consulted and no network call is made).
50
- test("OpenAIEmbeddingProvider.embed() throws MissingKeyError (live provider, no key)", async () => {
51
- const p = new OpenAIEmbeddingProvider({ apiKey: "" });
52
- await assert.rejects(p.embed(["hi"]), MissingKeyError);
53
- });
54
- test("OpenAILLMProvider.complete() throws MissingKeyError (live provider, no key)", async () => {
55
- const p = new OpenAILLMProvider({ apiKey: "" });
56
- await assert.rejects(p.complete({ user: "hi" }), MissingKeyError);
57
- });
58
- test("AnthropicLLMProvider.complete() throws NotImplementedError", async () => {
59
- const p = new AnthropicLLMProvider();
60
- await assert.rejects(p.complete({ user: "hi" }), NotImplementedError);
61
- });
62
- test("VoyageEmbeddingProvider.embed() throws NotImplementedError", async () => {
63
- const p = new VoyageEmbeddingProvider();
64
- await assert.rejects(p.embed(["hi"]), NotImplementedError);
65
- });
66
- });
67
- describe("Stub healthCheck conformance (T8)", () => {
68
- test("OpenAI embedding returns ok=false with error when no key", async () => {
69
- const p = new OpenAIEmbeddingProvider({ apiKey: "" });
70
- const s = await p.healthCheck();
71
- assert.equal(s.ok, false);
72
- assert.ok(s.error && s.error.length > 0);
73
- assert.equal(typeof s.latencyMs, "number");
74
- });
75
- test("Anthropic LLM stub returns ok=false with error", async () => {
76
- const p = new AnthropicLLMProvider();
77
- const s = await p.healthCheck();
78
- assert.equal(s.ok, false);
79
- assert.ok(s.error && s.error.length > 0);
80
- });
81
- test("Voyage embedding stub returns ok=false with error", async () => {
82
- const p = new VoyageEmbeddingProvider();
83
- const s = await p.healthCheck();
84
- assert.equal(s.ok, false);
85
- assert.ok(s.error && s.error.length > 0);
86
- });
87
- test("provider healthCheck never throws (returns ok=false)", async () => {
88
- const stubs = [
89
- new OpenAIEmbeddingProvider({ apiKey: "" }),
90
- new OpenAILLMProvider({ apiKey: "" }),
91
- new AnthropicLLMProvider(),
92
- new VoyageEmbeddingProvider(),
93
- ];
94
- for (const s of stubs) {
95
- await assert.doesNotReject(s.healthCheck());
96
- }
97
- });
98
- });
@@ -1,151 +0,0 @@
1
- /**
2
- * cost-cap.test.ts — CostCappedProvider + CostCapExceededError (T10).
3
- *
4
- * Cases (10):
5
- * 1. below cap → provider called, result returned
6
- * 2. at exactly cap → CostCapExceededError thrown
7
- * 3. above cap → CostCapExceededError thrown
8
- * 4. bypass=1 → proceeds despite cap, audit callback invoked
9
- * 5. CostCapExceededError message does NOT contain prompt content
10
- * 6. CostCapExceededError fields: capUsd, spentUsd, resetAtUtc set correctly
11
- * 7. estimateCostUsd: known model price computed correctly
12
- * 8. estimateCostUsd: unknown model returns 0
13
- * 9. after successful call, cost is accumulated (next call sees higher spent)
14
- * 10. in-memory accumulator resets across day boundary
15
- */
16
- import { test, describe } from "node:test";
17
- import { strict as assert } from "node:assert";
18
- import { CostCappedProvider, CostCapExceededError, estimateCostUsd, resetInMemoryAccumulator, } from "../../lib/cost-cap.js";
19
- // ─── Helpers ──────────────────────────────────────────────────────────────────
20
- function makeProvider(name, text = "ok") {
21
- return {
22
- name,
23
- model: "gemini-2.5-flash-lite",
24
- contextWindow: 1_000_000,
25
- async complete(_opts) {
26
- return { text, tokensIn: 10, tokensOut: 5, latencyMs: 1 };
27
- },
28
- async healthCheck() {
29
- return { ok: true, latencyMs: 1 };
30
- },
31
- };
32
- }
33
- // ─── Tests ────────────────────────────────────────────────────────────────────
34
- describe("CostCappedProvider — cap enforcement", () => {
35
- test("below cap → provider called, result returned", async () => {
36
- resetInMemoryAccumulator();
37
- const p = new CostCappedProvider({
38
- provider: makeProvider("gemini"),
39
- capUsd: 10.00,
40
- accumulatedCostFn: async () => 5.00,
41
- bypassFn: () => false,
42
- });
43
- const result = await p.complete({ user: "hello" });
44
- assert.equal(result.text, "ok");
45
- });
46
- test("at exactly cap → CostCapExceededError thrown", async () => {
47
- const p = new CostCappedProvider({
48
- provider: makeProvider("gemini"),
49
- capUsd: 10.00,
50
- accumulatedCostFn: async () => 10.00,
51
- bypassFn: () => false,
52
- });
53
- await assert.rejects(p.complete({ user: "hello" }), CostCapExceededError);
54
- });
55
- test("above cap → CostCapExceededError thrown", async () => {
56
- const p = new CostCappedProvider({
57
- provider: makeProvider("gemini"),
58
- capUsd: 10.00,
59
- accumulatedCostFn: async () => 50.00,
60
- bypassFn: () => false,
61
- });
62
- await assert.rejects(p.complete({ user: "hello" }), CostCapExceededError);
63
- });
64
- test("bypass=1 → proceeds despite cap, onBypass invoked", async () => {
65
- const bypassRecords = [];
66
- const p = new CostCappedProvider({
67
- provider: makeProvider("gemini"),
68
- capUsd: 10.00,
69
- accumulatedCostFn: async () => 50.00,
70
- bypassFn: () => true,
71
- onBypass: (record) => bypassRecords.push(record),
72
- });
73
- const result = await p.complete({ user: "urgent call" });
74
- assert.equal(result.text, "ok");
75
- assert.equal(bypassRecords.length, 1);
76
- assert.equal(bypassRecords[0]?.capUsd, 10.00);
77
- assert.ok((bypassRecords[0]?.spentUsd ?? 0) >= 10.00);
78
- });
79
- test("CostCapExceededError message does NOT contain prompt content", async () => {
80
- const secretPrompt = "CONFIDENTIAL_DATA_DO_NOT_LOG_12345";
81
- const p = new CostCappedProvider({
82
- provider: makeProvider("gemini"),
83
- capUsd: 1.00,
84
- accumulatedCostFn: async () => 100.00,
85
- bypassFn: () => false,
86
- });
87
- let caughtMessage = "";
88
- try {
89
- await p.complete({ user: secretPrompt });
90
- }
91
- catch (err) {
92
- caughtMessage = err instanceof Error ? err.message : String(err);
93
- }
94
- // Message must NOT contain prompt text.
95
- assert.equal(caughtMessage.includes(secretPrompt), false);
96
- // Must contain only numeric info.
97
- assert.match(caughtMessage, /CostCapExceededError/);
98
- assert.match(caughtMessage, /\$\d+\.\d+/);
99
- });
100
- test("CostCapExceededError fields populated correctly", async () => {
101
- const p = new CostCappedProvider({
102
- provider: makeProvider("gemini"),
103
- capUsd: 25.00,
104
- accumulatedCostFn: async () => 49.99,
105
- bypassFn: () => false,
106
- });
107
- let caught;
108
- try {
109
- await p.complete({ user: "hi" });
110
- }
111
- catch (err) {
112
- if (err instanceof CostCapExceededError)
113
- caught = err;
114
- }
115
- assert.ok(caught, "should have thrown CostCapExceededError");
116
- assert.equal(caught?.capUsd, 25.00);
117
- assert.equal(caught?.spentUsd, 49.99);
118
- assert.match(caught?.resetAtUtc ?? "", /^\d{4}-\d{2}-\d{2}$/);
119
- });
120
- test("after successful call cost is accumulated (in-memory)", async () => {
121
- resetInMemoryAccumulator();
122
- const spent = [];
123
- const p = new CostCappedProvider({
124
- provider: makeProvider("gemini"),
125
- capUsd: 100.00,
126
- // Each call returns 10 in + 5 out tokens at gemini-2.5-flash-lite prices.
127
- });
128
- await p.complete({ user: "call 1" });
129
- await p.complete({ user: "call 2" });
130
- // In-memory accumulator should have increased (we can verify by checking if
131
- // a cap slightly above single-call cost doesn't throw on call 1 but would on call N).
132
- // This test verifies the accumulation path ran without error.
133
- assert.ok(true, "both calls succeeded — accumulation path ran without throw");
134
- void spent;
135
- });
136
- });
137
- describe("estimateCostUsd", () => {
138
- test("gemini-2.5-flash-lite: 1M in + 1M out = $0.10 + $0.40 = $0.50", () => {
139
- const cost = estimateCostUsd("gemini-2.5-flash-lite", 1_000_000, 1_000_000);
140
- assert.ok(Math.abs(cost - 0.50) < 0.001, `expected ~0.50, got ${cost}`);
141
- });
142
- test("gpt-4o-mini: 100k in + 50k out reasonable estimate", () => {
143
- const cost = estimateCostUsd("gpt-4o-mini", 100_000, 50_000);
144
- // 100k * $0.15/1M = $0.015; 50k * $0.60/1M = $0.030 → total $0.045
145
- assert.ok(cost > 0 && cost < 1, `cost ${cost} should be small positive`);
146
- });
147
- test("unknown model returns 0", () => {
148
- const cost = estimateCostUsd("totally-unknown-model-xyz", 1_000_000, 1_000_000);
149
- assert.equal(cost, 0);
150
- });
151
- });
@@ -1,79 +0,0 @@
1
- /**
2
- * e2e-real.test.ts — E2E real-providers test (T14, gated).
3
- *
4
- * GATED: requires `NOX_E2E_REAL_PROVIDERS=1` + relevant API keys.
5
- * All tests skip with clear reason if env/keys missing.
6
- *
7
- * Cost cap: tiny inputs, MAX_TOKENS=10 to minimize spend.
8
- *
9
- * Cases:
10
- * - Gemini embedding: real embed call → Float32Array of dim 3072
11
- * - Gemini LLM: real complete() call → non-empty text response
12
- * - OpenAI: live provider — surfaces MissingKeyError without credentials
13
- * - Anthropic: still a NotImplementedError stub
14
- */
15
- import { test, describe } from "node:test";
16
- import { strict as assert } from "node:assert";
17
- import { GeminiEmbeddingProvider } from "../embedding/gemini.js";
18
- import { GeminiLLMProvider } from "../llm/gemini.js";
19
- const E2E_ENABLED = process.env.NOX_E2E_REAL_PROVIDERS === "1";
20
- const GEMINI_KEY = process.env.GEMINI_API_KEY ?? "";
21
- /** Skip helper: returns `true` if the test should run. */
22
- function shouldRun(requiredKey, keyName) {
23
- if (!E2E_ENABLED)
24
- return false;
25
- if (!requiredKey) {
26
- console.log(`[e2e-real] SKIP: ${keyName} not set`);
27
- return false;
28
- }
29
- return true;
30
- }
31
- describe("E2E real providers (gated: NOX_E2E_REAL_PROVIDERS=1)", () => {
32
- test("Gemini embedding — real embed, dim 3072", { skip: !shouldRun(GEMINI_KEY, "GEMINI_API_KEY") }, async () => {
33
- const p = new GeminiEmbeddingProvider({ apiKey: GEMINI_KEY });
34
- const results = await p.embed(["hello world"]);
35
- assert.equal(results.length, 1);
36
- const v = results[0];
37
- assert.ok(v instanceof Float32Array, "should return Float32Array");
38
- assert.equal(v.length, 3072);
39
- // Sanity: vector should not be all zeros.
40
- const nonZero = Array.from(v).some((x) => x !== 0);
41
- assert.ok(nonZero, "embedding should have non-zero values");
42
- });
43
- test("Gemini LLM — real complete(), non-empty response", { skip: !shouldRun(GEMINI_KEY, "GEMINI_API_KEY") }, async () => {
44
- const p = new GeminiLLMProvider({ apiKey: GEMINI_KEY });
45
- const result = await p.complete({
46
- user: "Say 'yes'.",
47
- maxTokens: 10,
48
- temperature: 0,
49
- });
50
- assert.ok(result.text.length > 0, "should return non-empty text");
51
- assert.ok(result.tokensIn > 0, "should report input tokens");
52
- assert.ok(result.tokensOut > 0, "should report output tokens");
53
- assert.ok(result.latencyMs > 0, "should report latency");
54
- });
55
- test("Gemini health check — real network call", { skip: !shouldRun(GEMINI_KEY, "GEMINI_API_KEY") }, async () => {
56
- const p = new GeminiEmbeddingProvider({ apiKey: GEMINI_KEY });
57
- const status = await p.healthCheck();
58
- assert.equal(status.ok, true, `health check should pass, got error: ${status.error}`);
59
- assert.ok((status.latencyMs ?? 0) > 0, "latency should be > 0 on real call");
60
- });
61
- // OpenAI is a live provider now: construction never throws, and a missing
62
- // key surfaces as MissingKeyError on the first call (not NotImplementedError).
63
- test("OpenAI live provider: no key → MissingKeyError, no network call", async () => {
64
- // This test always runs — verifies the live provider fails closed without
65
- // credentials rather than silently hitting the network.
66
- const { OpenAIEmbeddingProvider } = await import("../embedding/openai.js");
67
- const { MissingKeyError } = await import("../types.js");
68
- // apiKey:"" forces the no-credentials path deterministically (ambient
69
- // OPENAI_API_KEY env var is never consulted, so no network call is made).
70
- const p = new OpenAIEmbeddingProvider({ apiKey: "" });
71
- await assert.rejects(p.embed(["test"]), MissingKeyError);
72
- });
73
- test("Anthropic stub does NOT hit network even with ANTHROPIC_API_KEY set", async () => {
74
- const { AnthropicLLMProvider } = await import("../llm/anthropic.js");
75
- const { NotImplementedError } = await import("../types.js");
76
- const p = new AnthropicLLMProvider({ apiKey: process.env.ANTHROPIC_API_KEY ?? "dummy" });
77
- await assert.rejects(p.complete({ user: "test" }), NotImplementedError);
78
- });
79
- });
@@ -1,80 +0,0 @@
1
- /**
2
- * factory.test.ts — T2 selectEmbeddingProvider / selectLLMProvider.
3
- *
4
- * Cases (8):
5
- * 1. Default env → gemini embedding provider
6
- * 2. Default env → gemini llm provider (default model = flash-lite, D41)
7
- * 3. NOX_EMBEDDING_PROVIDER=openai → OpenAIEmbeddingProvider (stub)
8
- * 4. NOX_LLM_PROVIDER=anthropic → AnthropicLLMProvider (stub)
9
- * 5. NOX_LLM_PROVIDER=voyage → UnknownProviderError (voyage is embedding only)
10
- * 6. Unknown provider → UnknownProviderError
11
- * 7. NOX_LLM_MODEL=gemini-2.5-flash → flash full applied (regra #3, explicit)
12
- * 8. NOX_EMBEDDING_MODEL=text-embedding-3-large applied to openai stub
13
- */
14
- import { test, describe } from "node:test";
15
- import { strict as assert } from "node:assert";
16
- import { selectEmbeddingProvider, selectLLMProvider, UnknownProviderError, } from "../index.js";
17
- import { GeminiEmbeddingProvider } from "../embedding/gemini.js";
18
- import { GeminiLLMProvider } from "../llm/gemini.js";
19
- import { OpenAIEmbeddingProvider } from "../embedding/openai.js";
20
- import { AnthropicLLMProvider } from "../llm/anthropic.js";
21
- const FAKE_KEY = "AIzaTESTtestTESTtestTESTtestTESTtest";
22
- describe("selectEmbeddingProvider (T2)", () => {
23
- test("defaults to gemini with GEMINI_API_KEY set", () => {
24
- const p = selectEmbeddingProvider(undefined, { GEMINI_API_KEY: FAKE_KEY });
25
- assert.equal(p.name, "gemini");
26
- assert.equal(p.dimensions, 3072);
27
- assert.ok(p instanceof GeminiEmbeddingProvider);
28
- });
29
- test("honours NOX_EMBEDDING_PROVIDER=openai (stub)", () => {
30
- const p = selectEmbeddingProvider(undefined, { NOX_EMBEDDING_PROVIDER: "openai" });
31
- assert.equal(p.name, "openai");
32
- assert.ok(p instanceof OpenAIEmbeddingProvider);
33
- });
34
- test("honours NOX_EMBEDDING_MODEL on stub provider", () => {
35
- const p = selectEmbeddingProvider(undefined, {
36
- NOX_EMBEDDING_PROVIDER: "openai",
37
- NOX_EMBEDDING_MODEL: "text-embedding-3-large",
38
- });
39
- // `model` is implementation-level (not on the locked EmbeddingProvider
40
- // interface — see embedding/types.ts comment). All concrete classes expose
41
- // it; cast through the known shape to assert.
42
- assert.equal(p.model, "text-embedding-3-large");
43
- });
44
- test("unknown name throws UnknownProviderError", () => {
45
- assert.throws(() => selectEmbeddingProvider("cohere", { GEMINI_API_KEY: FAKE_KEY }), UnknownProviderError);
46
- });
47
- });
48
- describe("selectLLMProvider (T2)", () => {
49
- test("defaults to gemini flash-lite (D41)", () => {
50
- const p = selectLLMProvider(undefined, { GEMINI_API_KEY: FAKE_KEY });
51
- assert.equal(p.name, "gemini");
52
- assert.equal(p.model, "gemini-2.5-flash-lite");
53
- assert.ok(p instanceof GeminiLLMProvider);
54
- });
55
- test("NOX_LLM_PROVIDER=anthropic returns Anthropic stub", () => {
56
- const p = selectLLMProvider(undefined, { NOX_LLM_PROVIDER: "anthropic" });
57
- assert.equal(p.name, "anthropic");
58
- assert.ok(p instanceof AnthropicLLMProvider);
59
- });
60
- test("NOX_LLM_PROVIDER=voyage rejected (voyage is embedding-only)", () => {
61
- assert.throws(() => selectLLMProvider(undefined, { NOX_LLM_PROVIDER: "voyage" }), UnknownProviderError);
62
- });
63
- test("NOX_LLM_MODEL=gemini-2.5-flash applied explicitly (regra #3)", () => {
64
- const p = selectLLMProvider(undefined, {
65
- GEMINI_API_KEY: FAKE_KEY,
66
- NOX_LLM_MODEL: "gemini-2.5-flash",
67
- });
68
- assert.equal(p.model, "gemini-2.5-flash");
69
- });
70
- });
71
- // Sanity-check sentinel to keep the "explicit name beats env" path covered.
72
- describe("explicit arg precedence", () => {
73
- test("explicit name arg overrides env", () => {
74
- const p = selectLLMProvider("anthropic", {
75
- GEMINI_API_KEY: FAKE_KEY,
76
- NOX_LLM_PROVIDER: "gemini",
77
- });
78
- assert.equal(p.name, "anthropic");
79
- });
80
- });
@@ -1,223 +0,0 @@
1
- /**
2
- * fallback.test.ts — LLMFallbackChain (T9).
3
- *
4
- * Cases (13):
5
- * 1. primary succeeds → result returned, providerId = primary.name
6
- * 2. primary 429 → fallback tried and succeeds
7
- * 3. primary 429 → fallback also 429 → second fallback tried → all fail throws
8
- * 4. primary 401 → fail-fast, no fallback attempted
9
- * 5. primary 403 → fail-fast, no fallback attempted
10
- * 6. primary timeout → fallback tried
11
- * 7. all providers fail → throws original error, not swallowed
12
- * 8. telemetry events emitted (primary_ok on success)
13
- * 9. telemetry events emitted (primary_fail_try_next + fallback_ok on 429-then-ok)
14
- * 10. telemetry events emitted (auth_fail on 401)
15
- * 11. CostCappedProvider integration: cap exceeded throws CostCapExceededError
16
- * 12. cooldown: rate-limited provider is skipped on second call within window
17
- * 13. empty fallbacks list → primary-only mode
18
- */
19
- import { test, describe, beforeEach } from "node:test";
20
- import { strict as assert } from "node:assert";
21
- import { buildFallbackChain, clearAllCooldowns } from "../llm/chain.js";
22
- // ─── Test helpers ─────────────────────────────────────────────────────────────
23
- function makeProvider(name, model, behaviour) {
24
- return {
25
- name,
26
- model,
27
- contextWindow: 100_000,
28
- async complete(_opts) {
29
- if (behaviour.kind === "success") {
30
- return {
31
- text: behaviour.text,
32
- tokensIn: behaviour.tokensIn ?? 5,
33
- tokensOut: behaviour.tokensOut ?? 10,
34
- latencyMs: 1,
35
- };
36
- }
37
- if (behaviour.kind === "http_error") {
38
- throw new Error(`${name}: HTTP ${behaviour.status} error`);
39
- }
40
- if (behaviour.kind === "timeout") {
41
- await new Promise((resolve) => setTimeout(resolve, behaviour.delayMs));
42
- throw new Error(`${name}: timed out`);
43
- }
44
- // network_error
45
- throw new Error(`${name}: network error`);
46
- },
47
- async healthCheck() {
48
- return { ok: true, latencyMs: 1 };
49
- },
50
- };
51
- }
52
- beforeEach(() => {
53
- clearAllCooldowns();
54
- });
55
- // ─── Tests ────────────────────────────────────────────────────────────────────
56
- describe("LLMFallbackChain — basic routing", () => {
57
- test("primary succeeds → result returned with primary.name as providerId", async () => {
58
- const primary = makeProvider("gemini", "gemini-2.5-flash-lite", {
59
- kind: "success",
60
- text: "hello",
61
- });
62
- const chain = buildFallbackChain(primary, []);
63
- const result = await chain.complete({ user: "hi" });
64
- assert.equal(result.text, "hello");
65
- // CompleteResult extended with providerId by chain.
66
- const ext = result;
67
- assert.equal(ext.providerId, "gemini");
68
- });
69
- test("primary 429 → fallback succeeds", async () => {
70
- const primary = makeProvider("gemini", "gemini-2.5-flash-lite", {
71
- kind: "http_error",
72
- status: 429,
73
- });
74
- const fallback = makeProvider("anthropic", "claude-3-5-haiku", {
75
- kind: "success",
76
- text: "from fallback",
77
- });
78
- const chain = buildFallbackChain(primary, [fallback], { cooldownMs: 1 });
79
- const result = await chain.complete({ user: "hi" });
80
- assert.equal(result.text, "from fallback");
81
- const ext = result;
82
- assert.equal(ext.providerId, "anthropic");
83
- });
84
- test("primary 429 + fallback 429 → second fallback OK", async () => {
85
- const primary = makeProvider("gemini", "gemini-2.5-flash-lite", {
86
- kind: "http_error",
87
- status: 429,
88
- });
89
- const fb1 = makeProvider("anthropic", "claude-3-5-haiku", {
90
- kind: "http_error",
91
- status: 429,
92
- });
93
- const fb2 = makeProvider("openai", "gpt-4o-mini", {
94
- kind: "success",
95
- text: "openai wins",
96
- });
97
- const chain = buildFallbackChain(primary, [fb1, fb2], { cooldownMs: 1 });
98
- const result = await chain.complete({ user: "hi" });
99
- assert.equal(result.text, "openai wins");
100
- });
101
- test("primary 401 → fail-fast, no fallback attempted", async () => {
102
- const primary = makeProvider("gemini", "gemini-2.5-flash-lite", {
103
- kind: "http_error",
104
- status: 401,
105
- });
106
- const fallback = makeProvider("anthropic", "claude-3-5-haiku", {
107
- kind: "success",
108
- text: "should not reach",
109
- });
110
- const chain = buildFallbackChain(primary, [fallback]);
111
- await assert.rejects(chain.complete({ user: "hi" }), (err) => {
112
- assert.match(err.message, /auth failure/);
113
- assert.match(err.message, /401/);
114
- // Fallback was NOT used.
115
- assert.equal(err.message.includes("anthropic"), false);
116
- return true;
117
- });
118
- });
119
- test("primary 403 → fail-fast, error message mentions provider", async () => {
120
- const primary = makeProvider("gemini", "gemini-2.5-flash-lite", {
121
- kind: "http_error",
122
- status: 403,
123
- });
124
- const chain = buildFallbackChain(primary, []);
125
- await assert.rejects(chain.complete({ user: "hi" }), /auth failure/);
126
- });
127
- test("primary timeout → fallback tried and succeeds", async () => {
128
- const primary = makeProvider("gemini", "gemini-2.5-flash-lite", {
129
- kind: "timeout",
130
- delayMs: 200,
131
- });
132
- const fallback = makeProvider("anthropic", "claude-3-5-haiku", {
133
- kind: "success",
134
- text: "fallback after timeout",
135
- });
136
- const chain = buildFallbackChain(primary, [fallback], { timeoutMs: 50 });
137
- const result = await chain.complete({ user: "hi" });
138
- assert.equal(result.text, "fallback after timeout");
139
- });
140
- test("all providers fail → throws, error message is redacted", async () => {
141
- const primary = makeProvider("gemini", "gemini-2.5-flash-lite", {
142
- kind: "network_error",
143
- });
144
- const fallback = makeProvider("anthropic", "claude-3-5-haiku", {
145
- kind: "network_error",
146
- });
147
- const chain = buildFallbackChain(primary, [fallback]);
148
- await assert.rejects(chain.complete({ user: "hi" }), /network error/);
149
- });
150
- test("empty fallbacks (primary-only) → primary-only mode", async () => {
151
- const primary = makeProvider("gemini", "gemini-2.5-flash-lite", {
152
- kind: "success",
153
- text: "solo",
154
- });
155
- const chain = buildFallbackChain(primary, []);
156
- const result = await chain.complete({ user: "hi" });
157
- assert.equal(result.text, "solo");
158
- });
159
- });
160
- describe("LLMFallbackChain — telemetry events", () => {
161
- test("primary_ok event fired on success", async () => {
162
- const primary = makeProvider("gemini", "gemini-2.5-flash-lite", {
163
- kind: "success",
164
- text: "ok",
165
- });
166
- const events = [];
167
- const chain = buildFallbackChain(primary, [], {
168
- onEvent: (e) => events.push(e.kind),
169
- });
170
- await chain.complete({ user: "hi" });
171
- assert.deepEqual(events, ["primary_ok"]);
172
- });
173
- test("primary_fail_try_next + fallback_ok events on 429→ok", async () => {
174
- const primary = makeProvider("gemini", "g", { kind: "http_error", status: 429 });
175
- const fallback = makeProvider("anthropic", "h", { kind: "success", text: "ok" });
176
- const events = [];
177
- const chain = buildFallbackChain(primary, [fallback], {
178
- onEvent: (e) => events.push(e.kind),
179
- cooldownMs: 1,
180
- });
181
- await chain.complete({ user: "hi" });
182
- assert.deepEqual(events, ["primary_fail_try_next", "fallback_ok"]);
183
- });
184
- test("auth_fail event on 401", async () => {
185
- const primary = makeProvider("gemini", "g", { kind: "http_error", status: 401 });
186
- const events = [];
187
- const chain = buildFallbackChain(primary, [], {
188
- onEvent: (e) => events.push(`${e.kind}:${e.errorKind ?? ""}`),
189
- });
190
- await assert.rejects(chain.complete({ user: "hi" }));
191
- assert.deepEqual(events, ["auth_fail:auth"]);
192
- });
193
- });
194
- describe("LLMFallbackChain — cooldown", () => {
195
- test("rate-limited provider skipped on second call within cooldown window", async () => {
196
- let primaryCallCount = 0;
197
- const primary = {
198
- name: "gemini",
199
- model: "m",
200
- contextWindow: 1000,
201
- async complete() {
202
- primaryCallCount++;
203
- // First call: 429; subsequent calls (after cooldown): success.
204
- if (primaryCallCount === 1)
205
- throw new Error("HTTP 429");
206
- return { text: "ok", tokensIn: 1, tokensOut: 1, latencyMs: 1 };
207
- },
208
- async healthCheck() { return { ok: true, latencyMs: 1 }; },
209
- };
210
- const fallback = makeProvider("anthropic", "h", { kind: "success", text: "fallback-ok" });
211
- const chain = buildFallbackChain(primary, [fallback], {
212
- cooldownMs: 5_000, // long cooldown — primary stays skipped
213
- });
214
- // Call 1: primary 429 → fallback used, primary enters cooldown.
215
- const r1 = await chain.complete({ user: "1" });
216
- assert.equal(r1.text, "fallback-ok");
217
- // Call 2 (within cooldown): primary is skipped → fallback used directly.
218
- const r2 = await chain.complete({ user: "2" });
219
- assert.equal(r2.text, "fallback-ok");
220
- // Primary should only have been called once.
221
- assert.equal(primaryCallCount, 1);
222
- });
223
- });