@wirecat/cli-core 0.719.0 → 0.721.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/dist/attachments/documents.d.ts +5 -0
  3. package/dist/attachments/documents.js +2 -2
  4. package/dist/background/daily-archive-timer.d.ts +1 -1
  5. package/dist/cli/config-command.js +8 -2
  6. package/dist/cli/config-issues.d.ts +3 -1
  7. package/dist/cli/config-issues.js +9 -2
  8. package/dist/cli/documents/file-conflicts.d.ts +25 -0
  9. package/dist/cli/documents/file-conflicts.js +102 -0
  10. package/dist/cli/documents/file-edit.d.ts +29 -0
  11. package/dist/cli/documents/file-edit.js +352 -0
  12. package/dist/cli/documents/file-update.d.ts +43 -0
  13. package/dist/cli/documents/file-update.js +95 -0
  14. package/dist/cli/documents/history.d.ts +34 -0
  15. package/dist/cli/documents/history.js +89 -0
  16. package/dist/cli/documents/index.d.ts +9 -2
  17. package/dist/cli/documents/index.js +9 -2
  18. package/dist/cli/documents/library.js +10 -0
  19. package/dist/cli/permission-keys.d.ts +6 -0
  20. package/dist/cli/permission-keys.js +15 -3
  21. package/dist/cli/service-api.d.ts +1 -1
  22. package/dist/cli/service-api.js +16 -34
  23. package/dist/documents/file-mirror-model.d.ts +32 -1
  24. package/dist/documents/index.d.ts +7 -4
  25. package/dist/documents/index.js +4 -1
  26. package/dist/documents/model.d.ts +16 -1
  27. package/dist/errors/reasons.js +6 -1
  28. package/dist/office/docx.d.ts +43 -0
  29. package/dist/office/docx.js +349 -0
  30. package/dist/office/index.d.ts +2 -0
  31. package/dist/office/index.js +2 -0
  32. package/dist/office/package.d.ts +39 -0
  33. package/dist/office/package.js +98 -0
  34. package/dist/office/xlsx.d.ts +55 -0
  35. package/dist/office/xlsx.js +550 -0
  36. package/dist/office/xml.d.ts +34 -0
  37. package/dist/office/xml.js +186 -0
  38. package/dist/office/zip.d.ts +10 -0
  39. package/dist/office/zip.js +116 -0
  40. package/dist/services/documents/block-diff.d.ts +13 -3
  41. package/dist/services/documents/block-diff.js +13 -7
  42. package/dist/services/documents/ingestion.d.ts +21 -2
  43. package/dist/services/documents/ingestion.js +29 -2
  44. package/dist/services/documents/plan.js +16 -7
  45. package/dist/services/documents/ports.d.ts +2 -0
  46. package/dist/services/documents/sync.d.ts +1 -0
  47. package/dist/services/documents/sync.js +9 -4
  48. package/dist/services/files/conflicts.d.ts +78 -0
  49. package/dist/services/files/conflicts.js +183 -0
  50. package/dist/services/files/guarded-write.d.ts +34 -0
  51. package/dist/services/files/guarded-write.js +42 -0
  52. package/dist/services/files/listing.d.ts +36 -0
  53. package/dist/services/files/listing.js +47 -0
  54. package/dist/services/files/local-files.d.ts +54 -0
  55. package/dist/services/files/local-files.js +143 -0
  56. package/dist/services/files/mirror-state.d.ts +14 -0
  57. package/dist/services/files/mirror-state.js +65 -0
  58. package/dist/services/files/mirror.d.ts +4 -14
  59. package/dist/services/files/mirror.js +177 -204
  60. package/dist/services/files/text-merge.d.ts +27 -0
  61. package/dist/services/files/text-merge.js +134 -0
  62. package/dist/services/files/versions.d.ts +36 -9
  63. package/dist/services/files/versions.js +40 -12
  64. package/dist/store/index.d.ts +2 -0
  65. package/dist/store/index.js +1 -0
  66. package/dist/store/people.d.ts +8 -0
  67. package/dist/store/people.js +2 -0
  68. package/dist/store/sqlite/account-purge.js +3 -0
  69. package/dist/store/sqlite/document-history.d.ts +84 -0
  70. package/dist/store/sqlite/document-history.js +158 -0
  71. package/dist/store/sqlite/manifest.js +2 -0
  72. package/dist/store/sqlite/migrations.generated.js +17 -0
  73. package/dist/store/sqlite/notes.d.ts +9 -10
  74. package/dist/store/sqlite/notes.js +33 -21
  75. package/dist/store/sqlite/person-erase.d.ts +39 -0
  76. package/dist/store/sqlite/person-erase.js +152 -0
  77. package/dist/store/sqlite/schema/document-changes.d.ts +136 -0
  78. package/dist/store/sqlite/schema/document-changes.js +11 -0
  79. package/dist/store/sqlite/schema.d.ts +65 -0
  80. package/dist/store/sqlite/schema.js +5 -0
  81. package/package.json +6 -2
@@ -140,6 +140,8 @@ export const MANIFEST = [
140
140
  { name: "20261117211414_version-70-tracker-item-words", version: 70, minCompatible: 56 },
141
141
  { name: "20261118230213_version-71-content", version: 71, minCompatible: 56 },
142
142
  { name: "20261118230214_version-71-content-words", version: 71, minCompatible: 56 },
143
+ { name: "20261123022342_version-72-document-history", version: 72, minCompatible: 56 },
144
+ { name: "20261123022347_version-72-document-changes-trigger", version: 72, minCompatible: 56 },
143
145
  ];
144
146
  export const generatedMigrations = (manifest = MANIFEST, generated = GENERATED) => {
145
147
  const migrations = [];
@@ -1424,5 +1424,22 @@ export const GENERATED = [
1424
1424
  "CREATE TRIGGER content_post_words_au AFTER UPDATE OF normalized_text ON content_posts\n WHEN old.normalized_text IS NOT new.normalized_text BEGIN\n DELETE FROM content_post_words WHERE rowid = old.id;\n INSERT INTO content_post_words (rowid, normalized_text)\n SELECT new.id, new.normalized_text WHERE new.normalized_text <> '';\nEND;",
1425
1425
  "-- Taggings are polymorphic, with no foreign key: a post row that goes takes its tags along.\nCREATE TRIGGER content_post_words_ad AFTER DELETE ON content_posts BEGIN\n DELETE FROM content_post_words WHERE rowid = old.id;\n DELETE FROM taggings WHERE taggable_type = 'post' AND taggable_id = old.id;\nEND;"
1426
1426
  ]
1427
+ },
1428
+ {
1429
+ "name": "20261123022342_version-72-document-history",
1430
+ "statements": [
1431
+ "CREATE TABLE `document_changes` (\n\t`id` integer PRIMARY KEY,\n\t`account_id` integer NOT NULL,\n\t`document_id` integer NOT NULL,\n\t`path` text NOT NULL,\n\t`title` text,\n\t`event` text NOT NULL,\n\t`revision` integer NOT NULL,\n\t`at` integer NOT NULL\n);",
1432
+ "ALTER TABLE `document_revisions` ADD `title` text;",
1433
+ "ALTER TABLE `document_revisions` ADD `front_matter` text;",
1434
+ "ALTER TABLE `document_revisions` ADD `reason` text;",
1435
+ "ALTER TABLE `documents` ADD `removal` text;",
1436
+ "CREATE INDEX `document_changes_by_account_id_at` ON `document_changes` (`account_id`,`at`);"
1437
+ ]
1438
+ },
1439
+ {
1440
+ "name": "20261123022347_version-72-document-changes-trigger",
1441
+ "statements": [
1442
+ "-- No foreign key on the change log, so an older build that purges an account still can; this drops its rows with it.\nCREATE TRIGGER document_changes_account_bd BEFORE DELETE ON accounts BEGIN\n DELETE FROM document_changes WHERE account_id = old.id;\nEND;"
1443
+ ]
1427
1444
  }
1428
1445
  ];
@@ -3,6 +3,8 @@ import type { Section } from "../../readers/types.js";
3
3
  import { type Decider } from "../decisions.js";
4
4
  import type { CacheDatabase } from "../driver.js";
5
5
  import type { AddedSources } from "./added-sources.js";
6
+ import type { DocumentHistoryStore, DocumentRemoval } from "./document-history.js";
7
+ import { keepRevision } from "./document-history.js";
6
8
  import { type DocumentMetadata } from "./document-metadata.js";
7
9
  import { type ImportedDocuments } from "./imported-documents.js";
8
10
  import { LINK_KINDS, LINK_ORIGINS, type LINK_SOURCES } from "./link-kinds.js";
@@ -117,7 +119,7 @@ export interface MessageDocument {
117
119
  reference: string;
118
120
  fileId: string;
119
121
  }
120
- export interface NotesStore extends NoteSearch, ImportedDocuments, AddedSources {
122
+ export interface NotesStore extends NoteSearch, ImportedDocuments, AddedSources, DocumentHistoryStore {
121
123
  addFolder(input: {
122
124
  name: string;
123
125
  format?: NoteFolder["format"];
@@ -145,8 +147,11 @@ export interface NotesStore extends NoteSearch, ImportedDocuments, AddedSources
145
147
  path: string;
146
148
  modifiedAt: string;
147
149
  }[]): Promise<number>;
148
- /** Marks the folder's notes at these paths deleted; answers how many were live. */
149
- deleteFileNotes(folderId: string, paths: string[]): Promise<number>;
150
+ /**
151
+ * Takes the folder's notes at these paths out of the live copy; answers how many were live. `deleted` (the default)
152
+ * and `unsynced` keep the last text as a version and blank it; `unavailable` keeps the text on the document.
153
+ */
154
+ deleteFileNotes(folderId: string, paths: string[], reason?: DocumentRemoval): Promise<number>;
150
155
  /** A note about the things named, the first of them its subject; about nothing, a note to self. */
151
156
  addNote(input: {
152
157
  text: string;
@@ -205,13 +210,7 @@ export interface NotesStore extends NoteSearch, ImportedDocuments, AddedSources
205
210
  type Row = Record<string, unknown>;
206
211
  /** What a link's written target is matched by: case, accents and a leading `@` do not count. */
207
212
  export declare const targetKey: (text: string) => string;
208
- /**
209
- * Keeps a document's text under its current revision before the caller writes the new text with `revision + 1`, so
210
- * a citation reads back the words it cited and the source check sees the change.
211
- */
212
- export declare const keepRevision: (database: CacheDatabase, row: Row, at: number) => {
213
- changes: number;
214
- };
213
+ export { keepRevision };
215
214
  export declare const documentOf: (row: Row) => Note;
216
215
  export declare const noteOf: (row: Row, database: CacheDatabase) => Note;
217
216
  /** A document or note row by its typed reference, or `undefined`. */
@@ -9,6 +9,7 @@ import { assertMayWithdraw } from "../decisions.js";
9
9
  import { fold } from "../normalize.js";
10
10
  import { ulid } from "../ulid.js";
11
11
  import { ownerPerson } from "./actors.js";
12
+ import { documentHistoryOver, keepRevision, logDocumentChange, removeDocument } from "./document-history.js";
12
13
  import { encodeDocumentMetadata, languageOf } from "./document-metadata.js";
13
14
  import { deleteDocumentRow, forgetEvidenceToRow } from "./evidence-signature.js";
14
15
  import { fileNoteRow } from "./file-note.js";
@@ -33,13 +34,7 @@ const iso = (value) => new Date(Number(value)).toISOString();
33
34
  const optionalIso = (value) => (value == null ? null : iso(value));
34
35
  /** What a link's written target is matched by: case, accents and a leading `@` do not count. */
35
36
  export const targetKey = (text) => fold(text).trim().replace(/^@/, "");
36
- /**
37
- * Keeps a document's text under its current revision before the caller writes the new text with `revision + 1`, so
38
- * a citation reads back the words it cited and the source check sees the change.
39
- */
40
- export const keepRevision = (database, row, at) => database
41
- .prepare("INSERT INTO document_revisions (document_id, body, revision, created_at) VALUES (?, ?, ?, ?)")
42
- .run(Number(row.id), String(row.body ?? ""), Number(row.revision), at);
37
+ export { keepRevision };
43
38
  export const documentOf = (row) => ({
44
39
  id: String(row.id),
45
40
  ref: `document:${row.id}`,
@@ -345,6 +340,7 @@ export const notesStoreOver = (context) => {
345
340
  path,
346
341
  });
347
342
  return {
343
+ ...documentHistoryOver(context),
348
344
  addFolder: async ({ name, format = "obsidian" }) => {
349
345
  const at = now();
350
346
  const checked = oneOf(format, NOTE_FORMATS, "a folder's format");
@@ -394,10 +390,12 @@ export const notesStoreOver = (context) => {
394
390
  if (candidates.length === 1) {
395
391
  const id = candidates[0];
396
392
  const joined = documentRow(String(id));
397
- if (joined.deleted_at != null)
393
+ if (joined.deleted_at != null) {
398
394
  database
399
- .prepare("UPDATE documents SET deleted_at = NULL, body = ?, updated_at = ? WHERE id = ?")
395
+ .prepare("UPDATE documents SET deleted_at = NULL, removal = NULL, body = ?, updated_at = ? WHERE id = ?")
400
396
  .run(text, at, id);
397
+ logDocumentChange(database, id, "restored", at);
398
+ }
401
399
  syncFile(database, at, id, { place: here, method: "content-hash" });
402
400
  followPreferred(id, at);
403
401
  return { note: noteAt(id, folder, path), changed: true };
@@ -415,6 +413,7 @@ export const notesStoreOver = (context) => {
415
413
  "VALUES (?, ?, 'file', ?, ?, ?, ?, 'local', ?, ?, ?, 'text', ?, ?, 1, ?, ?) RETURNING id")
416
414
  .get(folder, path, title, location, fileName, extension, hash, frontMatter, text, metadata, language, at, at);
417
415
  const id = Number(row?.id);
416
+ logDocumentChange(database, id, "added", at);
418
417
  const file = syncFile(database, at, id);
419
418
  if (candidates.length > 1 && file)
420
419
  reviewLink(database, { type: "file", id: file.id }, "document", candidates, "content-hash", at);
@@ -432,12 +431,25 @@ export const notesStoreOver = (context) => {
432
431
  (found.content_hash ?? null) === hash &&
433
432
  found.deleted_at == null;
434
433
  if (!same) {
435
- if ((found.body ?? "") !== text)
434
+ const back = found.deleted_at != null;
435
+ // A catalog entry has no text until its first read: that read adds the document.
436
+ const unread = found.body == null;
437
+ const revised = (found.body ?? "") !== text ||
438
+ (found.title ?? null) !== title ||
439
+ (found.front_matter ?? null) !== keptFrontMatter;
440
+ // A removed document whose last text was already kept holds only a blank body.
441
+ if (revised && !unread && !(back && (found.body ?? "") === ""))
436
442
  keepRevision(database, found, at);
437
443
  database
438
444
  .prepare("UPDATE documents SET title = ?, body = ?, front_matter = ?, content_hash = ?, metadata = ?, language = ?, " +
439
- "revision = revision + ?, updated_at = ?, deleted_at = NULL WHERE id = ?")
440
- .run(title, text, keptFrontMatter, hash, keptMetadata, language, (found.body ?? "") === text ? 0 : 1, at, id);
445
+ "revision = revision + ?, updated_at = ?, deleted_at = NULL, removal = NULL WHERE id = ?")
446
+ .run(title, text, keptFrontMatter, hash, keptMetadata, language, revised && !unread ? 1 : 0, at, id);
447
+ if (back)
448
+ logDocumentChange(database, id, "restored", at);
449
+ else if (unread)
450
+ logDocumentChange(database, id, "added", at);
451
+ else if (revised)
452
+ logDocumentChange(database, id, "changed", at);
441
453
  }
442
454
  syncFile(database, at, id, own ? {} : { place: here });
443
455
  if (!same)
@@ -491,19 +503,21 @@ export const notesStoreOver = (context) => {
491
503
  return noteAt(id, folder, target);
492
504
  }),
493
505
  dateFileNotes: async (folderId, dates) => write(database, () => dateFileNotes(database, Number(folderRow(folderId, true).id), dates)),
494
- deleteFileNotes: async (folderId, paths) => write(database, () => {
506
+ deleteFileNotes: async (folderId, paths, reason = "deleted") => write(database, () => {
495
507
  const folder = Number(folderRow(folderId, true).id);
496
508
  let deleted = 0;
497
509
  for (const path of paths) {
498
510
  const at = now();
499
511
  const place = fileAt(folder, path, true);
500
512
  if (!place) {
501
- const marked = database
502
- .prepare("UPDATE documents SET deleted_at = ?, body = '' WHERE account_id = ? AND external_id = ? AND deleted_at IS NULL RETURNING id")
503
- .all(at, folder, path);
504
- for (const row of marked)
513
+ const live = database
514
+ .prepare("SELECT id FROM documents WHERE account_id = ? AND external_id = ? AND deleted_at IS NULL")
515
+ .all(folder, path);
516
+ for (const row of live) {
517
+ removeDocument(database, Number(row.id), at, reason);
505
518
  syncFile(database, at, Number(row.id), { seen: false });
506
- deleted += marked.length;
519
+ }
520
+ deleted += live.length;
507
521
  continue;
508
522
  }
509
523
  database.prepare("UPDATE files SET deleted_at = ?, updated_at = ? WHERE id = ?").run(at, at, Number(place.id));
@@ -518,9 +532,7 @@ export const notesStoreOver = (context) => {
518
532
  if (elsewhere)
519
533
  followPreferred(id, at);
520
534
  else
521
- database
522
- .prepare("UPDATE documents SET deleted_at = ?, body = '' WHERE id = ? AND deleted_at IS NULL")
523
- .run(at, id);
535
+ removeDocument(database, id, at, reason);
524
536
  }
525
537
  return deleted;
526
538
  }),
@@ -0,0 +1,39 @@
1
+ import type { Decider } from "../decisions.js";
2
+ import type { CacheDatabase } from "../driver.js";
3
+ import type { StoreContext } from "./open.js";
4
+ export interface PersonErasure {
5
+ person: string;
6
+ name: string | null;
7
+ /** `false`: what `erase` would do, nothing changed. */
8
+ erased: boolean;
9
+ /** Identities that go with the person. */
10
+ identities: string[];
11
+ /**
12
+ * Identities a message, mail, meeting or chat still names: they stay, with no person, and the next sync or people
13
+ * scan gives them one again.
14
+ */
15
+ kept: {
16
+ identity: string;
17
+ references: number;
18
+ }[];
19
+ /** Rows that only tied something to the person, such as a tag, a link or a mention, by `table.column`. */
20
+ deleted: Record<string, number>;
21
+ /** Rows that stay and lose the person, such as a fact about them or a record made into them. */
22
+ detached: Record<string, number>;
23
+ }
24
+ /**
25
+ * Deletes a person and what memo knows of them alone: their identities, the tags, links, aliases and mentions that
26
+ * name them, their involvements. A fact, a note, a record or a task that names them stays and loses the name. A
27
+ * message, mail or meeting is the source's: its sender stays as an identity with no person. Refused for the owner,
28
+ * and while an invoice, order, subscription or a row they wrote cannot be without them. `apply: false` answers the
29
+ * same without changing anything.
30
+ */
31
+ export declare const erasePerson: (context: StoreContext, uid: string, by: Decider, apply: boolean) => PersonErasure;
32
+ /** The people an account's records made into persons: read before a purge deletes the records. */
33
+ export declare const importedPeople: (database: CacheDatabase, accountKey: number) => number[];
34
+ /**
35
+ * After a purge, the people only its records made go too: nothing else names them, and no message, mail or meeting
36
+ * names their identities; their involvements are derived and go with them. One the owner tagged, linked or gave a
37
+ * task to stays.
38
+ */
39
+ export declare const eraseImportedPeople: (context: StoreContext, people: readonly number[]) => void;
@@ -0,0 +1,152 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { OWN, referencesTo } from "./accounts.js";
3
+ import { pointerPairs } from "./entity-types.js";
4
+ import { forgetDanglingEvidence } from "./evidence-signature.js";
5
+ import { forgetErasedLinks } from "./identity-link-rows.js";
6
+ import { forgetErasedSplits } from "./identity-split-proposals.js";
7
+ import { currentPerson } from "./merged-persons.js";
8
+ import { ownerOnly } from "./person-merges.js";
9
+ import { forgetErasedTestData } from "./test-people.js";
10
+ /** Who wrote or approved a row: the row is the writer's history, never silently rewritten. */
11
+ const AUTHORS = new Set(["author", "confirmed_by", "decided_by", "proposed_by", "actor", "closed_by"]);
12
+ /** Business rows that cannot be without the person: the owner moves them first. */
13
+ const blocking = (table, pointer, database) => AUTHORS.has(pointer) || hasChildren(database, table);
14
+ const hasChildren = (database, table) => database
15
+ .prepare(`SELECT 1 FROM sqlite_master m JOIN pragma_foreign_key_list(m.name) f WHERE m.type = 'table' AND f."table" = ?
16
+ LIMIT 1`)
17
+ .get(table) !== undefined;
18
+ const nullable = (database, table, column) => Number(database.prepare(`SELECT "notnull" AS n FROM pragma_table_info('${table}') WHERE name = ?`).get(column)?.n) ===
19
+ 0;
20
+ /** A link is about both ends: one that loses an end means nothing, so it goes. */
21
+ const LINK_ROWS = new Set(["links", "mentions", "task_assignments"]);
22
+ const personOf = (context, uid) => {
23
+ const asked = /^(?:person:)?([1-9]\d*)$/u.exec(uid.trim())?.[1];
24
+ const known = asked === undefined ? undefined : context.database.prepare("SELECT id FROM persons WHERE id = ?").get(Number(asked));
25
+ if (known === undefined)
26
+ throw new CliError("not_found", `the store has no person for "${uid}"`, { reason: "person.unknown" });
27
+ return currentPerson(context.database, Number(known.id));
28
+ };
29
+ const count = (database, sql, ...params) => Number(database.prepare(`SELECT count(*) AS n FROM ${sql}`).get(...params)?.n);
30
+ /**
31
+ * Deletes a person and what memo knows of them alone: their identities, the tags, links, aliases and mentions that
32
+ * name them, their involvements. A fact, a note, a record or a task that names them stays and loses the name. A
33
+ * message, mail or meeting is the source's: its sender stays as an identity with no person. Refused for the owner,
34
+ * and while an invoice, order, subscription or a row they wrote cannot be without them. `apply: false` answers the
35
+ * same without changing anything.
36
+ */
37
+ export const erasePerson = (context, uid, by, apply) => {
38
+ ownerOnly(by, "deletes a person");
39
+ const { database } = context;
40
+ const person = personOf(context, uid);
41
+ const row = database.prepare("SELECT owner, name FROM persons WHERE id = ?").get(person);
42
+ if (Number(row?.owner) === 1)
43
+ throw new CliError("validation_error", "your own person cannot be deleted", { reason: "person.owner" });
44
+ const linked = database
45
+ .prepare(`SELECT i.id AS id, i.provider || ':' || i.external_id AS ref FROM identity_links l
46
+ JOIN identities i ON i.id = l.identity_id WHERE l.person_id = ? ORDER BY i.id`)
47
+ .all(person)
48
+ .map((one) => ({ id: Number(one.id), ref: String(one.ref) }));
49
+ const ids = JSON.stringify(linked.map(({ id }) => id));
50
+ const theirs = "SELECT value FROM json_each(?)";
51
+ const outside = referencesTo(database, "identities", new Set([...OWN, "account_identities", "organization_identities", "involvements"]), theirs);
52
+ const named = new Map();
53
+ for (const one of database
54
+ .prepare(`SELECT id, count(*) AS n FROM (${outside}) GROUP BY id`)
55
+ .all(...refsOf(outside, ids)))
56
+ named.set(Number(one.id), Number(one.n));
57
+ const going = linked.filter(({ id }) => !named.has(id));
58
+ const kept = linked.filter(({ id }) => named.has(id));
59
+ const goingIds = JSON.stringify(going.map(({ id }) => id));
60
+ const deleted = {};
61
+ const detached = {};
62
+ const blocked = [];
63
+ const plan = [];
64
+ const pointing = (type, among, params) => {
65
+ for (const { table, pointer } of pointerPairs(database)) {
66
+ const where = `${pointer}_type = '${type}' AND ${pointer}_id IN (${among})`;
67
+ const n = count(database, `"${table}" WHERE ${where}`, ...params);
68
+ if (n === 0)
69
+ continue;
70
+ const key = `${table}.${pointer}`;
71
+ if (LINK_ROWS.has(table) || !nullable(database, table, `${pointer}_id`)) {
72
+ if (!LINK_ROWS.has(table) && blocking(table, pointer, database)) {
73
+ blocked.push(`${n} ${table} (${pointer})`);
74
+ continue;
75
+ }
76
+ deleted[key] = (deleted[key] ?? 0) + n;
77
+ plan.push(() => database.prepare(`DELETE FROM "${table}" WHERE ${where}`).run(...params));
78
+ }
79
+ else {
80
+ detached[key] = (detached[key] ?? 0) + n;
81
+ plan.push(() => database
82
+ .prepare(`UPDATE "${table}" SET ${pointer}_type = NULL, ${pointer}_id = NULL WHERE ${where}`)
83
+ .run(...params));
84
+ }
85
+ }
86
+ };
87
+ pointing("person", "?", [person]);
88
+ pointing("identity", theirs, [goingIds]);
89
+ const involvements = count(database, `involvements WHERE person_id = ? OR identity_id IN (${theirs})`, person, goingIds);
90
+ if (involvements > 0)
91
+ deleted["involvements.person"] = (deleted["involvements.person"] ?? 0) + involvements;
92
+ const bots = count(database, "bots WHERE owner_person_id = ?", person);
93
+ if (bots > 0)
94
+ detached["bots.owner_person"] = bots;
95
+ if (blocked.length > 0)
96
+ throw new CliError("validation_error", `person:${person} is still named by ${blocked.join(", ")}; change those first — nothing was deleted`, { reason: "person.erase-blocked", blocked });
97
+ const answer = (erased) => ({
98
+ person: `person:${person}`,
99
+ name: row?.name == null ? null : String(row.name),
100
+ erased,
101
+ identities: going.map(({ ref }) => ref),
102
+ kept: kept.map(({ id, ref }) => ({ identity: ref, references: named.get(id) ?? 0 })),
103
+ deleted,
104
+ detached,
105
+ });
106
+ if (!apply)
107
+ return answer(false);
108
+ for (const step of plan)
109
+ step();
110
+ database.prepare(`DELETE FROM involvements WHERE person_id = ? OR identity_id IN (${theirs})`).run(person, goingIds);
111
+ database.prepare("UPDATE bots SET owner_person_id = NULL WHERE owner_person_id = ?").run(person);
112
+ for (const table of ["account_identities", "organization_identities", "identity_revisions"])
113
+ database.prepare(`DELETE FROM ${table} WHERE identity_id IN (${theirs})`).run(goingIds);
114
+ database
115
+ .prepare(`DELETE FROM identity_link_events WHERE to_person_id = ? OR identity_id IN (${theirs})`)
116
+ .run(person, goingIds);
117
+ database.prepare("UPDATE identity_link_events SET from_person_id = NULL WHERE from_person_id = ?").run(person);
118
+ database.prepare("DELETE FROM identity_links WHERE person_id = ?").run(person);
119
+ database.prepare(`DELETE FROM identities WHERE id IN (${theirs})`).run(goingIds);
120
+ database.prepare("DELETE FROM persons WHERE id = ?").run(person);
121
+ forgetErasedLinks(database);
122
+ forgetErasedSplits(database);
123
+ forgetErasedTestData(database);
124
+ forgetDanglingEvidence(database, context.now());
125
+ return answer(true);
126
+ };
127
+ /** `referencesTo` with `among` binds the ids once per arm. */
128
+ const refsOf = (sql, ids) => Array.from({ length: sql.split("json_each(?)").length - 1 }, () => ids);
129
+ /** The people an account's records made into persons: read before a purge deletes the records. */
130
+ export const importedPeople = (database, accountKey) => database
131
+ .prepare("SELECT DISTINCT entity_id AS id FROM records WHERE account_id = ? AND entity_type = 'person'")
132
+ .all(accountKey)
133
+ .map(({ id }) => Number(id));
134
+ /**
135
+ * After a purge, the people only its records made go too: nothing else names them, and no message, mail or meeting
136
+ * names their identities; their involvements are derived and go with them. One the owner tagged, linked or gave a
137
+ * task to stays.
138
+ */
139
+ export const eraseImportedPeople = (context, people) => {
140
+ const { database } = context;
141
+ const others = referencesTo(database, "persons", new Set(["identity_links", "identity_link_events", "involvements"]), "?");
142
+ for (const person of people) {
143
+ if (database.prepare("SELECT 1 FROM persons WHERE id = ? AND owner = 0").get(person) === undefined)
144
+ continue;
145
+ const params = Array.from({ length: others.split("IN (?)").length - 1 }, () => person);
146
+ if (database.prepare(`SELECT 1 FROM (${others}) LIMIT 1`).get(...params) !== undefined)
147
+ continue;
148
+ const plan = erasePerson(context, String(person), "owner", false);
149
+ if (plan.kept.length === 0)
150
+ erasePerson(context, String(person), "owner", true);
151
+ }
152
+ };
@@ -0,0 +1,136 @@
1
+ export declare const documentChanges: import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
2
+ name: "document_changes";
3
+ schema: undefined;
4
+ columns: {
5
+ id: import("drizzle-orm/sqlite-core").SQLiteColumn<{
6
+ name: string;
7
+ tableName: "document_changes";
8
+ dataType: "number int53";
9
+ data: number;
10
+ driverParam: number;
11
+ notNull: true;
12
+ hasDefault: true;
13
+ isPrimaryKey: true;
14
+ isAutoincrement: false;
15
+ hasRuntimeDefault: false;
16
+ enumValues: undefined;
17
+ baseColumn: never;
18
+ identity: undefined;
19
+ generated: undefined;
20
+ }, {}>;
21
+ accountId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
22
+ name: string;
23
+ tableName: "document_changes";
24
+ dataType: "number int53";
25
+ data: number;
26
+ driverParam: number;
27
+ notNull: true;
28
+ hasDefault: false;
29
+ isPrimaryKey: false;
30
+ isAutoincrement: false;
31
+ hasRuntimeDefault: false;
32
+ enumValues: undefined;
33
+ baseColumn: never;
34
+ identity: undefined;
35
+ generated: undefined;
36
+ }, {}>;
37
+ documentId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
38
+ name: string;
39
+ tableName: "document_changes";
40
+ dataType: "number int53";
41
+ data: number;
42
+ driverParam: number;
43
+ notNull: true;
44
+ hasDefault: false;
45
+ isPrimaryKey: false;
46
+ isAutoincrement: false;
47
+ hasRuntimeDefault: false;
48
+ enumValues: undefined;
49
+ baseColumn: never;
50
+ identity: undefined;
51
+ generated: undefined;
52
+ }, {}>;
53
+ path: import("drizzle-orm/sqlite-core").SQLiteColumn<{
54
+ name: string;
55
+ tableName: "document_changes";
56
+ dataType: "string";
57
+ data: string;
58
+ driverParam: string;
59
+ notNull: true;
60
+ hasDefault: false;
61
+ isPrimaryKey: false;
62
+ isAutoincrement: false;
63
+ hasRuntimeDefault: false;
64
+ enumValues: [string, ...string[]];
65
+ baseColumn: never;
66
+ identity: undefined;
67
+ generated: undefined;
68
+ }, {}>;
69
+ title: import("drizzle-orm/sqlite-core").SQLiteColumn<{
70
+ name: string;
71
+ tableName: "document_changes";
72
+ dataType: "string";
73
+ data: string;
74
+ driverParam: string;
75
+ notNull: false;
76
+ hasDefault: false;
77
+ isPrimaryKey: false;
78
+ isAutoincrement: false;
79
+ hasRuntimeDefault: false;
80
+ enumValues: [string, ...string[]];
81
+ baseColumn: never;
82
+ identity: undefined;
83
+ generated: undefined;
84
+ }, {}>;
85
+ event: import("drizzle-orm/sqlite-core").SQLiteColumn<{
86
+ name: string;
87
+ tableName: "document_changes";
88
+ dataType: "string";
89
+ data: string;
90
+ driverParam: string;
91
+ notNull: true;
92
+ hasDefault: false;
93
+ isPrimaryKey: false;
94
+ isAutoincrement: false;
95
+ hasRuntimeDefault: false;
96
+ enumValues: [string, ...string[]];
97
+ baseColumn: never;
98
+ identity: undefined;
99
+ generated: undefined;
100
+ }, {}>;
101
+ revision: import("drizzle-orm/sqlite-core").SQLiteColumn<{
102
+ name: string;
103
+ tableName: "document_changes";
104
+ dataType: "number int53";
105
+ data: number;
106
+ driverParam: number;
107
+ notNull: true;
108
+ hasDefault: false;
109
+ isPrimaryKey: false;
110
+ isAutoincrement: false;
111
+ hasRuntimeDefault: false;
112
+ enumValues: undefined;
113
+ baseColumn: never;
114
+ identity: undefined;
115
+ generated: undefined;
116
+ }, {}>;
117
+ at: import("drizzle-orm/sqlite-core").SQLiteColumn<{
118
+ name: string;
119
+ tableName: "document_changes";
120
+ dataType: "number int53";
121
+ data: number;
122
+ driverParam: number;
123
+ notNull: true;
124
+ hasDefault: false;
125
+ isPrimaryKey: false;
126
+ isAutoincrement: false;
127
+ hasRuntimeDefault: false;
128
+ enumValues: undefined;
129
+ baseColumn: never;
130
+ identity: undefined;
131
+ generated: undefined;
132
+ }, {}>;
133
+ };
134
+ dialect: 'sqlite';
135
+ isAlias: false;
136
+ }>;
@@ -0,0 +1,11 @@
1
+ import { index, integer, sqliteTable, text } from "../drizzle/core.js";
2
+ export const documentChanges = sqliteTable("document_changes", {
3
+ id: integer("id").primaryKey(),
4
+ accountId: integer("account_id").notNull(),
5
+ documentId: integer("document_id").notNull(),
6
+ path: text("path").notNull(),
7
+ title: text("title"),
8
+ event: text("event").notNull(),
9
+ revision: integer("revision").notNull(),
10
+ at: integer("at").notNull(),
11
+ }, (table) => [index("document_changes_by_account_id_at").on(table.accountId, table.at)]);
@@ -7330,6 +7330,22 @@ export declare const documents: import("drizzle-orm/sqlite-core").SQLiteTableWit
7330
7330
  identity: undefined;
7331
7331
  generated: undefined;
7332
7332
  }, {}>;
7333
+ removal: import("drizzle-orm/sqlite-core").SQLiteColumn<{
7334
+ name: string;
7335
+ tableName: "documents";
7336
+ dataType: "string";
7337
+ data: string;
7338
+ driverParam: string;
7339
+ notNull: false;
7340
+ hasDefault: false;
7341
+ isPrimaryKey: false;
7342
+ isAutoincrement: false;
7343
+ hasRuntimeDefault: false;
7344
+ enumValues: [string, ...string[]];
7345
+ baseColumn: never;
7346
+ identity: undefined;
7347
+ generated: undefined;
7348
+ }, {}>;
7333
7349
  };
7334
7350
  dialect: 'sqlite';
7335
7351
  isAlias: false;
@@ -7746,10 +7762,59 @@ export declare const documentRevisions: import("drizzle-orm/sqlite-core").SQLite
7746
7762
  identity: undefined;
7747
7763
  generated: undefined;
7748
7764
  }, {}>;
7765
+ title: import("drizzle-orm/sqlite-core").SQLiteColumn<{
7766
+ name: string;
7767
+ tableName: "document_revisions";
7768
+ dataType: "string";
7769
+ data: string;
7770
+ driverParam: string;
7771
+ notNull: false;
7772
+ hasDefault: false;
7773
+ isPrimaryKey: false;
7774
+ isAutoincrement: false;
7775
+ hasRuntimeDefault: false;
7776
+ enumValues: [string, ...string[]];
7777
+ baseColumn: never;
7778
+ identity: undefined;
7779
+ generated: undefined;
7780
+ }, {}>;
7781
+ frontMatter: import("drizzle-orm/sqlite-core").SQLiteColumn<{
7782
+ name: string;
7783
+ tableName: "document_revisions";
7784
+ dataType: "string";
7785
+ data: string;
7786
+ driverParam: string;
7787
+ notNull: false;
7788
+ hasDefault: false;
7789
+ isPrimaryKey: false;
7790
+ isAutoincrement: false;
7791
+ hasRuntimeDefault: false;
7792
+ enumValues: [string, ...string[]];
7793
+ baseColumn: never;
7794
+ identity: undefined;
7795
+ generated: undefined;
7796
+ }, {}>;
7797
+ reason: import("drizzle-orm/sqlite-core").SQLiteColumn<{
7798
+ name: string;
7799
+ tableName: "document_revisions";
7800
+ dataType: "string";
7801
+ data: string;
7802
+ driverParam: string;
7803
+ notNull: false;
7804
+ hasDefault: false;
7805
+ isPrimaryKey: false;
7806
+ isAutoincrement: false;
7807
+ hasRuntimeDefault: false;
7808
+ enumValues: [string, ...string[]];
7809
+ baseColumn: never;
7810
+ identity: undefined;
7811
+ generated: undefined;
7812
+ }, {}>;
7749
7813
  };
7750
7814
  dialect: 'sqlite';
7751
7815
  isAlias: false;
7752
7816
  }>;
7817
+ export { documentChanges } from "./schema/document-changes.js";
7753
7818
  export { documentIndexPending } from "./schema/document-index-pending.js";
7754
7819
  export declare const notes: import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
7755
7820
  name: "notes";
@@ -797,6 +797,7 @@ export const documents = sqliteTable("documents", {
797
797
  updatedAt: integer("updated_at").notNull(),
798
798
  deletedAt: integer("deleted_at"),
799
799
  pinnedFileId: integer("pinned_file_id"),
800
+ removal: text("removal"),
800
801
  }, (table) => [unique().on(table.accountId, table.externalId)]);
801
802
  export const files = sqliteTable("files", {
802
803
  id: integer("id").primaryKey(),
@@ -836,7 +837,11 @@ export const documentRevisions = sqliteTable("document_revisions", {
836
837
  body: text("body").notNull(),
837
838
  revision: integer("revision").notNull(),
838
839
  createdAt: integer("created_at").notNull(),
840
+ title: text("title"),
841
+ frontMatter: text("front_matter"),
842
+ reason: text("reason"),
839
843
  }, (table) => [index("document_revisions_by_document_id").on(table.documentId)]);
844
+ export { documentChanges } from "./schema/document-changes.js";
840
845
  export { documentIndexPending } from "./schema/document-index-pending.js";
841
846
  export const notes = sqliteTable("notes", {
842
847
  id: integer("id").primaryKey(),