@crowandraven/evalkeeper 0.10.0 → 0.11.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 (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
@@ -0,0 +1,389 @@
1
+ import { after } from "next/server.js";
2
+ import { revalidatePath } from "next/cache.js";
3
+ import {
4
+ answerFromForm,
5
+ attackMistakes,
6
+ attacksFrom,
7
+ blindRating,
8
+ caseFromFeedback,
9
+ formText,
10
+ isInjectionSuite,
11
+ leakNote,
12
+ raterStatus,
13
+ skipMark,
14
+ suggest,
15
+ withoutLeaks,
16
+ } from "../index.js";
17
+ import { evalsPath, type EvalActions } from "../react/app.js";
18
+ import { weeklyCheck } from "./weekly.js";
19
+ import type { EvalWiring } from "./wiring.js";
20
+
21
+ const VS: Record<string, string> = {
22
+ BETTER: "more accurate than live",
23
+ SAME: "about as accurate as live",
24
+ WORSE: "less accurate than live",
25
+ TOO_FEW: "too few cases to compare",
26
+ };
27
+
28
+ /**
29
+ * Every action on the eval pages, for Next.js. Each checks `requireAdmin`
30
+ * first and records the admin as who made a change; answers to tests come
31
+ * back after the response (`after`), while the page refreshes.
32
+ *
33
+ * Next.js only accepts server actions from a `"use server"` module of your
34
+ * app, so `add pages` writes `lib/evalkeeper/actions.ts`: one line per
35
+ * action, each calling these.
36
+ *
37
+ * @param w - Your wiring.
38
+ */
39
+ export function evalActions(w: EvalWiring): Required<EvalActions> {
40
+ const { runner, settings, store, feedbackStore } = w;
41
+ const page = (...parts: string[]) => evalsPath(w, ...parts);
42
+ /** Every eval page, after a change that shows on more than one. */
43
+ const everyPage = () => {
44
+ revalidatePath(w.basePath, "layout");
45
+ };
46
+ const weekly = weeklyCheck(w);
47
+
48
+ const suiteFrom = (form: FormData) =>
49
+ runner.suiteOrThrow(formText(form, "suite"));
50
+
51
+ /**
52
+ * The suite whose page chooses models: never an injection suite, whose
53
+ * results show on its base suite's page and count in its suggestion.
54
+ */
55
+ function choosingSuite(form: FormData) {
56
+ const suite = suiteFrom(form);
57
+ if (isInjectionSuite(suite))
58
+ throw new Error(`Choose models on ${suite.base.label}`);
59
+ return suite;
60
+ }
61
+
62
+ /** A suite's injection suites, as its suggestion reads them. */
63
+ const attacksOn = async (suiteKey: string) =>
64
+ attacksFrom(await runner.attackBoards(suiteKey));
65
+
66
+ /** Answers a test's runs one after another: the feature's, then its attacks'. */
67
+ async function runAll(runs: { id: string }[]) {
68
+ for (const r of runs) await runner.runEval(r.id);
69
+ }
70
+
71
+ /** A case of the suite, by the form's "case"; throws on any other. */
72
+ async function knownCase(suiteKey: string, form: FormData) {
73
+ const id = formText(form, "case");
74
+ const c = (await store.listCases(suiteKey)).find((x) => x.id === id);
75
+ if (!c) throw new Error("Unknown case");
76
+ return c;
77
+ }
78
+
79
+ /**
80
+ * The case a blind rating or skip is for: in this imported suite, not
81
+ * retired, and not yet rated or skipped by this person, so nobody answers
82
+ * twice and nothing lands over another person's answer.
83
+ */
84
+ async function caseToRate(form: FormData, raterId: string) {
85
+ const suite = suiteFrom(form);
86
+ if (suite.caseKind !== "imported")
87
+ throw new Error("This suite isn't rated blind");
88
+ const c = await knownCase(suite.key, form);
89
+ if (raterStatus(c, raterId))
90
+ throw new Error("You've already rated or skipped this case");
91
+ return { suite, c };
92
+ }
93
+
94
+ /** The current test of a model's row, for choosing it live or fallback. */
95
+ async function rowOf(suiteKey: string, model: string) {
96
+ const board = await runner.board(suiteKey);
97
+ return {
98
+ board,
99
+ row: board.rows.find((r) => r.model === model && !r.variant),
100
+ };
101
+ }
102
+
103
+ async function feedbackById(id: string) {
104
+ const f = (await feedbackStore.listFeedback()).find((x) => x.id === id);
105
+ if (!f) throw new Error("Unknown rating");
106
+ return f;
107
+ }
108
+
109
+ return {
110
+ async testModel(form) {
111
+ await w.requireAdmin();
112
+ const suite = suiteFrom(form);
113
+ const model = formText(form, "model");
114
+ if (!runner.modelsFor(suite.operation).includes(model))
115
+ throw new Error("Unknown model");
116
+ // The feature's cases and its attack cases, in one test.
117
+ const { runs } = await runner.createTest({ suite: suite.key, model });
118
+ after(() => runAll(runs));
119
+ revalidatePath(page(suite.key));
120
+ },
121
+
122
+ async testAll(form) {
123
+ await w.requireAdmin();
124
+ const suite = suiteFrom(form);
125
+ for (const model of runner.modelsFor(suite.operation)) {
126
+ const { runs } = await runner.createTest({ suite: suite.key, model });
127
+ after(() => runAll(runs));
128
+ }
129
+ revalidatePath(page(suite.key));
130
+ },
131
+
132
+ async makeLive(form) {
133
+ const admin = await w.requireAdmin();
134
+ const suite = choosingSuite(form);
135
+ const { board, row } = await rowOf(suite.key, formText(form, "model"));
136
+ if (!row?.test || row.test.stale)
137
+ throw new Error("Test this model on the current cases first");
138
+ const score = { right: row.test.right, total: row.test.total };
139
+ const attacked = attackMistakes(row.key, await attacksOn(suite.key));
140
+ await settings.update(
141
+ suite.operation,
142
+ { model: row.model },
143
+ {
144
+ by: admin.name,
145
+ reason: `Made ${row.label} live: ${score.right}/${score.total}, ${VS[row.vsLive ?? ""] ?? "no comparison"}${attacked === null ? "" : `; ${attacked} serious ${attacked === 1 ? "mistake" : "mistakes"} under attack`}`,
146
+ // The evidence, so the history can show why.
147
+ evidence: {
148
+ runId: row.test.runId,
149
+ liveRunId: board.liveRunId,
150
+ vsLive: row.vsLive,
151
+ score,
152
+ },
153
+ },
154
+ );
155
+ everyPage();
156
+ },
157
+
158
+ async makeFallback(form) {
159
+ const admin = await w.requireAdmin();
160
+ const suite = choosingSuite(form);
161
+ const { board, row } = await rowOf(suite.key, formText(form, "model"));
162
+ if (!row?.canMakeFallback)
163
+ throw new Error("This model can't be the fallback");
164
+ const test = row.test && !row.test.stale ? row.test : null;
165
+ const failed = test?.failedAnswers
166
+ ? `, ${test.failedAnswers} failed`
167
+ : "";
168
+ await settings.update(
169
+ suite.operation,
170
+ { fallbackModel: row.model },
171
+ {
172
+ by: admin.name,
173
+ reason: `Made ${row.label} the fallback: ${test ? `${Math.round(test.right)}/${Math.round(test.total)}${failed}` : "not tested"}`,
174
+ evidence: {
175
+ runId: test?.runId ?? null,
176
+ liveRunId: board.liveRunId,
177
+ score: test ? { right: test.right, total: test.total } : null,
178
+ },
179
+ },
180
+ );
181
+ everyPage();
182
+ },
183
+
184
+ /** Applies the suggestion: its live and fallback models, in one change. */
185
+ async useSuggestion(form) {
186
+ const admin = await w.requireAdmin();
187
+ const suite = choosingSuite(form);
188
+ const [board, attacks] = await Promise.all([
189
+ runner.board(suite.key),
190
+ attacksOn(suite.key),
191
+ ]);
192
+ const s = suggest(board.rows, suite.checks, suite.priority, w.models, {
193
+ attacks,
194
+ });
195
+ if (!s || s.same) return;
196
+ await settings.update(
197
+ suite.operation,
198
+ { model: s.live.model, fallbackModel: s.fallback?.model ?? null },
199
+ {
200
+ by: admin.name,
201
+ reason: s.reasons.join(" "),
202
+ evidence: {
203
+ suggestion: s.reasons,
204
+ live: s.live.test?.runId ?? null,
205
+ fallback: s.fallback?.test?.runId ?? null,
206
+ },
207
+ },
208
+ );
209
+ everyPage();
210
+ },
211
+
212
+ /** Makes an earlier version live again; a reason is required. */
213
+ async rollBackSettings(form) {
214
+ const admin = await w.requireAdmin();
215
+ const suite = choosingSuite(form);
216
+ const reason = formText(form, "reason");
217
+ if (!reason) throw new Error("Say why you're rolling back");
218
+ await settings.rollBack(suite.operation, formText(form, "version"), {
219
+ by: admin.name,
220
+ reason,
221
+ });
222
+ everyPage();
223
+ },
224
+
225
+ /** A person confirms an answer: the only way a draft gets used. */
226
+ async confirmAnswer(form) {
227
+ await w.requireAdmin();
228
+ const suite = suiteFrom(form);
229
+ await store.setLabelStatus(formText(form, "label"), "CONFIRMED");
230
+ after(() => runner.rescoreRecent(suite.key));
231
+ revalidatePath(page(suite.key));
232
+ },
233
+
234
+ async rescore(form) {
235
+ await w.requireAdmin();
236
+ const suite = suiteFrom(form);
237
+ await runner.rescoreRecent(suite.key);
238
+ revalidatePath(page(suite.key));
239
+ },
240
+
241
+ /**
242
+ * A person adds a case. They wrote its answer, so it's confirmed. The
243
+ * suite's leak check runs first, and the case's note says what it
244
+ * removed.
245
+ */
246
+ async addCase(form) {
247
+ await w.requireAdmin();
248
+ const suite = suiteFrom(form);
249
+ const { input, removed } = withoutLeaks(
250
+ suite,
251
+ suite.inputFromForm(form),
252
+ null,
253
+ );
254
+ await store.createCase({
255
+ suite: suite.key,
256
+ input,
257
+ tags: formText(form, "tags")
258
+ .split(",")
259
+ .map((t) => t.trim())
260
+ .filter(Boolean),
261
+ split: formText(form, "split") === "TEST" ? "TEST" : "DEV",
262
+ status: "ACTIVE",
263
+ source: "OWNER",
264
+ sourceRef: null,
265
+ note: leakNote(removed),
266
+ labels: [
267
+ {
268
+ kind: "EXPECTED",
269
+ status: "CONFIRMED",
270
+ value: answerFromForm(suite, form),
271
+ raterRole: "OWNER",
272
+ raterId: null,
273
+ note: null,
274
+ },
275
+ ],
276
+ });
277
+ revalidatePath(page(suite.key));
278
+ },
279
+
280
+ /**
281
+ * A person changes a case's answer: a new confirmed answer, with the
282
+ * old ones kept as history. Stored answers are rescored for free.
283
+ */
284
+ async editAnswer(form) {
285
+ await w.requireAdmin();
286
+ const suite = suiteFrom(form);
287
+ const c = await knownCase(suite.key, form);
288
+ await store.addLabel(c.id, {
289
+ kind: "EXPECTED",
290
+ status: "CONFIRMED",
291
+ value: answerFromForm(suite, form),
292
+ raterRole: "OWNER",
293
+ raterId: null,
294
+ note: null,
295
+ });
296
+ // A draft (from feedback) is in use once it has an answer.
297
+ await store.setCaseStatus(c.id, "ACTIVE");
298
+ after(() => runner.rescoreRecent(suite.key));
299
+ revalidatePath(page(suite.key));
300
+ },
301
+
302
+ /** Takes a case out of use; its stored answers stay. */
303
+ async retireCase(form) {
304
+ await w.requireAdmin();
305
+ const suite = suiteFrom(form);
306
+ const c = await knownCase(suite.key, form);
307
+ await store.setCaseStatus(c.id, "RETIRED");
308
+ revalidatePath(page(suite.key));
309
+ },
310
+
311
+ /**
312
+ * Retires the easy cases beyond the floor, then rescores recent tests
313
+ * (free), so their scores leave the retired cases out.
314
+ */
315
+ async retireEasy(form) {
316
+ await w.requireAdmin();
317
+ const suite = suiteFrom(form);
318
+ await runner.retireEasy(suite.key);
319
+ revalidatePath(page(suite.key));
320
+ },
321
+
322
+ /** Retires drafts nobody reviewed in STALE_DRAFT_DAYS. */
323
+ async retireStaleDrafts(form) {
324
+ await w.requireAdmin();
325
+ const suite = suiteFrom(form);
326
+ await runner.retireStaleDrafts(suite.key);
327
+ revalidatePath(page(suite.key));
328
+ },
329
+
330
+ /**
331
+ * A person rates an imported case blind: their own confirmed answer,
332
+ * with their reason, added beside anyone else's. Tests are rescored
333
+ * for free.
334
+ */
335
+ async rateBlind(form) {
336
+ const admin = await w.requireAdmin();
337
+ const { suite, c } = await caseToRate(form, admin.id);
338
+ await store.addLabel(
339
+ c.id,
340
+ blindRating({
341
+ raterId: admin.id,
342
+ value: answerFromForm(suite, form),
343
+ reason: formText(form, "reason"),
344
+ }),
345
+ );
346
+ // A draft is in use once it has an answer.
347
+ if (c.status === "DRAFT") await store.setCaseStatus(c.id, "ACTIVE");
348
+ after(() => runner.rescoreRecent(suite.key));
349
+ revalidatePath(page(suite.key), "layout");
350
+ },
351
+
352
+ /** A person passes on an imported case: it leaves their queue only. */
353
+ async skipCase(form) {
354
+ const admin = await w.requireAdmin();
355
+ const { suite, c } = await caseToRate(form, admin.id);
356
+ await store.addLabel(c.id, skipMark(admin.id));
357
+ revalidatePath(page(suite.key, "rate"));
358
+ },
359
+
360
+ /** Makes a draft case from a rating; a person finishes its answer. */
361
+ async makeCase(form) {
362
+ await w.requireAdmin();
363
+ const f = await feedbackById(formText(form, "feedback"));
364
+ const suite = w.suites.find(
365
+ (s) => s.operation === f.operation && !isInjectionSuite(s),
366
+ );
367
+ const draft = suite ? caseFromFeedback(f, suite) : null;
368
+ if (!draft) throw new Error("This rating can't become a case");
369
+ const c = await store.createCase(draft);
370
+ await feedbackStore.setFeedbackStatus(f.id, "CASED", c.id);
371
+ everyPage();
372
+ },
373
+
374
+ async dismissFeedback(form) {
375
+ await w.requireAdmin();
376
+ const f = await feedbackById(formText(form, "feedback"));
377
+ await feedbackStore.setFeedbackStatus(f.id, "DISMISSED");
378
+ revalidatePath(page("feedback"));
379
+ },
380
+
381
+ async runWeeklyNow() {
382
+ await w.requireAdmin();
383
+ // Recorded before the page re-renders, so it shows them running.
384
+ const ids = await weekly.start();
385
+ after(() => weekly.run(ids));
386
+ revalidatePath(w.basePath);
387
+ },
388
+ };
389
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Next.js's own pieces for Evalkeeper's screens: its `Link`, so moving
3
+ * between eval pages doesn't reload, and a `RefreshWhile` on its router,
4
+ * so a page refreshes while a test runs. Spread them into your provider
5
+ * before your own components:
6
+ *
7
+ * ```tsx
8
+ * <EvalComponentsProvider components={{ ...nextComponents, Button }}>
9
+ * ```
10
+ *
11
+ * Import it from `@crowandraven/evalkeeper/next/components` in a client
12
+ * component.
13
+ *
14
+ * @module evalkeeper/next/components
15
+ */
16
+ import NextLink from "next/link.js";
17
+ import type { ComponentType } from "react";
18
+ import type { EvalComponents, LinkProps } from "../react/pieces.js";
19
+ import { RefreshWhile } from "./RefreshWhile.js";
20
+
21
+ export { RefreshWhile };
22
+
23
+ // Next.js bundles this, where the default import is the component; the
24
+ // cast only bridges how TypeScript types a CommonJS module's default.
25
+ const Link = NextLink as unknown as ComponentType<LinkProps>;
26
+
27
+ /** Next.js's `Link` and a `RefreshWhile` on its router. */
28
+ export const nextComponents = {
29
+ Link,
30
+ RefreshWhile,
31
+ } satisfies Partial<EvalComponents>;
@@ -4,6 +4,9 @@ import { timingSafeEqual } from "node:crypto";
4
4
  * Whether a request carries the cron secret ("Authorization: Bearer …").
5
5
  * Fails closed when no secret is set, and compares in constant time so the
6
6
  * secret can't be guessed a character at a time.
7
+ *
8
+ * @param header - The request's Authorization header.
9
+ * @param secret - Your cron secret, such as `process.env.CRON_SECRET`.
7
10
  */
8
11
  export function isAuthorizedCron(
9
12
  header: string | null,
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Evalkeeper's glue for the Next.js App Router: the server actions, the
3
+ * pages, the weekly check, and its cron route, so the files `add pages`
4
+ * writes in your app are each a few lines. Import from
5
+ * `@crowandraven/evalkeeper/next` in server code; your app's own
6
+ * components go in `@crowandraven/evalkeeper/next/components`.
7
+ *
8
+ * @module evalkeeper/next
9
+ */
10
+ export * from "./wiring.js";
11
+ export * from "./actions.js";
12
+ export * from "./pages.js";
13
+ export * from "./weekly.js";
14
+ export * from "./route.js";
15
+ export * from "./cron.js";
@@ -0,0 +1,106 @@
1
+ import type { Metadata } from "next/types.js";
2
+ import { notFound } from "next/navigation.js";
3
+ import type { ReactNode } from "react";
4
+ import type { EvalAppConfig } from "../react/app.js";
5
+ import { HubPage } from "../react/HubSections.js";
6
+ import { SuitePage } from "../react/SuiteSections.js";
7
+ import { RunView } from "../react/RunView.js";
8
+ import { CompareView } from "../react/CompareView.js";
9
+ import { SideBySideView } from "../react/SideBySideView.js";
10
+ import { RateView } from "../react/RateView.js";
11
+ import { FeedbackView } from "../react/FeedbackView.js";
12
+ import type { EvalAdmin } from "./wiring.js";
13
+
14
+ type Search = Record<string, string | string[] | undefined>;
15
+ type Props<P> = { params: Promise<P>; searchParams: Promise<Search> };
16
+
17
+ /** One page: what a route file exports as its page and its title. */
18
+ export type EvalPage<P> = {
19
+ Page: (props: Props<P>) => Promise<ReactNode>;
20
+ generateMetadata: (props: Props<P>) => Promise<Metadata>;
21
+ };
22
+
23
+ /**
24
+ * Evalkeeper's pages for the Next.js App Router. Each route file `add
25
+ * pages` writes exports one of these as its page and title. Every page
26
+ * calls `requireAdmin` first, and a suite or test that isn't there is a
27
+ * 404.
28
+ *
29
+ * @example
30
+ * ```ts
31
+ * // app/evals/[suite]/page.tsx
32
+ * import { pages } from "@/lib/evalkeeper/evals";
33
+ * export const dynamic = "force-dynamic";
34
+ * export const generateMetadata = pages.suite.generateMetadata;
35
+ * export default pages.suite.Page;
36
+ * ```
37
+ *
38
+ * @param app - Your screens' configuration, from `defineEvals`.
39
+ * @param requireAdmin - Who may use the pages; it throws for anyone else.
40
+ */
41
+ export function evalPages(
42
+ app: EvalAppConfig,
43
+ requireAdmin: () => Promise<EvalAdmin>,
44
+ ) {
45
+ /** A page of one suite, titled "{what}: {suite}". */
46
+ function suitePage<P extends { suite: string }>(
47
+ what: string,
48
+ draw: (p: P, search: Search, admin: EvalAdmin) => Promise<ReactNode>,
49
+ ): EvalPage<P> {
50
+ return {
51
+ Page: async ({ params, searchParams }) => {
52
+ const admin = await requireAdmin();
53
+ const view = await draw(await params, await searchParams, admin);
54
+ if (!view) notFound();
55
+ return view;
56
+ },
57
+ generateMetadata: async ({ params }) => {
58
+ const label = app.suiteByKey[(await params).suite]?.label ?? "Evals";
59
+ return { title: what ? `${what}: ${label}` : `Evals: ${label}` };
60
+ },
61
+ };
62
+ }
63
+
64
+ return {
65
+ /** The hub: where each suite stands and what needs attention. */
66
+ hub: {
67
+ Page: async () => {
68
+ await requireAdmin();
69
+ return HubPage({ app });
70
+ },
71
+ generateMetadata: async () => {
72
+ return { title: "Evals" };
73
+ },
74
+ } satisfies EvalPage<object>,
75
+ /** A suite: its models, suggestion, versions, checks, and answer key. */
76
+ suite: suitePage<{ suite: string }>("", (p) =>
77
+ SuitePage({ app, suite: p.suite }),
78
+ ),
79
+ /** One test: every answer, with what each check found. */
80
+ run: suitePage<{ suite: string; runId: string }>("Test", (p) =>
81
+ RunView({ app, suite: p.suite, runId: p.runId }),
82
+ ),
83
+ /** Two tests compared: the verdict, each check, and where they differ. */
84
+ compare: suitePage<{ suite: string }>("Compare", (p, search) =>
85
+ CompareView({ app, suite: p.suite, search }),
86
+ ),
87
+ /** Two tests' answers where they differ, side by side. */
88
+ sideBySide: suitePage<{ suite: string }>("Side by side", (p, search) =>
89
+ SideBySideView({ app, suite: p.suite, search }),
90
+ ),
91
+ /** Blind rating: one case at a time, by its input only. */
92
+ rate: suitePage<{ suite: string }>("Rate blind", (p, _search, rater) =>
93
+ RateView({ app, suite: p.suite, rater }),
94
+ ),
95
+ /** Thumbs up and down, and what to do with each. */
96
+ feedback: {
97
+ Page: async () => {
98
+ await requireAdmin();
99
+ return FeedbackView({ app });
100
+ },
101
+ generateMetadata: async () => {
102
+ return { title: "Feedback: Evals" };
103
+ },
104
+ } satisfies EvalPage<object>,
105
+ };
106
+ }
@@ -0,0 +1,35 @@
1
+ import { after } from "next/server.js";
2
+ import { isAuthorizedCron } from "./cron.js";
3
+ import { weeklyCheck } from "./weekly.js";
4
+ import type { EvalWiring } from "./wiring.js";
5
+
6
+ /**
7
+ * The weekly check's cron route: answers at once, then runs each suite's
8
+ * quick set on its live model after the response. Call it with
9
+ * "Authorization: Bearer $CRON_SECRET"; anything else gets a 401.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * // app/api/cron/evals-weekly/route.ts
14
+ * import { weeklyCronRoute } from "@crowandraven/evalkeeper/next";
15
+ * import { wiring } from "@/lib/evalkeeper";
16
+ * export const maxDuration = 300;
17
+ * export const GET = weeklyCronRoute(wiring);
18
+ * ```
19
+ *
20
+ * @param w - Your wiring: its runner, store, and suites.
21
+ * @param secret - The cron secret; `process.env.CRON_SECRET` by default.
22
+ */
23
+ export function weeklyCronRoute(
24
+ w: Pick<EvalWiring, "runner" | "store" | "suites">,
25
+ secret: () => string | undefined = () => process.env.CRON_SECRET,
26
+ ) {
27
+ const weekly = weeklyCheck(w);
28
+ return async function GET(request: Request): Promise<Response> {
29
+ if (!isAuthorizedCron(request.headers.get("authorization"), secret()))
30
+ return Response.json({ error: "Unauthorized" }, { status: 401 });
31
+ const ids = await weekly.start();
32
+ after(() => weekly.run(ids));
33
+ return Response.json({ started: ids.length }, { status: 202 });
34
+ };
35
+ }
@@ -0,0 +1,70 @@
1
+ import { isInjectionSuite } from "../types.js";
2
+ import { injectionCases } from "../suites/injection.js";
3
+ import type { EvalWiring } from "./wiring.js";
4
+
5
+ /** The weekly check, in the two halves a request can split it into. */
6
+ export type WeeklyCheck = {
7
+ /**
8
+ * Brings attack cases up to date with newly confirmed answers, then
9
+ * records each suite's test on its live model, so the hub shows them
10
+ * running. Returns the tests' ids for `run`.
11
+ */
12
+ start: () => Promise<string[]>;
13
+ /** Drafts cases from the week's activity, then answers the tests. */
14
+ run: (ids: string[]) => Promise<void>;
15
+ };
16
+
17
+ /**
18
+ * The weekly check: each suite's quick set on its live model. On a
19
+ * platform with a request limit, give the runner `requestLimitMs` and
20
+ * `continueRun` so a slow suite carries on in a fresh request.
21
+ *
22
+ * @param w - Your wiring: its runner, store, and suites.
23
+ */
24
+ export function weeklyCheck(
25
+ w: Pick<EvalWiring, "runner" | "store" | "suites">,
26
+ ): WeeklyCheck {
27
+ /**
28
+ * New draft cases from the week's activity, for suites that can draft
29
+ * them. One suite failing doesn't stop the rest.
30
+ */
31
+ async function draft() {
32
+ for (const suite of w.suites) {
33
+ if (!suite.draftFromActivity) continue;
34
+ try {
35
+ await w.runner.draftFromActivity(suite.key);
36
+ } catch (e) {
37
+ console.error(`Drafting from activity failed for ${suite.key}`, e);
38
+ }
39
+ }
40
+ }
41
+
42
+ return {
43
+ async start() {
44
+ for (const suite of w.suites)
45
+ if (isInjectionSuite(suite))
46
+ // Trust boundary: isInjectionSuite means injectionSuite made it.
47
+ await injectionCases(
48
+ w.store,
49
+ suite as unknown as Parameters<typeof injectionCases>[1],
50
+ );
51
+ const ids: string[] = [];
52
+ for (const suite of w.suites) {
53
+ const id = await w.runner.startDriftCheck(suite.key);
54
+ if (id) ids.push(id);
55
+ }
56
+ return ids;
57
+ },
58
+ async run(ids) {
59
+ // Drafts nobody reviewed in a month go, so the review queue stays
60
+ // short; the weekly job's other half adds this week's.
61
+ for (const suite of w.suites)
62
+ await w.runner.retireStaleDrafts(suite.key).catch((e: unknown) => {
63
+ console.error(`Retiring old drafts failed for ${suite.key}`, e);
64
+ });
65
+ await draft();
66
+ // runEval never throws: a suite that fails says why on its own test.
67
+ for (const id of ids) await w.runner.runEval(id, { fresh: true });
68
+ },
69
+ };
70
+ }
@@ -0,0 +1,18 @@
1
+ import type { EvalApp } from "../react/app.js";
2
+
3
+ /** Who's using the eval pages, as your `requireAdmin` returns them. */
4
+ export type EvalAdmin = { id: string; name: string };
5
+
6
+ /**
7
+ * Your app's Evalkeeper wiring, as the Next.js glue reads it: everything
8
+ * the screens need except their actions (the glue makes those), and who
9
+ * may use the pages.
10
+ */
11
+ export type EvalWiring = Omit<EvalApp, "actions"> & {
12
+ /**
13
+ * Who may use the eval pages. Every page and action calls it first:
14
+ * throw when the person isn't an admin, and return who they are, which
15
+ * is recorded as who made each change.
16
+ */
17
+ requireAdmin: () => Promise<EvalAdmin>;
18
+ };