@crowandraven/evalkeeper 0.4.1 → 0.7.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 (101) hide show
  1. package/README.md +7 -0
  2. package/dist/activity.d.ts +58 -0
  3. package/dist/activity.js +125 -0
  4. package/dist/activity.js.map +1 -0
  5. package/dist/assertExpect.d.ts +52 -0
  6. package/dist/assertExpect.js +104 -0
  7. package/dist/assertExpect.js.map +1 -0
  8. package/dist/blind.d.ts +79 -0
  9. package/dist/blind.js +113 -0
  10. package/dist/blind.js.map +1 -0
  11. package/dist/cli/addPages.d.ts +34 -0
  12. package/dist/cli/addPages.js +91 -11
  13. package/dist/cli/addPages.js.map +1 -1
  14. package/dist/cli/main.d.ts +1 -1
  15. package/dist/cli/main.js +9 -0
  16. package/dist/cli/main.js.map +1 -1
  17. package/dist/compare.d.ts +38 -0
  18. package/dist/compare.js +62 -0
  19. package/dist/compare.js.map +1 -1
  20. package/dist/glossary.d.ts +20 -0
  21. package/dist/glossary.js +20 -0
  22. package/dist/glossary.js.map +1 -1
  23. package/dist/health.js +5 -3
  24. package/dist/health.js.map +1 -1
  25. package/dist/importCases.d.ts +76 -5
  26. package/dist/importCases.js +114 -14
  27. package/dist/importCases.js.map +1 -1
  28. package/dist/index.d.ts +4 -0
  29. package/dist/index.js +4 -0
  30. package/dist/index.js.map +1 -1
  31. package/dist/memoryStore.js +3 -1
  32. package/dist/memoryStore.js.map +1 -1
  33. package/dist/readCheck.d.ts +116 -0
  34. package/dist/readCheck.js +321 -0
  35. package/dist/readCheck.js.map +1 -0
  36. package/dist/runner.d.ts +7 -0
  37. package/dist/runner.js +25 -3
  38. package/dist/runner.js.map +1 -1
  39. package/dist/settings.d.ts +81 -3
  40. package/dist/settings.js +160 -23
  41. package/dist/settings.js.map +1 -1
  42. package/dist/store.d.ts +10 -3
  43. package/dist/suggest.d.ts +10 -1
  44. package/dist/suggest.js +22 -4
  45. package/dist/suggest.js.map +1 -1
  46. package/dist/suiteContract.d.ts +17 -0
  47. package/dist/suiteContract.js +69 -0
  48. package/dist/suiteContract.js.map +1 -0
  49. package/dist/suites/crisisRisk.d.ts +83 -0
  50. package/dist/suites/crisisRisk.js +176 -0
  51. package/dist/suites/crisisRisk.js.map +1 -0
  52. package/dist/suites/crisisRiskCases.d.ts +40 -0
  53. package/dist/suites/crisisRiskCases.js +179 -0
  54. package/dist/suites/crisisRiskCases.js.map +1 -0
  55. package/dist/suites/index.d.ts +9 -0
  56. package/dist/suites/index.js +10 -0
  57. package/dist/suites/index.js.map +1 -0
  58. package/dist/testing.d.ts +140 -8
  59. package/dist/testing.js +420 -125
  60. package/dist/testing.js.map +1 -1
  61. package/dist/types.d.ts +92 -0
  62. package/dist/types.js +68 -0
  63. package/dist/types.js.map +1 -1
  64. package/dist/weekly.d.ts +21 -3
  65. package/dist/weekly.js +18 -1
  66. package/dist/weekly.js.map +1 -1
  67. package/package.json +5 -1
  68. package/src/activity.ts +154 -0
  69. package/src/assertExpect.ts +168 -0
  70. package/src/blind.ts +138 -0
  71. package/src/cli/addPages.ts +119 -17
  72. package/src/cli/main.ts +11 -0
  73. package/src/compare.ts +85 -0
  74. package/src/glossary.ts +36 -0
  75. package/src/health.ts +5 -3
  76. package/src/importCases.ts +172 -33
  77. package/src/index.ts +4 -0
  78. package/src/memoryStore.ts +2 -1
  79. package/src/readCheck.ts +458 -0
  80. package/src/runner.ts +33 -4
  81. package/src/settings.ts +192 -26
  82. package/src/store.ts +11 -3
  83. package/src/suggest.ts +33 -4
  84. package/src/suiteContract.ts +101 -0
  85. package/src/suites/crisisRisk.ts +250 -0
  86. package/src/suites/crisisRiskCases.ts +205 -0
  87. package/src/suites/index.ts +9 -0
  88. package/src/testing.ts +564 -127
  89. package/src/types.ts +141 -0
  90. package/src/weekly.ts +39 -3
  91. package/templates/app/evals/[suite]/compare/page.tsx +375 -0
  92. package/templates/app/evals/[suite]/page.tsx +55 -19
  93. package/templates/app/evals/[suite]/rate/page.tsx +133 -0
  94. package/templates/app/evals/[suite]/runs/[runId]/page.tsx +12 -0
  95. package/templates/app/evals/[suite]/side-by-side/page.tsx +300 -0
  96. package/templates/components/evalkeeper/DisagreementChip.tsx +35 -0
  97. package/templates/components/evalkeeper/RollBack.tsx +21 -1
  98. package/templates/components/evalkeeper/SettingsHistory.tsx +20 -2
  99. package/templates/components/evalkeeper/WeeklyCheck.tsx +34 -2
  100. package/templates/lib/evalkeeper/actions.ts +68 -4
  101. package/templates/lib/evalkeeper/weekly.ts +27 -4
package/dist/testing.js CHANGED
@@ -1,25 +1,95 @@
1
1
  /**
2
- * The contracts every store must meet, as Vitest tests.
2
+ * The contracts every store and set of suites must meet, as tests. They
3
+ * register with Vitest by default, or with the test functions you pass
4
+ * (`node:test` with `assertExpect`, say), so Vitest stays optional.
3
5
  *
4
6
  * @module evalkeeper/testing
5
7
  */
6
- import { describe, expect, it } from "vitest";
7
8
  import { z } from "zod";
9
+ import { BLIND_RATER, blindRating, nextToRate, skipMark } from "./blind.js";
10
+ import { confirmedLabel } from "./labels.js";
8
11
  import { createRunner } from "./runner.js";
9
- import { SettingsConflict, } from "./settings.js";
12
+ import { CHANGE_KINDS, SettingsConflict, } from "./settings.js";
13
+ import { suiteContractProblems } from "./suiteContract.js";
14
+ import { readCheckSummary } from "./readCheck.js";
15
+ export { assertExpect, } from "./assertExpect.js";
10
16
  /**
11
- * The contract every EvalStore must meet, as Vitest tests. Run it against
12
- * your store to know the runner will work on it. `make` must return an
13
- * empty store each time it's called.
17
+ * Vitest's test functions, or why they couldn't be loaded. A dynamic
18
+ * import (awaited as this module loads), so this module loads without
19
+ * Vitest when you pass your own test functions.
20
+ */
21
+ const vitest = await import("vitest").then((v) => ({
22
+ describe: v.describe,
23
+ it: v.it,
24
+ expect: v.expect,
25
+ afterAll: v.afterAll,
26
+ }), (e) => (e instanceof Error ? e : new Error(String(e))));
27
+ /** The test functions to register with: the ones given, else Vitest's. */
28
+ function testFunctions(given) {
29
+ if (given)
30
+ return given;
31
+ if (!(vitest instanceof Error))
32
+ return vitest;
33
+ throw new Error(`Vitest couldn't be loaded (${vitest.message}), so pass your own test functions: { test: { describe, it, expect: assertExpect } } with describe and it from "node:test", and assertExpect from this module.`);
34
+ }
35
+ /**
36
+ * A namer for each test: in a scoped contract, a fresh prefix per test
37
+ * (so tests don't see each other's rows); otherwise names as they are.
38
+ */
39
+ function scopeNames(scope) {
40
+ if (scope === undefined)
41
+ return () => (name) => name;
42
+ if (!scope.trim())
43
+ throw new Error('A contract\'s scope must be a prefix with some text in it, such as "contract-": an empty one would match every row.');
44
+ const run = Date.now().toString(36);
45
+ let n = 0;
46
+ return () => {
47
+ const prefix = `${scope}${run}-${(n++).toString(36)}-`;
48
+ return (name) => prefix + name;
49
+ };
50
+ }
51
+ /** Registers a scoped contract's cleanup, after checking it can run. */
52
+ function registerCleanup(t, opts) {
53
+ const { cleanup, scope } = opts;
54
+ if (!cleanup)
55
+ return;
56
+ if (scope === undefined)
57
+ throw new Error("cleanup needs a scope: it deletes only the rows the scope names. Without a scope, return an empty store from make instead.");
58
+ if (!t.afterAll)
59
+ throw new Error("cleanup runs after the contract's tests, so pass afterAll (node:test's after) with your test functions.");
60
+ t.afterAll(async () => {
61
+ await cleanup(scope);
62
+ });
63
+ }
64
+ /**
65
+ * The contract every EvalStore must meet. Run it against your store to
66
+ * know the runner will work on it. `make` must return an empty store each
67
+ * time it's called, unless `opts.scope` is set: then every suite the
68
+ * contract writes (and every request hash it picks) starts with the
69
+ * scope, the tests never look past their own rows, and `opts.cleanup`
70
+ * deletes those suites' cases, answers, tests, and outputs afterward, so
71
+ * it can run on a database that holds other rows. `opts.without` names
72
+ * run settings its tables have no column for; `opts.test` passes test
73
+ * functions other than Vitest's.
14
74
  *
15
75
  * @example
16
76
  * ```ts
17
77
  * import { describeStoreContract } from "@crowandraven/evalkeeper/testing";
18
78
  *
19
79
  * describeStoreContract("my store", () => myStore(freshDatabase()));
80
+ *
81
+ * // On a database with other rows: only rows starting "contract-" are
82
+ * // written, and cleanup deletes only those.
83
+ * describeStoreContract("our tables", () => prismaStore(prisma, map), {
84
+ * scope: "contract-",
85
+ * cleanup: (scope) => deleteScopedRows(prisma, scope, { map }),
86
+ * });
20
87
  * ```
21
88
  */
22
- export function describeStoreContract(name, make) {
89
+ export function describeStoreContract(name, make, opts = {}) {
90
+ const t = testFunctions(opts.test);
91
+ const { describe, it, expect } = t;
92
+ const names = scopeNames(opts.scope);
23
93
  const newCase = (suite, over = {}) => ({
24
94
  suite,
25
95
  input: { text: "hello", nested: { n: 1 } },
@@ -54,10 +124,12 @@ export function describeStoreContract(name, make) {
54
124
  startedBy: null,
55
125
  });
56
126
  describe(`EvalStore contract: ${name}`, () => {
127
+ registerCleanup(t, opts);
57
128
  it("keeps a case's input, tags, and answers as given", async () => {
58
129
  const store = await make();
59
- const c = await store.createCase(newCase("s"));
60
- const [listed] = await store.listCases("s");
130
+ const n = names();
131
+ const c = await store.createCase(newCase(n("s")));
132
+ const [listed] = await store.listCases(n("s"));
61
133
  expect(listed?.id).toBe(c.id);
62
134
  expect(listed?.input).toEqual({ text: "hello", nested: { n: 1 } });
63
135
  expect(listed?.tags).toEqual(["a", "b"]);
@@ -68,24 +140,54 @@ export function describeStoreContract(name, make) {
68
140
  value: { want: "HELLO" },
69
141
  });
70
142
  });
143
+ it("keeps where a case came from and when, retired ones too", async () => {
144
+ // Drafts from activity and imports skip what they made before by
145
+ // source and sourceRef, so both must read back as written.
146
+ const store = await make();
147
+ const n = names();
148
+ const before = Date.now();
149
+ const c = await store.createCase(newCase(n("s"), {
150
+ status: "DRAFT",
151
+ source: "ACTIVITY",
152
+ sourceRef: "answer-42",
153
+ note: "Flagged by an admin.",
154
+ labels: [],
155
+ }));
156
+ await store.setCaseStatus(c.id, "RETIRED");
157
+ const [listed] = await store.listCases(n("s"), {
158
+ includeRetired: true,
159
+ });
160
+ expect(listed).toMatchObject({
161
+ status: "RETIRED",
162
+ source: "ACTIVITY",
163
+ sourceRef: "answer-42",
164
+ note: "Flagged by an admin.",
165
+ labels: [],
166
+ });
167
+ // Within a second either way: some databases round to the second.
168
+ expect(+(listed?.createdAt ?? 0)).toBeGreaterThanOrEqual(before - 1000);
169
+ expect(+(listed?.createdAt ?? 0)).toBeLessThanOrEqual(Date.now() + 1000);
170
+ });
71
171
  it("lists a suite's cases oldest first, leaving out retired ones", async () => {
72
172
  const store = await make();
73
- const first = await store.createCase(newCase("s"));
173
+ const n = names();
174
+ const first = await store.createCase(newCase(n("s")));
74
175
  // Apart in time: two cases made in the same millisecond have no
75
176
  // oldest one.
76
177
  await new Promise((r) => setTimeout(r, 5));
77
- const second = await store.createCase(newCase("s"));
78
- await store.createCase(newCase("other"));
178
+ const second = await store.createCase(newCase(n("s")));
179
+ await store.createCase(newCase(n("other")));
79
180
  await store.setCaseStatus(first.id, "RETIRED");
80
- expect((await store.listCases("s")).map((c) => c.id)).toEqual([
181
+ expect((await store.listCases(n("s"))).map((c) => c.id)).toEqual([
81
182
  second.id,
82
183
  ]);
83
184
  // On request, retired ones too, still oldest first.
84
- expect((await store.listCases("s", { includeRetired: true })).map((c) => c.id)).toEqual([first.id, second.id]);
185
+ expect((await store.listCases(n("s"), { includeRetired: true })).map((c) => c.id)).toEqual([first.id, second.id]);
85
186
  });
86
187
  it("adds answers without overwriting, and changes their status", async () => {
87
188
  const store = await make();
88
- const c = await store.createCase(newCase("s", { labels: [] }));
189
+ const n = names();
190
+ const c = await store.createCase(newCase(n("s"), { labels: [] }));
89
191
  const l = await store.addLabel(c.id, {
90
192
  kind: "EXPECTED",
91
193
  status: "PENDING",
@@ -95,61 +197,113 @@ export function describeStoreContract(name, make) {
95
197
  note: null,
96
198
  });
97
199
  await store.setLabelStatus(l.id, "CONFIRMED");
98
- const [listed] = await store.listCases("s");
200
+ const [listed] = await store.listCases(n("s"));
99
201
  expect(listed?.labels).toHaveLength(1);
100
202
  expect(listed?.labels[0]?.status).toBe("CONFIRMED");
101
203
  });
204
+ it("keeps each rater's blind rating and skip beside others' answers", async () => {
205
+ const store = await make();
206
+ const n = names();
207
+ const c = await store.createCase(newCase(n("s")));
208
+ const before = (await store.listCases(n("s")))[0]?.updatedAt;
209
+ // Apart in time, so a skip that touched the case would show.
210
+ await new Promise((r) => setTimeout(r, 5));
211
+ await store.addLabel(c.id, skipMark("rater-1"));
212
+ const [skipped] = await store.listCases(n("s"));
213
+ expect(skipped?.updatedAt).toEqual(before);
214
+ expect(skipped?.labels.find((l) => l.status === "SKIPPED")).toMatchObject({ value: null, raterId: "rater-1", raterRole: BLIND_RATER });
215
+ // The skip is never graded against: the owner's answer stays in use.
216
+ expect(confirmedLabel(skipped?.labels ?? [])?.value).toEqual({
217
+ want: "HELLO",
218
+ });
219
+ expect(nextToRate(await store.listCases(n("s")), "rater-1")).toBeNull();
220
+ expect(nextToRate(await store.listCases(n("s")), "rater-2")?.id).toBe(c.id);
221
+ await store.addLabel(c.id, blindRating({
222
+ raterId: "rater-2",
223
+ value: { want: "HI" },
224
+ reason: "It greets",
225
+ }));
226
+ const [rated] = await store.listCases(n("s"));
227
+ expect(rated?.labels).toHaveLength(3);
228
+ expect(rated?.labels.find((l) => l.raterId === "rater-2")).toMatchObject({
229
+ status: "CONFIRMED",
230
+ value: { want: "HI" },
231
+ note: "It greets",
232
+ });
233
+ // The owner's answer is still there, unchanged.
234
+ expect(rated?.labels.find((l) => l.raterRole === "OWNER")).toMatchObject({
235
+ status: "CONFIRMED",
236
+ value: { want: "HELLO" },
237
+ });
238
+ expect(nextToRate(await store.listCases(n("s")), "rater-2")).toBeNull();
239
+ });
102
240
  it("starts runs as running, lists them newest first, and filters", async () => {
103
241
  const store = await make();
104
- const a = await store.createRun(newRun("s"));
242
+ const n = names();
243
+ const a = await store.createRun(newRun(n("s")));
105
244
  await new Promise((r) => setTimeout(r, 5));
106
- const b = await store.createRun(newRun("s"));
245
+ const b = await store.createRun(newRun(n("s")));
107
246
  expect(a.status).toBe("RUNNING");
108
- expect((await store.listRuns("s")).map((r) => r.id)).toEqual([
247
+ expect((await store.listRuns(n("s"))).map((r) => r.id)).toEqual([
109
248
  b.id,
110
249
  a.id,
111
250
  ]);
112
- expect(await store.listRuns("s", { limit: 1 })).toHaveLength(1);
251
+ expect(await store.listRuns(n("s"), { limit: 1 })).toHaveLength(1);
113
252
  await store.updateRun(a.id, { status: "SUCCEEDED" });
114
- expect((await store.listRuns("s", { status: "SUCCEEDED" })).map((r) => r.id)).toEqual([a.id]);
115
- expect(await store.getRun("missing")).toBeNull();
116
- });
117
- it("keeps the temperature a run was tested at", async () => {
118
- const store = await make();
119
- const warm = await store.createRun({ ...newRun("s"), temperature: 0.7 });
120
- const none = await store.createRun({ ...newRun("s"), temperature: null });
121
- expect((await store.getRun(warm.id))?.temperature).toBe(0.7);
122
- expect((await store.getRun(none.id))?.temperature ?? null).toBeNull();
253
+ expect((await store.listRuns(n("s"), { status: "SUCCEEDED" })).map((r) => r.id)).toEqual([a.id]);
254
+ expect(await store.getRun(n("missing"))).toBeNull();
123
255
  });
124
- it("keeps the output cap a run was tested at", async () => {
125
- const store = await make();
126
- const capped = await store.createRun({
127
- ...newRun("s"),
128
- maxOutputTokens: 4000,
129
- });
130
- const none = await store.createRun({
131
- ...newRun("s"),
132
- maxOutputTokens: null,
256
+ const runSettings = [
257
+ ["temperature", "temperature", 0.7],
258
+ ["maxOutputTokens", "output cap", 4000],
259
+ ];
260
+ for (const [field, words, value] of runSettings) {
261
+ if (opts.without?.includes(field)) {
262
+ it(`refuses a ${words} it has no column for, and keeps none`, async () => {
263
+ const store = await make();
264
+ const n = names();
265
+ await expect(store.createRun({ ...newRun(n("s")), [field]: value })).rejects.toThrow(field);
266
+ const none = await store.createRun({
267
+ ...newRun(n("s")),
268
+ [field]: null,
269
+ });
270
+ expect((await store.getRun(none.id))?.[field] ?? null).toBeNull();
271
+ });
272
+ continue;
273
+ }
274
+ it(`keeps the ${words} a run was tested at`, async () => {
275
+ const store = await make();
276
+ const n = names();
277
+ const set = await store.createRun({
278
+ ...newRun(n("s")),
279
+ [field]: value,
280
+ });
281
+ const none = await store.createRun({
282
+ ...newRun(n("s")),
283
+ [field]: null,
284
+ });
285
+ expect((await store.getRun(set.id))?.[field]).toBe(value);
286
+ expect((await store.getRun(none.id))?.[field] ?? null).toBeNull();
133
287
  });
134
- expect((await store.getRun(capped.id))?.maxOutputTokens).toBe(4000);
135
- expect((await store.getRun(none.id))?.maxOutputTokens ?? null).toBeNull();
136
- });
288
+ }
137
289
  it("updates a run only while it has the status it's guarded by", async () => {
138
290
  const store = await make();
139
- const r = await store.createRun(newRun("s"));
291
+ const n = names();
292
+ const r = await store.createRun(newRun(n("s")));
140
293
  await store.updateRun(r.id, { status: "FAILED" }, { status: "RUNNING" });
141
294
  await store.updateRun(r.id, { status: "SUCCEEDED" }, { status: "RUNNING" });
142
295
  expect((await store.getRun(r.id))?.status).toBe("FAILED");
143
296
  });
144
297
  it("stores outputs and scores, and finds only originals to reuse", async () => {
145
298
  const store = await make();
146
- const c = await store.createCase(newCase("s"));
147
- const r = await store.createRun(newRun("s"));
299
+ const n = names();
300
+ const c = await store.createCase(newCase(n("s")));
301
+ const r = await store.createRun(newRun(n("s")));
148
302
  const base = {
149
303
  runId: r.id,
150
304
  caseId: c.id,
151
305
  repeat: 1,
152
- requestHash: "h",
306
+ requestHash: n("h"),
153
307
  output: { text: "HELLO" },
154
308
  error: null,
155
309
  scores: null,
@@ -166,18 +320,19 @@ export function describeStoreContract(name, make) {
166
320
  expect(outs.find((x) => x.id === o.id)?.scores).toEqual([
167
321
  { key: "match", pass: true },
168
322
  ]);
169
- const found = await store.findReusableOutput("h", new Date(0));
323
+ const found = await store.findReusableOutput(n("h"), new Date(0));
170
324
  expect(found?.id).toBe(o.id);
171
325
  expect(found?.output).toEqual({ text: "HELLO" });
172
- expect(await store.findReusableOutput("h", new Date(Date.now() + 60_000))).toBeNull();
326
+ expect(await store.findReusableOutput(n("h"), new Date(Date.now() + 60_000))).toBeNull();
173
327
  });
174
328
  it("lists several tests' outputs and reusable hashes in one call, where it can", async () => {
175
329
  const store = await make();
176
- const c = await store.createCase(newCase("s"));
330
+ const n = names();
331
+ const c = await store.createCase(newCase(n("s")));
177
332
  const [r1, r2, r3] = await Promise.all([
178
- store.createRun(newRun("s")),
179
- store.createRun(newRun("s")),
180
- store.createRun(newRun("s")),
333
+ store.createRun(newRun(n("s"))),
334
+ store.createRun(newRun(n("s"))),
335
+ store.createRun(newRun(n("s"))),
181
336
  ]);
182
337
  const base = {
183
338
  caseId: c.id,
@@ -189,40 +344,41 @@ export function describeStoreContract(name, make) {
189
344
  ms: 12,
190
345
  reused: false,
191
346
  };
192
- await store.createOutput({ ...base, runId: r1.id, requestHash: "a" });
193
- await store.createOutput({ ...base, runId: r2.id, requestHash: "b" });
347
+ await store.createOutput({ ...base, runId: r1.id, requestHash: n("a") });
348
+ await store.createOutput({ ...base, runId: r2.id, requestHash: n("b") });
194
349
  await store.createOutput({
195
350
  ...base,
196
351
  runId: r2.id,
197
- requestHash: "c",
352
+ requestHash: n("c"),
198
353
  reused: true,
199
354
  });
200
355
  await store.createOutput({
201
356
  ...base,
202
357
  runId: r3.id,
203
- requestHash: "d",
358
+ requestHash: n("d"),
204
359
  error: "boom",
205
360
  output: null,
206
361
  });
207
362
  if (store.listOutputsFor) {
208
363
  const outs = await store.listOutputsFor([r1.id, r2.id]);
209
- expect(outs.map((o) => o.requestHash).sort()).toEqual(["a", "b", "c"]);
364
+ expect(outs.map((o) => o.requestHash).sort()).toEqual([n("a"), n("b"), n("c")].sort());
210
365
  expect(await store.listOutputsFor([])).toEqual([]);
211
366
  }
212
367
  if (store.findReusableHashes) {
213
368
  expect([
214
- ...(await store.findReusableHashes(["a", "b", "c", "d", "e"], new Date(0))),
215
- ].sort()).toEqual(["a", "b"]);
216
- expect((await store.findReusableHashes(["a"], new Date(Date.now() + 60_000)))
217
- .size).toBe(0);
369
+ ...(await store.findReusableHashes(["a", "b", "c", "d", "e"].map(n), new Date(0))),
370
+ ].sort()).toEqual([n("a"), n("b")].sort());
371
+ expect((await store.findReusableHashes([n("a")], new Date(Date.now() + 60_000))).size).toBe(0);
218
372
  expect((await store.findReusableHashes([], new Date(0))).size).toBe(0);
219
373
  }
220
374
  });
221
375
  it("runs a whole test through the runner", async () => {
222
376
  const store = await make();
377
+ const n = names();
378
+ const key = n("contract");
223
379
  const echo = {
224
- key: "contract",
225
- operation: "contract",
380
+ key,
381
+ operation: key,
226
382
  priority: { favor: "quality" },
227
383
  label: "Contract",
228
384
  description: "Uppercases text.",
@@ -245,17 +401,14 @@ export function describeStoreContract(name, make) {
245
401
  inputFromForm: () => ({ text: "" }),
246
402
  title: (i) => i.text,
247
403
  };
248
- await store.createCase(newCase("contract"));
404
+ await store.createCase(newCase(key));
249
405
  const runner = createRunner({
250
406
  store,
251
407
  suites: [echo],
252
408
  models: { "model-a": { label: "Model A", provider: "acme" } },
253
409
  promptVersion: () => "v1",
254
410
  });
255
- const { run } = await runner.createRun({
256
- suite: "contract",
257
- model: "model-a",
258
- });
411
+ const { run } = await runner.createRun({ suite: key, model: "model-a" });
259
412
  await runner.runEval(run.id);
260
413
  const done = await store.getRun(run.id);
261
414
  expect(done?.status).toBe("SUCCEEDED");
@@ -265,11 +418,17 @@ export function describeStoreContract(name, make) {
265
418
  }
266
419
  /**
267
420
  * The contract every FeedbackStore must meet. `make` must return an empty
268
- * store each time it's called.
421
+ * store each time it's called, unless `opts.scope` is set (see
422
+ * `describeStoreContract`): then every feature the contract rates starts
423
+ * with the scope, and its lists ask for those features only.
269
424
  */
270
- export function describeFeedbackStoreContract(name, make) {
271
- const rating = (over = {}) => ({
272
- operation: "triage",
425
+ export function describeFeedbackStoreContract(name, make, opts = {}) {
426
+ const t = testFunctions(opts.test);
427
+ const { describe, it, expect } = t;
428
+ const names = scopeNames(opts.scope);
429
+ const scoped = opts.scope !== undefined;
430
+ const rating = (operation, over = {}) => ({
431
+ operation,
273
432
  targetId: "answer-1",
274
433
  raterId: "person-1",
275
434
  rating: "DOWN",
@@ -280,11 +439,13 @@ export function describeFeedbackStoreContract(name, make) {
280
439
  ...over,
281
440
  });
282
441
  describe(`FeedbackStore contract: ${name}`, () => {
442
+ registerCleanup(t, opts);
283
443
  it("keeps a rating with its reason, input, and output, open", async () => {
284
444
  const store = await make();
285
- const f = await store.rate(rating());
445
+ const op = names()("triage");
446
+ const f = await store.rate(rating(op));
286
447
  expect(f).toMatchObject({
287
- operation: "triage",
448
+ operation: op,
288
449
  rating: "DOWN",
289
450
  reason: "Wrong queue",
290
451
  excerpt: "billing",
@@ -296,31 +457,36 @@ export function describeFeedbackStoreContract(name, make) {
296
457
  });
297
458
  it("keeps one rating per person per answer, and reopens a changed one", async () => {
298
459
  const store = await make();
299
- const first = await store.rate(rating());
460
+ const op = names()("triage");
461
+ const first = await store.rate(rating(op));
300
462
  await store.setFeedbackStatus(first.id, "DISMISSED");
301
- const changed = await store.rate(rating({ rating: "UP" }));
463
+ const changed = await store.rate(rating(op, { rating: "UP" }));
302
464
  expect(changed.id).toBe(first.id);
303
465
  expect(changed.status).toBe("OPEN");
304
466
  expect(changed.reason).toBeNull();
305
- await store.rate(rating({ raterId: "person-2" }));
306
- expect(await store.listFeedback()).toHaveLength(2);
467
+ await store.rate(rating(op, { raterId: "person-2" }));
468
+ expect(await store.listFeedback(scoped ? { operation: op } : {})).toHaveLength(2);
307
469
  });
308
470
  it("takes a rating back", async () => {
309
471
  const store = await make();
310
- await store.rate(rating());
311
- await store.clearRating("person-1", "triage", "answer-1");
312
- expect(await store.listFeedback()).toHaveLength(0);
472
+ const op = names()("triage");
473
+ await store.rate(rating(op));
474
+ await store.clearRating("person-1", op, "answer-1");
475
+ expect(await store.listFeedback(scoped ? { operation: op } : {})).toHaveLength(0);
313
476
  });
314
477
  it("filters by feature, rating, status, and date, newest first", async () => {
315
478
  const store = await make();
316
- const a = await store.rate(rating({ targetId: "a" }));
479
+ const n = names();
480
+ const op = n("triage");
481
+ const mine = scoped ? { operation: op } : {};
482
+ const a = await store.rate(rating(op, { targetId: "a" }));
317
483
  await new Promise((r) => setTimeout(r, 5));
318
- const b = await store.rate(rating({ targetId: "b", rating: "UP" }));
319
- await store.rate(rating({ targetId: "c", operation: "summary" }));
320
- expect((await store.listFeedback({ operation: "triage" })).map((f) => f.id)).toEqual([b.id, a.id]);
321
- expect(await store.listFeedback({ rating: "UP" })).toHaveLength(1);
484
+ const b = await store.rate(rating(op, { targetId: "b", rating: "UP" }));
485
+ await store.rate(rating(n("summary"), { targetId: "c" }));
486
+ expect((await store.listFeedback({ operation: op })).map((f) => f.id)).toEqual([b.id, a.id]);
487
+ expect(await store.listFeedback({ ...mine, rating: "UP" })).toHaveLength(1);
322
488
  await store.setFeedbackStatus(a.id, "CASED", "case-1");
323
- const cased = await store.listFeedback({ status: "CASED" });
489
+ const cased = await store.listFeedback({ ...mine, status: "CASED" });
324
490
  expect(cased.map((f) => [f.id, f.caseId])).toEqual([[a.id, "case-1"]]);
325
491
  expect(await store.listFeedback({ since: new Date(Date.now() + 60_000) })).toHaveLength(0);
326
492
  expect(await store.listFeedback({ limit: 1 })).toHaveLength(1);
@@ -329,9 +495,15 @@ export function describeFeedbackStoreContract(name, make) {
329
495
  }
330
496
  /**
331
497
  * The contract every SettingsStore must meet. `make` must return an empty
332
- * store each time it's called.
498
+ * store each time it's called, unless `opts.scope` is set (see
499
+ * `describeStoreContract`): then every feature the contract versions
500
+ * starts with the scope. `opts.without` names settings its tables have no
501
+ * column for (see `StoreContractOptions`).
333
502
  */
334
- export function describeSettingsStoreContract(name, make) {
503
+ export function describeSettingsStoreContract(name, make, opts = {}) {
504
+ const t = testFunctions(opts.test);
505
+ const { describe, it, expect } = t;
506
+ const names = scopeNames(opts.scope);
335
507
  const settings = (model) => ({
336
508
  model,
337
509
  fallbackModel: null,
@@ -346,29 +518,34 @@ export function describeSettingsStoreContract(name, make) {
346
518
  expectLive,
347
519
  });
348
520
  describe(`SettingsStore contract: ${name}`, () => {
521
+ registerCleanup(t, opts);
349
522
  it("has nothing live until the first switch, then numbers versions", async () => {
350
523
  const store = await make();
351
- expect(await store.liveVersion("triage")).toBeNull();
352
- const v1 = await store.switchTo("triage", create("a", null));
353
- const v2 = await store.switchTo("triage", create("b", v1.id));
524
+ const op = names()("triage");
525
+ expect(await store.liveVersion(op)).toBeNull();
526
+ const v1 = await store.switchTo(op, create("a", null));
527
+ const v2 = await store.switchTo(op, create("b", v1.id));
354
528
  expect([v1.number, v2.number]).toEqual([1, 2]);
355
529
  expect(v2).toMatchObject({
356
- operation: "triage",
530
+ operation: op,
357
531
  model: "b",
358
532
  promptVersion: "p1",
359
533
  });
360
- expect((await store.liveVersion("triage"))?.id).toBe(v2.id);
361
- expect((await store.listVersions("triage")).map((v) => v.number)).toEqual([2, 1]);
534
+ expect((await store.liveVersion(op))?.id).toBe(v2.id);
535
+ expect((await store.listVersions(op)).map((v) => v.number)).toEqual([
536
+ 2, 1,
537
+ ]);
362
538
  });
363
539
  it("logs every switch, newest first, with who, why, and evidence", async () => {
364
540
  const store = await make();
365
- const v1 = await store.switchTo("triage", create("a", null));
366
- await store.switchTo("triage", {
541
+ const op = names()("triage");
542
+ const v1 = await store.switchTo(op, create("a", null));
543
+ await store.switchTo(op, {
367
544
  ...create("b", v1.id),
368
545
  kind: "PROMOTE",
369
546
  evidence: { runId: "r1", verdict: "BETTER" },
370
547
  });
371
- const [latest, first] = await store.listChanges("triage");
548
+ const [latest, first] = await store.listChanges(op);
372
549
  expect(latest).toMatchObject({
373
550
  kind: "PROMOTE",
374
551
  fromVersionId: v1.id,
@@ -377,33 +554,36 @@ export function describeSettingsStoreContract(name, make) {
377
554
  evidence: { runId: "r1", verdict: "BETTER" },
378
555
  });
379
556
  expect(first).toMatchObject({ kind: "CHANGE", fromVersionId: null });
380
- expect(await store.listChanges("triage", { limit: 1 })).toHaveLength(1);
557
+ expect(await store.listChanges(op, { limit: 1 })).toHaveLength(1);
381
558
  });
382
559
  it("makes an earlier version live again without a new one", async () => {
383
560
  const store = await make();
384
- const v1 = await store.switchTo("triage", create("a", null));
385
- const v2 = await store.switchTo("triage", create("b", v1.id));
386
- await store.switchTo("triage", {
561
+ const op = names()("triage");
562
+ const v1 = await store.switchTo(op, create("a", null));
563
+ const v2 = await store.switchTo(op, create("b", v1.id));
564
+ await store.switchTo(op, {
387
565
  versionId: v1.id,
388
566
  kind: "ROLLBACK",
389
567
  reason: "b was worse",
390
568
  by: "person-1",
391
569
  expectLive: v2.id,
392
570
  });
393
- expect((await store.liveVersion("triage"))?.id).toBe(v1.id);
394
- expect(await store.listVersions("triage")).toHaveLength(2);
571
+ expect((await store.liveVersion(op))?.id).toBe(v1.id);
572
+ expect(await store.listVersions(op)).toHaveLength(2);
395
573
  });
396
574
  it("refuses a switch decided against a live version that changed", async () => {
397
575
  const store = await make();
398
- const v1 = await store.switchTo("triage", create("a", null));
399
- await store.switchTo("triage", create("b", v1.id));
400
- await expect(store.switchTo("triage", create("c", v1.id))).rejects.toBeInstanceOf(SettingsConflict);
401
- expect((await store.liveVersion("triage"))?.model).toBe("b");
402
- expect(await store.listVersions("triage")).toHaveLength(2);
576
+ const op = names()("triage");
577
+ const v1 = await store.switchTo(op, create("a", null));
578
+ await store.switchTo(op, create("b", v1.id));
579
+ await expect(store.switchTo(op, create("c", v1.id))).rejects.toBeInstanceOf(SettingsConflict);
580
+ expect((await store.liveVersion(op))?.model).toBe("b");
581
+ expect(await store.listVersions(op)).toHaveLength(2);
403
582
  });
404
583
  it("keeps a version's reasoning setting as named, even a newer one", async () => {
405
584
  const store = await make();
406
- const v1 = await store.switchTo("triage", {
585
+ const op = names()("triage");
586
+ const v1 = await store.switchTo(op, {
407
587
  ...create("a", null),
408
588
  create: {
409
589
  settings: { ...settings("a"), reasoningEffort: "xhigh" },
@@ -411,29 +591,144 @@ export function describeSettingsStoreContract(name, make) {
411
591
  },
412
592
  });
413
593
  expect(v1.reasoningEffort).toBe("xhigh");
414
- expect((await store.liveVersion("triage"))?.reasoningEffort).toBe("xhigh");
594
+ expect((await store.liveVersion(op))?.reasoningEffort).toBe("xhigh");
415
595
  });
416
- it("keeps a version's temperature", async () => {
417
- const store = await make();
418
- const v1 = await store.switchTo("triage", {
419
- ...create("a", null),
420
- create: {
421
- settings: { ...settings("a"), temperature: 0.4 },
422
- promptVersion: "p1",
423
- },
596
+ if (opts.without?.includes("temperature")) {
597
+ it("refuses a temperature it has no column for, and keeps none", async () => {
598
+ const store = await make();
599
+ const op = names()("triage");
600
+ await expect(store.switchTo(op, {
601
+ ...create("a", null),
602
+ create: {
603
+ settings: { ...settings("a"), temperature: 0.4 },
604
+ promptVersion: "p1",
605
+ },
606
+ })).rejects.toThrow("temperature");
607
+ expect(await store.liveVersion(op)).toBeNull();
608
+ const v1 = await store.switchTo(op, create("a", null));
609
+ expect(v1.temperature ?? null).toBeNull();
424
610
  });
425
- expect(v1.temperature).toBe(0.4);
426
- expect((await store.liveVersion("triage"))?.temperature).toBe(0.4);
427
- const v2 = await store.switchTo("triage", create("b", v1.id));
428
- expect(v2.temperature ?? null).toBeNull();
611
+ }
612
+ else {
613
+ it("keeps a version's temperature", async () => {
614
+ const store = await make();
615
+ const op = names()("triage");
616
+ const v1 = await store.switchTo(op, {
617
+ ...create("a", null),
618
+ create: {
619
+ settings: { ...settings("a"), temperature: 0.4 },
620
+ promptVersion: "p1",
621
+ },
622
+ });
623
+ expect(v1.temperature).toBe(0.4);
624
+ expect((await store.liveVersion(op))?.temperature).toBe(0.4);
625
+ const v2 = await store.switchTo(op, create("b", v1.id));
626
+ expect(v2.temperature ?? null).toBeNull();
627
+ });
628
+ }
629
+ it("keeps every kind of change, with its evidence", async () => {
630
+ const store = await make();
631
+ const op = names()("triage");
632
+ let live = (await store.switchTo(op, create("a", null))).id;
633
+ for (const kind of CHANGE_KINDS.slice(1))
634
+ live = (await store.switchTo(op, {
635
+ ...create(kind.toLowerCase(), live),
636
+ kind,
637
+ evidence: kind === "PROMOTE" ? { runId: "r1" } : undefined,
638
+ })).id;
639
+ const changes = await store.listChanges(op);
640
+ expect(changes.map((c) => c.kind)).toEqual([...CHANGE_KINDS].reverse());
641
+ expect(changes.map((c) => c.evidence)).toEqual([
642
+ null,
643
+ null,
644
+ null,
645
+ null,
646
+ { runId: "r1" },
647
+ null,
648
+ ]);
429
649
  });
430
650
  it("keeps each feature's versions and live one apart", async () => {
431
651
  const store = await make();
432
- await store.switchTo("triage", create("a", null));
433
- const other = await store.switchTo("summary", create("x", null));
652
+ const n = names();
653
+ await store.switchTo(n("triage"), create("a", null));
654
+ const other = await store.switchTo(n("summary"), create("x", null));
434
655
  expect(other.number).toBe(1);
435
- expect((await store.liveVersion("triage"))?.model).toBe("a");
656
+ expect((await store.liveVersion(n("triage")))?.model).toBe("a");
436
657
  });
437
658
  });
438
659
  }
660
+ /**
661
+ * The contract every set of suites should meet, so people confirming
662
+ * answers weeks later (and the pages) can read them: unique keys, a label
663
+ * and help for every top-level field of each suite's input and answer,
664
+ * a description for every check, and starter cases that fit the suite's
665
+ * own schemas. One test per suite, listing what's missing in plain words
666
+ * (`suiteContractProblems`).
667
+ *
668
+ * @param name - What the tests are called, e.g. "our suites".
669
+ * @param suites - Every suite the app registers.
670
+ * @param opts - Test functions other than Vitest's.
671
+ *
672
+ * @example
673
+ * ```ts
674
+ * import { describeSuiteContract } from "@crowandraven/evalkeeper/testing";
675
+ * import { SUITES } from "../lib/suites";
676
+ *
677
+ * describeSuiteContract("our suites", SUITES);
678
+ * ```
679
+ */
680
+ export function describeSuiteContract(name, suites, opts = {}) {
681
+ const { describe, it, expect } = testFunctions(opts.test);
682
+ describe(`Suite contract: ${name}`, () => {
683
+ it("has unique keys", () => {
684
+ expect(suiteContractProblems(suites).filter((p) => p.endsWith("another suite has the same key."))).toEqual([]);
685
+ });
686
+ for (const suite of suites)
687
+ it(`${suite.key}: every field, check, and starter can be read`, () => {
688
+ expect(suiteContractProblems([suite]), "What's missing for people to read this suite").toEqual([]);
689
+ });
690
+ });
691
+ }
692
+ /**
693
+ * A read-only check, as a test, that a store mapped onto your own tables
694
+ * reads what's already there: one test per suite that fails listing every
695
+ * case, answer, test, and output that doesn't parse, with counts. It only
696
+ * reads, so it's the check to run first, on a copy of real data. Pass the
697
+ * report from `checkStoreReads` (any store) or `prismaReadCheck` (sees a
698
+ * Prisma table's values before the store fills in defaults).
699
+ *
700
+ * @param name - What the tests are called, e.g. "our answer key".
701
+ * @param check - Makes the report; called once, when the tests run.
702
+ * @param opts - The suite keys to name a test for, and test functions
703
+ * other than Vitest's.
704
+ *
705
+ * @example
706
+ * ```ts
707
+ * import { describeMappedReadCheck } from "@crowandraven/evalkeeper/testing";
708
+ * import { prismaReadCheck } from "@crowandraven/evalkeeper-prisma";
709
+ *
710
+ * describeMappedReadCheck(
711
+ * "our answer key",
712
+ * () => prismaReadCheck(prisma, map, { suites: SUITES }),
713
+ * { suites: SUITES.map((s) => s.key) },
714
+ * );
715
+ * ```
716
+ */
717
+ export function describeMappedReadCheck(name, check, opts) {
718
+ const { describe, it, expect } = testFunctions(opts.test);
719
+ let report = null;
720
+ const once = () => (report ??= check());
721
+ describe(`Read check: ${name}`, () => {
722
+ for (const key of opts.suites)
723
+ it(`${key}: every case, answer, test, and output reads`, async () => {
724
+ const found = (await once()).suites.find((s) => s.suite === key);
725
+ expect(found, `The check found no report for ${key}`).toMatchObject({
726
+ suite: key,
727
+ });
728
+ if (!found)
729
+ return;
730
+ expect(found.problems, readCheckSummary({ suites: [found] }).join("\n")).toEqual([]);
731
+ });
732
+ });
733
+ }
439
734
  //# sourceMappingURL=testing.js.map