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