@crowandraven/evalkeeper 0.16.0 → 0.17.1

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.
@@ -1,7 +1,7 @@
1
1
  import { InfoTip, Select, TextArea, TextInput } from "./pieces.js";
2
+ import { ReadableValue } from "./Readable.js";
2
3
  import {
3
4
  ANSWER_JSON_FIELD,
4
- asText,
5
5
  fieldValue,
6
6
  type AnswerEditorProps,
7
7
  type FormField,
@@ -33,16 +33,16 @@ export function Fields({
33
33
  <label htmlFor={id} className="block text-sm font-medium">
34
34
  {f.label}
35
35
  </label>
36
- {f.kind === "select" ? (
36
+ {f.kind === "select" || choices(f) ? (
37
37
  <Select
38
38
  id={id}
39
39
  name={f.name}
40
- defaultValue={value || f.options?.[0]}
40
+ defaultValue={value || (f.options ?? choices(f))?.[0]}
41
41
  className={box}
42
42
  >
43
- {f.options?.map((o) => (
43
+ {(f.options ?? choices(f))?.map((o) => (
44
44
  <option key={o} value={o}>
45
- {o.replace(/_/g, " ")}
45
+ {f.optionLabels?.[o] ?? o.replace(/_/g, " ")}
46
46
  </option>
47
47
  ))}
48
48
  </Select>
@@ -73,19 +73,26 @@ export function Fields({
73
73
  );
74
74
  }
75
75
 
76
- /** A stored input or answer, read with the suite's field labels. */
76
+ /**
77
+ * A stored input or answer, read with the suite's field labels: objects as
78
+ * labeled rows, long text folded, never raw data. `marks` are highlighted
79
+ * (a suite's `lookAt`).
80
+ */
77
81
  export function FieldValues({
78
82
  fields,
79
83
  values,
80
84
  prefix = "",
85
+ marks,
81
86
  }: {
82
87
  fields: FormField[];
83
88
  values: unknown;
84
89
  /** Keeps tooltip ids unique when a page shows several. */
85
90
  prefix?: string;
91
+ /** Text to highlight wherever it appears. */
92
+ marks?: string[] | undefined;
86
93
  }) {
87
94
  return (
88
- <dl className="space-y-2">
95
+ <dl className="space-y-3">
89
96
  {fields.map((f) => {
90
97
  const v = (values as Record<string, unknown> | null)?.[f.name];
91
98
  return (
@@ -94,24 +101,13 @@ export function FieldValues({
94
101
  {f.label}
95
102
  <InfoTip text={f.help} id={`${prefix}${f.name}-read`} />
96
103
  </dt>
97
- <dd className="readable break-words whitespace-pre-wrap">
98
- {f.kind === "json" && v !== undefined && v !== null ? (
99
- <pre className="text-xs whitespace-pre-wrap">
100
- {JSON.stringify(v, null, 2)}
101
- </pre>
102
- ) : Array.isArray(v) ? (
103
- v.length ? (
104
- <ul className="list-disc pl-5">
105
- {v.map((x, i) => (
106
- <li key={i}>{asText(x)}</li>
107
- ))}
108
- </ul>
104
+ <dd className="mt-0.5 break-words">
105
+ {labelOf(f, v) ??
106
+ (f.kind === "json" && typeof v === "string" ? (
107
+ <ReadableValue value={parseJson(v)} marks={marks} />
109
108
  ) : (
110
- <span className="text-muted">None</span>
111
- )
112
- ) : (
113
- (asText(v) || "—").replace(/_/g, " ")
114
- )}
109
+ <ReadableValue value={v} marks={marks} />
110
+ ))}
115
111
  </dd>
116
112
  </div>
117
113
  );
@@ -120,6 +116,35 @@ export function FieldValues({
120
116
  );
121
117
  }
122
118
 
119
+ /**
120
+ * A JSON field whose values are all named in `optionLabels` (a
121
+ * yes-or-no: "true" and "false") is a choice, not a box to type JSON in.
122
+ * Its value is submitted as the JSON it names.
123
+ */
124
+ function choices(f: FormField): string[] | undefined {
125
+ if (f.kind !== "json" || !f.optionLabels) return undefined;
126
+ const keys = Object.keys(f.optionLabels);
127
+ return keys.length ? keys : undefined;
128
+ }
129
+
130
+ /**
131
+ * How a value reads by the field's `optionLabels`: a choice ("YES" →
132
+ * "Would apply") or a yes-or-no (true → "Yes, as they typed it").
133
+ */
134
+ function labelOf(f: FormField, v: unknown): string | undefined {
135
+ if (typeof v !== "string" && typeof v !== "boolean") return undefined;
136
+ return f.optionLabels?.[String(v)];
137
+ }
138
+
139
+ /** A JSON field stored as text, parsed when it parses. */
140
+ function parseJson(text: string): unknown {
141
+ try {
142
+ return JSON.parse(text);
143
+ } catch {
144
+ return text;
145
+ }
146
+ }
147
+
123
148
  /**
124
149
  * A suite's answer, for writing or editing it: the app's own answer editor
125
150
  * when it registered one for this suite (`answerEditors` in the wiring
@@ -0,0 +1,38 @@
1
+ "use client";
2
+
3
+ import { useState, type ReactNode } from "react";
4
+ import { Button } from "./pieces.js";
5
+
6
+ /**
7
+ * Long content, folded: `short` shows until the person opens the rest.
8
+ * For a posting's text or a long list, so a case reads at a glance.
9
+ */
10
+ export function Folded({
11
+ short,
12
+ children,
13
+ more,
14
+ }: {
15
+ /** What shows while folded. */
16
+ short: ReactNode;
17
+ /** The whole of it. */
18
+ children: ReactNode;
19
+ /** The button's label: "Show all 24" or "Show the whole text". */
20
+ more: string;
21
+ }) {
22
+ const [open, setOpen] = useState(false);
23
+ return (
24
+ <>
25
+ {open ? children : short}
26
+ <Button
27
+ type="button"
28
+ aria-expanded={open}
29
+ onClick={() => {
30
+ setOpen(!open);
31
+ }}
32
+ className="mt-1 text-xs text-accent hover:underline"
33
+ >
34
+ {open ? "Show less" : more}
35
+ </Button>
36
+ </>
37
+ );
38
+ }
@@ -0,0 +1,266 @@
1
+ import type { ReactNode } from "react";
2
+ import { asText } from "../index.js";
3
+ import { Folded } from "./Folded.js";
4
+
5
+ /** Longer than this, text is folded to its start. */
6
+ const LONG_TEXT = 320;
7
+ /** More items than this, a list is folded to its first ones. */
8
+ const LONG_LIST = 6;
9
+ /** Deeper than this, a value shows as data. */
10
+ const MAX_DEPTH = 3;
11
+
12
+ /** "linkStatus" or "link_status" → "Link status". */
13
+ export function humanize(key: string): string {
14
+ const words = key
15
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
16
+ .replace(/[_-]+/g, " ")
17
+ .trim()
18
+ .toLowerCase();
19
+ return words.charAt(0).toUpperCase() + words.slice(1);
20
+ }
21
+
22
+ /** `text` with each of `marks` highlighted, ignoring case. */
23
+ export function Marked({
24
+ text,
25
+ marks = [],
26
+ }: {
27
+ text: string;
28
+ marks?: string[] | undefined;
29
+ }): ReactNode {
30
+ const terms = marks.map((m) => m.trim()).filter(Boolean);
31
+ if (!terms.length) return text;
32
+ const escaped = terms
33
+ .sort((a, b) => b.length - a.length)
34
+ .map((m) => m.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
35
+ const parts = text.split(new RegExp(`(${escaped.join("|")})`, "gi"));
36
+ if (parts.length === 1) return text;
37
+ const lower = new Set(terms.map((t) => t.toLowerCase()));
38
+ return parts.map((p, i) =>
39
+ lower.has(p.toLowerCase()) ? (
40
+ <mark key={i} className="rounded-sm bg-warn/20 px-0.5 text-ink">
41
+ {p}
42
+ </mark>
43
+ ) : (
44
+ p
45
+ ),
46
+ );
47
+ }
48
+
49
+ /** "VERIFIED" → "Verified", "NOT_SURE" → "Not sure"; other text as is. */
50
+ export function enumText(text: string): string {
51
+ if (!/^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)*$/.test(text)) return text;
52
+ const words = text.replace(/_/g, " ").toLowerCase();
53
+ return words.charAt(0).toUpperCase() + words.slice(1);
54
+ }
55
+
56
+ /** Whether `value` contains any of `marks` anywhere, ignoring case. */
57
+ export function hasMark(value: unknown, marks: string[] = []): boolean {
58
+ if (!marks.length) return false;
59
+ const text = (typeof value === "string" ? value : asText(value))
60
+ .toLowerCase()
61
+ .replace(/\\n/g, "\n");
62
+ return marks.some((m) => m.trim() && text.includes(m.trim().toLowerCase()));
63
+ }
64
+
65
+ type Block =
66
+ | { kind: "heading"; text: string }
67
+ | { kind: "list"; items: string[] }
68
+ | { kind: "text"; text: string };
69
+
70
+ /**
71
+ * Text as blocks a person reads: Markdown-style headings ("### Wants")
72
+ * and lists ("- item") as such, paragraphs at blank lines, other line
73
+ * breaks kept.
74
+ */
75
+ export function blocksOf(text: string): Block[] {
76
+ const out: Block[] = [];
77
+ let para: string[] = [];
78
+ const endPara = () => {
79
+ const t = para.join("\n").trim();
80
+ if (t) out.push({ kind: "text", text: t });
81
+ para = [];
82
+ };
83
+ for (const raw of text.split("\n")) {
84
+ const line = raw.trimEnd();
85
+ const heading = /^#{1,6}\s+(.+)$/.exec(line);
86
+ const item = /^\s*[-*•]\s+(.+)$/.exec(line);
87
+ if (heading?.[1]) {
88
+ endPara();
89
+ out.push({ kind: "heading", text: heading[1] });
90
+ } else if (item?.[1]) {
91
+ endPara();
92
+ const last = out.at(-1);
93
+ if (last?.kind === "list") last.items.push(item[1]);
94
+ else out.push({ kind: "list", items: [item[1]] });
95
+ } else if (!line.trim()) endPara();
96
+ else para.push(line);
97
+ }
98
+ endPara();
99
+ return out;
100
+ }
101
+
102
+ /** Text in blocks: headings, lists, and paragraphs, with marks. */
103
+ function Paragraphs({
104
+ text,
105
+ marks,
106
+ }: {
107
+ text: string;
108
+ marks?: string[] | undefined;
109
+ }) {
110
+ return (
111
+ <div className="readable space-y-2">
112
+ {blocksOf(text).map((b, i) =>
113
+ b.kind === "heading" ? (
114
+ <p key={i} className="text-xs font-semibold text-muted">
115
+ <Marked text={b.text} marks={marks} />
116
+ </p>
117
+ ) : b.kind === "list" ? (
118
+ <ul key={i} className="list-disc space-y-1 pl-5">
119
+ {b.items.map((t, j) => (
120
+ <li key={j}>
121
+ <Marked text={t} marks={marks} />
122
+ </li>
123
+ ))}
124
+ </ul>
125
+ ) : (
126
+ <p key={i} className="whitespace-pre-wrap">
127
+ <Marked text={b.text} marks={marks} />
128
+ </p>
129
+ ),
130
+ )}
131
+ </div>
132
+ );
133
+ }
134
+
135
+ /**
136
+ * Text as a person reads it: short text inline, long text as paragraphs
137
+ * folded to its start, unless a highlight sits in the rest.
138
+ */
139
+ function ReadableText({
140
+ text,
141
+ marks,
142
+ }: {
143
+ text: string;
144
+ marks?: string[] | undefined;
145
+ }) {
146
+ if (/^https?:\/\/\S+$/.test(text))
147
+ return (
148
+ <a
149
+ href={text}
150
+ target="_blank"
151
+ rel="noreferrer"
152
+ className="break-all text-accent hover:underline"
153
+ >
154
+ <Marked text={text} marks={marks} />
155
+ </a>
156
+ );
157
+ if (text.length <= LONG_TEXT && !text.includes("\n"))
158
+ return <Marked text={enumText(text)} marks={marks} />;
159
+ const whole = (
160
+ <div className="rounded-md bg-tint px-3 py-2">
161
+ <Paragraphs text={text} marks={marks} />
162
+ </div>
163
+ );
164
+ if (text.length <= LONG_TEXT) return whole;
165
+ const cut = text.slice(0, LONG_TEXT).replace(/\s+\S*$/, "");
166
+ const markedLater = hasMark(text, marks) && !hasMark(cut, marks);
167
+ return (
168
+ <div>
169
+ <Folded
170
+ more="Show the whole text"
171
+ short={
172
+ <div className="rounded-md bg-tint px-3 py-2">
173
+ <Paragraphs text={`${cut}…`} marks={marks} />
174
+ {markedLater && (
175
+ <p className="mt-1 text-xs text-muted">
176
+ More highlighted further on.
177
+ </p>
178
+ )}
179
+ </div>
180
+ }
181
+ >
182
+ {whole}
183
+ </Folded>
184
+ </div>
185
+ );
186
+ }
187
+
188
+ /**
189
+ * A stored value, read like a page rather than data: an object as
190
+ * labeled rows, a list as a list (folded when long), text as text, with
191
+ * `marks` highlighted.
192
+ */
193
+ export function ReadableValue({
194
+ value,
195
+ marks,
196
+ depth = 0,
197
+ }: {
198
+ value: unknown;
199
+ marks?: string[] | undefined;
200
+ depth?: number;
201
+ }): ReactNode {
202
+ if (value === undefined || value === null || value === "")
203
+ return <span className="text-muted">—</span>;
204
+ if (typeof value === "string")
205
+ return <ReadableText text={value} marks={marks} />;
206
+ if (typeof value === "boolean") return value ? "Yes" : "No";
207
+ if (typeof value === "number") return String(value);
208
+ if (depth >= MAX_DEPTH)
209
+ return (
210
+ <pre className="whitespace-pre-wrap text-xs">
211
+ {JSON.stringify(value, null, 2)}
212
+ </pre>
213
+ );
214
+ if (Array.isArray(value)) {
215
+ if (!value.length) return <span className="text-muted">None</span>;
216
+ // Records (résumés, facts with fields): each its own tinted block.
217
+ const records = value.every(
218
+ (x) => x !== null && typeof x === "object" && !Array.isArray(x),
219
+ );
220
+ const items = (xs: unknown[]) =>
221
+ records ? (
222
+ <ul className="space-y-2">
223
+ {xs.map((x, i) => (
224
+ <li key={i} className="rounded-md bg-tint px-3 py-2">
225
+ <ReadableValue value={x} marks={marks} depth={depth + 1} />
226
+ </li>
227
+ ))}
228
+ </ul>
229
+ ) : (
230
+ <ul className="list-disc space-y-1 pl-5">
231
+ {xs.map((x, i) => (
232
+ <li key={i}>
233
+ <ReadableValue value={x} marks={marks} depth={depth + 1} />
234
+ </li>
235
+ ))}
236
+ </ul>
237
+ );
238
+ if (value.length <= LONG_LIST) return items(value);
239
+ return (
240
+ <div>
241
+ <Folded
242
+ more={`Show all ${value.length}`}
243
+ short={items(value.slice(0, LONG_LIST - 1))}
244
+ >
245
+ {items(value)}
246
+ </Folded>
247
+ </div>
248
+ );
249
+ }
250
+ const entries = Object.entries(value as Record<string, unknown>).filter(
251
+ ([, v]) => v !== undefined,
252
+ );
253
+ if (!entries.length) return <span className="text-muted">—</span>;
254
+ return (
255
+ <dl className="grid grid-cols-[minmax(6rem,auto)_minmax(0,1fr)] gap-x-3 gap-y-1.5">
256
+ {entries.map(([k, v]) => (
257
+ <div key={k} className="contents">
258
+ <dt className="text-xs text-muted">{humanize(k)}</dt>
259
+ <dd className="min-w-0 break-words">
260
+ <ReadableValue value={v} marks={marks} depth={depth + 1} />
261
+ </dd>
262
+ </div>
263
+ ))}
264
+ </dl>
265
+ );
266
+ }
@@ -9,7 +9,7 @@ import {
9
9
  type ReactNode,
10
10
  } from "react";
11
11
  import { useFormStatus } from "react-dom";
12
- import { ArrowLeft, Info, LoaderCircle } from "lucide-react";
12
+ import { ArrowLeft, CircleAlert, Info, LoaderCircle } from "lucide-react";
13
13
  import { GLOSSARY, type GlossaryTerm } from "../glossary.js";
14
14
  import {
15
15
  STANDING_LABEL,
@@ -120,8 +120,22 @@ export type EvalComponents = {
120
120
  TextArea: ComponentType<TextAreaProps>;
121
121
  Select: ComponentType<SelectProps>;
122
122
  RefreshWhile: ComponentType<RefreshWhileProps>;
123
+ /**
124
+ * Your app's toast, for what happened after a quick action (an answer
125
+ * confirmed, or a save that failed). Without it, the screens say so in
126
+ * place, and say nothing on success.
127
+ */
128
+ notify: Notify;
123
129
  };
124
130
 
131
+ /** Shows a short message as your app does (`EvalComponents.notify`). */
132
+ export type Notify = (type: "success" | "error", message: string) => void;
133
+
134
+ /** Your app's toast, if it gave one (`EvalComponents.notify`). */
135
+ export function useNotify(): Notify | undefined {
136
+ return useContext(Swapped).notify;
137
+ }
138
+
125
139
  const Swapped = createContext<Partial<EvalComponents>>({});
126
140
 
127
141
  /**
@@ -271,12 +285,38 @@ export function StandingBadge({ standing }: { standing: HealthStanding }) {
271
285
  * footnote instead.
272
286
  */
273
287
  export function HealthReasons({ flags }: { flags: readonly HealthFlag[] }) {
274
- const line = flags
288
+ const reasons = flags
275
289
  .filter((f) => f.kind !== "provisional" && f.kind !== "good")
276
- .flatMap(flagChips)
277
- .map((c) => c.text)
278
- .join(" · ");
279
- return line ? <p className="text-sm font-medium text-ink">{line}</p> : null;
290
+ .flatMap(flagChips);
291
+ if (!reasons.length) return null;
292
+ // Each in its standing's color with an icon, so it reads at a glance
293
+ // without another row of chips.
294
+ return (
295
+ <ul className="flex flex-wrap gap-x-4 gap-y-1 text-sm font-medium">
296
+ {reasons.map((r) => {
297
+ const urgent = r.tone === "serious" || r.tone === "warn";
298
+ return (
299
+ <li
300
+ key={r.text}
301
+ className={`inline-flex items-center gap-1.5 ${
302
+ r.tone === "serious"
303
+ ? "text-bad"
304
+ : r.tone === "warn"
305
+ ? "text-warn"
306
+ : "text-ink"
307
+ }`}
308
+ >
309
+ {urgent ? (
310
+ <CircleAlert aria-hidden className="h-4 w-4 shrink-0" />
311
+ ) : (
312
+ <Info aria-hidden className="h-4 w-4 shrink-0 text-muted" />
313
+ )}
314
+ {r.text}
315
+ </li>
316
+ );
317
+ })}
318
+ </ul>
319
+ );
280
320
  }
281
321
 
282
322
  /**
@@ -391,7 +431,7 @@ export function IconSubmit(props: IconSubmitProps) {
391
431
  type="submit"
392
432
  aria-label={props.label}
393
433
  disabled={pending}
394
- className="inline-flex h-8 w-8 items-center justify-center rounded-md border border-line bg-card text-ink hover:bg-tint disabled:opacity-60"
434
+ className={`inline-flex h-8 w-8 items-center justify-center rounded-md disabled:opacity-60 ${QUIET_BUTTON}`}
395
435
  >
396
436
  {pending ? <Spinner /> : props.icon}
397
437
  </button>
package/src/runner.ts CHANGED
@@ -760,13 +760,30 @@ export function createRunner(opts: RunnerOptions) {
760
760
  });
761
761
  }
762
762
 
763
- /** Regrades a suite's recent finished tests, e.g. after answers change. */
763
+ /**
764
+ * Regrades a suite's finished tests after answers change: the latest of
765
+ * every model and setting the board shows, however many tests ran since,
766
+ * plus the `limit` most recent. Any answer change puts every test out of
767
+ * date until it's regraded, and a test left out of date drops out of the
768
+ * board, its scores, and the answer key's health ("models split").
769
+ */
764
770
  async function rescoreRecent(suiteKey: string, limit = 10) {
765
- for (const r of await store.listRuns(suiteKey, {
766
- status: "SUCCEEDED",
767
- limit,
768
- }))
769
- await rescoreRun(r.id);
771
+ const runs = await store.listRuns(suiteKey, { status: "SUCCEEDED" });
772
+ const latest = new Map<string, string>();
773
+ for (const r of runs) {
774
+ const key = [
775
+ r.model,
776
+ r.reasoningEffort ?? "",
777
+ r.temperature ?? "",
778
+ r.maxOutputTokens ?? "",
779
+ ].join("|");
780
+ if (!latest.has(key)) latest.set(key, r.id);
781
+ }
782
+ const ids = new Set([
783
+ ...runs.slice(0, limit).map((r) => r.id),
784
+ ...latest.values(),
785
+ ]);
786
+ for (const id of ids) await rescoreRun(id);
770
787
  }
771
788
 
772
789
  /**
package/src/types.ts CHANGED
@@ -286,6 +286,39 @@ export type Suite<Input, Output, Label> = {
286
286
  * the model, so it doesn't change the instructions hash.
287
287
  */
288
288
  answerGuide?: AnswerGuide;
289
+ /**
290
+ * What a person should look at to check this case's answer: shown with
291
+ * the answer to confirm ("Look at: pay is below their floor"), each
292
+ * note's `marks` highlighted wherever they appear in the input. Pick
293
+ * them by rule from the case (a dealbreaker beside what it rules on),
294
+ * never from the draft answer's own reasoning: that steers a person to
295
+ * agree with it. When models' tests disagree, the answer key says so on
296
+ * its own. For people only: it never reaches the model.
297
+ *
298
+ * @param input - The case's input, already checked against `input`.
299
+ * @param answer - The answer being checked, or null without one.
300
+ */
301
+ lookAt?(input: Input, answer: Label | null): LookAt[];
302
+ /**
303
+ * One model's answer as a short line, shown beside that model's latest
304
+ * test in the answer key ("“Get a full-time admin job in local
305
+ * government”", or "Left as typed"), so a person can compare what
306
+ * models wrote with the input and the answer. Shown below the answer,
307
+ * so a person reads the answer first. Shown as given: quote the
308
+ * model's own words yourself. For people only.
309
+ *
310
+ * @param output - What the model returned, as stored.
311
+ * @returns The line, or null to show none for this output.
312
+ */
313
+ outputLine?(output: Output): string | null;
314
+ };
315
+
316
+ /** One thing to look at when checking an answer (`Suite.lookAt`). */
317
+ export type LookAt = {
318
+ /** A short note: "pay is below their $70K floor". */
319
+ note: string;
320
+ /** Text to highlight in the case's input: "$55,000–$61,000". */
321
+ marks?: string[];
289
322
  };
290
323
 
291
324
  /** How to judge a suite's answers: a lead-in, the points, and a note. */
@@ -333,6 +366,12 @@ export type FormField = {
333
366
  kind: "text" | "textarea" | "select" | "lines" | "json";
334
367
  /** For "select". */
335
368
  options?: readonly string[];
369
+ /**
370
+ * How each value reads to a person: a choice's options ("YES" → "Would
371
+ * apply"), or "true" and "false" for a yes-or-no field. A JSON field
372
+ * with these is edited as a choice between them.
373
+ */
374
+ optionLabels?: Readonly<Record<string, string>>;
336
375
  required?: boolean;
337
376
  };
338
377