@wirecat/cli-core 0.720.0 → 0.722.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 (85) hide show
  1. package/CHANGELOG.md +106 -0
  2. package/dist/cli/config-command.js +8 -2
  3. package/dist/cli/config-issues.d.ts +3 -1
  4. package/dist/cli/config-issues.js +9 -2
  5. package/dist/cli/documents/file-conflicts.d.ts +25 -0
  6. package/dist/cli/documents/file-conflicts.js +102 -0
  7. package/dist/cli/documents/file-edit.d.ts +29 -0
  8. package/dist/cli/documents/file-edit.js +352 -0
  9. package/dist/cli/documents/file-update.d.ts +43 -0
  10. package/dist/cli/documents/file-update.js +95 -0
  11. package/dist/cli/documents/history.d.ts +34 -0
  12. package/dist/cli/documents/history.js +89 -0
  13. package/dist/cli/documents/index.d.ts +9 -2
  14. package/dist/cli/documents/index.js +9 -2
  15. package/dist/cli/documents/library.js +10 -0
  16. package/dist/cli/messenger/lacks.d.ts +2 -1
  17. package/dist/cli/messenger/lacks.js +14 -1
  18. package/dist/cli/permission-keys.d.ts +6 -0
  19. package/dist/cli/permission-keys.js +15 -3
  20. package/dist/cli/service-api.d.ts +1 -1
  21. package/dist/cli/service-api.js +16 -34
  22. package/dist/cli/token-session.d.ts +2 -1
  23. package/dist/cli/token-session.js +2 -2
  24. package/dist/crm/cli/account.d.ts +60 -0
  25. package/dist/crm/cli/account.js +147 -0
  26. package/dist/crm/cli/files.js +2 -1
  27. package/dist/crm/cli/index.d.ts +3 -0
  28. package/dist/crm/cli/index.js +4 -0
  29. package/dist/crm/foreign-contacts.js +2 -1
  30. package/dist/crm/state-folders.d.ts +5 -0
  31. package/dist/crm/state-folders.js +2 -0
  32. package/dist/documents/file-mirror-model.d.ts +18 -1
  33. package/dist/documents/index.d.ts +7 -4
  34. package/dist/documents/index.js +4 -1
  35. package/dist/documents/model.d.ts +16 -1
  36. package/dist/errors/reasons.d.ts +1 -1
  37. package/dist/errors/reasons.js +15 -0
  38. package/dist/services/documents/block-diff.d.ts +13 -3
  39. package/dist/services/documents/block-diff.js +13 -7
  40. package/dist/services/documents/ingestion.d.ts +21 -2
  41. package/dist/services/documents/ingestion.js +29 -2
  42. package/dist/services/documents/plan.js +16 -7
  43. package/dist/services/documents/ports.d.ts +2 -0
  44. package/dist/services/documents/sync.d.ts +1 -0
  45. package/dist/services/documents/sync.js +9 -4
  46. package/dist/services/files/conflicts.d.ts +78 -0
  47. package/dist/services/files/conflicts.js +183 -0
  48. package/dist/services/files/guarded-write.d.ts +34 -0
  49. package/dist/services/files/guarded-write.js +42 -0
  50. package/dist/services/files/listing.d.ts +8 -0
  51. package/dist/services/files/listing.js +1 -1
  52. package/dist/services/files/local-files.d.ts +54 -0
  53. package/dist/services/files/local-files.js +143 -0
  54. package/dist/services/files/mirror-state.d.ts +14 -0
  55. package/dist/services/files/mirror-state.js +65 -0
  56. package/dist/services/files/mirror.d.ts +8 -15
  57. package/dist/services/files/mirror.js +164 -205
  58. package/dist/services/files/text-merge.d.ts +27 -0
  59. package/dist/services/files/text-merge.js +134 -0
  60. package/dist/services/files/versions.d.ts +36 -9
  61. package/dist/services/files/versions.js +40 -12
  62. package/dist/services/metadata.d.ts +1 -1
  63. package/dist/store/index.d.ts +2 -0
  64. package/dist/store/index.js +1 -0
  65. package/dist/store/sqlite/account-purge.js +3 -0
  66. package/dist/store/sqlite/crm-stage-entries.js +4 -1
  67. package/dist/store/sqlite/document-history.d.ts +84 -0
  68. package/dist/store/sqlite/document-history.js +158 -0
  69. package/dist/store/sqlite/erase-plan.d.ts +19 -0
  70. package/dist/store/sqlite/erase-plan.js +74 -0
  71. package/dist/store/sqlite/manifest.js +2 -0
  72. package/dist/store/sqlite/messages.js +2 -1
  73. package/dist/store/sqlite/migrations.generated.js +17 -0
  74. package/dist/store/sqlite/notes.d.ts +9 -10
  75. package/dist/store/sqlite/notes.js +33 -21
  76. package/dist/store/sqlite/organization-erase.d.ts +29 -0
  77. package/dist/store/sqlite/organization-erase.js +83 -0
  78. package/dist/store/sqlite/organizations.d.ts +10 -1
  79. package/dist/store/sqlite/organizations.js +6 -1
  80. package/dist/store/sqlite/person-erase.js +4 -45
  81. package/dist/store/sqlite/schema/document-changes.d.ts +136 -0
  82. package/dist/store/sqlite/schema/document-changes.js +11 -0
  83. package/dist/store/sqlite/schema.d.ts +65 -0
  84. package/dist/store/sqlite/schema.js +5 -0
  85. package/package.json +3 -3
@@ -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,29 @@
1
+ import type { Decider } from "../decisions.js";
2
+ import type { CacheDatabase } from "../driver.js";
3
+ import type { StoreContext } from "./open.js";
4
+ export interface OrganizationErasure {
5
+ organization: string;
6
+ name: string;
7
+ /** `false`: what `erase` would do, nothing changed. */
8
+ erased: boolean;
9
+ /** Identities the organization held, such as its domain; the identities stay, the holding goes. */
10
+ identities: string[];
11
+ /** Rows that only tied something to the organization, such as a tag, a link or a mention, by `table.column`. */
12
+ deleted: Record<string, number>;
13
+ /** Rows that stay and lose the organization, such as a deal, a lead, a project or an account. */
14
+ detached: Record<string, number>;
15
+ }
16
+ /**
17
+ * Deletes an organization and what memo knows of it alone: the tags, links, aliases and mentions that name it, and
18
+ * which identities it held. A deal, lead, project, account, fact or note that names it stays and loses the name.
19
+ * Refused for one of the owner's own companies, and while an invoice, order, subscription or a row it wrote cannot
20
+ * be without it. `apply: false` answers the same without changing anything.
21
+ */
22
+ export declare const eraseOrganization: (context: StoreContext, ref: string, by: Decider, apply: boolean) => OrganizationErasure;
23
+ /** The organizations an account's records made: read before a purge deletes the records. */
24
+ export declare const importedOrganizations: (database: CacheDatabase, accountKey: number) => number[];
25
+ /**
26
+ * After a purge, the organizations only its records made go too: no other row names them. One the owner tagged,
27
+ * linked, gave a deal to or calls his own stays.
28
+ */
29
+ export declare const eraseImportedOrganizations: (context: StoreContext, organizations: readonly number[]) => void;
@@ -0,0 +1,83 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { ErasePlan } from "./erase-plan.js";
3
+ import { forgetDanglingEvidence } from "./evidence-signature.js";
4
+ import { ownerOnly } from "./person-merges.js";
5
+ const OWN_ROWS = new Set(["organization_identities"]);
6
+ const organizationOf = (database, ref) => {
7
+ const asked = /^(?:organization:)?([1-9]\d*)$/u.exec(ref.trim())?.[1];
8
+ const row = asked === undefined
9
+ ? undefined
10
+ : database.prepare("SELECT id, name, metadata FROM organizations WHERE id = ?").get(Number(asked));
11
+ if (row === undefined)
12
+ throw new CliError("not_found", `the store has no organization for "${ref}"`, { reason: "organization.not-found" });
13
+ return {
14
+ id: Number(row.id),
15
+ name: String(row.name),
16
+ own: [true, 1].includes(JSON.parse(String(row.metadata ?? "{}"))?.own),
17
+ };
18
+ };
19
+ /**
20
+ * Deletes an organization and what memo knows of it alone: the tags, links, aliases and mentions that name it, and
21
+ * which identities it held. A deal, lead, project, account, fact or note that names it stays and loses the name.
22
+ * Refused for one of the owner's own companies, and while an invoice, order, subscription or a row it wrote cannot
23
+ * be without it. `apply: false` answers the same without changing anything.
24
+ */
25
+ export const eraseOrganization = (context, ref, by, apply) => {
26
+ ownerOnly(by, "deletes an organization");
27
+ const { database } = context;
28
+ const organization = organizationOf(database, ref);
29
+ if (organization.own)
30
+ throw new CliError("validation_error", `organization:${organization.id} is one of your own companies`, {
31
+ reason: "organization.own",
32
+ });
33
+ const identities = database
34
+ .prepare(`SELECT i.provider || ':' || i.external_id AS ref FROM organization_identities o
35
+ JOIN identities i ON i.id = o.identity_id WHERE o.organization_id = ? ORDER BY i.id`)
36
+ .all(organization.id)
37
+ .map((one) => String(one.ref));
38
+ const plan = new ErasePlan(database)
39
+ .pointers("organization", "?", [organization.id])
40
+ .foreignKeys("organizations", organization.id, OWN_ROWS);
41
+ if (plan.blocked.length > 0)
42
+ throw new CliError("validation_error", `organization:${organization.id} is still named by ${plan.blocked.join(", ")}; change those first — nothing ` +
43
+ "was deleted", { reason: "organization.erase-blocked", blocked: plan.blocked });
44
+ const answer = (erased) => ({
45
+ organization: `organization:${organization.id}`,
46
+ name: organization.name,
47
+ erased,
48
+ identities,
49
+ deleted: plan.deleted,
50
+ detached: plan.detached,
51
+ });
52
+ if (!apply)
53
+ return answer(false);
54
+ plan.run();
55
+ database.prepare("DELETE FROM organization_identities WHERE organization_id = ?").run(organization.id);
56
+ database.prepare("DELETE FROM organizations WHERE id = ?").run(organization.id);
57
+ forgetDanglingEvidence(database, context.now());
58
+ return answer(true);
59
+ };
60
+ /** The organizations an account's records made: read before a purge deletes the records. */
61
+ export const importedOrganizations = (database, accountKey) => database
62
+ .prepare("SELECT DISTINCT entity_id AS id FROM records WHERE account_id = ? AND entity_type = 'organization'")
63
+ .all(accountKey)
64
+ .map(({ id }) => Number(id));
65
+ /**
66
+ * After a purge, the organizations only its records made go too: no other row names them. One the owner tagged,
67
+ * linked, gave a deal to or calls his own stays.
68
+ */
69
+ export const eraseImportedOrganizations = (context, organizations) => {
70
+ for (const id of organizations) {
71
+ if (context.database.prepare("SELECT 1 FROM organizations WHERE id = ?").get(id) === undefined)
72
+ continue;
73
+ try {
74
+ const plan = eraseOrganization(context, String(id), "owner", false);
75
+ if (Object.keys(plan.deleted).length === 0 && Object.keys(plan.detached).length === 0)
76
+ eraseOrganization(context, String(id), "owner", true);
77
+ }
78
+ catch (error) {
79
+ if (!(error instanceof CliError))
80
+ throw error;
81
+ }
82
+ }
83
+ };
@@ -1,7 +1,9 @@
1
1
  import { type QueryAst } from "@wirecat/cli-base/query";
2
+ import type { Decider } from "../decisions.js";
2
3
  import type { Organization } from "./knowledge.js";
3
4
  import type { StoreContext } from "./open.js";
4
5
  import { type OrganizationFilter } from "./organization-categories.js";
6
+ import { type OrganizationErasure } from "./organization-erase.js";
5
7
  type Row = Record<string, unknown>;
6
8
  export declare const organizationOf: (row: Row) => Organization;
7
9
  export interface OrganizationsStore {
@@ -21,6 +23,13 @@ export interface OrganizationsStore {
21
23
  }>;
22
24
  /** The owner's own companies: the owner's mark, else a CRM's own-company flag (`metadata.own`). */
23
25
  ownOrganizations(): Promise<Organization[]>;
26
+ /**
27
+ * Deletes an organization and what memo knows of it alone; see `eraseOrganization`. `apply: false` answers what
28
+ * would go and changes nothing. The owner's alone; refused for the owner's own companies.
29
+ */
30
+ eraseOrganization(organization: string, by: Decider, options: {
31
+ apply: boolean;
32
+ }): Promise<OrganizationErasure>;
24
33
  }
25
- export declare const organizationsStoreOver: ({ database, now }: StoreContext) => OrganizationsStore;
34
+ export declare const organizationsStoreOver: (context: StoreContext) => OrganizationsStore;
26
35
  export {};
@@ -2,6 +2,7 @@ import { CliError } from "@wirecat/cli-base";
2
2
  import { evaluate, timezoneOf, walkQuery } from "@wirecat/cli-base/query";
3
3
  import { ORGANIZATIONS_QUERY } from "../knowledge-query.js";
4
4
  import { categorySql } from "./organization-categories.js";
5
+ import { eraseOrganization } from "./organization-erase.js";
5
6
  import { queryFilter } from "./query-filter.js";
6
7
  import { thingOf } from "./things.js";
7
8
  import { write } from "./transaction.js";
@@ -13,7 +14,11 @@ export const organizationOf = (row) => ({
13
14
  scope: row.scope,
14
15
  createdAt: new Date(Number(row.created_at)).toISOString(),
15
16
  });
16
- export const organizationsStoreOver = ({ database, now }) => ({
17
+ export const organizationsStoreOver = (context) => ({
18
+ eraseOrganization: async (organization, by, { apply }) => write(context.database, () => eraseOrganization(context, organization, by, apply)),
19
+ ...organizationsReadsOver(context),
20
+ });
21
+ const organizationsReadsOver = ({ database, now }) => ({
17
22
  organizations: async (query, filter = {}) => {
18
23
  const category = categorySql(filter, now());
19
24
  const inCategory = category ? ` AND ${category.sql}` : "";
@@ -1,24 +1,12 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { OWN, referencesTo } from "./accounts.js";
3
- import { pointerPairs } from "./entity-types.js";
3
+ import { count, ErasePlan } from "./erase-plan.js";
4
4
  import { forgetDanglingEvidence } from "./evidence-signature.js";
5
5
  import { forgetErasedLinks } from "./identity-link-rows.js";
6
6
  import { forgetErasedSplits } from "./identity-split-proposals.js";
7
7
  import { currentPerson } from "./merged-persons.js";
8
8
  import { ownerOnly } from "./person-merges.js";
9
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
10
  const personOf = (context, uid) => {
23
11
  const asked = /^(?:person:)?([1-9]\d*)$/u.exec(uid.trim())?.[1];
24
12
  const known = asked === undefined ? undefined : context.database.prepare("SELECT id FROM persons WHERE id = ?").get(Number(asked));
@@ -26,7 +14,6 @@ const personOf = (context, uid) => {
26
14
  throw new CliError("not_found", `the store has no person for "${uid}"`, { reason: "person.unknown" });
27
15
  return currentPerson(context.database, Number(known.id));
28
16
  };
29
- const count = (database, sql, ...params) => Number(database.prepare(`SELECT count(*) AS n FROM ${sql}`).get(...params)?.n);
30
17
  /**
31
18
  * Deletes a person and what memo knows of them alone: their identities, the tags, links, aliases and mentions that
32
19
  * name them, their involvements. A fact, a note, a record or a task that names them stays and loses the name. A
@@ -57,35 +44,8 @@ export const erasePerson = (context, uid, by, apply) => {
57
44
  const going = linked.filter(({ id }) => !named.has(id));
58
45
  const kept = linked.filter(({ id }) => named.has(id));
59
46
  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]);
47
+ const plan = new ErasePlan(database).pointers("person", "?", [person]).pointers("identity", theirs, [goingIds]);
48
+ const { deleted, detached, blocked } = plan;
89
49
  const involvements = count(database, `involvements WHERE person_id = ? OR identity_id IN (${theirs})`, person, goingIds);
90
50
  if (involvements > 0)
91
51
  deleted["involvements.person"] = (deleted["involvements.person"] ?? 0) + involvements;
@@ -105,8 +65,7 @@ export const erasePerson = (context, uid, by, apply) => {
105
65
  });
106
66
  if (!apply)
107
67
  return answer(false);
108
- for (const step of plan)
109
- step();
68
+ plan.run();
110
69
  database.prepare(`DELETE FROM involvements WHERE person_id = ? OR identity_id IN (${theirs})`).run(person, goingIds);
111
70
  database.prepare("UPDATE bots SET owner_person_id = NULL WHERE owner_person_id = ?").run(person);
112
71
  for (const table of ["account_identities", "organization_identities", "identity_revisions"])
@@ -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)]);