botnote 0.2.7 → 0.2.9

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.
@@ -0,0 +1,64 @@
1
+ import type { Database } from "../db/client.js";
2
+ import type { Scope } from "./scope.js";
3
+ /**
4
+ * JSON Lines workspace dump. Line 1 is the header; every later line is one
5
+ * record whose `type` names the table it came from. Records are written in
6
+ * dependency order (projects before entities before edges, ...) so the
7
+ * importer can stream them without buffering the whole file.
8
+ *
9
+ * Bump FORMAT_VERSION only for changes an older importer could not read.
10
+ * Adding optional fields is not such a change.
11
+ */
12
+ export declare const FORMAT_VERSION = 1;
13
+ export declare const RECORD_TYPES: readonly ["project", "entity", "edge", "recurrence_rule", "recurrence_exception", "entity_revision", "settings"];
14
+ export type RecordType = (typeof RECORD_TYPES)[number];
15
+ export interface ExportHeader {
16
+ type: "header";
17
+ formatVersion: number;
18
+ botnoteVersion: string;
19
+ exportedAt: string;
20
+ workspace: {
21
+ id: string;
22
+ slug: string;
23
+ name: string;
24
+ };
25
+ includesVectors: boolean;
26
+ }
27
+ export interface ExportOptions {
28
+ /** Include `bodyVec` on entities. Off by default: vectors are large and the importer re-embeds. */
29
+ includeVectors?: boolean;
30
+ }
31
+ export declare function exportWorkspace(scope: Scope, db: Database["db"], opts?: ExportOptions): AsyncGenerator<string>;
32
+ export interface ImportCounts {
33
+ imported: number;
34
+ skipped: number;
35
+ conflicts: number;
36
+ }
37
+ export interface ImportConflict {
38
+ type: RecordType;
39
+ id: string;
40
+ reason: string;
41
+ }
42
+ export interface ImportReport {
43
+ formatVersion: number;
44
+ botnoteVersion: string;
45
+ exportedAt: string;
46
+ sourceWorkspace: {
47
+ id: string;
48
+ slug: string;
49
+ name: string;
50
+ };
51
+ counts: Record<RecordType, ImportCounts>;
52
+ /** First MAX_REPORTED_CONFLICTS conflicts; `conflictsTotal` has the full count. */
53
+ conflicts: ImportConflict[];
54
+ conflictsTotal: number;
55
+ /** Entities inserted without a vector; run the embedding backfill to search them. */
56
+ entitiesWithoutVector: number;
57
+ }
58
+ /**
59
+ * Import a dump produced by exportWorkspace into `scope`. Idempotent: rows
60
+ * whose id already exists here are skipped, so a partial import can simply be
61
+ * re-run. Rows owned by another workspace, or whose parent row is missing,
62
+ * are reported as conflicts and left out rather than aborting the import.
63
+ */
64
+ export declare function importWorkspace(scope: Scope, db: Database["db"], lines: AsyncIterable<string> | Iterable<string>): Promise<ImportReport>;
@@ -0,0 +1,629 @@
1
+ import { and, asc, eq, gt, inArray, sql } from "drizzle-orm";
2
+ import { z } from "zod";
3
+ import { ACTOR_KINDS, EDGE_KINDS, ENTITY_KINDS, VECTOR_DIMENSIONS, edges, entities, entityRevisions, projects, recurrenceExceptions, recurrenceRules, tokens, workspaceSettings, workspaces } from "../db/schema.js";
4
+ import { VERSION } from "../version.js";
5
+ import { Uuid } from "./types.js";
6
+ /**
7
+ * JSON Lines workspace dump. Line 1 is the header; every later line is one
8
+ * record whose `type` names the table it came from. Records are written in
9
+ * dependency order (projects before entities before edges, ...) so the
10
+ * importer can stream them without buffering the whole file.
11
+ *
12
+ * Bump FORMAT_VERSION only for changes an older importer could not read.
13
+ * Adding optional fields is not such a change.
14
+ */
15
+ export const FORMAT_VERSION = 1;
16
+ export const RECORD_TYPES = [
17
+ "project",
18
+ "entity",
19
+ "edge",
20
+ "recurrence_rule",
21
+ "recurrence_exception",
22
+ "entity_revision",
23
+ "settings"
24
+ ];
25
+ const BATCH = 500;
26
+ const MAX_REPORTED_CONFLICTS = 100;
27
+ function clientError(message, statusCode) {
28
+ const err = new Error(message);
29
+ err.statusCode = statusCode;
30
+ return err;
31
+ }
32
+ function line(type, row) {
33
+ return `${JSON.stringify({ type, ...row })}\n`;
34
+ }
35
+ async function* pages(fetch, cursorOf) {
36
+ let after = null;
37
+ for (;;) {
38
+ const rows = await fetch(after);
39
+ if (rows.length === 0)
40
+ return;
41
+ yield rows;
42
+ if (rows.length < BATCH)
43
+ return;
44
+ after = cursorOf(rows[rows.length - 1]);
45
+ }
46
+ }
47
+ export async function* exportWorkspace(scope, db, opts = {}) {
48
+ const wsId = scope.workspaceId;
49
+ const [ws] = await db.select().from(workspaces).where(eq(workspaces.id, wsId)).limit(1);
50
+ if (!ws)
51
+ throw clientError(`workspace ${wsId} not found`, 404);
52
+ const header = {
53
+ type: "header",
54
+ formatVersion: FORMAT_VERSION,
55
+ botnoteVersion: VERSION,
56
+ exportedAt: new Date().toISOString(),
57
+ workspace: { id: ws.id, slug: ws.slug, name: ws.name },
58
+ includesVectors: Boolean(opts.includeVectors)
59
+ };
60
+ yield `${JSON.stringify(header)}\n`;
61
+ for await (const rows of pages((after) => db
62
+ .select()
63
+ .from(projects)
64
+ .where(and(eq(projects.workspaceId, wsId), after ? gt(projects.id, after) : undefined))
65
+ .orderBy(asc(projects.id))
66
+ .limit(BATCH), (r) => r.id)) {
67
+ for (const { workspaceId: _ws, ...p } of rows)
68
+ yield line("project", p);
69
+ }
70
+ for await (const rows of pages((after) => db
71
+ .select()
72
+ .from(entities)
73
+ .where(and(eq(entities.workspaceId, wsId), after ? gt(entities.id, after) : undefined))
74
+ .orderBy(asc(entities.id))
75
+ .limit(BATCH), (r) => r.id)) {
76
+ for (const { workspaceId: _ws, bodyTsv: _tsv, bodyVec, ...e } of rows) {
77
+ yield line("entity", opts.includeVectors && bodyVec ? { ...e, bodyVec } : e);
78
+ }
79
+ }
80
+ let edgeCursor = null;
81
+ for (;;) {
82
+ const rows = (await db.execute(sql `
83
+ SELECT e.from_id, e.to_id, e.kind, e.created_at
84
+ FROM edges e
85
+ JOIN entities f ON f.id = e.from_id
86
+ WHERE f.workspace_id = ${wsId}::uuid
87
+ ${edgeCursor
88
+ ? sql `AND (e.from_id, e.to_id, e.kind) > (${edgeCursor.fromId}::uuid, ${edgeCursor.toId}::uuid, ${edgeCursor.kind})`
89
+ : sql ``}
90
+ ORDER BY e.from_id, e.to_id, e.kind
91
+ LIMIT ${BATCH}
92
+ `)).rows;
93
+ for (const r of rows) {
94
+ yield line("edge", { fromId: r.from_id, toId: r.to_id, kind: r.kind, createdAt: new Date(r.created_at) });
95
+ }
96
+ if (rows.length < BATCH)
97
+ break;
98
+ const last = rows[rows.length - 1];
99
+ edgeCursor = { fromId: last.from_id, toId: last.to_id, kind: last.kind };
100
+ }
101
+ for await (const rows of pages((after) => db
102
+ .select()
103
+ .from(recurrenceRules)
104
+ .where(and(eq(recurrenceRules.workspaceId, wsId), after ? gt(recurrenceRules.id, after) : undefined))
105
+ .orderBy(asc(recurrenceRules.id))
106
+ .limit(BATCH), (r) => r.id)) {
107
+ for (const { workspaceId: _ws, ...r } of rows)
108
+ yield line("recurrence_rule", r);
109
+ }
110
+ for await (const rows of pages(async (after) => (await db
111
+ .select({ ex: recurrenceExceptions })
112
+ .from(recurrenceExceptions)
113
+ .innerJoin(recurrenceRules, eq(recurrenceRules.id, recurrenceExceptions.ruleId))
114
+ .where(and(eq(recurrenceRules.workspaceId, wsId), after ? gt(recurrenceExceptions.id, after) : undefined))
115
+ .orderBy(asc(recurrenceExceptions.id))
116
+ .limit(BATCH)).map((r) => r.ex), (r) => r.id)) {
117
+ for (const r of rows)
118
+ yield line("recurrence_exception", r);
119
+ }
120
+ for await (const rows of pages(async (after) => (await db
121
+ .select({ rev: entityRevisions })
122
+ .from(entityRevisions)
123
+ .innerJoin(entities, eq(entities.id, entityRevisions.entityId))
124
+ .where(and(eq(entities.workspaceId, wsId), after ? gt(entityRevisions.id, after) : undefined))
125
+ .orderBy(asc(entityRevisions.id))
126
+ .limit(BATCH)).map((r) => r.rev), (r) => r.id)) {
127
+ for (const r of rows)
128
+ yield line("entity_revision", r);
129
+ }
130
+ const [settings] = await db
131
+ .select({ timezone: workspaceSettings.timezone })
132
+ .from(workspaceSettings)
133
+ .where(eq(workspaceSettings.workspaceId, wsId))
134
+ .limit(1);
135
+ if (settings)
136
+ yield line("settings", { timezone: settings.timezone });
137
+ }
138
+ // ----- import -----
139
+ const Iso = z.coerce.date();
140
+ const IsoNull = z.coerce.date().nullable().default(null);
141
+ const UuidNull = Uuid.nullable().default(null);
142
+ const HeaderRecord = z.object({
143
+ type: z.literal("header"),
144
+ formatVersion: z.number().int().positive(),
145
+ botnoteVersion: z.string().default("unknown"),
146
+ exportedAt: z.string().default(""),
147
+ workspace: z
148
+ .object({ id: z.string(), slug: z.string().default(""), name: z.string().default("") })
149
+ .default({ id: "", slug: "", name: "" }),
150
+ includesVectors: z.boolean().default(false)
151
+ });
152
+ const ProjectRecord = z.object({
153
+ id: Uuid,
154
+ key: z.string().min(1),
155
+ name: z.string().default(""),
156
+ status: z.string().default("active"),
157
+ color: z.string().default("#5e6ad2"),
158
+ icon: z.string().default("circle"),
159
+ agentsMd: z.string().default(""),
160
+ archivedAt: IsoNull,
161
+ nextSeq: z.number().int().min(1).default(1),
162
+ createdAt: Iso,
163
+ updatedAt: Iso
164
+ });
165
+ const EntityRecord = z.object({
166
+ id: Uuid,
167
+ projectId: UuidNull,
168
+ kind: z.enum(ENTITY_KINDS),
169
+ title: z.string().nullable().default(null),
170
+ body: z.string().default(""),
171
+ tags: z.array(z.string()).default([]),
172
+ status: z.string().default("open"),
173
+ actorKind: z.enum(ACTOR_KINDS).default("human"),
174
+ actorTokenId: UuidNull,
175
+ idempotencyKey: z.string().nullable().default(null),
176
+ parentId: UuidNull,
177
+ bodyVec: z.array(z.number()).nullable().optional(),
178
+ metadata: z.record(z.unknown()).default({}),
179
+ dueAt: IsoNull,
180
+ priority: z.string().default("none"),
181
+ sequenceId: z.number().int().nullable().default(null),
182
+ pinned: z.boolean().default(false),
183
+ completedAt: IsoNull,
184
+ lastAccessedAt: IsoNull,
185
+ accessCount: z.number().int().default(0),
186
+ deletedAt: IsoNull,
187
+ createdAt: Iso,
188
+ updatedAt: Iso
189
+ });
190
+ const EdgeRecord = z.object({
191
+ fromId: Uuid,
192
+ toId: Uuid,
193
+ kind: z.enum(EDGE_KINDS),
194
+ createdAt: Iso
195
+ });
196
+ const RuleRecord = z.object({
197
+ id: Uuid,
198
+ seriesId: Uuid,
199
+ currentOccurrenceId: UuidNull,
200
+ enabled: z.boolean().default(true),
201
+ rrule: z.string().min(1),
202
+ dtstart: Iso,
203
+ timezone: z.string().default("UTC"),
204
+ allDay: z.boolean().default(true),
205
+ anchor: z.string().default("scheduled"),
206
+ maxInstancesAhead: z.number().int().default(1),
207
+ generatedCount: z.number().int().default(1),
208
+ lastOccurrenceAt: IsoNull,
209
+ nextOccurrenceAt: IsoNull,
210
+ endedAt: IsoNull,
211
+ createdAt: Iso,
212
+ updatedAt: Iso
213
+ });
214
+ const ExceptionRecord = z.object({
215
+ id: Uuid,
216
+ ruleId: Uuid,
217
+ occurrenceAt: Iso,
218
+ action: z.string(),
219
+ entityId: UuidNull,
220
+ metadata: z.record(z.unknown()).default({}),
221
+ createdAt: Iso
222
+ });
223
+ const RevisionRecord = z.object({
224
+ id: Uuid,
225
+ entityId: Uuid,
226
+ revision: z.number().int().positive(),
227
+ title: z.string().nullable().default(null),
228
+ body: z.string().default(""),
229
+ tags: z.array(z.string()).default([]),
230
+ priority: z.string().default("none"),
231
+ status: z.string().default("open"),
232
+ actorKind: z.enum(ACTOR_KINDS).default("human"),
233
+ actorTokenId: UuidNull,
234
+ createdAt: Iso
235
+ });
236
+ const SettingsRecord = z.object({
237
+ timezone: z.string().min(1).max(80)
238
+ });
239
+ async function existingRows(db, table, ids) {
240
+ if (ids.length === 0)
241
+ return new Map();
242
+ const rows = (await db.execute(sql `
243
+ SELECT id::text AS id, workspace_id::text AS ws
244
+ FROM ${sql.identifier(table)}
245
+ WHERE id IN (${sql.join(ids.map((id) => sql `${id}::uuid`), sql `, `)})
246
+ `)).rows;
247
+ return new Map(rows.map((r) => [r.id, r.ws]));
248
+ }
249
+ async function existingIds(db, table, ids) {
250
+ if (ids.length === 0)
251
+ return new Set();
252
+ const rows = (await db.execute(sql `
253
+ SELECT id::text AS id FROM ${sql.identifier(table)}
254
+ WHERE id IN (${sql.join(ids.map((id) => sql `${id}::uuid`), sql `, `)})
255
+ `)).rows;
256
+ return new Set(rows.map((r) => r.id));
257
+ }
258
+ async function entityIdsInScope(scope, db, ids) {
259
+ const unique = [...new Set(ids)];
260
+ if (unique.length === 0)
261
+ return new Set();
262
+ const rows = await db
263
+ .select({ id: entities.id })
264
+ .from(entities)
265
+ .where(and(eq(entities.workspaceId, scope.workspaceId), inArray(entities.id, unique)));
266
+ return new Set(rows.map((r) => r.id));
267
+ }
268
+ async function tokenIdsInScope(scope, db, ids) {
269
+ const unique = [...new Set(ids.filter((id) => Boolean(id)))];
270
+ if (unique.length === 0)
271
+ return new Set();
272
+ const rows = await db
273
+ .select({ id: tokens.id })
274
+ .from(tokens)
275
+ .where(and(eq(tokens.workspaceId, scope.workspaceId), inArray(tokens.id, unique)));
276
+ return new Set(rows.map((r) => r.id));
277
+ }
278
+ class Importer {
279
+ scope;
280
+ db;
281
+ counts = Object.fromEntries(RECORD_TYPES.map((t) => [t, { imported: 0, skipped: 0, conflicts: 0 }]));
282
+ conflicts = [];
283
+ conflictsTotal = 0;
284
+ entitiesWithoutVector = 0;
285
+ importedProjectStamps = new Map();
286
+ constructor(scope, db) {
287
+ this.scope = scope;
288
+ this.db = db;
289
+ }
290
+ conflict(type, id, reason) {
291
+ this.counts[type].conflicts++;
292
+ this.conflictsTotal++;
293
+ if (this.conflicts.length < MAX_REPORTED_CONFLICTS)
294
+ this.conflicts.push({ type, id, reason });
295
+ }
296
+ /** Rows that exist in this workspace are skipped; rows owned elsewhere are conflicts. */
297
+ async partitionExisting(type, table, rows) {
298
+ const existing = await existingRows(this.db, table, rows.map((r) => r.id));
299
+ return rows.filter((r) => {
300
+ const ws = existing.get(r.id);
301
+ if (ws === undefined)
302
+ return true;
303
+ if (ws === this.scope.workspaceId)
304
+ this.counts[type].skipped++;
305
+ else
306
+ this.conflict(type, r.id, "id already exists in another workspace");
307
+ return false;
308
+ });
309
+ }
310
+ settle(type, attempted, inserted, reason) {
311
+ for (const id of attempted) {
312
+ if (inserted.has(id))
313
+ this.counts[type].imported++;
314
+ else
315
+ this.conflict(type, id, reason);
316
+ }
317
+ }
318
+ async projects(rows) {
319
+ let fresh = await this.partitionExisting("project", "projects", rows);
320
+ if (fresh.length === 0)
321
+ return;
322
+ const taken = await this.db
323
+ .select({ id: projects.id, key: projects.key })
324
+ .from(projects)
325
+ .where(and(eq(projects.workspaceId, this.scope.workspaceId), inArray(projects.key, fresh.map((p) => p.key))));
326
+ const takenKeys = new Map(taken.map((p) => [p.key, p.id]));
327
+ fresh = fresh.filter((p) => {
328
+ const owner = takenKeys.get(p.key);
329
+ if (!owner)
330
+ return true;
331
+ this.conflict("project", p.id, `key ${p.key} already belongs to project ${owner}`);
332
+ return false;
333
+ });
334
+ if (fresh.length === 0)
335
+ return;
336
+ const inserted = await this.db
337
+ .insert(projects)
338
+ .values(fresh.map((p) => ({ ...p, workspaceId: this.scope.workspaceId })))
339
+ .onConflictDoNothing()
340
+ .returning({ id: projects.id });
341
+ const insertedIds = new Set(inserted.map((r) => r.id));
342
+ for (const p of fresh)
343
+ if (insertedIds.has(p.id))
344
+ this.importedProjectStamps.set(p.id, p.updatedAt);
345
+ this.settle("project", fresh.map((p) => p.id), insertedIds, "rejected by a unique constraint");
346
+ }
347
+ /**
348
+ * The KEY-SEQ trigger bumps projects.next_seq for every imported entity,
349
+ * and that UPDATE stamps updated_at. Put the exported timestamps back.
350
+ */
351
+ async finish() {
352
+ const stamps = [...this.importedProjectStamps];
353
+ for (let i = 0; i < stamps.length; i += BATCH) {
354
+ const chunk = stamps.slice(i, i + BATCH);
355
+ await this.db.execute(sql `
356
+ UPDATE projects p
357
+ SET updated_at = v.ts
358
+ FROM (VALUES ${sql.join(chunk.map(([id, ts]) => sql `(${id}::uuid, ${ts.toISOString()}::timestamptz)`), sql `, `)}) AS v(id, ts)
359
+ WHERE p.id = v.id AND p.updated_at <> v.ts
360
+ `);
361
+ }
362
+ }
363
+ async entities(rows) {
364
+ let fresh = await this.partitionExisting("entity", "entities", rows);
365
+ if (fresh.length === 0)
366
+ return;
367
+ const projectIds = [...new Set(fresh.map((e) => e.projectId).filter((id) => Boolean(id)))];
368
+ const knownProjects = new Set(projectIds.length === 0
369
+ ? []
370
+ : (await this.db
371
+ .select({ id: projects.id })
372
+ .from(projects)
373
+ .where(and(eq(projects.workspaceId, this.scope.workspaceId), inArray(projects.id, projectIds)))).map((p) => p.id));
374
+ fresh = fresh.filter((e) => {
375
+ if (!e.projectId || knownProjects.has(e.projectId))
376
+ return true;
377
+ this.conflict("entity", e.id, `project ${e.projectId} is not in the target workspace`);
378
+ return false;
379
+ });
380
+ if (fresh.length === 0)
381
+ return;
382
+ const knownTokens = await tokenIdsInScope(this.scope, this.db, fresh.map((e) => e.actorTokenId));
383
+ const values = fresh.map(({ bodyVec, ...e }) => {
384
+ const vec = bodyVec && bodyVec.length === VECTOR_DIMENSIONS ? bodyVec : null;
385
+ if (!vec)
386
+ this.entitiesWithoutVector++;
387
+ return {
388
+ ...e,
389
+ workspaceId: this.scope.workspaceId,
390
+ actorTokenId: e.actorTokenId && knownTokens.has(e.actorTokenId) ? e.actorTokenId : null,
391
+ bodyVec: vec
392
+ };
393
+ });
394
+ const inserted = await this.db
395
+ .insert(entities)
396
+ .values(values)
397
+ .onConflictDoNothing()
398
+ .returning({ id: entities.id });
399
+ const insertedIds = new Set(inserted.map((r) => r.id));
400
+ this.entitiesWithoutVector -= values.filter((v) => !v.bodyVec && !insertedIds.has(v.id)).length;
401
+ this.settle("entity", fresh.map((e) => e.id), insertedIds, "rejected by a unique constraint (idempotency key or KEY-SEQ already taken)");
402
+ }
403
+ async edges(rows) {
404
+ const known = await entityIdsInScope(this.scope, this.db, rows.flatMap((e) => [e.fromId, e.toId]));
405
+ const fresh = rows.filter((e) => {
406
+ if (known.has(e.fromId) && known.has(e.toId))
407
+ return true;
408
+ this.conflict("edge", `${e.fromId}->${e.toId}:${e.kind}`, "an endpoint is not in the target workspace");
409
+ return false;
410
+ });
411
+ if (fresh.length === 0)
412
+ return;
413
+ const inserted = await this.db
414
+ .insert(edges)
415
+ .values(fresh)
416
+ .onConflictDoNothing()
417
+ .returning({ fromId: edges.fromId, toId: edges.toId, kind: edges.kind });
418
+ this.counts.edge.imported += inserted.length;
419
+ this.counts.edge.skipped += fresh.length - inserted.length;
420
+ }
421
+ async rules(rows) {
422
+ let fresh = await this.partitionExisting("recurrence_rule", "recurrence_rules", rows);
423
+ if (fresh.length === 0)
424
+ return;
425
+ const known = await entityIdsInScope(this.scope, this.db, fresh.flatMap((r) => [r.seriesId, ...(r.currentOccurrenceId ? [r.currentOccurrenceId] : [])]));
426
+ fresh = fresh.filter((r) => {
427
+ if (known.has(r.seriesId))
428
+ return true;
429
+ this.conflict("recurrence_rule", r.id, `series task ${r.seriesId} is not in the target workspace`);
430
+ return false;
431
+ });
432
+ if (fresh.length === 0)
433
+ return;
434
+ const inserted = await this.db
435
+ .insert(recurrenceRules)
436
+ .values(fresh.map((r) => ({
437
+ ...r,
438
+ workspaceId: this.scope.workspaceId,
439
+ currentOccurrenceId: r.currentOccurrenceId && known.has(r.currentOccurrenceId) ? r.currentOccurrenceId : null
440
+ })))
441
+ .onConflictDoNothing()
442
+ .returning({ id: recurrenceRules.id });
443
+ this.settle("recurrence_rule", fresh.map((r) => r.id), new Set(inserted.map((r) => r.id)), "series already has an enabled rule");
444
+ }
445
+ async exceptions(rows) {
446
+ const existing = await existingIds(this.db, "recurrence_exceptions", rows.map((r) => r.id));
447
+ let fresh = rows.filter((r) => {
448
+ if (!existing.has(r.id))
449
+ return true;
450
+ this.counts.recurrence_exception.skipped++;
451
+ return false;
452
+ });
453
+ if (fresh.length === 0)
454
+ return;
455
+ const ruleIds = [...new Set(fresh.map((r) => r.ruleId))];
456
+ const knownRules = new Set((await this.db
457
+ .select({ id: recurrenceRules.id })
458
+ .from(recurrenceRules)
459
+ .where(and(eq(recurrenceRules.workspaceId, this.scope.workspaceId), inArray(recurrenceRules.id, ruleIds)))).map((r) => r.id));
460
+ fresh = fresh.filter((r) => {
461
+ if (knownRules.has(r.ruleId))
462
+ return true;
463
+ this.conflict("recurrence_exception", r.id, `rule ${r.ruleId} is not in the target workspace`);
464
+ return false;
465
+ });
466
+ if (fresh.length === 0)
467
+ return;
468
+ const knownEntities = await entityIdsInScope(this.scope, this.db, fresh.map((r) => r.entityId).filter((id) => Boolean(id)));
469
+ const inserted = await this.db
470
+ .insert(recurrenceExceptions)
471
+ .values(fresh.map((r) => ({
472
+ ...r,
473
+ entityId: r.entityId && knownEntities.has(r.entityId) ? r.entityId : null
474
+ })))
475
+ .onConflictDoNothing()
476
+ .returning({ id: recurrenceExceptions.id });
477
+ this.settle("recurrence_exception", fresh.map((r) => r.id), new Set(inserted.map((r) => r.id)), "rejected by a unique constraint");
478
+ }
479
+ async revisions(rows) {
480
+ const existing = await existingIds(this.db, "entity_revisions", rows.map((r) => r.id));
481
+ let fresh = rows.filter((r) => {
482
+ if (!existing.has(r.id))
483
+ return true;
484
+ this.counts.entity_revision.skipped++;
485
+ return false;
486
+ });
487
+ if (fresh.length === 0)
488
+ return;
489
+ const known = await entityIdsInScope(this.scope, this.db, fresh.map((r) => r.entityId));
490
+ fresh = fresh.filter((r) => {
491
+ if (known.has(r.entityId))
492
+ return true;
493
+ this.conflict("entity_revision", r.id, `entity ${r.entityId} is not in the target workspace`);
494
+ return false;
495
+ });
496
+ if (fresh.length === 0)
497
+ return;
498
+ const knownTokens = await tokenIdsInScope(this.scope, this.db, fresh.map((r) => r.actorTokenId));
499
+ const inserted = await this.db
500
+ .insert(entityRevisions)
501
+ .values(fresh.map((r) => ({
502
+ ...r,
503
+ actorTokenId: r.actorTokenId && knownTokens.has(r.actorTokenId) ? r.actorTokenId : null
504
+ })))
505
+ .onConflictDoNothing()
506
+ .returning({ id: entityRevisions.id });
507
+ this.settle("entity_revision", fresh.map((r) => r.id), new Set(inserted.map((r) => r.id)), "revision number already taken for that entity");
508
+ }
509
+ async settings(rows) {
510
+ const last = rows[rows.length - 1];
511
+ if (!last)
512
+ return;
513
+ await this.db
514
+ .insert(workspaceSettings)
515
+ .values({ workspaceId: this.scope.workspaceId, timezone: last.timezone })
516
+ .onConflictDoUpdate({
517
+ target: workspaceSettings.workspaceId,
518
+ set: { timezone: last.timezone, updatedAt: new Date() }
519
+ });
520
+ this.counts.settings.imported += rows.length;
521
+ }
522
+ }
523
+ const RECORD_SCHEMAS = {
524
+ project: ProjectRecord,
525
+ entity: EntityRecord,
526
+ edge: EdgeRecord,
527
+ recurrence_rule: RuleRecord,
528
+ recurrence_exception: ExceptionRecord,
529
+ entity_revision: RevisionRecord,
530
+ settings: SettingsRecord
531
+ };
532
+ function parseRecord(type, raw, lineNo) {
533
+ const parsed = RECORD_SCHEMAS[type].safeParse(raw);
534
+ if (!parsed.success) {
535
+ const issue = parsed.error.issues[0];
536
+ throw clientError(`line ${lineNo}: invalid ${type} record${issue ? ` (${issue.path.join(".")}: ${issue.message})` : ""}`, 400);
537
+ }
538
+ return parsed.data;
539
+ }
540
+ /**
541
+ * Import a dump produced by exportWorkspace into `scope`. Idempotent: rows
542
+ * whose id already exists here are skipped, so a partial import can simply be
543
+ * re-run. Rows owned by another workspace, or whose parent row is missing,
544
+ * are reported as conflicts and left out rather than aborting the import.
545
+ */
546
+ export async function importWorkspace(scope, db, lines) {
547
+ const importer = new Importer(scope, db);
548
+ let header = null;
549
+ let lineNo = 0;
550
+ let bufferType = null;
551
+ let buffer = [];
552
+ const flush = async () => {
553
+ if (!bufferType || buffer.length === 0)
554
+ return;
555
+ const rows = buffer;
556
+ switch (bufferType) {
557
+ case "project":
558
+ await importer.projects(rows);
559
+ break;
560
+ case "entity":
561
+ await importer.entities(rows);
562
+ break;
563
+ case "edge":
564
+ await importer.edges(rows);
565
+ break;
566
+ case "recurrence_rule":
567
+ await importer.rules(rows);
568
+ break;
569
+ case "recurrence_exception":
570
+ await importer.exceptions(rows);
571
+ break;
572
+ case "entity_revision":
573
+ await importer.revisions(rows);
574
+ break;
575
+ case "settings":
576
+ await importer.settings(rows);
577
+ break;
578
+ }
579
+ buffer = [];
580
+ };
581
+ for await (const rawLine of lines) {
582
+ lineNo++;
583
+ const text = rawLine.trim();
584
+ if (!text)
585
+ continue;
586
+ let raw;
587
+ try {
588
+ raw = JSON.parse(text);
589
+ }
590
+ catch {
591
+ throw clientError(`line ${lineNo}: not valid JSON`, 400);
592
+ }
593
+ if (!header) {
594
+ const parsed = HeaderRecord.safeParse(raw);
595
+ if (!parsed.success)
596
+ throw clientError("line 1 must be the export header", 400);
597
+ if (parsed.data.formatVersion > FORMAT_VERSION) {
598
+ throw clientError(`dump uses formatVersion ${parsed.data.formatVersion}; this botnote reads up to ${FORMAT_VERSION}`, 400);
599
+ }
600
+ header = parsed.data;
601
+ continue;
602
+ }
603
+ const type = raw?.type;
604
+ if (typeof type !== "string" || !RECORD_TYPES.includes(type)) {
605
+ throw clientError(`line ${lineNo}: unknown record type ${JSON.stringify(type)}`, 400);
606
+ }
607
+ const record = parseRecord(type, raw, lineNo);
608
+ if (bufferType !== type || buffer.length >= BATCH) {
609
+ await flush();
610
+ bufferType = type;
611
+ }
612
+ buffer.push(record);
613
+ }
614
+ await flush();
615
+ if (!header)
616
+ throw clientError("empty dump: expected a header line", 400);
617
+ await importer.finish();
618
+ return {
619
+ formatVersion: header.formatVersion,
620
+ botnoteVersion: header.botnoteVersion,
621
+ exportedAt: header.exportedAt,
622
+ sourceWorkspace: header.workspace,
623
+ counts: importer.counts,
624
+ conflicts: importer.conflicts,
625
+ conflictsTotal: importer.conflictsTotal,
626
+ entitiesWithoutVector: importer.entitiesWithoutVector
627
+ };
628
+ }
629
+ //# sourceMappingURL=transfer.js.map