@crowandraven/evalkeeper 0.9.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 (246) 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 +9 -0
  29. package/dist/glossary.js +9 -0
  30. package/dist/glossary.js.map +1 -1
  31. package/dist/health.d.ts +4 -1
  32. package/dist/health.js +4 -2
  33. package/dist/health.js.map +1 -1
  34. package/dist/inInstructions.d.ts +1 -1
  35. package/dist/inInstructions.js +1 -1
  36. package/dist/next/RefreshWhile.d.ts +11 -0
  37. package/dist/next/RefreshWhile.js +28 -0
  38. package/dist/next/RefreshWhile.js.map +1 -0
  39. package/dist/next/actions.d.ts +14 -0
  40. package/dist/next/actions.js +332 -0
  41. package/dist/next/actions.js.map +1 -0
  42. package/dist/next/components.d.ts +9 -0
  43. package/dist/next/components.js +27 -0
  44. package/dist/next/components.js.map +1 -0
  45. package/dist/next/cron.d.ts +9 -0
  46. package/dist/next/cron.js +17 -0
  47. package/dist/next/cron.js.map +1 -0
  48. package/dist/next/index.d.ts +15 -0
  49. package/dist/next/index.js +16 -0
  50. package/dist/next/index.js.map +1 -0
  51. package/dist/next/pages.d.ts +70 -0
  52. package/dist/next/pages.js +77 -0
  53. package/dist/next/pages.js.map +1 -0
  54. package/dist/next/route.d.ts +19 -0
  55. package/dist/next/route.js +31 -0
  56. package/dist/next/route.js.map +1 -0
  57. package/dist/next/weekly.d.ts +20 -0
  58. package/dist/next/weekly.js +55 -0
  59. package/dist/next/weekly.js.map +1 -0
  60. package/dist/next/wiring.d.ts +19 -0
  61. package/dist/next/wiring.js +2 -0
  62. package/dist/next/wiring.js.map +1 -0
  63. package/dist/prisma/contracts.d.ts +74 -0
  64. package/dist/prisma/contracts.js +178 -0
  65. package/dist/prisma/contracts.js.map +1 -0
  66. package/dist/prisma/index.d.ts +423 -0
  67. package/dist/prisma/index.js +622 -0
  68. package/dist/prisma/index.js.map +1 -0
  69. package/dist/prisma/mapping.d.ts +63 -0
  70. package/dist/prisma/mapping.js +111 -0
  71. package/dist/prisma/mapping.js.map +1 -0
  72. package/dist/prisma/moveIn.d.ts +106 -0
  73. package/dist/prisma/moveIn.js +299 -0
  74. package/dist/prisma/moveIn.js.map +1 -0
  75. package/dist/prune.d.ts +45 -0
  76. package/dist/prune.js +32 -0
  77. package/dist/prune.js.map +1 -1
  78. package/dist/react/AddCase.d.ts +10 -0
  79. package/dist/react/AddCase.js +19 -0
  80. package/dist/react/AddCase.js.map +1 -0
  81. package/dist/react/AnswerKey.d.ts +22 -0
  82. package/dist/react/AnswerKey.js +83 -0
  83. package/dist/react/AnswerKey.js.map +1 -0
  84. package/dist/react/CaseMenu.d.ts +17 -0
  85. package/dist/react/CaseMenu.js +41 -0
  86. package/dist/react/CaseMenu.js.map +1 -0
  87. package/dist/react/CompareView.d.ts +14 -0
  88. package/dist/react/CompareView.js +51 -0
  89. package/dist/react/CompareView.js.map +1 -0
  90. package/dist/react/ConfirmAnswer.d.ts +13 -0
  91. package/dist/react/ConfirmAnswer.js +27 -0
  92. package/dist/react/ConfirmAnswer.js.map +1 -0
  93. package/dist/react/DisagreementChip.d.ts +10 -0
  94. package/dist/react/DisagreementChip.js +21 -0
  95. package/dist/react/DisagreementChip.js.map +1 -0
  96. package/dist/react/FeedbackView.d.ts +10 -0
  97. package/dist/react/FeedbackView.js +26 -0
  98. package/dist/react/FeedbackView.js.map +1 -0
  99. package/dist/react/Fields.d.ts +32 -0
  100. package/dist/react/Fields.js +33 -0
  101. package/dist/react/Fields.js.map +1 -0
  102. package/dist/react/HubSections.d.ts +78 -0
  103. package/dist/react/HubSections.js +124 -0
  104. package/dist/react/HubSections.js.map +1 -0
  105. package/dist/react/ModelMenu.d.ts +16 -0
  106. package/dist/react/ModelMenu.js +38 -0
  107. package/dist/react/ModelMenu.js.map +1 -0
  108. package/dist/react/RateView.d.ts +18 -0
  109. package/dist/react/RateView.js +30 -0
  110. package/dist/react/RateView.js.map +1 -0
  111. package/dist/react/ReadableOutput.d.ts +3 -0
  112. package/dist/react/ReadableOutput.js +50 -0
  113. package/dist/react/ReadableOutput.js.map +1 -0
  114. package/dist/react/RollBack.d.ts +17 -0
  115. package/dist/react/RollBack.js +26 -0
  116. package/dist/react/RollBack.js.map +1 -0
  117. package/dist/react/RunView.d.ts +9 -0
  118. package/dist/react/RunView.js +41 -0
  119. package/dist/react/RunView.js.map +1 -0
  120. package/dist/react/SettingsHistory.d.ts +33 -0
  121. package/dist/react/SettingsHistory.js +79 -0
  122. package/dist/react/SettingsHistory.js.map +1 -0
  123. package/dist/react/SideBySideView.d.ts +14 -0
  124. package/dist/react/SideBySideView.js +67 -0
  125. package/dist/react/SideBySideView.js.map +1 -0
  126. package/dist/react/SuiteSections.d.ts +111 -0
  127. package/dist/react/SuiteSections.js +224 -0
  128. package/dist/react/SuiteSections.js.map +1 -0
  129. package/dist/react/Tabs.d.ts +15 -0
  130. package/dist/react/Tabs.js +18 -0
  131. package/dist/react/Tabs.js.map +1 -0
  132. package/dist/react/Thumbs.d.ts +13 -0
  133. package/dist/react/Thumbs.js +54 -0
  134. package/dist/react/Thumbs.js.map +1 -0
  135. package/dist/react/WeeklyCheck.d.ts +11 -0
  136. package/dist/react/WeeklyCheck.js +19 -0
  137. package/dist/react/WeeklyCheck.js.map +1 -0
  138. package/dist/react/app.d.ts +118 -0
  139. package/dist/react/app.js +87 -0
  140. package/dist/react/app.js.map +1 -0
  141. package/dist/react/format.d.ts +27 -0
  142. package/dist/react/format.js +38 -0
  143. package/dist/react/format.js.map +1 -0
  144. package/dist/react/index.d.ts +31 -0
  145. package/dist/react/index.js +32 -0
  146. package/dist/react/index.js.map +1 -0
  147. package/dist/react/pieces.d.ts +191 -0
  148. package/dist/react/pieces.js +191 -0
  149. package/dist/react/pieces.js.map +1 -0
  150. package/dist/readCheck.d.ts +1 -1
  151. package/dist/runner.d.ts +76 -3
  152. package/dist/runner.js +133 -3
  153. package/dist/runner.js.map +1 -1
  154. package/dist/settings.d.ts +1 -1
  155. package/dist/store.d.ts +1 -1
  156. package/dist/suggest.d.ts +52 -2
  157. package/dist/suggest.js +101 -8
  158. package/dist/suggest.js.map +1 -1
  159. package/dist/suiteContract.d.ts +3 -3
  160. package/dist/suiteContract.js +20 -16
  161. package/dist/suiteContract.js.map +1 -1
  162. package/dist/testing.d.ts +2 -2
  163. package/dist/testing.js +1 -1
  164. package/dist/types.d.ts +79 -2
  165. package/dist/types.js +96 -12
  166. package/dist/types.js.map +1 -1
  167. package/package.json +56 -6
  168. package/schema/evalkeeper.prisma +196 -0
  169. package/src/ai-sdk/decide.ts +57 -0
  170. package/src/ai-sdk/hash.ts +74 -0
  171. package/src/ai-sdk/index.ts +15 -0
  172. package/src/ai-sdk/judge.ts +163 -0
  173. package/src/ai-sdk/usage.ts +31 -0
  174. package/src/board.ts +5 -0
  175. package/src/cli/addPages.ts +15 -7
  176. package/src/cli/main.ts +135 -9
  177. package/src/cli/migration.ts +349 -0
  178. package/src/feedback.ts +1 -1
  179. package/src/glossary.ts +18 -0
  180. package/src/health.ts +4 -2
  181. package/src/inInstructions.ts +1 -1
  182. package/{templates/components/evalkeeper → src/next}/RefreshWhile.tsx +2 -2
  183. package/src/next/actions.ts +389 -0
  184. package/src/next/components.ts +31 -0
  185. package/{templates/lib/evalkeeper/cronAuth.ts → src/next/cron.ts} +3 -0
  186. package/src/next/index.ts +15 -0
  187. package/src/next/pages.tsx +106 -0
  188. package/src/next/route.ts +35 -0
  189. package/src/next/weekly.ts +70 -0
  190. package/src/next/wiring.ts +18 -0
  191. package/src/prisma/contracts.ts +249 -0
  192. package/src/prisma/index.ts +1169 -0
  193. package/src/prisma/mapping.ts +147 -0
  194. package/src/prisma/moveIn.ts +502 -0
  195. package/src/prune.ts +77 -0
  196. package/{templates/components/evalkeeper → src/react}/AddCase.tsx +6 -6
  197. package/{templates/components/evalkeeper → src/react}/AnswerKey.tsx +96 -59
  198. package/{templates/components/evalkeeper → src/react}/CaseMenu.tsx +9 -8
  199. package/src/react/CompareView.tsx +270 -0
  200. package/{templates/components/evalkeeper → src/react}/ConfirmAnswer.tsx +6 -3
  201. package/{templates/components/evalkeeper → src/react}/DisagreementChip.tsx +2 -3
  202. package/src/react/FeedbackView.tsx +230 -0
  203. package/{templates/components/evalkeeper → src/react}/Fields.tsx +54 -10
  204. package/src/react/HubSections.tsx +446 -0
  205. package/src/react/ModelMenu.tsx +89 -0
  206. package/src/react/RateView.tsx +143 -0
  207. package/{templates/components/evalkeeper → src/react}/ReadableOutput.tsx +1 -1
  208. package/{templates/components/evalkeeper → src/react}/RollBack.tsx +9 -10
  209. package/src/react/RunView.tsx +151 -0
  210. package/{templates/components/evalkeeper → src/react}/SettingsHistory.tsx +16 -9
  211. package/src/react/SideBySideView.tsx +307 -0
  212. package/src/react/SuiteSections.tsx +925 -0
  213. package/src/react/Tabs.tsx +61 -0
  214. package/{templates/components/evalkeeper → src/react}/Thumbs.tsx +7 -6
  215. package/{templates/components/evalkeeper → src/react}/WeeklyCheck.tsx +31 -20
  216. package/src/react/app.ts +173 -0
  217. package/src/react/format.ts +45 -0
  218. package/src/react/index.ts +31 -0
  219. package/src/react/pieces.tsx +412 -0
  220. package/src/readCheck.ts +1 -1
  221. package/src/runner.ts +182 -4
  222. package/src/settings.ts +1 -1
  223. package/src/store.ts +1 -1
  224. package/src/suggest.ts +145 -13
  225. package/src/suiteContract.ts +35 -28
  226. package/src/testing.ts +2 -2
  227. package/src/types.ts +147 -19
  228. package/starter/index.ts +33 -8
  229. package/templates/app/api/cron/evals-weekly/route.ts +5 -15
  230. package/templates/app/evals/[suite]/compare/page.tsx +6 -383
  231. package/templates/app/evals/[suite]/page.tsx +7 -532
  232. package/templates/app/evals/[suite]/rate/page.tsx +6 -141
  233. package/templates/app/evals/[suite]/runs/[runId]/page.tsx +6 -174
  234. package/templates/app/evals/[suite]/side-by-side/page.tsx +6 -318
  235. package/templates/app/evals/feedback/page.tsx +6 -227
  236. package/templates/app/evals/layout.tsx +10 -0
  237. package/templates/app/evals/page.tsx +7 -365
  238. package/templates/lib/evalkeeper/actions.ts +34 -296
  239. package/templates/lib/evalkeeper/appComponents.tsx +21 -0
  240. package/templates/lib/evalkeeper/evals.ts +14 -0
  241. package/templates/lib/evalkeeper/paths.ts +2 -7
  242. package/templates/components/evalkeeper/Submit.tsx +0 -67
  243. package/templates/components/evalkeeper/Tip.tsx +0 -98
  244. package/templates/components/evalkeeper/ui.tsx +0 -105
  245. package/templates/lib/evalkeeper/time.ts +0 -4
  246. package/templates/lib/evalkeeper/weekly.ts +0 -74
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Renaming between Evalkeeper's model and column names and an app's own,
3
+ * for the stores in index.ts. With no mapping every name is its own, so
4
+ * the queries are exactly what they'd be without this layer.
5
+ */
6
+
7
+ /** A row or query object, keyed by column. */
8
+ export type Row = Record<string, unknown>;
9
+
10
+ /**
11
+ * Column names for one of Evalkeeper's tables, keyed by Evalkeeper's field
12
+ * name. A field left out keeps its own name. `null` says the app's table
13
+ * has no such column: reads give null, and writing anything but null
14
+ * fails, so a value is never silently lost. Only fields that may be null
15
+ * can be left without a column.
16
+ */
17
+ export type ColumnMap<R> = {
18
+ [K in keyof R]?: null extends R[K] ? string | null : string;
19
+ };
20
+
21
+ /** The model methods the stores call, as any Prisma client has them. */
22
+ export type RawDelegate = {
23
+ findMany(args: object): PromiseLike<unknown>;
24
+ findFirst(args: object): PromiseLike<unknown>;
25
+ findUnique(args: object): PromiseLike<unknown>;
26
+ create(args: object): PromiseLike<unknown>;
27
+ update(args: object): PromiseLike<unknown>;
28
+ updateMany(args: object): PromiseLike<unknown>;
29
+ };
30
+
31
+ const METHODS = [
32
+ "findMany",
33
+ "findFirst",
34
+ "findUnique",
35
+ "create",
36
+ "update",
37
+ "updateMany",
38
+ ] as const;
39
+
40
+ function isDelegate(d: unknown): d is RawDelegate {
41
+ if (typeof d !== "object" || d === null) return false;
42
+ return METHODS.every((m) => typeof Reflect.get(d, m) === "function");
43
+ }
44
+
45
+ /** Whether a value read from Prisma is a row (a plain object). */
46
+ export function isRow(v: unknown): v is Row {
47
+ return typeof v === "object" && v !== null && !Array.isArray(v);
48
+ }
49
+
50
+ /**
51
+ * A Prisma Decimal (or any number-like object with `toNumber`) as a
52
+ * number. Evalkeeper keeps money as plain numbers; an app's Decimal
53
+ * columns read the same.
54
+ */
55
+ function plain(v: unknown): unknown {
56
+ if (typeof v !== "object" || v === null || v instanceof Date) return v;
57
+ const toNumber: unknown = Reflect.get(v, "toNumber");
58
+ return typeof toNumber === "function" ? Number(toNumber.call(v)) : v;
59
+ }
60
+
61
+ /**
62
+ * One of Evalkeeper's tables on an app's model: the delegate, and the
63
+ * renames both ways.
64
+ */
65
+ export class Table {
66
+ private readonly toColumn: Map<string, string | null>;
67
+ private readonly columns: Set<string>;
68
+
69
+ /**
70
+ * @param table - Evalkeeper's name for the table, for error messages.
71
+ * @param model - The Prisma client's delegate name for it.
72
+ * @param fields - The renamed and missing columns.
73
+ */
74
+ constructor(
75
+ readonly table: string,
76
+ readonly model: string,
77
+ fields: Readonly<Record<string, string | null | undefined>> = {},
78
+ ) {
79
+ this.toColumn = new Map();
80
+ for (const [field, column] of Object.entries(fields))
81
+ if (column !== undefined) this.toColumn.set(field, column);
82
+ this.columns = new Set(
83
+ [...this.toColumn.values()].filter((c): c is string => c !== null),
84
+ );
85
+ }
86
+
87
+ /** The delegate for this table on a client or transaction. */
88
+ on(db: object): RawDelegate {
89
+ const d: unknown = Reflect.get(db, this.model);
90
+ if (!isDelegate(d))
91
+ throw new Error(
92
+ `Your Prisma client has no model "${this.model}" for Evalkeeper's ${this.table} table: check the mapping's models.`,
93
+ );
94
+ return d;
95
+ }
96
+
97
+ /** The column a field is stored in; null when the table has none. */
98
+ col(field: string): string | null {
99
+ const c = this.toColumn.get(field);
100
+ return c === undefined ? field : c;
101
+ }
102
+
103
+ /**
104
+ * An object keyed by fields (data to write, a where, an orderBy, a
105
+ * select), keyed by columns instead. Values are left as they are.
106
+ */
107
+ out(obj: Row): Row {
108
+ const res: Row = {};
109
+ for (const [field, value] of Object.entries(obj)) {
110
+ const c = this.col(field);
111
+ if (c !== null) res[c] = value;
112
+ else if (value !== null && value !== undefined)
113
+ throw new Error(
114
+ `Evalkeeper's ${this.table}.${field} has no column in your table (the mapping sets it to null), so it can't keep ${JSON.stringify(value)}. Add a nullable column and map ${field} to it.`,
115
+ );
116
+ }
117
+ return res;
118
+ }
119
+
120
+ /** Field names in a `distinct` list, as columns. */
121
+ names(fields: string[]): string[] {
122
+ return fields.map((f) => this.col(f)).filter((c): c is string => !!c);
123
+ }
124
+
125
+ /**
126
+ * A row as read, keyed by Evalkeeper's fields: renamed columns back,
127
+ * missing ones null, Decimals as numbers. Anything that isn't a row is
128
+ * an error in the client, not data.
129
+ */
130
+ in(raw: unknown): Row {
131
+ if (!isRow(raw))
132
+ throw new Error(`Expected a ${this.table} row from Prisma`);
133
+ const res: Row = {};
134
+ for (const [column, value] of Object.entries(raw))
135
+ if (!this.columns.has(column)) res[column] = plain(value);
136
+ for (const [field, column] of this.toColumn)
137
+ res[field] = column === null ? null : plain(raw[column]);
138
+ return res;
139
+ }
140
+
141
+ /** Several rows as read. */
142
+ ins(raw: unknown): Row[] {
143
+ if (!Array.isArray(raw))
144
+ throw new Error(`Expected a list of ${this.table} rows from Prisma`);
145
+ return raw.map((r) => this.in(r));
146
+ }
147
+ }
@@ -0,0 +1,502 @@
1
+ import { checkStoreReads, readCheckSummary } from "../readCheck.js";
2
+ import type { ReadCheckReport } from "../readCheck.js";
3
+ import { stableJson } from "../stableJson.js";
4
+ import type { FeedbackRecord, FeedbackStore } from "../feedback.js";
5
+ import type {
6
+ SettingsChange,
7
+ SettingsStore,
8
+ SettingsVersion,
9
+ } from "../settings.js";
10
+ import type {
11
+ CaseRecord,
12
+ EvalStore,
13
+ LabelRecord,
14
+ OutputRecord,
15
+ RunRecord,
16
+ } from "../store.js";
17
+ import type {
18
+ PrismaEvalClient,
19
+ PrismaFeedbackClient,
20
+ PrismaSettingsTables,
21
+ PrismaStoreMap,
22
+ } from "./index.js";
23
+ import { prismaReadCheck } from "./contracts.js";
24
+ import {
25
+ prismaFeedbackStore,
26
+ prismaSettingsStore,
27
+ prismaStore,
28
+ } from "./index.js";
29
+
30
+ /**
31
+ * Moving in: copying an app's eval data from tables of its own into
32
+ * Evalkeeper's, once. The app's current stores (mapped onto its tables)
33
+ * read everything; this writes it into Evalkeeper's tables keeping every
34
+ * id, date, and who did what, then reads it back to check it's the same.
35
+ * A dry run writes nothing. Running it again skips what already moved.
36
+ * The app's own tables are never changed.
37
+ */
38
+
39
+ /** What to read from: the app's current stores, and what they hold. */
40
+ export type MoveInSource = {
41
+ /** The app's eval store, mapped onto its own tables. */
42
+ store: EvalStore;
43
+ /** The app's thumbs store, if it has thumbs to move. */
44
+ feedbackStore?: FeedbackStore;
45
+ /** The app's settings store, if it has versioned settings to move. */
46
+ settingsStore?: SettingsStore;
47
+ /** The suites whose cases and tests to move, by key. */
48
+ suites: readonly string[];
49
+ /** The operations whose settings to move. */
50
+ operations?: readonly string[];
51
+ /**
52
+ * Your Prisma client and the map your store uses, so the read check
53
+ * sees each value before the store fills in a default (an unknown
54
+ * status read as a known one). Without it, the check reads through the
55
+ * store and can't see those.
56
+ */
57
+ tables?: { db: object; map: PrismaStoreMap };
58
+ };
59
+
60
+ /** The part of a generated Prisma client moving in writes to. */
61
+ export type PrismaMoveInClient = PrismaEvalClient &
62
+ PrismaFeedbackClient &
63
+ PrismaSettingsTables;
64
+
65
+ /** How one table's rows stand. */
66
+ export type MoveInCount = {
67
+ /** Which rows: "cases", "answers", "tests", … */
68
+ table: string;
69
+ /** Rows read from the app's tables. */
70
+ found: number;
71
+ /** Rows already in Evalkeeper's tables from an earlier run. */
72
+ already: number;
73
+ /** Rows this run copied, or would copy on a dry run. */
74
+ moved: number;
75
+ };
76
+
77
+ /** What moving in did, or would do. */
78
+ export type MoveInReport = {
79
+ dryRun: boolean;
80
+ counts: MoveInCount[];
81
+ /**
82
+ * Why rows can't move as they are: they'd clash with rows already in
83
+ * Evalkeeper's tables, or point at a row that isn't there. Nothing is
84
+ * written while there are any.
85
+ */
86
+ problems: string[];
87
+ /** Values in the app's tables that Evalkeeper reads differently. */
88
+ readCheck: ReadCheckReport;
89
+ /** After a move: whether everything reads back the same. */
90
+ verified: { ok: boolean; differences: string[] } | null;
91
+ };
92
+
93
+ /** What moving in takes beyond the source. */
94
+ export type MoveInOptions = {
95
+ /** Read and report, and write nothing. */
96
+ dryRun?: boolean;
97
+ /**
98
+ * Move even though the read check found values Evalkeeper reads
99
+ * differently; they move as Evalkeeper reads them.
100
+ */
101
+ acceptReadProblems?: boolean;
102
+ };
103
+
104
+ /** Everything the source holds, read once. */
105
+ type Data = {
106
+ cases: CaseRecord[];
107
+ runs: RunRecord[];
108
+ outputs: OutputRecord[];
109
+ feedback: FeedbackRecord[];
110
+ versions: SettingsVersion[];
111
+ changes: SettingsChange[];
112
+ live: SettingsVersion[];
113
+ };
114
+
115
+ async function readAll(s: MoveInSource): Promise<Data> {
116
+ const cases: CaseRecord[] = [];
117
+ const runs: RunRecord[] = [];
118
+ for (const suite of s.suites) {
119
+ cases.push(...(await s.store.listCases(suite, { includeRetired: true })));
120
+ runs.push(...(await s.store.listRuns(suite)));
121
+ }
122
+ const ids = runs.map((r) => r.id);
123
+ const outputs = s.store.listOutputsFor
124
+ ? await s.store.listOutputsFor(ids)
125
+ : (await Promise.all(ids.map((id) => s.store.listOutputs(id)))).flat();
126
+ const feedback = s.feedbackStore ? await s.feedbackStore.listFeedback() : [];
127
+ const versions: SettingsVersion[] = [];
128
+ const changes: SettingsChange[] = [];
129
+ const live: SettingsVersion[] = [];
130
+ if (s.settingsStore)
131
+ for (const op of s.operations ?? []) {
132
+ versions.push(...(await s.settingsStore.listVersions(op)));
133
+ changes.push(...(await s.settingsStore.listChanges(op)));
134
+ const l = await s.settingsStore.liveVersion(op);
135
+ if (l) live.push(l);
136
+ }
137
+ return { cases, runs, outputs, feedback, versions, changes, live };
138
+ }
139
+
140
+ /** Prisma reads `undefined` as "leave it alone": JSON null stays unset. */
141
+ const json = (v: unknown) => (v === undefined || v === null ? undefined : v);
142
+
143
+ /** Which of these ids a table already has. */
144
+ async function existing(
145
+ table: { findMany(args: object): PromiseLike<object[]> },
146
+ ids: string[],
147
+ key = "id",
148
+ ): Promise<Set<string>> {
149
+ const found = new Set<string>();
150
+ // In batches, so a large table never makes one huge query.
151
+ for (let i = 0; i < ids.length; i += 500) {
152
+ const rows = await table.findMany({
153
+ where: { [key]: { in: ids.slice(i, i + 500) } },
154
+ select: { [key]: true },
155
+ });
156
+ for (const r of rows)
157
+ found.add(String((r as Record<string, unknown>)[key]));
158
+ }
159
+ return found;
160
+ }
161
+
162
+ /** A record as JSON, for comparing what moved with what it came from. */
163
+ const same = (a: unknown, b: unknown) => stableJson(a) === stableJson(b);
164
+
165
+ /** A case with its answers in a fixed order, for comparing. */
166
+ const sortedCase = (c: CaseRecord) => ({
167
+ ...c,
168
+ labels: [...c.labels].sort((x, y) => (x.id < y.id ? -1 : 1)),
169
+ });
170
+
171
+ /** A rating without what only a mapped store says (`keepsInputs`). */
172
+ const rating = ({ keepsInputs: _k, ...f }: FeedbackRecord) => f;
173
+
174
+ /**
175
+ * Copies an app's eval data from its own tables (read through its current
176
+ * stores) into Evalkeeper's tables, keeping ids, dates, who confirmed each
177
+ * answer, and every test's answers and grades. Run it with `dryRun`
178
+ * first: it reports what it would copy, table by table, what already
179
+ * moved, and anything that doesn't fit, and writes nothing. A real run
180
+ * copies only what isn't there yet, so it's safe to run again, and then
181
+ * reads everything back to check it's the same. Your own tables are never
182
+ * changed; keep them until you decide to drop them.
183
+ *
184
+ * @example
185
+ * ```ts
186
+ * const source = { store: myMappedStore, feedbackStore: myThumbs,
187
+ * suites: SUITES.map((s) => s.key) };
188
+ * console.log(moveInSummary(await moveIn(source, prisma, { dryRun: true })).join("\n"));
189
+ * ```
190
+ *
191
+ * @param source - Your current stores, and the suites and operations to move.
192
+ * @param db - Your Prisma client, with Evalkeeper's tables migrated.
193
+ * @param opts - `dryRun` to only report.
194
+ */
195
+ export async function moveIn(
196
+ source: MoveInSource,
197
+ db: PrismaMoveInClient,
198
+ opts: MoveInOptions = {},
199
+ ): Promise<MoveInReport> {
200
+ const data = await readAll(source);
201
+ const readCheck = source.tables
202
+ ? await prismaReadCheck(source.tables.db, source.tables.map, {
203
+ suites: source.suites,
204
+ })
205
+ : await checkStoreReads(source.store, { suites: source.suites });
206
+ const problems: string[] = [];
207
+
208
+ // What each table already has, by id.
209
+ const has = {
210
+ cases: await existing(
211
+ db.evalCase,
212
+ data.cases.map((c) => c.id),
213
+ ),
214
+ labels: await existing(
215
+ db.evalCaseLabel,
216
+ data.cases.flatMap((c) => c.labels.map((l) => l.id)),
217
+ ),
218
+ runs: await existing(
219
+ db.evalRun,
220
+ data.runs.map((r) => r.id),
221
+ ),
222
+ outputs: await existing(
223
+ db.evalOutput,
224
+ data.outputs.map((o) => o.id),
225
+ ),
226
+ feedback: await existing(
227
+ db.evalFeedback,
228
+ data.feedback.map((f) => f.id),
229
+ ),
230
+ versions: await existing(
231
+ db.evalSettingsVersion,
232
+ data.versions.map((v) => v.id),
233
+ ),
234
+ changes: await existing(
235
+ db.evalSettingsChange,
236
+ data.changes.map((c) => c.id),
237
+ ),
238
+ live: await existing(
239
+ db.evalSettingsLive,
240
+ data.live.map((l) => l.operation),
241
+ "operation",
242
+ ),
243
+ };
244
+
245
+ // Rows that point at something that isn't moving.
246
+ const caseIds = new Set(data.cases.map((c) => c.id));
247
+ const runIds = new Set(data.runs.map((r) => r.id));
248
+ const outputs = data.outputs.filter((o) => {
249
+ if (caseIds.has(o.caseId) && runIds.has(o.runId)) return true;
250
+ problems.push(
251
+ `Test answer ${o.id} belongs to a ${caseIds.has(o.caseId) ? "test" : "case"} that isn't in the suites being moved.`,
252
+ );
253
+ return false;
254
+ });
255
+
256
+ // Rows that would clash with what's already in Evalkeeper's tables.
257
+ for (const op of source.operations ?? []) {
258
+ if (!source.settingsStore) break;
259
+ const theirs = await db.evalSettingsVersion.findMany({
260
+ where: { operation: op },
261
+ select: { id: true },
262
+ });
263
+ const ours = new Set(
264
+ data.versions.filter((v) => v.operation === op).map((v) => v.id),
265
+ );
266
+ if (theirs.some((v) => !ours.has(v.id)))
267
+ problems.push(
268
+ `${op} already has settings versions in Evalkeeper's tables that aren't from your tables; histories aren't merged. Move into empty settings tables.`,
269
+ );
270
+ }
271
+ for (const f of data.feedback) {
272
+ if (has.feedback.has(f.id)) continue;
273
+ const clash = await db.evalFeedback.findFirst({
274
+ where: {
275
+ raterId: f.raterId,
276
+ operation: f.operation,
277
+ targetId: f.targetId,
278
+ },
279
+ });
280
+ if (clash)
281
+ problems.push(
282
+ `Thumbs ${f.id} clashes with ${clash.id} in Evalkeeper's tables: the same person rated the same answer.`,
283
+ );
284
+ }
285
+
286
+ const labels = data.cases.flatMap((c) =>
287
+ c.labels.map((l) => ({ ...l, caseId: c.id })),
288
+ );
289
+ const todo = {
290
+ cases: data.cases.filter((c) => !has.cases.has(c.id)),
291
+ labels: labels.filter((l) => !has.labels.has(l.id)),
292
+ runs: data.runs.filter((r) => !has.runs.has(r.id)),
293
+ outputs: outputs.filter((o) => !has.outputs.has(o.id)),
294
+ feedback: data.feedback.filter((f) => !has.feedback.has(f.id)),
295
+ versions: data.versions.filter((v) => !has.versions.has(v.id)),
296
+ changes: data.changes.filter((c) => !has.changes.has(c.id)),
297
+ live: data.live.filter((l) => !has.live.has(l.operation)),
298
+ };
299
+ const count = (table: string, found: number, moved: number) => ({
300
+ table,
301
+ found,
302
+ already: found - moved,
303
+ moved,
304
+ });
305
+ const counts: MoveInCount[] = [
306
+ count("cases", data.cases.length, todo.cases.length),
307
+ count("answers", labels.length, todo.labels.length),
308
+ count("tests", data.runs.length, todo.runs.length),
309
+ count("test answers", outputs.length, todo.outputs.length),
310
+ count("thumbs", data.feedback.length, todo.feedback.length),
311
+ count("settings versions", data.versions.length, todo.versions.length),
312
+ count("settings changes", data.changes.length, todo.changes.length),
313
+ count("live settings", data.live.length, todo.live.length),
314
+ ];
315
+ const readProblems = readCheck.suites.some((s) => s.problems.length);
316
+ const report = { counts, problems, readCheck, verified: null };
317
+ if (
318
+ opts.dryRun ||
319
+ problems.length ||
320
+ (readProblems && !opts.acceptReadProblems)
321
+ )
322
+ return { ...report, dryRun: true };
323
+
324
+ for (const c of todo.cases)
325
+ await db.evalCase.create({
326
+ data: {
327
+ id: c.id,
328
+ suite: c.suite,
329
+ input: json(c.input),
330
+ tags: c.tags,
331
+ split: c.split,
332
+ status: c.status,
333
+ source: c.source,
334
+ sourceRef: c.sourceRef,
335
+ note: c.note,
336
+ createdAt: c.createdAt,
337
+ updatedAt: c.updatedAt,
338
+ },
339
+ });
340
+ for (const l of todo.labels)
341
+ await db.evalCaseLabel.create({
342
+ data: {
343
+ id: l.id,
344
+ caseId: l.caseId,
345
+ kind: l.kind,
346
+ status: l.status,
347
+ // A skip's value is {}, as the store writes it.
348
+ value: l.status === "SKIPPED" ? {} : json(l.value),
349
+ raterRole: l.raterRole,
350
+ raterId: l.raterId,
351
+ note: l.note,
352
+ createdAt: l.createdAt,
353
+ updatedAt: l.updatedAt,
354
+ } satisfies Omit<LabelRecord, "value"> & {
355
+ caseId: string;
356
+ value: unknown;
357
+ },
358
+ });
359
+ for (const r of todo.runs)
360
+ await db.evalRun.create({
361
+ data: {
362
+ ...r,
363
+ temperature: r.temperature ?? null,
364
+ maxOutputTokens: r.maxOutputTokens ?? null,
365
+ metrics: json(r.metrics),
366
+ },
367
+ });
368
+ for (const o of todo.outputs)
369
+ await db.evalOutput.create({
370
+ data: { ...o, output: json(o.output), scores: json(o.scores) },
371
+ });
372
+ for (const f of todo.feedback)
373
+ await db.evalFeedback.create({
374
+ data: { ...rating(f), input: json(f.input), output: json(f.output) },
375
+ });
376
+ for (const v of todo.versions)
377
+ await db.evalSettingsVersion.create({
378
+ data: { ...v, temperature: v.temperature ?? null },
379
+ });
380
+ for (const c of todo.changes)
381
+ await db.evalSettingsChange.create({
382
+ data: { ...c, evidence: json(c.evidence) },
383
+ });
384
+ for (const l of todo.live)
385
+ await db.evalSettingsLive.create({
386
+ data: { operation: l.operation, versionId: l.id },
387
+ });
388
+
389
+ return {
390
+ ...report,
391
+ dryRun: false,
392
+ verified: await verify(source, data, outputs, db),
393
+ };
394
+ }
395
+
396
+ /** Reads everything back from Evalkeeper's tables and compares. */
397
+ async function verify(
398
+ source: MoveInSource,
399
+ data: Data,
400
+ outputs: OutputRecord[],
401
+ db: PrismaMoveInClient,
402
+ ): Promise<{ ok: boolean; differences: string[] }> {
403
+ const store = prismaStore(db);
404
+ const differences: string[] = [];
405
+ const check = <T extends { id: string }>(
406
+ what: string,
407
+ before: T[],
408
+ after: T[],
409
+ shape: (x: T) => unknown = (x) => x,
410
+ ) => {
411
+ const byId = new Map(after.map((x) => [x.id, x]));
412
+ for (const b of before) {
413
+ const a = byId.get(b.id);
414
+ if (!a) differences.push(`${what} ${b.id} isn't in Evalkeeper's tables.`);
415
+ else if (!same(shape(a), shape(b)))
416
+ differences.push(`${what} ${b.id} reads back differently.`);
417
+ }
418
+ };
419
+ const cases: CaseRecord[] = [];
420
+ const runs: RunRecord[] = [];
421
+ for (const suite of source.suites) {
422
+ cases.push(...(await store.listCases(suite, { includeRetired: true })));
423
+ runs.push(...(await store.listRuns(suite)));
424
+ }
425
+ check("Case", data.cases, cases, sortedCase);
426
+ check("Test", data.runs, runs);
427
+ const runsMoved = [...new Set(outputs.map((o) => o.runId))];
428
+ check(
429
+ "Test answer",
430
+ outputs,
431
+ (await Promise.all(runsMoved.map((id) => store.listOutputs(id)))).flat(),
432
+ );
433
+ if (source.feedbackStore)
434
+ check(
435
+ "Thumbs",
436
+ data.feedback,
437
+ await prismaFeedbackStore(db).listFeedback(),
438
+ rating,
439
+ );
440
+ if (source.settingsStore) {
441
+ // Its own transaction isn't needed for reading.
442
+ const settings = prismaSettingsStore({
443
+ ...db,
444
+ $transaction: (fn) => fn(db),
445
+ });
446
+ for (const op of source.operations ?? []) {
447
+ check(
448
+ "Settings version",
449
+ data.versions.filter((v) => v.operation === op),
450
+ await settings.listVersions(op),
451
+ );
452
+ check(
453
+ "Settings change",
454
+ data.changes.filter((c) => c.operation === op),
455
+ await settings.listChanges(op),
456
+ );
457
+ const was = data.live.find((l) => l.operation === op);
458
+ const now = await settings.liveVersion(op);
459
+ if (was?.id !== now?.id)
460
+ differences.push(`${op}'s live settings read back differently.`);
461
+ }
462
+ }
463
+ return { ok: !differences.length, differences };
464
+ }
465
+
466
+ /**
467
+ * A move-in report in words: what moved (or would), table by table, then
468
+ * anything that stopped it or reads back differently.
469
+ *
470
+ * @param r - What `moveIn` returned.
471
+ */
472
+ export function moveInSummary(r: MoveInReport): string[] {
473
+ const lines = [
474
+ r.dryRun
475
+ ? "Moving in: nothing written. It would copy:"
476
+ : "Moved into Evalkeeper's tables:",
477
+ ];
478
+ for (const c of r.counts)
479
+ if (c.found)
480
+ lines.push(
481
+ ` ${c.table}: ${c.moved} of ${c.found}${c.already ? ` (${c.already} already there)` : ""}`,
482
+ );
483
+ if (r.counts.every((c) => !c.found)) lines.push(" nothing: no rows found.");
484
+ if (r.readCheck.suites.some((s) => s.problems.length))
485
+ lines.push(
486
+ "Values Evalkeeper reads differently (they'd move as it reads them; pass acceptReadProblems once that's right):",
487
+ ...readCheckSummary(r.readCheck).map((l) => ` ${l}`),
488
+ );
489
+ if (r.problems.length)
490
+ lines.push(
491
+ "Can't move until these are fixed:",
492
+ ...r.problems.map((p) => ` ${p}`),
493
+ );
494
+ if (r.verified)
495
+ lines.push(
496
+ r.verified.ok
497
+ ? "Read back: every row is the same."
498
+ : "Read back differently:",
499
+ ...r.verified.differences.map((d) => ` ${d}`),
500
+ );
501
+ return lines;
502
+ }