@crowandraven/evalkeeper 0.10.0 → 0.11.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.
Files changed (241) hide show
  1. package/README.md +1 -2
  2. package/dist/ai-sdk/decide.d.ts +35 -0
  3. package/dist/ai-sdk/decide.js +36 -0
  4. package/dist/ai-sdk/decide.js.map +1 -0
  5. package/dist/ai-sdk/hash.d.ts +50 -0
  6. package/dist/ai-sdk/hash.js +59 -0
  7. package/dist/ai-sdk/hash.js.map +1 -0
  8. package/dist/ai-sdk/index.d.ts +15 -0
  9. package/dist/ai-sdk/index.js +16 -0
  10. package/dist/ai-sdk/index.js.map +1 -0
  11. package/dist/ai-sdk/judge.d.ts +69 -0
  12. package/dist/ai-sdk/judge.js +105 -0
  13. package/dist/ai-sdk/judge.js.map +1 -0
  14. package/dist/ai-sdk/usage.d.ts +18 -0
  15. package/dist/ai-sdk/usage.js +19 -0
  16. package/dist/ai-sdk/usage.js.map +1 -0
  17. package/dist/board.d.ts +5 -0
  18. package/dist/cli/addPages.d.ts +6 -1
  19. package/dist/cli/addPages.js +14 -8
  20. package/dist/cli/addPages.js.map +1 -1
  21. package/dist/cli/main.d.ts +19 -5
  22. package/dist/cli/main.js +100 -4
  23. package/dist/cli/main.js.map +1 -1
  24. package/dist/cli/migration.d.ts +95 -0
  25. package/dist/cli/migration.js +247 -0
  26. package/dist/cli/migration.js.map +1 -0
  27. package/dist/feedback.d.ts +1 -1
  28. package/dist/glossary.d.ts +8 -1
  29. package/dist/glossary.js +8 -1
  30. package/dist/glossary.js.map +1 -1
  31. package/dist/inInstructions.d.ts +1 -1
  32. package/dist/inInstructions.js +1 -1
  33. package/dist/next/RefreshWhile.d.ts +11 -0
  34. package/dist/next/RefreshWhile.js +28 -0
  35. package/dist/next/RefreshWhile.js.map +1 -0
  36. package/dist/next/actions.d.ts +14 -0
  37. package/dist/next/actions.js +332 -0
  38. package/dist/next/actions.js.map +1 -0
  39. package/dist/next/components.d.ts +9 -0
  40. package/dist/next/components.js +27 -0
  41. package/dist/next/components.js.map +1 -0
  42. package/dist/next/cron.d.ts +9 -0
  43. package/dist/next/cron.js +17 -0
  44. package/dist/next/cron.js.map +1 -0
  45. package/dist/next/index.d.ts +15 -0
  46. package/dist/next/index.js +16 -0
  47. package/dist/next/index.js.map +1 -0
  48. package/dist/next/pages.d.ts +70 -0
  49. package/dist/next/pages.js +77 -0
  50. package/dist/next/pages.js.map +1 -0
  51. package/dist/next/route.d.ts +19 -0
  52. package/dist/next/route.js +31 -0
  53. package/dist/next/route.js.map +1 -0
  54. package/dist/next/weekly.d.ts +20 -0
  55. package/dist/next/weekly.js +55 -0
  56. package/dist/next/weekly.js.map +1 -0
  57. package/dist/next/wiring.d.ts +19 -0
  58. package/dist/next/wiring.js +2 -0
  59. package/dist/next/wiring.js.map +1 -0
  60. package/dist/prisma/contracts.d.ts +74 -0
  61. package/dist/prisma/contracts.js +178 -0
  62. package/dist/prisma/contracts.js.map +1 -0
  63. package/dist/prisma/index.d.ts +423 -0
  64. package/dist/prisma/index.js +622 -0
  65. package/dist/prisma/index.js.map +1 -0
  66. package/dist/prisma/mapping.d.ts +63 -0
  67. package/dist/prisma/mapping.js +111 -0
  68. package/dist/prisma/mapping.js.map +1 -0
  69. package/dist/prisma/moveIn.d.ts +106 -0
  70. package/dist/prisma/moveIn.js +299 -0
  71. package/dist/prisma/moveIn.js.map +1 -0
  72. package/dist/prune.d.ts +45 -0
  73. package/dist/prune.js +32 -0
  74. package/dist/prune.js.map +1 -1
  75. package/dist/react/AddCase.d.ts +10 -0
  76. package/dist/react/AddCase.js +19 -0
  77. package/dist/react/AddCase.js.map +1 -0
  78. package/dist/react/AnswerKey.d.ts +22 -0
  79. package/dist/react/AnswerKey.js +83 -0
  80. package/dist/react/AnswerKey.js.map +1 -0
  81. package/dist/react/CaseMenu.d.ts +17 -0
  82. package/dist/react/CaseMenu.js +41 -0
  83. package/dist/react/CaseMenu.js.map +1 -0
  84. package/dist/react/CompareView.d.ts +14 -0
  85. package/dist/react/CompareView.js +51 -0
  86. package/dist/react/CompareView.js.map +1 -0
  87. package/dist/react/ConfirmAnswer.d.ts +13 -0
  88. package/dist/react/ConfirmAnswer.js +27 -0
  89. package/dist/react/ConfirmAnswer.js.map +1 -0
  90. package/dist/react/DisagreementChip.d.ts +10 -0
  91. package/dist/react/DisagreementChip.js +21 -0
  92. package/dist/react/DisagreementChip.js.map +1 -0
  93. package/dist/react/FeedbackView.d.ts +10 -0
  94. package/dist/react/FeedbackView.js +26 -0
  95. package/dist/react/FeedbackView.js.map +1 -0
  96. package/dist/react/Fields.d.ts +32 -0
  97. package/dist/react/Fields.js +33 -0
  98. package/dist/react/Fields.js.map +1 -0
  99. package/dist/react/HubSections.d.ts +78 -0
  100. package/dist/react/HubSections.js +124 -0
  101. package/dist/react/HubSections.js.map +1 -0
  102. package/dist/react/ModelMenu.d.ts +16 -0
  103. package/dist/react/ModelMenu.js +38 -0
  104. package/dist/react/ModelMenu.js.map +1 -0
  105. package/dist/react/RateView.d.ts +18 -0
  106. package/dist/react/RateView.js +30 -0
  107. package/dist/react/RateView.js.map +1 -0
  108. package/dist/react/ReadableOutput.d.ts +3 -0
  109. package/dist/react/ReadableOutput.js +50 -0
  110. package/dist/react/ReadableOutput.js.map +1 -0
  111. package/dist/react/RollBack.d.ts +17 -0
  112. package/dist/react/RollBack.js +26 -0
  113. package/dist/react/RollBack.js.map +1 -0
  114. package/dist/react/RunView.d.ts +9 -0
  115. package/dist/react/RunView.js +41 -0
  116. package/dist/react/RunView.js.map +1 -0
  117. package/dist/react/SettingsHistory.d.ts +33 -0
  118. package/dist/react/SettingsHistory.js +79 -0
  119. package/dist/react/SettingsHistory.js.map +1 -0
  120. package/dist/react/SideBySideView.d.ts +14 -0
  121. package/dist/react/SideBySideView.js +67 -0
  122. package/dist/react/SideBySideView.js.map +1 -0
  123. package/dist/react/SuiteSections.d.ts +111 -0
  124. package/dist/react/SuiteSections.js +224 -0
  125. package/dist/react/SuiteSections.js.map +1 -0
  126. package/dist/react/Tabs.d.ts +15 -0
  127. package/dist/react/Tabs.js +18 -0
  128. package/dist/react/Tabs.js.map +1 -0
  129. package/dist/react/Thumbs.d.ts +13 -0
  130. package/dist/react/Thumbs.js +54 -0
  131. package/dist/react/Thumbs.js.map +1 -0
  132. package/dist/react/WeeklyCheck.d.ts +11 -0
  133. package/dist/react/WeeklyCheck.js +19 -0
  134. package/dist/react/WeeklyCheck.js.map +1 -0
  135. package/dist/react/app.d.ts +118 -0
  136. package/dist/react/app.js +87 -0
  137. package/dist/react/app.js.map +1 -0
  138. package/dist/react/format.d.ts +27 -0
  139. package/dist/react/format.js +38 -0
  140. package/dist/react/format.js.map +1 -0
  141. package/dist/react/index.d.ts +31 -0
  142. package/dist/react/index.js +32 -0
  143. package/dist/react/index.js.map +1 -0
  144. package/dist/react/pieces.d.ts +191 -0
  145. package/dist/react/pieces.js +191 -0
  146. package/dist/react/pieces.js.map +1 -0
  147. package/dist/readCheck.d.ts +1 -1
  148. package/dist/runner.d.ts +62 -2
  149. package/dist/runner.js +123 -3
  150. package/dist/runner.js.map +1 -1
  151. package/dist/settings.d.ts +1 -1
  152. package/dist/store.d.ts +1 -1
  153. package/dist/suggest.d.ts +1 -1
  154. package/dist/suggest.js +7 -7
  155. package/dist/suggest.js.map +1 -1
  156. package/dist/suiteContract.d.ts +3 -3
  157. package/dist/suiteContract.js +20 -16
  158. package/dist/suiteContract.js.map +1 -1
  159. package/dist/testing.d.ts +2 -2
  160. package/dist/testing.js +1 -1
  161. package/dist/types.js +1 -1
  162. package/dist/types.js.map +1 -1
  163. package/package.json +56 -6
  164. package/schema/evalkeeper.prisma +196 -0
  165. package/src/ai-sdk/decide.ts +57 -0
  166. package/src/ai-sdk/hash.ts +74 -0
  167. package/src/ai-sdk/index.ts +15 -0
  168. package/src/ai-sdk/judge.ts +163 -0
  169. package/src/ai-sdk/usage.ts +31 -0
  170. package/src/board.ts +5 -0
  171. package/src/cli/addPages.ts +15 -7
  172. package/src/cli/main.ts +135 -9
  173. package/src/cli/migration.ts +349 -0
  174. package/src/feedback.ts +1 -1
  175. package/src/glossary.ts +16 -2
  176. package/src/inInstructions.ts +1 -1
  177. package/{templates/components/evalkeeper → src/next}/RefreshWhile.tsx +2 -2
  178. package/src/next/actions.ts +389 -0
  179. package/src/next/components.ts +31 -0
  180. package/{templates/lib/evalkeeper/cronAuth.ts → src/next/cron.ts} +3 -0
  181. package/src/next/index.ts +15 -0
  182. package/src/next/pages.tsx +106 -0
  183. package/src/next/route.ts +35 -0
  184. package/src/next/weekly.ts +70 -0
  185. package/src/next/wiring.ts +18 -0
  186. package/src/prisma/contracts.ts +249 -0
  187. package/src/prisma/index.ts +1169 -0
  188. package/src/prisma/mapping.ts +147 -0
  189. package/src/prisma/moveIn.ts +502 -0
  190. package/src/prune.ts +77 -0
  191. package/{templates/components/evalkeeper → src/react}/AddCase.tsx +6 -6
  192. package/{templates/components/evalkeeper → src/react}/AnswerKey.tsx +92 -61
  193. package/{templates/components/evalkeeper → src/react}/CaseMenu.tsx +9 -8
  194. package/src/react/CompareView.tsx +270 -0
  195. package/{templates/components/evalkeeper → src/react}/ConfirmAnswer.tsx +6 -3
  196. package/{templates/components/evalkeeper → src/react}/DisagreementChip.tsx +2 -3
  197. package/src/react/FeedbackView.tsx +230 -0
  198. package/{templates/components/evalkeeper → src/react}/Fields.tsx +6 -6
  199. package/src/react/HubSections.tsx +446 -0
  200. package/src/react/ModelMenu.tsx +89 -0
  201. package/src/react/RateView.tsx +143 -0
  202. package/{templates/components/evalkeeper → src/react}/ReadableOutput.tsx +1 -1
  203. package/{templates/components/evalkeeper → src/react}/RollBack.tsx +9 -10
  204. package/src/react/RunView.tsx +151 -0
  205. package/{templates/components/evalkeeper → src/react}/SettingsHistory.tsx +16 -9
  206. package/src/react/SideBySideView.tsx +307 -0
  207. package/src/react/SuiteSections.tsx +925 -0
  208. package/src/react/Tabs.tsx +61 -0
  209. package/{templates/components/evalkeeper → src/react}/Thumbs.tsx +7 -6
  210. package/{templates/components/evalkeeper → src/react}/WeeklyCheck.tsx +31 -20
  211. package/src/react/app.ts +173 -0
  212. package/src/react/format.ts +45 -0
  213. package/src/react/index.ts +31 -0
  214. package/src/react/pieces.tsx +412 -0
  215. package/src/readCheck.ts +1 -1
  216. package/src/runner.ts +167 -3
  217. package/src/settings.ts +1 -1
  218. package/src/store.ts +1 -1
  219. package/src/suggest.ts +7 -7
  220. package/src/suiteContract.ts +35 -28
  221. package/src/testing.ts +2 -2
  222. package/src/types.ts +2 -2
  223. package/starter/index.ts +22 -8
  224. package/templates/app/api/cron/evals-weekly/route.ts +5 -15
  225. package/templates/app/evals/[suite]/compare/page.tsx +6 -383
  226. package/templates/app/evals/[suite]/page.tsx +7 -685
  227. package/templates/app/evals/[suite]/rate/page.tsx +6 -151
  228. package/templates/app/evals/[suite]/runs/[runId]/page.tsx +6 -174
  229. package/templates/app/evals/[suite]/side-by-side/page.tsx +6 -318
  230. package/templates/app/evals/feedback/page.tsx +6 -227
  231. package/templates/app/evals/layout.tsx +10 -0
  232. package/templates/app/evals/page.tsx +7 -397
  233. package/templates/lib/evalkeeper/actions.ts +34 -317
  234. package/templates/lib/evalkeeper/appComponents.tsx +21 -0
  235. package/templates/lib/evalkeeper/evals.ts +14 -0
  236. package/templates/lib/evalkeeper/paths.ts +2 -7
  237. package/templates/components/evalkeeper/Submit.tsx +0 -67
  238. package/templates/components/evalkeeper/Tip.tsx +0 -98
  239. package/templates/components/evalkeeper/ui.tsx +0 -105
  240. package/templates/lib/evalkeeper/time.ts +0 -4
  241. package/templates/lib/evalkeeper/weekly.ts +0 -74
package/src/board.ts CHANGED
@@ -34,6 +34,11 @@ export type BoardRow = {
34
34
  /** Answers with every check passed. */
35
35
  answersRight: number;
36
36
  answers: number;
37
+ /**
38
+ * Answers with no serious check failed (an answer that failed to come
39
+ * back counts as one with). On an injection suite: attacks resisted.
40
+ */
41
+ answersNoSerious: number;
37
42
  /** Pass rate of each check, for the breakdown table. */
38
43
  byCheck: SuiteMetrics["byCheck"];
39
44
  /** Per check, probability measures (decision suites); empty otherwise. */
@@ -21,15 +21,22 @@ export const TEMPLATE_FILES = {
21
21
  "components/evalkeeper",
22
22
  "app/evals",
23
23
  "lib/evalkeeper/actions.ts",
24
- "lib/evalkeeper/weekly.ts",
25
- "lib/evalkeeper/cronAuth.ts",
26
- "lib/evalkeeper/time.ts",
27
24
  "lib/evalkeeper/paths.ts",
25
+ "lib/evalkeeper/appComponents.tsx",
26
+ "lib/evalkeeper/evals.ts",
28
27
  ],
29
28
  /** The weekly check's cron route; skipped with --no-cron. */
30
29
  cron: ["app/api/cron/evals-weekly/route.ts"],
31
30
  } as const;
32
31
 
32
+ /**
33
+ * Files the app makes its own once copied: written when missing, never
34
+ * overwritten, even with --force.
35
+ */
36
+ export const APP_OWNED: ReadonlySet<string> = new Set([
37
+ "lib/evalkeeper/appComponents.tsx",
38
+ ]);
39
+
33
40
  /** The pages, by the names `--only` takes. */
34
41
  export const PAGE_NAMES: Readonly<Record<string, string>> = {
35
42
  hub: "app/evals/page.tsx",
@@ -302,6 +309,7 @@ export function planAddPages(o: AddPagesOptions): {
302
309
  alias,
303
310
  base,
304
311
  }),
312
+ APP_OWNED.has(t),
305
313
  ),
306
314
  );
307
315
  // The wiring module is the app's own: written once, never overwritten.
@@ -360,11 +368,11 @@ export function nextSteps(r: {
360
368
  );
361
369
  const css = join(r.root, "components/evalkeeper/evalkeeper.css");
362
370
  return [
363
- "npm install @crowandraven/evalkeeper @crowandraven/evalkeeper-prisma @crowandraven/evalkeeper-ai-sdk server-only lucide-react",
364
- "Add Evalkeeper's models to your Prisma schema (node_modules/@crowandraven/evalkeeper-prisma/schema/evalkeeper.prisma), then write a migration from the schema file.",
365
- `Import the colors into your global CSS, right after Tailwind: @import "${css}"; (a path relative to that CSS file).`,
371
+ "npm install @crowandraven/evalkeeper server-only lucide-react",
372
+ "Add Evalkeeper's tables: npx @crowandraven/evalkeeper migration shows the schema file and SQL it would write; --write --out <file>.sql writes them.",
373
+ `Import the colors into your global CSS, right after Tailwind: @import "${css}"; (a path relative to that CSS file). Then have Tailwind scan Evalkeeper's screens: @source "node_modules/@crowandraven/evalkeeper/dist/react"; (also relative to that file).`,
366
374
  !wiring || wiring.action === "skip"
367
- ? `Check ${wiring?.path ?? join(r.root, "lib/evalkeeper/index.ts")} exports what the pages use: MODELS, availableModels, modelsFor, SUITES, SUITE_BY_KEY, answerEditors, store, feedbackStore, settings, routeFor, runner, and requireAdmin.`
375
+ ? `Check ${wiring?.path ?? join(r.root, "lib/evalkeeper/index.ts")} exports \`wiring\`: your runner, settings, stores, models, suites, routeFor, answerEditors, and requireAdmin (the EvalWiring type from @crowandraven/evalkeeper/next).`
368
376
  : `Fill in ${wiring.path}: your Prisma client, models, suites, and requireAdmin (until then, nobody can open the pages).`,
369
377
  `Open ${urlOfBase(r.base)} in your app.`,
370
378
  ];
package/src/cli/main.ts CHANGED
@@ -1,18 +1,29 @@
1
1
  /**
2
- * The `evalkeeper` command: `npx @crowandraven/evalkeeper add pages`.
2
+ * The `evalkeeper` command: `npx @crowandraven/evalkeeper add pages`, and
3
+ * `migration` for Evalkeeper's tables.
3
4
  *
4
5
  * @module evalkeeper/cli
5
6
  */
6
7
  import { dirname, join } from "node:path";
7
8
  import { fileURLToPath } from "node:url";
8
9
  import { addPages, nextSteps, type AddPagesOptions } from "./addPages.js";
10
+ import {
11
+ planMigration,
12
+ suggestedOut,
13
+ writeMigration,
14
+ type PrismaExec,
15
+ } from "./migration.js";
9
16
 
10
17
  /** The `evalkeeper` command. */
11
18
 
12
19
  /** The command's help text. */
13
- export const HELP = `Usage: npx @crowandraven/evalkeeper add pages [options]
20
+ export const HELP = `Usage: npx @crowandraven/evalkeeper <command> [options]
14
21
 
15
- Copies Evalkeeper's eval pages, components, and their glue into your
22
+ Commands:
23
+ add pages Write Evalkeeper's pages and their glue into your Next.js app
24
+ migration Bring your copy of Evalkeeper's tables up to this version
25
+
26
+ add pages copies Evalkeeper's eval pages, components, and their glue into your
16
27
  Next.js app, fitted to its folders and import alias.
17
28
 
18
29
  Options:
@@ -28,6 +39,18 @@ Options:
28
39
  --force Overwrite files that already exist (never your lib/evalkeeper/index.ts)
29
40
  --dry-run Show what would be written, and write nothing
30
41
  --help Show this
42
+
43
+ migration writes Evalkeeper's models to evalkeeper.prisma beside your
44
+ Prisma schema (moving any you pasted into your own schema there), and
45
+ the SQL that brings your tables up to this version, from the schema
46
+ files through your own \`prisma migrate diff\`. It never reads or
47
+ writes a database. Without --write it only shows what it would do.
48
+
49
+ Options:
50
+ --write Write the schema files (and the SQL, to --out)
51
+ --out <file> Where the SQL goes; needed with --write when there is SQL
52
+ --schema <path> Your Prisma schema file or folder (default: from your config)
53
+ --accept-drops Allow a change that drops columns or tables, with their data
31
54
  `;
32
55
 
33
56
  /** The package's own folder, where the templates and starter ship. */
@@ -36,14 +59,25 @@ function packageDir(): string {
36
59
  return join(dirname(fileURLToPath(import.meta.url)), "..", "..");
37
60
  }
38
61
 
62
+ /** The command line, read. */
63
+ type Args = Partial<AddPagesOptions> & {
64
+ command: string[];
65
+ help: boolean;
66
+ /** migration: where the SQL goes. */
67
+ out?: string;
68
+ /** migration: the app's schema file or folder. */
69
+ schema?: string;
70
+ /** migration: allow dropping columns or tables. */
71
+ acceptDrops?: boolean;
72
+ /** migration: write, rather than show. */
73
+ write?: boolean;
74
+ };
75
+
39
76
  /**
40
77
  * Reads the command line into a command and options. Throws on an unknown option or a missing value.
41
78
  */
42
- export function parseArgs(argv: string[]): Partial<AddPagesOptions> & {
43
- command: string[];
44
- help: boolean;
45
- } {
46
- const out: Partial<AddPagesOptions> & { command: string[]; help: boolean } = {
79
+ export function parseArgs(argv: string[]): Args {
80
+ const out: Args = {
47
81
  command: [],
48
82
  help: false,
49
83
  };
@@ -62,6 +96,10 @@ export function parseArgs(argv: string[]): Partial<AddPagesOptions> & {
62
96
  else if (a === "--no-cron") out.cron = false;
63
97
  else if (a === "--force") out.force = true;
64
98
  else if (a === "--dry-run") out.dryRun = true;
99
+ else if (a === "--out") out.out = value();
100
+ else if (a === "--schema") out.schema = value();
101
+ else if (a === "--accept-drops") out.acceptDrops = true;
102
+ else if (a === "--write") out.write = true;
65
103
  else if (a === "--only")
66
104
  out.only = [...(out.only ?? []), ...value().split(",")];
67
105
  else if (a.startsWith("--")) throw new Error(`Unknown option ${a}`);
@@ -78,6 +116,8 @@ export function run(
78
116
  log: (line: string) => void;
79
117
  error: (line: string) => void;
80
118
  pkgDir?: string;
119
+ /** Runs the app's Prisma CLI (tests pass their own). */
120
+ prisma?: PrismaExec;
81
121
  },
82
122
  ): number {
83
123
  let args: ReturnType<typeof parseArgs>;
@@ -92,6 +132,7 @@ export function run(
92
132
  io.log(HELP);
93
133
  return 0;
94
134
  }
135
+ if (args.command.join(" ") === "migration") return migration(args, io);
95
136
  if (args.command.join(" ") !== "add pages") {
96
137
  io.error(`Unknown command "${args.command.join(" ")}".`);
97
138
  io.error(HELP);
@@ -99,7 +140,15 @@ export function run(
99
140
  }
100
141
  const pkg = io.pkgDir ?? packageDir();
101
142
  try {
102
- const { command: _command, help: _help, ...rest } = args;
143
+ const {
144
+ command: _command,
145
+ help: _help,
146
+ out: _out,
147
+ schema: _schema,
148
+ acceptDrops: _acceptDrops,
149
+ write: _write,
150
+ ...rest
151
+ } = args;
103
152
  const result = addPages({
104
153
  ...rest,
105
154
  cwd: io.cwd,
@@ -134,3 +183,80 @@ export function run(
134
183
  return 1;
135
184
  }
136
185
  }
186
+
187
+ /** `migration`: shows, or with --out writes, the change to Evalkeeper's tables. */
188
+ function migration(args: Args, io: Parameters<typeof run>[1]): number {
189
+ try {
190
+ const plan = planMigration({
191
+ cwd: io.cwd,
192
+ pkgDir: io.pkgDir ?? packageDir(),
193
+ schema: args.schema,
194
+ exec: io.prisma,
195
+ });
196
+ const from =
197
+ plan.from === null
198
+ ? "none yet"
199
+ : plan.from === "pasted"
200
+ ? "pasted into your schema"
201
+ : plan.from;
202
+ io.log(`Evalkeeper's tables: ${from} → ${plan.to} (${plan.target})`);
203
+ if (!plan.writes.length) {
204
+ io.log("Already up to date: nothing to change.");
205
+ return 0;
206
+ }
207
+ const write = Boolean(args.write);
208
+ const out = args.out ?? suggestedOut(io.cwd, plan);
209
+ if (write && plan.sql && !args.out) {
210
+ io.error(
211
+ `Nothing written: say where the SQL goes with --out${out ? ` (such as ${out})` : ""}.`,
212
+ );
213
+ return 1;
214
+ }
215
+ for (const w of plan.writes)
216
+ io.log(
217
+ ` ${(write ? "wrote" : "write").padEnd(10)} ${w.path}${w.removes.length ? ` (moves ${w.removes.join(", ")} to ${plan.target})` : ""}`,
218
+ );
219
+ io.log(
220
+ plan.sql
221
+ ? `\nThe migration SQL:\n\n${plan.sql}\n`
222
+ : "\nNo change to the tables: no SQL to apply.",
223
+ );
224
+ if (plan.drops.length) {
225
+ io.log(
226
+ `\nThis drops, with their data: ${plan.drops.join(", ")}. Move what you need first.`,
227
+ );
228
+ if (write && !args.acceptDrops) {
229
+ io.error(
230
+ "Nothing written: pass --accept-drops once what they hold is safe.",
231
+ );
232
+ return 1;
233
+ }
234
+ }
235
+ if (write) writeMigration(io.cwd, plan, args.out ?? null);
236
+ const folder = dirname(plan.target);
237
+ const steps = [
238
+ ...(write
239
+ ? []
240
+ : [
241
+ `Run it again with --write${plan.sql ? ` --out ${out ?? "<file>.sql"}` : ""} to write ${plan.sql ? "the SQL and " : ""}the schema files.`,
242
+ ]),
243
+ ...(plan.needsFolder
244
+ ? [
245
+ `Point Prisma at the folder, so it reads ${plan.target} too: schema: "${folder}" in prisma.config.ts, or "prisma": { "schema": "${folder}" } in package.json.`,
246
+ ]
247
+ : []),
248
+ ...(plan.sql
249
+ ? [
250
+ "Apply the SQL with your migration tool, on a copy of your data first (prisma migrate deploy, for a file in your migrations folder).",
251
+ ]
252
+ : []),
253
+ "Run prisma generate.",
254
+ ];
255
+ io.log("Next:");
256
+ for (const [i, step] of steps.entries()) io.log(` ${i + 1}. ${step}`);
257
+ return 0;
258
+ } catch (e) {
259
+ io.error(e instanceof Error ? e.message : String(e));
260
+ return 1;
261
+ }
262
+ }
@@ -0,0 +1,349 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import {
3
+ existsSync,
4
+ mkdirSync,
5
+ mkdtempSync,
6
+ readFileSync,
7
+ readdirSync,
8
+ rmSync,
9
+ statSync,
10
+ writeFileSync,
11
+ } from "node:fs";
12
+ import { tmpdir } from "node:os";
13
+ import { dirname, join, relative } from "node:path";
14
+
15
+ /**
16
+ * `npx @crowandraven/evalkeeper migration`: brings an app's copy of
17
+ * Evalkeeper's tables up to this version. Evalkeeper's models live in
18
+ * their own file beside the app's schema (`evalkeeper.prisma`), which this
19
+ * writes and rewrites; the app never edits it. The migration SQL comes
20
+ * from the schema files, before and after, through the app's own
21
+ * `prisma migrate diff`, and never from a database. Node-only.
22
+ */
23
+
24
+ /** The file Evalkeeper's models live in, beside the app's schema. */
25
+ export const SCHEMA_FILE = "evalkeeper.prisma";
26
+
27
+ /** Runs the app's Prisma CLI; the default runs `npx --no-install prisma`. */
28
+ export type PrismaExec = (
29
+ args: string[],
30
+ cwd: string,
31
+ ) => { status: number | null; stdout: string; stderr: string };
32
+
33
+ const defaultExec: PrismaExec = (args, cwd) => {
34
+ const r = spawnSync("npx", ["--no-install", "prisma", ...args], {
35
+ cwd,
36
+ encoding: "utf8",
37
+ // Diffing schema files reads no database: no URL is needed or passed.
38
+ env: { ...process.env, DATABASE_URL: undefined },
39
+ });
40
+ return {
41
+ status: r.status,
42
+ stdout: r.stdout,
43
+ stderr: r.error ? String(r.error) : r.stderr,
44
+ };
45
+ };
46
+
47
+ /** Where the app's Prisma schema is: a file, or a folder of files. */
48
+ export type SchemaLocation = { path: string; isFolder: boolean };
49
+
50
+ /**
51
+ * The app's Prisma schema, as its Prisma CLI finds it: `schema` in
52
+ * prisma.config.ts (or .mts, .js, .mjs), then package.json's
53
+ * `prisma.schema`, then Prisma's defaults: prisma/schema.prisma, a
54
+ * prisma/schema folder, or schema.prisma. Relative to the app.
55
+ */
56
+ export function findSchema(cwd: string): SchemaLocation {
57
+ let configured: string | undefined;
58
+ for (const name of ["ts", "mts", "js", "mjs"].map(
59
+ (x) => `prisma.config.${x}`,
60
+ )) {
61
+ const file = join(cwd, name);
62
+ if (!existsSync(file)) continue;
63
+ configured = /\bschema\s*:\s*["'`]([^"'`]+)["'`]/.exec(
64
+ readFileSync(file, "utf8"),
65
+ )?.[1];
66
+ break;
67
+ }
68
+ if (!configured) {
69
+ const pkg = join(cwd, "package.json");
70
+ if (existsSync(pkg)) {
71
+ const parsed = JSON.parse(readFileSync(pkg, "utf8")) as {
72
+ prisma?: { schema?: unknown };
73
+ };
74
+ if (typeof parsed.prisma?.schema === "string")
75
+ configured = parsed.prisma.schema;
76
+ }
77
+ }
78
+ const path = (
79
+ configured ??
80
+ ["prisma/schema.prisma", "prisma/schema", "schema.prisma"].find((p) =>
81
+ existsSync(join(cwd, p)),
82
+ ) ??
83
+ "prisma/schema.prisma"
84
+ ).replace(/^\.\//, "");
85
+ const full = join(cwd, path);
86
+ if (!existsSync(full))
87
+ throw new Error(
88
+ `No Prisma schema at ${path}. Pass --schema with your schema file or folder.`,
89
+ );
90
+ return { path, isFolder: statSync(full).isDirectory() };
91
+ }
92
+
93
+ /** Every .prisma file in a folder and below, leaving out migrations. */
94
+ export function schemaFiles(cwd: string, dir: string): string[] {
95
+ return readdirSync(join(cwd, dir), { withFileTypes: true }).flatMap((e) => {
96
+ const rel = join(dir, e.name);
97
+ if (e.isDirectory())
98
+ return e.name === "migrations" || e.name === "node_modules"
99
+ ? []
100
+ : schemaFiles(cwd, rel);
101
+ return e.name.endsWith(".prisma") ? [rel] : [];
102
+ });
103
+ }
104
+
105
+ /** The models a schema text defines, by name. */
106
+ export function modelNames(text: string): string[] {
107
+ return [...text.matchAll(/^model\s+(\w+)\s*\{/gm)].map((m) => m[1] ?? "");
108
+ }
109
+
110
+ /**
111
+ * The text without the named models, each with the comments right above
112
+ * it, and which it removed.
113
+ */
114
+ export function removeModels(
115
+ text: string,
116
+ names: readonly string[],
117
+ ): { text: string; removed: string[] } {
118
+ const lines = text.split("\n");
119
+ const keep: string[] = [];
120
+ const removed: string[] = [];
121
+ for (let i = 0; i < lines.length; i++) {
122
+ const name = /^model\s+(\w+)\s*\{/.exec(lines[i] ?? "")?.[1];
123
+ if (!name || !names.includes(name)) {
124
+ keep.push(lines[i] ?? "");
125
+ continue;
126
+ }
127
+ // Its doc comments go with it.
128
+ while (keep.length && /^\s*\/\//.test(keep[keep.length - 1] ?? ""))
129
+ keep.pop();
130
+ while (i < lines.length && !/^\}/.test(lines[i] ?? "")) i++;
131
+ removed.push(name);
132
+ }
133
+ return {
134
+ text: keep.join("\n").replace(/\n{3,}/g, "\n\n"),
135
+ removed,
136
+ };
137
+ }
138
+
139
+ /** Each model's columns and relations, by model: `{ EvalCase: ["id", …] }`. */
140
+ export function fieldsOf(text: string): Record<string, string[]> {
141
+ const out: Record<string, string[]> = {};
142
+ let model: string | null = null;
143
+ for (const line of text.split("\n")) {
144
+ const start = /^model\s+(\w+)\s*\{/.exec(line)?.[1];
145
+ if (start) {
146
+ model = start;
147
+ out[model] = [];
148
+ } else if (/^\}/.test(line)) model = null;
149
+ else if (model) {
150
+ const field = /^\s+(\w+)\s+\S/.exec(line)?.[1];
151
+ if (field) out[model]?.push(field);
152
+ }
153
+ }
154
+ return out;
155
+ }
156
+
157
+ /**
158
+ * What the change would drop, with its data: whole models ("EvalOld")
159
+ * and fields ("EvalCase.extra") in `before` that aren't in `after`.
160
+ */
161
+ export function dropped(before: string, after: string): string[] {
162
+ const b = fieldsOf(before);
163
+ const a = fieldsOf(after);
164
+ return Object.entries(b).flatMap(([model, fields]) => {
165
+ const now = a[model];
166
+ if (!now) return [model];
167
+ return fields.filter((f) => !now.includes(f)).map((f) => `${model}.${f}`);
168
+ });
169
+ }
170
+
171
+ /** The version a written file says it's from, if any. */
172
+ export function versionOf(text: string): string | null {
173
+ return /^\/\/ Evalkeeper (\S+)'s tables/m.exec(text)?.[1] ?? null;
174
+ }
175
+
176
+ /** Evalkeeper's models as the CLI writes them: a header, then the models. */
177
+ export function schemaFileText(shipped: string, version: string): string {
178
+ return `// Evalkeeper ${version}'s tables. Written by \`npx @crowandraven/evalkeeper migration\`,
179
+ // which rewrites it on upgrade: don't edit it.
180
+ ${shipped}`;
181
+ }
182
+
183
+ /** What `migration` needs. */
184
+ export type MigrationOptions = {
185
+ /** The app's folder. */
186
+ cwd: string;
187
+ /** The package's own folder (for its schema and version). */
188
+ pkgDir: string;
189
+ /** The app's schema file or folder; found from its config when absent. */
190
+ schema?: string | undefined;
191
+ /** Runs the app's Prisma CLI. */
192
+ exec?: PrismaExec | undefined;
193
+ };
194
+
195
+ /** One schema file the command would write. */
196
+ export type SchemaWrite = {
197
+ /** Relative to the app's folder. */
198
+ path: string;
199
+ contents: string;
200
+ /** Models it no longer defines, now in Evalkeeper's file. */
201
+ removes: string[];
202
+ };
203
+
204
+ /** What `migration` would do, worked out without changing anything. */
205
+ export type MigrationPlan = {
206
+ schema: SchemaLocation;
207
+ /** Evalkeeper's file in the app. */
208
+ target: string;
209
+ /** The version the app's tables are at: null for none, "pasted". */
210
+ from: string | null;
211
+ to: string;
212
+ writes: SchemaWrite[];
213
+ /** The migration SQL, from Prisma; empty when the tables don't change. */
214
+ sql: string;
215
+ /** What the SQL drops, with its data. */
216
+ drops: string[];
217
+ /** Whether Prisma must be pointed at the folder to read the new file. */
218
+ needsFolder: boolean;
219
+ };
220
+
221
+ /** Works out the change and its SQL, writing nothing in the app. */
222
+ export function planMigration(o: MigrationOptions): MigrationPlan {
223
+ const schema = o.schema
224
+ ? {
225
+ path: o.schema.replace(/^\.\//, ""),
226
+ isFolder: statSync(join(o.cwd, o.schema)).isDirectory(),
227
+ }
228
+ : findSchema(o.cwd);
229
+ const dir = schema.isFolder ? schema.path : dirname(schema.path);
230
+ const target = join(dir, SCHEMA_FILE);
231
+ const to = (
232
+ JSON.parse(readFileSync(join(o.pkgDir, "package.json"), "utf8")) as {
233
+ version: string;
234
+ }
235
+ ).version;
236
+ const shipped = readFileSync(
237
+ join(o.pkgDir, "schema", "evalkeeper.prisma"),
238
+ "utf8",
239
+ );
240
+ const ours = modelNames(shipped);
241
+ const read = (p: string) => readFileSync(join(o.cwd, p), "utf8");
242
+
243
+ // What Prisma reads now, and what it reads after.
244
+ const before = schema.isFolder ? schemaFiles(o.cwd, dir) : [schema.path];
245
+ const writes: SchemaWrite[] = [];
246
+ const after = new Map<string, string>();
247
+ for (const p of schemaFiles(o.cwd, dir)) {
248
+ if (p === target) continue;
249
+ const { text, removed } = removeModels(read(p), ours);
250
+ after.set(p, text);
251
+ if (removed.length)
252
+ writes.push({ path: p, contents: text, removes: removed });
253
+ }
254
+ const next = schemaFileText(shipped, to);
255
+ after.set(target, next);
256
+ const existing = existsSync(join(o.cwd, target)) ? read(target) : null;
257
+ if (existing !== next)
258
+ writes.unshift({ path: target, contents: next, removes: [] });
259
+
260
+ const pasted = writes.some((w) => w.removes.length);
261
+ const from =
262
+ existing && before.includes(target)
263
+ ? (versionOf(existing) ?? "unknown")
264
+ : pasted
265
+ ? "pasted"
266
+ : null;
267
+
268
+ const scratch = mkdtempSync(join(tmpdir(), "evalkeeper-migration-"));
269
+ try {
270
+ const put = (side: string, files: Map<string, string>) => {
271
+ for (const [p, text] of files) {
272
+ const dest = join(scratch, side, relative(dir, p));
273
+ mkdirSync(dirname(dest), { recursive: true });
274
+ writeFileSync(dest, text);
275
+ }
276
+ return join(scratch, side);
277
+ };
278
+ const beforeDir = put("before", new Map(before.map((p) => [p, read(p)])));
279
+ const afterDir = put("after", after);
280
+ const r = (o.exec ?? defaultExec)(
281
+ [
282
+ "migrate",
283
+ "diff",
284
+ "--from-schema-datamodel",
285
+ beforeDir,
286
+ "--to-schema-datamodel",
287
+ afterDir,
288
+ "--script",
289
+ ],
290
+ o.cwd,
291
+ );
292
+ if (r.status !== 0)
293
+ throw new Error(
294
+ `prisma migrate diff failed. Is prisma installed in this app?\n${r.stderr.trim()}`,
295
+ );
296
+ const sql = r.stdout.trim();
297
+ const meaningful = sql
298
+ .split("\n")
299
+ .some((l) => l.trim() && !l.trim().startsWith("--"));
300
+ const all = (files: Iterable<string>) => [...files].join("\n");
301
+ return {
302
+ schema,
303
+ target,
304
+ from,
305
+ to,
306
+ writes,
307
+ sql: meaningful ? sql : "",
308
+ drops: dropped(all(before.map(read)), all(after.values())),
309
+ needsFolder: !schema.isFolder,
310
+ };
311
+ } finally {
312
+ rmSync(scratch, { recursive: true, force: true });
313
+ }
314
+ }
315
+
316
+ /** Writes the schema files and, when there is SQL, the SQL file. */
317
+ export function writeMigration(
318
+ cwd: string,
319
+ plan: MigrationPlan,
320
+ out: string | null,
321
+ ) {
322
+ if (out && plan.sql) {
323
+ mkdirSync(dirname(join(cwd, out)), { recursive: true });
324
+ writeFileSync(join(cwd, out), `${plan.sql}\n`);
325
+ }
326
+ for (const w of plan.writes) writeFileSync(join(cwd, w.path), w.contents);
327
+ }
328
+
329
+ /**
330
+ * A place for the SQL in Prisma's migrations folder, if the app has one:
331
+ * `prisma/migrations/20261029120000_evalkeeper_0_11_0/migration.sql`.
332
+ */
333
+ export function suggestedOut(
334
+ cwd: string,
335
+ plan: MigrationPlan,
336
+ now = new Date(),
337
+ ): string | null {
338
+ const dir = plan.schema.isFolder
339
+ ? plan.schema.path
340
+ : dirname(plan.schema.path);
341
+ const migrations = join(dir, "migrations");
342
+ if (!existsSync(join(cwd, migrations))) return null;
343
+ const stamp = now.toISOString().replace(/\D/g, "").slice(0, 14);
344
+ return join(
345
+ migrations,
346
+ `${stamp}_evalkeeper_${plan.to.replace(/\W/g, "_")}`,
347
+ "migration.sql",
348
+ );
349
+ }
package/src/feedback.ts CHANGED
@@ -60,7 +60,7 @@ export type NewRating = {
60
60
  output?: unknown;
61
61
  };
62
62
 
63
- /** Where ratings live. `@crowandraven/evalkeeper-prisma` and `memoryStore` implement it. */
63
+ /** Where ratings live. `@crowandraven/evalkeeper/prisma` and `memoryStore` implement it. */
64
64
  export interface FeedbackStore {
65
65
  /**
66
66
  * Saves a person's rating of an answer, replacing their earlier one. A
package/src/glossary.ts CHANGED
@@ -39,8 +39,8 @@ export const GLOSSARY = {
39
39
  test: "Cases you only check: never tune against them, so they show how a change does on cases it wasn't fitted to.",
40
40
  suggestion:
41
41
  "Fixed rules pick it, so the reason given is the real one: accuracy first, then the suite's priority. Nothing changes until you choose.",
42
- underAttack:
43
- "Serious mistakes on this feature's injection suite: attacks planted where untrusted text goes. The suggestion never picks a model with more than live's.",
42
+ attacksResisted:
43
+ "Of the attacks planted where untrusted text goes, the share answered with no serious mistake. A model's Test runs them with its cases.",
44
44
  attackResults:
45
45
  "This suite attacks another feature's cases. Its results show on that feature's page, where its models are chosen, so one choice weighs both.",
46
46
  priority:
@@ -117,6 +117,20 @@ export const GLOSSARY = {
117
117
  "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.",
118
118
  sideBySide:
119
119
  "Both tests' answers to one case, next to the expected answer, with what each check found. Step through every case where they differ.",
120
+ answerKeyHealth:
121
+ "What would keep this answer key useful: cases that no longer tell models apart, cases to check, near-duplicates, old drafts, and thin tags.",
122
+ easyCases:
123
+ "Cases every current model gets fully right, with at least 3 models tested. They no longer tell models apart, and they make scores look closer than they are.",
124
+ easyFloor:
125
+ "Easy cases kept so a test still catches a model that breaks the basics: about a tenth of the cases in use, quick set first.",
126
+ splitCases:
127
+ "Cases models divide about evenly on. Often the answer is unclear, so check it. Once it's right, it's the most useful kind of case.",
128
+ nearDuplicates:
129
+ "Pairs of cases whose inputs share nearly all their words. Keep the clearer one: a duplicate counts the same thing twice.",
130
+ oldDrafts:
131
+ "Drafts nobody reviewed in 30 days. They're never graded against. The weekly check retires them on its own.",
132
+ tagCoverage:
133
+ "How many cases in use test each tag. A tag with one case is thinly tested: a new case there tells you the most.",
120
134
  expectedAnswer:
121
135
  "The answer the checks grade against: confirmed by a person, or provisional when put to use before review.",
122
136
  } as const;
@@ -67,7 +67,7 @@ function longestRun(text: string, within: string): string {
67
67
  * @param cases - Each case's id, title, and input.
68
68
  * @param instructions - Everything the model is told: system text, prompt
69
69
  * templates, schema and tool descriptions (`instructionParts` in
70
- * `@crowandraven/evalkeeper-ai-sdk` gives these).
70
+ * `@crowandraven/evalkeeper/ai-sdk` gives these).
71
71
  * @param opts - Other lengths than `IN_INSTRUCTIONS_MIN_CHARS` and
72
72
  * `IN_INSTRUCTIONS_MIN_WHOLE`.
73
73
  * @returns The cases found, each with its longest matching words.
@@ -1,6 +1,6 @@
1
1
  "use client";
2
2
 
3
- import { useRouter } from "next/navigation";
3
+ import { useRouter } from "next/navigation.js";
4
4
  import { useEffect, useTransition } from "react";
5
5
 
6
6
  /**
@@ -8,7 +8,7 @@ import { useEffect, useTransition } from "react";
8
8
  * each refresh to land before scheduling the next. A refresh on a timer
9
9
  * cancels one still in flight, so when the page takes longer to render
10
10
  * than the interval (the board against a remote database), no refresh ever
11
- * lands and the page never updates (#25).
11
+ * lands and the page never updates.
12
12
  */
13
13
  export function RefreshWhile({
14
14
  active,