@crowandraven/evalkeeper 0.4.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/README.md +7 -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 +34 -0
  12. package/dist/cli/addPages.js +91 -11
  13. package/dist/cli/addPages.js.map +1 -1
  14. package/dist/cli/main.d.ts +1 -1
  15. package/dist/cli/main.js +9 -0
  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/glossary.d.ts +20 -0
  21. package/dist/glossary.js +20 -0
  22. package/dist/glossary.js.map +1 -1
  23. package/dist/health.js +5 -3
  24. package/dist/health.js.map +1 -1
  25. package/dist/importCases.d.ts +76 -5
  26. package/dist/importCases.js +114 -14
  27. package/dist/importCases.js.map +1 -1
  28. package/dist/index.d.ts +4 -0
  29. package/dist/index.js +4 -0
  30. package/dist/index.js.map +1 -1
  31. package/dist/memoryStore.js +3 -1
  32. package/dist/memoryStore.js.map +1 -1
  33. package/dist/readCheck.d.ts +116 -0
  34. package/dist/readCheck.js +321 -0
  35. package/dist/readCheck.js.map +1 -0
  36. package/dist/runner.d.ts +7 -0
  37. package/dist/runner.js +25 -3
  38. package/dist/runner.js.map +1 -1
  39. package/dist/settings.d.ts +81 -3
  40. package/dist/settings.js +160 -23
  41. package/dist/settings.js.map +1 -1
  42. package/dist/store.d.ts +10 -3
  43. package/dist/suggest.d.ts +10 -1
  44. package/dist/suggest.js +22 -4
  45. package/dist/suggest.js.map +1 -1
  46. package/dist/suiteContract.d.ts +17 -0
  47. package/dist/suiteContract.js +69 -0
  48. package/dist/suiteContract.js.map +1 -0
  49. package/dist/suites/crisisRisk.d.ts +83 -0
  50. package/dist/suites/crisisRisk.js +176 -0
  51. package/dist/suites/crisisRisk.js.map +1 -0
  52. package/dist/suites/crisisRiskCases.d.ts +40 -0
  53. package/dist/suites/crisisRiskCases.js +179 -0
  54. package/dist/suites/crisisRiskCases.js.map +1 -0
  55. package/dist/suites/index.d.ts +9 -0
  56. package/dist/suites/index.js +10 -0
  57. package/dist/suites/index.js.map +1 -0
  58. package/dist/testing.d.ts +140 -8
  59. package/dist/testing.js +420 -125
  60. package/dist/testing.js.map +1 -1
  61. package/dist/types.d.ts +92 -0
  62. package/dist/types.js +68 -0
  63. package/dist/types.js.map +1 -1
  64. package/dist/weekly.d.ts +21 -3
  65. package/dist/weekly.js +18 -1
  66. package/dist/weekly.js.map +1 -1
  67. package/package.json +5 -1
  68. package/src/activity.ts +154 -0
  69. package/src/assertExpect.ts +168 -0
  70. package/src/blind.ts +138 -0
  71. package/src/cli/addPages.ts +119 -17
  72. package/src/cli/main.ts +11 -0
  73. package/src/compare.ts +85 -0
  74. package/src/glossary.ts +36 -0
  75. package/src/health.ts +5 -3
  76. package/src/importCases.ts +172 -33
  77. package/src/index.ts +4 -0
  78. package/src/memoryStore.ts +2 -1
  79. package/src/readCheck.ts +458 -0
  80. package/src/runner.ts +33 -4
  81. package/src/settings.ts +192 -26
  82. package/src/store.ts +11 -3
  83. package/src/suggest.ts +33 -4
  84. package/src/suiteContract.ts +101 -0
  85. package/src/suites/crisisRisk.ts +250 -0
  86. package/src/suites/crisisRiskCases.ts +205 -0
  87. package/src/suites/index.ts +9 -0
  88. package/src/testing.ts +564 -127
  89. package/src/types.ts +141 -0
  90. package/src/weekly.ts +39 -3
  91. package/templates/app/evals/[suite]/compare/page.tsx +375 -0
  92. package/templates/app/evals/[suite]/page.tsx +55 -19
  93. package/templates/app/evals/[suite]/rate/page.tsx +133 -0
  94. package/templates/app/evals/[suite]/runs/[runId]/page.tsx +12 -0
  95. package/templates/app/evals/[suite]/side-by-side/page.tsx +300 -0
  96. package/templates/components/evalkeeper/DisagreementChip.tsx +35 -0
  97. package/templates/components/evalkeeper/RollBack.tsx +21 -1
  98. package/templates/components/evalkeeper/SettingsHistory.tsx +20 -2
  99. package/templates/components/evalkeeper/WeeklyCheck.tsx +34 -2
  100. package/templates/lib/evalkeeper/actions.ts +68 -4
  101. package/templates/lib/evalkeeper/weekly.ts +27 -4
@@ -0,0 +1,168 @@
1
+ import assert from "node:assert/strict";
2
+
3
+ /**
4
+ * The matchers the contracts in `@crowandraven/evalkeeper/testing` use, a
5
+ * small part of Vitest's and Jest's `expect`. Any `expect` with these
6
+ * works: Vitest's, the `expect` package, or `assertExpect`.
7
+ */
8
+ export type ContractMatchers = {
9
+ /** Passes when the value is the same one (`Object.is`). */
10
+ toBe(expected: unknown): void;
11
+ /** Passes when the value has the same content, ignoring undefined keys. */
12
+ toEqual(expected: unknown): void;
13
+ /** Passes when the value has at least these keys with these values. */
14
+ toMatchObject(expected: object): void;
15
+ /** Passes when the value's `length` is this. */
16
+ toHaveLength(length: number): void;
17
+ /** Passes when the value is null. */
18
+ toBeNull(): void;
19
+ /** Passes when the value is a number at least this. */
20
+ toBeGreaterThanOrEqual(expected: number): void;
21
+ /** Passes when the value is a number at most this. */
22
+ toBeLessThanOrEqual(expected: number): void;
23
+ /** For a promise: passes when it fails as described. */
24
+ rejects: {
25
+ /** Passes when the promise fails with an error whose message has this text. */
26
+ toThrow(expected: string): Promise<void>;
27
+ /** Passes when the promise fails with an instance of this class. */
28
+ toBeInstanceOf(
29
+ expected: abstract new (...args: never[]) => unknown,
30
+ ): Promise<void>;
31
+ };
32
+ };
33
+
34
+ /**
35
+ * An `expect` the contracts can use: takes a value (and a message to show
36
+ * when a check fails) and returns the matchers.
37
+ */
38
+ export type ContractExpect = (
39
+ actual: unknown,
40
+ message?: string,
41
+ ) => ContractMatchers;
42
+
43
+ function isPlainObject(v: unknown): v is Record<string, unknown> {
44
+ if (typeof v !== "object" || v === null) return false;
45
+ const proto: unknown = Object.getPrototypeOf(v);
46
+ return proto === Object.prototype || proto === null;
47
+ }
48
+
49
+ /** A copy without undefined keys, as Vitest's `toEqual` compares. */
50
+ function withoutUndefined(v: unknown): unknown {
51
+ if (Array.isArray(v)) return v.map(withoutUndefined);
52
+ if (!isPlainObject(v)) return v;
53
+ const out: Record<string, unknown> = {};
54
+ for (const [k, x] of Object.entries(v))
55
+ if (x !== undefined) out[k] = withoutUndefined(x);
56
+ return out;
57
+ }
58
+
59
+ /**
60
+ * The part of `actual` that `expected` names, so a deep comparison of the
61
+ * two checks only those keys (Vitest's `toMatchObject`).
62
+ */
63
+ function picked(actual: unknown, expected: unknown): unknown {
64
+ if (Array.isArray(expected) && Array.isArray(actual))
65
+ return actual.length === expected.length
66
+ ? actual.map((a, i) => picked(a, expected[i]))
67
+ : actual;
68
+ if (!isPlainObject(expected) || !isPlainObject(actual)) return actual;
69
+ const out: Record<string, unknown> = {};
70
+ for (const k of Object.keys(expected))
71
+ if (k in actual) out[k] = picked(actual[k], expected[k]);
72
+ return out;
73
+ }
74
+
75
+ async function failure(p: unknown): Promise<unknown> {
76
+ try {
77
+ await p;
78
+ } catch (e) {
79
+ return e;
80
+ }
81
+ throw new assert.AssertionError({
82
+ message: "Expected the promise to fail, but it succeeded",
83
+ });
84
+ }
85
+
86
+ /**
87
+ * An `expect` on `node:assert`, with just the matchers the contracts use,
88
+ * for running them outside Vitest (under `node:test`, say). Failures are
89
+ * `node:assert` errors, so any runner reports them.
90
+ *
91
+ * @param actual - The value to check.
92
+ * @param message - What to say when a check fails.
93
+ *
94
+ * @example
95
+ * ```ts
96
+ * import { describe, it } from "node:test";
97
+ * import { assertExpect, describeStoreContract } from "@crowandraven/evalkeeper/testing";
98
+ *
99
+ * describeStoreContract("my store", () => myStore(), {
100
+ * test: { describe, it, expect: assertExpect },
101
+ * });
102
+ * ```
103
+ */
104
+ export const assertExpect: ContractExpect = (actual, message) => ({
105
+ toBe(expected) {
106
+ assert.ok(
107
+ Object.is(actual, expected),
108
+ message ?? `Expected ${String(actual)} to be ${String(expected)}`,
109
+ );
110
+ },
111
+ toEqual(expected) {
112
+ assert.deepStrictEqual(
113
+ withoutUndefined(actual),
114
+ withoutUndefined(expected),
115
+ message,
116
+ );
117
+ },
118
+ toMatchObject(expected) {
119
+ assert.ok(
120
+ typeof actual === "object" && actual !== null,
121
+ message ?? "Expected an object",
122
+ );
123
+ assert.deepStrictEqual(
124
+ withoutUndefined(picked(actual, expected)),
125
+ withoutUndefined(expected),
126
+ message,
127
+ );
128
+ },
129
+ toHaveLength(length) {
130
+ const got: unknown =
131
+ typeof actual === "string" || Array.isArray(actual)
132
+ ? actual.length
133
+ : undefined;
134
+ assert.strictEqual(got, length, message);
135
+ },
136
+ toBeNull() {
137
+ assert.strictEqual(actual, null, message);
138
+ },
139
+ toBeGreaterThanOrEqual(expected) {
140
+ assert.ok(
141
+ typeof actual === "number" && actual >= expected,
142
+ message ?? `Expected ${String(actual)} to be at least ${expected}`,
143
+ );
144
+ },
145
+ toBeLessThanOrEqual(expected) {
146
+ assert.ok(
147
+ typeof actual === "number" && actual <= expected,
148
+ message ?? `Expected ${String(actual)} to be at most ${expected}`,
149
+ );
150
+ },
151
+ rejects: {
152
+ async toThrow(expected) {
153
+ const e = await failure(actual);
154
+ const text = e instanceof Error ? e.message : String(e);
155
+ assert.ok(
156
+ text.includes(expected),
157
+ message ?? `Expected an error saying "${expected}", got "${text}"`,
158
+ );
159
+ },
160
+ async toBeInstanceOf(expected) {
161
+ const e = await failure(actual);
162
+ assert.ok(
163
+ e instanceof expected,
164
+ message ?? `Expected an error of class ${expected.name}`,
165
+ );
166
+ },
167
+ },
168
+ });
package/src/blind.ts ADDED
@@ -0,0 +1,138 @@
1
+ import type { CaseRecord, NewLabel } from "./store.js";
2
+
3
+ /**
4
+ * Rating imported cases blind: one person at a time, shown only a case's
5
+ * input, gives the answer and a reason, or skips it. What someone did with
6
+ * an item isn't the answer (docs/lessons.md, "History isn't a verdict"),
7
+ * and seeing what the app decided anchors the rating, so the page hides it.
8
+ */
9
+
10
+ /**
11
+ * The `raterRole` on answers given by rating blind, so they can be told
12
+ * apart from answers written while looking at the app's output.
13
+ */
14
+ export const BLIND_RATER = "BLIND_RATER";
15
+
16
+ /**
17
+ * Where a case stands for one rater: they gave it an answer ("rated"),
18
+ * passed on it ("skipped"), or neither yet (null). Any answer of theirs
19
+ * counts as rated, whatever its status, so nobody is asked twice.
20
+ *
21
+ * @param c - The case, with its answers.
22
+ * @param raterId - The person rating, as your app identifies them.
23
+ */
24
+ export function raterStatus(
25
+ c: Pick<CaseRecord, "labels">,
26
+ raterId: string,
27
+ ): "rated" | "skipped" | null {
28
+ const theirs = c.labels.filter((l) => l.raterId === raterId);
29
+ if (theirs.some((l) => l.status !== "SKIPPED")) return "rated";
30
+ return theirs.length ? "skipped" : null;
31
+ }
32
+
33
+ /** One rater's place in a suite's blind rating. */
34
+ export type RateQueue = {
35
+ /** The oldest case they haven't rated or skipped; null when none is left. */
36
+ next: CaseRecord | null;
37
+ /** Cases they've given an answer. */
38
+ rated: number;
39
+ /** Cases they passed on. */
40
+ skipped: number;
41
+ /** Cases still waiting for them, the next one included. */
42
+ left: number;
43
+ };
44
+
45
+ /**
46
+ * One rater's queue over a suite's cases: the next case to rate (the
47
+ * oldest one they haven't rated or skipped) and how far along they are.
48
+ * Answers other people gave don't take a case out of the queue: each
49
+ * rater gives their own. Retired cases are left out.
50
+ *
51
+ * @param cases - The suite's cases, as `store.listCases` returns them.
52
+ * @param raterId - The person rating, as your app identifies them.
53
+ *
54
+ * @example
55
+ * ```ts
56
+ * const queue = rateQueue(await store.listCases("ticket_routing"), admin.id);
57
+ * if (queue.next) showInputOnly(queue.next.input);
58
+ * ```
59
+ */
60
+ export function rateQueue(
61
+ cases: readonly CaseRecord[],
62
+ raterId: string,
63
+ ): RateQueue {
64
+ const inUse = cases
65
+ .filter((c) => c.status !== "RETIRED")
66
+ .sort((a, b) => +a.createdAt - +b.createdAt);
67
+ let rated = 0;
68
+ let skipped = 0;
69
+ const waiting: CaseRecord[] = [];
70
+ for (const c of inUse) {
71
+ const s = raterStatus(c, raterId);
72
+ if (s === "rated") rated += 1;
73
+ else if (s === "skipped") skipped += 1;
74
+ else waiting.push(c);
75
+ }
76
+ return { next: waiting[0] ?? null, rated, skipped, left: waiting.length };
77
+ }
78
+
79
+ /**
80
+ * The oldest case this person hasn't rated or skipped, or null when none
81
+ * is left. See `rateQueue` for their progress too.
82
+ *
83
+ * @param cases - The suite's cases, as `store.listCases` returns them.
84
+ * @param raterId - The person rating, as your app identifies them.
85
+ */
86
+ export function nextToRate(
87
+ cases: readonly CaseRecord[],
88
+ raterId: string,
89
+ ): CaseRecord | null {
90
+ return rateQueue(cases, raterId).next;
91
+ }
92
+
93
+ /**
94
+ * A blind rating as an answer to add with `store.addLabel`: confirmed,
95
+ * since the person gave it themselves, recorded as theirs with their
96
+ * reason. It's added beside other people's answers, never over them.
97
+ * Throws when the reason is blank: a rating without one can't be checked
98
+ * later.
99
+ *
100
+ * @param r - Who rated, the answer (already read with the suite's
101
+ * `labelFromForm`), and why.
102
+ */
103
+ export function blindRating(r: {
104
+ raterId: string;
105
+ value: unknown;
106
+ reason: string;
107
+ }): NewLabel {
108
+ const reason = r.reason.trim();
109
+ if (!reason) throw new Error("Say why: a rating needs a reason");
110
+ if (!r.raterId) throw new Error("A rating needs a rater");
111
+ return {
112
+ kind: "EXPECTED",
113
+ status: "CONFIRMED",
114
+ value: r.value,
115
+ raterRole: BLIND_RATER,
116
+ raterId: r.raterId,
117
+ note: reason,
118
+ };
119
+ }
120
+
121
+ /**
122
+ * A mark that this person passed on a case, to add with `store.addLabel`.
123
+ * It has no value and is never graded against; it only keeps the case
124
+ * out of their queue.
125
+ *
126
+ * @param raterId - The person who skipped it.
127
+ */
128
+ export function skipMark(raterId: string): NewLabel {
129
+ if (!raterId) throw new Error("A skip needs a rater");
130
+ return {
131
+ kind: "EXPECTED",
132
+ status: "SKIPPED",
133
+ value: null,
134
+ raterRole: BLIND_RATER,
135
+ raterId,
136
+ note: null,
137
+ };
138
+ }
@@ -5,7 +5,7 @@ import {
5
5
  readdirSync,
6
6
  writeFileSync,
7
7
  } from "node:fs";
8
- import { dirname, join, relative } from "node:path";
8
+ import { basename, dirname, join, posix, relative } from "node:path";
9
9
 
10
10
  /**
11
11
  * `npx @crowandraven/evalkeeper add pages`: copies the eval pages, components, and their
@@ -30,6 +30,79 @@ export const TEMPLATE_FILES = {
30
30
  cron: ["app/api/cron/evals-weekly/route.ts"],
31
31
  } as const;
32
32
 
33
+ /** The pages, by the names `--only` takes. */
34
+ export const PAGE_NAMES: Readonly<Record<string, string>> = {
35
+ hub: "app/evals/page.tsx",
36
+ suite: "app/evals/[suite]/page.tsx",
37
+ run: "app/evals/[suite]/runs/[runId]/page.tsx",
38
+ rate: "app/evals/[suite]/rate/page.tsx",
39
+ compare: "app/evals/[suite]/compare/page.tsx",
40
+ "side-by-side": "app/evals/[suite]/side-by-side/page.tsx",
41
+ feedback: "app/evals/feedback/page.tsx",
42
+ cron: "app/api/cron/evals-weekly/route.ts",
43
+ };
44
+
45
+ /** The name `--only` knows a template file by: a page's, or the file's own. */
46
+ export function templateName(templatePath: string): string {
47
+ const page = Object.entries(PAGE_NAMES).find(([, p]) => p === templatePath);
48
+ return page ? page[0] : basename(templatePath).replace(/\.tsx?$/, "");
49
+ }
50
+
51
+ /**
52
+ * The template files `--only` picks: each name is a page (hub, suite,
53
+ * run, rate, compare, side-by-side, feedback, cron), a component or glue file by its name (AnswerKey,
54
+ * actions, evalkeeper.css), or a group (pages, components), in any case.
55
+ * "index" (the wiring module) is allowed and handled by `planAddPages`.
56
+ * Throws on a name it doesn't know, listing the ones it does.
57
+ */
58
+ export function pickOnly(sources: string[], only: string[]): string[] {
59
+ const groups: Record<string, (t: string) => boolean> = {
60
+ pages: (t) =>
61
+ Object.values(PAGE_NAMES).includes(t) && !t.includes("/cron/"),
62
+ components: (t) => t.startsWith("components/"),
63
+ };
64
+ const picked = new Set<string>();
65
+ for (const raw of only) {
66
+ const name = raw.trim().toLowerCase();
67
+ // Empty, or the wiring module, which isn't a template (see planAddPages).
68
+ if (!name || name === "index") continue;
69
+ const group = groups[name];
70
+ const matches = sources.filter((t) =>
71
+ group ? group(t) : templateName(t).toLowerCase() === name,
72
+ );
73
+ if (!matches.length)
74
+ throw new Error(
75
+ `--only: no page or component called "${raw.trim()}". Known: ${[
76
+ ...Object.keys(groups),
77
+ ...sources.map(templateName),
78
+ "index",
79
+ ].join(", ")}.`,
80
+ );
81
+ for (const m of matches) picked.add(m);
82
+ }
83
+ return sources.filter((t) => picked.has(t));
84
+ }
85
+
86
+ /**
87
+ * The template files `templatePath` imports from the copied set
88
+ * (components and glue), relative or through the alias. The wiring
89
+ * module is "lib/evalkeeper/index.ts".
90
+ */
91
+ export function importsOf(templatePath: string, text: string): string[] {
92
+ const found: string[] = [];
93
+ for (const m of text.matchAll(/from\s+["']([^"']+)["']/g)) {
94
+ const spec = m[1] ?? "";
95
+ let target: string;
96
+ if (spec.startsWith("@/")) target = spec.slice(2);
97
+ else if (spec.startsWith("."))
98
+ target = posix.join(posix.dirname(templatePath), spec);
99
+ else continue;
100
+ if (target === "lib/evalkeeper") found.push("lib/evalkeeper/index.ts");
101
+ else if (/^(components|lib)\/evalkeeper\//.test(target)) found.push(target);
102
+ }
103
+ return found;
104
+ }
105
+
33
106
  /**
34
107
  * What `addPages` needs: the app's folder, the templates, and the choices from the command line.
35
108
  */
@@ -49,6 +122,12 @@ export type AddPagesOptions = {
49
122
  cron?: boolean;
50
123
  force?: boolean;
51
124
  dryRun?: boolean;
125
+ /**
126
+ * Copy only these pages and components (see `pickOnly`), for an app
127
+ * that keeps its own where it has better ones. The wiring module is
128
+ * then written only if it's named ("index").
129
+ */
130
+ only?: string[];
52
131
  };
53
132
 
54
133
  /** One file the command would write, overwrite, or leave alone. */
@@ -158,6 +237,11 @@ export function planAddPages(o: AddPagesOptions): {
158
237
  alias: string;
159
238
  root: string;
160
239
  base: string;
240
+ /**
241
+ * Files the chosen ones import that are neither in the app nor being
242
+ * written, by their `--only` names. Empty without `--only`.
243
+ */
244
+ needs: string[];
161
245
  } {
162
246
  const base = cleanBase(o.base ?? "evals");
163
247
  const found = readAlias(o.cwd);
@@ -173,7 +257,7 @@ export function planAddPages(o: AddPagesOptions): {
173
257
  `No app folder at ${relative(o.cwd, join(rootDir, "app")) || "app"}: Evalkeeper's pages are for the Next.js App Router.`,
174
258
  );
175
259
 
176
- const sources = [
260
+ const all = [
177
261
  ...TEMPLATE_FILES.always,
178
262
  ...(o.cron === false ? [] : TEMPLATE_FILES.cron),
179
263
  ].flatMap((entry) => {
@@ -184,8 +268,11 @@ export function planAddPages(o: AddPagesOptions): {
184
268
  );
185
269
  return entry.endsWith(".ts") || entry.endsWith(".tsx")
186
270
  ? [entry]
187
- : listFiles(full).map((f) => relative(o.templatesDir, f));
271
+ : listFiles(full).map((f) =>
272
+ relative(o.templatesDir, f).split("\\").join("/"),
273
+ );
188
274
  });
275
+ const sources = o.only ? pickOnly(all, o.only) : all;
189
276
 
190
277
  const plan = (path: string, contents: string, alwaysSkipExisting = false) => {
191
278
  const exists = existsSync(join(o.cwd, path));
@@ -207,17 +294,32 @@ export function planAddPages(o: AddPagesOptions): {
207
294
  ),
208
295
  );
209
296
  // The wiring module is the app's own: written once, never overwritten.
210
- files.push(
211
- plan(
212
- join(root, "lib/evalkeeper/index.ts"),
213
- fitFile("lib/evalkeeper/index.ts", readFileSync(o.starterFile, "utf8"), {
214
- alias,
215
- base,
216
- }),
217
- true,
218
- ),
219
- );
220
- return { files, alias, root, base };
297
+ const wiring = "lib/evalkeeper/index.ts";
298
+ if (!o.only || o.only.some((n) => n.trim().toLowerCase() === "index"))
299
+ files.push(
300
+ plan(
301
+ join(root, wiring),
302
+ fitFile(wiring, readFileSync(o.starterFile, "utf8"), { alias, base }),
303
+ true,
304
+ ),
305
+ );
306
+
307
+ // What the chosen files import that the app won't have.
308
+ const has = (t: string) =>
309
+ sources.includes(t) ||
310
+ (t === wiring && files.some((f) => f.path === join(root, wiring))) ||
311
+ [t, `${t}.ts`, `${t}.tsx`].some((p) =>
312
+ existsSync(join(rootDir, destinationOf(p, base))),
313
+ );
314
+ const needs = new Set<string>();
315
+ if (o.only)
316
+ for (const t of sources)
317
+ for (const dep of importsOf(
318
+ t,
319
+ readFileSync(join(o.templatesDir, t), "utf8"),
320
+ ))
321
+ if (!has(dep)) needs.add(templateName(dep));
322
+ return { files, alias, root, base, needs: [...needs] };
221
323
  }
222
324
 
223
325
  /** Writes the plan (unless it's a dry run) and returns it. */
@@ -248,9 +350,9 @@ export function nextSteps(r: {
248
350
  "npm install @crowandraven/evalkeeper @crowandraven/evalkeeper-prisma @crowandraven/evalkeeper-ai-sdk server-only lucide-react",
249
351
  "Add Evalkeeper's models to your Prisma schema (node_modules/@crowandraven/evalkeeper-prisma/schema/evalkeeper.prisma), then write a migration from the schema file.",
250
352
  `Import the colors into your global CSS, right after Tailwind: @import "${css}"; (a path relative to that CSS file).`,
251
- wiring?.action === "skip"
252
- ? `Check ${wiring.path} exports what the pages use: MODELS, availableModels, modelsFor, SUITES, SUITE_BY_KEY, store, feedbackStore, settings, routeFor, runner, and requireAdmin.`
253
- : `Fill in ${wiring?.path ?? "lib/evalkeeper/index.ts"}: your Prisma client, models, suites, and requireAdmin (until then, nobody can open the pages).`,
353
+ !wiring || wiring.action === "skip"
354
+ ? `Check ${wiring?.path ?? join(r.root, "lib/evalkeeper/index.ts")} exports what the pages use: MODELS, availableModels, modelsFor, SUITES, SUITE_BY_KEY, store, feedbackStore, settings, routeFor, runner, and requireAdmin.`
355
+ : `Fill in ${wiring.path}: your Prisma client, models, suites, and requireAdmin (until then, nobody can open the pages).`,
254
356
  `Open /${r.base} in your app.`,
255
357
  ];
256
358
  }
package/src/cli/main.ts CHANGED
@@ -20,6 +20,11 @@ Options:
20
20
  --alias <name> Your import alias, e.g. "@" or "~" (default: from tsconfig.json)
21
21
  --root <dir> Where the alias points, e.g. "src" (default: from tsconfig.json)
22
22
  --no-cron Leave out the weekly check's cron route
23
+ --only <names> Copy only these, comma-separated: pages (hub, suite, run,
24
+ rate, compare, side-by-side, feedback, cron), components
25
+ and glue by name (AnswerKey, actions, …), the groups
26
+ "pages" and "components", or "index" for a starter
27
+ lib/evalkeeper/index.ts
23
28
  --force Overwrite files that already exist (never your lib/evalkeeper/index.ts)
24
29
  --dry-run Show what would be written, and write nothing
25
30
  --help Show this
@@ -57,6 +62,8 @@ export function parseArgs(argv: string[]): Partial<AddPagesOptions> & {
57
62
  else if (a === "--no-cron") out.cron = false;
58
63
  else if (a === "--force") out.force = true;
59
64
  else if (a === "--dry-run") out.dryRun = true;
65
+ else if (a === "--only")
66
+ out.only = [...(out.only ?? []), ...value().split(",")];
60
67
  else if (a.startsWith("--")) throw new Error(`Unknown option ${a}`);
61
68
  else out.command.push(a);
62
69
  }
@@ -114,6 +121,10 @@ export function run(
114
121
  io.log(
115
122
  `\n${skipped} file${skipped === 1 ? "" : "s"} already existed and stayed as they are. --force overwrites them (your lib/evalkeeper/index.ts never).`,
116
123
  );
124
+ if (result.needs.length)
125
+ io.log(
126
+ `\nThese import ${result.needs.join(", ")}, which your app doesn't have: add them to --only, or point the imports at your own.`,
127
+ );
117
128
  io.log("\nNext:");
118
129
  for (const [i, step] of nextSteps(result).entries())
119
130
  io.log(` ${i + 1}. ${step}`);
package/src/compare.ts CHANGED
@@ -259,3 +259,88 @@ export function verdictSentence(c: Comparison, challengerName: string): string {
259
259
  return `No clear difference: ${challengerName} is somewhere between ${Math.round(c.low * 100)} and ${c.high > 0 ? "+" : ""}${Math.round(c.high * 100)} points${cost}.`;
260
260
  }
261
261
  }
262
+
263
+ /**
264
+ * How two tests' answers to one case differ: the challenger broke a case
265
+ * the champion got fully right, fixed one the champion didn't, or both
266
+ * missed it in different ways (other checks failed, or one gave no answer).
267
+ */
268
+ export type DisagreementKind = "broke" | "fixed" | "differ";
269
+
270
+ /** One case the two tests graded differently, for reading side by side. */
271
+ export type Disagreement = {
272
+ caseId: string;
273
+ kind: DisagreementKind;
274
+ /** Each test's score on the case, averaged over its repeats (0 to 1). */
275
+ champion: number;
276
+ challenger: number;
277
+ };
278
+
279
+ /** The order disagreements are listed in: what got worse first. */
280
+ const KIND_ORDER: Record<DisagreementKind, number> = {
281
+ broke: 0,
282
+ fixed: 1,
283
+ differ: 2,
284
+ };
285
+
286
+ /** What went wrong on a case across its repeats: failed checks, and "no answer". */
287
+ function missesByCase(outputs: RunOutput[]): Map<string, string> {
288
+ const by = new Map<string, Set<string>>();
289
+ for (const o of outputs) {
290
+ const misses = by.get(o.caseId) ?? new Set<string>();
291
+ if (!o.checks) misses.add("(no answer)");
292
+ for (const c of o.checks ?? []) if (c.pass === false) misses.add(c.key);
293
+ by.set(o.caseId, misses);
294
+ }
295
+ return new Map([...by].map(([id, m]) => [id, [...m].sort().join("|")]));
296
+ }
297
+
298
+ /**
299
+ * The cases two tests graded differently, on the cases they share: a
300
+ * different score, different checks failed, or an answer on one side and
301
+ * none on the other. Cases the challenger broke come first, then fixed,
302
+ * then the rest, each in case order. Use it to read where two models
303
+ * disagree: next to `compareRuns`, which says by how much.
304
+ *
305
+ * @param champion - The answers of the test in place (usually the live model's).
306
+ * @param challenger - The answers of the test it's compared with.
307
+ */
308
+ export function disagreements(
309
+ champion: RunOutput[],
310
+ challenger: RunOutput[],
311
+ ): Disagreement[] {
312
+ const a = passShareByCase(champion);
313
+ const b = passShareByCase(challenger);
314
+ const ma = missesByCase(champion);
315
+ const mb = missesByCase(challenger);
316
+ const found: Disagreement[] = [];
317
+ for (const id of [...a.keys()].filter((k) => b.has(k)).sort()) {
318
+ const sa = mustGet(a, id);
319
+ const sb = mustGet(b, id);
320
+ if (sa === sb && ma.get(id) === mb.get(id)) continue;
321
+ const kind: DisagreementKind =
322
+ sa === 1 && sb < 1 ? "broke" : sb === 1 && sa < 1 ? "fixed" : "differ";
323
+ found.push({ caseId: id, kind, champion: sa, challenger: sb });
324
+ }
325
+ return found.sort((x, y) => KIND_ORDER[x.kind] - KIND_ORDER[y.kind]);
326
+ }
327
+
328
+ /**
329
+ * Where a case sits in a list of disagreements, and the cases before and
330
+ * after it, for stepping through them one at a time. `index` is -1 (and
331
+ * `previous` null, `next` the first) when the case isn't in the list.
332
+ *
333
+ * @param list - The disagreements, in the order they're read.
334
+ * @param caseId - The case being read now.
335
+ */
336
+ export function aroundCase(
337
+ list: Disagreement[],
338
+ caseId: string,
339
+ ): { index: number; previous: string | null; next: string | null } {
340
+ const index = list.findIndex((d) => d.caseId === caseId);
341
+ return {
342
+ index,
343
+ previous: index > 0 ? (list[index - 1]?.caseId ?? null) : null,
344
+ next: list[index + 1]?.caseId ?? null,
345
+ };
346
+ }
package/src/glossary.ts CHANGED
@@ -49,12 +49,23 @@ export const GLOSSARY = {
49
49
  "Keeps what you typed, without your name, so it can become a test case for future models. Without it, a rating still counts but can't become a case.",
50
50
  makeCase:
51
51
  "Turns this rating into a draft case on its real input. A thumbs down needs a person to write the right answer; a thumbs up proposes the model's answer for a person to confirm.",
52
+ rateBlind:
53
+ "Rating imported cases one at a time from their input alone, never the app's output or what anyone did, so nothing anchors your answer. Each rating is your own confirmed answer, kept beside other people's.",
54
+ rateQueue:
55
+ "Your progress: cases you rated, cases you skipped, and cases still waiting for you, oldest first. Other people's answers don't count toward yours.",
56
+ skip: "Passes on this case for you only. It gives no answer and changes no test; others can still rate it, and you can still answer it in the answer key.",
52
57
  needsAnswer:
53
58
  "A draft case with no answer yet. Write what a good answer is; until then, tests leave it out.",
54
59
  weeklyCheck:
55
60
  "Each suite's quick set, answered again on its live model every week. A drop of 15 points or more against last week's check of the same model, instructions, and grading is drift.",
61
+ activityDraft:
62
+ "A case drafted from what the feature saw in your app this week. Its answer is pending or missing until a person reviews it, and tests leave it out until then.",
56
63
  versions:
57
64
  "Each numbered version of this feature's settings (model, fallback, reasoning, output limit, temperature), with who changed it, when, why, and its evidence. Any version can be made live again.",
65
+ changedOutside:
66
+ "The app's own settings no longer matched the live version: a script, SQL, or another page changed them. Recorded as found, before the next save, so you can roll back to it.",
67
+ instructionsEdited:
68
+ "Instructions edited at runtime (an admin override or added guidance) changed under the live settings. Dated when noticed, which can be after the edit.",
58
69
  suites:
59
70
  "One suite per AI feature: its cases, the answers people confirmed, and the checks that grade any model against them. Open one to compare models and choose the live one.",
60
71
  answerKey:
@@ -69,6 +80,31 @@ export const GLOSSARY = {
69
80
  "The model returns its own probabilities for every option, so they can be scored and compared.",
70
81
  promptedProbabilities:
71
82
  "The model writes out its own estimate. Choices come without a distribution, so only true-or-false questions get probability scores.",
83
+ comparison:
84
+ "Two finished tests of one suite, compared case by case on the cases both answered, so which cases each happened to get can't decide it.",
85
+ inPlace:
86
+ "The test the other is weighed against, usually the live model's. Differences are counted from it.",
87
+ challenger:
88
+ "The test weighed against the one in place: another model, reasoning setting, or set of instructions.",
89
+ verdict:
90
+ "More accurate, about as accurate, or less accurate, read off a 95% range from resampling the shared cases. Under 5 shared cases, too few to tell.",
91
+ sharedCases: "Cases both tests answered. Only these are compared.",
92
+ measuredDifferently:
93
+ "The tests differ in more than the model: other cases, answers, checks, or instructions. Rescore both, or test again, before trusting the verdict.",
94
+ passRate:
95
+ "How often the check passed on the answers it applies to, and on how many answers.",
96
+ disagreements:
97
+ "Cases the two tests graded differently. About as accurate can hide cases one model gets right and the other wrong, so read them side by side.",
98
+ broke: "The test in place got this case fully right; the challenger didn't.",
99
+ fixed: "The challenger got this case fully right; the test in place didn't.",
100
+ missedDifferently:
101
+ "Neither got this case fully right, but they missed it in different ways: other checks failed, fewer parts right, or no answer on one side.",
102
+ caseScore:
103
+ "A test's score on this one case: 100% when every check passed, or parts right of parts expected with partial credit, averaged over repeats.",
104
+ sideBySide:
105
+ "Both tests' answers to one case, next to the expected answer, with what each check found. Step through every case where they differ.",
106
+ expectedAnswer:
107
+ "The answer the checks grade against: confirmed by a person, or provisional when put to use before review.",
72
108
  } as const;
73
109
 
74
110
  /** A word the glossary defines, for tooltips. */