@crowandraven/evalkeeper 0.7.0 → 0.9.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 +9 -0
  2. package/dist/cli/addPages.d.ts +5 -0
  3. package/dist/cli/addPages.js +15 -3
  4. package/dist/cli/addPages.js.map +1 -1
  5. package/dist/decisions.js +8 -0
  6. package/dist/decisions.js.map +1 -1
  7. package/dist/feedback.d.ts +20 -3
  8. package/dist/feedback.js +16 -3
  9. package/dist/feedback.js.map +1 -1
  10. package/dist/glossary.d.ts +6 -1
  11. package/dist/glossary.js +6 -1
  12. package/dist/glossary.js.map +1 -1
  13. package/dist/importCases.d.ts +15 -4
  14. package/dist/importCases.js +20 -18
  15. package/dist/importCases.js.map +1 -1
  16. package/dist/inInstructions.d.ts +47 -0
  17. package/dist/inInstructions.js +95 -0
  18. package/dist/inInstructions.js.map +1 -0
  19. package/dist/index.d.ts +2 -0
  20. package/dist/index.js +2 -0
  21. package/dist/index.js.map +1 -1
  22. package/dist/reviews.d.ts +172 -0
  23. package/dist/reviews.js +294 -0
  24. package/dist/reviews.js.map +1 -0
  25. package/dist/runner.d.ts +9 -0
  26. package/dist/runner.js +26 -0
  27. package/dist/runner.js.map +1 -1
  28. package/dist/suiteContract.d.ts +12 -5
  29. package/dist/suiteContract.js +47 -7
  30. package/dist/suiteContract.js.map +1 -1
  31. package/dist/suites/attackImport.d.ts +99 -0
  32. package/dist/suites/attackImport.js +283 -0
  33. package/dist/suites/attackImport.js.map +1 -0
  34. package/dist/suites/crisisRisk.d.ts +9 -2
  35. package/dist/suites/crisisRisk.js +8 -3
  36. package/dist/suites/crisisRisk.js.map +1 -1
  37. package/dist/suites/crisisRiskCases.d.ts +4 -3
  38. package/dist/suites/crisisRiskCases.js +4 -3
  39. package/dist/suites/crisisRiskCases.js.map +1 -1
  40. package/dist/suites/crisisRiskReviews.d.ts +15 -0
  41. package/dist/suites/crisisRiskReviews.js +926 -0
  42. package/dist/suites/crisisRiskReviews.js.map +1 -0
  43. package/dist/suites/hopelessness.d.ts +123 -0
  44. package/dist/suites/hopelessness.js +296 -0
  45. package/dist/suites/hopelessness.js.map +1 -0
  46. package/dist/suites/hopelessnessCases.d.ts +62 -0
  47. package/dist/suites/hopelessnessCases.js +243 -0
  48. package/dist/suites/hopelessnessCases.js.map +1 -0
  49. package/dist/suites/hopelessnessReviews.d.ts +15 -0
  50. package/dist/suites/hopelessnessReviews.js +1080 -0
  51. package/dist/suites/hopelessnessReviews.js.map +1 -0
  52. package/dist/suites/index.d.ts +7 -0
  53. package/dist/suites/index.js +7 -0
  54. package/dist/suites/index.js.map +1 -1
  55. package/dist/suites/injection.d.ts +162 -0
  56. package/dist/suites/injection.js +331 -0
  57. package/dist/suites/injection.js.map +1 -0
  58. package/dist/suites/injectionAttacks.d.ts +3 -0
  59. package/dist/suites/injectionAttacks.js +34 -0
  60. package/dist/suites/injectionAttacks.js.map +1 -0
  61. package/dist/testing.d.ts +36 -2
  62. package/dist/testing.js +104 -14
  63. package/dist/testing.js.map +1 -1
  64. package/dist/types.d.ts +27 -0
  65. package/dist/types.js +11 -0
  66. package/dist/types.js.map +1 -1
  67. package/package.json +1 -1
  68. package/src/cli/addPages.ts +16 -3
  69. package/src/decisions.ts +10 -0
  70. package/src/feedback.ts +23 -3
  71. package/src/glossary.ts +11 -1
  72. package/src/importCases.ts +21 -20
  73. package/src/inInstructions.ts +105 -0
  74. package/src/index.ts +2 -0
  75. package/src/reviews.ts +428 -0
  76. package/src/runner.ts +41 -0
  77. package/src/suiteContract.ts +56 -7
  78. package/src/suites/attackImport.ts +327 -0
  79. package/src/suites/crisisRisk.ts +15 -3
  80. package/src/suites/crisisRiskCases.ts +4 -3
  81. package/src/suites/crisisRiskReviews.ts +927 -0
  82. package/src/suites/hopelessness.ts +420 -0
  83. package/src/suites/hopelessnessCases.ts +287 -0
  84. package/src/suites/hopelessnessReviews.ts +1081 -0
  85. package/src/suites/index.ts +7 -0
  86. package/src/suites/injection.ts +463 -0
  87. package/src/suites/injectionAttacks.ts +136 -0
  88. package/src/testing.ts +144 -18
  89. package/src/types.ts +30 -0
  90. package/starter/index.ts +8 -0
  91. package/templates/app/evals/[suite]/compare/page.tsx +10 -0
  92. package/templates/app/evals/[suite]/page.tsx +55 -18
  93. package/templates/app/evals/[suite]/rate/page.tsx +10 -0
  94. package/templates/app/evals/[suite]/runs/[runId]/page.tsx +72 -3
  95. package/templates/app/evals/[suite]/side-by-side/page.tsx +37 -17
  96. package/templates/app/evals/feedback/page.tsx +6 -1
  97. package/templates/app/evals/page.tsx +36 -26
  98. package/templates/components/evalkeeper/AnswerKey.tsx +25 -1
  99. package/templates/components/evalkeeper/ReadableOutput.tsx +97 -0
  100. package/templates/components/evalkeeper/SettingsHistory.tsx +10 -4
  101. package/templates/lib/evalkeeper/actions.ts +4 -1
@@ -1,5 +1,5 @@
1
1
  import { nextSplit } from "./quickSet.js";
2
- import { stableJson } from "./stableJson.js";
2
+ import { addShippedReviews, starterKey, type ReviewResult } from "./reviews.js";
3
3
  import type { EvalStore, NewCase, NewLabel } from "./store.js";
4
4
  import type { AnySuite } from "./types.js";
5
5
 
@@ -353,34 +353,34 @@ export async function importCases<Row>(opts: {
353
353
  return { added, skipped, removed };
354
354
  }
355
355
 
356
- /** A short, stable id for a starter case: a hash of its input. */
357
- function starterId(input: unknown): string {
358
- // FNV-1a: the core stays free of node:crypto; this only names rows.
359
- let h = 0x811c9dc5;
360
- for (const ch of stableJson(input)) {
361
- h ^= ch.charCodeAt(0);
362
- h = Math.imul(h, 0x01000193) >>> 0;
363
- }
364
- return h.toString(16).padStart(8, "0");
365
- }
366
-
367
356
  /**
368
357
  * Adds a suite's `starter` cases as drafts with pending answers, for a
369
- * person to confirm on the pages. Safe to run again: starters already
370
- * added (by their input) are skipped. A suite's leak check runs on each,
371
- * as in `importCases`.
358
+ * person to confirm on the pages. A case with a review shipped with the
359
+ * suite (`reviews`: its author or an expert checked it) gets that review
360
+ * as a confirmed answer instead, and is in use at once; see
361
+ * `addShippedReviews` for when one is left out. Safe to run again:
362
+ * starters already added (by their input) are skipped, and reviews shipped
363
+ * since are added to them. A suite's leak check runs on each, as in
364
+ * `importCases`.
365
+ *
366
+ * @param store - Where to add the cases.
367
+ * @param suite - The suite whose `starter` cases and `reviews` to add.
368
+ * @returns What was added and skipped, what the leak check removed, how
369
+ * many shipped reviews were added, and cases whose answer from someone
370
+ * in the app differs from a shipped review.
372
371
  */
373
- export function importStarters(
372
+ export async function importStarters(
374
373
  store: EvalStore,
375
374
  suite: AnySuite,
376
- ): Promise<ImportResult> {
377
- return importCases({
375
+ ): Promise<ImportResult & ReviewResult> {
376
+ const source = `starter:${suite.key}`;
377
+ const imported = await importCases({
378
378
  store,
379
379
  suite,
380
- source: `starter:${suite.key}`,
380
+ source,
381
381
  rows: suite.starter ?? [],
382
382
  map: (s) => ({
383
- id: starterId(s.input),
383
+ id: starterKey(s.input),
384
384
  input: s.input,
385
385
  label: s.label,
386
386
  tags: s.tags,
@@ -388,4 +388,5 @@ export function importStarters(
388
388
  split: s.split,
389
389
  }),
390
390
  });
391
+ return { ...imported, ...(await addShippedReviews(store, suite, source)) };
391
392
  }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Finds cases whose text appears in a feature's instructions. A case
3
+ * copied into the instructions as an example gets graded on an answer the
4
+ * model was handed, so its score rises without the model getting better.
5
+ * Pure.
6
+ */
7
+
8
+ /** A stretch this long (after evening out) counts, even inside a longer text. */
9
+ export const IN_INSTRUCTIONS_MIN_CHARS = 20;
10
+
11
+ /** A whole case text this long counts when all of it appears. */
12
+ export const IN_INSTRUCTIONS_MIN_WHOLE = 12;
13
+
14
+ /** One case found in the instructions, with the words that matched. */
15
+ export type CaseInInstructions = {
16
+ caseId: string;
17
+ title: string;
18
+ /** The matching words, evened out (lowercase, no punctuation). */
19
+ found: string;
20
+ };
21
+
22
+ /**
23
+ * Lowercase, apostrophes (straight or curly) dropped, and anything but
24
+ * letters and digits turned to single spaces, so "The Broncos are
25
+ * hopeless!" and "the broncos are hopeless" read the same.
26
+ */
27
+ function evenOut(text: string): string {
28
+ return text
29
+ .toLowerCase()
30
+ .replace(/[‘’']/g, "")
31
+ .replace(/[^\p{L}\p{N}]+/gu, " ")
32
+ .trim();
33
+ }
34
+
35
+ /** Every string in a value, however deep, in order. */
36
+ function stringsIn(value: unknown): string[] {
37
+ if (typeof value === "string") return [value];
38
+ if (Array.isArray(value)) return value.flatMap(stringsIn);
39
+ if (value && typeof value === "object")
40
+ return Object.values(value).flatMap(stringsIn);
41
+ return [];
42
+ }
43
+
44
+ /** The longest run of whole words from `text` that appears in `within`. */
45
+ function longestRun(text: string, within: string): string {
46
+ const words = text.split(" ");
47
+ let best = "";
48
+ for (let i = 0; i < words.length; i++) {
49
+ let run = "";
50
+ for (let j = i; j < words.length; j++) {
51
+ const next = run ? `${run} ${words[j] ?? ""}` : (words[j] ?? "");
52
+ if (!` ${within} `.includes(` ${next} `)) break;
53
+ run = next;
54
+ }
55
+ if (run.length > best.length) best = run;
56
+ }
57
+ return best;
58
+ }
59
+
60
+ /**
61
+ * The cases whose input text appears in the instructions: all of one of
62
+ * its texts (when at least `minWhole` characters), or a run of whole words
63
+ * at least `minChars` long, after evening out case and punctuation. Use it
64
+ * to warn, not to fail: an example may belong in the instructions, and
65
+ * then the case should be rewritten or retired.
66
+ *
67
+ * @param cases - Each case's id, title, and input.
68
+ * @param instructions - Everything the model is told: system text, prompt
69
+ * templates, schema and tool descriptions (`instructionParts` in
70
+ * `@crowandraven/evalkeeper-ai-sdk` gives these).
71
+ * @param opts - Other lengths than `IN_INSTRUCTIONS_MIN_CHARS` and
72
+ * `IN_INSTRUCTIONS_MIN_WHOLE`.
73
+ * @returns The cases found, each with its longest matching words.
74
+ * @example
75
+ * ```ts
76
+ * casesInInstructions(
77
+ * [{ id: "c1", title: "Broncos", input: { message: "the Broncos are hopeless" } }],
78
+ * ["Not hopeless: “The Broncos are hopeless!” is about a team."],
79
+ * ); // [{ caseId: "c1", title: "Broncos", found: "the broncos are hopeless" }]
80
+ * ```
81
+ */
82
+ export function casesInInstructions(
83
+ cases: readonly { id: string; title: string; input: unknown }[],
84
+ instructions: readonly string[],
85
+ opts: { minChars?: number; minWhole?: number } = {},
86
+ ): CaseInInstructions[] {
87
+ const minChars = opts.minChars ?? IN_INSTRUCTIONS_MIN_CHARS;
88
+ const minWhole = opts.minWhole ?? IN_INSTRUCTIONS_MIN_WHOLE;
89
+ const within = instructions.map(evenOut).join(" \u0000 ");
90
+ if (!within) return [];
91
+ const found: CaseInInstructions[] = [];
92
+ for (const c of cases) {
93
+ let best = "";
94
+ for (const raw of stringsIn(c.input)) {
95
+ const text = evenOut(raw);
96
+ if (!text) continue;
97
+ const run = longestRun(text, within);
98
+ const counts =
99
+ run.length >= minChars || (run === text && run.length >= minWhole);
100
+ if (counts && run.length > best.length) best = run;
101
+ }
102
+ if (best) found.push({ caseId: c.id, title: c.title, found: best });
103
+ }
104
+ return found;
105
+ }
package/src/index.ts CHANGED
@@ -32,7 +32,9 @@ export * from "./suiteContract.js";
32
32
  export * from "./readCheck.js";
33
33
  export * from "./labels.js";
34
34
  export * from "./blind.js";
35
+ export * from "./inInstructions.js";
35
36
  // Server-only (node:crypto): import from "@crowandraven/evalkeeper/runner".
36
37
  // In-memory store for tests and demos: "@crowandraven/evalkeeper/memory".
37
38
  export * from "./importCases.js";
39
+ export * from "./reviews.js";
38
40
  export * from "./activity.js";
package/src/reviews.ts ADDED
@@ -0,0 +1,428 @@
1
+ import { stableJson } from "./stableJson.js";
2
+ import type { CaseRecord, EvalStore, NewLabel } from "./store.js";
3
+ import type { AnySuite } from "./types.js";
4
+
5
+ /**
6
+ * Reviews that ship with a suite: a person checked a starter case's answer
7
+ * once, for every app that uses the suite, so it arrives confirmed instead
8
+ * of pending. It's still a person's confirmation, never one made on their
9
+ * behalf: each review names who, when, and what qualifies them, and only
10
+ * counts for the exact input and answer they saw.
11
+ */
12
+
13
+ /**
14
+ * Who reviewed a shipped case: the suite's author ("AUTHOR"), or someone
15
+ * with experience in what the suite judges ("EXPERT"), such as a crisis
16
+ * line counselor for the crisis risk suite.
17
+ */
18
+ export type ReviewLevel = "AUTHOR" | "EXPERT";
19
+
20
+ /** The `raterRole` on an answer the suite's author reviewed. */
21
+ export const AUTHOR_REVIEWED = "SUITE_AUTHOR";
22
+ /** The `raterRole` on an answer an expert reviewed for the suite. */
23
+ export const EXPERT_REVIEWED = "SUITE_EXPERT";
24
+ /**
25
+ * The `raterRole` on an attack case's answer (see `injectionCases`),
26
+ * carried from the base case it was made from: an attack shouldn't change
27
+ * the right answer, so its confirmation is the base case's.
28
+ */
29
+ export const FROM_BASE_CASE = "FROM_BASE_CASE";
30
+
31
+ const ROLE: Record<ReviewLevel, string> = {
32
+ AUTHOR: AUTHOR_REVIEWED,
33
+ EXPERT: EXPERT_REVIEWED,
34
+ };
35
+
36
+ /**
37
+ * One person's review of one starter case, shipped with the suite. It
38
+ * counts only while the case's input and answer are what the reviewer
39
+ * saw: edit either and the case arrives pending again, and the suite
40
+ * contract fails until the review is redone or removed.
41
+ */
42
+ export type ShippedReview = {
43
+ /** The case reviewed: `starterKey` of its input. */
44
+ case: string;
45
+ /** The answer they confirmed, in the suite's answer shape. */
46
+ label: unknown;
47
+ level: ReviewLevel;
48
+ /** Who reviewed it, shown with the answer. */
49
+ by: string;
50
+ /** What qualifies them ("suite author", "crisis line counselor"). */
51
+ credential: string;
52
+ /** The day they reviewed it, as YYYY-MM-DD. */
53
+ at: string;
54
+ };
55
+
56
+ /**
57
+ * A short, stable key for a starter case: a hash of its input. Reviews
58
+ * name cases by it, and `importStarters` uses it as the case's id, so a
59
+ * rerun skips cases already added.
60
+ *
61
+ * @param input - The starter case's input.
62
+ */
63
+ export function starterKey(input: unknown): string {
64
+ // FNV-1a: the core stays free of node:crypto; this only names rows.
65
+ let h = 0x811c9dc5;
66
+ for (const ch of stableJson(input)) {
67
+ h ^= ch.charCodeAt(0);
68
+ h = Math.imul(h, 0x01000193) >>> 0;
69
+ }
70
+ return h.toString(16).padStart(8, "0");
71
+ }
72
+
73
+ /**
74
+ * Whether an answer's confirmation shipped with the suite (author or
75
+ * expert reviewed) rather than coming from someone in the app.
76
+ *
77
+ * @param label - The answer, or just its rater role.
78
+ */
79
+ export function isShippedReview(label: { raterRole: string }): boolean {
80
+ return (
81
+ label.raterRole === AUTHOR_REVIEWED || label.raterRole === EXPERT_REVIEWED
82
+ );
83
+ }
84
+
85
+ /** A review's day, or null when it isn't a real YYYY-MM-DD date. */
86
+ function dayOf(at: string): Date | null {
87
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(at)) return null;
88
+ const d = new Date(`${at}T00:00:00Z`);
89
+ return Number.isNaN(d.getTime()) || d.toISOString().slice(0, 10) !== at
90
+ ? null
91
+ : d;
92
+ }
93
+
94
+ /** The suite's answer, parsed, as stable text to compare; null if it doesn't fit. */
95
+ function answerText(suite: AnySuite, label: unknown): string | null {
96
+ const parsed = suite.labelValue.safeParse(label);
97
+ return parsed.success ? stableJson(parsed.data) : null;
98
+ }
99
+
100
+ /**
101
+ * What's wrong with one review against the suite's starters, in plain
102
+ * sentences; empty when it counts.
103
+ */
104
+ function problemsOf(
105
+ suite: AnySuite,
106
+ r: ShippedReview,
107
+ answers: Map<string, string | null>,
108
+ now: Date,
109
+ ): string[] {
110
+ const out: string[] = [];
111
+ const name = `${suite.key}: the review of case ${r.case}`;
112
+ if (!answers.has(r.case))
113
+ out.push(
114
+ `${name} matches no starter case; its input changed or it was removed.`,
115
+ );
116
+ else {
117
+ const mine = answerText(suite, r.label);
118
+ if (mine === null)
119
+ out.push(`${name} has an answer that doesn't fit the schema.`);
120
+ else if (mine !== answers.get(r.case))
121
+ out.push(`${name} confirms a different answer than the case has now.`);
122
+ }
123
+ if (!r.by.trim()) out.push(`${name} doesn't say who reviewed it.`);
124
+ if (!r.credential.trim())
125
+ out.push(`${name} doesn't say what qualifies the reviewer.`);
126
+ const day = dayOf(r.at);
127
+ if (!day) out.push(`${name} has no date as YYYY-MM-DD.`);
128
+ // A day starts up to 14 hours before UTC's somewhere (UTC+14), so a
129
+ // review dated today counts wherever today is.
130
+ else if (+day > +now + 14 * 3_600_000)
131
+ out.push(`${name} is dated in the future.`);
132
+ return out;
133
+ }
134
+
135
+ /** Each starter's key and its input as stable text. */
136
+ function starterInputs(suite: AnySuite): Map<string, string> {
137
+ return new Map(
138
+ (suite.starter ?? []).map((s) => [
139
+ starterKey(s.input),
140
+ stableJson(s.input),
141
+ ]),
142
+ );
143
+ }
144
+
145
+ /** Each starter's key and its answer as stable text. */
146
+ function starterAnswers(suite: AnySuite): Map<string, string | null> {
147
+ return new Map(
148
+ (suite.starter ?? []).map((s) => [
149
+ starterKey(s.input),
150
+ answerText(suite, s.label),
151
+ ]),
152
+ );
153
+ }
154
+
155
+ /**
156
+ * What's wrong with a suite's shipped reviews, in plain sentences; empty
157
+ * when every one counts. A review that matches no starter, confirms a
158
+ * different answer than the case has now, or is missing who, what
159
+ * qualifies them, or when, is a problem: `suiteContractProblems` reports
160
+ * these so a stale review is fixed, not silently ignored.
161
+ *
162
+ * @param suite - The suite whose `reviews` to check.
163
+ * @param now - Today; reviews dated after it are a problem.
164
+ */
165
+ export function reviewProblems(
166
+ suite: AnySuite,
167
+ now: Date = new Date(),
168
+ ): string[] {
169
+ const answers = starterAnswers(suite);
170
+ const out: string[] = [];
171
+ const seen = new Set<string>();
172
+ for (const r of suite.reviews ?? []) {
173
+ out.push(...problemsOf(suite, r, answers, now));
174
+ const id = `${r.case}|${r.level}|${r.by.trim()}`;
175
+ if (seen.has(id))
176
+ out.push(
177
+ `${suite.key}: case ${r.case} has the same ${r.level.toLowerCase()} review twice.`,
178
+ );
179
+ seen.add(id);
180
+ }
181
+ return out;
182
+ }
183
+
184
+ /**
185
+ * The confirmed answer a review adds to a case.
186
+ *
187
+ * @param suite - The suite the review shipped with.
188
+ * @param r - A review that counts (see `reviewProblems`).
189
+ */
190
+ export function reviewedLabel(suite: AnySuite, r: ShippedReview): NewLabel {
191
+ const who = r.level === "EXPERT" ? "an expert" : "the suite's author";
192
+ return {
193
+ kind: "EXPECTED",
194
+ status: "CONFIRMED",
195
+ value: suite.labelValue.parse(r.label),
196
+ raterRole: ROLE[r.level],
197
+ raterId: r.by.trim(),
198
+ note: `Reviewed by ${who} for the ${suite.label} suite: ${r.by.trim()} (${r.credential.trim()}) confirmed it on ${r.at}.`,
199
+ };
200
+ }
201
+
202
+ /** What adding a suite's shipped reviews did. */
203
+ export type ReviewResult = {
204
+ /** Confirmed answers added from the suite's reviews. */
205
+ reviewed: number;
206
+ /**
207
+ * Cases whose own confirmed or provisional answer, from someone in the
208
+ * app, differs from a shipped review. The app's answer stays; these are
209
+ * listed for a person to look at.
210
+ */
211
+ disagree: { caseId: string; review: ShippedReview }[];
212
+ /**
213
+ * Cases whose stored input isn't the one reviewed (the suite's leak
214
+ * check changed it when it was added), so their reviews were left out.
215
+ */
216
+ notSeen: { caseId: string; review: ShippedReview }[];
217
+ };
218
+
219
+ /** The newest answer someone in the app put to use, if any. */
220
+ function appAnswer(c: CaseRecord) {
221
+ return [...c.labels]
222
+ .filter(
223
+ (l) =>
224
+ (l.status === "CONFIRMED" || l.status === "PROVISIONAL") &&
225
+ !isShippedReview(l),
226
+ )
227
+ .sort((a, b) => +b.updatedAt - +a.updatedAt)[0];
228
+ }
229
+
230
+ /**
231
+ * Adds a suite's shipped reviews to its starter cases already in the
232
+ * store, as confirmed answers. Safe to run again: a review already added
233
+ * is skipped, and one re-signed with a new answer (after the case's
234
+ * answer changed) is added as the newer confirmation. A case whose own
235
+ * confirmed or provisional answer came from someone in the app keeps it:
236
+ * the review is never added over it, and a different answer is reported
237
+ * in `disagree`. A case whose stored input isn't the one reviewed (a leak
238
+ * check changed it) gets no review and is reported in `notSeen`. Reviews
239
+ * that don't count (see `reviewProblems`) are left out. `importStarters`
240
+ * runs it.
241
+ *
242
+ * @param store - Where the suite's cases are.
243
+ * @param suite - The suite whose `reviews` to add.
244
+ * @param source - The `sourceRef` prefix starter cases were added under.
245
+ * @param now - Today; reviews dated after it are left out.
246
+ */
247
+ export async function addShippedReviews(
248
+ store: EvalStore,
249
+ suite: AnySuite,
250
+ source: string,
251
+ now: Date = new Date(),
252
+ ): Promise<ReviewResult> {
253
+ const result: ReviewResult = { reviewed: 0, disagree: [], notSeen: [] };
254
+ const reviews = suite.reviews ?? [];
255
+ if (!reviews.length) return result;
256
+ const answers = starterAnswers(suite);
257
+ const inputs = starterInputs(suite);
258
+ const counting = reviews.filter(
259
+ (r) => problemsOf(suite, r, answers, now).length === 0,
260
+ );
261
+ const byRef = new Map(
262
+ (await store.listCases(suite.key)).map((c) => [c.sourceRef, c]),
263
+ );
264
+ // Reviews added in this pass, by case: a store may or may not hand back
265
+ // the same case objects, so don't rely on them updating.
266
+ const added = new Set<string>();
267
+ for (const r of counting) {
268
+ const c = byRef.get(`${source}#${r.case}`);
269
+ if (!c) continue;
270
+ if (stableJson(c.input) !== inputs.get(r.case)) {
271
+ result.notSeen.push({ caseId: c.id, review: r });
272
+ continue;
273
+ }
274
+ const label = reviewedLabel(suite, r);
275
+ const value = stableJson(label.value);
276
+ const id = `${c.id}|${label.raterRole}|${label.raterId ?? ""}|${value}`;
277
+ if (
278
+ added.has(id) ||
279
+ c.labels.some(
280
+ (l) =>
281
+ l.raterRole === label.raterRole &&
282
+ l.raterId === label.raterId &&
283
+ stableJson(l.value) === value,
284
+ )
285
+ )
286
+ continue;
287
+ const theirs = appAnswer(c);
288
+ if (theirs) {
289
+ if (stableJson(theirs.value) !== value)
290
+ result.disagree.push({ caseId: c.id, review: r });
291
+ continue;
292
+ }
293
+ await store.addLabel(c.id, label);
294
+ added.add(id);
295
+ if (c.status === "DRAFT" && !added.has(c.id)) {
296
+ await store.setCaseStatus(c.id, "ACTIVE");
297
+ added.add(c.id);
298
+ }
299
+ result.reviewed += 1;
300
+ }
301
+ return result;
302
+ }
303
+
304
+ /** One row of a review sheet: a starter case for a reviewer to mark. */
305
+ export type ReviewSheetRow = {
306
+ /** The case: `starterKey` of its input. */
307
+ case: string;
308
+ /** The case's title, as the pages show it. */
309
+ title: string;
310
+ /** The whole input, so the reviewer sees what the model sees. */
311
+ input: string;
312
+ /** The answer to confirm, as stable JSON. */
313
+ answer: string;
314
+ };
315
+
316
+ /**
317
+ * A suite's starter cases as rows for a reviewer to mark, in the order
318
+ * the suite lists them. `reviewsFromSheet` turns the rows they confirm
319
+ * into shipped reviews.
320
+ *
321
+ * @param suite - The suite whose `starter` cases to list.
322
+ */
323
+ export function reviewSheet(suite: AnySuite): ReviewSheetRow[] {
324
+ return (suite.starter ?? []).map((s) => {
325
+ const input = suite.input.parse(s.input);
326
+ return {
327
+ case: starterKey(s.input),
328
+ title: suite.title(input),
329
+ input: suite.describe?.(input) ?? stableJson(s.input),
330
+ answer: stableJson(s.label),
331
+ };
332
+ });
333
+ }
334
+
335
+ /** Who reviewed a sheet, for every review it makes. */
336
+ export type Reviewer = Pick<
337
+ ShippedReview,
338
+ "level" | "by" | "credential" | "at"
339
+ >;
340
+
341
+ /** Marks that confirm a row of a review sheet. */
342
+ const CONFIRMS = new Set(["y", "yes", "ok", "confirm", "confirmed"]);
343
+
344
+ /**
345
+ * Turns a marked review sheet into shipped reviews: one for each row the
346
+ * reviewer confirmed ("yes", "y", "ok"), of the case's answer as it is
347
+ * now. Rows left blank are left out. A row naming a case the suite
348
+ * doesn't have, marked anything else, or showing an answer other than the
349
+ * case's answer now (it changed after the sheet was made) stops it: a
350
+ * case whose answer should change is edited in the suite first, then
351
+ * reviewed again on a new sheet.
352
+ *
353
+ * @param suite - The suite the sheet was made from.
354
+ * @param rows - Each row's case, the reviewer's mark, and the answer the
355
+ * sheet showed them (from `reviewSheet`), when the sheet kept it.
356
+ * @param reviewer - Who reviewed it, what qualifies them, and when.
357
+ * @returns The reviews, in the suite's order.
358
+ * @throws When a row names an unknown case or has an unknown mark, or
359
+ * the reviewer is missing who, what qualifies them, or a date.
360
+ */
361
+ export function reviewsFromSheet(
362
+ suite: AnySuite,
363
+ rows: readonly { case: string; confirm: string; answer?: string }[],
364
+ reviewer: Reviewer,
365
+ ): ShippedReview[] {
366
+ const problems: string[] = [];
367
+ if (!reviewer.by.trim()) problems.push("no reviewer (--by)");
368
+ if (!reviewer.credential.trim())
369
+ problems.push("no credential (--credential)");
370
+ if (!dayOf(reviewer.at)) problems.push("no date as YYYY-MM-DD (--at)");
371
+ const starters = new Map(
372
+ (suite.starter ?? []).map((s) => [starterKey(s.input), s.label]),
373
+ );
374
+ const confirmed = new Set<string>();
375
+ for (const r of rows) {
376
+ const mark = r.confirm.trim().toLowerCase();
377
+ if (!starters.has(r.case))
378
+ problems.push(`case ${r.case} isn't one of ${suite.key}'s starters`);
379
+ else if (
380
+ CONFIRMS.has(mark) &&
381
+ r.answer !== undefined &&
382
+ r.answer.trim() !== stableJson(starters.get(r.case))
383
+ )
384
+ problems.push(
385
+ `case ${r.case}'s answer changed after the sheet was made; make a new sheet`,
386
+ );
387
+ else if (CONFIRMS.has(mark)) confirmed.add(r.case);
388
+ else if (mark)
389
+ problems.push(
390
+ `case ${r.case} is marked "${r.confirm.trim()}"; mark "yes" or leave it blank`,
391
+ );
392
+ }
393
+ if (problems.length)
394
+ throw new Error(`The sheet can't be signed: ${problems.join("; ")}.`);
395
+ return [...starters].flatMap(([key, label]) =>
396
+ confirmed.has(key)
397
+ ? [
398
+ {
399
+ case: key,
400
+ label,
401
+ level: reviewer.level,
402
+ by: reviewer.by.trim(),
403
+ credential: reviewer.credential.trim(),
404
+ at: reviewer.at,
405
+ },
406
+ ]
407
+ : [],
408
+ );
409
+ }
410
+
411
+ /**
412
+ * A suite's reviews with one reviewer's replaced by a new set: everyone
413
+ * else's stay as they were, and theirs (same name and level) are swapped
414
+ * for `next`, so signing a sheet again never duplicates a review.
415
+ *
416
+ * @param existing - The reviews the suite ships now.
417
+ * @param next - The reviews from the newly signed sheet.
418
+ * @param reviewer - Whose reviews `next` replaces.
419
+ */
420
+ export function mergeReviews(
421
+ existing: readonly ShippedReview[],
422
+ next: readonly ShippedReview[],
423
+ reviewer: Pick<Reviewer, "level" | "by">,
424
+ ): ShippedReview[] {
425
+ const theirs = (r: ShippedReview) =>
426
+ r.level === reviewer.level && r.by.trim() === reviewer.by.trim();
427
+ return [...existing.filter((r) => !theirs(r)), ...next];
428
+ }
package/src/runner.ts CHANGED
@@ -27,6 +27,10 @@ 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";
30
34
  import {
31
35
  draftFromActivity as draftCases,
32
36
  type ActivityDraftResult,
@@ -72,6 +76,13 @@ export type RunnerOptions = {
72
76
  * marks older tests out of date.
73
77
  */
74
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[]>;
75
86
  /**
76
87
  * The live reasoning setting for an operation; null: the model's own.
77
88
  * Defaults to the route's, when `route` is given.
@@ -866,6 +877,35 @@ export function createRunner(opts: RunnerOptions) {
866
877
  };
867
878
  }
868
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
+ );
907
+ }
908
+
869
909
  /**
870
910
  * The model board for one suite: every model the operation can use, with
871
911
  * its latest test on every case in use, and how it compares with the
@@ -1107,6 +1147,7 @@ export function createRunner(opts: RunnerOptions) {
1107
1147
  rescoreRecent,
1108
1148
  stopStuckRuns,
1109
1149
  compare,
1150
+ casesInInstructions: casesInInstructionsFor,
1110
1151
  };
1111
1152
  }
1112
1153