@crowandraven/evalkeeper 0.5.0 → 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 +1 -1
  12. package/dist/cli/addPages.js +4 -1
  13. package/dist/cli/addPages.js.map +1 -1
  14. package/dist/cli/main.d.ts +1 -1
  15. package/dist/cli/main.js +4 -3
  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 +127 -11
  59. package/dist/testing.js +378 -104
  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 +4 -1
  72. package/src/cli/main.ts +4 -3
  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 +508 -109
  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/src/testing.ts CHANGED
@@ -1,25 +1,144 @@
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 type { ContractExpect } from "./assertExpect.js";
10
+ import { BLIND_RATER, blindRating, nextToRate, skipMark } from "./blind.js";
8
11
  import type { FeedbackStore, NewRating } from "./feedback.js";
12
+ import { confirmedLabel } from "./labels.js";
9
13
  import { createRunner } from "./runner.js";
10
14
  import {
15
+ CHANGE_KINDS,
11
16
  SettingsConflict,
12
17
  type Settings,
13
18
  type SettingsStore,
14
19
  } from "./settings.js";
15
20
  import type { EvalStore, NewCase } from "./store.js";
16
- import type { Suite } from "./types.js";
21
+ import { suiteContractProblems } from "./suiteContract.js";
22
+ import type { AnySuite, Suite } from "./types.js";
23
+ import { readCheckSummary, type ReadCheckReport } from "./readCheck.js";
24
+
25
+ export {
26
+ assertExpect,
27
+ type ContractExpect,
28
+ type ContractMatchers,
29
+ } from "./assertExpect.js";
30
+
31
+ /**
32
+ * The test functions a contract registers its tests with. Vitest's
33
+ * `describe`, `it`, `expect`, and `afterAll` fit, and so do `node:test`'s
34
+ * `describe`, `it`, and `after` with `assertExpect`.
35
+ */
36
+ export type ContractTest = {
37
+ /** Groups tests, like Vitest's or node:test's `describe`. */
38
+ describe: (name: string, fn: () => void) => unknown;
39
+ /** Adds a test, like Vitest's or node:test's `it`. */
40
+ it: (name: string, fn: () => Promise<void> | void) => unknown;
41
+ /** Checks values: Vitest's `expect`, or `assertExpect` on node:assert. */
42
+ expect: ContractExpect;
43
+ /**
44
+ * Runs once after a group's tests, like Vitest's `afterAll` or
45
+ * node:test's `after`. Needed only with `cleanup`.
46
+ */
47
+ afterAll?: (fn: () => Promise<void> | void) => unknown;
48
+ };
49
+
50
+ /**
51
+ * Vitest's test functions, or why they couldn't be loaded. A dynamic
52
+ * import (awaited as this module loads), so this module loads without
53
+ * Vitest when you pass your own test functions.
54
+ */
55
+ const vitest: ContractTest | Error = await import("vitest").then(
56
+ (v) => ({
57
+ describe: v.describe,
58
+ it: v.it,
59
+ expect: v.expect,
60
+ afterAll: v.afterAll,
61
+ }),
62
+ (e: unknown) => (e instanceof Error ? e : new Error(String(e))),
63
+ );
64
+
65
+ /** The test functions to register with: the ones given, else Vitest's. */
66
+ function testFunctions(given: ContractTest | undefined): ContractTest {
67
+ if (given) return given;
68
+ if (!(vitest instanceof Error)) return vitest;
69
+ throw new Error(
70
+ `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.`,
71
+ );
72
+ }
73
+
74
+ /** Options every contract takes. */
75
+ export type ContractOptions = {
76
+ /** The test functions to use. Vitest's by default. */
77
+ test?: ContractTest;
78
+ };
79
+
80
+ /**
81
+ * Options for running a store contract on a database that holds other
82
+ * rows too, such as a shared development database.
83
+ */
84
+ export type ScopedContractOptions = ContractOptions & {
85
+ /**
86
+ * A prefix for every suite and feature the contract writes (each test
87
+ * adds its own after it), so its rows never mix with others and `make`
88
+ * needn't return an empty store. Without it, `make` must return an
89
+ * empty store every time.
90
+ */
91
+ scope?: string;
92
+ /**
93
+ * Deletes the rows whose suite or feature starts with the scope, once
94
+ * after the contract's tests (and so also any left by an earlier run
95
+ * that stopped early). Needs `scope`, and `afterAll` among the test
96
+ * functions. For Prisma, `deleteScopedRows` from
97
+ * `@crowandraven/evalkeeper-prisma`.
98
+ */
99
+ cleanup?: (scope: string) => Promise<unknown>;
100
+ };
101
+
102
+ /**
103
+ * A namer for each test: in a scoped contract, a fresh prefix per test
104
+ * (so tests don't see each other's rows); otherwise names as they are.
105
+ */
106
+ function scopeNames(scope: string | undefined): () => (name: string) => string {
107
+ if (scope === undefined) return () => (name) => name;
108
+ if (!scope.trim())
109
+ throw new Error(
110
+ 'A contract\'s scope must be a prefix with some text in it, such as "contract-": an empty one would match every row.',
111
+ );
112
+ const run = Date.now().toString(36);
113
+ let n = 0;
114
+ return () => {
115
+ const prefix = `${scope}${run}-${(n++).toString(36)}-`;
116
+ return (name) => prefix + name;
117
+ };
118
+ }
119
+
120
+ /** Registers a scoped contract's cleanup, after checking it can run. */
121
+ function registerCleanup(t: ContractTest, opts: ScopedContractOptions) {
122
+ const { cleanup, scope } = opts;
123
+ if (!cleanup) return;
124
+ if (scope === undefined)
125
+ throw new Error(
126
+ "cleanup needs a scope: it deletes only the rows the scope names. Without a scope, return an empty store from make instead.",
127
+ );
128
+ if (!t.afterAll)
129
+ throw new Error(
130
+ "cleanup runs after the contract's tests, so pass afterAll (node:test's after) with your test functions.",
131
+ );
132
+ t.afterAll(async () => {
133
+ await cleanup(scope);
134
+ });
135
+ }
17
136
 
18
137
  /**
19
138
  * Options for a store contract, for a store on tables that lack an
20
139
  * optional column.
21
140
  */
22
- export type StoreContractOptions = {
141
+ export type StoreContractOptions = ScopedContractOptions & {
23
142
  /**
24
143
  * Settings the store has no column for. The contract then checks the
25
144
  * store refuses a value for them (rather than losing it) and reads
@@ -29,16 +148,28 @@ export type StoreContractOptions = {
29
148
  };
30
149
 
31
150
  /**
32
- * The contract every EvalStore must meet, as Vitest tests. Run it against
33
- * your store to know the runner will work on it. `make` must return an
34
- * empty store each time it's called; `opts.without` names run settings
35
- * its tables have no column for.
151
+ * The contract every EvalStore must meet. Run it against your store to
152
+ * know the runner will work on it. `make` must return an empty store each
153
+ * time it's called, unless `opts.scope` is set: then every suite the
154
+ * contract writes (and every request hash it picks) starts with the
155
+ * scope, the tests never look past their own rows, and `opts.cleanup`
156
+ * deletes those suites' cases, answers, tests, and outputs afterward, so
157
+ * it can run on a database that holds other rows. `opts.without` names
158
+ * run settings its tables have no column for; `opts.test` passes test
159
+ * functions other than Vitest's.
36
160
  *
37
161
  * @example
38
162
  * ```ts
39
163
  * import { describeStoreContract } from "@crowandraven/evalkeeper/testing";
40
164
  *
41
165
  * describeStoreContract("my store", () => myStore(freshDatabase()));
166
+ *
167
+ * // On a database with other rows: only rows starting "contract-" are
168
+ * // written, and cleanup deletes only those.
169
+ * describeStoreContract("our tables", () => prismaStore(prisma, map), {
170
+ * scope: "contract-",
171
+ * cleanup: (scope) => deleteScopedRows(prisma, scope, { map }),
172
+ * });
42
173
  * ```
43
174
  */
44
175
  export function describeStoreContract(
@@ -46,6 +177,9 @@ export function describeStoreContract(
46
177
  make: () => EvalStore | Promise<EvalStore>,
47
178
  opts: StoreContractOptions = {},
48
179
  ) {
180
+ const t = testFunctions(opts.test);
181
+ const { describe, it, expect } = t;
182
+ const names = scopeNames(opts.scope);
49
183
  const newCase = (suite: string, over: Partial<NewCase> = {}): NewCase => ({
50
184
  suite,
51
185
  input: { text: "hello", nested: { n: 1 } },
@@ -81,10 +215,13 @@ export function describeStoreContract(
81
215
  });
82
216
 
83
217
  describe(`EvalStore contract: ${name}`, () => {
218
+ registerCleanup(t, opts);
219
+
84
220
  it("keeps a case's input, tags, and answers as given", async () => {
85
221
  const store = await make();
86
- const c = await store.createCase(newCase("s"));
87
- const [listed] = await store.listCases("s");
222
+ const n = names();
223
+ const c = await store.createCase(newCase(n("s")));
224
+ const [listed] = await store.listCases(n("s"));
88
225
  expect(listed?.id).toBe(c.id);
89
226
  expect(listed?.input).toEqual({ text: "hello", nested: { n: 1 } });
90
227
  expect(listed?.tags).toEqual(["a", "b"]);
@@ -96,27 +233,62 @@ export function describeStoreContract(
96
233
  });
97
234
  });
98
235
 
236
+ it("keeps where a case came from and when, retired ones too", async () => {
237
+ // Drafts from activity and imports skip what they made before by
238
+ // source and sourceRef, so both must read back as written.
239
+ const store = await make();
240
+ const n = names();
241
+ const before = Date.now();
242
+ const c = await store.createCase(
243
+ newCase(n("s"), {
244
+ status: "DRAFT",
245
+ source: "ACTIVITY",
246
+ sourceRef: "answer-42",
247
+ note: "Flagged by an admin.",
248
+ labels: [],
249
+ }),
250
+ );
251
+ await store.setCaseStatus(c.id, "RETIRED");
252
+ const [listed] = await store.listCases(n("s"), {
253
+ includeRetired: true,
254
+ });
255
+ expect(listed).toMatchObject({
256
+ status: "RETIRED",
257
+ source: "ACTIVITY",
258
+ sourceRef: "answer-42",
259
+ note: "Flagged by an admin.",
260
+ labels: [],
261
+ });
262
+ // Within a second either way: some databases round to the second.
263
+ expect(+(listed?.createdAt ?? 0)).toBeGreaterThanOrEqual(before - 1000);
264
+ expect(+(listed?.createdAt ?? 0)).toBeLessThanOrEqual(Date.now() + 1000);
265
+ });
266
+
99
267
  it("lists a suite's cases oldest first, leaving out retired ones", async () => {
100
268
  const store = await make();
101
- const first = await store.createCase(newCase("s"));
269
+ const n = names();
270
+ const first = await store.createCase(newCase(n("s")));
102
271
  // Apart in time: two cases made in the same millisecond have no
103
272
  // oldest one.
104
273
  await new Promise((r) => setTimeout(r, 5));
105
- const second = await store.createCase(newCase("s"));
106
- await store.createCase(newCase("other"));
274
+ const second = await store.createCase(newCase(n("s")));
275
+ await store.createCase(newCase(n("other")));
107
276
  await store.setCaseStatus(first.id, "RETIRED");
108
- expect((await store.listCases("s")).map((c) => c.id)).toEqual([
277
+ expect((await store.listCases(n("s"))).map((c) => c.id)).toEqual([
109
278
  second.id,
110
279
  ]);
111
280
  // On request, retired ones too, still oldest first.
112
281
  expect(
113
- (await store.listCases("s", { includeRetired: true })).map((c) => c.id),
282
+ (await store.listCases(n("s"), { includeRetired: true })).map(
283
+ (c) => c.id,
284
+ ),
114
285
  ).toEqual([first.id, second.id]);
115
286
  });
116
287
 
117
288
  it("adds answers without overwriting, and changes their status", async () => {
118
289
  const store = await make();
119
- const c = await store.createCase(newCase("s", { labels: [] }));
290
+ const n = names();
291
+ const c = await store.createCase(newCase(n("s"), { labels: [] }));
120
292
  const l = await store.addLabel(c.id, {
121
293
  kind: "EXPECTED",
122
294
  status: "PENDING",
@@ -126,27 +298,75 @@ export function describeStoreContract(
126
298
  note: null,
127
299
  });
128
300
  await store.setLabelStatus(l.id, "CONFIRMED");
129
- const [listed] = await store.listCases("s");
301
+ const [listed] = await store.listCases(n("s"));
130
302
  expect(listed?.labels).toHaveLength(1);
131
303
  expect(listed?.labels[0]?.status).toBe("CONFIRMED");
132
304
  });
133
305
 
306
+ it("keeps each rater's blind rating and skip beside others' answers", async () => {
307
+ const store = await make();
308
+ const n = names();
309
+ const c = await store.createCase(newCase(n("s")));
310
+ const before = (await store.listCases(n("s")))[0]?.updatedAt;
311
+ // Apart in time, so a skip that touched the case would show.
312
+ await new Promise((r) => setTimeout(r, 5));
313
+ await store.addLabel(c.id, skipMark("rater-1"));
314
+ const [skipped] = await store.listCases(n("s"));
315
+ expect(skipped?.updatedAt).toEqual(before);
316
+ expect(skipped?.labels.find((l) => l.status === "SKIPPED")).toMatchObject(
317
+ { value: null, raterId: "rater-1", raterRole: BLIND_RATER },
318
+ );
319
+ // The skip is never graded against: the owner's answer stays in use.
320
+ expect(confirmedLabel(skipped?.labels ?? [])?.value).toEqual({
321
+ want: "HELLO",
322
+ });
323
+ expect(nextToRate(await store.listCases(n("s")), "rater-1")).toBeNull();
324
+ expect(nextToRate(await store.listCases(n("s")), "rater-2")?.id).toBe(
325
+ c.id,
326
+ );
327
+
328
+ await store.addLabel(
329
+ c.id,
330
+ blindRating({
331
+ raterId: "rater-2",
332
+ value: { want: "HI" },
333
+ reason: "It greets",
334
+ }),
335
+ );
336
+ const [rated] = await store.listCases(n("s"));
337
+ expect(rated?.labels).toHaveLength(3);
338
+ expect(rated?.labels.find((l) => l.raterId === "rater-2")).toMatchObject({
339
+ status: "CONFIRMED",
340
+ value: { want: "HI" },
341
+ note: "It greets",
342
+ });
343
+ // The owner's answer is still there, unchanged.
344
+ expect(rated?.labels.find((l) => l.raterRole === "OWNER")).toMatchObject({
345
+ status: "CONFIRMED",
346
+ value: { want: "HELLO" },
347
+ });
348
+ expect(nextToRate(await store.listCases(n("s")), "rater-2")).toBeNull();
349
+ });
350
+
134
351
  it("starts runs as running, lists them newest first, and filters", async () => {
135
352
  const store = await make();
136
- const a = await store.createRun(newRun("s"));
353
+ const n = names();
354
+ const a = await store.createRun(newRun(n("s")));
137
355
  await new Promise((r) => setTimeout(r, 5));
138
- const b = await store.createRun(newRun("s"));
356
+ const b = await store.createRun(newRun(n("s")));
139
357
  expect(a.status).toBe("RUNNING");
140
- expect((await store.listRuns("s")).map((r) => r.id)).toEqual([
358
+ expect((await store.listRuns(n("s"))).map((r) => r.id)).toEqual([
141
359
  b.id,
142
360
  a.id,
143
361
  ]);
144
- expect(await store.listRuns("s", { limit: 1 })).toHaveLength(1);
362
+ expect(await store.listRuns(n("s"), { limit: 1 })).toHaveLength(1);
145
363
  await store.updateRun(a.id, { status: "SUCCEEDED" });
146
364
  expect(
147
- (await store.listRuns("s", { status: "SUCCEEDED" })).map((r) => r.id),
365
+ (await store.listRuns(n("s"), { status: "SUCCEEDED" })).map(
366
+ (r) => r.id,
367
+ ),
148
368
  ).toEqual([a.id]);
149
- expect(await store.getRun("missing")).toBeNull();
369
+ expect(await store.getRun(n("missing"))).toBeNull();
150
370
  });
151
371
 
152
372
  const runSettings = [
@@ -157,18 +377,29 @@ export function describeStoreContract(
157
377
  if (opts.without?.includes(field)) {
158
378
  it(`refuses a ${words} it has no column for, and keeps none`, async () => {
159
379
  const store = await make();
380
+ const n = names();
160
381
  await expect(
161
- store.createRun({ ...newRun("s"), [field]: value }),
382
+ store.createRun({ ...newRun(n("s")), [field]: value }),
162
383
  ).rejects.toThrow(field);
163
- const none = await store.createRun({ ...newRun("s"), [field]: null });
384
+ const none = await store.createRun({
385
+ ...newRun(n("s")),
386
+ [field]: null,
387
+ });
164
388
  expect((await store.getRun(none.id))?.[field] ?? null).toBeNull();
165
389
  });
166
390
  continue;
167
391
  }
168
392
  it(`keeps the ${words} a run was tested at`, async () => {
169
393
  const store = await make();
170
- const set = await store.createRun({ ...newRun("s"), [field]: value });
171
- const none = await store.createRun({ ...newRun("s"), [field]: null });
394
+ const n = names();
395
+ const set = await store.createRun({
396
+ ...newRun(n("s")),
397
+ [field]: value,
398
+ });
399
+ const none = await store.createRun({
400
+ ...newRun(n("s")),
401
+ [field]: null,
402
+ });
172
403
  expect((await store.getRun(set.id))?.[field]).toBe(value);
173
404
  expect((await store.getRun(none.id))?.[field] ?? null).toBeNull();
174
405
  });
@@ -176,7 +407,8 @@ export function describeStoreContract(
176
407
 
177
408
  it("updates a run only while it has the status it's guarded by", async () => {
178
409
  const store = await make();
179
- const r = await store.createRun(newRun("s"));
410
+ const n = names();
411
+ const r = await store.createRun(newRun(n("s")));
180
412
  await store.updateRun(r.id, { status: "FAILED" }, { status: "RUNNING" });
181
413
  await store.updateRun(
182
414
  r.id,
@@ -188,13 +420,14 @@ export function describeStoreContract(
188
420
 
189
421
  it("stores outputs and scores, and finds only originals to reuse", async () => {
190
422
  const store = await make();
191
- const c = await store.createCase(newCase("s"));
192
- const r = await store.createRun(newRun("s"));
423
+ const n = names();
424
+ const c = await store.createCase(newCase(n("s")));
425
+ const r = await store.createRun(newRun(n("s")));
193
426
  const base = {
194
427
  runId: r.id,
195
428
  caseId: c.id,
196
429
  repeat: 1,
197
- requestHash: "h",
430
+ requestHash: n("h"),
198
431
  output: { text: "HELLO" },
199
432
  error: null,
200
433
  scores: null,
@@ -211,21 +444,22 @@ export function describeStoreContract(
211
444
  expect(outs.find((x) => x.id === o.id)?.scores).toEqual([
212
445
  { key: "match", pass: true },
213
446
  ]);
214
- const found = await store.findReusableOutput("h", new Date(0));
447
+ const found = await store.findReusableOutput(n("h"), new Date(0));
215
448
  expect(found?.id).toBe(o.id);
216
449
  expect(found?.output).toEqual({ text: "HELLO" });
217
450
  expect(
218
- await store.findReusableOutput("h", new Date(Date.now() + 60_000)),
451
+ await store.findReusableOutput(n("h"), new Date(Date.now() + 60_000)),
219
452
  ).toBeNull();
220
453
  });
221
454
 
222
455
  it("lists several tests' outputs and reusable hashes in one call, where it can", async () => {
223
456
  const store = await make();
224
- const c = await store.createCase(newCase("s"));
457
+ const n = names();
458
+ const c = await store.createCase(newCase(n("s")));
225
459
  const [r1, r2, r3] = await Promise.all([
226
- store.createRun(newRun("s")),
227
- store.createRun(newRun("s")),
228
- store.createRun(newRun("s")),
460
+ store.createRun(newRun(n("s"))),
461
+ store.createRun(newRun(n("s"))),
462
+ store.createRun(newRun(n("s"))),
229
463
  ]);
230
464
  const base = {
231
465
  caseId: c.id,
@@ -237,38 +471,44 @@ export function describeStoreContract(
237
471
  ms: 12,
238
472
  reused: false,
239
473
  };
240
- await store.createOutput({ ...base, runId: r1.id, requestHash: "a" });
241
- await store.createOutput({ ...base, runId: r2.id, requestHash: "b" });
474
+ await store.createOutput({ ...base, runId: r1.id, requestHash: n("a") });
475
+ await store.createOutput({ ...base, runId: r2.id, requestHash: n("b") });
242
476
  await store.createOutput({
243
477
  ...base,
244
478
  runId: r2.id,
245
- requestHash: "c",
479
+ requestHash: n("c"),
246
480
  reused: true,
247
481
  });
248
482
  await store.createOutput({
249
483
  ...base,
250
484
  runId: r3.id,
251
- requestHash: "d",
485
+ requestHash: n("d"),
252
486
  error: "boom",
253
487
  output: null,
254
488
  });
255
489
  if (store.listOutputsFor) {
256
490
  const outs = await store.listOutputsFor([r1.id, r2.id]);
257
- expect(outs.map((o) => o.requestHash).sort()).toEqual(["a", "b", "c"]);
491
+ expect(outs.map((o) => o.requestHash).sort()).toEqual(
492
+ [n("a"), n("b"), n("c")].sort(),
493
+ );
258
494
  expect(await store.listOutputsFor([])).toEqual([]);
259
495
  }
260
496
  if (store.findReusableHashes) {
261
497
  expect(
262
498
  [
263
499
  ...(await store.findReusableHashes(
264
- ["a", "b", "c", "d", "e"],
500
+ ["a", "b", "c", "d", "e"].map(n),
265
501
  new Date(0),
266
502
  )),
267
503
  ].sort(),
268
- ).toEqual(["a", "b"]);
504
+ ).toEqual([n("a"), n("b")].sort());
269
505
  expect(
270
- (await store.findReusableHashes(["a"], new Date(Date.now() + 60_000)))
271
- .size,
506
+ (
507
+ await store.findReusableHashes(
508
+ [n("a")],
509
+ new Date(Date.now() + 60_000),
510
+ )
511
+ ).size,
272
512
  ).toBe(0);
273
513
  expect((await store.findReusableHashes([], new Date(0))).size).toBe(0);
274
514
  }
@@ -276,10 +516,12 @@ export function describeStoreContract(
276
516
 
277
517
  it("runs a whole test through the runner", async () => {
278
518
  const store = await make();
519
+ const n = names();
520
+ const key = n("contract");
279
521
  const echo: Suite<{ text: string }, { text: string }, { want: string }> =
280
522
  {
281
- key: "contract",
282
- operation: "contract",
523
+ key,
524
+ operation: key,
283
525
  priority: { favor: "quality" },
284
526
  label: "Contract",
285
527
  description: "Uppercases text.",
@@ -302,17 +544,14 @@ export function describeStoreContract(
302
544
  inputFromForm: () => ({ text: "" }),
303
545
  title: (i) => i.text,
304
546
  };
305
- await store.createCase(newCase("contract"));
547
+ await store.createCase(newCase(key));
306
548
  const runner = createRunner({
307
549
  store,
308
550
  suites: [echo],
309
551
  models: { "model-a": { label: "Model A", provider: "acme" } },
310
552
  promptVersion: () => "v1",
311
553
  });
312
- const { run } = await runner.createRun({
313
- suite: "contract",
314
- model: "model-a",
315
- });
554
+ const { run } = await runner.createRun({ suite: key, model: "model-a" });
316
555
  await runner.runEval(run.id);
317
556
  const done = await store.getRun(run.id);
318
557
  expect(done?.status).toBe("SUCCEEDED");
@@ -323,14 +562,24 @@ export function describeStoreContract(
323
562
 
324
563
  /**
325
564
  * The contract every FeedbackStore must meet. `make` must return an empty
326
- * store each time it's called.
565
+ * store each time it's called, unless `opts.scope` is set (see
566
+ * `describeStoreContract`): then every feature the contract rates starts
567
+ * with the scope, and its lists ask for those features only.
327
568
  */
328
569
  export function describeFeedbackStoreContract(
329
570
  name: string,
330
571
  make: () => FeedbackStore | Promise<FeedbackStore>,
572
+ opts: ScopedContractOptions = {},
331
573
  ) {
332
- const rating = (over: Partial<NewRating> = {}): NewRating => ({
333
- operation: "triage",
574
+ const t = testFunctions(opts.test);
575
+ const { describe, it, expect } = t;
576
+ const names = scopeNames(opts.scope);
577
+ const scoped = opts.scope !== undefined;
578
+ const rating = (
579
+ operation: string,
580
+ over: Partial<NewRating> = {},
581
+ ): NewRating => ({
582
+ operation,
334
583
  targetId: "answer-1",
335
584
  raterId: "person-1",
336
585
  rating: "DOWN",
@@ -342,11 +591,14 @@ export function describeFeedbackStoreContract(
342
591
  });
343
592
 
344
593
  describe(`FeedbackStore contract: ${name}`, () => {
594
+ registerCleanup(t, opts);
595
+
345
596
  it("keeps a rating with its reason, input, and output, open", async () => {
346
597
  const store = await make();
347
- const f = await store.rate(rating());
598
+ const op = names()("triage");
599
+ const f = await store.rate(rating(op));
348
600
  expect(f).toMatchObject({
349
- operation: "triage",
601
+ operation: op,
350
602
  rating: "DOWN",
351
603
  reason: "Wrong queue",
352
604
  excerpt: "billing",
@@ -359,35 +611,46 @@ export function describeFeedbackStoreContract(
359
611
 
360
612
  it("keeps one rating per person per answer, and reopens a changed one", async () => {
361
613
  const store = await make();
362
- const first = await store.rate(rating());
614
+ const op = names()("triage");
615
+ const first = await store.rate(rating(op));
363
616
  await store.setFeedbackStatus(first.id, "DISMISSED");
364
- const changed = await store.rate(rating({ rating: "UP" }));
617
+ const changed = await store.rate(rating(op, { rating: "UP" }));
365
618
  expect(changed.id).toBe(first.id);
366
619
  expect(changed.status).toBe("OPEN");
367
620
  expect(changed.reason).toBeNull();
368
- await store.rate(rating({ raterId: "person-2" }));
369
- expect(await store.listFeedback()).toHaveLength(2);
621
+ await store.rate(rating(op, { raterId: "person-2" }));
622
+ expect(
623
+ await store.listFeedback(scoped ? { operation: op } : {}),
624
+ ).toHaveLength(2);
370
625
  });
371
626
 
372
627
  it("takes a rating back", async () => {
373
628
  const store = await make();
374
- await store.rate(rating());
375
- await store.clearRating("person-1", "triage", "answer-1");
376
- expect(await store.listFeedback()).toHaveLength(0);
629
+ const op = names()("triage");
630
+ await store.rate(rating(op));
631
+ await store.clearRating("person-1", op, "answer-1");
632
+ expect(
633
+ await store.listFeedback(scoped ? { operation: op } : {}),
634
+ ).toHaveLength(0);
377
635
  });
378
636
 
379
637
  it("filters by feature, rating, status, and date, newest first", async () => {
380
638
  const store = await make();
381
- const a = await store.rate(rating({ targetId: "a" }));
639
+ const n = names();
640
+ const op = n("triage");
641
+ const mine = scoped ? { operation: op } : {};
642
+ const a = await store.rate(rating(op, { targetId: "a" }));
382
643
  await new Promise((r) => setTimeout(r, 5));
383
- const b = await store.rate(rating({ targetId: "b", rating: "UP" }));
384
- await store.rate(rating({ targetId: "c", operation: "summary" }));
644
+ const b = await store.rate(rating(op, { targetId: "b", rating: "UP" }));
645
+ await store.rate(rating(n("summary"), { targetId: "c" }));
385
646
  expect(
386
- (await store.listFeedback({ operation: "triage" })).map((f) => f.id),
647
+ (await store.listFeedback({ operation: op })).map((f) => f.id),
387
648
  ).toEqual([b.id, a.id]);
388
- expect(await store.listFeedback({ rating: "UP" })).toHaveLength(1);
649
+ expect(await store.listFeedback({ ...mine, rating: "UP" })).toHaveLength(
650
+ 1,
651
+ );
389
652
  await store.setFeedbackStatus(a.id, "CASED", "case-1");
390
- const cased = await store.listFeedback({ status: "CASED" });
653
+ const cased = await store.listFeedback({ ...mine, status: "CASED" });
391
654
  expect(cased.map((f) => [f.id, f.caseId])).toEqual([[a.id, "case-1"]]);
392
655
  expect(
393
656
  await store.listFeedback({ since: new Date(Date.now() + 60_000) }),
@@ -397,16 +660,27 @@ export function describeFeedbackStoreContract(
397
660
  });
398
661
  }
399
662
 
663
+ /** Options for the settings store contract. */
664
+ export type SettingsStoreContractOptions = ScopedContractOptions & {
665
+ /** Settings the store has no column for (see `StoreContractOptions`). */
666
+ without?: "temperature"[];
667
+ };
668
+
400
669
  /**
401
670
  * The contract every SettingsStore must meet. `make` must return an empty
402
- * store each time it's called; `opts.without` names settings its tables
403
- * have no column for (see `StoreContractOptions`).
671
+ * store each time it's called, unless `opts.scope` is set (see
672
+ * `describeStoreContract`): then every feature the contract versions
673
+ * starts with the scope. `opts.without` names settings its tables have no
674
+ * column for (see `StoreContractOptions`).
404
675
  */
405
676
  export function describeSettingsStoreContract(
406
677
  name: string,
407
678
  make: () => SettingsStore | Promise<SettingsStore>,
408
- opts: { without?: "temperature"[] } = {},
679
+ opts: SettingsStoreContractOptions = {},
409
680
  ) {
681
+ const t = testFunctions(opts.test);
682
+ const { describe, it, expect } = t;
683
+ const names = scopeNames(opts.scope);
410
684
  const settings = (model: string): Settings => ({
411
685
  model,
412
686
  fallbackModel: null,
@@ -422,32 +696,36 @@ export function describeSettingsStoreContract(
422
696
  });
423
697
 
424
698
  describe(`SettingsStore contract: ${name}`, () => {
699
+ registerCleanup(t, opts);
700
+
425
701
  it("has nothing live until the first switch, then numbers versions", async () => {
426
702
  const store = await make();
427
- expect(await store.liveVersion("triage")).toBeNull();
428
- const v1 = await store.switchTo("triage", create("a", null));
429
- const v2 = await store.switchTo("triage", create("b", v1.id));
703
+ const op = names()("triage");
704
+ expect(await store.liveVersion(op)).toBeNull();
705
+ const v1 = await store.switchTo(op, create("a", null));
706
+ const v2 = await store.switchTo(op, create("b", v1.id));
430
707
  expect([v1.number, v2.number]).toEqual([1, 2]);
431
708
  expect(v2).toMatchObject({
432
- operation: "triage",
709
+ operation: op,
433
710
  model: "b",
434
711
  promptVersion: "p1",
435
712
  });
436
- expect((await store.liveVersion("triage"))?.id).toBe(v2.id);
437
- expect((await store.listVersions("triage")).map((v) => v.number)).toEqual(
438
- [2, 1],
439
- );
713
+ expect((await store.liveVersion(op))?.id).toBe(v2.id);
714
+ expect((await store.listVersions(op)).map((v) => v.number)).toEqual([
715
+ 2, 1,
716
+ ]);
440
717
  });
441
718
 
442
719
  it("logs every switch, newest first, with who, why, and evidence", async () => {
443
720
  const store = await make();
444
- const v1 = await store.switchTo("triage", create("a", null));
445
- await store.switchTo("triage", {
721
+ const op = names()("triage");
722
+ const v1 = await store.switchTo(op, create("a", null));
723
+ await store.switchTo(op, {
446
724
  ...create("b", v1.id),
447
725
  kind: "PROMOTE",
448
726
  evidence: { runId: "r1", verdict: "BETTER" },
449
727
  });
450
- const [latest, first] = await store.listChanges("triage");
728
+ const [latest, first] = await store.listChanges(op);
451
729
  expect(latest).toMatchObject({
452
730
  kind: "PROMOTE",
453
731
  fromVersionId: v1.id,
@@ -456,38 +734,41 @@ export function describeSettingsStoreContract(
456
734
  evidence: { runId: "r1", verdict: "BETTER" },
457
735
  });
458
736
  expect(first).toMatchObject({ kind: "CHANGE", fromVersionId: null });
459
- expect(await store.listChanges("triage", { limit: 1 })).toHaveLength(1);
737
+ expect(await store.listChanges(op, { limit: 1 })).toHaveLength(1);
460
738
  });
461
739
 
462
740
  it("makes an earlier version live again without a new one", async () => {
463
741
  const store = await make();
464
- const v1 = await store.switchTo("triage", create("a", null));
465
- const v2 = await store.switchTo("triage", create("b", v1.id));
466
- await store.switchTo("triage", {
742
+ const op = names()("triage");
743
+ const v1 = await store.switchTo(op, create("a", null));
744
+ const v2 = await store.switchTo(op, create("b", v1.id));
745
+ await store.switchTo(op, {
467
746
  versionId: v1.id,
468
747
  kind: "ROLLBACK",
469
748
  reason: "b was worse",
470
749
  by: "person-1",
471
750
  expectLive: v2.id,
472
751
  });
473
- expect((await store.liveVersion("triage"))?.id).toBe(v1.id);
474
- expect(await store.listVersions("triage")).toHaveLength(2);
752
+ expect((await store.liveVersion(op))?.id).toBe(v1.id);
753
+ expect(await store.listVersions(op)).toHaveLength(2);
475
754
  });
476
755
 
477
756
  it("refuses a switch decided against a live version that changed", async () => {
478
757
  const store = await make();
479
- const v1 = await store.switchTo("triage", create("a", null));
480
- await store.switchTo("triage", create("b", v1.id));
758
+ const op = names()("triage");
759
+ const v1 = await store.switchTo(op, create("a", null));
760
+ await store.switchTo(op, create("b", v1.id));
481
761
  await expect(
482
- store.switchTo("triage", create("c", v1.id)),
762
+ store.switchTo(op, create("c", v1.id)),
483
763
  ).rejects.toBeInstanceOf(SettingsConflict);
484
- expect((await store.liveVersion("triage"))?.model).toBe("b");
485
- expect(await store.listVersions("triage")).toHaveLength(2);
764
+ expect((await store.liveVersion(op))?.model).toBe("b");
765
+ expect(await store.listVersions(op)).toHaveLength(2);
486
766
  });
487
767
 
488
768
  it("keeps a version's reasoning setting as named, even a newer one", async () => {
489
769
  const store = await make();
490
- const v1 = await store.switchTo("triage", {
770
+ const op = names()("triage");
771
+ const v1 = await store.switchTo(op, {
491
772
  ...create("a", null),
492
773
  create: {
493
774
  settings: { ...settings("a"), reasoningEffort: "xhigh" },
@@ -495,16 +776,15 @@ export function describeSettingsStoreContract(
495
776
  },
496
777
  });
497
778
  expect(v1.reasoningEffort).toBe("xhigh");
498
- expect((await store.liveVersion("triage"))?.reasoningEffort).toBe(
499
- "xhigh",
500
- );
779
+ expect((await store.liveVersion(op))?.reasoningEffort).toBe("xhigh");
501
780
  });
502
781
 
503
782
  if (opts.without?.includes("temperature")) {
504
783
  it("refuses a temperature it has no column for, and keeps none", async () => {
505
784
  const store = await make();
785
+ const op = names()("triage");
506
786
  await expect(
507
- store.switchTo("triage", {
787
+ store.switchTo(op, {
508
788
  ...create("a", null),
509
789
  create: {
510
790
  settings: { ...settings("a"), temperature: 0.4 },
@@ -512,14 +792,15 @@ export function describeSettingsStoreContract(
512
792
  },
513
793
  }),
514
794
  ).rejects.toThrow("temperature");
515
- expect(await store.liveVersion("triage")).toBeNull();
516
- const v1 = await store.switchTo("triage", create("a", null));
795
+ expect(await store.liveVersion(op)).toBeNull();
796
+ const v1 = await store.switchTo(op, create("a", null));
517
797
  expect(v1.temperature ?? null).toBeNull();
518
798
  });
519
799
  } else {
520
800
  it("keeps a version's temperature", async () => {
521
801
  const store = await make();
522
- const v1 = await store.switchTo("triage", {
802
+ const op = names()("triage");
803
+ const v1 = await store.switchTo(op, {
523
804
  ...create("a", null),
524
805
  create: {
525
806
  settings: { ...settings("a"), temperature: 0.4 },
@@ -527,18 +808,136 @@ export function describeSettingsStoreContract(
527
808
  },
528
809
  });
529
810
  expect(v1.temperature).toBe(0.4);
530
- expect((await store.liveVersion("triage"))?.temperature).toBe(0.4);
531
- const v2 = await store.switchTo("triage", create("b", v1.id));
811
+ expect((await store.liveVersion(op))?.temperature).toBe(0.4);
812
+ const v2 = await store.switchTo(op, create("b", v1.id));
532
813
  expect(v2.temperature ?? null).toBeNull();
533
814
  });
534
815
  }
535
816
 
817
+ it("keeps every kind of change, with its evidence", async () => {
818
+ const store = await make();
819
+ const op = names()("triage");
820
+ let live = (await store.switchTo(op, create("a", null))).id;
821
+ for (const kind of CHANGE_KINDS.slice(1))
822
+ live = (
823
+ await store.switchTo(op, {
824
+ ...create(kind.toLowerCase(), live),
825
+ kind,
826
+ evidence: kind === "PROMOTE" ? { runId: "r1" } : undefined,
827
+ })
828
+ ).id;
829
+ const changes = await store.listChanges(op);
830
+ expect(changes.map((c) => c.kind)).toEqual([...CHANGE_KINDS].reverse());
831
+ expect(changes.map((c) => c.evidence)).toEqual([
832
+ null,
833
+ null,
834
+ null,
835
+ null,
836
+ { runId: "r1" },
837
+ null,
838
+ ]);
839
+ });
840
+
536
841
  it("keeps each feature's versions and live one apart", async () => {
537
842
  const store = await make();
538
- await store.switchTo("triage", create("a", null));
539
- const other = await store.switchTo("summary", create("x", null));
843
+ const n = names();
844
+ await store.switchTo(n("triage"), create("a", null));
845
+ const other = await store.switchTo(n("summary"), create("x", null));
540
846
  expect(other.number).toBe(1);
541
- expect((await store.liveVersion("triage"))?.model).toBe("a");
847
+ expect((await store.liveVersion(n("triage")))?.model).toBe("a");
542
848
  });
543
849
  });
544
850
  }
851
+
852
+ /**
853
+ * The contract every set of suites should meet, so people confirming
854
+ * answers weeks later (and the pages) can read them: unique keys, a label
855
+ * and help for every top-level field of each suite's input and answer,
856
+ * a description for every check, and starter cases that fit the suite's
857
+ * own schemas. One test per suite, listing what's missing in plain words
858
+ * (`suiteContractProblems`).
859
+ *
860
+ * @param name - What the tests are called, e.g. "our suites".
861
+ * @param suites - Every suite the app registers.
862
+ * @param opts - Test functions other than Vitest's.
863
+ *
864
+ * @example
865
+ * ```ts
866
+ * import { describeSuiteContract } from "@crowandraven/evalkeeper/testing";
867
+ * import { SUITES } from "../lib/suites";
868
+ *
869
+ * describeSuiteContract("our suites", SUITES);
870
+ * ```
871
+ */
872
+ export function describeSuiteContract(
873
+ name: string,
874
+ suites: readonly AnySuite[],
875
+ opts: ContractOptions = {},
876
+ ) {
877
+ const { describe, it, expect } = testFunctions(opts.test);
878
+ describe(`Suite contract: ${name}`, () => {
879
+ it("has unique keys", () => {
880
+ expect(
881
+ suiteContractProblems(suites).filter((p) =>
882
+ p.endsWith("another suite has the same key."),
883
+ ),
884
+ ).toEqual([]);
885
+ });
886
+ for (const suite of suites)
887
+ it(`${suite.key}: every field, check, and starter can be read`, () => {
888
+ expect(
889
+ suiteContractProblems([suite]),
890
+ "What's missing for people to read this suite",
891
+ ).toEqual([]);
892
+ });
893
+ });
894
+ }
895
+
896
+ /**
897
+ * A read-only check, as a test, that a store mapped onto your own tables
898
+ * reads what's already there: one test per suite that fails listing every
899
+ * case, answer, test, and output that doesn't parse, with counts. It only
900
+ * reads, so it's the check to run first, on a copy of real data. Pass the
901
+ * report from `checkStoreReads` (any store) or `prismaReadCheck` (sees a
902
+ * Prisma table's values before the store fills in defaults).
903
+ *
904
+ * @param name - What the tests are called, e.g. "our answer key".
905
+ * @param check - Makes the report; called once, when the tests run.
906
+ * @param opts - The suite keys to name a test for, and test functions
907
+ * other than Vitest's.
908
+ *
909
+ * @example
910
+ * ```ts
911
+ * import { describeMappedReadCheck } from "@crowandraven/evalkeeper/testing";
912
+ * import { prismaReadCheck } from "@crowandraven/evalkeeper-prisma";
913
+ *
914
+ * describeMappedReadCheck(
915
+ * "our answer key",
916
+ * () => prismaReadCheck(prisma, map, { suites: SUITES }),
917
+ * { suites: SUITES.map((s) => s.key) },
918
+ * );
919
+ * ```
920
+ */
921
+ export function describeMappedReadCheck(
922
+ name: string,
923
+ check: () => Promise<ReadCheckReport>,
924
+ opts: ContractOptions & { suites: readonly string[] },
925
+ ) {
926
+ const { describe, it, expect } = testFunctions(opts.test);
927
+ let report: Promise<ReadCheckReport> | null = null;
928
+ const once = () => (report ??= check());
929
+ describe(`Read check: ${name}`, () => {
930
+ for (const key of opts.suites)
931
+ it(`${key}: every case, answer, test, and output reads`, async () => {
932
+ const found = (await once()).suites.find((s) => s.suite === key);
933
+ expect(found, `The check found no report for ${key}`).toMatchObject({
934
+ suite: key,
935
+ });
936
+ if (!found) return;
937
+ expect(
938
+ found.problems,
939
+ readCheckSummary({ suites: [found] }).join("\n"),
940
+ ).toEqual([]);
941
+ });
942
+ });
943
+ }