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