@crowandraven/evalkeeper 0.8.0 → 0.10.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 (92) hide show
  1. package/dist/cli/addPages.js +1 -1
  2. package/dist/cli/addPages.js.map +1 -1
  3. package/dist/feedback.d.ts +3 -1
  4. package/dist/feedback.js +3 -1
  5. package/dist/feedback.js.map +1 -1
  6. package/dist/glossary.d.ts +5 -0
  7. package/dist/glossary.js +5 -0
  8. package/dist/glossary.js.map +1 -1
  9. package/dist/health.d.ts +4 -1
  10. package/dist/health.js +4 -2
  11. package/dist/health.js.map +1 -1
  12. package/dist/importCases.d.ts +15 -4
  13. package/dist/importCases.js +20 -18
  14. package/dist/importCases.js.map +1 -1
  15. package/dist/index.d.ts +1 -0
  16. package/dist/index.js +1 -0
  17. package/dist/index.js.map +1 -1
  18. package/dist/reviews.d.ts +172 -0
  19. package/dist/reviews.js +294 -0
  20. package/dist/reviews.js.map +1 -0
  21. package/dist/runner.d.ts +14 -1
  22. package/dist/runner.js +10 -0
  23. package/dist/runner.js.map +1 -1
  24. package/dist/suggest.d.ts +52 -2
  25. package/dist/suggest.js +101 -8
  26. package/dist/suggest.js.map +1 -1
  27. package/dist/suiteContract.d.ts +3 -2
  28. package/dist/suiteContract.js +5 -2
  29. package/dist/suiteContract.js.map +1 -1
  30. package/dist/suites/attackImport.d.ts +99 -0
  31. package/dist/suites/attackImport.js +283 -0
  32. package/dist/suites/attackImport.js.map +1 -0
  33. package/dist/suites/crisisRisk.d.ts +9 -2
  34. package/dist/suites/crisisRisk.js +8 -3
  35. package/dist/suites/crisisRisk.js.map +1 -1
  36. package/dist/suites/crisisRiskCases.d.ts +4 -3
  37. package/dist/suites/crisisRiskCases.js +4 -3
  38. package/dist/suites/crisisRiskCases.js.map +1 -1
  39. package/dist/suites/crisisRiskReviews.d.ts +15 -0
  40. package/dist/suites/crisisRiskReviews.js +926 -0
  41. package/dist/suites/crisisRiskReviews.js.map +1 -0
  42. package/dist/suites/hopelessness.d.ts +9 -2
  43. package/dist/suites/hopelessness.js +8 -5
  44. package/dist/suites/hopelessness.js.map +1 -1
  45. package/dist/suites/hopelessnessCases.d.ts +3 -2
  46. package/dist/suites/hopelessnessCases.js +3 -2
  47. package/dist/suites/hopelessnessCases.js.map +1 -1
  48. package/dist/suites/hopelessnessReviews.d.ts +15 -0
  49. package/dist/suites/hopelessnessReviews.js +1080 -0
  50. package/dist/suites/hopelessnessReviews.js.map +1 -0
  51. package/dist/suites/index.d.ts +5 -0
  52. package/dist/suites/index.js +5 -0
  53. package/dist/suites/index.js.map +1 -1
  54. package/dist/suites/injection.d.ts +162 -0
  55. package/dist/suites/injection.js +331 -0
  56. package/dist/suites/injection.js.map +1 -0
  57. package/dist/suites/injectionAttacks.d.ts +3 -0
  58. package/dist/suites/injectionAttacks.js +34 -0
  59. package/dist/suites/injectionAttacks.js.map +1 -0
  60. package/dist/types.d.ts +100 -2
  61. package/dist/types.js +106 -11
  62. package/dist/types.js.map +1 -1
  63. package/package.json +1 -1
  64. package/src/cli/addPages.ts +1 -1
  65. package/src/feedback.ts +3 -1
  66. package/src/glossary.ts +10 -0
  67. package/src/health.ts +4 -2
  68. package/src/importCases.ts +21 -20
  69. package/src/index.ts +1 -0
  70. package/src/reviews.ts +428 -0
  71. package/src/runner.ts +15 -1
  72. package/src/suggest.ts +145 -13
  73. package/src/suiteContract.ts +5 -2
  74. package/src/suites/attackImport.ts +327 -0
  75. package/src/suites/crisisRisk.ts +15 -3
  76. package/src/suites/crisisRiskCases.ts +4 -3
  77. package/src/suites/crisisRiskReviews.ts +927 -0
  78. package/src/suites/hopelessness.ts +15 -5
  79. package/src/suites/hopelessnessCases.ts +3 -2
  80. package/src/suites/hopelessnessReviews.ts +1081 -0
  81. package/src/suites/index.ts +5 -0
  82. package/src/suites/injection.ts +463 -0
  83. package/src/suites/injectionAttacks.ts +136 -0
  84. package/src/types.ts +169 -17
  85. package/starter/index.ts +11 -0
  86. package/templates/app/evals/[suite]/page.tsx +185 -32
  87. package/templates/app/evals/[suite]/rate/page.tsx +14 -4
  88. package/templates/app/evals/feedback/page.tsx +3 -1
  89. package/templates/app/evals/page.tsx +44 -5
  90. package/templates/components/evalkeeper/AnswerKey.tsx +35 -6
  91. package/templates/components/evalkeeper/Fields.tsx +49 -5
  92. package/templates/lib/evalkeeper/actions.ts +39 -15
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
@@ -38,7 +38,7 @@ import {
38
38
  import { SCHEDULED } from "./weekly.js";
39
39
  import { confirmedLabel, isProvisional } from "./labels.js";
40
40
  export { confirmedLabel, isProvisional };
41
- import type { AnySuite, CheckResult } from "./types.js";
41
+ import { injectionSuitesOf, type AnySuite, type CheckResult } from "./types.js";
42
42
  import { at } from "./util.js";
43
43
  import { mustGet } from "./util.js";
44
44
 
@@ -1132,11 +1132,25 @@ export function createRunner(opts: RunnerOptions) {
1132
1132
  };
1133
1133
  }
1134
1134
 
1135
+ /**
1136
+ * The boards of the injection suites that attack a suite, for the base
1137
+ * suite's page and its suggestion (`attacksFrom`). Empty when nothing
1138
+ * attacks it.
1139
+ */
1140
+ async function attackBoards(suiteKey: string) {
1141
+ return Promise.all(
1142
+ injectionSuitesOf(opts.suites, suiteOrThrow(suiteKey).key).map((s) =>
1143
+ board(s.key),
1144
+ ),
1145
+ );
1146
+ }
1147
+
1135
1148
  return {
1136
1149
  startDriftCheck,
1137
1150
  runDriftCheck,
1138
1151
  draftFromActivity,
1139
1152
  board,
1153
+ attackBoards,
1140
1154
  suiteOrThrow,
1141
1155
  casesFor,
1142
1156
  estimateRun,
package/src/suggest.ts CHANGED
@@ -20,7 +20,11 @@ import { at } from "./util.js";
20
20
  * Models the provider is retiring are never suggested, and a retiring live
21
21
  * model is replaced by the best-scoring one that isn't. A live model whose
22
22
  * current test has failed answers is tested again, not replaced: it can't
23
- * be compared yet, and a timeout or two isn't a reason to switch. Pure.
23
+ * be compared yet, and a timeout or two isn't a reason to switch. With a
24
+ * feature's injection suites (`attacks`), a model is suggested as live only
25
+ * with a current test against the attacks, and never with more serious
26
+ * mistakes under attack than live; making at least two fewer is a reason
27
+ * to switch on its own. Pure.
24
28
  */
25
29
 
26
30
  /** One model's row, as the suggestion reads it. */
@@ -69,6 +73,71 @@ export type Suggestion<R extends SuggestRow = SuggestRow> = {
69
73
  reasons: string[];
70
74
  };
71
75
 
76
+ /**
77
+ * One injection suite's board, as the suggestion reads it: the same
78
+ * feature attacked, so a model's row there has the same key as on the
79
+ * base suite's board. Build it with `attacksFrom`.
80
+ */
81
+ export type AttackResults = {
82
+ /** The injection suite's label, for the reasons. */
83
+ label: string;
84
+ rows: SuggestRow[];
85
+ checks: CheckDef[];
86
+ };
87
+
88
+ /** What else the suggestion weighs, besides the suite's own board. */
89
+ export type SuggestOptions = {
90
+ /**
91
+ * The feature's injection suites, from `runner.attackBoards(suiteKey)`
92
+ * through `attacksFrom`. Without them, attacks aren't weighed.
93
+ */
94
+ attacks?: AttackResults[];
95
+ };
96
+
97
+ /**
98
+ * Injection suites' boards in the shape `suggest` reads, for its
99
+ * `attacks` option.
100
+ *
101
+ * @param boards - The boards of a feature's injection suites
102
+ * (`runner.attackBoards`).
103
+ * @returns One entry per injection suite.
104
+ */
105
+ export function attacksFrom(
106
+ boards: readonly {
107
+ suite: { label: string; checks: CheckDef[] };
108
+ rows: SuggestRow[];
109
+ }[],
110
+ ): AttackResults[] {
111
+ return boards.map((b) => ({
112
+ label: b.suite.label,
113
+ rows: b.rows,
114
+ checks: b.suite.checks,
115
+ }));
116
+ }
117
+
118
+ /**
119
+ * A model's serious mistakes under attack: its serious mistakes on every
120
+ * injection suite, added up. Null when any of them has no current,
121
+ * complete test of it, so it can't be compared yet; also null with no
122
+ * injection suites.
123
+ *
124
+ * @param key - The model's row key (model and reasoning setting).
125
+ * @param attacks - The feature's injection suites.
126
+ */
127
+ export function attackMistakes(
128
+ key: string,
129
+ attacks: readonly AttackResults[],
130
+ ): number | null {
131
+ if (!attacks.length) return null;
132
+ let total = 0;
133
+ for (const a of attacks) {
134
+ const r = a.rows.find((x) => x.key === key);
135
+ if (!r?.test || r.test.stale || r.test.failedAnswers) return null;
136
+ total += seriousMistakes(r, a.checks);
137
+ }
138
+ return total;
139
+ }
140
+
72
141
  /**
73
142
  * How many serious checks a model's test failed; Infinity without a test.
74
143
  */
@@ -113,7 +182,15 @@ export function suggest<R extends SuggestRow>(
113
182
  priority: SuitePriority = { favor: "quality" },
114
183
  /** Your model catalog: providers (for the fallback) and retirements. */
115
184
  models: ModelCatalog = {},
185
+ /** The feature's injection suites, to weigh attacks too. */
186
+ opts: SuggestOptions = {},
116
187
  ): Suggestion<R> | null {
188
+ const attacks = opts.attacks ?? [];
189
+ const weighAttacks = attacks.length > 0;
190
+ /** Serious mistakes under attack; null when not tested against them. */
191
+ const underAttack = (r: SuggestRow) => attackMistakes(r.key, attacks);
192
+ const attackTested = (r: SuggestRow) =>
193
+ !weighAttacks || underAttack(r) !== null;
117
194
  const provider = (model: string) => models[model]?.provider ?? model;
118
195
  const retiring = (r: SuggestRow) => retiresLabel(models, r.model);
119
196
  const limitMs = priority.maxSeconds ? priority.maxSeconds * 1000 : Infinity;
@@ -162,10 +239,15 @@ export function suggest<R extends SuggestRow>(
162
239
  );
163
240
  } else if (!live) {
164
241
  if (!liveable.length) return null;
242
+ // Only models tested against the attacks, unless none are.
243
+ const known = liveable.filter(attackTested);
165
244
  next = at(
166
- [...liveable].sort(
245
+ [...(known.length ? known : liveable)].sort(
167
246
  (a, b) =>
168
- rate(b) - rate(a) || serious(a) - serious(b) || cost(a) - cost(b),
247
+ rate(b) - rate(a) ||
248
+ serious(a) - serious(b) ||
249
+ (underAttack(a) ?? 0) - (underAttack(b) ?? 0) ||
250
+ cost(a) - cost(b),
169
251
  ),
170
252
  0,
171
253
  );
@@ -174,13 +256,27 @@ export function suggest<R extends SuggestRow>(
174
256
  ? `${liveRetires && liveRow ? `${liveRow.label} retires in ${liveRetires}.` : liveSlow} ${next.label} scores highest of the rest (${pct(rate(next))}) with ${mistakes(serious(next))}.`
175
257
  : `${next.label} scores highest (${pct(rate(next))}) with ${mistakes(serious(next))}. The live model has no up-to-date test to compare with.`,
176
258
  );
259
+ if (!attackTested(next))
260
+ reasons.push(
261
+ `No model has an up-to-date test against the attacks: test ${next.label} on them before relying on it.`,
262
+ );
177
263
  } else {
264
+ // At least two fewer serious mistakes under attack, as accurate or more.
265
+ const attackReason = (r: R): string | null => {
266
+ const ra = underAttack(r);
267
+ const la = underAttack(live);
268
+ return ra !== null && la !== null && ra <= la - 2 && rate(r) >= rate(live)
269
+ ? `${r.label} makes fewer serious mistakes under attack than ${live.label} (${ra} against ${la}), and scores at least as well (${pct(rate(r))} against ${pct(rate(live))}).`
270
+ : null;
271
+ };
178
272
  const why = (r: R): string | null => {
179
273
  if (rate(r) < rate(live)) return trade(r);
180
274
  if (r.vsLive === "BETTER")
181
275
  return `${r.label} is clearly more accurate than ${live.label}: ${pct(rate(r))} against ${pct(rate(live))}.`;
182
276
  if (serious(r) <= serious(live) - 2)
183
277
  return `${r.label} makes fewer serious mistakes than ${live.label} (${serious(r)} against ${serious(live)}), and scores at least as well (${pct(rate(r))} against ${pct(rate(live))}).`;
278
+ const byAttacks = attackReason(r);
279
+ if (byAttacks) return byAttacks;
184
280
  if (priority.favor === "cost" && clearlyLess(cost(r), cost(live)))
185
281
  return `${r.label} scores at least as well as ${live.label} (${pct(rate(r))} against ${pct(rate(live))}) at ${Math.round((1 - cost(r) / cost(live)) * 100)}% less per answer.`;
186
282
  if (priority.favor === "speed" && clearlyLess(ms(r), ms(live)))
@@ -204,14 +300,23 @@ export function suggest<R extends SuggestRow>(
204
300
  return `${close}, and answers in ${(ms(r) / 1000).toFixed(1)}s against ${(ms(live) / 1000).toFixed(1)}s. This suite favors speed.`;
205
301
  return null;
206
302
  };
303
+ // Under attack: tested, and no more serious mistakes than live (when
304
+ // live has a test to compare with).
305
+ const liveAttack = underAttack(live);
306
+ const safeUnderAttack = (r: R) => {
307
+ const a = underAttack(r);
308
+ return (
309
+ !weighAttacks ||
310
+ (a !== null && (liveAttack === null || a <= liveAttack))
311
+ );
312
+ };
313
+ const qualifies = (r: R) =>
314
+ !r.live &&
315
+ r.vsLive !== "WORSE" &&
316
+ serious(r) <= serious(live) &&
317
+ why(r) !== null;
207
318
  const candidates = liveable
208
- .filter(
209
- (r) =>
210
- !r.live &&
211
- r.vsLive !== "WORSE" &&
212
- serious(r) <= serious(live) &&
213
- why(r),
214
- )
319
+ .filter((r) => qualifies(r) && safeUnderAttack(r))
215
320
  .sort(
216
321
  (a, b) =>
217
322
  Number(b.vsLive === "BETTER") - Number(a.vsLive === "BETTER") ||
@@ -227,11 +332,28 @@ export function suggest<R extends SuggestRow>(
227
332
  next = at(candidates, 0);
228
333
  const reason = why(next);
229
334
  if (reason) reasons.push(reason);
335
+ const a = underAttack(next);
336
+ if (a !== null && reason !== attackReason(next))
337
+ reasons.push(
338
+ liveAttack === null
339
+ ? `Under attack, ${next.label} makes ${mistakes(a)}. ${live.label} has no up-to-date test against the attacks to compare with.`
340
+ : `Under attack, ${next.label} makes ${mistakes(a)}, against ${liveAttack} for ${live.label}.`,
341
+ );
230
342
  } else {
231
343
  next = live;
232
344
  reasons.push(
233
345
  `Keep ${live.label}: no other model is safely better on these cases.`,
234
346
  );
347
+ // Would have been suggested, but for the attacks.
348
+ const held = liveable.find((r) => qualifies(r) && !safeUnderAttack(r));
349
+ if (held) {
350
+ const a = underAttack(held);
351
+ reasons.push(
352
+ a === null
353
+ ? `${held.label} would otherwise qualify, but it has no up-to-date test against the attacks. Test it on ${at(attacks, 0).label}.`
354
+ : `${held.label} would otherwise qualify, but it makes more serious mistakes under attack (${a} against ${liveAttack ?? 0}).`,
355
+ );
356
+ }
235
357
  // The one to watch: scored higher, but not by enough to tell.
236
358
  const watch = tested
237
359
  .filter((r) => !r.live && rate(r) > rate(live))
@@ -256,12 +378,22 @@ export function suggest<R extends SuggestRow>(
256
378
  )
257
379
  .sort(
258
380
  (a, b) =>
259
- rate(b) - rate(a) || serious(a) - serious(b) || cost(a) - cost(b),
381
+ rate(b) - rate(a) ||
382
+ serious(a) - serious(b) ||
383
+ (underAttack(a) ?? Infinity) - (underAttack(b) ?? Infinity) ||
384
+ cost(a) - cost(b),
260
385
  )[0] ?? null;
261
- if (fallback)
386
+ if (fallback) {
387
+ const a = underAttack(fallback);
388
+ const attacked = !weighAttacks
389
+ ? ""
390
+ : a === null
391
+ ? "; not tested against the attacks"
392
+ : `; ${mistakes(a)} under attack`;
262
393
  reasons.push(
263
- `Fallback: ${fallback.label} is the most accurate from another provider (${pct(rate(fallback))}, ${mistakes(serious(fallback))}).`,
394
+ `Fallback: ${fallback.label} is the most accurate from another provider (${pct(rate(fallback))}, ${mistakes(serious(fallback))}${attacked}).`,
264
395
  );
396
+ }
265
397
 
266
398
  const keepLive = next.live;
267
399
  const retestLive = Boolean(liveFailed);