@william_jin/vireo 0.0.0-stage → 0.19.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 (70) hide show
  1. package/LICENSE.md +61 -0
  2. package/README.md +136 -2
  3. package/dist/bin.d.ts +2 -0
  4. package/dist/bin.js +61 -0
  5. package/dist/bin.js.map +1 -0
  6. package/dist/board.d.ts +87 -0
  7. package/dist/board.js +310 -0
  8. package/dist/board.js.map +1 -0
  9. package/dist/calls.d.ts +19 -0
  10. package/dist/calls.js +9 -0
  11. package/dist/calls.js.map +1 -0
  12. package/dist/cli.d.ts +24 -0
  13. package/dist/cli.js +496 -0
  14. package/dist/cli.js.map +1 -0
  15. package/dist/collect.d.ts +43 -0
  16. package/dist/collect.js +41 -0
  17. package/dist/collect.js.map +1 -0
  18. package/dist/db.d.ts +18 -0
  19. package/dist/db.js +18 -0
  20. package/dist/db.js.map +1 -0
  21. package/dist/index.d.ts +10 -0
  22. package/dist/index.js +8 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/live.d.ts +28 -0
  25. package/dist/live.js +121 -0
  26. package/dist/live.js.map +1 -0
  27. package/dist/media.d.ts +25 -0
  28. package/dist/media.js +63 -0
  29. package/dist/media.js.map +1 -0
  30. package/dist/migrations.d.ts +5 -0
  31. package/dist/migrations.js +12 -0
  32. package/dist/migrations.js.map +1 -0
  33. package/dist/schema.d.ts +2103 -0
  34. package/dist/schema.js +362 -0
  35. package/dist/schema.js.map +1 -0
  36. package/dist/stats.d.ts +72 -0
  37. package/dist/stats.js +185 -0
  38. package/dist/stats.js.map +1 -0
  39. package/dist/store.d.ts +1068 -0
  40. package/dist/store.js +1226 -0
  41. package/dist/store.js.map +1 -0
  42. package/dist/sync.d.ts +26 -0
  43. package/dist/sync.js +47 -0
  44. package/dist/sync.js.map +1 -0
  45. package/drizzle/0000_init.sql +116 -0
  46. package/drizzle/0001_lineage.sql +18 -0
  47. package/drizzle/0002_drop_parent_id.sql +1 -0
  48. package/drizzle/0003_batch_n.sql +8 -0
  49. package/drizzle/0004_score.sql +7 -0
  50. package/drizzle/0005_steers.sql +26 -0
  51. package/drizzle/0006_steers_fk_index.sql +3 -0
  52. package/drizzle/0007_batch_title.sql +1 -0
  53. package/drizzle/0008_calls.sql +24 -0
  54. package/drizzle/0009_content_type.sql +1 -0
  55. package/drizzle/0010_board_pins.sql +33 -0
  56. package/drizzle/0011_pins_fk_indexes.sql +2 -0
  57. package/drizzle/meta/0000_snapshot.json +816 -0
  58. package/drizzle/meta/0001_snapshot.json +918 -0
  59. package/drizzle/meta/0002_snapshot.json +912 -0
  60. package/drizzle/meta/0003_snapshot.json +927 -0
  61. package/drizzle/meta/0004_snapshot.json +941 -0
  62. package/drizzle/meta/0005_snapshot.json +1120 -0
  63. package/drizzle/meta/0006_snapshot.json +1165 -0
  64. package/drizzle/meta/0007_snapshot.json +1171 -0
  65. package/drizzle/meta/0008_snapshot.json +1256 -0
  66. package/drizzle/meta/0009_snapshot.json +1262 -0
  67. package/drizzle/meta/0010_snapshot.json +1493 -0
  68. package/drizzle/meta/0011_snapshot.json +1523 -0
  69. package/drizzle/meta/_journal.json +90 -0
  70. package/package.json +91 -4
package/dist/store.js ADDED
@@ -0,0 +1,1226 @@
1
+ /**
2
+ * The vireo ledger: one method per thing a CLI, an agent or a page does, bound to the host's
3
+ * ports (database, collectors, hooks). Ranking and rates are `stats.ts`.
4
+ */
5
+ import { and, asc, desc, eq, inArray, isNotNull, isNull, like, or, sql } from "drizzle-orm";
6
+ import { PgTransaction } from "drizzle-orm/pg-core";
7
+ import * as pinboard from "./board.js";
8
+ import { collect } from "./collect.js";
9
+ import { atomic, VireoError } from "./db.js";
10
+ import { live } from "./live.js";
11
+ import { batches, calls, guides, lineage, notes, samples, ships, steers, subjects, TAP, VERDICTS, verdictOf, } from "./schema.js";
12
+ import { fitPlackettLuce, rateSplit, tiersToChoices } from "./stats.js";
13
+ import { isSource } from "./sync.js";
14
+ /** `s3://` (the bucket signs it) or `https://` (served as is: a live page on its own origin). */
15
+ export const isMediaUri = (uri) => /^(s3|https):\/\/[^\s/]+/i.test(uri);
16
+ const parentOf = (p) => typeof p === "number" ? { id: p, took: null } : { id: p.id, took: p.took?.trim() || null };
17
+ /** What the person saw: fixed only before a call or a note. */
18
+ const SEEN_FIELDS = ["body", "media", "poster", "source"];
19
+ const SAMPLE_FIELDS = ["name", "change", "guides", ...SEEN_FIELDS];
20
+ /** `by` of calls made before calls had a judge (migration 0008); a host may name them after. */
21
+ export const EARLIER_JUDGE = "person";
22
+ export const BATCH_SORTS = ["waiting", "newest", "oldest", "subject", "good"];
23
+ /** `roots` and every sample that grew from them, over any parent edge. */
24
+ function grownFrom(roots, edges) {
25
+ const kids = new Map();
26
+ for (const e of edges)
27
+ kids.set(e.parentId, [...(kids.get(e.parentId) ?? []), e.childId]);
28
+ const out = new Set();
29
+ const stack = [...roots];
30
+ while (stack.length) {
31
+ const id = stack.pop();
32
+ if (out.has(id))
33
+ continue;
34
+ out.add(id);
35
+ stack.push(...(kids.get(id) ?? []));
36
+ }
37
+ return out;
38
+ }
39
+ const steerName = (s) => s.kind === "width"
40
+ ? `width ${s.width} (steer ${s.id})`
41
+ : s.kind === "cross"
42
+ ? `cross ${s.sampleId} × ${s.otherId} (steer ${s.id})`
43
+ : `${s.kind} ${s.sampleId} (steer ${s.id})`;
44
+ const GOOD = ["amazing", "good"];
45
+ /** Unmarked in a judged batch reads as an okay 5: no call is a middling one. */
46
+ const UNMARKED = 5;
47
+ /** Fisher-Yates with Math.random: positions only hide the agent's order. */
48
+ const shuffled = (xs) => {
49
+ const a = [...xs];
50
+ for (let i = a.length - 1; i > 0; i--) {
51
+ const j = Math.floor(Math.random() * (i + 1));
52
+ [a[i], a[j]] = [a[j], a[i]];
53
+ }
54
+ return a;
55
+ };
56
+ /**
57
+ * One sheet per (batch, person) who called in it: each sample of the batch with that person's
58
+ * call, or none (unmarked). The unit of every rank and rate (D11).
59
+ */
60
+ export function sheets(rows, cs) {
61
+ const inBatch = new Map();
62
+ for (const r of rows)
63
+ inBatch.set(r.batchId, [...(inBatch.get(r.batchId) ?? []), r.id]);
64
+ const batchOf = new Map(rows.map((r) => [r.id, r.batchId]));
65
+ const out = new Map();
66
+ for (const c of cs) {
67
+ const b = batchOf.get(c.sampleId);
68
+ if (b == null)
69
+ continue;
70
+ const k = `${b}\u0000${c.by}`;
71
+ const sheet = out.get(k) ?? { batchId: b, by: c.by, got: new Map() };
72
+ sheet.got.set(c.sampleId, c);
73
+ out.set(k, sheet);
74
+ }
75
+ return [...out.values()].map((x) => ({
76
+ batchId: x.batchId,
77
+ by: x.by,
78
+ marks: (inBatch.get(x.batchId) ?? []).map((id) => ({ id, call: x.got.get(id) ?? null })),
79
+ }));
80
+ }
81
+ /**
82
+ * Strength per judged sample: each sheet is a partial ranking by score, 10 down to 1, ties
83
+ * unordered; unmarked reads as 5. Wins from 9 and up count double.
84
+ */
85
+ export function strengths(rows, cs) {
86
+ const ss = sheets(rows, cs);
87
+ const ids = [...new Set(ss.flatMap((x) => x.marks.map((m) => String(m.id))))];
88
+ const scores = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
89
+ const choices = ss.flatMap((x) => tiersToChoices(scores.map((n) => x.marks.filter((m) => (m.call?.score ?? UNMARKED) === n).map((m) => String(m.id))), scores.map((n) => (n >= TAP.amazing ? 2 : 1))));
90
+ return fitPlackettLuce(ids, choices);
91
+ }
92
+ /** Good or better over every (sample, person) mark of these sheets; null with none. */
93
+ export function goodRateOf(ss) {
94
+ const marks = ss.flatMap((x) => x.marks);
95
+ return marks.length
96
+ ? marks.filter((m) => GOOD.includes(m.call?.verdict ?? null)).length / marks.length
97
+ : null;
98
+ }
99
+ /** With-vs-without good rate per guide, over every mark in judged batches. */
100
+ export function guideStats(guideRows, judged, cs) {
101
+ const guidesOf = new Map(judged.map((r) => [r.id, r.guides]));
102
+ const marks = sheets(judged, cs).flatMap((x) => x.marks);
103
+ return guideRows.map((g) => ({
104
+ ...g,
105
+ effect: rateSplit(marks.map((m) => ({
106
+ has: (guidesOf.get(m.id) ?? []).includes(g.id),
107
+ good: GOOD.includes(m.call?.verdict ?? null),
108
+ }))),
109
+ }));
110
+ }
111
+ /** Mean of the calls a reader may see, and its zone; null with none. */
112
+ const pooled = (cs) => {
113
+ if (!cs.length)
114
+ return { score: null, verdict: null };
115
+ const mean = cs.reduce((a, c) => a + c.score, 0) / cs.length;
116
+ return { score: Math.round(mean * 10) / 10, verdict: verdictOf(Math.round(mean)) };
117
+ };
118
+ /**
119
+ * What a reader may see of an open batch (D11). `viewer` = a person: while open, only their own
120
+ * calls and notes, and none of the agent's words. Null = the agent: everything.
121
+ */
122
+ const blindFor = (viewer, open) => viewer != null && open;
123
+ /** Waits on the person: open and its subject's newest. A newer batch replaces an unmarked one. */
124
+ const WAITS = and(eq(batches.state, "open"), sql `${batches.n} = (select max(b.n) from vireo.batches b where b.subject_id = ${batches.subjectId})`);
125
+ /** How people and agents name a batch: its number within the subject. The id is secondary. */
126
+ export const refOf = (slug, n) => `${slug}:${n}`;
127
+ export class Vireo {
128
+ db;
129
+ collectors;
130
+ hooks;
131
+ constructor(p) {
132
+ this.db = p.db;
133
+ this.collectors = p.collectors ?? [];
134
+ this.hooks = p.hooks ?? {};
135
+ }
136
+ async write(by, fn) {
137
+ const out = await atomic(this.db, async (tx) => {
138
+ if (by && this.hooks.onWrite)
139
+ await this.hooks.onWrite(tx, by);
140
+ return fn(tx);
141
+ });
142
+ await this.told();
143
+ return out;
144
+ }
145
+ /** The host's push after a commit; a host transaction commits later, so none then. */
146
+ async told() {
147
+ const after = this.hooks.afterWrite;
148
+ if (!after || this.db instanceof PgTransaction)
149
+ return;
150
+ await Promise.resolve()
151
+ .then(after)
152
+ .catch(() => undefined);
153
+ }
154
+ async subjectOf(ref, db = this.db) {
155
+ const id = typeof ref === "number" || /^\d+$/.test(ref) ? Number(ref) : null;
156
+ const [row] = await db
157
+ .select()
158
+ .from(subjects)
159
+ .where(id ? eq(subjects.id, id) : eq(subjects.slug, String(ref)));
160
+ if (!row)
161
+ throw new VireoError(`no subject ${ref}`, 404);
162
+ return row;
163
+ }
164
+ /** A batch by id, or `<subject>:<n>` (its number within the subject). */
165
+ async batchOf(ref, db = this.db) {
166
+ if (typeof ref === "number" || /^\d+$/.test(ref))
167
+ return Number(ref);
168
+ const m = /^(.+):(\d+)$/.exec(ref);
169
+ if (!m)
170
+ throw new VireoError(`a batch is an id or <subject>:<n>, not ${ref}`);
171
+ const subject = await this.subjectOf(m[1], db);
172
+ const [row] = await db
173
+ .select({ id: batches.id })
174
+ .from(batches)
175
+ .where(and(eq(batches.subjectId, subject.id), eq(batches.n, Number(m[2]))));
176
+ if (!row)
177
+ throw new VireoError(`no batch ${ref}`, 404);
178
+ return row.id;
179
+ }
180
+ /** More samples in an open batch: `addBatch` with `into`, the subject read from the batch. */
181
+ async appendBatch(ref, b) {
182
+ const id = await this.batchOf(ref);
183
+ const [row] = await this.db
184
+ .select({ subjectId: batches.subjectId })
185
+ .from(batches)
186
+ .where(eq(batches.id, id));
187
+ if (!row)
188
+ throw new VireoError(`no batch ${ref}`, 404);
189
+ return this.addBatch(row.subjectId, { ...b, into: id });
190
+ }
191
+ /** A sample of an open batch: a closed batch's calls and notes are its finished ranking. Share lock: a close waits. */
192
+ async markable(tx, sampleId) {
193
+ const [sample] = await tx
194
+ .select({ batchId: samples.batchId })
195
+ .from(samples)
196
+ .where(eq(samples.id, sampleId));
197
+ if (!sample)
198
+ throw new VireoError(`no sample ${sampleId}`, 404);
199
+ const [row] = await tx
200
+ .select({ state: batches.state, n: batches.n, subjectId: batches.subjectId })
201
+ .from(batches)
202
+ .where(eq(batches.id, sample.batchId))
203
+ .for("share");
204
+ if (!row)
205
+ throw new VireoError(`no sample ${sampleId}`, 404);
206
+ if (row.state !== "open") {
207
+ const s = await this.subjectOf(row.subjectId, tx);
208
+ throw new VireoError(`${refOf(s.slug, row.n)} is closed: its calls and notes stay`, 409);
209
+ }
210
+ }
211
+ /** An open batch of this subject, for more samples; a closed one is refused. */
212
+ async openBatch(tx, subject, ref) {
213
+ const id = await this.batchOf(ref, tx);
214
+ const [row] = await tx.select().from(batches).where(eq(batches.id, id)).for("update");
215
+ if (!row)
216
+ throw new VireoError(`no batch ${ref}`, 404);
217
+ if (row.subjectId !== subject.id)
218
+ throw new VireoError(`batch ${ref} is not ${subject.slug}'s`, 409);
219
+ if (row.state !== "open")
220
+ throw new VireoError(`${refOf(subject.slug, row.n)} is closed: add a new batch`, 409);
221
+ return row;
222
+ }
223
+ /** Each sample's parent ids in a batch. */
224
+ async parentSetsOf(db, batchId) {
225
+ const es = await db
226
+ .select({ childId: lineage.childId, parentId: lineage.parentId })
227
+ .from(lineage)
228
+ .innerJoin(samples, eq(samples.id, lineage.childId))
229
+ .where(eq(samples.batchId, batchId));
230
+ const by = new Map();
231
+ for (const e of es)
232
+ by.set(e.childId, (by.get(e.childId) ?? new Set()).add(e.parentId));
233
+ return [...by.values()];
234
+ }
235
+ /**
236
+ * Moves an open batch's samples into another open batch of the subject, then deletes the
237
+ * empty one. For a batch that should have been an append.
238
+ */
239
+ mergeBatch(from, into, by) {
240
+ return this.write(by, async (tx) => {
241
+ const src = await this.batchOf(from, tx);
242
+ const dst = await this.batchOf(into, tx);
243
+ if (src === dst)
244
+ throw new VireoError("a batch cannot merge into itself");
245
+ // both rows, in id order: A→B and B→A at once wait instead of deadlocking
246
+ await tx
247
+ .select({ id: batches.id })
248
+ .from(batches)
249
+ .where(inArray(batches.id, [src, dst]))
250
+ .orderBy(batches.id)
251
+ .for("update");
252
+ const [a] = await tx.select().from(batches).where(eq(batches.id, src)).for("update");
253
+ if (!a)
254
+ throw new VireoError(`no batch ${from}`, 404);
255
+ const subject = await this.subjectOf(a.subjectId, tx);
256
+ if (a.state !== "open")
257
+ throw new VireoError(`${refOf(subject.slug, a.n)} is closed: its marks stay where they are`, 409);
258
+ const b = await this.openBatch(tx, subject, dst);
259
+ const [last] = await tx
260
+ .select({ p: sql `coalesce(max(${samples.position}), -1)::int` })
261
+ .from(samples)
262
+ .where(eq(samples.batchId, b.id));
263
+ const moved = await tx
264
+ .update(samples)
265
+ .set({
266
+ batchId: b.id,
267
+ position: sql `${samples.position} + ${(last?.p ?? -1) + 1}`,
268
+ })
269
+ .where(eq(samples.batchId, a.id))
270
+ .returning({ id: samples.id });
271
+ await tx.update(steers).set({ endedBy: b.id }).where(eq(steers.endedBy, a.id));
272
+ await tx
273
+ .update(batches)
274
+ .set({ why: `${b.why}\n\nAdded: ${a.why}` })
275
+ .where(eq(batches.id, b.id));
276
+ await tx.delete(batches).where(eq(batches.id, a.id));
277
+ return {
278
+ batch: refOf(subject.slug, b.n),
279
+ id: b.id,
280
+ merged: { batch: refOf(subject.slug, a.n), id: a.id },
281
+ samples: moved.map((r) => r.id).sort((x, y) => x - y),
282
+ };
283
+ });
284
+ }
285
+ newSubject(s) {
286
+ return this.write(s.by ?? null, async (tx) => {
287
+ const [row] = await tx
288
+ .insert(subjects)
289
+ .values({
290
+ slug: s.slug,
291
+ name: s.name,
292
+ kind: s.kind,
293
+ contentType: s.contentType ?? null,
294
+ brief: s.brief ?? null,
295
+ seeds: s.seeds ?? [],
296
+ by: s.by ?? null,
297
+ })
298
+ .returning();
299
+ return row;
300
+ });
301
+ }
302
+ async listSubjects() {
303
+ const rows = await this.db.select().from(subjects).orderBy(desc(subjects.createdAt));
304
+ const counts = await this.db
305
+ .select({
306
+ subjectId: samples.subjectId,
307
+ samples: sql `count(*)::int`,
308
+ kept: sql `count(${samples.keptAt})::int`,
309
+ open: sql `count(*) filter (where ${WAITS})::int`,
310
+ })
311
+ .from(samples)
312
+ .innerJoin(batches, eq(batches.id, samples.batchId))
313
+ .groupBy(samples.subjectId);
314
+ const by = new Map(counts.map((c) => [c.subjectId, c]));
315
+ return rows.map((s) => ({
316
+ ...s,
317
+ samples: by.get(s.id)?.samples ?? 0,
318
+ kept: by.get(s.id)?.kept ?? 0,
319
+ toPick: by.get(s.id)?.open ?? 0,
320
+ }));
321
+ }
322
+ /** One batch for review: samples in a shuffled order. */
323
+ /** A new batch, or with `into` (id or `<subject>:<n>`) more samples in an open one. */
324
+ async addBatch(ref, b) {
325
+ if (!b.why.trim())
326
+ throw new VireoError("say why: what changed and what it tests");
327
+ const title = b.title?.trim() || null;
328
+ // appending keeps the batch's title
329
+ if (b.into == null && !title)
330
+ throw new VireoError("a title: one line, what this batch is");
331
+ if (title && title.length > 120)
332
+ throw new VireoError("a title is 120 characters at most");
333
+ if (!b.samples.length)
334
+ throw new VireoError("a batch needs samples");
335
+ for (const s of b.samples)
336
+ if (!s.body?.trim() && !s.media)
337
+ throw new VireoError("each sample needs a body or a file");
338
+ for (const s of b.samples)
339
+ for (const uri of [s.media, s.poster])
340
+ if (uri && !isMediaUri(uri))
341
+ throw new VireoError("media and poster are s3:// or https://");
342
+ for (const s of b.samples)
343
+ if (s.source != null && !isSource(s.source))
344
+ throw new VireoError("source needs a ref and spans of {s, e} seconds, e > s");
345
+ for (const s of b.samples) {
346
+ if (s.name != null && s.name.trim().length > 60)
347
+ throw new VireoError("a name is 60 characters at most");
348
+ const ids = (s.parents ?? []).map((p) => parentOf(p).id);
349
+ if (ids.some((i) => !Number.isSafeInteger(i) || i <= 0))
350
+ throw new VireoError("parents are sample ids");
351
+ if (new Set(ids).size < ids.length)
352
+ throw new VireoError("a parent is named twice");
353
+ }
354
+ return this.write(b.agent ?? null, async (tx) => {
355
+ const subject = await this.subjectOf(ref, tx);
356
+ // lock the subject: two adds at once must not take the same number
357
+ await tx
358
+ .select({ id: subjects.id })
359
+ .from(subjects)
360
+ .where(eq(subjects.id, subject.id))
361
+ .for("update");
362
+ const [top] = await tx
363
+ .select({ n: sql `coalesce(max(${batches.n}), 0)::int` })
364
+ .from(batches)
365
+ .where(eq(batches.subjectId, subject.id));
366
+ const target = b.into == null ? null : await this.openBatch(tx, subject, b.into);
367
+ const wanted = [
368
+ ...new Set(b.samples.flatMap((s) => (s.parents ?? []).map((p) => parentOf(p).id))),
369
+ ];
370
+ if (wanted.length) {
371
+ const found = await tx
372
+ .select({ id: samples.id })
373
+ .from(samples)
374
+ .where(and(inArray(samples.id, wanted), eq(samples.subjectId, subject.id)));
375
+ const have = new Set(found.map((r) => r.id));
376
+ const gone = wanted.filter((i) => !have.has(i));
377
+ if (gone.length)
378
+ throw new VireoError(`not a sample of ${subject.slug}: ${gone.join(", ")}`);
379
+ }
380
+ const live = await this.steersIn(tx, subject.id);
381
+ const parentsOf = b.samples.map((s) => new Set((s.parents ?? []).map((p) => parentOf(p).id)));
382
+ // appending: the batch's own samples count toward a pin or a cross
383
+ if (target)
384
+ parentsOf.push(...(await this.parentSetsOf(tx, target.id)));
385
+ const pruned = await this.prunedIn(tx, subject.id, live);
386
+ for (const s of live) {
387
+ if (s.kind === "prune")
388
+ for (const ps of parentsOf)
389
+ for (const id of ps)
390
+ if (pruned.get(id) === s.id)
391
+ throw new VireoError(`sample ${id} is pruned (${steerName(s)}): grow from another, or lift the steer`, 409);
392
+ if (s.kind === "pin" && !parentsOf.some((ps) => ps.has(s.sampleId)))
393
+ throw new VireoError(`pinned: a sample must name ${s.sampleId} as a parent (${steerName(s)})`, 409);
394
+ if (s.kind === "cross" &&
395
+ !parentsOf.some((ps) => ps.has(s.sampleId) && ps.has(s.otherId)))
396
+ throw new VireoError(`cross asked: a sample must name both ${s.sampleId} and ${s.otherId} as parents (${steerName(s)})`, 409);
397
+ }
398
+ const batch = target
399
+ ? (await tx
400
+ .update(batches)
401
+ .set({ why: `${target.why}\n\nAdded: ${b.why.trim()}` })
402
+ .where(eq(batches.id, target.id))
403
+ .returning())[0]
404
+ : (await tx
405
+ .insert(batches)
406
+ .values({
407
+ subjectId: subject.id,
408
+ n: (top?.n ?? 0) + 1,
409
+ title,
410
+ why: b.why,
411
+ agent: b.agent ?? null,
412
+ })
413
+ .returning())[0];
414
+ // appended samples go after the batch's own, shuffled among themselves
415
+ const [last] = target
416
+ ? await tx
417
+ .select({ p: sql `coalesce(max(${samples.position}), -1)::int` })
418
+ .from(samples)
419
+ .where(eq(samples.batchId, target.id))
420
+ : [{ p: -1 }];
421
+ const from = (last?.p ?? -1) + 1;
422
+ const order = shuffled(b.samples.map((_, i) => i));
423
+ const rows = await tx
424
+ .insert(samples)
425
+ .values(b.samples.map((s, i) => ({
426
+ batchId: batch?.id,
427
+ subjectId: subject.id,
428
+ position: from + order.indexOf(i),
429
+ body: s.body ?? null,
430
+ media: s.media ?? null,
431
+ poster: s.poster ?? null,
432
+ source: s.source ?? null,
433
+ name: s.name?.trim() || null,
434
+ guides: s.guides ?? [],
435
+ change: s.change ?? null,
436
+ agent: b.agent ?? null,
437
+ })))
438
+ .returning({ id: samples.id });
439
+ // returning keeps insert order: rows[i] is b.samples[i]
440
+ const edges = b.samples.flatMap((s, i) => (s.parents ?? []).map((p, position) => ({
441
+ childId: rows[i]?.id,
442
+ parentId: parentOf(p).id,
443
+ position,
444
+ took: parentOf(p).took,
445
+ })));
446
+ if (edges.length)
447
+ await tx.insert(lineage).values(edges);
448
+ // a cross is one batch's ask: this batch met it
449
+ const met = live.filter((x) => x.kind === "cross").map((x) => x.id);
450
+ if (met.length)
451
+ await tx
452
+ .update(steers)
453
+ .set({ endedAt: new Date(), endedBy: batch?.id })
454
+ .where(inArray(steers.id, met));
455
+ return {
456
+ batch: refOf(subject.slug, batch?.n),
457
+ id: batch?.id,
458
+ n: batch?.n,
459
+ subject: subject.slug,
460
+ ...(target ? { appended: true } : {}),
461
+ samples: rows.map((r) => r.id),
462
+ };
463
+ });
464
+ }
465
+ /** Live steers of a subject, oldest first. */
466
+ steersIn(db, subjectId) {
467
+ return db
468
+ .select()
469
+ .from(steers)
470
+ .where(and(eq(steers.subjectId, subjectId), isNull(steers.endedAt)))
471
+ .orderBy(asc(steers.id));
472
+ }
473
+ /** Pruned sample id → the prune steer that covers it (the oldest, when two do). */
474
+ async prunedIn(db, subjectId, live) {
475
+ const prunes = live.filter((s) => s.kind === "prune");
476
+ const out = new Map();
477
+ if (!prunes.length)
478
+ return out;
479
+ const edges = await db
480
+ .select({ childId: lineage.childId, parentId: lineage.parentId })
481
+ .from(lineage)
482
+ .innerJoin(samples, eq(samples.id, lineage.childId))
483
+ .where(eq(samples.subjectId, subjectId));
484
+ for (const p of prunes)
485
+ for (const id of grownFrom([p.sampleId], edges))
486
+ if (!out.has(id))
487
+ out.set(id, p.id);
488
+ return out;
489
+ }
490
+ /** Set a steer (D10). The same live pin, prune or cross again returns the one there. */
491
+ steer(n, by) {
492
+ return this.write(by, async (tx) => {
493
+ let subjectId;
494
+ if (n.kind === "width")
495
+ subjectId = (await this.subjectOf(n.subject, tx)).id;
496
+ else {
497
+ const ids = n.kind === "cross" ? [n.sample, n.other] : [n.sample];
498
+ if (n.kind === "cross" && n.sample === n.other)
499
+ throw new VireoError("a cross needs two samples");
500
+ const rows = await tx
501
+ .select({ id: samples.id, subjectId: samples.subjectId })
502
+ .from(samples)
503
+ .where(inArray(samples.id, ids));
504
+ const gone = ids.filter((i) => !rows.some((r) => r.id === i));
505
+ if (gone.length)
506
+ throw new VireoError(`no sample ${gone.join(", ")}`, 404);
507
+ if (new Set(rows.map((r) => r.subjectId)).size > 1)
508
+ throw new VireoError("a cross is within one subject");
509
+ subjectId = rows[0]?.subjectId;
510
+ }
511
+ await tx
512
+ .select({ id: subjects.id })
513
+ .from(subjects)
514
+ .where(eq(subjects.id, subjectId))
515
+ .for("update");
516
+ const live = await this.steersIn(tx, subjectId);
517
+ const why = n.why?.trim() || null;
518
+ if (n.kind === "width") {
519
+ const old = live.filter((s) => s.kind === "width").map((s) => s.id);
520
+ if (old.length)
521
+ await tx.update(steers).set({ endedAt: new Date() }).where(inArray(steers.id, old));
522
+ const [row] = await tx
523
+ .insert(steers)
524
+ .values({ subjectId, kind: "width", width: n.width, why, by })
525
+ .returning();
526
+ return row;
527
+ }
528
+ const same = live.find((s) => s.kind === n.kind &&
529
+ (n.kind === "cross"
530
+ ? new Set([s.sampleId, s.otherId, n.sample, n.other]).size === 2
531
+ : s.sampleId === n.sample));
532
+ if (same)
533
+ return same;
534
+ const pruned = await this.prunedIn(tx, subjectId, live);
535
+ const hit = (n.kind === "cross" ? [n.sample, n.other] : [n.sample]).find((i) => pruned.has(i));
536
+ if (n.kind !== "prune" && hit != null)
537
+ throw new VireoError(`sample ${hit} is pruned (steer ${pruned.get(hit)}): lift it first`, 409);
538
+ if (n.kind === "prune") {
539
+ const edges = await tx
540
+ .select({ childId: lineage.childId, parentId: lineage.parentId })
541
+ .from(lineage)
542
+ .innerJoin(samples, eq(samples.id, lineage.childId))
543
+ .where(eq(samples.subjectId, subjectId));
544
+ const cut = grownFrom([n.sample], edges);
545
+ const pin = live.find((s) => (s.kind === "pin" && cut.has(s.sampleId)) ||
546
+ (s.kind === "cross" && (cut.has(s.sampleId) || cut.has(s.otherId))));
547
+ if (pin)
548
+ throw new VireoError(`this prune cuts a live ${steerName(pin)}: lift that first`, 409);
549
+ }
550
+ const [row] = await tx
551
+ .insert(steers)
552
+ .values({
553
+ subjectId,
554
+ kind: n.kind,
555
+ sampleId: n.sample,
556
+ otherId: n.kind === "cross" ? n.other : null,
557
+ why,
558
+ by,
559
+ })
560
+ .returning();
561
+ return row;
562
+ });
563
+ }
564
+ /** Lift a live steer. */
565
+ unsteer(id, by) {
566
+ return this.write(by, async (tx) => {
567
+ const [row] = await tx
568
+ .update(steers)
569
+ .set({ endedAt: new Date() })
570
+ .where(and(eq(steers.id, id), isNull(steers.endedAt)))
571
+ .returning();
572
+ if (!row)
573
+ throw new VireoError(`no live steer ${id}`, 404);
574
+ return row;
575
+ });
576
+ }
577
+ /** A subject's live steers, and every sample a prune covers. */
578
+ async steersOf(ref) {
579
+ const s = await this.subjectOf(ref);
580
+ const live = await this.steersIn(this.db, s.id);
581
+ const pruned = await this.prunedIn(this.db, s.id, live);
582
+ return { steers: live, pruned: [...pruned.keys()].sort((a, b) => a - b) };
583
+ }
584
+ /**
585
+ * Batches that wait on the person, oldest first, with samples and notes: what they have to pick.
586
+ * `viewer`: a person sees only their own calls and notes (D11).
587
+ */
588
+ async queue(ref, viewer = null) {
589
+ // a subject, or one batch as `<subject>:<n>`
590
+ const one = typeof ref === "string" && /:\d+$/.test(ref) ? await this.batchOf(ref) : null;
591
+ const subjectId = ref == null || one ? null : (await this.subjectOf(ref)).id;
592
+ const open = await this.db
593
+ .select({ batch: batches, subject: subjects })
594
+ .from(batches)
595
+ .innerJoin(subjects, eq(subjects.id, batches.subjectId))
596
+ .where(and(WAITS, subjectId ? eq(batches.subjectId, subjectId) : undefined, one ? eq(batches.id, one) : undefined))
597
+ .orderBy(asc(batches.createdAt));
598
+ if (!open.length)
599
+ return [];
600
+ const rows = await this.db
601
+ .select()
602
+ .from(samples)
603
+ .where(inArray(samples.batchId, open.map((o) => o.batch.id)))
604
+ .orderBy(asc(samples.position));
605
+ const ids = rows.map((r) => r.id);
606
+ const mine = (x) => viewer == null || x.by === viewer;
607
+ const ns = (await this.notesOf(ids)).filter(mine);
608
+ const cs = (await this.callsOf(ids)).filter(mine);
609
+ return open.map((o) => ({
610
+ batch: { ref: refOf(o.subject.slug, o.batch.n), ...o.batch },
611
+ subject: o.subject,
612
+ samples: rows
613
+ .filter((r) => r.batchId === o.batch.id)
614
+ .map((r) => {
615
+ const own = cs.filter((c) => c.sampleId === r.id);
616
+ return { ...r, ...pooled(own), calls: own, notes: ns.filter((n) => n.sampleId === r.id) };
617
+ }),
618
+ }));
619
+ }
620
+ async callsOf(sampleIds) {
621
+ if (!sampleIds.length)
622
+ return [];
623
+ return this.db
624
+ .select()
625
+ .from(calls)
626
+ .where(inArray(calls.sampleId, sampleIds))
627
+ .orderBy(asc(calls.at));
628
+ }
629
+ async notesOf(sampleIds) {
630
+ if (!sampleIds.length)
631
+ return [];
632
+ return this.db
633
+ .select()
634
+ .from(notes)
635
+ .where(inArray(notes.sampleId, sampleIds))
636
+ .orderBy(asc(notes.createdAt));
637
+ }
638
+ /** Parent edges of these children, main parent first. */
639
+ async lineageOf(childIds) {
640
+ if (!childIds.length)
641
+ return [];
642
+ return this.db
643
+ .select()
644
+ .from(lineage)
645
+ .where(inArray(lineage.childId, childIds))
646
+ .orderBy(asc(lineage.childId), asc(lineage.position));
647
+ }
648
+ /**
649
+ * `by`'s call: a 1-10 score, a verdict (its tap score) or null to clear. The verdict follows.
650
+ * One call per person per sample (D11).
651
+ */
652
+ async judge(sampleId, call, by) {
653
+ if (!by)
654
+ throw new VireoError("a call needs who made it", 400);
655
+ const score = typeof call === "string" ? TAP[call] : call;
656
+ if (score != null && !(Number.isInteger(score) && score >= 1 && score <= 10))
657
+ throw new VireoError(`score ${score}: 1-10, or ${VERDICTS.join("|")}`, 400);
658
+ return this.write(by, async (tx) => {
659
+ await this.markable(tx, sampleId);
660
+ const mine = and(eq(calls.sampleId, sampleId), eq(calls.by, by));
661
+ if (score == null) {
662
+ await tx.delete(calls).where(mine);
663
+ return { id: sampleId, by, score: null, verdict: null };
664
+ }
665
+ const verdict = verdictOf(score);
666
+ await tx
667
+ .insert(calls)
668
+ .values({ sampleId, by, score, verdict })
669
+ .onConflictDoUpdate({
670
+ target: [calls.sampleId, calls.by],
671
+ set: { score, verdict, at: sql `now()` },
672
+ });
673
+ return { id: sampleId, by, score, verdict };
674
+ });
675
+ }
676
+ async addNote(sampleId, n, by) {
677
+ if (!n.tone && !n.text?.trim())
678
+ throw new VireoError("a note needs a tone or words");
679
+ return this.write(by, async (tx) => {
680
+ await this.markable(tx, sampleId);
681
+ const [row] = await tx
682
+ .insert(notes)
683
+ .values({
684
+ sampleId,
685
+ anchor: n.anchor ?? null,
686
+ tone: n.tone ?? null,
687
+ text: n.text?.trim() || null,
688
+ by,
689
+ })
690
+ .returning();
691
+ return row;
692
+ });
693
+ }
694
+ dropNote(noteId, by) {
695
+ return this.write(by, async (tx) => {
696
+ const [note] = await tx
697
+ .select({ sampleId: notes.sampleId })
698
+ .from(notes)
699
+ .where(eq(notes.id, noteId));
700
+ if (note)
701
+ await this.markable(tx, note.sampleId);
702
+ const rows = await tx.delete(notes).where(eq(notes.id, noteId)).returning({ id: notes.id });
703
+ return { done: rows.map((r) => r.id) };
704
+ });
705
+ }
706
+ /** Close a batch: the person's note goes to the agent with the marks. */
707
+ closeBatch(ref, note, by) {
708
+ return this.write(by, async (tx) => {
709
+ const batchId = await this.batchOf(ref, tx);
710
+ const [row] = await tx
711
+ .update(batches)
712
+ .set({ state: "closed", note: note?.trim() || null, closedAt: new Date() })
713
+ .where(and(eq(batches.id, batchId), eq(batches.state, "open")))
714
+ .returning({ id: batches.id, n: batches.n, subjectId: batches.subjectId });
715
+ if (!row) {
716
+ const [b] = await tx
717
+ .select({ id: batches.id })
718
+ .from(batches)
719
+ .where(eq(batches.id, batchId));
720
+ throw b
721
+ ? new VireoError(`batch ${ref} is closed`, 409)
722
+ : new VireoError(`no batch ${ref}`, 404);
723
+ }
724
+ const s = await this.subjectOf(row.subjectId, tx);
725
+ return { batch: refOf(s.slug, row.n), ...row };
726
+ });
727
+ }
728
+ keep(sampleId, on, by) {
729
+ return this.write(by, async (tx) => {
730
+ const [row] = await tx
731
+ .update(samples)
732
+ .set({ keptAt: on ? new Date() : null })
733
+ .where(eq(samples.id, sampleId))
734
+ .returning({ id: samples.id, keptAt: samples.keptAt });
735
+ if (!row)
736
+ throw new VireoError(`no sample ${sampleId}`, 404);
737
+ return row;
738
+ });
739
+ }
740
+ /** A subject's shown name; the slug stays its ref. */
741
+ async setContentType(ref, type, by) {
742
+ const to = type.trim();
743
+ if (!to)
744
+ throw new VireoError("a content type, not blank");
745
+ return this.write(by, async (tx) => {
746
+ const s = await this.subjectOf(ref, tx);
747
+ const [row] = await tx
748
+ .update(subjects)
749
+ .set({ contentType: to })
750
+ .where(eq(subjects.id, s.id))
751
+ .returning({ id: subjects.id, slug: subjects.slug, contentType: subjects.contentType });
752
+ return row;
753
+ });
754
+ }
755
+ async renameSubject(ref, name, by) {
756
+ const to = name.trim();
757
+ if (!to)
758
+ throw new VireoError("a name, not blank");
759
+ return this.write(by, async (tx) => {
760
+ const s = await this.subjectOf(ref, tx);
761
+ const [row] = await tx
762
+ .update(subjects)
763
+ .set({ name: to })
764
+ .where(eq(subjects.id, s.id))
765
+ .returning({ id: subjects.id, slug: subjects.slug, name: subjects.name });
766
+ return row;
767
+ });
768
+ }
769
+ /** A batch's title (id or `<subject>:<n>`); blank refused. */
770
+ async renameBatch(ref, title, by) {
771
+ const to = title.trim();
772
+ if (!to)
773
+ throw new VireoError("a title, not blank");
774
+ if (to.length > 120)
775
+ throw new VireoError("a title is 120 characters at most");
776
+ return this.write(by, async (tx) => {
777
+ const id = await this.batchOf(ref, tx);
778
+ const [row] = await tx
779
+ .update(batches)
780
+ .set({ title: to })
781
+ .where(eq(batches.id, id))
782
+ .returning({ id: batches.id, n: batches.n, title: batches.title });
783
+ if (!row)
784
+ throw new VireoError(`no batch ${ref}`, 404);
785
+ return row;
786
+ });
787
+ }
788
+ /** Live-page samples (`https://` media) with no poster, oldest first; one subject or all. */
789
+ async posterless(ref) {
790
+ const s = ref == null ? null : await this.subjectOf(ref);
791
+ return this.db
792
+ .select({ id: samples.id, media: samples.media })
793
+ .from(samples)
794
+ .innerJoin(batches, eq(batches.id, samples.batchId))
795
+ .where(and(isNull(samples.poster), like(samples.media, "https://%"), ...(s ? [eq(batches.subjectId, s.id)] : [])))
796
+ .orderBy(asc(samples.id));
797
+ }
798
+ /** A sample's poster (`s3://…` or `https://…`): the thumb a batch row shows. */
799
+ async setPoster(sampleId, poster, by) {
800
+ return this.write(by, async (tx) => {
801
+ const [row] = await tx
802
+ .update(samples)
803
+ .set({ poster })
804
+ .where(eq(samples.id, sampleId))
805
+ .returning({ id: samples.id, poster: samples.poster });
806
+ if (!row)
807
+ throw new VireoError(`no sample ${sampleId}`, 404);
808
+ return row;
809
+ });
810
+ }
811
+ /**
812
+ * Fix samples in place, all or nothing: the agent's words (`name`, `change`, `guides`) any time;
813
+ * what the person sees (`body`, `media`, `poster`, `source`) only before anyone judged or noted
814
+ * it, since a call or a note points at what was seen. Blank `name` or `change` clears it.
815
+ */
816
+ async editSamples(edits, by) {
817
+ if (!edits.length)
818
+ throw new VireoError("no edit");
819
+ for (const e of edits) {
820
+ const n = e.name?.trim();
821
+ if (n && n.length > 60)
822
+ throw new VireoError(`sample ${e.id}: a name is 60 characters at most`);
823
+ if (e.source != null && !isSource(e.source))
824
+ throw new VireoError(`sample ${e.id}: source is {ref, spans: [[from, to], ...]}`);
825
+ if (!SAMPLE_FIELDS.some((k) => e[k] !== undefined))
826
+ throw new VireoError(`sample ${e.id}: nothing to change`);
827
+ }
828
+ return this.write(by, async (tx) => {
829
+ const out = [];
830
+ for (const e of edits) {
831
+ const [was] = await tx.select().from(samples).where(eq(samples.id, e.id));
832
+ if (!was)
833
+ throw new VireoError(`no sample ${e.id}`, 404);
834
+ if (SEEN_FIELDS.some((k) => e[k] !== undefined)) {
835
+ const [c] = await tx
836
+ .select({ n: sql `count(*)::int` })
837
+ .from(calls)
838
+ .where(eq(calls.sampleId, e.id));
839
+ const [m] = await tx
840
+ .select({ n: sql `count(*)::int` })
841
+ .from(notes)
842
+ .where(eq(notes.sampleId, e.id));
843
+ if ((c?.n ?? 0) + (m?.n ?? 0) > 0)
844
+ throw new VireoError(`sample ${e.id} has calls or notes on what was seen: add a new sample in the next batch instead`, 409);
845
+ }
846
+ const set = {};
847
+ if (e.name !== undefined)
848
+ set.name = e.name?.trim() || null;
849
+ if (e.change !== undefined)
850
+ set.change = e.change?.trim() || null;
851
+ if (e.guides !== undefined)
852
+ set.guides = e.guides ?? [];
853
+ if (e.body !== undefined)
854
+ set.body = e.body;
855
+ if (e.media !== undefined)
856
+ set.media = e.media;
857
+ if (e.poster !== undefined)
858
+ set.poster = e.poster;
859
+ if (e.source !== undefined)
860
+ set.source = e.source;
861
+ const [row] = await tx.update(samples).set(set).where(eq(samples.id, e.id)).returning();
862
+ out.push(row);
863
+ }
864
+ return out;
865
+ });
866
+ }
867
+ async addGuide(g) {
868
+ if (!g.text.trim())
869
+ throw new VireoError("say the tip");
870
+ return this.write(g.by ?? null, async (tx) => {
871
+ const subjectId = g.subject == null ? null : (await this.subjectOf(g.subject, tx)).id;
872
+ const [row] = await tx
873
+ .insert(guides)
874
+ .values({
875
+ text: g.text.trim(),
876
+ source: g.source ?? "person",
877
+ ref: g.ref ?? null,
878
+ subjectId,
879
+ kind: g.kind ?? null,
880
+ by: g.by ?? null,
881
+ })
882
+ .returning();
883
+ return row;
884
+ });
885
+ }
886
+ setGuide(id, state, by) {
887
+ return this.write(by, async (tx) => {
888
+ const [row] = await tx
889
+ .update(guides)
890
+ .set({ state, decidedAt: state === "testing" ? null : new Date() })
891
+ .where(eq(guides.id, id))
892
+ .returning();
893
+ if (!row)
894
+ throw new VireoError(`no guide ${id}`, 404);
895
+ return row;
896
+ });
897
+ }
898
+ /** Guides that reach a subject: its own, its kind's, and everyone's. */
899
+ guidesFor(s) {
900
+ return this.db
901
+ .select()
902
+ .from(guides)
903
+ .where(or(eq(guides.subjectId, s.id), and(isNull(guides.subjectId), eq(guides.kind, s.kind)), and(isNull(guides.subjectId), isNull(guides.kind))))
904
+ .orderBy(asc(guides.createdAt));
905
+ }
906
+ /** Everything about a subject: for the agent's next batch and a page's subject view. */
907
+ async feedback(ref) {
908
+ const s = await this.subjectOf(ref);
909
+ const bs = await this.db
910
+ .select()
911
+ .from(batches)
912
+ .where(eq(batches.subjectId, s.id))
913
+ .orderBy(asc(batches.createdAt));
914
+ const ss = await this.db
915
+ .select()
916
+ .from(samples)
917
+ .where(eq(samples.subjectId, s.id))
918
+ .orderBy(asc(samples.batchId), asc(samples.position));
919
+ const ns = await this.notesOf(ss.map((r) => r.id));
920
+ const es = await this.lineageOf(ss.map((r) => r.id));
921
+ const cs = await this.callsOf(ss.map((r) => r.id));
922
+ const judgedBatches = new Set(bs.filter((b) => b.state === "closed").map((b) => b.id));
923
+ const judged = ss.filter((r) => judgedBatches.has(r.batchId));
924
+ const strength = new Map(strengths(ss, cs).map((x) => [Number(x.id), x]));
925
+ const gs = guideStats(await this.guidesFor(s), judged, cs);
926
+ return {
927
+ subject: s,
928
+ guides: gs,
929
+ batches: bs.map((b) => {
930
+ const mine = ss.filter((r) => r.batchId === b.id);
931
+ return {
932
+ ref: refOf(s.slug, b.n),
933
+ ...b,
934
+ goodRate: goodRateOf(sheets(mine, cs)),
935
+ judges: [
936
+ ...new Set(cs.filter((c) => mine.some((r) => r.id === c.sampleId)).map((c) => c.by)),
937
+ ],
938
+ samples: mine.map((r) => ({
939
+ ...r,
940
+ ...pooled(cs.filter((c) => c.sampleId === r.id)),
941
+ calls: cs.filter((c) => c.sampleId === r.id),
942
+ strength: strength.get(r.id) ?? null,
943
+ notes: ns.filter((n) => n.sampleId === r.id),
944
+ parents: es
945
+ .filter((e) => e.childId === r.id)
946
+ .map((e) => ({ id: e.parentId, took: e.took })),
947
+ })),
948
+ };
949
+ }),
950
+ leaders: [...strength.values()]
951
+ .slice(0, 5)
952
+ .map((x) => ({ sample: Number(x.id), strength: x.strength, se: x.se })),
953
+ live: await live(this.db, this.collectors, s.id),
954
+ ...(await this.steersOf(s.id)),
955
+ /** the subject's board: what people and agents pinned for it (the brief's references) */
956
+ board: await pinboard.boardOf(this.db, s.id),
957
+ };
958
+ }
959
+ /** A subject's board: every pin, with its board position. */
960
+ async board(ref) {
961
+ const s = await this.subjectOf(ref);
962
+ return {
963
+ subject: { id: s.id, slug: s.slug, name: s.name },
964
+ pins: await pinboard.boardOf(this.db, s.id),
965
+ };
966
+ }
967
+ /** Pins on a subject's board, in one write. */
968
+ async pin(ref, list, by) {
969
+ return this.write(by, async (tx) => {
970
+ const s = await this.subjectOf(ref, tx);
971
+ return pinboard.addPins(tx, s.id, list, by);
972
+ });
973
+ }
974
+ async movePins(moves, by) {
975
+ return this.write(by, (tx) => pinboard.movePins(tx, moves));
976
+ }
977
+ async editPin(e, by) {
978
+ return this.write(by, (tx) => pinboard.editPin(tx, e));
979
+ }
980
+ async unpin(ids, by) {
981
+ return this.write(by, (tx) => pinboard.unpin(tx, ids));
982
+ }
983
+ /** A person keeps a pin; the host sends it to Canon and stores what it made (`setPinCanon`). */
984
+ async keepPin(id, on, by) {
985
+ return this.write(by, (tx) => pinboard.keepPin(tx, id, on, by));
986
+ }
987
+ async setPinCanon(id, canon, by) {
988
+ return this.write(by, (tx) => pinboard.setPinCanon(tx, id, canon));
989
+ }
990
+ /** A sample goes live on a channel's target; `collect` reads its numbers from then on. */
991
+ async ship(sampleId, o, by) {
992
+ if (!o.target.trim())
993
+ throw new VireoError("a ship needs the channel's target id");
994
+ if (!this.collectors.some((c) => c.channel === o.channel))
995
+ throw new VireoError(`no collector for ${o.channel}: one of ${this.collectors.map((c) => c.channel).join(", ") || "(none)"}`);
996
+ return this.write(by, async (tx) => {
997
+ const [sample] = await tx
998
+ .select({ id: samples.id })
999
+ .from(samples)
1000
+ .where(eq(samples.id, sampleId));
1001
+ if (!sample)
1002
+ throw new VireoError(`no sample ${sampleId}`, 404);
1003
+ const target = o.target.trim();
1004
+ const [row] = await tx
1005
+ .insert(ships)
1006
+ .values({ sampleId, channel: o.channel, target, why: o.why ?? null, by })
1007
+ .onConflictDoNothing({ target: [ships.channel, ships.target, ships.sampleId] })
1008
+ .returning();
1009
+ if (row)
1010
+ return row;
1011
+ // the same ship again: live is a no-op; an ended one stays ended (its numbers are frozen)
1012
+ const [had] = await tx
1013
+ .select()
1014
+ .from(ships)
1015
+ .where(and(eq(ships.sampleId, sampleId), eq(ships.channel, o.channel), eq(ships.target, target)));
1016
+ if (!had)
1017
+ throw new Error("ship not written");
1018
+ if (had.endedAt)
1019
+ throw new VireoError(`ship ${had.id} ended: its numbers are frozen; ship to a new target`, 409);
1020
+ return had;
1021
+ });
1022
+ }
1023
+ /** Ends a ship: its numbers stay, frozen at the next collect. */
1024
+ unship(shipId, by) {
1025
+ return this.write(by, async (tx) => {
1026
+ const [row] = await tx
1027
+ .update(ships)
1028
+ .set({ endedAt: sql `now()` })
1029
+ .where(and(eq(ships.id, shipId), isNull(ships.endedAt)))
1030
+ .returning();
1031
+ if (!row)
1032
+ throw new VireoError(`no live ship ${shipId}`, 404);
1033
+ return row;
1034
+ });
1035
+ }
1036
+ /** A subject's ships, newest first. */
1037
+ async shipsOf(ref) {
1038
+ const s = await this.subjectOf(ref);
1039
+ const rows = await this.db
1040
+ .select({ ship: ships })
1041
+ .from(ships)
1042
+ .innerJoin(samples, eq(samples.id, ships.sampleId))
1043
+ .where(eq(samples.subjectId, s.id))
1044
+ .orderBy(desc(ships.startedAt));
1045
+ return rows.map((x) => x.ship);
1046
+ }
1047
+ /** Read every live ship's numbers now (or one ship's). */
1048
+ async collect(o = {}) {
1049
+ const out = await collect(this.db, this.collectors, o);
1050
+ await this.told();
1051
+ return out;
1052
+ }
1053
+ /** Kept samples, newest first, with their subject. */
1054
+ /**
1055
+ * Batches as a page: filters, a sort and an offset (D11). `viewer` = the person reading: an open
1056
+ * batch shows only their own marks, and none of the agent's words.
1057
+ */
1058
+ async batches(q = {}, viewer = null) {
1059
+ const limit = Math.min(Math.max(q.limit ?? 30, 1), 100);
1060
+ const after = Math.max(q.after ?? 0, 0);
1061
+ const subjectId = q.subject == null ? null : (await this.subjectOf(q.subject)).id;
1062
+ const good = sql `${calls.verdict} in ('good', 'amazing')`;
1063
+ const n = sql `count(distinct ${samples.id})::int`;
1064
+ const judges = sql `count(distinct ${calls.by})::int`;
1065
+ // an open batch has no rate: partial, and a sort on it would show others' marks
1066
+ const rate = sql `case when ${batches.state} = 'closed' then (count(${calls.id}) filter (where ${good}))::float / nullif((${judges}) * (${n}), 0) end`;
1067
+ const waits = sql `(${WAITS})`;
1068
+ const tally = (v) => sql `(count(${calls.id}) filter (where ${calls.verdict} = ${v}))::int`;
1069
+ const where = and(q.subjects
1070
+ ? inArray(batches.subjectId, q.subjects.length ? [...q.subjects] : [-1])
1071
+ : undefined, subjectId ? eq(batches.subjectId, subjectId) : undefined, q.kind ? eq(subjects.kind, q.kind) : undefined, q.state === "waits" ? WAITS : q.state ? eq(batches.state, q.state) : undefined, q.who
1072
+ ? sql `exists (select 1 from vireo.calls c join vireo.samples x on x.id = c.sample_id where x.batch_id = ${batches.id} and c.by = ${q.who})`
1073
+ : undefined);
1074
+ const order = {
1075
+ newest: [desc(batches.createdAt), desc(batches.id)],
1076
+ oldest: [asc(batches.createdAt), asc(batches.id)],
1077
+ waiting: [desc(waits), desc(batches.createdAt), desc(batches.id)],
1078
+ subject: [asc(subjects.name), desc(batches.n)],
1079
+ good: [sql `${rate} desc nulls last`, desc(batches.createdAt), desc(batches.id)],
1080
+ }[q.sort ?? "waiting"];
1081
+ const got = await this.db
1082
+ .select({
1083
+ batch: batches,
1084
+ subject: subjects,
1085
+ samples: n,
1086
+ kept: sql `(count(distinct ${samples.id}) filter (where ${samples.keptAt} is not null))::int`,
1087
+ judges,
1088
+ mine: viewer
1089
+ ? sql `(count(${calls.id}) filter (where ${calls.by} = ${viewer}))::int`
1090
+ : sql `0`,
1091
+ rate,
1092
+ waits,
1093
+ amazing: tally("amazing"),
1094
+ good: tally("good"),
1095
+ okay: tally("okay"),
1096
+ bad: tally("bad"),
1097
+ })
1098
+ .from(batches)
1099
+ .innerJoin(subjects, eq(subjects.id, batches.subjectId))
1100
+ .leftJoin(samples, eq(samples.batchId, batches.id))
1101
+ .leftJoin(calls, eq(calls.sampleId, samples.id))
1102
+ .where(where)
1103
+ .groupBy(batches.id, subjects.id)
1104
+ .orderBy(...order)
1105
+ .limit(limit + 1)
1106
+ .offset(after);
1107
+ const page = got.slice(0, limit);
1108
+ const [count] = await this.db
1109
+ .select({ waiting: sql `(count(*) filter (where ${WAITS}))::int` })
1110
+ .from(batches)
1111
+ .innerJoin(subjects, eq(subjects.id, batches.subjectId))
1112
+ .where(where);
1113
+ // thumbs: each batch's posters in made order, with the calls a reader may see
1114
+ const thumbs = page.length
1115
+ ? await this.db
1116
+ .select({ id: samples.id, batchId: samples.batchId, poster: samples.poster })
1117
+ .from(samples)
1118
+ .where(and(inArray(samples.batchId, page.map((r) => r.batch.id)), isNotNull(samples.poster)))
1119
+ .orderBy(asc(samples.id))
1120
+ : [];
1121
+ const cs = await this.callsOf(thumbs.map((t) => t.id));
1122
+ return {
1123
+ rows: page.map((r) => {
1124
+ const blind = blindFor(viewer, r.batch.state === "open");
1125
+ const tallied = r.judges * r.samples;
1126
+ return {
1127
+ ref: refOf(r.subject.slug, r.batch.n),
1128
+ id: r.batch.id,
1129
+ n: r.batch.n,
1130
+ title: r.batch.title,
1131
+ state: r.batch.state,
1132
+ note: r.batch.note,
1133
+ why: blind ? null : r.batch.why,
1134
+ createdAt: r.batch.createdAt,
1135
+ subject: r.subject,
1136
+ waits: r.waits,
1137
+ samples: r.samples,
1138
+ kept: r.kept,
1139
+ // while open a person sees only their own count
1140
+ marked: blind ? r.mine : r.amazing + r.good + r.okay + r.bad,
1141
+ judges: blind ? null : r.judges,
1142
+ goodRate: blind ? null : r.rate,
1143
+ tally: blind
1144
+ ? null
1145
+ : {
1146
+ amazing: r.amazing,
1147
+ good: r.good,
1148
+ okay: r.okay,
1149
+ bad: r.bad,
1150
+ unmarked: tallied ? tallied - (r.amazing + r.good + r.okay + r.bad) : r.samples,
1151
+ },
1152
+ thumbs: thumbs
1153
+ .filter((t) => t.batchId === r.batch.id)
1154
+ .map((t) => ({
1155
+ id: t.id,
1156
+ poster: t.poster,
1157
+ verdict: blind ? null : pooled(cs.filter((c) => c.sampleId === t.id)).verdict,
1158
+ })),
1159
+ };
1160
+ }),
1161
+ next: got.length > limit ? after + limit : null,
1162
+ waiting: count?.waiting ?? 0,
1163
+ };
1164
+ }
1165
+ /** One batch whole, for `viewer` (see `batches`); `newer` = the subject's newer open batch. */
1166
+ async batch(ref, viewer = null) {
1167
+ const id = await this.batchOf(ref);
1168
+ const [o] = await this.db
1169
+ .select({ batch: batches, subject: subjects })
1170
+ .from(batches)
1171
+ .innerJoin(subjects, eq(subjects.id, batches.subjectId))
1172
+ .where(eq(batches.id, id));
1173
+ if (!o)
1174
+ throw new VireoError(`no batch ${ref}`, 404);
1175
+ const blind = blindFor(viewer, o.batch.state === "open");
1176
+ const rows = await this.db
1177
+ .select()
1178
+ .from(samples)
1179
+ .where(eq(samples.batchId, id))
1180
+ .orderBy(asc(samples.id));
1181
+ const ids = rows.map((r) => r.id);
1182
+ const seen = (x) => !blind || x.by === viewer;
1183
+ const ns = (await this.notesOf(ids)).filter(seen);
1184
+ const cs = (await this.callsOf(ids)).filter(seen);
1185
+ const es = blind ? [] : await this.lineageOf(ids);
1186
+ const [newer] = await this.db
1187
+ .select({ n: batches.n })
1188
+ .from(batches)
1189
+ .where(and(eq(batches.subjectId, o.batch.subjectId), eq(batches.state, "open"), sql `${batches.n} > ${o.batch.n}`))
1190
+ .orderBy(desc(batches.n))
1191
+ .limit(1);
1192
+ return {
1193
+ ref: refOf(o.subject.slug, o.batch.n),
1194
+ ...o.batch,
1195
+ why: blind ? null : o.batch.why,
1196
+ subject: o.subject,
1197
+ goodRate: blind ? null : goodRateOf(sheets(rows, cs)),
1198
+ judges: blind ? null : [...new Set(cs.map((c) => c.by))],
1199
+ newer: newer ? { n: newer.n, ref: refOf(o.subject.slug, newer.n) } : null,
1200
+ samples: rows.map((r) => ({
1201
+ ...r,
1202
+ // the name says what it tries and shows while blind; the change (vs its parent) does not
1203
+ change: blind ? null : r.change,
1204
+ ...pooled(cs.filter((c) => c.sampleId === r.id)),
1205
+ calls: cs.filter((c) => c.sampleId === r.id),
1206
+ notes: ns.filter((x) => x.sampleId === r.id),
1207
+ parents: es
1208
+ .filter((e) => e.childId === r.id)
1209
+ .map((e) => ({ id: e.parentId, took: e.took })),
1210
+ })),
1211
+ };
1212
+ }
1213
+ async catalog(opts = {}) {
1214
+ const subjectId = opts.subject == null ? null : (await this.subjectOf(opts.subject)).id;
1215
+ return this.db
1216
+ .select({
1217
+ sample: samples,
1218
+ subject: { slug: subjects.slug, name: subjects.name, kind: subjects.kind },
1219
+ })
1220
+ .from(samples)
1221
+ .innerJoin(subjects, eq(subjects.id, samples.subjectId))
1222
+ .where(and(isNotNull(samples.keptAt), opts.kind ? eq(subjects.kind, opts.kind) : undefined, subjectId ? eq(samples.subjectId, subjectId) : undefined))
1223
+ .orderBy(desc(samples.keptAt));
1224
+ }
1225
+ }
1226
+ //# sourceMappingURL=store.js.map