@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
@@ -0,0 +1,458 @@
1
+ import type { EvalStore } from "./store.js";
2
+ import { EVAL_SETS } from "./store.js";
3
+ import type { AnySuite } from "./types.js";
4
+
5
+ /**
6
+ * A read-only check that a store reads what's already in your tables:
7
+ * every case, answer, test, and output of each suite, with anything that
8
+ * doesn't parse (an unknown status, a cost that isn't a number, a missing
9
+ * column) listed by row, with counts. It never writes, so it's safe on a
10
+ * copy of real data; it's the first thing to run after mapping a store
11
+ * onto an app's own tables.
12
+ */
13
+
14
+ /** What a row is: a case, an answer, a test (a run), or an output. */
15
+ export type ReadKind = "case" | "answer" | "test" | "output";
16
+
17
+ /** One value that doesn't read as Evalkeeper expects. */
18
+ export type ReadProblem = {
19
+ suite: string;
20
+ kind: ReadKind;
21
+ /** The row's id, or empty when the rows couldn't be read at all. */
22
+ id: string;
23
+ /** Evalkeeper's name for the field, or empty for the whole row. */
24
+ field: string;
25
+ /** What's wrong, in plain words. */
26
+ problem: string;
27
+ };
28
+
29
+ /** How many of each were read. */
30
+ export type ReadCounts = {
31
+ cases: number;
32
+ answers: number;
33
+ tests: number;
34
+ outputs: number;
35
+ };
36
+
37
+ /** What a read check found for one suite. */
38
+ export type SuiteReadReport = {
39
+ suite: string;
40
+ counts: ReadCounts;
41
+ problems: ReadProblem[];
42
+ };
43
+
44
+ /** What a read check found, suite by suite. */
45
+ export type ReadCheckReport = { suites: SuiteReadReport[] };
46
+
47
+ /** A row as read, keyed by Evalkeeper's field names. */
48
+ export type ReadRow = Readonly<Record<string, unknown>>;
49
+
50
+ /**
51
+ * Where a read check reads rows from: a store's records
52
+ * (`checkStoreReads`), or an adapter's raw rows before it fills in
53
+ * defaults (`prismaReadCheck` in `@crowandraven/evalkeeper-prisma`), so a
54
+ * value the store would quietly replace still shows. Cases come with
55
+ * their answers in `labels`.
56
+ */
57
+ export type ReadSource = {
58
+ /** A suite's cases, retired ones too, each with its answers. */
59
+ cases(suite: string): Promise<readonly ReadRow[]>;
60
+ /** A suite's tests, newest first, at most `limit` when given. */
61
+ tests(suite: string, limit: number | undefined): Promise<readonly ReadRow[]>;
62
+ /** These tests' outputs. */
63
+ outputs(testIds: readonly string[]): Promise<readonly ReadRow[]>;
64
+ };
65
+
66
+ /** What to check: suites by key, or the suites themselves. */
67
+ export type ReadCheckOptions = {
68
+ /**
69
+ * The suites to read. Pass the suite itself (not just its key) to also
70
+ * check each case's input and answer against the suite's own schemas,
71
+ * the way your code reads them.
72
+ */
73
+ suites: readonly (string | AnySuite)[];
74
+ /** Read at most this many tests per suite, newest first. All by default. */
75
+ tests?: number;
76
+ };
77
+
78
+ const CASE_STATUSES = ["DRAFT", "ACTIVE", "RETIRED"];
79
+ const SPLITS = ["DEV", "TEST"];
80
+ const LABEL_STATUSES = [
81
+ "PENDING",
82
+ "CONFIRMED",
83
+ "PROVISIONAL",
84
+ "REJECTED",
85
+ "SKIPPED",
86
+ ];
87
+ const RUN_STATUSES = ["RUNNING", "SUCCEEDED", "FAILED"];
88
+
89
+ type Rule = (v: unknown) => string | null;
90
+
91
+ const missing = "is missing (no column for it, or not mapped)";
92
+ // JSON.stringify gives undefined for these, or throws for a bigint.
93
+ const show = (v: unknown): string =>
94
+ v === undefined || typeof v === "bigint" || typeof v === "function"
95
+ ? String(v)
96
+ : JSON.stringify(v);
97
+
98
+ const text: Rule = (v) =>
99
+ v === undefined
100
+ ? missing
101
+ : typeof v === "string"
102
+ ? null
103
+ : `isn't text: ${show(v)}`;
104
+ const textOrNull: Rule = (v) => (v === null ? null : text(v));
105
+ const present: Rule = (v) => (v === undefined ? missing : null);
106
+ const oneOf =
107
+ (allowed: readonly string[], orNull = false): Rule =>
108
+ (v) =>
109
+ v === undefined
110
+ ? missing
111
+ : (orNull && v === null) || (typeof v === "string" && allowed.includes(v))
112
+ ? null
113
+ : `${show(v)} isn't one of ${allowed.join(", ")}`;
114
+ const when: Rule = (v) =>
115
+ v === undefined
116
+ ? missing
117
+ : v instanceof Date && !Number.isNaN(v.getTime())
118
+ ? null
119
+ : `isn't a date: ${show(v)}`;
120
+ const whenOrNull: Rule = (v) => (v === null ? null : when(v));
121
+ const amount =
122
+ (orNull: boolean): Rule =>
123
+ (v) =>
124
+ v === undefined
125
+ ? missing
126
+ : orNull && v === null
127
+ ? null
128
+ : typeof v === "number" && Number.isFinite(v) && v >= 0
129
+ ? null
130
+ : `isn't a number of zero or more: ${show(v)}`;
131
+ /** A run setting: a column the app may not have, so unset is fine. */
132
+ const setting: Rule = (v) =>
133
+ v === undefined || v === null || (typeof v === "number" && Number.isFinite(v))
134
+ ? null
135
+ : `isn't a number: ${show(v)}`;
136
+ const count: Rule = (v) =>
137
+ v === undefined
138
+ ? missing
139
+ : typeof v === "number" && Number.isInteger(v) && v >= 1
140
+ ? null
141
+ : `isn't a whole number of 1 or more: ${show(v)}`;
142
+ const yesNo: Rule = (v) =>
143
+ v === undefined
144
+ ? missing
145
+ : typeof v === "boolean"
146
+ ? null
147
+ : `isn't true or false: ${show(v)}`;
148
+ const words: Rule = (v) =>
149
+ v === undefined
150
+ ? missing
151
+ : Array.isArray(v) && v.every((x) => typeof x === "string")
152
+ ? null
153
+ : `isn't a list of words: ${show(v)}`;
154
+ const objectOrNull: Rule = (v) =>
155
+ v === undefined || v === null || (typeof v === "object" && !Array.isArray(v))
156
+ ? null
157
+ : `isn't what the runner writes: ${show(v)}`;
158
+ const scores: Rule = (v) =>
159
+ v === undefined ||
160
+ v === null ||
161
+ (Array.isArray(v) &&
162
+ v.every(
163
+ (s) =>
164
+ typeof s === "object" &&
165
+ s !== null &&
166
+ typeof Reflect.get(s, "key") === "string",
167
+ ))
168
+ ? null
169
+ : `isn't a list of check results: ${show(v)}`;
170
+
171
+ /**
172
+ * The fields of each kind of row and what each must be. Nulls the stores
173
+ * read on purpose (a legacy test with no set reads as ALL, no grader
174
+ * version as empty) aren't problems.
175
+ */
176
+ const RULES: Record<ReadKind, Record<string, Rule>> = {
177
+ case: {
178
+ id: text,
179
+ suite: text,
180
+ input: present,
181
+ tags: words,
182
+ split: oneOf(SPLITS),
183
+ status: oneOf(CASE_STATUSES),
184
+ source: text,
185
+ sourceRef: textOrNull,
186
+ note: textOrNull,
187
+ createdAt: when,
188
+ updatedAt: when,
189
+ },
190
+ answer: {
191
+ id: text,
192
+ kind: oneOf(["EXPECTED"]),
193
+ status: oneOf(LABEL_STATUSES),
194
+ value: present,
195
+ raterRole: text,
196
+ raterId: textOrNull,
197
+ note: textOrNull,
198
+ createdAt: when,
199
+ updatedAt: when,
200
+ },
201
+ test: {
202
+ id: text,
203
+ suite: text,
204
+ model: text,
205
+ promptVersion: text,
206
+ reasoningEffort: textOrNull,
207
+ temperature: setting,
208
+ maxOutputTokens: setting,
209
+ set: oneOf(EVAL_SETS, true),
210
+ repeats: count,
211
+ datasetVersion: textOrNull,
212
+ graderVersion: textOrNull,
213
+ status: oneOf(RUN_STATUSES),
214
+ metrics: objectOrNull,
215
+ error: textOrNull,
216
+ estimatedCostUsd: amount(true),
217
+ startedBy: textOrNull,
218
+ startedAt: when,
219
+ finishedAt: whenOrNull,
220
+ },
221
+ output: {
222
+ id: text,
223
+ runId: text,
224
+ caseId: text,
225
+ repeat: count,
226
+ requestHash: text,
227
+ output: present,
228
+ error: textOrNull,
229
+ scores,
230
+ costUsd: amount(false),
231
+ ms: amount(false),
232
+ reused: yesNo,
233
+ createdAt: when,
234
+ },
235
+ };
236
+
237
+ /**
238
+ * What doesn't read as Evalkeeper expects in one row: each field that's
239
+ * missing or holds a value the store can't use as it is.
240
+ *
241
+ * @param kind - What the row is.
242
+ * @param row - The row, keyed by Evalkeeper's field names.
243
+ */
244
+ export function rowProblems(
245
+ kind: ReadKind,
246
+ row: ReadRow,
247
+ ): { field: string; problem: string }[] {
248
+ const out: { field: string; problem: string }[] = [];
249
+ for (const [field, rule] of Object.entries(RULES[kind])) {
250
+ const problem = rule(row[field]);
251
+ if (problem) out.push({ field, problem });
252
+ }
253
+ return out;
254
+ }
255
+
256
+ const idOf = (row: ReadRow) => (typeof row.id === "string" ? row.id : "");
257
+ const message = (e: unknown) => (e instanceof Error ? e.message : String(e));
258
+
259
+ /** The first thing a schema says is wrong, in a line. */
260
+ function schemaProblem(
261
+ schema: AnySuite["input"],
262
+ value: unknown,
263
+ ): string | null {
264
+ const parsed = schema.safeParse(value);
265
+ if (parsed.success) return null;
266
+ const [first] = parsed.error.issues;
267
+ const where = first?.path.length ? `${first.path.join(".")}: ` : "";
268
+ return `doesn't fit the suite's schema (${where}${first?.message ?? "invalid"})`;
269
+ }
270
+
271
+ async function checkSuite(
272
+ source: ReadSource,
273
+ key: string,
274
+ suite: AnySuite | null,
275
+ opts: ReadCheckOptions,
276
+ ): Promise<SuiteReadReport> {
277
+ const counts: ReadCounts = { cases: 0, answers: 0, tests: 0, outputs: 0 };
278
+ const problems: ReadProblem[] = [];
279
+ const add = (kind: ReadKind, row: ReadRow) => {
280
+ for (const p of rowProblems(kind, row))
281
+ problems.push({ suite: key, kind, id: idOf(row), ...p });
282
+ };
283
+ const unreadable = (kind: ReadKind, e: unknown) =>
284
+ problems.push({
285
+ suite: key,
286
+ kind,
287
+ id: "",
288
+ field: "",
289
+ problem: `couldn't be read: ${message(e)}`,
290
+ });
291
+
292
+ try {
293
+ for (const c of await source.cases(key)) {
294
+ counts.cases++;
295
+ add("case", c);
296
+ if (suite && c.input !== undefined) {
297
+ const p = schemaProblem(suite.input, c.input);
298
+ if (p)
299
+ problems.push({
300
+ suite: key,
301
+ kind: "case",
302
+ id: idOf(c),
303
+ field: "input",
304
+ problem: p,
305
+ });
306
+ }
307
+ if (!Array.isArray(c.labels)) {
308
+ problems.push({
309
+ suite: key,
310
+ kind: "case",
311
+ id: idOf(c),
312
+ field: "labels",
313
+ problem:
314
+ "has no list of answers (check the mapping's labels relation)",
315
+ });
316
+ continue;
317
+ }
318
+ for (const l of c.labels as unknown[]) {
319
+ counts.answers++;
320
+ const row: ReadRow =
321
+ typeof l === "object" && l !== null
322
+ ? // Trust boundary: a row object from the source, read by key.
323
+ (l as ReadRow)
324
+ : {};
325
+ add("answer", row);
326
+ // A skip (blind rating) has no answer to fit the schema.
327
+ if (suite && row.value !== undefined && row.status !== "SKIPPED") {
328
+ const p = schemaProblem(suite.labelValue, row.value);
329
+ if (p)
330
+ problems.push({
331
+ suite: key,
332
+ kind: "answer",
333
+ id: idOf(row),
334
+ field: "value",
335
+ problem: p,
336
+ });
337
+ }
338
+ }
339
+ }
340
+ } catch (e) {
341
+ unreadable("case", e);
342
+ }
343
+
344
+ let testIds: string[] = [];
345
+ try {
346
+ const tests = await source.tests(key, opts.tests);
347
+ counts.tests = tests.length;
348
+ for (const t of tests) add("test", t);
349
+ testIds = tests.map(idOf).filter((id) => id !== "");
350
+ } catch (e) {
351
+ unreadable("test", e);
352
+ }
353
+
354
+ if (testIds.length) {
355
+ try {
356
+ const outputs = await source.outputs(testIds);
357
+ counts.outputs = outputs.length;
358
+ for (const o of outputs) add("output", o);
359
+ } catch (e) {
360
+ unreadable("output", e);
361
+ }
362
+ }
363
+ return { suite: key, counts, problems };
364
+ }
365
+
366
+ /**
367
+ * Reads each suite's rows from a source and lists what doesn't parse, with
368
+ * counts. Read-only. Use `checkStoreReads` for any store, or an adapter's
369
+ * own check (`prismaReadCheck`) to see values before the store fills in
370
+ * defaults.
371
+ *
372
+ * @param source - Where to read the rows.
373
+ * @param opts - Which suites, and how many tests of each.
374
+ */
375
+ export async function checkReads(
376
+ source: ReadSource,
377
+ opts: ReadCheckOptions,
378
+ ): Promise<ReadCheckReport> {
379
+ const suites: SuiteReadReport[] = [];
380
+ for (const s of opts.suites)
381
+ suites.push(
382
+ await checkSuite(
383
+ source,
384
+ typeof s === "string" ? s : s.key,
385
+ typeof s === "string" ? null : s,
386
+ opts,
387
+ ),
388
+ );
389
+ return { suites };
390
+ }
391
+
392
+ /**
393
+ * Reads each suite's cases, answers, tests, and outputs through a store
394
+ * and lists anything that doesn't parse, with counts. Read-only, so it's
395
+ * safe on a copy of real data. A store may fill in defaults as it reads
396
+ * (the Prisma store reads an unknown status as a known one); for a Prisma
397
+ * store, `prismaReadCheck` sees the values before that.
398
+ *
399
+ * @param store - The store to read through.
400
+ * @param opts - Which suites, and how many tests of each.
401
+ *
402
+ * @example
403
+ * ```ts
404
+ * import { checkStoreReads, readCheckSummary } from "@crowandraven/evalkeeper";
405
+ *
406
+ * const report = await checkStoreReads(store, { suites: SUITES });
407
+ * console.log(readCheckSummary(report).join("\n"));
408
+ * ```
409
+ */
410
+ export function checkStoreReads(
411
+ store: EvalStore,
412
+ opts: ReadCheckOptions,
413
+ ): Promise<ReadCheckReport> {
414
+ return checkReads(
415
+ {
416
+ cases: (suite) => store.listCases(suite, { includeRetired: true }),
417
+ tests: (suite, limit) =>
418
+ store.listRuns(suite, limit === undefined ? {} : { limit }),
419
+ outputs: async (ids) =>
420
+ store.listOutputsFor
421
+ ? store.listOutputsFor([...ids])
422
+ : (await Promise.all(ids.map((id) => store.listOutputs(id)))).flat(),
423
+ },
424
+ opts,
425
+ );
426
+ }
427
+
428
+ const plural = (n: number, one: string, many: string) =>
429
+ `${n.toLocaleString("en-US")} ${n === 1 ? one : many}`;
430
+
431
+ /**
432
+ * A read check in words: a line per suite with its counts, then each kind
433
+ * of problem once with how many rows have it and an example id.
434
+ *
435
+ * @param report - What `checkReads`, `checkStoreReads`, or
436
+ * `prismaReadCheck` found.
437
+ */
438
+ export function readCheckSummary(report: ReadCheckReport): string[] {
439
+ const lines: string[] = [];
440
+ for (const s of report.suites) {
441
+ const c = s.counts;
442
+ lines.push(
443
+ `${s.suite}: ${plural(c.cases, "case", "cases")}, ${plural(c.answers, "answer", "answers")}, ${plural(c.tests, "test", "tests")}, and ${plural(c.outputs, "output", "outputs")}; ${s.problems.length ? plural(s.problems.length, "problem", "problems") : "no problems"}.`,
444
+ );
445
+ const groups = new Map<string, { n: number; id: string }>();
446
+ for (const p of s.problems) {
447
+ const what = `${p.kind}${p.field ? ` ${p.field}` : ""} ${p.problem}`;
448
+ const g = groups.get(what);
449
+ if (g) g.n++;
450
+ else groups.set(what, { n: 1, id: p.id });
451
+ }
452
+ for (const [what, g] of groups)
453
+ lines.push(
454
+ ` ${what}: ${plural(g.n, "row", "rows")}${g.id ? ` (e.g. ${g.id})` : ""}.`,
455
+ );
456
+ }
457
+ return lines;
458
+ }
package/src/runner.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  * @module evalkeeper/runner
6
6
  */
7
7
  import { createHash } from "node:crypto";
8
- import { compareRuns, type RunOutput } from "./compare.js";
8
+ import { compareRuns, disagreements, type RunOutput } from "./compare.js";
9
9
  import { isStuck, shouldContinue } from "./legs.js";
10
10
  import {
11
11
  effortFor,
@@ -27,6 +27,14 @@ import type {
27
27
  OutputRecord,
28
28
  } from "./store.js";
29
29
  import { withTimeout } from "./timeout.js";
30
+ import {
31
+ casesInInstructions,
32
+ type CaseInInstructions,
33
+ } from "./inInstructions.js";
34
+ import {
35
+ draftFromActivity as draftCases,
36
+ type ActivityDraftResult,
37
+ } from "./activity.js";
30
38
  import { SCHEDULED } from "./weekly.js";
31
39
  import { confirmedLabel, isProvisional } from "./labels.js";
32
40
  export { confirmedLabel, isProvisional };
@@ -68,6 +76,13 @@ export type RunnerOptions = {
68
76
  * marks older tests out of date.
69
77
  */
70
78
  promptVersion: (operation: string) => string | Promise<string>;
79
+ /**
80
+ * Everything the operation's model is told, as text: system text, prompt
81
+ * templates, schema and tool descriptions (`instructionParts` in
82
+ * `@crowandraven/evalkeeper-ai-sdk`, from the parts you hash). Lets
83
+ * `casesInInstructions` warn when a case was copied into them.
84
+ */
85
+ instructionTexts?: (operation: string) => string[] | Promise<string[]>;
71
86
  /**
72
87
  * The live reasoning setting for an operation; null: the model's own.
73
88
  * Defaults to the route's, when `route` is given.
@@ -753,6 +768,20 @@ export function createRunner(opts: RunnerOptions) {
753
768
  return id;
754
769
  }
755
770
 
771
+ /**
772
+ * One suite's weekly drafts from your app's activity: asks the suite's
773
+ * `draftFromActivity` for up to `limit` cases a week (default
774
+ * ACTIVITY_DRAFTS_PER_WEEK) and adds new ones as drafts with PENDING
775
+ * answers, skipping anything drafted before. Call it for each suite from
776
+ * the weekly job; suites without the method draft nothing.
777
+ */
778
+ async function draftFromActivity(
779
+ suiteKey: string,
780
+ o: { limit?: number; since?: Date; today?: Date } = {},
781
+ ): Promise<ActivityDraftResult> {
782
+ return draftCases({ store, suite: suiteOrThrow(suiteKey), ...o });
783
+ }
784
+
756
785
  /**
757
786
  * Several tests' outputs by test id: one call where the store can, so a
758
787
  * remote database isn't asked once per test.
@@ -798,6 +827,8 @@ export function createRunner(opts: RunnerOptions) {
798
827
  /**
799
828
  * Two finished tests of a suite compared case by case: `a` the one in
800
829
  * place, `b` the challenger. Null if either isn't a finished test.
830
+ * `disagreements` lists the cases they graded differently, for reading
831
+ * the two answers side by side.
801
832
  */
802
833
  async function compare(suiteKey: string, a: string, b: string) {
803
834
  const suite = suiteOrThrow(suiteKey);
@@ -820,9 +851,10 @@ export function createRunner(opts: RunnerOptions) {
820
851
  ms: x.ms,
821
852
  reused: x.reused,
822
853
  }));
854
+ const [oa, ob] = await Promise.all([asOutputs(ra), asOutputs(rb)]);
823
855
  const comparison = compareRuns(
824
- await asOutputs(ra),
825
- await asOutputs(rb),
856
+ oa,
857
+ ob,
826
858
  suite.checks.map((c) => c.key),
827
859
  );
828
860
  // Comparable only when measured the same way.
@@ -835,7 +867,43 @@ export function createRunner(opts: RunnerOptions) {
835
867
  ra.promptVersion !== rb.promptVersion &&
836
868
  `different instructions (${ra.promptVersion} and ${rb.promptVersion})`,
837
869
  ].filter((x): x is string => Boolean(x));
838
- return { suite, a: ra, b: rb, comparison, caveats };
870
+ return {
871
+ suite,
872
+ a: ra,
873
+ b: rb,
874
+ comparison,
875
+ disagreements: disagreements(oa, ob),
876
+ caveats,
877
+ };
878
+ }
879
+
880
+ /**
881
+ * The suite's cases in use or in draft whose text appears in its
882
+ * operation's instructions (see `casesInInstructions`), for a warning on
883
+ * the suite page. Empty without `instructionTexts`.
884
+ */
885
+ async function casesInInstructionsFor(
886
+ suiteKey: string,
887
+ ): Promise<CaseInInstructions[]> {
888
+ const suite = suiteOrThrow(suiteKey);
889
+ if (!opts.instructionTexts) return [];
890
+ const [texts, cases] = await Promise.all([
891
+ opts.instructionTexts(suite.operation),
892
+ store.listCases(suite.key),
893
+ ]);
894
+ return casesInInstructions(
895
+ cases
896
+ .filter((c) => c.status !== "RETIRED")
897
+ .map((c) => {
898
+ const parsed = suite.input.safeParse(c.input);
899
+ return {
900
+ id: c.id,
901
+ title: parsed.success ? suite.title(parsed.data) : "A case",
902
+ input: c.input,
903
+ };
904
+ }),
905
+ texts,
906
+ );
839
907
  }
840
908
 
841
909
  /**
@@ -1067,6 +1135,7 @@ export function createRunner(opts: RunnerOptions) {
1067
1135
  return {
1068
1136
  startDriftCheck,
1069
1137
  runDriftCheck,
1138
+ draftFromActivity,
1070
1139
  board,
1071
1140
  suiteOrThrow,
1072
1141
  casesFor,
@@ -1078,6 +1147,7 @@ export function createRunner(opts: RunnerOptions) {
1078
1147
  rescoreRecent,
1079
1148
  stopStuckRuns,
1080
1149
  compare,
1150
+ casesInInstructions: casesInInstructionsFor,
1081
1151
  };
1082
1152
  }
1083
1153