benjivers/jev-mcp Public Public: anyone can read this; nobody can change it.

workbenchthis machine
Files 27603c12d06cd7899d93c0fbb8ce9331040b8a8c
186 lines · 8.7 KB · ~2.6k tok Raw History
1
// Unit tests for the pure helpers. No network, no child process.
2
3
import assert from "node:assert/strict";
4
import test from "node:test";
5
import { APIError } from "@typesafe-ai/sdk";
6
import {
7
  assertStateWithinLimit,
8
  assertUniqueIds,
9
  buildChoiceCriteria,
10
  describeError,
11
  gateConfidence,
12
  gateProbability,
13
  MalformedResponseError,
14
  MAX_CHOICE_OPTIONS,
15
  readPositiveInt,
16
  resolveNoneKey,
17
  stateSize,
18
  validateChoiceAnswer,
19
  validateNoulAnswer,
20
  validateScoreAnswer,
21
} from "../dist/lib.js";
22
23
test("readPositiveInt falls back loudly instead of yielding NaN", () => {
24
  assert.deepEqual(readPositiveInt(undefined, 15000, "T"), { value: 15000 });
25
  assert.deepEqual(readPositiveInt("  ", 15000, "T"), { value: 15000 });
26
  assert.equal(readPositiveInt("500", 15000, "T").value, 500);
27
  assert.equal(readPositiveInt("12.7", 15000, "T").value, 12);
28
29
  for (const bad of ["abc", "0", "-5", "NaN"]) {
30
    const parsed = readPositiveInt(bad, 15000, "T");
31
    assert.equal(parsed.value, 15000, `${bad} should fall back`);
32
    assert.ok(parsed.warning, `${bad} should warn`);
33
  }
34
});
35
36
test("resolveNoneKey steps aside when the caller already uses the name", () => {
37
  assert.equal(resolveNoneKey([]), "none");
38
  assert.equal(resolveNoneKey(["a", "b"]), "none");
39
  assert.equal(resolveNoneKey(["none"]), "none_of_these");
40
  assert.equal(resolveNoneKey(["none", "none_of_these"]), "none_of_these_2");
41
});
42
43
test("buildChoiceCriteria never overwrites a caller's own option", () => {
44
  const callerMeaning = "The request was already handled; no action needed.";
45
  const { criteria, noneKey } = buildChoiceCriteria({ none: callerMeaning, escalate: "Send to a human" }, true);
46
47
  assert.equal(criteria.none, callerMeaning, "the caller's option must survive verbatim");
48
  assert.equal(noneKey, "none_of_these");
49
  assert.equal(criteria.none_of_these, "None of the other options fits.");
50
});
51
52
test("buildChoiceCriteria reports the no-match key it used", () => {
53
  const { criteria, noneKey } = buildChoiceCriteria({ a: "d", b: "d" }, true);
54
  assert.equal(noneKey, "none");
55
  assert.deepEqual(Object.keys(criteria).sort(), ["a", "b", "none"]);
56
57
  const off = buildChoiceCriteria({ a: "d", b: "d" }, false);
58
  assert.equal(off.noneKey, null);
59
  assert.deepEqual(Object.keys(off.criteria).sort(), ["a", "b"]);
60
});
61
62
test("buildChoiceCriteria rejects empty, single-outcome, and oversized option sets", () => {
63
  assert.throws(() => buildChoiceCriteria({}, true), /at least one option/);
64
  assert.throws(() => buildChoiceCriteria({ only: "d" }, false), /at least two outcomes/);
65
66
  const tooMany = Object.fromEntries(Array.from({ length: MAX_CHOICE_OPTIONS + 1 }, (_, i) => [`o${i}`, null]));
67
  assert.throws(() => buildChoiceCriteria(tooMany, false), /at most 255 options/);
68
69
  const exactlyAtLimit = Object.fromEntries(Array.from({ length: MAX_CHOICE_OPTIONS }, (_, i) => [`o${i}`, null]));
70
  assert.doesNotThrow(() => buildChoiceCriteria(exactlyAtLimit, false));
71
});
72
73
test("assertUniqueIds names the duplicates rather than dropping questions", () => {
74
  assert.doesNotThrow(() => assertUniqueIds(["a", "b", "c"]));
75
  assert.throws(() => assertUniqueIds(["a", "b", "a"]), /Duplicate question ids: "a"/);
76
});
77
78
test("state size is measured, and oversized state is rejected not truncated", () => {
79
  assert.equal(stateSize("abcde"), 5);
80
  assert.equal(stateSize({ a: 1 }), JSON.stringify({ a: 1 }).length);
81
82
  assert.doesNotThrow(() => assertStateWithinLimit("abc", 10));
83
  assert.throws(() => assertStateWithinLimit("a".repeat(20), 10), /above the 10 limit/);
84
});
85
86
test("gateConfidence maps confidence onto an action", () => {
87
  assert.equal(gateConfidence(0.95, 0.8, 0.5), "act");
88
  assert.equal(gateConfidence(0.8, 0.8, 0.5), "act");
89
  assert.equal(gateConfidence(0.6, 0.8, 0.5), "review");
90
  assert.equal(gateConfidence(0.2, 0.8, 0.5), "abstain");
91
  assert.equal(gateConfidence(null, 0.8, 0.5), "abstain");
92
  assert.equal(gateConfidence(undefined, 0.8, 0.5), "abstain");
93
});
94
95
test("gateProbability keeps the middle band uncertain instead of rounding", () => {
96
  assert.equal(gateProbability(0.9, 0.7, 0.3), "yes");
97
  assert.equal(gateProbability(0.7, 0.7, 0.3), "yes");
98
  assert.equal(gateProbability(0.51, 0.7, 0.3), "uncertain", "0.51 is a coin flip, not a yes");
99
  assert.equal(gateProbability(0.3, 0.7, 0.3), "no");
100
  assert.equal(gateProbability(0.05, 0.7, 0.3), "no");
101
});
102
103
test("describeError separates failures a caller should treat differently", () => {
104
  const missing = describeError(new Error("No API key. Set TYPESAFE_API_KEY in the environment."));
105
  assert.equal(missing.kind, "no_api_key");
106
  assert.equal(missing.retryable, false);
107
108
  const headers = new Headers({ "x-typesafe-request-id": "req_abc" });
109
  const rateLimited = describeError(APIError.fromResponse(429, {}, headers));
110
  assert.equal(rateLimited.kind, "rate_limit");
111
  assert.equal(rateLimited.retryable, true);
112
  assert.equal(rateLimited.status, 429);
113
  assert.equal(rateLimited.requestId, "req_abc");
114
115
  const unauthorized = describeError(APIError.fromResponse(401, {}, new Headers()));
116
  assert.equal(unauthorized.kind, "authentication");
117
  assert.equal(unauthorized.retryable, false, "a bad key never succeeds on retry");
118
119
  const malformed = describeError(APIError.fromResponse(422, {}, new Headers()));
120
  assert.equal(malformed.kind, "invalid_request");
121
  assert.equal(malformed.retryable, false);
122
123
  const overloaded = describeError(APIError.fromResponse(529, {}, new Headers()));
124
  assert.equal(overloaded.kind, "server_error");
125
  assert.equal(overloaded.retryable, true);
126
});
127
128
// ── Answer validation ───────────────────────────────────────────────────────
129
130
const KEYS = ["a", "b", "none"];
131
const goodChoice = { type: "choice", choice: "a", confidence: 0.8, probabilities: { a: 0.8, b: 0.15, none: 0.05 } };
132
133
test("validateChoiceAnswer accepts a well-formed answer", () => {
134
  assert.doesNotThrow(() => validateChoiceAnswer(goodChoice, KEYS, "q"));
135
});
136
137
test("validateChoiceAnswer rejects a choice that was never offered", () => {
138
  const answer = { ...goodChoice, choice: "c", probabilities: { a: 0.8, b: 0.15, none: 0.05 } };
139
  assert.throws(() => validateChoiceAnswer(answer, KEYS, "q"), MalformedResponseError);
140
});
141
142
test("validateChoiceAnswer rejects a distribution over the wrong options", () => {
143
  const missing = { ...goodChoice, probabilities: { a: 0.9, b: 0.1 } };
144
  assert.throws(() => validateChoiceAnswer(missing, KEYS, "q"), /offered/);
145
  const extra = { ...goodChoice, probabilities: { a: 0.8, b: 0.1, none: 0.05, c: 0.05 } };
146
  assert.throws(() => validateChoiceAnswer(extra, KEYS, "q"), /offered/);
147
});
148
149
test("validateChoiceAnswer rejects probabilities that do not sum to one", () => {
150
  const answer = { ...goodChoice, probabilities: { a: 0.9, b: 0.9, none: 0.1 } };
151
  assert.throws(() => validateChoiceAnswer(answer, KEYS, "q"), /summing/);
152
});
153
154
test("validateChoiceAnswer rejects a choice that is not the most probable option", () => {
155
  const answer = { ...goodChoice, choice: "b" };
156
  assert.throws(() => validateChoiceAnswer(answer, KEYS, "q"), /highest probability/);
157
});
158
159
test("validateChoiceAnswer rejects NaN, out-of-range, and missing values", () => {
160
  assert.throws(() => validateChoiceAnswer({ ...goodChoice, confidence: NaN }, KEYS, "q"), MalformedResponseError);
161
  assert.throws(() => validateChoiceAnswer({ ...goodChoice, probabilities: { a: 1.5, b: -0.4, none: -0.1 } }, KEYS, "q"), MalformedResponseError);
162
  assert.throws(() => validateChoiceAnswer(undefined, KEYS, "q"), /No answer/);
163
  assert.throws(() => validateChoiceAnswer("a", KEYS, "q"), /No answer/);
164
});
165
166
test("validateScoreAnswer checks the legend and distribution against the levels sent", () => {
167
  const good = { type: "score", score: 1.2, confidence: 0.7, legend: { 0: "low", 1: "mid", 2: "high" }, probabilities: { 0: 0.1, 1: 0.6, 2: 0.3 } };
168
  assert.doesNotThrow(() => validateScoreAnswer(good, 3, "r"));
169
  assert.throws(() => validateScoreAnswer(good, 4, "r"), /legend of 3 levels/);
170
  assert.throws(() => validateScoreAnswer({ ...good, score: Infinity }, 3, "r"), /finite score/);
171
  assert.throws(() => validateScoreAnswer({ ...good, probabilities: { 0: 0.5, 1: 0.5 } }, 3, "r"), /offered/);
172
});
173
174
test("validateNoulAnswer requires one probability in [0, 1]", () => {
175
  assert.doesNotThrow(() => validateNoulAnswer({ type: "noul", noul: 0.42 }, "c"));
176
  for (const bad of [{ noul: 1.2 }, { noul: NaN }, { noul: "0.4" }, {}, undefined]) {
177
    assert.throws(() => validateNoulAnswer(bad, "c"), MalformedResponseError);
178
  }
179
});
180
181
test("describeError classifies a malformed response as retryable and never actionable", () => {
182
  const described = describeError(new MalformedResponseError("bad"));
183
  assert.equal(described.kind, "malformed_response");
184
  assert.equal(described.retryable, true);
185
  assert.match(described.hint, /should be acted on/i);
186
});
↑↓ navigate ↵ open esc close
↑↓ navigate ↵ open esc close

Keyboard shortcuts