@crowandraven/evalkeeper 0.12.0 → 0.14.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/dist/drafts.d.ts +2 -0
  2. package/dist/drafts.js +3 -1
  3. package/dist/drafts.js.map +1 -1
  4. package/dist/failures.d.ts +16 -0
  5. package/dist/failures.js +40 -0
  6. package/dist/failures.js.map +1 -0
  7. package/dist/glossary.d.ts +4 -2
  8. package/dist/glossary.js +4 -2
  9. package/dist/glossary.js.map +1 -1
  10. package/dist/health.d.ts +35 -2
  11. package/dist/health.js +31 -6
  12. package/dist/health.js.map +1 -1
  13. package/dist/index.d.ts +2 -0
  14. package/dist/index.js +2 -0
  15. package/dist/index.js.map +1 -1
  16. package/dist/legs.d.ts +4 -1
  17. package/dist/legs.js +6 -2
  18. package/dist/legs.js.map +1 -1
  19. package/dist/next/actions.js +79 -15
  20. package/dist/next/actions.js.map +1 -1
  21. package/dist/next/route.js +2 -1
  22. package/dist/next/route.js.map +1 -1
  23. package/dist/next/weekly.d.ts +7 -2
  24. package/dist/next/weekly.js +5 -3
  25. package/dist/next/weekly.js.map +1 -1
  26. package/dist/next/wiring.d.ts +6 -0
  27. package/dist/order.d.ts +18 -0
  28. package/dist/order.js +53 -0
  29. package/dist/order.js.map +1 -0
  30. package/dist/prisma/index.d.ts +1 -0
  31. package/dist/prisma/index.js +3 -0
  32. package/dist/prisma/index.js.map +1 -1
  33. package/dist/prune.d.ts +4 -1
  34. package/dist/prune.js +11 -2
  35. package/dist/prune.js.map +1 -1
  36. package/dist/react/AddCase.d.ts +12 -2
  37. package/dist/react/AddCase.js +70 -8
  38. package/dist/react/AddCase.js.map +1 -1
  39. package/dist/react/AnswerKey.js +11 -5
  40. package/dist/react/AnswerKey.js.map +1 -1
  41. package/dist/react/CaseMenu.d.ts +6 -1
  42. package/dist/react/CaseMenu.js +5 -2
  43. package/dist/react/CaseMenu.js.map +1 -1
  44. package/dist/react/CompareView.js +4 -4
  45. package/dist/react/CompareView.js.map +1 -1
  46. package/dist/react/FeedbackView.js +3 -3
  47. package/dist/react/FeedbackView.js.map +1 -1
  48. package/dist/react/HubSections.js +11 -10
  49. package/dist/react/HubSections.js.map +1 -1
  50. package/dist/react/ModelMenu.d.ts +13 -4
  51. package/dist/react/ModelMenu.js +12 -7
  52. package/dist/react/ModelMenu.js.map +1 -1
  53. package/dist/react/PriorityPicker.d.ts +21 -0
  54. package/dist/react/PriorityPicker.js +47 -0
  55. package/dist/react/PriorityPicker.js.map +1 -0
  56. package/dist/react/RateView.js +1 -0
  57. package/dist/react/RateView.js.map +1 -1
  58. package/dist/react/RunView.js +21 -5
  59. package/dist/react/RunView.js.map +1 -1
  60. package/dist/react/SettingsHistory.js +3 -3
  61. package/dist/react/SettingsHistory.js.map +1 -1
  62. package/dist/react/SuiteSections.d.ts +6 -0
  63. package/dist/react/SuiteSections.js +100 -39
  64. package/dist/react/SuiteSections.js.map +1 -1
  65. package/dist/react/WeeklyCheck.js +4 -8
  66. package/dist/react/WeeklyCheck.js.map +1 -1
  67. package/dist/react/app.d.ts +4 -0
  68. package/dist/react/app.js.map +1 -1
  69. package/dist/react/format.d.ts +2 -2
  70. package/dist/react/format.js +4 -2
  71. package/dist/react/format.js.map +1 -1
  72. package/dist/react/pieces.d.ts +21 -1
  73. package/dist/react/pieces.js +67 -2
  74. package/dist/react/pieces.js.map +1 -1
  75. package/dist/runner.d.ts +7 -2
  76. package/dist/runner.js +5 -2
  77. package/dist/runner.js.map +1 -1
  78. package/dist/settings.d.ts +14 -0
  79. package/dist/settings.js +24 -2
  80. package/dist/settings.js.map +1 -1
  81. package/dist/suggest.js +25 -7
  82. package/dist/suggest.js.map +1 -1
  83. package/dist/testing.d.ts +1 -1
  84. package/dist/testing.js +32 -0
  85. package/dist/testing.js.map +1 -1
  86. package/dist/types.d.ts +12 -0
  87. package/dist/types.js +11 -0
  88. package/dist/types.js.map +1 -1
  89. package/package.json +10 -10
  90. package/schema/evalkeeper.prisma +3 -0
  91. package/src/drafts.ts +6 -1
  92. package/src/failures.ts +50 -0
  93. package/src/glossary.ts +6 -2
  94. package/src/health.ts +55 -7
  95. package/src/index.ts +2 -0
  96. package/src/legs.ts +8 -2
  97. package/src/next/actions.ts +96 -17
  98. package/src/next/route.ts +2 -1
  99. package/src/next/weekly.ts +15 -4
  100. package/src/next/wiring.ts +6 -0
  101. package/src/order.ts +64 -0
  102. package/src/prisma/index.ts +5 -0
  103. package/src/prune.ts +15 -1
  104. package/src/react/AddCase.tsx +98 -11
  105. package/src/react/AnswerKey.tsx +74 -14
  106. package/src/react/CaseMenu.tsx +24 -0
  107. package/src/react/CompareView.tsx +19 -4
  108. package/src/react/FeedbackView.tsx +13 -3
  109. package/src/react/HubSections.tsx +18 -11
  110. package/src/react/ModelMenu.tsx +24 -7
  111. package/src/react/PriorityPicker.tsx +143 -0
  112. package/src/react/RateView.tsx +1 -0
  113. package/src/react/RunView.tsx +41 -6
  114. package/src/react/SettingsHistory.tsx +3 -3
  115. package/src/react/SuiteSections.tsx +418 -251
  116. package/src/react/WeeklyCheck.tsx +12 -6
  117. package/src/react/app.ts +4 -0
  118. package/src/react/format.ts +4 -2
  119. package/src/react/pieces.tsx +96 -2
  120. package/src/runner.ts +11 -4
  121. package/src/settings.ts +37 -2
  122. package/src/suggest.ts +26 -7
  123. package/src/testing.ts +35 -1
  124. package/src/types.ts +18 -0
  125. package/templates/lib/evalkeeper/actions.ts +8 -0
@@ -6,6 +6,7 @@ import {
6
6
  attacksFrom,
7
7
  blindRating,
8
8
  caseFromFeedback,
9
+ confirmedLabel,
9
10
  draftMoreCases,
10
11
  formText,
11
12
  importStarters,
@@ -16,6 +17,7 @@ import {
16
17
  suggest,
17
18
  useDraftsProvisionally,
18
19
  withoutLeaks,
20
+ priorityOf,
19
21
  type ReasoningEffort,
20
22
  } from "../index.js";
21
23
  import { evalsPath, type EvalActions } from "../react/app.js";
@@ -50,6 +52,10 @@ export function evalActions(w: EvalWiring): Required<EvalActions> {
50
52
  };
51
53
  const weekly = weeklyCheck(w);
52
54
 
55
+ /** Who a settings change records: the admin's name, or their id. */
56
+ const changer = (admin: { id: string; name: string }) =>
57
+ w.changedBy === "id" ? admin.id : admin.name;
58
+
53
59
  const suiteFrom = (form: FormData) =>
54
60
  runner.suiteOrThrow(formText(form, "suite"));
55
61
 
@@ -88,7 +94,7 @@ export function evalActions(w: EvalWiring): Required<EvalActions> {
88
94
  */
89
95
  async function caseToRate(form: FormData, raterId: string) {
90
96
  const suite = suiteFrom(form);
91
- if (suite.caseKind !== "imported")
97
+ if (suite.caseKind !== "imported" || suite.rateBlind === false)
92
98
  throw new Error("This suite isn't rated blind");
93
99
  const c = await knownCase(suite.key, form);
94
100
  if (raterStatus(c, raterId))
@@ -206,7 +212,7 @@ export function evalActions(w: EvalWiring): Required<EvalActions> {
206
212
  ? { model: row.model, reasoningEffort: row.effort }
207
213
  : { model: row.model },
208
214
  {
209
- by: admin.name,
215
+ by: changer(admin),
210
216
  reason: `Made ${row.label} live: ${score.right}/${score.total}, ${VS[row.vsLive ?? ""] ?? "no comparison"}${attacked === null ? "" : `; ${attacked} serious ${attacked === 1 ? "mistake" : "mistakes"} under attack`}`,
211
217
  // The evidence, so the history can show why.
212
218
  evidence: {
@@ -234,7 +240,7 @@ export function evalActions(w: EvalWiring): Required<EvalActions> {
234
240
  suite.operation,
235
241
  { fallbackModel: row.model },
236
242
  {
237
- by: admin.name,
243
+ by: changer(admin),
238
244
  reason: `Made ${row.label} the fallback: ${test ? `${Math.round(test.right)}/${Math.round(test.total)}${failed}` : "not tested"}`,
239
245
  evidence: {
240
246
  runId: test?.runId ?? null,
@@ -254,15 +260,24 @@ export function evalActions(w: EvalWiring): Required<EvalActions> {
254
260
  runner.board(suite.key),
255
261
  attacksOn(suite.key),
256
262
  ]);
257
- const s = suggest(board.rows, suite.checks, suite.priority, w.models, {
258
- attacks,
259
- });
263
+ if (board.rows.some((r) => r.testing))
264
+ throw new Error("Wait for the tests running now to finish");
265
+ const { settings: live } = await settings.current(suite.operation);
266
+ const s = suggest(
267
+ board.rows,
268
+ suite.checks,
269
+ priorityOf(suite, live),
270
+ w.models,
271
+ {
272
+ attacks,
273
+ },
274
+ );
260
275
  if (!s || s.same) return;
261
276
  await settings.update(
262
277
  suite.operation,
263
278
  { model: s.live.model, fallbackModel: s.fallback?.model ?? null },
264
279
  {
265
- by: admin.name,
280
+ by: changer(admin),
266
281
  reason: s.reasons.join(" "),
267
282
  evidence: {
268
283
  suggestion: s.reasons,
@@ -281,7 +296,7 @@ export function evalActions(w: EvalWiring): Required<EvalActions> {
281
296
  const reason = formText(form, "reason");
282
297
  if (!reason) throw new Error("Say why you're rolling back");
283
298
  await settings.rollBack(suite.operation, formText(form, "version"), {
284
- by: admin.name,
299
+ by: changer(admin),
285
300
  reason,
286
301
  });
287
302
  everyPage();
@@ -292,7 +307,9 @@ export function evalActions(w: EvalWiring): Required<EvalActions> {
292
307
  await w.requireAdmin();
293
308
  const suite = suiteFrom(form);
294
309
  await store.setLabelStatus(formText(form, "label"), "CONFIRMED");
295
- after(() => runner.rescoreRecent(suite.key));
310
+ // Rescored before the page refreshes (free, about a second): an
311
+ // answer change marks tests out of date until then.
312
+ await runner.rescoreRecent(suite.key);
296
313
  revalidatePath(page(suite.key));
297
314
  },
298
315
 
@@ -360,11 +377,35 @@ export function evalActions(w: EvalWiring): Required<EvalActions> {
360
377
  });
361
378
  // A draft (from feedback) is in use once it has an answer.
362
379
  await store.setCaseStatus(c.id, "ACTIVE");
363
- after(() => runner.rescoreRecent(suite.key));
380
+ // Rescored before the page refreshes (free, about a second): an
381
+ // answer change marks tests out of date until then.
382
+ await runner.rescoreRecent(suite.key);
364
383
  revalidatePath(page(suite.key));
365
384
  },
366
385
 
367
386
  /** Takes a case out of use; its stored answers stay. */
387
+ async keepAnswer(form) {
388
+ const admin = await w.requireAdmin();
389
+ const suite = suiteFrom(form);
390
+ const c = await knownCase(suite.key, form);
391
+ const answer = confirmedLabel(c.labels);
392
+ if (!answer) throw new Error("This case has no answer in use");
393
+ // A fresh confirmation of the same answer, by whoever checked it: the
394
+ // split list leaves it out until a newer test splits on it again.
395
+ await store.addLabel(c.id, {
396
+ kind: "EXPECTED",
397
+ status: "CONFIRMED",
398
+ value: answer.value,
399
+ raterRole: "REVIEWER",
400
+ raterId: admin.id,
401
+ note: "Checked when models split on it, and kept as right.",
402
+ });
403
+ // Rescored before the page refreshes (free, about a second): an
404
+ // answer change marks tests out of date until then.
405
+ await runner.rescoreRecent(suite.key);
406
+ revalidatePath(page(suite.key));
407
+ },
408
+
368
409
  async retireCase(form) {
369
410
  await w.requireAdmin();
370
411
  const suite = suiteFrom(form);
@@ -420,18 +461,53 @@ export function evalActions(w: EvalWiring): Required<EvalActions> {
420
461
  await w.requireAdmin();
421
462
  const suite = suiteFrom(form);
422
463
  if (!suite.draftMore) throw new Error("This suite can't draft cases");
423
- const focus = form.get("focus");
464
+ const text = (name: string) => {
465
+ const v = form.get(name);
466
+ return typeof v === "string" ? v.trim() : "";
467
+ };
468
+ // Topics picked from Answer key health's thin ones, each worth two.
469
+ const topics = form
470
+ .getAll("topic")
471
+ .filter((t): t is string => typeof t === "string" && t.trim() !== "");
472
+ const asked = Number(text("count"));
473
+ const focus =
474
+ text("focus") ||
475
+ (topics.length ? `Cases on these topics: ${topics.join(", ")}` : "");
424
476
  await draftMoreCases({
425
477
  store,
426
478
  suite,
427
- focus:
428
- typeof focus === "string" && focus.trim()
429
- ? focus.trim().slice(0, 500)
430
- : null,
479
+ focus: focus ? focus.slice(0, 500) : null,
480
+ ...(Number.isFinite(asked) && asked > 0
481
+ ? { count: asked }
482
+ : topics.length
483
+ ? { count: topics.length * 2 }
484
+ : {}),
431
485
  });
432
486
  revalidatePath(page(suite.key));
433
487
  },
434
488
 
489
+ async setPriority(form) {
490
+ const admin = await w.requireAdmin();
491
+ const suite = choosingSuite(form);
492
+ const favor = formText(form, "favor");
493
+ if (favor !== "quality" && favor !== "speed" && favor !== "cost")
494
+ throw new Error("Pick accuracy, speed, or cost");
495
+ const reason = form.get("reason");
496
+ await settings.update(
497
+ suite.operation,
498
+ // The suite's own priority needs no override.
499
+ { favor: favor === suite.priority.favor ? null : favor },
500
+ {
501
+ by: changer(admin),
502
+ reason:
503
+ typeof reason === "string" && reason.trim()
504
+ ? reason.trim().slice(0, 300)
505
+ : `Favors ${favor === "quality" ? "accuracy" : favor}`,
506
+ },
507
+ );
508
+ everyPage();
509
+ },
510
+
435
511
  async useDraftsProvisionally(form) {
436
512
  await w.requireAdmin();
437
513
  const suite = suiteFrom(form);
@@ -457,7 +533,9 @@ export function evalActions(w: EvalWiring): Required<EvalActions> {
457
533
  );
458
534
  // A draft is in use once it has an answer.
459
535
  if (c.status === "DRAFT") await store.setCaseStatus(c.id, "ACTIVE");
460
- after(() => runner.rescoreRecent(suite.key));
536
+ // Rescored before the page refreshes (free, about a second): an
537
+ // answer change marks tests out of date until then.
538
+ await runner.rescoreRecent(suite.key);
461
539
  revalidatePath(page(suite.key), "layout");
462
540
  },
463
541
 
@@ -491,10 +569,11 @@ export function evalActions(w: EvalWiring): Required<EvalActions> {
491
569
  },
492
570
 
493
571
  async runWeeklyNow() {
572
+ const startedAt = Date.now();
494
573
  await w.requireAdmin();
495
574
  // Recorded before the page re-renders, so it shows them running.
496
575
  const ids = await weekly.start();
497
- after(() => weekly.run(ids));
576
+ after(() => weekly.run(ids, startedAt));
498
577
  revalidatePath(w.basePath);
499
578
  },
500
579
  };
package/src/next/route.ts CHANGED
@@ -26,10 +26,11 @@ export function weeklyCronRoute(
26
26
  ) {
27
27
  const weekly = weeklyCheck(w);
28
28
  return async function GET(request: Request): Promise<Response> {
29
+ const startedAt = Date.now();
29
30
  if (!isAuthorizedCron(request.headers.get("authorization"), secret()))
30
31
  return Response.json({ error: "Unauthorized" }, { status: 401 });
31
32
  const ids = await weekly.start();
32
- after(() => weekly.run(ids));
33
+ after(() => weekly.run(ids, startedAt));
33
34
  return Response.json({ started: ids.length }, { status: 202 });
34
35
  };
35
36
  }
@@ -1,6 +1,10 @@
1
1
  import { isInjectionSuite } from "../types.js";
2
2
  import { injectionCases } from "../suites/injection.js";
3
3
  import type { EvalWiring } from "./wiring.js";
4
+ import { mapLimit } from "../runner.js";
5
+
6
+ /** Suites the weekly check answers at once. */
7
+ const SUITES_AT_ONCE = 3;
4
8
 
5
9
  /** The weekly check, in the two halves a request can split it into. */
6
10
  export type WeeklyCheck = {
@@ -10,8 +14,13 @@ export type WeeklyCheck = {
10
14
  * running. Returns the tests' ids for `run`.
11
15
  */
12
16
  start: () => Promise<string[]>;
13
- /** Drafts cases from the week's activity, then answers the tests. */
14
- run: (ids: string[]) => Promise<void>;
17
+ /**
18
+ * Drafts cases from the week's activity, then answers the tests, a few
19
+ * suites at a time. `startedAt` is when the request began (default:
20
+ * now): the runner's time limit counts from then, and tests it can't
21
+ * reach in time carry on in fresh requests.
22
+ */
23
+ run: (ids: string[], startedAt?: number) => Promise<void>;
15
24
  };
16
25
 
17
26
  /**
@@ -55,7 +64,7 @@ export function weeklyCheck(
55
64
  }
56
65
  return ids;
57
66
  },
58
- async run(ids) {
67
+ async run(ids, startedAt = Date.now()) {
59
68
  // Drafts nobody reviewed in a month go, so the review queue stays
60
69
  // short; the weekly job's other half adds this week's.
61
70
  for (const suite of w.suites)
@@ -64,7 +73,9 @@ export function weeklyCheck(
64
73
  });
65
74
  await draft();
66
75
  // runEval never throws: a suite that fails says why on its own test.
67
- for (const id of ids) await w.runner.runEval(id, { fresh: true });
76
+ await mapLimit(ids, SUITES_AT_ONCE, (id) =>
77
+ w.runner.runEval(id, { fresh: true, requestStartedAt: startedAt }),
78
+ );
68
79
  },
69
80
  };
70
81
  }
@@ -15,4 +15,10 @@ export type EvalWiring = Omit<EvalApp, "actions"> & {
15
15
  * is recorded as who made each change.
16
16
  */
17
17
  requireAdmin: () => Promise<EvalAdmin>;
18
+ /**
19
+ * What the settings history records as who made a change: the admin's
20
+ * `name` (the default) or `id`. Use "id" when your settings store keeps
21
+ * a user id there (a foreign key) and shows names from it.
22
+ */
23
+ changedBy?: "name" | "id";
18
24
  };
package/src/order.ts ADDED
@@ -0,0 +1,64 @@
1
+ import type { BoardRow } from "./board.js";
2
+ import type { CheckDef, SuitePriority } from "./types.js";
3
+ import { seriousMistakes } from "./suggest.js";
4
+
5
+ /**
6
+ * A board's rows in the order the suggestion weighs them: the suggested
7
+ * live model first, then the live one, then models with a current test by
8
+ * fewest serious mistakes, highest accuracy, and the suite's priority
9
+ * (lower cost or time), then the rest. Accuracy is never traded away by
10
+ * this order: cost and speed only break ties. Pure.
11
+ */
12
+ export function orderRows<R extends BoardRow>(
13
+ rows: readonly R[],
14
+ checks: CheckDef[],
15
+ priority: SuitePriority,
16
+ suggested: { live: string | null } = { live: null },
17
+ ): R[] {
18
+ const current = (r: R) => !!r.test && !r.test.stale;
19
+ const accuracy = (r: R) => (r.test?.total ? r.test.right / r.test.total : 0);
20
+ const favored = (r: R) =>
21
+ priority.favor === "cost"
22
+ ? (r.test?.costPerAnswer ?? Infinity)
23
+ : priority.favor === "speed"
24
+ ? (r.test?.avgMs ?? Infinity)
25
+ : 0;
26
+ const rank = (r: R): number[] => [
27
+ r.key === suggested.live ? 0 : 1,
28
+ r.live ? 0 : 1,
29
+ current(r) ? 0 : 1,
30
+ current(r) ? seriousMistakes(r, checks) : 0,
31
+ -accuracy(r),
32
+ favored(r),
33
+ ];
34
+ return [...rows].sort((a, b) => {
35
+ const x = rank(a);
36
+ const y = rank(b);
37
+ for (let i = 0; i < x.length; i++)
38
+ if (x[i] !== y[i]) return (x[i] ?? 0) - (y[i] ?? 0);
39
+ return 0;
40
+ });
41
+ }
42
+
43
+ /**
44
+ * What a model gains on the suite's priority over the live one, when
45
+ * it's about as accurate: "4× cheaper", "2.5× faster". Null under 1.5×,
46
+ * or when the suite favors accuracy. Pure.
47
+ */
48
+ export function priorityGain(
49
+ row: BoardRow,
50
+ live: BoardRow | undefined,
51
+ priority: SuitePriority,
52
+ ): string | null {
53
+ if (!row.test || !live?.test || priority.favor === "quality") return null;
54
+ const [mine, theirs, word] =
55
+ priority.favor === "cost"
56
+ ? [row.test.costPerAnswer, live.test.costPerAnswer, "cheaper"]
57
+ : [row.test.avgMs, live.test.avgMs, "faster"];
58
+ if (mine === null || theirs === null || !(mine > 0) || !(theirs > 0))
59
+ return null;
60
+ const ratio = theirs / mine;
61
+ if (ratio < 1.5) return null;
62
+ const shown = ratio >= 10 ? Math.round(ratio) : Math.round(ratio * 10) / 10;
63
+ return `${shown}× ${word}`;
64
+ }
@@ -863,6 +863,7 @@ export type EvalSettingsVersionRow = {
863
863
  reasoningEffort: string | null;
864
864
  maxOutputTokens: number | null;
865
865
  temperature: number | null;
866
+ favor?: string | null;
866
867
  promptVersion: string | null;
867
868
  createdAt: Date;
868
869
  };
@@ -921,10 +922,14 @@ const version = (v: Row): SettingsVersion => ({
921
922
  reasoningEffort: strOrNull(v.reasoningEffort),
922
923
  maxOutputTokens: numOrNull(v.maxOutputTokens),
923
924
  temperature: numOrNull(v.temperature),
925
+ // An unknown or missing value reads as the suite's own priority.
926
+ favor: FAVORS.find((f) => f === v.favor) ?? null,
924
927
  promptVersion: strOrNull(v.promptVersion),
925
928
  createdAt: date(v.createdAt),
926
929
  });
927
930
 
931
+ const FAVORS = ["speed", "cost", "quality"] as const;
932
+
928
933
  const settingsChange = (c: Row, by: string | null): SettingsChange => ({
929
934
  id: str(c.id),
930
935
  operation: str(c.operation),
package/src/prune.ts CHANGED
@@ -127,6 +127,12 @@ export type AnswerKeyHealth<C> = {
127
127
  tags: [string, number][];
128
128
  };
129
129
 
130
+ /** Whether a person confirmed the case's answer after `at`. */
131
+ function checkedSince(labels: readonly LabelLike[], since: Date): boolean {
132
+ const answer = confirmedLabel(labels);
133
+ return !!answer && answer.status === "CONFIRMED" && answer.updatedAt > since;
134
+ }
135
+
130
136
  /**
131
137
  * A suite's answer-key health, from its cases (retired ones are ignored)
132
138
  * and how each case fared across the board's current tests. The floor of
@@ -137,6 +143,9 @@ export type AnswerKeyHealth<C> = {
137
143
  * @param caseResults - Per case, how many current models tested it and
138
144
  * got it fully right (the board's `caseResults`).
139
145
  * @param today - Now, for old drafts.
146
+ * @param testedAt - When the newest current test ran. A split case whose
147
+ * answer a person confirmed after it ("the answer is right") isn't
148
+ * listed again until a newer test splits on it.
140
149
  * @returns What needs a look: easy, split, and duplicate cases, old
141
150
  * drafts, and how the tags spread.
142
151
  */
@@ -144,6 +153,7 @@ export function answerKeyHealth<C extends HealthCase>(
144
153
  cases: readonly C[],
145
154
  caseResults: Readonly<Record<string, CaseResult>>,
146
155
  today = new Date(),
156
+ testedAt: Date | null = null,
147
157
  ): AnswerKeyHealth<C> {
148
158
  const live = cases.filter((c) => c.status !== "RETIRED");
149
159
  const inUse = live.filter((c) => confirmedLabel(c.labels));
@@ -164,7 +174,11 @@ export function answerKeyHealth<C extends HealthCase>(
164
174
  inUse: inUse.length,
165
175
  easy,
166
176
  easyToRetire: easy.filter((c) => retire.has(c.id)),
167
- split: inUse.filter((c) => isSplit(caseResults[c.id])),
177
+ split: inUse.filter(
178
+ (c) =>
179
+ isSplit(caseResults[c.id]) &&
180
+ !(testedAt && checkedSince(c.labels, testedAt)),
181
+ ),
168
182
  duplicates: nearDuplicates(inUse),
169
183
  staleDrafts: drafts.filter((c) => isStaleDraft(c.createdAt, today)),
170
184
  tags: tagCounts(inUse),
@@ -2,24 +2,60 @@
2
2
 
3
3
  import { Button, Card } from "./pieces.js";
4
4
  import { QUIET_BUTTON } from "./format.js";
5
- import { useState } from "react";
5
+ import { useEffect, useState, useSyncExternalStore } from "react";
6
6
  import { Plus } from "lucide-react";
7
7
 
8
+ /** The address's hash, kept current; "" on the server. */
9
+ const hashNow = () => window.location.hash;
10
+ const noHash = () => "";
11
+ const onHash = (change: () => void) => {
12
+ window.addEventListener("hashchange", change);
13
+ return () => {
14
+ window.removeEventListener("hashchange", change);
15
+ };
16
+ };
17
+
8
18
  /**
9
19
  * A section's header row with an "Add a case" button at the top right,
10
- * beside `tools`; the button opens `form` below the header.
20
+ * beside `tools`; the button opens `form` below the header. With `draft`,
21
+ * a second tab drafts cases from a request in the person's own words. A
22
+ * link to "#add-case=<topic>" opens it with that topic in the tags.
11
23
  */
12
24
  export function AddCaseHeader({
13
25
  heading,
14
26
  tools,
15
27
  form,
28
+ draft,
16
29
  }: {
17
30
  heading: React.ReactNode;
18
31
  tools?: React.ReactNode;
19
32
  /** The add-a-case form; null hides the button. */
20
33
  form: React.ReactNode;
34
+ /** A form that drafts cases from a description; null for none. */
35
+ draft?: React.ReactNode;
21
36
  }) {
22
37
  const [open, setOpen] = useState(false);
38
+ const [tab, setTab] = useState<"write" | "describe">("write");
39
+ const hash = useSyncExternalStore(onHash, hashNow, noHash);
40
+ const topic = hash.startsWith("#add-case=")
41
+ ? decodeURIComponent(hash.slice("#add-case=".length))
42
+ : null;
43
+ const shown = open || topic !== null;
44
+ // A topic from the link goes into the new case's tags.
45
+ useEffect(() => {
46
+ if (!topic) return;
47
+ const tags = document.getElementById("new-tags");
48
+ if (tags instanceof HTMLInputElement && !tags.value.includes(topic))
49
+ tags.value = tags.value ? `${tags.value}, ${topic}` : topic;
50
+ tags?.scrollIntoView({ block: "center" });
51
+ }, [topic]);
52
+ const close = () => {
53
+ setOpen(false);
54
+ if (topic !== null)
55
+ history.replaceState(null, "", window.location.pathname);
56
+ };
57
+ const tabClass = (on: boolean) =>
58
+ `rounded-md px-3 py-1.5 text-sm ${on ? "bg-tint font-medium text-ink" : "text-muted hover:text-ink"}`;
23
59
  return (
24
60
  <>
25
61
  <div className="flex flex-wrap items-center justify-between gap-4">
@@ -28,9 +64,10 @@ export function AddCaseHeader({
28
64
  {form && (
29
65
  <Button
30
66
  type="button"
31
- aria-expanded={open}
67
+ aria-expanded={shown}
32
68
  onClick={() => {
33
- setOpen(!open);
69
+ if (shown) close();
70
+ else setOpen(true);
34
71
  }}
35
72
  className={`inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm ${QUIET_BUTTON}`}
36
73
  >
@@ -41,23 +78,73 @@ export function AddCaseHeader({
41
78
  {tools}
42
79
  </div>
43
80
  </div>
44
- {open && form && (
81
+ {shown && form && (
45
82
  <Card className="space-y-4">
46
- <div className="flex items-center justify-between gap-2">
47
- <h3 className="font-medium">New case</h3>
83
+ <div className="flex flex-wrap items-center justify-between gap-2">
84
+ {draft ? (
85
+ <div role="tablist" className="flex gap-1">
86
+ <Button
87
+ type="button"
88
+ role="tab"
89
+ aria-selected={tab === "write"}
90
+ onClick={() => {
91
+ setTab("write");
92
+ }}
93
+ className={tabClass(tab === "write")}
94
+ >
95
+ Write one
96
+ </Button>
97
+ <Button
98
+ type="button"
99
+ role="tab"
100
+ aria-selected={tab === "describe"}
101
+ onClick={() => {
102
+ setTab("describe");
103
+ }}
104
+ className={tabClass(tab === "describe")}
105
+ >
106
+ Describe them
107
+ </Button>
108
+ </div>
109
+ ) : (
110
+ <h3 className="font-medium">New case</h3>
111
+ )}
48
112
  <Button
49
113
  type="button"
50
- onClick={() => {
51
- setOpen(false);
52
- }}
114
+ onClick={close}
53
115
  className="text-sm text-muted hover:text-ink"
54
116
  >
55
117
  Cancel
56
118
  </Button>
57
119
  </div>
58
- {form}
120
+ {draft && tab === "describe" ? draft : form}
59
121
  </Card>
60
122
  )}
61
123
  </>
62
124
  );
63
125
  }
126
+
127
+ /**
128
+ * Opens the case a link points at ("#case-…", from Answer key health's
129
+ * "Fix the answer"), on load and whenever the address changes, and
130
+ * scrolls it into view. Draws nothing.
131
+ */
132
+ export function OpenLinkedCase() {
133
+ useEffect(() => {
134
+ const open = () => {
135
+ const id = decodeURIComponent(window.location.hash.slice(1));
136
+ if (!id.startsWith("case-")) return;
137
+ const el = document.getElementById(id);
138
+ if (el instanceof HTMLDetailsElement) {
139
+ el.open = true;
140
+ el.scrollIntoView({ block: "start" });
141
+ }
142
+ };
143
+ open();
144
+ window.addEventListener("hashchange", open);
145
+ return () => {
146
+ window.removeEventListener("hashchange", open);
147
+ };
148
+ }, []);
149
+ return null;
150
+ }