@crowandraven/evalkeeper 0.5.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/README.md +16 -0
  2. package/dist/activity.d.ts +58 -0
  3. package/dist/activity.js +125 -0
  4. package/dist/activity.js.map +1 -0
  5. package/dist/assertExpect.d.ts +52 -0
  6. package/dist/assertExpect.js +104 -0
  7. package/dist/assertExpect.js.map +1 -0
  8. package/dist/blind.d.ts +79 -0
  9. package/dist/blind.js +113 -0
  10. package/dist/blind.js.map +1 -0
  11. package/dist/cli/addPages.d.ts +6 -1
  12. package/dist/cli/addPages.js +19 -4
  13. package/dist/cli/addPages.js.map +1 -1
  14. package/dist/cli/main.d.ts +1 -1
  15. package/dist/cli/main.js +4 -3
  16. package/dist/cli/main.js.map +1 -1
  17. package/dist/compare.d.ts +38 -0
  18. package/dist/compare.js +62 -0
  19. package/dist/compare.js.map +1 -1
  20. package/dist/decisions.js +8 -0
  21. package/dist/decisions.js.map +1 -1
  22. package/dist/feedback.d.ts +17 -2
  23. package/dist/feedback.js +13 -2
  24. package/dist/feedback.js.map +1 -1
  25. package/dist/glossary.d.ts +22 -0
  26. package/dist/glossary.js +22 -0
  27. package/dist/glossary.js.map +1 -1
  28. package/dist/health.js +5 -3
  29. package/dist/health.js.map +1 -1
  30. package/dist/importCases.d.ts +76 -5
  31. package/dist/importCases.js +114 -14
  32. package/dist/importCases.js.map +1 -1
  33. package/dist/inInstructions.d.ts +47 -0
  34. package/dist/inInstructions.js +95 -0
  35. package/dist/inInstructions.js.map +1 -0
  36. package/dist/index.d.ts +5 -0
  37. package/dist/index.js +5 -0
  38. package/dist/index.js.map +1 -1
  39. package/dist/memoryStore.js +3 -1
  40. package/dist/memoryStore.js.map +1 -1
  41. package/dist/readCheck.d.ts +116 -0
  42. package/dist/readCheck.js +321 -0
  43. package/dist/readCheck.js.map +1 -0
  44. package/dist/runner.d.ts +16 -0
  45. package/dist/runner.js +51 -3
  46. package/dist/runner.js.map +1 -1
  47. package/dist/settings.d.ts +81 -3
  48. package/dist/settings.js +160 -23
  49. package/dist/settings.js.map +1 -1
  50. package/dist/store.d.ts +10 -3
  51. package/dist/suggest.d.ts +10 -1
  52. package/dist/suggest.js +22 -4
  53. package/dist/suggest.js.map +1 -1
  54. package/dist/suiteContract.d.ts +23 -0
  55. package/dist/suiteContract.js +106 -0
  56. package/dist/suiteContract.js.map +1 -0
  57. package/dist/suites/crisisRisk.d.ts +83 -0
  58. package/dist/suites/crisisRisk.js +176 -0
  59. package/dist/suites/crisisRisk.js.map +1 -0
  60. package/dist/suites/crisisRiskCases.d.ts +40 -0
  61. package/dist/suites/crisisRiskCases.js +179 -0
  62. package/dist/suites/crisisRiskCases.js.map +1 -0
  63. package/dist/suites/hopelessness.d.ts +116 -0
  64. package/dist/suites/hopelessness.js +293 -0
  65. package/dist/suites/hopelessness.js.map +1 -0
  66. package/dist/suites/hopelessnessCases.d.ts +61 -0
  67. package/dist/suites/hopelessnessCases.js +242 -0
  68. package/dist/suites/hopelessnessCases.js.map +1 -0
  69. package/dist/suites/index.d.ts +11 -0
  70. package/dist/suites/index.js +12 -0
  71. package/dist/suites/index.js.map +1 -0
  72. package/dist/testing.d.ts +162 -12
  73. package/dist/testing.js +479 -115
  74. package/dist/testing.js.map +1 -1
  75. package/dist/types.d.ts +98 -0
  76. package/dist/types.js +68 -0
  77. package/dist/types.js.map +1 -1
  78. package/dist/weekly.d.ts +21 -3
  79. package/dist/weekly.js +18 -1
  80. package/dist/weekly.js.map +1 -1
  81. package/package.json +5 -1
  82. package/src/activity.ts +154 -0
  83. package/src/assertExpect.ts +168 -0
  84. package/src/blind.ts +138 -0
  85. package/src/cli/addPages.ts +20 -4
  86. package/src/cli/main.ts +4 -3
  87. package/src/compare.ts +85 -0
  88. package/src/decisions.ts +10 -0
  89. package/src/feedback.ts +20 -2
  90. package/src/glossary.ts +40 -0
  91. package/src/health.ts +5 -3
  92. package/src/importCases.ts +172 -33
  93. package/src/inInstructions.ts +105 -0
  94. package/src/index.ts +5 -0
  95. package/src/memoryStore.ts +2 -1
  96. package/src/readCheck.ts +458 -0
  97. package/src/runner.ts +74 -4
  98. package/src/settings.ts +192 -26
  99. package/src/store.ts +11 -3
  100. package/src/suggest.ts +33 -4
  101. package/src/suiteContract.ts +147 -0
  102. package/src/suites/crisisRisk.ts +250 -0
  103. package/src/suites/crisisRiskCases.ts +205 -0
  104. package/src/suites/hopelessness.ts +410 -0
  105. package/src/suites/hopelessnessCases.ts +286 -0
  106. package/src/suites/index.ts +11 -0
  107. package/src/testing.ts +646 -121
  108. package/src/types.ts +147 -0
  109. package/src/weekly.ts +39 -3
  110. package/starter/index.ts +8 -0
  111. package/templates/app/evals/[suite]/compare/page.tsx +385 -0
  112. package/templates/app/evals/[suite]/page.tsx +104 -31
  113. package/templates/app/evals/[suite]/rate/page.tsx +143 -0
  114. package/templates/app/evals/[suite]/runs/[runId]/page.tsx +84 -3
  115. package/templates/app/evals/[suite]/side-by-side/page.tsx +320 -0
  116. package/templates/app/evals/feedback/page.tsx +3 -0
  117. package/templates/app/evals/page.tsx +3 -0
  118. package/templates/components/evalkeeper/AnswerKey.tsx +2 -1
  119. package/templates/components/evalkeeper/DisagreementChip.tsx +35 -0
  120. package/templates/components/evalkeeper/ReadableOutput.tsx +97 -0
  121. package/templates/components/evalkeeper/RollBack.tsx +21 -1
  122. package/templates/components/evalkeeper/SettingsHistory.tsx +29 -5
  123. package/templates/components/evalkeeper/WeeklyCheck.tsx +34 -2
  124. package/templates/lib/evalkeeper/actions.ts +68 -4
  125. package/templates/lib/evalkeeper/weekly.ts +27 -4
package/src/settings.ts CHANGED
@@ -47,9 +47,73 @@ export type SettingsVersion = Settings & {
47
47
  * CHANGE: a person changed a setting. PROMOTE: a model was made live or
48
48
  * the fallback from a test, with the test as evidence. ROLLBACK: an
49
49
  * earlier version made live again. DEPLOY: the instructions changed in code
50
- * under the live settings.
50
+ * under the live settings. OUTSIDE: the app's own settings no longer
51
+ * matched the live version (changed by a script, SQL, or another page),
52
+ * recorded as found before the next save (`readActual`). INSTRUCTIONS:
53
+ * instructions edited at runtime (an admin override or guidance injected
54
+ * at call time) changed under the live settings, dated when noticed.
51
55
  */
52
- export type ChangeKind = "CHANGE" | "PROMOTE" | "ROLLBACK" | "DEPLOY";
56
+ export type ChangeKind =
57
+ "CHANGE" | "PROMOTE" | "ROLLBACK" | "DEPLOY" | "OUTSIDE" | "INSTRUCTIONS";
58
+
59
+ /** Every kind of change, in the order they were added. */
60
+ export const CHANGE_KINDS: readonly ChangeKind[] = [
61
+ "CHANGE",
62
+ "PROMOTE",
63
+ "ROLLBACK",
64
+ "DEPLOY",
65
+ "OUTSIDE",
66
+ "INSTRUCTIONS",
67
+ ];
68
+
69
+ /**
70
+ * One instructions hash from its two parts: the instructions in code, and
71
+ * what's edited at runtime (an admin override, guidance injected at call
72
+ * time). Use it for `promptVersion` (the runner's and `createSettings`'s)
73
+ * when part of what the model receives isn't in code, so a test is out of
74
+ * date when either part changes, and `syncPrompt` can tell a deploy
75
+ * (DEPLOY) from a runtime edit (INSTRUCTIONS). With no runtime part, it's
76
+ * the code hash unchanged, so existing hashes stay the same.
77
+ *
78
+ * @param parts - `code`: the hash of the instructions in code. `runtime`:
79
+ * a hash of everything added or replaced at runtime, or null for none.
80
+ * Neither may contain `+`, which joins them.
81
+ *
82
+ * @example
83
+ * ```ts
84
+ * const settings = createSettings({
85
+ * store,
86
+ * defaults,
87
+ * promptVersion: async (op) =>
88
+ * promptVersionOf({
89
+ * code: PROMPT_VERSIONS[op],
90
+ * runtime: await guidanceHash(op), // null when there's none
91
+ * }),
92
+ * });
93
+ * ```
94
+ */
95
+ export function promptVersionOf(parts: {
96
+ code: string;
97
+ runtime: string | null;
98
+ }): string {
99
+ return parts.runtime ? `${parts.code}+${parts.runtime}` : parts.code;
100
+ }
101
+
102
+ /**
103
+ * An instructions hash split back into the parts `promptVersionOf` joined.
104
+ * A hash made without it is all code.
105
+ *
106
+ * @param version - A version's or a test's instructions hash.
107
+ */
108
+ export function splitPromptVersion(version: string): {
109
+ code: string;
110
+ runtime: string | null;
111
+ } {
112
+ const at = version.indexOf("+");
113
+ return at < 0
114
+ ? { code: version, runtime: null }
115
+ : { code: version.slice(0, at), runtime: version.slice(at + 1) || null };
116
+ }
53
117
 
54
118
  /**
55
119
  * One switch in a feature's history: its kind, the versions it went from and to, who, why,
@@ -218,6 +282,22 @@ export type HistoryEntry = SettingsChange & {
218
282
  * reason: "Imported from the admin config",
219
283
  * });
220
284
  * ```
285
+ *
286
+ * When call sites read the app's own settings row (which a script, SQL,
287
+ * or an older admin page can change without a version), pass
288
+ * `readActual`, so a change made there is recorded (OUTSIDE) before the
289
+ * next save, and a rollback can always get back to it:
290
+ *
291
+ * ```ts
292
+ * const settings = createSettings({
293
+ * store,
294
+ * defaults: () => null,
295
+ * readActual: async (op) => {
296
+ * const row = await db.aiConfig.findUnique({ where: { operation: op } });
297
+ * return row ? settingsFromRow(row) : null;
298
+ * },
299
+ * });
300
+ * ```
221
301
  */
222
302
  export function createSettings(opts: {
223
303
  store: SettingsStore;
@@ -227,22 +307,76 @@ export function createSettings(opts: {
227
307
  * `NoSettingsError` until a version is recorded.
228
308
  */
229
309
  defaults: (operation: string) => Settings | null;
230
- /** The instructions' current hash, so a version records what it ran. */
310
+ /**
311
+ * The instructions' current hash, so a version records what it ran. It
312
+ * must cover everything the model receives: the instructions in code,
313
+ * and any admin override or guidance added at call time. Join the two
314
+ * with `promptVersionOf`, so `syncPrompt` can tell a runtime edit from a
315
+ * deploy.
316
+ */
231
317
  promptVersion?: (operation: string) => string | Promise<string>;
318
+ /**
319
+ * The settings the app's call sites actually use, read from wherever
320
+ * they read them (the app's own settings row), or null when it has none.
321
+ * When given, reading or saving settings first compares them with the
322
+ * live version, and records a mismatch as an OUTSIDE version, so the
323
+ * history holds every state that ran. Your save must update or roll back
324
+ * here first and write the row after, or the new settings read as
325
+ * changed outside. Without it, nothing is compared.
326
+ */
327
+ readActual?: (
328
+ operation: string,
329
+ ) => Settings | null | Promise<Settings | null>;
232
330
  }) {
233
331
  const { store } = opts;
234
332
  const prompt = async (op: string) =>
235
333
  opts.promptVersion ? await opts.promptVersion(op) : null;
334
+ const actual = async (op: string) =>
335
+ opts.readActual ? await opts.readActual(op) : null;
236
336
 
237
337
  /**
238
- * The live settings: the live version's, else the default from code.
239
- * Throws `NoSettingsError` when the feature has neither.
338
+ * The live version, after recording the app's actual settings as an
339
+ * OUTSIDE version when they no longer match it (with `readActual`). The
340
+ * new version keeps the live version's instructions hash: only the
341
+ * settings were changed outside.
342
+ */
343
+ async function reconcile(operation: string): Promise<SettingsVersion | null> {
344
+ const live = await store.liveVersion(operation);
345
+ if (!live || !opts.readActual) return live;
346
+ const found = await actual(operation);
347
+ if (!found || sameSettings(settingsOf(live), found)) return live;
348
+ try {
349
+ return await store.switchTo(operation, {
350
+ create: {
351
+ settings: settingsOf(found),
352
+ promptVersion: live.promptVersion,
353
+ },
354
+ kind: "OUTSIDE",
355
+ reason:
356
+ "Changed outside these settings (a script, SQL, or another page); recorded as found",
357
+ by: null,
358
+ expectLive: live.id,
359
+ });
360
+ } catch (e) {
361
+ // Another request recorded it first.
362
+ if (e instanceof SettingsConflict) return store.liveVersion(operation);
363
+ throw e;
364
+ }
365
+ }
366
+
367
+ /**
368
+ * The live settings: the live version's, else the app's actual settings
369
+ * (with `readActual`), else the default from code. With `readActual`, a
370
+ * mismatch with the live version is recorded first (OUTSIDE). Throws
371
+ * `NoSettingsError` when the feature has none of them.
240
372
  */
241
373
  async function current(
242
374
  operation: string,
243
375
  ): Promise<{ settings: Settings; version: SettingsVersion | null }> {
244
- const version = await store.liveVersion(operation);
376
+ const version = await reconcile(operation);
245
377
  if (version) return { settings: settingsOf(version), version };
378
+ const found = await actual(operation);
379
+ if (found) return { settings: settingsOf(found), version };
246
380
  const fallback = opts.defaults(operation);
247
381
  if (!fallback) throw new NoSettingsError(operation);
248
382
  return { settings: fallback, version };
@@ -262,10 +396,12 @@ export function createSettings(opts: {
262
396
 
263
397
  /**
264
398
  * Makes new settings live as a new version. The first change to a
265
- * feature first records its default as version 1, so there's always
266
- * something to roll back to; a feature with no default gets `next` as
267
- * version 1. With `evidence`, it's a promotion. Returns null when
268
- * nothing changed.
399
+ * feature first records what it ran on as version 1 (its default, or
400
+ * the app's actual settings with `readActual`), so there's always
401
+ * something to roll back to; a feature with neither gets `next` as
402
+ * version 1. With `evidence`, it's a promotion. With `readActual`, a
403
+ * mismatch with the live version is recorded first (OUTSIDE). Returns
404
+ * null when nothing changed.
269
405
  */
270
406
  async function change(
271
407
  operation: string,
@@ -273,9 +409,13 @@ export function createSettings(opts: {
273
409
  by: { by: string | null; reason: string | null; evidence?: unknown },
274
410
  ): Promise<SettingsVersion | null> {
275
411
  const promptVersion = await prompt(operation);
276
- let live = await store.liveVersion(operation);
412
+ let live = await reconcile(operation);
277
413
  if (!live) {
278
- const initial = opts.defaults(operation);
414
+ const found = await actual(operation);
415
+ const fallback = opts.defaults(operation);
416
+ const initial = found ?? fallback;
417
+ // Found settings that differ from code were set outside.
418
+ const outside = !!found && !(fallback && sameSettings(fallback, found));
279
419
  if (!initial)
280
420
  return store.switchTo(operation, {
281
421
  create: { settings: settingsOf(next), promptVersion },
@@ -287,9 +427,11 @@ export function createSettings(opts: {
287
427
  });
288
428
  if (sameSettings(initial, next)) return null;
289
429
  live = await store.switchTo(operation, {
290
- create: { settings: initial, promptVersion },
291
- kind: "CHANGE",
292
- reason: "The default from code, before the first change",
430
+ create: { settings: settingsOf(initial), promptVersion },
431
+ kind: outside ? "OUTSIDE" : "CHANGE",
432
+ reason: outside
433
+ ? "The settings in use before the first change, set outside these settings"
434
+ : "The default from code, before the first change",
293
435
  by: null,
294
436
  expectLive: null,
295
437
  });
@@ -318,16 +460,21 @@ export function createSettings(opts: {
318
460
  return change(operation, { ...settings, ...patch }, by);
319
461
  }
320
462
 
321
- /** Makes an earlier version live again. */
463
+ /**
464
+ * Makes an earlier version live again. Only the settings go back: the
465
+ * instructions stay as they are now. With `readActual`, a mismatch with
466
+ * the live version is recorded first (OUTSIDE), so it can be rolled back
467
+ * to later.
468
+ */
322
469
  async function rollBack(
323
470
  operation: string,
324
471
  versionId: string,
325
472
  by: { by: string | null; reason: string },
326
473
  ): Promise<SettingsVersion> {
474
+ const live = await reconcile(operation);
327
475
  const versions = await store.listVersions(operation);
328
476
  const to = versions.find((v) => v.id === versionId);
329
477
  if (!to) throw new Error("No such version for this feature");
330
- const live = await store.liveVersion(operation);
331
478
  if (live?.id === to.id) return to;
332
479
  return store.switchTo(operation, {
333
480
  versionId: to.id,
@@ -339,24 +486,36 @@ export function createSettings(opts: {
339
486
  }
340
487
 
341
488
  /**
342
- * Instructions live in code, so a deploy can change them under live
343
- * settings. When it has, records a version with the same settings and the
344
- * new instructions, so the history says what changed and when. Call it
345
- * where the feature's settings are read (or after each deploy).
489
+ * Instructions can change under live settings: in code by a deploy, or
490
+ * at runtime by an admin override or edited guidance. When they have,
491
+ * records a version with the same settings and the new instructions, so
492
+ * the history says what changed and when: DEPLOY when the code part
493
+ * changed, INSTRUCTIONS when only the runtime part did (see
494
+ * `promptVersionOf`), dated when noticed. Call it where the feature's
495
+ * settings are read (or after each deploy and each runtime edit). With
496
+ * `readActual`, a mismatch with the live settings is recorded first
497
+ * (OUTSIDE).
346
498
  */
347
499
  async function syncPrompt(
348
500
  operation: string,
349
501
  ): Promise<SettingsVersion | null> {
350
- const live = await store.liveVersion(operation);
502
+ const live = await reconcile(operation);
351
503
  const now = await prompt(operation);
352
504
  if (!live || !now || now === live.promptVersion) return live;
505
+ const was = live.promptVersion
506
+ ? splitPromptVersion(live.promptVersion)
507
+ : null;
508
+ const is = splitPromptVersion(now);
509
+ const runtime = was !== null && was.code === is.code;
353
510
  try {
354
511
  return await store.switchTo(operation, {
355
512
  create: { settings: settingsOf(live), promptVersion: now },
356
- kind: "DEPLOY",
357
- reason: live.promptVersion
358
- ? `Instructions changed (${live.promptVersion} → ${now})`
359
- : `Instructions recorded (${now})`,
513
+ kind: runtime ? "INSTRUCTIONS" : "DEPLOY",
514
+ reason: !was
515
+ ? `Instructions recorded (${now})`
516
+ : runtime
517
+ ? runtimeReason(was.runtime, is.runtime)
518
+ : `Instructions changed (${String(live.promptVersion)} → ${now})`,
360
519
  by: null,
361
520
  expectLive: live.id,
362
521
  });
@@ -438,5 +597,12 @@ export function createSettings(opts: {
438
597
  };
439
598
  }
440
599
 
600
+ /** Says how the runtime part of the instructions changed. */
601
+ function runtimeReason(was: string | null, is: string | null): string {
602
+ if (!is) return `Runtime instructions removed (were ${String(was)})`;
603
+ if (!was) return `Runtime instructions added (${is})`;
604
+ return `Instructions edited at runtime (${was} → ${is})`;
605
+ }
606
+
441
607
  /** What createSettings returns. */
442
608
  export type VersionedSettings = ReturnType<typeof createSettings>;
package/src/store.ts CHANGED
@@ -15,9 +15,13 @@ export type EvalSet = "ALL" | "SMOKE" | "DEV" | "TEST";
15
15
  export const EVAL_SETS: EvalSet[] = ["ALL", "SMOKE", "DEV", "TEST"];
16
16
 
17
17
  /**
18
- * Where an answer stands: pending review, confirmed, provisional, or rejected.
18
+ * Where an answer stands: pending review, confirmed, provisional, or
19
+ * rejected. SKIPPED isn't an answer: it marks a case one rater passed on
20
+ * when rating blind (see `skipMark`), with no value, so it's never graded
21
+ * against and doesn't change what tests use.
19
22
  */
20
- export type LabelStatus = "PENDING" | "CONFIRMED" | "PROVISIONAL" | "REJECTED";
23
+ export type LabelStatus =
24
+ "PENDING" | "CONFIRMED" | "PROVISIONAL" | "REJECTED" | "SKIPPED";
21
25
 
22
26
  /**
23
27
  * An answer to a case. EXPECTED is what a good answer looks like; a case's
@@ -154,7 +158,11 @@ export interface EvalStore {
154
158
  opts?: { includeRetired?: boolean },
155
159
  ): Promise<CaseRecord[]>;
156
160
  createCase(data: NewCase): Promise<CaseRecord>;
157
- /** Adds an answer to a case (answers are never overwritten). */
161
+ /**
162
+ * Adds an answer to a case (answers are never overwritten). A SKIPPED
163
+ * mark (value null) is kept the same way, and leaves the case's
164
+ * `updatedAt` alone, so a skip doesn't make tests out of date.
165
+ */
158
166
  addLabel(caseId: string, label: NewLabel): Promise<LabelRecord>;
159
167
  /** Changes an answer's status, e.g. a person confirming a draft. */
160
168
  setLabelStatus(labelId: string, status: LabelStatus): Promise<void>;
package/src/suggest.ts CHANGED
@@ -18,7 +18,9 @@ import { at } from "./util.js";
18
18
  * model is named as one to watch. The fallback is the most accurate model
19
19
  * from another provider; it needn't beat live, it only runs in an outage.
20
20
  * Models the provider is retiring are never suggested, and a retiring live
21
- * model is replaced by the best-scoring one that isn't. Pure.
21
+ * model is replaced by the best-scoring one that isn't. A live model whose
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.
22
24
  */
23
25
 
24
26
  /** One model's row, as the suggestion reads it. */
@@ -43,6 +45,8 @@ export type SuggestRow = {
43
45
  stale: boolean;
44
46
  /** Answers that failed; a test with any is incomplete. */
45
47
  failedAnswers?: number;
48
+ /** The error most failed answers share, for the reason. */
49
+ failureReason?: string | null;
46
50
  } | null;
47
51
  };
48
52
 
@@ -56,6 +60,11 @@ export type Suggestion<R extends SuggestRow = SuggestRow> = {
56
60
  keepLive: boolean;
57
61
  /** Nothing to change at all: live stays and the fallback is already set. */
58
62
  same: boolean;
63
+ /**
64
+ * Live's current test has failed answers: test it again before comparing.
65
+ * Live stays; the reasons say why.
66
+ */
67
+ retestLive: boolean;
59
68
  /** Why, in plain sentences. */
60
69
  reasons: string[];
61
70
  };
@@ -119,7 +128,6 @@ export function suggest<R extends SuggestRow>(
119
128
  !retiring(r) &&
120
129
  !tooSlow(r),
121
130
  );
122
- if (!tested.length) return null;
123
131
  const serious = (r: R) => seriousMistakes(r, checks);
124
132
  const live = tested.find((r) => r.live) ?? null;
125
133
  const reasons: string[] = [];
@@ -129,11 +137,30 @@ export function suggest<R extends SuggestRow>(
129
137
  liveRow?.test && !liveRow.test.stale && tooSlow(liveRow)
130
138
  ? `${liveRow.label} takes ${(ms(liveRow) / 1000).toFixed(1)}s, over this suite's ${priority.maxSeconds}s limit.`
131
139
  : null;
140
+ // Live was tested, but some answers failed (a timeout, say): it can't be
141
+ // compared yet, which isn't a reason to switch (#34).
142
+ const liveFailed =
143
+ liveRow?.test &&
144
+ !liveRow.test.stale &&
145
+ liveRow.test.failedAnswers &&
146
+ !isBaseline(models, liveRow.model) &&
147
+ !liveRetires &&
148
+ !liveSlow
149
+ ? liveRow
150
+ : null;
151
+ if (!tested.length && !liveFailed) return null;
132
152
 
133
153
  // Live: switch only for a real, safe improvement.
134
154
  let next: R;
135
155
  const liveable = tested.filter((r) => !r.fallbackOnly);
136
- if (!live) {
156
+ if (liveFailed?.test) {
157
+ next = liveFailed;
158
+ const n = liveFailed.test.failedAnswers ?? 0;
159
+ const why = liveFailed.test.failureReason;
160
+ reasons.push(
161
+ `Test ${liveFailed.label} again: ${n} of its answers failed on its last test${why ? ` (${why})` : ""}, so it can't be compared yet.`,
162
+ );
163
+ } else if (!live) {
137
164
  if (!liveable.length) return null;
138
165
  next = at(
139
166
  [...liveable].sort(
@@ -237,11 +264,13 @@ export function suggest<R extends SuggestRow>(
237
264
  );
238
265
 
239
266
  const keepLive = next.live;
267
+ const retestLive = Boolean(liveFailed);
240
268
  return {
241
269
  live: next,
242
270
  fallback,
243
271
  keepLive,
244
- same: keepLive && (!fallback || fallback.fallback),
272
+ same: keepLive && !retestLive && (!fallback || fallback.fallback),
273
+ retestLive,
245
274
  reasons,
246
275
  };
247
276
  }
@@ -0,0 +1,147 @@
1
+ import type { z } from "zod";
2
+ import type { AnySuite, FormField } from "./types.js";
3
+
4
+ /** A field help shorter than this says nothing a label doesn't. */
5
+ const MIN_HELP = 10;
6
+
7
+ /** A zod schema's definition, read by name so any copy of zod works. */
8
+ type Def = {
9
+ typeName?: string;
10
+ shape?: () => Record<string, unknown>;
11
+ schema?: z.ZodTypeAny;
12
+ innerType?: z.ZodTypeAny;
13
+ /** A union's options (a plain union's, or a discriminated one's). */
14
+ options?: readonly z.ZodTypeAny[];
15
+ };
16
+
17
+ /**
18
+ * The top-level keys of an object schema, through refinements, optional,
19
+ * nullable, and default wrappers. For a union (`z.union` or
20
+ * `z.discriminatedUnion`), every key that appears in any of its object
21
+ * options, in the order they first appear, so one `fields` list covers
22
+ * them all. Null for any other shape (a string, a list, a union with no
23
+ * object option).
24
+ *
25
+ * @param schema - A suite's input or answer schema.
26
+ */
27
+ export function schemaKeys(schema: z.ZodTypeAny): string[] | null {
28
+ return keysOf(schema, 0);
29
+ }
30
+
31
+ /** Wrappers and unions deeper than this are read as an unknown shape. */
32
+ const MAX_DEPTH = 10;
33
+
34
+ function keysOf(schema: z.ZodTypeAny, depth: number): string[] | null {
35
+ let s: z.ZodTypeAny | undefined = schema;
36
+ for (let i = depth; s && i < MAX_DEPTH; i++) {
37
+ // Trust boundary: zod's own definition object, read by its names.
38
+ const def = s._def as Def;
39
+ if (def.typeName === "ZodObject" && def.shape)
40
+ return Object.keys(def.shape());
41
+ if (
42
+ (def.typeName === "ZodUnion" ||
43
+ def.typeName === "ZodDiscriminatedUnion") &&
44
+ def.options
45
+ )
46
+ return unionKeys(def.options, i + 1);
47
+ s =
48
+ def.typeName === "ZodEffects"
49
+ ? def.schema
50
+ : def.typeName === "ZodOptional" ||
51
+ def.typeName === "ZodNullable" ||
52
+ def.typeName === "ZodDefault"
53
+ ? def.innerType
54
+ : undefined;
55
+ }
56
+ return null;
57
+ }
58
+
59
+ /** Every key of a union's object options; null when none is an object. */
60
+ function unionKeys(
61
+ options: readonly z.ZodTypeAny[],
62
+ depth: number,
63
+ ): string[] | null {
64
+ const keys = new Set<string>();
65
+ let known = false;
66
+ for (const o of options) {
67
+ const k = keysOf(o, depth);
68
+ if (k === null) continue;
69
+ known = true;
70
+ for (const key of k) keys.add(key);
71
+ }
72
+ return known ? [...keys] : null;
73
+ }
74
+
75
+ function fieldProblems(
76
+ suite: string,
77
+ side: "input" | "label",
78
+ keys: string[] | null,
79
+ fields: FormField[],
80
+ ): string[] {
81
+ const out: string[] = [];
82
+ for (const f of fields) {
83
+ if (!f.label.trim())
84
+ out.push(`${suite}: ${side} field "${f.name}" has no label.`);
85
+ if (f.help.trim().length < MIN_HELP)
86
+ out.push(
87
+ `${suite}: ${side} field "${f.name}" needs help that says what it means.`,
88
+ );
89
+ }
90
+ if (keys === null) return out;
91
+ const named = new Set(fields.map((f) => f.name));
92
+ for (const k of keys)
93
+ if (!named.has(k))
94
+ out.push(`${suite}: ${side} field "${k}" has no label and help.`);
95
+ // Help left behind after a rename, or for a field that was removed.
96
+ const has = new Set(keys);
97
+ const what = side === "input" ? "the input" : "the answer";
98
+ for (const f of fields)
99
+ if (!has.has(f.name))
100
+ out.push(
101
+ `${suite}: ${side} field "${f.name}" has help but ${what} has no such field.`,
102
+ );
103
+ return out;
104
+ }
105
+
106
+ /**
107
+ * What's missing for people (and pages) to read a set of suites, in plain
108
+ * sentences; empty when nothing is. Checks that suite keys are unique;
109
+ * every top-level field of each suite's input and answer (every option's,
110
+ * for a union) has a `fields` entry with a label and help, and no entry
111
+ * names a field the schema doesn't have; every check has a description; and starter
112
+ * cases fit the suite's own schemas. Pure; `describeSuiteContract` runs it
113
+ * as tests.
114
+ */
115
+ export function suiteContractProblems(suites: readonly AnySuite[]): string[] {
116
+ const out: string[] = [];
117
+ const seen = new Set<string>();
118
+ for (const suite of suites) {
119
+ const name = suite.key;
120
+ if (seen.has(name)) out.push(`${name}: another suite has the same key.`);
121
+ seen.add(name);
122
+ out.push(
123
+ ...fieldProblems(
124
+ name,
125
+ "input",
126
+ schemaKeys(suite.input),
127
+ suite.fields?.input ?? [],
128
+ ),
129
+ ...fieldProblems(
130
+ name,
131
+ "label",
132
+ schemaKeys(suite.labelValue),
133
+ suite.fields?.label ?? [],
134
+ ),
135
+ );
136
+ for (const c of suite.checks)
137
+ if (!c.description.trim())
138
+ out.push(`${name}: check "${c.key}" has no description.`);
139
+ (suite.starter ?? []).forEach((s, i) => {
140
+ if (!suite.input.safeParse(s.input).success)
141
+ out.push(`${name}: starter ${i + 1}'s input doesn't fit the schema.`);
142
+ if (!suite.labelValue.safeParse(s.label).success)
143
+ out.push(`${name}: starter ${i + 1}'s answer doesn't fit the schema.`);
144
+ });
145
+ }
146
+ return out;
147
+ }