@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
@@ -1,11 +1,21 @@
1
1
  import { type HeldLock } from "../documents/mirrors.js";
2
- /** Which way a sync moved a change. */
3
- export type VersionDirection = "local-to-remote" | "remote-to-local" | "restored";
2
+ /** Which way a sync moved a change; `both` is a merge or a conflict's resolution, written to both sides. */
3
+ export type VersionDirection = "local-to-remote" | "remote-to-local" | "restored" | "both";
4
+ /** The contents a merge, a conflict or its resolution worked from: the last sync's, and each side's. */
5
+ export interface VersionParts {
6
+ base?: string;
7
+ local?: string;
8
+ remote?: string;
9
+ }
4
10
  /** One line of a mirror's version log: what a sync did to a path, with the content's hash before and after. */
5
11
  export interface VersionEvent {
6
12
  at: string;
7
13
  path: string;
8
- event: "created" | "changed" | "deleted" | "renamed";
14
+ /**
15
+ * `merged`: both sides' changes merged into `new`. `conflict`: they could not be, and `parts` were kept. `resolved`:
16
+ * the owner settled the conflict with `new`, as `resolution` says.
17
+ */
18
+ event: "created" | "changed" | "deleted" | "renamed" | "merged" | "conflict" | "resolved";
9
19
  direction: VersionDirection;
10
20
  /** The content the change replaced: the local file kept before a pull or deletion, the remote version an upload replaced. */
11
21
  old?: string;
@@ -17,10 +27,22 @@ export interface VersionEvent {
17
27
  size?: number;
18
28
  /** A rename's new path. */
19
29
  to?: string;
30
+ /** A merge's, a conflict's or a resolution's contents; with `new`, kept for good. */
31
+ parts?: VersionParts;
32
+ /** How the owner resolved a conflict: kept one side, both, or gave the final file. */
33
+ resolution?: "local" | "remote" | "both" | "file";
20
34
  }
35
+ /** Which content of a merge or a conflict a kept version is; `result` is the merge's or the resolution's. */
36
+ export type VersionRole = "base" | "local" | "remote" | "result";
21
37
  /** A version of a path, and whether its bytes are still in the store. */
22
38
  export interface FileVersion extends VersionEvent {
23
39
  available: boolean;
40
+ /** Each content of a merge, a conflict or a resolution, and whether the store still has it. */
41
+ versions?: {
42
+ role: VersionRole;
43
+ sha256: string;
44
+ available: boolean;
45
+ }[];
24
46
  }
25
47
  export interface FileVersions {
26
48
  /** The folder the store keeps its copies in, when it is on disk: a sync checks its free space first. */
@@ -34,6 +56,8 @@ export interface FileVersions {
34
56
  keep(source: string | ((temp: string) => Promise<void>)): Promise<string>;
35
57
  /** Whether the store holds this content. */
36
58
  has(sha256: string): boolean;
59
+ /** A kept content's bytes, or undefined when the store does not hold it. Meant for text a merge reads whole. */
60
+ read(sha256: string): Promise<Buffer | undefined>;
37
61
  log(event: Omit<VersionEvent, "at">): void;
38
62
  /** Every event of `path`, oldest first, including renames to or from it. */
39
63
  list(path: string): FileVersion[];
@@ -42,15 +66,18 @@ export interface FileVersions {
42
66
  * undefined. False when the store no longer has the version or the file was not as `over` said.
43
67
  */
44
68
  write(sha256: string, into: string, over?: string): Promise<boolean>;
45
- /** Applies the retention rule; see `fileVersions`. A sync runs it under its lock; call it only under that lock. */
46
- prune(): Promise<void>;
69
+ /**
70
+ * Applies the retention rule; see `fileVersions`. `pinned` stay too: a mirror's last synced contents, the base of
71
+ * its next merge. A sync runs it under its lock; call it only under that lock.
72
+ */
73
+ prune(pinned?: Iterable<string>): Promise<void>;
47
74
  }
48
75
  /**
49
76
  * A mirror's local version store: `<dir>/objects/<sha256>` holds each kept content once, `<dir>/log.jsonl` is
50
- * append-only. The store lives under the profile's state folder, never inside the mirrored folder. Retention, one
51
- * rule: a content stays while an event newer than 30 days names it, and the last content of a path whose newest
52
- * event is a deletion stays for good. A content no event names stays 30 days after it was last kept, so a crash
53
- * between keeping a file and logging the change loses nothing.
77
+ * append-only. The store lives under the profile's state folder, never inside the mirrored folder. Retention: a
78
+ * content stays while an event newer than 30 days names it; the last content of a path whose newest event is a
79
+ * deletion, and every content a merge, a conflict or a resolution names, stay for good. A content no event names stays
80
+ * 30 days after it was last kept, so a crash between keeping a file and logging the change loses nothing.
54
81
  */
55
82
  export declare const fileVersions: (dir: string, now?: () => number) => FileVersions;
56
83
  /**
@@ -1,6 +1,6 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import { appendFileSync, createReadStream, createWriteStream, existsSync, mkdirSync, readFileSync } from "node:fs";
3
- import { mkdir, readdir, rename, rm, stat, utimes } from "node:fs/promises";
3
+ import { mkdir, readdir, readFile, rename, rm, stat, utimes } from "node:fs/promises";
4
4
  import { join } from "node:path";
5
5
  import { Transform } from "node:stream";
6
6
  import { pipeline } from "node:stream/promises";
@@ -36,12 +36,23 @@ const copyHashed = async (from, into) => {
36
36
  }), createWriteStream(into, { flags: "wx", mode: 0o600 }));
37
37
  return hash.digest("hex");
38
38
  };
39
+ const rolesOf = (event) => {
40
+ if (!event.parts)
41
+ return [];
42
+ const { base, local, remote } = event.parts;
43
+ return [
44
+ ...(base ? [{ role: "base", sha256: base }] : []),
45
+ ...(local ? [{ role: "local", sha256: local }] : []),
46
+ ...(remote ? [{ role: "remote", sha256: remote }] : []),
47
+ ...(event.new ? [{ role: "result", sha256: event.new }] : []),
48
+ ];
49
+ };
39
50
  /**
40
51
  * A mirror's local version store: `<dir>/objects/<sha256>` holds each kept content once, `<dir>/log.jsonl` is
41
- * append-only. The store lives under the profile's state folder, never inside the mirrored folder. Retention, one
42
- * rule: a content stays while an event newer than 30 days names it, and the last content of a path whose newest
43
- * event is a deletion stays for good. A content no event names stays 30 days after it was last kept, so a crash
44
- * between keeping a file and logging the change loses nothing.
52
+ * append-only. The store lives under the profile's state folder, never inside the mirrored folder. Retention: a
53
+ * content stays while an event newer than 30 days names it; the last content of a path whose newest event is a
54
+ * deletion, and every content a merge, a conflict or a resolution names, stay for good. A content no event names stays
55
+ * 30 days after it was last kept, so a crash between keeping a file and logging the change loses nothing.
45
56
  */
46
57
  export const fileVersions = (dir, now = Date.now) => {
47
58
  const objects = join(dir, "objects");
@@ -59,7 +70,7 @@ export const fileVersions = (dir, now = Date.now) => {
59
70
  throw error;
60
71
  }
61
72
  };
62
- const has = (sha256) => existsSync(join(objects, sha256));
73
+ const has = (sha256) => /^[0-9a-f]{64}$/.test(sha256) && existsSync(join(objects, sha256));
63
74
  return {
64
75
  dir,
65
76
  keep: async (source) => {
@@ -91,16 +102,31 @@ export const fileVersions = (dir, now = Date.now) => {
91
102
  }
92
103
  },
93
104
  has,
105
+ read: async (sha256) => {
106
+ if (!has(sha256))
107
+ return undefined;
108
+ return readFile(join(objects, sha256)).catch((error) => {
109
+ if (error.code === "ENOENT")
110
+ return undefined;
111
+ throw error;
112
+ });
113
+ },
94
114
  log: (event) => {
95
115
  mkdirSync(dir, { recursive: true, mode: 0o700 });
96
116
  appendFileSync(logPath, `${JSON.stringify({ at: new Date(now()).toISOString(), ...event })}\n`, { mode: 0o600 });
97
117
  },
98
118
  list: (path) => {
99
119
  const found = events().filter((event) => event.path === path || event.to === path);
100
- return found.map((event) => ({
101
- ...event,
102
- available: event.old !== undefined && existsSync(join(objects, event.old)),
103
- }));
120
+ return found.map((event) => {
121
+ const roles = rolesOf(event);
122
+ return {
123
+ ...event,
124
+ available: roles.length
125
+ ? roles.every(({ sha256 }) => has(sha256))
126
+ : event.old !== undefined && has(event.old),
127
+ ...(roles.length ? { versions: roles.map((role) => ({ ...role, available: has(role.sha256) })) } : {}),
128
+ };
129
+ });
104
130
  },
105
131
  write: async (sha256, into, over) => {
106
132
  if (!has(sha256))
@@ -108,9 +134,9 @@ export const fileVersions = (dir, now = Date.now) => {
108
134
  const copy = (temp) => pipeline(createReadStream(join(objects, sha256)), createWriteStream(temp, { flags: "wx" }));
109
135
  return (await replaceLocal(into, over, copy, { sha256 })) !== undefined;
110
136
  },
111
- prune: async () => {
137
+ prune: async (pinned = []) => {
112
138
  const all = events();
113
- const keep = new Set();
139
+ const keep = new Set(pinned);
114
140
  const last = new Map();
115
141
  for (const event of all) {
116
142
  last.set(event.path, event);
@@ -118,6 +144,8 @@ export const fileVersions = (dir, now = Date.now) => {
118
144
  for (const hash of [event.old, event.new])
119
145
  if (hash)
120
146
  keep.add(hash);
147
+ for (const { sha256 } of rolesOf(event))
148
+ keep.add(sha256);
121
149
  }
122
150
  for (const event of last.values())
123
151
  if (event.event === "deleted" && event.old)
@@ -14,12 +14,12 @@ export declare const metadataService: (deps: ServiceDeps) => {
14
14
  dryRun?: boolean;
15
15
  }) => Promise<{
16
16
  items: ({
17
- error?: undefined;
18
17
  chatId: string;
19
18
  tags: import("../domain/channel-tags.js").ChannelTagMatch[];
20
19
  algorithm: string;
21
20
  fetchedAt: string | null;
22
21
  source: string;
22
+ error?: undefined;
23
23
  } | {
24
24
  tags?: undefined;
25
25
  algorithm?: undefined;
@@ -56,6 +56,7 @@ export { type ChangeFilter, CRM_CHANGES, type CrmChange, type CrmChangeKind } fr
56
56
  export { COMPANY_TYPE_MEANINGS, type CompanyTypeMeaning, CRM_LINK_MODES, type CrmLinkMode, type CrmStageMove, type CrmStageTasks, crmSettingKey, type StageTaskRule, } from "./sqlite/crm-settings.js";
57
57
  export type { Deal, DealFilter, DealInput, DealPerson, DealScope, DealsStore, FunnelStage, Pipeline, PipelineInput, PipelineReport, PipelineStage, StageChange, } from "./sqlite/deals.js";
58
58
  export type { DecisionMessage, DecisionPress, DecisionRefusal, DecisionRequest, DecisionRequestInput, DecisionRequestStore, TakeResult, } from "./sqlite/decision-requests.js";
59
+ export { DOCUMENT_EVENTS, DOCUMENT_REMOVALS, type DocumentChange, type DocumentEvent, type DocumentHistoryAnswer, type DocumentHistoryStore, type DocumentRemoval, type DocumentVersion, type DocumentVersionText, type VersionReason, } from "./sqlite/document-history.js";
59
60
  export { DOCUMENT_KINDS, type DocumentDetail, type DocumentFolderNode, type DocumentKind, type DocumentLink, type DocumentListFilter, type DocumentListing, type DocumentListRow, type DocumentSourceNode, } from "./sqlite/document-listing.js";
60
61
  export type { Email, EmailAddress, EmailAttachment, EmailFacts, EmailFilter, EmailInput, EmailInThread, EmailLocationInput, EmailRecipient, EmailRef, EmailThread, EmailVectorHit, FolderEmail, Mailbox, MailboxInput, MailFilter, MailStore, PartialEmail, SenderScore, ThreadDetails, ThreadSave, } from "./sqlite/emails.js";
61
62
  export { EVENT_FIELDS, type EventChunkToEmbed, type EventHit, type EventQuery, type EventSearch, type NearestEvent, } from "./sqlite/event-search.js";
@@ -84,6 +85,7 @@ export { type NearestNote, NOTE_FIELDS, type NoteChunkToEmbed, type NoteHit, typ
84
85
  export type { FileNoteInput, Link, LinkInput, LinkListFilter, Note, NoteFolder, NotesStore, NoteTag, } from "./sqlite/notes.js";
85
86
  export type { Order, OrderDetail, OrderFilter, OrderInput, OrdersStore } from "./sqlite/orders.js";
86
87
  export type { OrganizationFilter } from "./sqlite/organization-categories.js";
88
+ export type { OrganizationErasure } from "./sqlite/organization-erase.js";
87
89
  export { DEFAULT_OWNER_LANGUAGES, ownerLanguages } from "./sqlite/owner-languages.js";
88
90
  export { type ListedPerson, PEOPLE_SORTS, type PeopleList, type PeopleListOptions, type PeopleSort, type SimilarPerson, } from "./sqlite/people-list.js";
89
91
  export { DOUBT_REASONS, type DoubtIdentity, type DoubtMove, type DoubtReason, type KeptPerson, type PersonDoubt, type PersonDoubts, type TestDataPerson, } from "./sqlite/person-doubts.js";
@@ -36,6 +36,7 @@ export { CATALOG_QUERY } from "./sqlite/catalog.js";
36
36
  export { crmIdentityId, } from "./sqlite/crm.js";
37
37
  export { CRM_CHANGES } from "./sqlite/crm-changes.js";
38
38
  export { COMPANY_TYPE_MEANINGS, CRM_LINK_MODES, crmSettingKey, } from "./sqlite/crm-settings.js";
39
+ export { DOCUMENT_EVENTS, DOCUMENT_REMOVALS, } from "./sqlite/document-history.js";
39
40
  export { DOCUMENT_KINDS, } from "./sqlite/document-listing.js";
40
41
  export { EVENT_FIELDS, } from "./sqlite/event-search.js";
41
42
  export { QUOTE_LIMIT, quoteKept } from "./sqlite/evidence-signature.js";
@@ -3,6 +3,7 @@ import { calendarCursorKey, calendarWritesOver } from "./calendar.js";
3
3
  import { forgetCalendarRows } from "./calendar-forget.js";
4
4
  import { eq, inArray, sql } from "./drizzle/core.js";
5
5
  import { forgetDanglingEvidence, forgetEvidenceTo } from "./evidence-signature.js";
6
+ import { eraseImportedOrganizations, importedOrganizations } from "./organization-erase.js";
6
7
  import { eraseImportedPeople, importedPeople } from "./person-erase.js";
7
8
  import { accountIdentities, accounts, aliases, botUpdates, chatEventPeople, chatEvents, chatMembers, chats, chunks, fetchLeases, involvements, memberCounts, memberObservationMembers, memberObservations, memberStays, messageReactions, messageRevisions, messages, messageTranscripts, pollVotes, projects, syncCursors, syncRanges, syncs, } from "./schema.js";
8
9
  import { dropUnusedVectors } from "./vector-index.js";
@@ -11,6 +12,7 @@ export const purgeAccount = (context, accountKey) => {
11
12
  const { orm, database, now } = context;
12
13
  const unseenBefore = unreferenced(database, "identities");
13
14
  const imported = importedPeople(database, accountKey);
15
+ const importedCompanies = importedOrganizations(database, accountKey);
14
16
  const at = now();
15
17
  const meetingIds = "SELECT id FROM meetings WHERE account_id = ?";
16
18
  const transcriptIds = `SELECT id FROM meeting_transcripts WHERE meeting_id IN (${meetingIds})`;
@@ -114,6 +116,7 @@ export const purgeAccount = (context, accountKey) => {
114
116
  orm.delete(accounts).where(eq(accounts.id, accountKey)).run();
115
117
  dropOrphanPeople(database, unseenBefore);
116
118
  eraseImportedPeople(context, imported);
119
+ eraseImportedOrganizations(context, importedCompanies);
117
120
  forgetDanglingEvidence(database, at);
118
121
  dropUnusedVectors(database, hashes);
119
122
  // The links' delete trigger writes a revision naming the account it is purging; the history goes with the links.
@@ -7,6 +7,7 @@ export const STAGE_ENTRY_DAYS = 90;
7
7
  /** A stage entered longer ago than this opens no task: the copy missed the deal for more than a sync or two. */
8
8
  const STAGE_TASK_DAYS = 7;
9
9
  const DAY = 86_400_000;
10
+ const SECOND = 1000;
10
11
  /**
11
12
  * Every stage entry of the kind's rows in one pipeline, or of one row, oldest first per row: the CRM's own history
12
13
  * where a row has any, else the copy's diffs, never both for one row. Entries handled or expired stay history.
@@ -79,6 +80,8 @@ export const crmStageEntriesOver = (context) => {
79
80
  const accountId = findAccountPk(context, key);
80
81
  if (accountId === undefined)
81
82
  return [];
83
+ // A CRM's history keeps whole seconds: a move in the second the rules were set would read as made before them.
84
+ const from = Math.max(Math.floor(since / SECOND) * SECOND, at - STAGE_TASK_DAYS * DAY);
82
85
  return database
83
86
  .prepare("SELECT r.id, r.external_id, json_extract(r.fields, '$.kind') AS kind, coalesce(d.id, l.id) AS item_id, " +
84
87
  "s.external_id AS stage, s.name AS stage_name, p.name AS pipeline_name FROM records r " +
@@ -91,7 +94,7 @@ export const crmStageEntriesOver = (context) => {
91
94
  "WHERE r.account_id = ? AND r.type = ? AND r.deleted_at IS NULL AND coalesce(d.id, l.id) IS NOT NULL " +
92
95
  "AND json_extract(r.fields, '$.handled') IS NULL AND json_extract(r.fields, '$.at') >= ? " +
93
96
  "ORDER BY json_extract(r.fields, '$.at'), r.id")
94
- .all(accountId, STAGE_ENTRY_RECORD, Math.max(since, at - STAGE_TASK_DAYS * DAY))
97
+ .all(accountId, STAGE_ENTRY_RECORD, from)
95
98
  .map((row) => {
96
99
  const ref = `${String(row.kind)}:${String(row.item_id)}`;
97
100
  return {
@@ -0,0 +1,84 @@
1
+ import type { CacheDatabase } from "../driver.js";
2
+ import type { StoreContext } from "./open.js";
3
+ type Row = Record<string, unknown>;
4
+ /** Why a sync took a document out of its copy. Only `deleted` is a deletion the source reported. */
5
+ export declare const DOCUMENT_REMOVALS: readonly ["deleted", "unavailable", "unsynced"];
6
+ export type DocumentRemoval = (typeof DOCUMENT_REMOVALS)[number];
7
+ /** What replaced a kept version: an edit, or one of the removals. */
8
+ export type VersionReason = "edited" | DocumentRemoval;
9
+ export declare const DOCUMENT_EVENTS: readonly ["added", "changed", "restored", "deleted", "unavailable", "unsynced"];
10
+ export type DocumentEvent = (typeof DOCUMENT_EVENTS)[number];
11
+ /** One earlier version of a document, as the store kept it before something replaced it. */
12
+ export interface DocumentVersion {
13
+ revision: number;
14
+ title: string | null;
15
+ reason: VersionReason;
16
+ /** When this version was replaced or removed; the current version's is when it was written. */
17
+ replacedAt: string | null;
18
+ current: boolean;
19
+ characters: number;
20
+ }
21
+ export interface DocumentVersionText extends DocumentVersion {
22
+ text: string;
23
+ frontMatter: unknown;
24
+ }
25
+ export interface DocumentHistoryAnswer {
26
+ ref: string;
27
+ title: string | null;
28
+ path: string;
29
+ revision: number;
30
+ deletedAt: string | null;
31
+ removal: DocumentRemoval | null;
32
+ /** Newest first, the current version at the top. */
33
+ versions: DocumentVersion[];
34
+ }
35
+ export interface DocumentChange {
36
+ ref: string;
37
+ path: string;
38
+ title: string | null;
39
+ event: DocumentEvent;
40
+ revision: number;
41
+ at: string;
42
+ }
43
+ export interface DocumentHistoryStore {
44
+ /** The document at this path of a documents account, a removed one too, as `document:<n>`. */
45
+ documentAt(folderId: string, path: string): Promise<string | undefined>;
46
+ documentHistory(reference: string): Promise<DocumentHistoryAnswer>;
47
+ documentVersion(reference: string, revision: number): Promise<DocumentVersionText>;
48
+ /** What changed in the account at or after `since` (ISO 8601), newest first. */
49
+ documentChanges(folderId: string, options: {
50
+ since: string;
51
+ until?: string;
52
+ events?: readonly DocumentEvent[];
53
+ limit: number;
54
+ offset: number;
55
+ }): Promise<{
56
+ items: DocumentChange[];
57
+ hasMore: boolean;
58
+ }>;
59
+ /**
60
+ * Drops the versions and the change log of the account older than `before` (ISO 8601), and the text of a document
61
+ * that has been unavailable since before then. Answers what it dropped.
62
+ */
63
+ pruneDocumentHistory(folderId: string, before: string): Promise<{
64
+ versions: number;
65
+ changes: number;
66
+ texts: number;
67
+ }>;
68
+ }
69
+ /**
70
+ * Keeps a document's text, title and front matter under its current revision before the caller replaces or removes
71
+ * them with `revision + 1`, so a citation reads back the words it cited and the history shows what was there.
72
+ */
73
+ export declare const keepRevision: (database: CacheDatabase, row: Row, at: number, reason?: VersionReason) => {
74
+ changes: number;
75
+ };
76
+ /** One line of the change log, from the document row as it is after the change. */
77
+ export declare const logDocumentChange: (database: CacheDatabase, id: number, event: DocumentEvent, at: number) => void;
78
+ /**
79
+ * Takes a document out of the live copy for `reason`. An unavailable one keeps its text, since the source may show it
80
+ * again; a deleted or unsynced one keeps its last text as a version and its body is blanked.
81
+ */
82
+ export declare const removeDocument: (database: CacheDatabase, id: number, at: number, reason: DocumentRemoval) => boolean;
83
+ export declare const documentHistoryOver: ({ database }: StoreContext) => DocumentHistoryStore;
84
+ export {};
@@ -0,0 +1,158 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { thingOf } from "./things.js";
3
+ import { write } from "./transaction.js";
4
+ /** Why a sync took a document out of its copy. Only `deleted` is a deletion the source reported. */
5
+ export const DOCUMENT_REMOVALS = ["deleted", "unavailable", "unsynced"];
6
+ export const DOCUMENT_EVENTS = ["added", "changed", "restored", ...DOCUMENT_REMOVALS];
7
+ const iso = (value) => (value == null ? null : new Date(Number(value)).toISOString());
8
+ const json = (value) => (value == null ? null : JSON.parse(String(value)));
9
+ /**
10
+ * Keeps a document's text, title and front matter under its current revision before the caller replaces or removes
11
+ * them with `revision + 1`, so a citation reads back the words it cited and the history shows what was there.
12
+ */
13
+ export const keepRevision = (database, row, at, reason = "edited") => database
14
+ .prepare("INSERT INTO document_revisions (document_id, body, revision, created_at, title, front_matter, reason) " +
15
+ "VALUES (?, ?, ?, ?, ?, ?, ?)")
16
+ .run(Number(row.id), String(row.body ?? ""), Number(row.revision), at, row.title == null ? null : String(row.title), row.front_matter == null ? null : String(row.front_matter), reason);
17
+ /** One line of the change log, from the document row as it is after the change. */
18
+ export const logDocumentChange = (database, id, event, at) => {
19
+ const row = database.prepare("SELECT account_id, external_id, title, revision FROM documents WHERE id = ?").get(id);
20
+ if (!row)
21
+ return;
22
+ database
23
+ .prepare("INSERT INTO document_changes (account_id, document_id, path, title, event, revision, at) " +
24
+ "VALUES (?, ?, ?, ?, ?, ?, ?)")
25
+ .run(Number(row.account_id), id, String(row.external_id), row.title == null ? null : String(row.title), event, Number(row.revision), at);
26
+ };
27
+ /**
28
+ * Takes a document out of the live copy for `reason`. An unavailable one keeps its text, since the source may show it
29
+ * again; a deleted or unsynced one keeps its last text as a version and its body is blanked.
30
+ */
31
+ export const removeDocument = (database, id, at, reason) => {
32
+ const row = database.prepare("SELECT * FROM documents WHERE id = ? AND deleted_at IS NULL").get(id);
33
+ if (!row)
34
+ return false;
35
+ if (reason === "unavailable")
36
+ database.prepare("UPDATE documents SET deleted_at = ?, removal = ? WHERE id = ?").run(at, reason, id);
37
+ else {
38
+ if (row.body != null)
39
+ keepRevision(database, row, at, reason);
40
+ database
41
+ .prepare("UPDATE documents SET deleted_at = ?, removal = ?, body = '', revision = revision + 1 WHERE id = ?")
42
+ .run(at, reason, id);
43
+ }
44
+ logDocumentChange(database, id, reason, at);
45
+ return true;
46
+ };
47
+ const removalOf = (value) => DOCUMENT_REMOVALS.includes(value) ? value : null;
48
+ export const documentHistoryOver = ({ database }) => {
49
+ const account = (folderId) => {
50
+ const row = /^\d+$/.test(folderId)
51
+ ? database.prepare("SELECT id FROM accounts WHERE id = ?").get(Number(folderId))
52
+ : undefined;
53
+ if (!row)
54
+ throw new CliError("not_found", `no documents account ${folderId} in the local store`);
55
+ return Number(row.id);
56
+ };
57
+ const documentRow = (reference) => {
58
+ const thing = thingOf(database, reference);
59
+ const row = thing?.type === "document" ? database.prepare("SELECT * FROM documents WHERE id = ?").get(thing.id) : undefined;
60
+ if (!row)
61
+ throw new CliError("not_found", `document ${reference} is not in the local store`);
62
+ return row;
63
+ };
64
+ const kept = (id) => database
65
+ .prepare("SELECT revision, title, front_matter, reason, body, created_at FROM document_revisions " +
66
+ "WHERE document_id = ? ORDER BY revision DESC, id DESC")
67
+ .all(id);
68
+ const keptVersion = (row, current = false) => ({
69
+ revision: Number(row.revision),
70
+ title: row.title == null ? null : String(row.title),
71
+ reason: current ? "edited" : (row.reason ?? "edited"),
72
+ replacedAt: current ? null : iso(row.created_at),
73
+ current,
74
+ characters: String(row.body ?? "").length,
75
+ });
76
+ // A removed document's row holds no text of its own once its last version was kept: it is not a version then.
77
+ const currentShown = (row) => row.deleted_at == null || String(row.body ?? "") !== "";
78
+ return {
79
+ documentAt: async (folderId, path) => {
80
+ const row = database
81
+ .prepare("SELECT id FROM documents WHERE account_id = ? AND external_id = ?")
82
+ .get(account(folderId), path);
83
+ return row ? `document:${row.id}` : undefined;
84
+ },
85
+ documentHistory: async (reference) => {
86
+ const row = documentRow(reference);
87
+ const id = Number(row.id);
88
+ return {
89
+ ref: `document:${id}`,
90
+ title: row.title == null ? null : String(row.title),
91
+ path: String(row.external_id),
92
+ revision: Number(row.revision),
93
+ deletedAt: iso(row.deleted_at),
94
+ removal: row.deleted_at == null ? null : removalOf(row.removal),
95
+ versions: [
96
+ ...(currentShown(row) ? [{ ...keptVersion(row, true), replacedAt: iso(row.updated_at) }] : []),
97
+ ...kept(id).map((one) => keptVersion(one)),
98
+ ],
99
+ };
100
+ },
101
+ documentVersion: async (reference, revision) => {
102
+ const row = documentRow(reference);
103
+ if (Number(row.revision) === revision && currentShown(row))
104
+ return {
105
+ ...keptVersion(row, true),
106
+ replacedAt: iso(row.updated_at),
107
+ text: String(row.body ?? ""),
108
+ frontMatter: json(row.front_matter),
109
+ };
110
+ const found = kept(Number(row.id)).find((one) => Number(one.revision) === revision);
111
+ if (!found)
112
+ throw new CliError("not_found", `document ${reference} has no version ${revision} in the local store`, {
113
+ reason: "document.version-missing",
114
+ });
115
+ return { ...keptVersion(found), text: String(found.body ?? ""), frontMatter: json(found.front_matter) };
116
+ },
117
+ documentChanges: async (folderId, { since, until, events, limit, offset }) => {
118
+ const from = Date.parse(since);
119
+ const to = until === undefined ? Number.MAX_SAFE_INTEGER : Date.parse(until);
120
+ if (Number.isNaN(from) || Number.isNaN(to))
121
+ throw new CliError("validation_error", "since and until take an ISO 8601 time");
122
+ const kinds = events?.length ? events : DOCUMENT_EVENTS;
123
+ const rows = database
124
+ .prepare("SELECT * FROM document_changes WHERE account_id = ? AND at >= ? AND at <= ? " +
125
+ `AND event IN (${kinds.map(() => "?").join(", ")}) ORDER BY at DESC, id DESC LIMIT ? OFFSET ?`)
126
+ .all(account(folderId), from, to, ...kinds, limit + 1, offset);
127
+ return {
128
+ items: rows.slice(0, limit).map((row) => ({
129
+ ref: `document:${row.document_id}`,
130
+ path: String(row.path),
131
+ title: row.title == null ? null : String(row.title),
132
+ event: row.event,
133
+ revision: Number(row.revision),
134
+ at: iso(row.at),
135
+ })),
136
+ hasMore: rows.length > limit,
137
+ };
138
+ },
139
+ pruneDocumentHistory: async (folderId, before) => write(database, () => {
140
+ const id = account(folderId);
141
+ const cut = Date.parse(before);
142
+ if (Number.isNaN(cut))
143
+ throw new CliError("validation_error", "before takes an ISO 8601 time");
144
+ const versions = database
145
+ .prepare("DELETE FROM document_revisions WHERE created_at < ? " +
146
+ "AND document_id IN (SELECT id FROM documents WHERE account_id = ?)")
147
+ .run(cut, id).changes;
148
+ const changes = database
149
+ .prepare("DELETE FROM document_changes WHERE account_id = ? AND at < ?")
150
+ .run(id, cut).changes;
151
+ const texts = database
152
+ .prepare("UPDATE documents SET body = '', revision = revision + 1 WHERE account_id = ? AND removal = 'unavailable' " +
153
+ "AND deleted_at IS NOT NULL AND deleted_at < ? AND body <> ''")
154
+ .run(id, cut).changes;
155
+ return { versions, changes, texts };
156
+ }),
157
+ };
158
+ };
@@ -0,0 +1,19 @@
1
+ import type { CacheDatabase } from "../driver.js";
2
+ export declare const count: (database: CacheDatabase, sql: string, ...params: (string | number)[]) => number;
3
+ /**
4
+ * What deleting an entity does to the rows that name it, read from the store's own `*_type`/`*_id` pointers and
5
+ * foreign keys, so the plan shown and the delete run read one list. A row that only ties something to the entity
6
+ * goes; one that can be without it loses the pointer; one that cannot, or that the entity wrote, blocks the delete.
7
+ */
8
+ export declare class ErasePlan {
9
+ #private;
10
+ private readonly database;
11
+ readonly deleted: Record<string, number>;
12
+ readonly detached: Record<string, number>;
13
+ readonly blocked: string[];
14
+ constructor(database: CacheDatabase);
15
+ pointers(type: string, among: string, params: (string | number)[]): this;
16
+ /** Foreign keys to `target`, but those in `own`, which the caller deletes with the entity. */
17
+ foreignKeys(target: string, id: number, own: ReadonlySet<string>): this;
18
+ run(): void;
19
+ }
@@ -0,0 +1,74 @@
1
+ import { pointerPairs } from "./entity-types.js";
2
+ /** Who wrote or approved a row: the row is the writer's history, never silently rewritten. */
3
+ const AUTHORS = new Set(["author", "confirmed_by", "decided_by", "proposed_by", "actor", "closed_by"]);
4
+ /** A link is about both ends: one that loses an end means nothing, so it goes. */
5
+ const LINK_ROWS = new Set(["links", "mentions", "task_assignments"]);
6
+ const hasChildren = (database, table) => database
7
+ .prepare(`SELECT 1 FROM sqlite_master m JOIN pragma_foreign_key_list(m.name) f WHERE m.type = 'table' AND f."table" = ?
8
+ LIMIT 1`)
9
+ .get(table) !== undefined;
10
+ const nullable = (database, table, column) => Number(database.prepare(`SELECT "notnull" AS n FROM pragma_table_info('${table}') WHERE name = ?`).get(column)?.n) ===
11
+ 0;
12
+ export const count = (database, sql, ...params) => Number(database.prepare(`SELECT count(*) AS n FROM ${sql}`).get(...params)?.n);
13
+ /**
14
+ * What deleting an entity does to the rows that name it, read from the store's own `*_type`/`*_id` pointers and
15
+ * foreign keys, so the plan shown and the delete run read one list. A row that only ties something to the entity
16
+ * goes; one that can be without it loses the pointer; one that cannot, or that the entity wrote, blocks the delete.
17
+ */
18
+ export class ErasePlan {
19
+ database;
20
+ deleted = {};
21
+ detached = {};
22
+ blocked = [];
23
+ #steps = [];
24
+ constructor(database) {
25
+ this.database = database;
26
+ }
27
+ pointers(type, among, params) {
28
+ for (const { table, pointer } of pointerPairs(this.database)) {
29
+ const where = `${pointer}_type = '${type}' AND ${pointer}_id IN (${among})`;
30
+ const n = count(this.database, `"${table}" WHERE ${where}`, ...params);
31
+ if (n === 0)
32
+ continue;
33
+ const key = `${table}.${pointer}`;
34
+ if (LINK_ROWS.has(table) || !nullable(this.database, table, `${pointer}_id`)) {
35
+ if (!LINK_ROWS.has(table) && (AUTHORS.has(pointer) || hasChildren(this.database, table))) {
36
+ this.blocked.push(`${n} ${table} (${pointer})`);
37
+ continue;
38
+ }
39
+ this.#add(this.deleted, key, n, `DELETE FROM "${table}" WHERE ${where}`, params);
40
+ }
41
+ else
42
+ this.#add(this.detached, key, n, `UPDATE "${table}" SET ${pointer}_type = NULL, ${pointer}_id = NULL WHERE ${where}`, params);
43
+ }
44
+ return this;
45
+ }
46
+ /** Foreign keys to `target`, but those in `own`, which the caller deletes with the entity. */
47
+ foreignKeys(target, id, own) {
48
+ for (const row of this.database
49
+ .prepare(`SELECT m.name AS tbl, f."from" AS col FROM sqlite_master m JOIN pragma_foreign_key_list(m.name) f
50
+ WHERE m.type = 'table' AND f."table" = ?`)
51
+ .all(target)) {
52
+ const table = String(row.tbl);
53
+ const column = String(row.col);
54
+ if (own.has(table))
55
+ continue;
56
+ const n = count(this.database, `"${table}" WHERE "${column}" = ?`, id);
57
+ if (n === 0)
58
+ continue;
59
+ if (nullable(this.database, table, column))
60
+ this.#add(this.detached, `${table}.${column}`, n, `UPDATE "${table}" SET "${column}" = NULL WHERE "${column}" = ?`, [id]);
61
+ else
62
+ this.blocked.push(`${n} ${table} (${column})`);
63
+ }
64
+ return this;
65
+ }
66
+ run() {
67
+ for (const step of this.#steps)
68
+ step();
69
+ }
70
+ #add(into, key, n, sql, params) {
71
+ into[key] = (into[key] ?? 0) + n;
72
+ this.#steps.push(() => this.database.prepare(sql).run(...params));
73
+ }
74
+ }
@@ -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 = [];
@@ -171,7 +171,8 @@ export const upsertMessage = (context, key, accountKey, chatKey, received, via,
171
171
  for (const field of ["views", "comments"])
172
172
  if (!validCounter(incoming[field]) && validCounter(previous[field]))
173
173
  incoming[field] = previous[field];
174
- fields.metadata = JSON.stringify(edit ? { ...previous, ...incoming } : incoming);
174
+ // A server search hit is a partial copy: what it leaves out (a thread's reply count) is not gone.
175
+ fields.metadata = JSON.stringify(edit || via === "search" ? { ...previous, ...incoming } : incoming);
175
176
  }
176
177
  }
177
178
  catch {