@kinloom/worker 0.1.0 → 0.2.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.
@@ -1,4 +1,70 @@
1
- import { AgentTokenScopeSchema, asRevisionId, asSha256Hex, AuthorTypeSchema, computeEntityDiff, EntityTypeSchema, parseEntityPayload, resolveEffectiveLiving, RevisionActionSchema, UserRoleSchema, } from '@kinloom/core';
1
+ import { AgentTokenScopeSchema, asRevisionId, asSha256Hex, AuthorTypeSchema, computeEntityDiff, entityLookupCompositeKey, EntityTypeSchema, parseEntityPayload, resolveEffectiveLiving, RevisionActionSchema, UserRoleSchema, } from '@kinloom/core';
2
+ // Set-based statements pass rows as one JSON array bind, read with json_each().
3
+ // D1 caps a single bound value at 2 MB, so keep each JSON chunk well under it.
4
+ const D1_JSON_PARAM_MAX_BYTES = 900_000;
5
+ const utf8 = new TextEncoder();
6
+ function chunkJsonArrayWithRanges(items) {
7
+ const chunks = [];
8
+ let current = [];
9
+ let currentMaxBytes = 2;
10
+ let currentExactBytes = 2;
11
+ let exactStale = false;
12
+ let chunkStart = 0;
13
+ for (let i = 0; i < items.length; i += 1) {
14
+ const encoded = JSON.stringify(items[i]);
15
+ const itemMaxBytes = encoded.length * 3 + 1;
16
+ if (current.length > 0 && currentMaxBytes + itemMaxBytes > D1_JSON_PARAM_MAX_BYTES) {
17
+ if (exactStale) {
18
+ currentExactBytes = utf8.encode(current.join(',')).length + 2;
19
+ exactStale = false;
20
+ }
21
+ const itemExactBytes = utf8.encode(encoded).length + 1;
22
+ if (currentExactBytes + itemExactBytes > D1_JSON_PARAM_MAX_BYTES) {
23
+ chunks.push({ json: `[${current.join(',')}]`, start: chunkStart, count: current.length });
24
+ current = [encoded];
25
+ currentMaxBytes = 2 + itemMaxBytes;
26
+ currentExactBytes = 2 + itemExactBytes;
27
+ exactStale = false;
28
+ chunkStart = i;
29
+ continue;
30
+ }
31
+ current.push(encoded);
32
+ currentMaxBytes += itemMaxBytes;
33
+ currentExactBytes += itemExactBytes;
34
+ continue;
35
+ }
36
+ current.push(encoded);
37
+ currentMaxBytes += itemMaxBytes;
38
+ exactStale = true;
39
+ }
40
+ if (current.length > 0) {
41
+ chunks.push({ json: `[${current.join(',')}]`, start: chunkStart, count: current.length });
42
+ }
43
+ return chunks;
44
+ }
45
+ function chunkJsonArray(items) {
46
+ return chunkJsonArrayWithRanges(items).map((c) => c.json);
47
+ }
48
+ function buildCommittedRevisionRecord(params) {
49
+ const { revisionId, parentRevisionId, op, batchId, author, nowIso } = params;
50
+ return {
51
+ revision_id: asRevisionId(revisionId),
52
+ batch_id: batchId,
53
+ entity_type: op.entity_type,
54
+ entity_id: op.entity_id,
55
+ parent_revision_id: parentRevisionId !== null ? asRevisionId(parentRevisionId) : null,
56
+ action: op.action,
57
+ reverted_revision_id: op.reverted_revision_id ?? null,
58
+ author_id: author.author_id,
59
+ author_name: author.author_name,
60
+ author_type: author.author_type,
61
+ summary: op.summary,
62
+ has_primary_source: op.has_primary_source,
63
+ before_json: op.before_json,
64
+ after_json: op.after_json,
65
+ created_at: nowIso,
66
+ };
67
+ }
2
68
  function parseJsonObject(raw) {
3
69
  const parsed = JSON.parse(raw);
4
70
  if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
@@ -143,6 +209,8 @@ function resolveSlugForOp(op) {
143
209
  * Cloudflare D1 implementation of ArchiveRepository.
144
210
  * Enforces zero-N+1 snapshot loading and mathematically atomic DB.batch() optimistic concurrency.
145
211
  */
212
+ const PREPARED_STATEMENT_CACHE_LIMIT = 64;
213
+ const preparedStatementCaches = new WeakMap();
146
214
  export class D1ArchiveRepository {
147
215
  db;
148
216
  privacyConfig;
@@ -150,16 +218,29 @@ export class D1ArchiveRepository {
150
218
  this.db = db;
151
219
  this.privacyConfig = options?.privacyConfig;
152
220
  }
221
+ prepare(sql) {
222
+ let cache = preparedStatementCaches.get(this.db);
223
+ if (!cache) {
224
+ cache = new Map();
225
+ preparedStatementCaches.set(this.db, cache);
226
+ }
227
+ let stmt = cache.get(sql);
228
+ if (!stmt) {
229
+ stmt = this.db.prepare(sql);
230
+ if (cache.size < PREPARED_STATEMENT_CACHE_LIMIT) {
231
+ cache.set(sql, stmt);
232
+ }
233
+ }
234
+ return stmt;
235
+ }
153
236
  async getHeadRevisionId() {
154
- const row = await this.db
155
- .prepare('SELECT COALESCE(MAX(revision_id), 0) AS head_revision_id FROM revisions')
237
+ const row = await this.prepare('SELECT COALESCE(MAX(revision_id), 0) AS head_revision_id FROM revisions')
156
238
  .first();
157
239
  return asRevisionId(row?.head_revision_id ?? 0);
158
240
  }
159
241
  async getEntity(entityType, entityId) {
160
242
  if (entityType === 'kinship_edge') {
161
- const row = await this.db
162
- .prepare(`SELECT edge_id, from_person_id, to_person_id, relation, family_xref,
243
+ const row = await this.prepare(`SELECT edge_id, from_person_id, to_person_id, relation, family_xref,
163
244
  current_revision_id, deleted_at, updated_at
164
245
  FROM kinship_edges
165
246
  WHERE edge_id = ?`)
@@ -167,8 +248,7 @@ export class D1ArchiveRepository {
167
248
  .first();
168
249
  return row ? mapKinshipRow(row) : null;
169
250
  }
170
- const row = await this.db
171
- .prepare(`SELECT entity_type, entity_id, slug, data_json, current_revision_id,
251
+ const row = await this.prepare(`SELECT entity_type, entity_id, slug, data_json, current_revision_id,
172
252
  has_primary_source, deleted_at, updated_at
173
253
  FROM entities
174
254
  WHERE entity_type = ? AND entity_id = ?`)
@@ -176,16 +256,81 @@ export class D1ArchiveRepository {
176
256
  .first();
177
257
  return row ? mapEntityRow(row) : null;
178
258
  }
259
+ async getEntitiesBatch(keys) {
260
+ const result = new Map();
261
+ if (keys.length === 0) {
262
+ return result;
263
+ }
264
+ const entityPairs = [];
265
+ const kinshipIds = [];
266
+ for (const key of keys) {
267
+ const composite = entityLookupCompositeKey(key.entityType, key.entityId);
268
+ if (result.has(composite)) {
269
+ continue;
270
+ }
271
+ result.set(composite, null);
272
+ if (key.entityType === 'kinship_edge') {
273
+ kinshipIds.push(key.entityId);
274
+ }
275
+ else {
276
+ entityPairs.push([key.entityType, key.entityId]);
277
+ }
278
+ }
279
+ const statements = [];
280
+ const statementKinds = [];
281
+ for (const pairsJson of chunkJsonArray(entityPairs)) {
282
+ statements.push(this.prepare(`SELECT e.entity_type, e.entity_id, e.slug, e.data_json, e.current_revision_id,
283
+ e.has_primary_source, e.deleted_at, e.updated_at
284
+ FROM json_each(?) AS k
285
+ JOIN entities AS e
286
+ ON e.entity_type = json_extract(k.value, '$[0]')
287
+ AND e.entity_id = json_extract(k.value, '$[1]')`)
288
+ .bind(pairsJson));
289
+ statementKinds.push('entity');
290
+ }
291
+ for (const idsJson of chunkJsonArray(kinshipIds)) {
292
+ statements.push(this.prepare(`SELECT edge_id, from_person_id, to_person_id, relation, family_xref,
293
+ current_revision_id, deleted_at, updated_at
294
+ FROM kinship_edges
295
+ WHERE edge_id IN (SELECT value FROM json_each(?))`)
296
+ .bind(idsJson));
297
+ statementKinds.push('kinship_edge');
298
+ }
299
+ const batchResults = await this.db.batch(statements);
300
+ for (let i = 0; i < batchResults.length; i += 1) {
301
+ const kind = statementKinds[i];
302
+ if (kind === 'kinship_edge') {
303
+ const rows = (batchResults[i]?.results ?? []);
304
+ for (const row of rows) {
305
+ const mapped = mapKinshipRow(row);
306
+ result.set(entityLookupCompositeKey('kinship_edge', mapped.edge_id), mapped);
307
+ }
308
+ }
309
+ else {
310
+ const rows = (batchResults[i]?.results ?? []);
311
+ for (const row of rows) {
312
+ const mapped = mapEntityRow(row);
313
+ result.set(entityLookupCompositeKey(mapped.entity_type, mapped.entity_id), mapped);
314
+ }
315
+ }
316
+ }
317
+ return result;
318
+ }
179
319
  async getLivingPersonIds() {
180
- const result = await this.db
181
- .prepare(`SELECT entity_id, data_json
320
+ const result = await this.prepare(`SELECT entity_id,
321
+ json_extract(data_json, '$.is_living') AS is_living,
322
+ json_extract(data_json, '$.birth_edtf') AS birth_edtf,
323
+ json_extract(data_json, '$.death_edtf') AS death_edtf
182
324
  FROM entities
183
325
  WHERE entity_type = 'person' AND deleted_at IS NULL`)
184
326
  .all();
185
327
  const living = new Set();
186
328
  for (const row of result.results) {
187
- const parsed = parseEntityPayload('person', parseJsonObject(row.data_json));
188
- if (resolveEffectiveLiving(parsed, this.privacyConfig)) {
329
+ if (resolveEffectiveLiving({
330
+ is_living: Boolean(row.is_living),
331
+ birth_edtf: row.birth_edtf == null ? '' : String(row.birth_edtf),
332
+ death_edtf: row.death_edtf == null ? '' : String(row.death_edtf),
333
+ }, this.privacyConfig)) {
189
334
  living.add(row.entity_id);
190
335
  }
191
336
  }
@@ -193,16 +338,16 @@ export class D1ArchiveRepository {
193
338
  }
194
339
  async loadActiveSnapshot() {
195
340
  const [entitiesRes, kinshipRes, headRes] = await this.db.batch([
196
- this.db.prepare(`SELECT entity_type, entity_id, slug, data_json, current_revision_id,
341
+ this.prepare(`SELECT entity_type, entity_id, slug, data_json, current_revision_id,
197
342
  has_primary_source, deleted_at, updated_at
198
343
  FROM entities
199
344
  WHERE deleted_at IS NULL
200
345
  ORDER BY entity_type, entity_id`),
201
- this.db.prepare(`SELECT edge_id, from_person_id, to_person_id, relation, family_xref,
346
+ this.prepare(`SELECT edge_id, from_person_id, to_person_id, relation, family_xref,
202
347
  current_revision_id, deleted_at, updated_at
203
348
  FROM kinship_edges
204
349
  WHERE deleted_at IS NULL`),
205
- this.db.prepare('SELECT COALESCE(MAX(revision_id), 0) AS head_revision_id FROM revisions'),
350
+ this.prepare('SELECT COALESCE(MAX(revision_id), 0) AS head_revision_id FROM revisions'),
206
351
  ]);
207
352
  const entities = entitiesRes.results.map(mapEntityRow);
208
353
  const kinship = kinshipRes.results
@@ -224,12 +369,32 @@ export class D1ArchiveRepository {
224
369
  };
225
370
  }
226
371
  const statements = [];
227
- const revisionResultIndices = [];
372
+ const revisionResultEntries = [];
228
373
  const mutatedInBatch = new Set();
229
- for (const op of params.operations) {
374
+ const ops = params.operations;
375
+ for (let i = 0; i < ops.length; i += 1) {
376
+ const op = ops[i];
230
377
  const key = entityCompositeKey(op.entity_type, op.entity_id);
378
+ if (op.action === 'create') {
379
+ // Each create run becomes a few set-based statements instead of two per row.
380
+ let runEnd = i;
381
+ while (runEnd < ops.length && ops[runEnd].action === 'create') {
382
+ mutatedInBatch.add(entityCompositeKey(ops[runEnd].entity_type, ops[runEnd].entity_id));
383
+ runEnd += 1;
384
+ }
385
+ this.pushCreateRunStatements({
386
+ ops: ops.slice(i, runEnd),
387
+ batchId: params.batch_id,
388
+ author: params.author,
389
+ nowIso: params.nowIso,
390
+ statements,
391
+ revisionResultEntries,
392
+ });
393
+ i = runEnd - 1;
394
+ continue;
395
+ }
231
396
  const alreadyMutatedInBatch = mutatedInBatch.has(key);
232
- if (op.action !== 'create' && op.expected_parent_revision_id === null && !alreadyMutatedInBatch) {
397
+ if (op.expected_parent_revision_id === null && !alreadyMutatedInBatch) {
233
398
  return this.buildConflictForOp(op, params.nowIso);
234
399
  }
235
400
  const revStmt = this.buildRevisionInsertStatement({
@@ -239,7 +404,11 @@ export class D1ArchiveRepository {
239
404
  nowIso: params.nowIso,
240
405
  alreadyMutatedInBatch,
241
406
  });
242
- revisionResultIndices.push(statements.length);
407
+ revisionResultEntries.push({
408
+ stmtIndex: statements.length,
409
+ kind: 'single',
410
+ ops: [op],
411
+ });
243
412
  statements.push(revStmt);
244
413
  const entityStmt = this.buildEntityMutationStatement(op, params.nowIso);
245
414
  statements.push(entityStmt);
@@ -248,13 +417,43 @@ export class D1ArchiveRepository {
248
417
  try {
249
418
  const results = await this.db.batch(statements);
250
419
  const committedRevisions = [];
251
- for (const idx of revisionResultIndices) {
252
- const revRows = results[idx]?.results;
253
- const revRow = revRows?.[0];
254
- if (!revRow) {
255
- throw new Error('D1 revision insert did not return the inserted revision row.');
420
+ for (const entry of revisionResultEntries) {
421
+ if (entry.kind === 'create') {
422
+ const revRows = (results[entry.stmtIndex]?.results ?? []);
423
+ if (revRows.length !== entry.ops.length) {
424
+ throw new Error(`D1 create revision insert returned ${revRows.length} rows for ${entry.ops.length} operations.`);
425
+ }
426
+ // RETURNING order is unspecified; AUTOINCREMENT revision_id follows insertion order.
427
+ const sortedIds = revRows.toSorted((a, b) => a.revision_id - b.revision_id);
428
+ for (let j = 0; j < sortedIds.length; j += 1) {
429
+ committedRevisions.push(buildCommittedRevisionRecord({
430
+ revisionId: sortedIds[j].revision_id,
431
+ parentRevisionId: null,
432
+ op: entry.ops[j],
433
+ batchId: params.batch_id,
434
+ author: params.author,
435
+ nowIso: params.nowIso,
436
+ }));
437
+ }
256
438
  }
257
- committedRevisions.push(mapRevisionRow(revRow));
439
+ else {
440
+ const revRows = (results[entry.stmtIndex]?.results ?? []);
441
+ const revRow = revRows[0];
442
+ if (!revRow) {
443
+ throw new Error('D1 revision insert did not return the inserted revision row.');
444
+ }
445
+ committedRevisions.push(buildCommittedRevisionRecord({
446
+ revisionId: revRow.revision_id,
447
+ parentRevisionId: revRow.parent_revision_id,
448
+ op: entry.ops[0],
449
+ batchId: params.batch_id,
450
+ author: params.author,
451
+ nowIso: params.nowIso,
452
+ }));
453
+ }
454
+ }
455
+ if (committedRevisions.length !== ops.length) {
456
+ throw new Error(`D1 batch returned ${committedRevisions.length} revisions for ${ops.length} operations.`);
258
457
  }
259
458
  const lastRevision = committedRevisions[committedRevisions.length - 1];
260
459
  return {
@@ -270,29 +469,147 @@ export class D1ArchiveRepository {
270
469
  return this.resolveConstraintConflict(params.operations, params.nowIso, error);
271
470
  }
272
471
  }
472
+ /**
473
+ * Appends set-based INSERTs for a run of create ops: revisions first, then the
474
+ * entity and kinship rows. Each row links to the newest revision for its key, which
475
+ * is the revision this run just inserted, and entities copy data_json and
476
+ * has_primary_source from it so the payload crosses the binding once. Duplicate
477
+ * keys still fail the primary key, so DB.batch() rolls back as before.
478
+ */
479
+ pushCreateRunStatements(params) {
480
+ const { ops, batchId, author, nowIso, statements, revisionResultEntries } = params;
481
+ // Pass before_json / after_json as raw objects so chunkJsonArrayWithRanges encodes
482
+ // each payload once; SQLite json_extract() returns compact JSON text for objects and NULL for null.
483
+ // Omit ORDER BY key because json_each() on a JSON array yields elements in array index order
484
+ // without forcing a temp B-tree sort over multi-megabyte payloads.
485
+ const firstSummary = ops[0].summary;
486
+ const firstPrimary = ops[0].has_primary_source;
487
+ const uniformMetadata = ops.every((op) => op.summary === firstSummary &&
488
+ op.has_primary_source === firstPrimary &&
489
+ op.before_json === null &&
490
+ (op.reverted_revision_id ?? null) === null);
491
+ if (uniformMetadata) {
492
+ const compactRows = ops.map((op) => [op.entity_type, op.entity_id, op.after_json]);
493
+ const uniformPrimaryInt = firstPrimary ? 1 : 0;
494
+ for (const chunk of chunkJsonArrayWithRanges(compactRows)) {
495
+ revisionResultEntries.push({
496
+ stmtIndex: statements.length,
497
+ kind: 'create',
498
+ ops: ops.slice(chunk.start, chunk.start + chunk.count),
499
+ });
500
+ statements.push(this.prepare(`INSERT INTO revisions (
501
+ batch_id, entity_type, entity_id, parent_revision_id, action,
502
+ reverted_revision_id, author_id, author_name, author_type,
503
+ summary, has_primary_source, before_json, after_json, created_at
504
+ )
505
+ SELECT ?, json_extract(value, '$[0]'), json_extract(value, '$[1]'), NULL, 'create',
506
+ NULL, ?, ?, ?, ?, ?, NULL, json_extract(value, '$[2]'), ?
507
+ FROM json_each(?)
508
+ RETURNING revision_id`).bind(batchId, author.author_id, author.author_name, author.author_type, firstSummary, uniformPrimaryInt, nowIso, chunk.json));
509
+ }
510
+ }
511
+ else {
512
+ const revisionRows = ops.map((op) => [
513
+ op.entity_type,
514
+ op.entity_id,
515
+ op.reverted_revision_id ?? null,
516
+ op.summary,
517
+ op.has_primary_source ? 1 : 0,
518
+ op.before_json,
519
+ op.after_json,
520
+ ]);
521
+ for (const chunk of chunkJsonArrayWithRanges(revisionRows)) {
522
+ revisionResultEntries.push({
523
+ stmtIndex: statements.length,
524
+ kind: 'create',
525
+ ops: ops.slice(chunk.start, chunk.start + chunk.count),
526
+ });
527
+ statements.push(this.prepare(`INSERT INTO revisions (
528
+ batch_id, entity_type, entity_id, parent_revision_id, action,
529
+ reverted_revision_id, author_id, author_name, author_type,
530
+ summary, has_primary_source, before_json, after_json, created_at
531
+ )
532
+ SELECT ?, json_extract(value, '$[0]'), json_extract(value, '$[1]'), NULL, 'create',
533
+ json_extract(value, '$[2]'), ?, ?, ?,
534
+ json_extract(value, '$[3]'), json_extract(value, '$[4]'),
535
+ json_extract(value, '$[5]'), json_extract(value, '$[6]'), ?
536
+ FROM json_each(?)
537
+ RETURNING revision_id`).bind(batchId, author.author_id, author.author_name, author.author_type, nowIso, chunk.json));
538
+ }
539
+ }
540
+ const entityRows = [];
541
+ const kinshipRows = [];
542
+ for (const op of ops) {
543
+ if (!op.after_json) {
544
+ throw new Error(`Create ${op.entity_type} operation requires after_json.`);
545
+ }
546
+ const deletedAt = op.soft_delete === true ? nowIso : null;
547
+ if (op.entity_type === 'kinship_edge') {
548
+ const edge = parseEntityPayload('kinship_edge', op.after_json);
549
+ kinshipRows.push([
550
+ op.entity_id,
551
+ edge.from,
552
+ edge.to,
553
+ edge.relation,
554
+ edge.family_xref ?? null,
555
+ deletedAt,
556
+ ]);
557
+ }
558
+ else {
559
+ entityRows.push([op.entity_type, op.entity_id, resolveSlugForOp(op).value, deletedAt]);
560
+ }
561
+ }
562
+ for (const rowsJson of chunkJsonArray(entityRows)) {
563
+ statements.push(this.prepare(`INSERT INTO entities (
564
+ entity_type, entity_id, slug, data_json, current_revision_id,
565
+ has_primary_source, deleted_at, updated_at
566
+ )
567
+ SELECT r.entity_type, r.entity_id, j.slug, r.after_json, r.revision_id,
568
+ r.has_primary_source, j.deleted_at, ?
569
+ FROM (
570
+ SELECT json_extract(value, '$[0]') AS entity_type,
571
+ json_extract(value, '$[1]') AS entity_id,
572
+ json_extract(value, '$[2]') AS slug,
573
+ json_extract(value, '$[3]') AS deleted_at
574
+ FROM json_each(?)
575
+ ) AS j
576
+ JOIN revisions r ON r.revision_id = (
577
+ SELECT MAX(r2.revision_id) FROM revisions r2
578
+ WHERE r2.entity_type = j.entity_type AND r2.entity_id = j.entity_id
579
+ )`)
580
+ .bind(nowIso, rowsJson));
581
+ }
582
+ for (const rowsJson of chunkJsonArray(kinshipRows)) {
583
+ statements.push(this.prepare(`INSERT INTO kinship_edges (
584
+ edge_id, from_person_id, to_person_id, relation, family_xref,
585
+ current_revision_id, deleted_at, updated_at
586
+ )
587
+ SELECT j.edge_id, j.from_person_id, j.to_person_id, j.relation, j.family_xref,
588
+ (SELECT MAX(r.revision_id) FROM revisions r
589
+ WHERE r.entity_type = 'kinship_edge' AND r.entity_id = j.edge_id),
590
+ j.deleted_at, ?
591
+ FROM (
592
+ SELECT json_extract(value, '$[0]') AS edge_id,
593
+ json_extract(value, '$[1]') AS from_person_id,
594
+ json_extract(value, '$[2]') AS to_person_id,
595
+ json_extract(value, '$[3]') AS relation,
596
+ json_extract(value, '$[4]') AS family_xref,
597
+ json_extract(value, '$[5]') AS deleted_at
598
+ FROM json_each(?)
599
+ ) AS j`)
600
+ .bind(nowIso, rowsJson));
601
+ }
602
+ }
273
603
  buildRevisionInsertStatement(params) {
274
604
  const { op, batchId, author, nowIso, alreadyMutatedInBatch } = params;
275
605
  const beforeJson = op.before_json !== null ? JSON.stringify(op.before_json) : null;
276
606
  const afterJson = op.after_json !== null ? JSON.stringify(op.after_json) : null;
277
607
  const hasPrimary = op.has_primary_source ? 1 : 0;
278
608
  const revertedRevId = op.reverted_revision_id ?? null;
279
- if (op.action === 'create') {
280
- return this.db
281
- .prepare(`INSERT INTO revisions (
282
- batch_id, entity_type, entity_id, parent_revision_id, action,
283
- reverted_revision_id, author_id, author_name, author_type,
284
- summary, has_primary_source, before_json, after_json, created_at
285
- ) VALUES (?, ?, ?, NULL, 'create', ?, ?, ?, ?, ?, ?, ?, ?, ?)
286
- RETURNING revision_id, batch_id, entity_type, entity_id, parent_revision_id, action,
287
- reverted_revision_id, author_id, author_name, author_type,
288
- summary, has_primary_source, before_json, after_json, created_at`)
289
- .bind(batchId, op.entity_type, op.entity_id, revertedRevId, author.author_id, author.author_name, author.author_type, op.summary, hasPrimary, beforeJson, afterJson, nowIso);
290
- }
291
609
  const lockWhere = this.buildLockWhereClause(op, alreadyMutatedInBatch);
292
610
  if (op.action === 'restore') {
293
611
  // Guard restore atomically through the action CHECK constraint so stale or active rows roll back DB.batch().
294
- return this.db
295
- .prepare(`INSERT INTO revisions (
612
+ return this.prepare(`INSERT INTO revisions (
296
613
  batch_id, entity_type, entity_id, parent_revision_id, action,
297
614
  reverted_revision_id, author_id, author_name, author_type,
298
615
  summary, has_primary_source, before_json, after_json, created_at
@@ -305,14 +622,11 @@ export class D1ArchiveRepository {
305
622
  END,
306
623
  ?, ?, ?, ?, ?, ?, ?, ?, ?
307
624
  )
308
- RETURNING revision_id, batch_id, entity_type, entity_id, parent_revision_id, action,
309
- reverted_revision_id, author_id, author_name, author_type,
310
- summary, has_primary_source, before_json, after_json, created_at`)
625
+ RETURNING revision_id, parent_revision_id`)
311
626
  .bind(batchId, op.entity_type, op.entity_id, ...lockWhere.bindings, ...lockWhere.bindings, revertedRevId, author.author_id, author.author_name, author.author_type, op.summary, hasPrimary, beforeJson, afterJson, nowIso);
312
627
  }
313
628
  // update, delete, and revert rely on CHECK (action IN ('create', 'restore') OR parent_revision_id IS NOT NULL).
314
- return this.db
315
- .prepare(`INSERT INTO revisions (
629
+ return this.prepare(`INSERT INTO revisions (
316
630
  batch_id, entity_type, entity_id, parent_revision_id, action,
317
631
  reverted_revision_id, author_id, author_name, author_type,
318
632
  summary, has_primary_source, before_json, after_json, created_at
@@ -321,9 +635,7 @@ export class D1ArchiveRepository {
321
635
  (SELECT current_revision_id FROM ${lockWhere.table} WHERE ${lockWhere.sql}),
322
636
  ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
323
637
  )
324
- RETURNING revision_id, batch_id, entity_type, entity_id, parent_revision_id, action,
325
- reverted_revision_id, author_id, author_name, author_type,
326
- summary, has_primary_source, before_json, after_json, created_at`)
638
+ RETURNING revision_id, parent_revision_id`)
327
639
  .bind(batchId, op.entity_type, op.entity_id, ...lockWhere.bindings, op.action, revertedRevId, author.author_id, author.author_name, author.author_type, op.summary, hasPrimary, beforeJson, afterJson, nowIso);
328
640
  }
329
641
  buildLockWhereClause(op, alreadyMutatedInBatch) {
@@ -360,76 +672,48 @@ export class D1ArchiveRepository {
360
672
  const isSoftDelete = op.soft_delete === true || op.action === 'delete' || op.after_json === null;
361
673
  const deletedAt = isSoftDelete ? nowIso : null;
362
674
  if (op.entity_type === 'kinship_edge') {
363
- if (op.action === 'create') {
364
- if (!op.after_json) {
365
- throw new Error('Create kinship_edge operation requires after_json.');
366
- }
367
- const edge = parseEntityPayload('kinship_edge', op.after_json);
368
- return this.db
369
- .prepare(`INSERT INTO kinship_edges (
370
- edge_id, from_person_id, to_person_id, relation, family_xref,
371
- current_revision_id, deleted_at, updated_at
372
- ) VALUES (?, ?, ?, ?, ?, last_insert_rowid(), ?, ?)`)
373
- .bind(op.entity_id, edge.from, edge.to, edge.relation, edge.family_xref ?? null, deletedAt, nowIso);
374
- }
375
675
  if (op.after_json !== null) {
376
676
  const edge = parseEntityPayload('kinship_edge', op.after_json);
377
- return this.db
378
- .prepare(`UPDATE kinship_edges
677
+ return this.prepare(`UPDATE kinship_edges
379
678
  SET from_person_id = ?, to_person_id = ?, relation = ?, family_xref = ?,
380
679
  current_revision_id = last_insert_rowid(), deleted_at = ?, updated_at = ?
381
680
  WHERE edge_id = ?`)
382
681
  .bind(edge.from, edge.to, edge.relation, edge.family_xref ?? null, deletedAt, nowIso, op.entity_id);
383
682
  }
384
- return this.db
385
- .prepare(`UPDATE kinship_edges
683
+ return this.prepare(`UPDATE kinship_edges
386
684
  SET current_revision_id = last_insert_rowid(), deleted_at = ?, updated_at = ?
387
685
  WHERE edge_id = ?`)
388
686
  .bind(deletedAt, nowIso, op.entity_id);
389
687
  }
390
688
  const hasPrimary = op.has_primary_source ? 1 : 0;
391
- if (op.action === 'create') {
392
- if (!op.after_json) {
393
- throw new Error(`Create ${op.entity_type} operation requires after_json.`);
394
- }
395
- const slugInfo = resolveSlugForOp(op);
396
- return this.db
397
- .prepare(`INSERT INTO entities (
398
- entity_type, entity_id, slug, data_json, current_revision_id,
399
- has_primary_source, deleted_at, updated_at
400
- ) VALUES (?, ?, ?, ?, last_insert_rowid(), ?, ?, ?)`)
401
- .bind(op.entity_type, op.entity_id, slugInfo.value, JSON.stringify(op.after_json), hasPrimary, deletedAt, nowIso);
402
- }
403
689
  if (op.after_json !== null) {
404
690
  const slugInfo = resolveSlugForOp(op);
405
691
  if (slugInfo.updateSlug) {
406
- return this.db
407
- .prepare(`UPDATE entities
692
+ return this.prepare(`UPDATE entities
408
693
  SET slug = ?, data_json = ?, current_revision_id = last_insert_rowid(),
409
694
  has_primary_source = ?, deleted_at = ?, updated_at = ?
410
695
  WHERE entity_type = ? AND entity_id = ?`)
411
696
  .bind(slugInfo.value, JSON.stringify(op.after_json), hasPrimary, deletedAt, nowIso, op.entity_type, op.entity_id);
412
697
  }
413
- return this.db
414
- .prepare(`UPDATE entities
698
+ return this.prepare(`UPDATE entities
415
699
  SET data_json = ?, current_revision_id = last_insert_rowid(),
416
700
  has_primary_source = ?, deleted_at = ?, updated_at = ?
417
701
  WHERE entity_type = ? AND entity_id = ?`)
418
702
  .bind(JSON.stringify(op.after_json), hasPrimary, deletedAt, nowIso, op.entity_type, op.entity_id);
419
703
  }
420
- return this.db
421
- .prepare(`UPDATE entities
704
+ return this.prepare(`UPDATE entities
422
705
  SET current_revision_id = last_insert_rowid(),
423
706
  has_primary_source = ?, deleted_at = ?, updated_at = ?
424
707
  WHERE entity_type = ? AND entity_id = ?`)
425
708
  .bind(hasPrimary, deletedAt, nowIso, op.entity_type, op.entity_id);
426
709
  }
427
710
  async resolveConstraintConflict(operations, nowIso, originalError) {
711
+ const existingByKey = await this.getEntitiesBatch(operations.map((op) => ({ entityType: op.entity_type, entityId: op.entity_id })));
428
712
  const seenInBatch = new Set();
429
713
  for (const op of operations) {
430
714
  const key = entityCompositeKey(op.entity_type, op.entity_id);
431
715
  const alreadySeen = seenInBatch.has(key);
432
- const existing = await this.getEntity(op.entity_type, op.entity_id);
716
+ const existing = existingByKey.get(key) ?? null;
433
717
  if (op.action === 'create') {
434
718
  if (existing !== null || alreadySeen) {
435
719
  return this.buildConflictFromExisting(op, existing, nowIso);
@@ -482,8 +766,7 @@ export class D1ArchiveRepository {
482
766
  diff: computeEntityDiff(null, op.after_json),
483
767
  };
484
768
  }
485
- const lastRev = await this.db
486
- .prepare(`SELECT author_name
769
+ const lastRev = await this.prepare(`SELECT author_name
487
770
  FROM revisions
488
771
  WHERE entity_type = ? AND entity_id = ?
489
772
  ORDER BY revision_id DESC
@@ -529,8 +812,7 @@ export class D1ArchiveRepository {
529
812
  bindings.push(query.cursor);
530
813
  }
531
814
  const whereSql = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
532
- const res = await this.db
533
- .prepare(`SELECT revision_id, batch_id, entity_type, entity_id, parent_revision_id, action,
815
+ const res = await this.prepare(`SELECT revision_id, batch_id, entity_type, entity_id, parent_revision_id, action,
534
816
  reverted_revision_id, author_id, author_name, author_type,
535
817
  summary, has_primary_source, before_json, after_json, created_at
536
818
  FROM revisions
@@ -549,8 +831,7 @@ export class D1ArchiveRepository {
549
831
  };
550
832
  }
551
833
  async getRevisionById(revisionId) {
552
- const row = await this.db
553
- .prepare(`SELECT revision_id, batch_id, entity_type, entity_id, parent_revision_id, action,
834
+ const row = await this.prepare(`SELECT revision_id, batch_id, entity_type, entity_id, parent_revision_id, action,
554
835
  reverted_revision_id, author_id, author_name, author_type,
555
836
  summary, has_primary_source, before_json, after_json, created_at
556
837
  FROM revisions
@@ -560,8 +841,7 @@ export class D1ArchiveRepository {
560
841
  return row ? mapRevisionRow(row) : null;
561
842
  }
562
843
  async getRevisionsByBatch(batchId) {
563
- const res = await this.db
564
- .prepare(`SELECT revision_id, batch_id, entity_type, entity_id, parent_revision_id, action,
844
+ const res = await this.prepare(`SELECT revision_id, batch_id, entity_type, entity_id, parent_revision_id, action,
565
845
  reverted_revision_id, author_id, author_name, author_type,
566
846
  summary, has_primary_source, before_json, after_json, created_at
567
847
  FROM revisions
@@ -572,8 +852,7 @@ export class D1ArchiveRepository {
572
852
  return res.results.map(mapRevisionRow);
573
853
  }
574
854
  async listTalkComments(entityType, entityId) {
575
- const res = await this.db
576
- .prepare(`SELECT comment_id, entity_type, entity_id, author_id, author_name,
855
+ const res = await this.prepare(`SELECT comment_id, entity_type, entity_id, author_id, author_name,
577
856
  body_md, created_at, edited_at, deleted_at
578
857
  FROM talk_comments
579
858
  WHERE entity_type = ? AND entity_id = ? AND deleted_at IS NULL
@@ -583,8 +862,7 @@ export class D1ArchiveRepository {
583
862
  return res.results.map(mapTalkRow);
584
863
  }
585
864
  async insertTalkComment(input) {
586
- const row = await this.db
587
- .prepare(`INSERT INTO talk_comments (
865
+ const row = await this.prepare(`INSERT INTO talk_comments (
588
866
  entity_type, entity_id, author_id, author_name, body_md, created_at
589
867
  ) VALUES (?, ?, ?, ?, ?, ?)
590
868
  RETURNING comment_id, entity_type, entity_id, author_id, author_name,
@@ -597,8 +875,7 @@ export class D1ArchiveRepository {
597
875
  return mapTalkRow(row);
598
876
  }
599
877
  async softDeleteTalkComment(commentId, deletedAt) {
600
- const res = await this.db
601
- .prepare(`UPDATE talk_comments
878
+ const res = await this.prepare(`UPDATE talk_comments
602
879
  SET deleted_at = ?
603
880
  WHERE comment_id = ? AND deleted_at IS NULL`)
604
881
  .bind(deletedAt, commentId)
@@ -607,8 +884,7 @@ export class D1ArchiveRepository {
607
884
  }
608
885
  async getUser(email) {
609
886
  const normalized = email.trim().toLowerCase();
610
- const row = await this.db
611
- .prepare(`SELECT email, display_name, role, added_by, added_at, last_login_at
887
+ const row = await this.prepare(`SELECT email, display_name, role, added_by, added_at, last_login_at
612
888
  FROM users
613
889
  WHERE email = ?`)
614
890
  .bind(normalized)
@@ -616,8 +892,7 @@ export class D1ArchiveRepository {
616
892
  return row ? mapUserRow(row) : null;
617
893
  }
618
894
  async listUsers() {
619
- const res = await this.db
620
- .prepare(`SELECT email, display_name, role, added_by, added_at, last_login_at
895
+ const res = await this.prepare(`SELECT email, display_name, role, added_by, added_at, last_login_at
621
896
  FROM users
622
897
  ORDER BY email ASC`)
623
898
  .all();
@@ -625,8 +900,7 @@ export class D1ArchiveRepository {
625
900
  }
626
901
  async upsertUser(user) {
627
902
  const normalizedEmail = user.email.trim().toLowerCase();
628
- const row = await this.db
629
- .prepare(`INSERT INTO users (email, display_name, role, added_by, added_at, last_login_at)
903
+ const row = await this.prepare(`INSERT INTO users (email, display_name, role, added_by, added_at, last_login_at)
630
904
  VALUES (?, ?, ?, ?, ?, ?)
631
905
  ON CONFLICT(email) DO UPDATE SET
632
906
  display_name = excluded.display_name,
@@ -644,8 +918,7 @@ export class D1ArchiveRepository {
644
918
  }
645
919
  async updateUserRole(email, role) {
646
920
  const normalized = email.trim().toLowerCase();
647
- const row = await this.db
648
- .prepare(`UPDATE users
921
+ const row = await this.prepare(`UPDATE users
649
922
  SET role = ?
650
923
  WHERE email = ?
651
924
  RETURNING email, display_name, role, added_by, added_at, last_login_at`)
@@ -655,19 +928,17 @@ export class D1ArchiveRepository {
655
928
  }
656
929
  async deleteUser(email) {
657
930
  const normalized = email.trim().toLowerCase();
658
- const res = await this.db.prepare('DELETE FROM users WHERE email = ?').bind(normalized).run();
931
+ const res = await this.prepare('DELETE FROM users WHERE email = ?').bind(normalized).run();
659
932
  return (res.meta.changes ?? 0) > 0;
660
933
  }
661
934
  async touchUserLogin(email, atIso) {
662
935
  const normalized = email.trim().toLowerCase();
663
- await this.db
664
- .prepare('UPDATE users SET last_login_at = ? WHERE email = ?')
936
+ await this.prepare('UPDATE users SET last_login_at = ? WHERE email = ?')
665
937
  .bind(atIso, normalized)
666
938
  .run();
667
939
  }
668
940
  async getInvite(token) {
669
- const row = await this.db
670
- .prepare(`SELECT token, label, created_by, created_at, expires_at, revoked_at, uses, last_used_at
941
+ const row = await this.prepare(`SELECT token, label, created_by, created_at, expires_at, revoked_at, uses, last_used_at
671
942
  FROM invites
672
943
  WHERE token = ?`)
673
944
  .bind(token)
@@ -675,16 +946,14 @@ export class D1ArchiveRepository {
675
946
  return row ? mapInviteRow(row) : null;
676
947
  }
677
948
  async listInvites() {
678
- const res = await this.db
679
- .prepare(`SELECT token, label, created_by, created_at, expires_at, revoked_at, uses, last_used_at
949
+ const res = await this.prepare(`SELECT token, label, created_by, created_at, expires_at, revoked_at, uses, last_used_at
680
950
  FROM invites
681
951
  ORDER BY created_at DESC`)
682
952
  .all();
683
953
  return res.results.map(mapInviteRow);
684
954
  }
685
955
  async createInvite(invite) {
686
- const row = await this.db
687
- .prepare(`INSERT INTO invites (
956
+ const row = await this.prepare(`INSERT INTO invites (
688
957
  token, label, created_by, created_at, expires_at, revoked_at, uses, last_used_at
689
958
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
690
959
  RETURNING token, label, created_by, created_at, expires_at, revoked_at, uses, last_used_at`)
@@ -696,29 +965,25 @@ export class D1ArchiveRepository {
696
965
  return mapInviteRow(row);
697
966
  }
698
967
  async recordInviteUse(token, atIso) {
699
- await this.db
700
- .prepare('UPDATE invites SET uses = uses + 1, last_used_at = ? WHERE token = ?')
968
+ await this.prepare('UPDATE invites SET uses = uses + 1, last_used_at = ? WHERE token = ?')
701
969
  .bind(atIso, token)
702
970
  .run();
703
971
  }
704
972
  async revokeInvite(token, atIso) {
705
- const res = await this.db
706
- .prepare('UPDATE invites SET revoked_at = ? WHERE token = ? AND revoked_at IS NULL')
973
+ const res = await this.prepare('UPDATE invites SET revoked_at = ? WHERE token = ? AND revoked_at IS NULL')
707
974
  .bind(atIso, token)
708
975
  .run();
709
976
  return (res.meta.changes ?? 0) > 0;
710
977
  }
711
978
  async insertMagicLink(record) {
712
- await this.db
713
- .prepare(`INSERT INTO magic_links (token_hash, email, invite_token, expires_at, used_at)
979
+ await this.prepare(`INSERT INTO magic_links (token_hash, email, invite_token, expires_at, used_at)
714
980
  VALUES (?, ?, ?, ?, ?)`)
715
981
  .bind(record.token_hash, record.email, record.invite_token, record.expires_at, record.used_at)
716
982
  .run();
717
983
  }
718
984
  async consumeMagicLink(tokenHash, nowIso) {
719
985
  // Single atomic UPDATE prevents replay races across concurrent verification requests.
720
- const row = await this.db
721
- .prepare(`UPDATE magic_links
986
+ const row = await this.prepare(`UPDATE magic_links
722
987
  SET used_at = ?
723
988
  WHERE token_hash = ?
724
989
  AND used_at IS NULL
@@ -729,8 +994,7 @@ export class D1ArchiveRepository {
729
994
  return row ? mapMagicLinkRow(row) : null;
730
995
  }
731
996
  async findActiveAgentTokenByHash(tokenHash) {
732
- const row = await this.db
733
- .prepare(`SELECT token_id, token_hash, label, scope, created_by, created_at, revoked_at
997
+ const row = await this.prepare(`SELECT token_id, token_hash, label, scope, created_by, created_at, revoked_at
734
998
  FROM agent_tokens
735
999
  WHERE token_hash = ? AND revoked_at IS NULL`)
736
1000
  .bind(tokenHash)
@@ -738,16 +1002,14 @@ export class D1ArchiveRepository {
738
1002
  return row ? mapAgentTokenRow(row) : null;
739
1003
  }
740
1004
  async listAgentTokens() {
741
- const res = await this.db
742
- .prepare(`SELECT token_id, token_hash, label, scope, created_by, created_at, revoked_at
1005
+ const res = await this.prepare(`SELECT token_id, token_hash, label, scope, created_by, created_at, revoked_at
743
1006
  FROM agent_tokens
744
1007
  ORDER BY created_at DESC`)
745
1008
  .all();
746
1009
  return res.results.map(mapAgentTokenRow);
747
1010
  }
748
1011
  async createAgentToken(record) {
749
- const row = await this.db
750
- .prepare(`INSERT INTO agent_tokens (
1012
+ const row = await this.prepare(`INSERT INTO agent_tokens (
751
1013
  token_id, token_hash, label, scope, created_by, created_at, revoked_at
752
1014
  ) VALUES (?, ?, ?, ?, ?, ?, ?)
753
1015
  RETURNING token_id, token_hash, label, scope, created_by, created_at, revoked_at`)
@@ -759,8 +1021,7 @@ export class D1ArchiveRepository {
759
1021
  return mapAgentTokenRow(row);
760
1022
  }
761
1023
  async revokeAgentToken(tokenId, atIso) {
762
- const res = await this.db
763
- .prepare('UPDATE agent_tokens SET revoked_at = ? WHERE token_id = ? AND revoked_at IS NULL')
1024
+ const res = await this.prepare('UPDATE agent_tokens SET revoked_at = ? WHERE token_id = ? AND revoked_at IS NULL')
764
1025
  .bind(atIso, tokenId)
765
1026
  .run();
766
1027
  return (res.meta.changes ?? 0) > 0;