@wirecat/cli-core 0.661.0 → 0.663.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 (201) hide show
  1. package/CHANGELOG.md +109 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/calendar/cli/bodies.js +2 -1
  4. package/dist/calendar/cli/index.js +13 -10
  5. package/dist/calendar/mcp/index.d.ts +3 -1
  6. package/dist/calendar/mcp/index.js +4 -4
  7. package/dist/cli/ai-model-command.js +3 -3
  8. package/dist/cli/call-stats-command.d.ts +18 -0
  9. package/dist/cli/call-stats-command.js +52 -0
  10. package/dist/cli/command-availability.d.ts +1 -1
  11. package/dist/cli/command-availability.js +4 -4
  12. package/dist/cli/contract-templates.js +2 -0
  13. package/dist/cli/dry-run-guard.js +7 -5
  14. package/dist/cli/early-refusal.d.ts +1 -1
  15. package/dist/cli/early-refusal.js +2 -2
  16. package/dist/cli/effects.d.ts +9 -2
  17. package/dist/cli/effects.js +16 -4
  18. package/dist/cli/envelope.d.ts +0 -5
  19. package/dist/cli/envelope.js +25 -0
  20. package/dist/cli/index.d.ts +3 -2
  21. package/dist/cli/index.js +3 -2
  22. package/dist/cli/meeting-batch.d.ts +2 -1
  23. package/dist/cli/meeting-batch.js +7 -5
  24. package/dist/cli/meeting-preparation-command.js +5 -5
  25. package/dist/cli/meeting-preparation-read.d.ts +5 -5
  26. package/dist/cli/meeting-preparation-read.js +13 -21
  27. package/dist/cli/meeting-series-inventory-command.js +2 -2
  28. package/dist/cli/meeting-series-inventory-read.d.ts +2 -2
  29. package/dist/cli/meeting-series-inventory-read.js +7 -15
  30. package/dist/cli/messenger/admin-moderation-command.js +2 -2
  31. package/dist/cli/messenger/admin-statistics-command.js +2 -2
  32. package/dist/cli/messenger/archive-commands.js +2 -2
  33. package/dist/cli/messenger/context.d.ts +2 -2
  34. package/dist/cli/messenger/context.js +5 -3
  35. package/dist/cli/messenger/counters-command.js +2 -2
  36. package/dist/cli/messenger/media-archive-command.js +5 -4
  37. package/dist/cli/messenger/media-archive-move-command.js +1 -1
  38. package/dist/cli/messenger/media-archive-timer-command.js +5 -4
  39. package/dist/cli/messenger/metadata-command.js +3 -3
  40. package/dist/cli/messenger/rankings-command.js +3 -3
  41. package/dist/cli/messenger/tags-command.js +7 -2
  42. package/dist/cli/messenger/tasks-command.js +4 -3
  43. package/dist/cli/paging.d.ts +10 -0
  44. package/dist/cli/paging.js +29 -0
  45. package/dist/cli/preview.js +3 -5
  46. package/dist/cli/program.js +2 -2
  47. package/dist/cli/runs/command.js +6 -4
  48. package/dist/cli/runs/search-command.js +9 -5
  49. package/dist/cli/schedule/schedule-command.js +1 -5
  50. package/dist/cli/shadowed-options.d.ts +7 -0
  51. package/dist/cli/shadowed-options.js +26 -0
  52. package/dist/crm/cli/index.js +4 -2
  53. package/dist/domain/moment.d.ts +29 -0
  54. package/dist/domain/moment.js +58 -0
  55. package/dist/domain/providers.d.ts +6 -4
  56. package/dist/domain/providers.js +10 -5
  57. package/dist/domain/send-time.d.ts +3 -4
  58. package/dist/domain/send-time.js +10 -24
  59. package/dist/entities/fields.d.ts +2 -2
  60. package/dist/entities/fields.js +2 -2
  61. package/dist/entities/index.d.ts +92 -1
  62. package/dist/entities/index.js +3 -2
  63. package/dist/entities/meeting.d.ts +1 -1
  64. package/dist/entities/meeting.js +1 -1
  65. package/dist/errors/reasons.js +0 -1
  66. package/dist/kit/sync-after-install.d.ts +10 -1
  67. package/dist/kit/sync-after-install.js +35 -11
  68. package/dist/mail/cli/index.js +4 -2
  69. package/dist/mail/facts.d.ts +5 -2
  70. package/dist/mail/facts.js +6 -3
  71. package/dist/mail/index.d.ts +1 -1
  72. package/dist/mail/meeting-notes.js +1 -1
  73. package/dist/mail/probe.d.ts +5 -2
  74. package/dist/mail/probe.js +9 -5
  75. package/dist/mail/server-search.js +4 -4
  76. package/dist/mail/sync.js +1 -1
  77. package/dist/mcp/meeting-preparation.js +1 -1
  78. package/dist/mcp/meeting-series-inventory.js +1 -1
  79. package/dist/mcp/prompts.js +6 -9
  80. package/dist/mcp/server.js +4 -4
  81. package/dist/mcp/tool.js +3 -3
  82. package/dist/meetings/call-answers.d.ts +106 -0
  83. package/dist/meetings/call-answers.js +171 -0
  84. package/dist/meetings/call-stats.d.ts +121 -0
  85. package/dist/meetings/call-stats.js +211 -0
  86. package/dist/meetings/calls.d.ts +76 -0
  87. package/dist/meetings/calls.js +78 -0
  88. package/dist/meetings/cli/index.d.ts +8 -0
  89. package/dist/meetings/cli/index.js +10 -22
  90. package/dist/meetings/cli/search.d.ts +9 -2
  91. package/dist/meetings/cli/search.js +16 -26
  92. package/dist/meetings/index.d.ts +3 -0
  93. package/dist/meetings/index.js +3 -0
  94. package/dist/meetings/mcp/index.d.ts +21 -18
  95. package/dist/meetings/mcp/index.js +2 -4
  96. package/dist/meetings/mcp/search.d.ts +6 -1
  97. package/dist/meetings/mcp/search.js +3 -3
  98. package/dist/meetings/read-through.d.ts +2 -1
  99. package/dist/meetings/read-through.js +10 -1
  100. package/dist/meetings/stats.d.ts +3 -0
  101. package/dist/meetings/stats.js +3 -3
  102. package/dist/meetings/testing/index.d.ts +1 -0
  103. package/dist/meetings/testing/index.js +1 -0
  104. package/dist/meetings/testing/paging.d.ts +6 -0
  105. package/dist/meetings/testing/paging.js +5 -0
  106. package/dist/moderation/rules.d.ts +2 -0
  107. package/dist/moderation/rules.js +16 -2
  108. package/dist/search/fusion.d.ts +17 -0
  109. package/dist/search/fusion.js +17 -0
  110. package/dist/search/lucene/resolved.d.ts +2 -0
  111. package/dist/search/question-plan.d.ts +2 -0
  112. package/dist/search/question-plan.js +5 -0
  113. package/dist/search/service-query.d.ts +6 -1
  114. package/dist/search/service-query.js +9 -1
  115. package/dist/sends/guard.js +4 -20
  116. package/dist/sends/keyed-guard.d.ts +1 -1
  117. package/dist/sends/keyed-guard.js +2 -1
  118. package/dist/sends/permissions.d.ts +14 -0
  119. package/dist/sends/permissions.js +32 -0
  120. package/dist/services/agenda-mail.js +2 -1
  121. package/dist/services/agenda.js +5 -3
  122. package/dist/services/attachments.js +4 -2
  123. package/dist/services/call-stats.d.ts +17 -0
  124. package/dist/services/call-stats.js +41 -0
  125. package/dist/services/chats.js +4 -2
  126. package/dist/services/conversations.js +4 -2
  127. package/dist/services/deps.d.ts +1 -1
  128. package/dist/services/document-source.d.ts +1 -1
  129. package/dist/services/document-source.js +4 -3
  130. package/dist/services/documents/ingestion.js +11 -40
  131. package/dist/services/documents/plan.d.ts +1 -1
  132. package/dist/services/documents/plan.js +30 -17
  133. package/dist/services/documents/ports.d.ts +5 -0
  134. package/dist/services/documents/sync.js +1 -1
  135. package/dist/services/embeddings-search.js +20 -4
  136. package/dist/services/events-search.js +2 -1
  137. package/dist/services/index.d.ts +1 -0
  138. package/dist/services/index.js +1 -0
  139. package/dist/services/mail-search.d.ts +1 -1
  140. package/dist/services/mail-search.js +10 -11
  141. package/dist/services/media-archive-move.js +2 -4
  142. package/dist/services/media-archive.d.ts +0 -1
  143. package/dist/services/media-archive.js +2 -12
  144. package/dist/services/meeting-combined.js +1 -1
  145. package/dist/services/messages-combined.js +15 -4
  146. package/dist/services/moderation.js +10 -2
  147. package/dist/services/moment.d.ts +4 -10
  148. package/dist/services/moment.js +16 -44
  149. package/dist/services/notes-search.d.ts +0 -2
  150. package/dist/services/notes-search.js +1 -2
  151. package/dist/services/search-all.js +2 -1
  152. package/dist/services/server-search.js +1 -1
  153. package/dist/services/tags.js +4 -2
  154. package/dist/services/task-stats.js +2 -2
  155. package/dist/services/tasks.js +2 -2
  156. package/dist/store/accounts.js +2 -1
  157. package/dist/store/sqlite/account-purge.d.ts +3 -0
  158. package/dist/store/sqlite/account-purge.js +143 -0
  159. package/dist/store/sqlite/accounts.d.ts +0 -2
  160. package/dist/store/sqlite/accounts.js +2 -134
  161. package/dist/store/sqlite/calendar.d.ts +1 -0
  162. package/dist/store/sqlite/calendar.js +5 -5
  163. package/dist/store/sqlite/catalog.js +2 -16
  164. package/dist/store/sqlite/chats.js +2 -1
  165. package/dist/store/sqlite/context-document-source.d.ts +3 -3
  166. package/dist/store/sqlite/context-document-source.js +9 -7
  167. package/dist/store/sqlite/context-evidence.js +9 -3
  168. package/dist/store/sqlite/document-listing.js +2 -1
  169. package/dist/store/sqlite/events.js +2 -1
  170. package/dist/store/sqlite/file-note.d.ts +6 -0
  171. package/dist/store/sqlite/file-note.js +15 -0
  172. package/dist/store/sqlite/files.d.ts +3 -2
  173. package/dist/store/sqlite/files.js +5 -3
  174. package/dist/store/sqlite/identities.js +2 -1
  175. package/dist/store/sqlite/imported-documents.js +2 -2
  176. package/dist/store/sqlite/knowledge.js +19 -19
  177. package/dist/store/sqlite/lucene-fields.js +8 -12
  178. package/dist/store/sqlite/mail-rules.js +2 -1
  179. package/dist/store/sqlite/meeting-calls.d.ts +4 -0
  180. package/dist/store/sqlite/meeting-calls.js +66 -0
  181. package/dist/store/sqlite/meetings.d.ts +2 -2
  182. package/dist/store/sqlite/meetings.js +4 -1
  183. package/dist/store/sqlite/mention-sources.js +2 -1
  184. package/dist/store/sqlite/mentions.js +2 -2
  185. package/dist/store/sqlite/messages.js +6 -1
  186. package/dist/store/sqlite/note-search.js +8 -11
  187. package/dist/store/sqlite/notes.d.ts +2 -0
  188. package/dist/store/sqlite/notes.js +24 -13
  189. package/dist/store/sqlite/organizations.js +2 -2
  190. package/dist/store/sqlite/people-list.js +3 -3
  191. package/dist/store/sqlite/query-filter.d.ts +3 -3
  192. package/dist/store/sqlite/query-filter.js +3 -3
  193. package/dist/store/sqlite/reads.d.ts +4 -4
  194. package/dist/store/sqlite/reads.js +4 -4
  195. package/dist/store/sqlite/search.js +11 -7
  196. package/dist/store/sqlite/test-accounts.js +1 -1
  197. package/dist/store/sqlite/trigram-match.d.ts +9 -0
  198. package/dist/store/sqlite/trigram-match.js +28 -0
  199. package/dist/store/sqlite/work-tasks.js +1 -1
  200. package/package.json +3 -3
  201. package/parity.json +2 -1
@@ -1,6 +1,7 @@
1
1
  import { ACCOUNT_GROUPS } from "../search/account-list.js";
2
2
  import { keysOver } from "./keys.js";
3
3
  import { accountGroupsOf, forgetProfile, profilesOf, saveProfile } from "./sqlite/account-groups.js";
4
+ import { purgeAccount } from "./sqlite/account-purge.js";
4
5
  import * as accounts from "./sqlite/accounts.js";
5
6
  import { linkOwnIdentities } from "./sqlite/own-identities.js";
6
7
  import { registerProvider } from "./sqlite/providers.js";
@@ -25,7 +26,7 @@ export const accountAccountsOver = (context) => {
25
26
  const accountKey = findAccountPk(key);
26
27
  if (accountKey === undefined)
27
28
  return;
28
- write(database, () => accounts.purgeAccount(context, accountKey));
29
+ write(database, () => purgeAccount(context, accountKey));
29
30
  },
30
31
  };
31
32
  };
@@ -0,0 +1,3 @@
1
+ import type { StoreContext } from "./open.js";
2
+ /** Everything the account holds, children before parents: the foreign keys are enforced. */
3
+ export declare const purgeAccount: (context: StoreContext, accountKey: number) => void;
@@ -0,0 +1,143 @@
1
+ import { dropOrphanPeople, unreferenced } from "./accounts.js";
2
+ import { calendarCursorKey, calendarWritesOver } from "./calendar.js";
3
+ import { forgetCalendarRows } from "./calendar-forget.js";
4
+ import { eq, inArray, sql } from "./drizzle/core.js";
5
+ import { forgetDanglingEvidence, forgetEvidenceTo } from "./evidence-signature.js";
6
+ 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";
7
+ import { dropUnusedVectors } from "./vector-index.js";
8
+ /** Everything the account holds, children before parents: the foreign keys are enforced. */
9
+ export const purgeAccount = (context, accountKey) => {
10
+ const { orm, database, now } = context;
11
+ const unseenBefore = unreferenced(database, "identities");
12
+ const at = now();
13
+ const meetingIds = "SELECT id FROM meetings WHERE account_id = ?";
14
+ const transcriptIds = `SELECT id FROM meeting_transcripts WHERE meeting_id IN (${meetingIds})`;
15
+ for (const [type, sql] of [
16
+ ["message", "SELECT id FROM messages WHERE account_id = ?"],
17
+ ["chat", "SELECT id FROM chats WHERE account_id = ?"],
18
+ ["email", "SELECT id FROM emails WHERE account_id = ?"],
19
+ ["email_thread", "SELECT id FROM email_threads WHERE account_id = ?"],
20
+ ["meeting", meetingIds],
21
+ ["meeting_transcript", transcriptIds],
22
+ [
23
+ "meeting_transcript_row",
24
+ `SELECT id FROM meeting_transcript_rows WHERE meeting_transcript_id IN (${transcriptIds})`,
25
+ ],
26
+ ])
27
+ forgetEvidenceTo(database, type, { sql, params: [accountKey] }, at);
28
+ const { refreshEvent, refreshSeries } = calendarWritesOver(context);
29
+ for (const { id } of database.prepare("SELECT id FROM calendars WHERE account_id = ?").all(accountKey))
30
+ forgetCalendarRows(database, { calendarId: Number(id), accountId: accountKey, cursorKey: calendarCursorKey(Number(id)), now: at }, { event: refreshEvent, series: refreshSeries });
31
+ for (const table of ["mail_rules", "reminders", "proposed_actions"])
32
+ database.prepare(`DELETE FROM ${table} WHERE account_id = ?`).run(accountKey);
33
+ const chatsOf = orm.select({ pk: chats.id }).from(chats).where(eq(chats.accountId, accountKey));
34
+ const messagesOf = orm.select({ pk: messages.id }).from(messages).where(eq(messages.accountId, accountKey));
35
+ orm.delete(botUpdates).where(eq(botUpdates.accountId, accountKey)).run();
36
+ orm.delete(involvements).where(eq(involvements.accountId, accountKey)).run();
37
+ // Vectors are keyed by text: those of this account's pieces go at the end, unless another piece holds that text.
38
+ const hashes = orm
39
+ .all(sql `SELECT DISTINCT content_hash AS hash FROM chunks WHERE account_id = ${accountKey}`)
40
+ .map(({ hash }) => hash);
41
+ orm.delete(chunks).where(eq(chunks.accountId, accountKey)).run();
42
+ orm.delete(aliases).where(eq(aliases.accountId, accountKey)).run();
43
+ orm.delete(syncs).where(eq(syncs.accountId, accountKey)).run();
44
+ orm.delete(messageTranscripts).where(inArray(messageTranscripts.chatId, chatsOf)).run();
45
+ orm.delete(pollVotes).where(inArray(pollVotes.chatId, chatsOf)).run();
46
+ orm.delete(messageReactions).where(inArray(messageReactions.chatId, chatsOf)).run();
47
+ orm
48
+ .delete(chatEventPeople)
49
+ .where(inArray(chatEventPeople.chatEventId, orm.select({ id: chatEvents.id }).from(chatEvents).where(inArray(chatEvents.chatId, chatsOf))))
50
+ .run();
51
+ orm.delete(chatEvents).where(inArray(chatEvents.chatId, chatsOf)).run();
52
+ orm.delete(fetchLeases).where(inArray(fetchLeases.chatId, chatsOf)).run();
53
+ orm.delete(chatMembers).where(inArray(chatMembers.chatId, chatsOf)).run();
54
+ const observationsOf = orm
55
+ .select({ id: memberObservations.id })
56
+ .from(memberObservations)
57
+ .where(inArray(memberObservations.chatId, chatsOf));
58
+ orm
59
+ .delete(memberObservationMembers)
60
+ .where(inArray(memberObservationMembers.memberObservationId, observationsOf))
61
+ .run();
62
+ orm.delete(memberObservations).where(inArray(memberObservations.chatId, chatsOf)).run();
63
+ orm.delete(memberStays).where(inArray(memberStays.chatId, chatsOf)).run();
64
+ orm.delete(memberCounts).where(inArray(memberCounts.chatId, chatsOf)).run();
65
+ orm.delete(syncRanges).where(inArray(syncRanges.chatId, chatsOf)).run();
66
+ orm.delete(messageRevisions).where(inArray(messageRevisions.messageId, messagesOf)).run();
67
+ orm.delete(messages).where(eq(messages.accountId, accountKey)).run();
68
+ orm.delete(chats).where(eq(chats.accountId, accountKey)).run();
69
+ orm.delete(syncCursors).where(eq(syncCursors.accountId, accountKey)).run();
70
+ orm.run(sql `DELETE FROM email_locations WHERE mailbox_id IN (SELECT id FROM mailboxes WHERE account_id = ${accountKey})`);
71
+ // Deleting an email clears its recipients, mailboxes, words, attachments and tags (trigger email_bd).
72
+ orm.run(sql `DELETE FROM emails WHERE account_id = ${accountKey}`);
73
+ orm.run(sql `DELETE FROM taggings WHERE taggable_type = 'email_thread' AND taggable_id IN (SELECT id FROM email_threads WHERE account_id = ${accountKey})`);
74
+ orm.run(sql `DELETE FROM email_threads WHERE account_id = ${accountKey}`);
75
+ orm.run(sql `DELETE FROM mailboxes WHERE account_id = ${accountKey}`);
76
+ // Meetings have no delete trigger: children first, then what points at a meeting, then the meetings.
77
+ const meetingsOf = sql `(SELECT id FROM meetings WHERE account_id = ${accountKey})`;
78
+ orm.run(sql `DELETE FROM meeting_transcript_rows WHERE meeting_transcript_id IN (SELECT id FROM meeting_transcripts WHERE meeting_id IN ${meetingsOf})`);
79
+ orm.run(sql `DELETE FROM meeting_transcripts WHERE meeting_id IN ${meetingsOf}`);
80
+ orm.run(sql `DELETE FROM meeting_chat_messages WHERE meeting_id IN ${meetingsOf}`);
81
+ orm.run(sql `DELETE FROM meeting_summaries WHERE meeting_id IN ${meetingsOf}`);
82
+ orm.run(sql `DELETE FROM meeting_participants WHERE meeting_id IN ${meetingsOf}`);
83
+ orm.run(sql `DELETE FROM attachments WHERE attachable_type = 'meeting' AND attachable_id IN ${meetingsOf}`);
84
+ orm.run(sql `DELETE FROM taggings WHERE taggable_type = 'meeting' AND taggable_id IN ${meetingsOf}`);
85
+ orm.run(sql `DELETE FROM links WHERE (from_type = 'meeting' AND from_id IN ${meetingsOf}) OR (to_type = 'meeting' AND to_id IN ${meetingsOf})`);
86
+ orm.run(sql `DELETE FROM meetings WHERE account_id = ${accountKey}`);
87
+ orm.run(sql `DELETE FROM meeting_series WHERE account_id = ${accountKey}`);
88
+ orm.delete(accountIdentities).where(eq(accountIdentities.accountId, accountKey)).run();
89
+ // The inbox project and its tasks are the owner's; only the tie to the account goes.
90
+ orm.update(projects).set({ accountId: null }).where(eq(projects.accountId, accountKey)).run();
91
+ orm.run(sql `DELETE FROM files WHERE account_id = ${accountKey}`);
92
+ // Deleting a document clears its pieces, words, revisions, tags and own links (trigger document_bd).
93
+ const documentsOf = sql `(SELECT id FROM documents WHERE account_id = ${accountKey})`;
94
+ orm.run(sql `DELETE FROM links WHERE to_type = 'document' AND to_id IN ${documentsOf}`);
95
+ orm.run(sql `UPDATE files SET document_id = NULL WHERE document_id IN ${documentsOf}`);
96
+ orm.run(sql `DELETE FROM documents WHERE account_id = ${accountKey}`);
97
+ purgeCrmCopies(database, accountKey);
98
+ orm.run(sql `DELETE FROM crm_fields WHERE account_id = ${accountKey}`);
99
+ // An entity made from a record is the owner's and stays; only what the source said goes.
100
+ const recordsOf = sql `(SELECT id FROM records WHERE account_id = ${accountKey})`;
101
+ orm.run(sql `DELETE FROM record_relations WHERE record_id IN ${recordsOf} OR target_id IN ${recordsOf}`);
102
+ orm.run(sql `DELETE FROM records WHERE account_id = ${accountKey}`);
103
+ orm.delete(accounts).where(eq(accounts.id, accountKey)).run();
104
+ dropOrphanPeople(database, unseenBefore);
105
+ forgetDanglingEvidence(database, at);
106
+ dropUnusedVectors(database, hashes);
107
+ // The links' delete trigger writes a revision naming the account it is purging; the history goes with the links.
108
+ orm.run(sql `DELETE FROM link_revisions WHERE account_id = ${accountKey}`);
109
+ };
110
+ /**
111
+ * A CRM's deals, leads and pipelines with their stages, children first. Another account's lead converted from one
112
+ * of these deals, and an order or contract that names one, keep their row and lose only the link.
113
+ */
114
+ const purgeCrmCopies = (database, accountKey) => {
115
+ const run = (statement, ...params) => database.prepare(statement).run(...params);
116
+ const dealsOf = "(SELECT id FROM deals WHERE account_id = ?)";
117
+ const leadsOf = "(SELECT id FROM leads WHERE account_id = ?)";
118
+ const pipelinesOf = "(SELECT id FROM pipelines WHERE account_id = ?)";
119
+ const stagesOf = `(SELECT id FROM pipeline_stages WHERE pipeline_id IN ${pipelinesOf})`;
120
+ for (const [type, ids] of [
121
+ ["deal", dealsOf],
122
+ ["lead", leadsOf],
123
+ ]) {
124
+ run(`DELETE FROM links WHERE (from_type = ? AND from_id IN ${ids}) OR (to_type = ? AND to_id IN ${ids})`, type, accountKey, type, accountKey);
125
+ for (const [table, pointer] of [
126
+ ["taggings", "taggable"],
127
+ ["aliases", "aliasable"],
128
+ ["attachments", "attachable"],
129
+ ["link_reviews", "linkable"],
130
+ ["entity_link_events", "linkable"],
131
+ ])
132
+ run(`DELETE FROM ${table} WHERE ${pointer}_type = ? AND ${pointer}_id IN ${ids}`, type, accountKey);
133
+ run(`DELETE FROM pipeline_stage_changes WHERE item_type = ? AND item_id IN ${ids}`, type, accountKey);
134
+ }
135
+ run(`DELETE FROM pipeline_stage_changes WHERE pipeline_id IN ${pipelinesOf}`, accountKey);
136
+ for (const table of ["leads", "orders", "contracts"])
137
+ run(`UPDATE ${table} SET deal_id = NULL WHERE deal_id IN ${dealsOf}`, accountKey);
138
+ run("DELETE FROM leads WHERE account_id = ?", accountKey);
139
+ run("DELETE FROM deals WHERE account_id = ?", accountKey);
140
+ run(`UPDATE pipeline_stages SET base_stage_id = NULL WHERE base_stage_id IN ${stagesOf}`, accountKey);
141
+ run(`DELETE FROM pipeline_stages WHERE pipeline_id IN ${pipelinesOf}`, accountKey);
142
+ run("DELETE FROM pipelines WHERE account_id = ?", accountKey);
143
+ };
@@ -19,8 +19,6 @@ export declare const storedAccount: ({ orm }: StoreContext, { provider, account
19
19
  * and facts carry the scope they were written with.
20
20
  */
21
21
  export declare const setAccountScope: (context: StoreContext, key: AccountKey, scope: StoredAccount["scope"]) => StoredAccount;
22
- /** Everything the account holds, children before parents: the foreign keys are enforced. */
23
- export declare const purgeAccount: ({ orm, database, now }: StoreContext, accountKey: number) => void;
24
22
  /** Identity and person rows a person's own record keeps, not evidence that anyone saw them. */
25
23
  export declare const OWN: Set<string>;
26
24
  /**
@@ -1,13 +1,11 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
- import { and, asc, eq, inArray, sql } from "./drizzle/core.js";
2
+ import { and, asc, eq, sql } from "./drizzle/core.js";
3
3
  import { pointerPairs } from "./entity-types.js";
4
- import { forgetDanglingEvidence, forgetEvidenceTo } from "./evidence-signature.js";
5
4
  import { forgetErasedLinks } from "./identity-link-rows.js";
6
5
  import { forgetErasedSplits } from "./identity-split-proposals.js";
7
6
  import { mergeSql } from "./merged-persons.js";
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";
7
+ import { accounts } from "./schema.js";
9
8
  import { forgetErasedTestData } from "./test-people.js";
10
- import { dropUnusedVectors } from "./vector-index.js";
11
9
  /**
12
10
  * An account's row, made on first sight; a name only replaces what was known when there is one. `startScope` is the
13
11
  * scope a new row takes; an existing row keeps its own, so a CLI's default never undoes the owner's choice.
@@ -96,136 +94,6 @@ export const setAccountScope = (context, key, scope) => {
96
94
  .run(held.id);
97
95
  return { ...held, scope };
98
96
  };
99
- /** Everything the account holds, children before parents: the foreign keys are enforced. */
100
- export const purgeAccount = ({ orm, database, now }, accountKey) => {
101
- const unseenBefore = unreferenced(database, "identities");
102
- const at = now();
103
- const meetingIds = "SELECT id FROM meetings WHERE account_id = ?";
104
- const transcriptIds = `SELECT id FROM meeting_transcripts WHERE meeting_id IN (${meetingIds})`;
105
- for (const [type, sql] of [
106
- ["message", "SELECT id FROM messages WHERE account_id = ?"],
107
- ["chat", "SELECT id FROM chats WHERE account_id = ?"],
108
- ["email", "SELECT id FROM emails WHERE account_id = ?"],
109
- ["email_thread", "SELECT id FROM email_threads WHERE account_id = ?"],
110
- ["meeting", meetingIds],
111
- ["meeting_transcript", transcriptIds],
112
- [
113
- "meeting_transcript_row",
114
- `SELECT id FROM meeting_transcript_rows WHERE meeting_transcript_id IN (${transcriptIds})`,
115
- ],
116
- ])
117
- forgetEvidenceTo(database, type, { sql, params: [accountKey] }, at);
118
- const chatsOf = orm.select({ pk: chats.id }).from(chats).where(eq(chats.accountId, accountKey));
119
- const messagesOf = orm.select({ pk: messages.id }).from(messages).where(eq(messages.accountId, accountKey));
120
- orm.delete(botUpdates).where(eq(botUpdates.accountId, accountKey)).run();
121
- orm.delete(involvements).where(eq(involvements.accountId, accountKey)).run();
122
- // Vectors are keyed by text: those of this account's pieces go at the end, unless another piece holds that text.
123
- const hashes = orm
124
- .all(sql `SELECT DISTINCT content_hash AS hash FROM chunks WHERE account_id = ${accountKey}`)
125
- .map(({ hash }) => hash);
126
- orm.delete(chunks).where(eq(chunks.accountId, accountKey)).run();
127
- orm.delete(aliases).where(eq(aliases.accountId, accountKey)).run();
128
- orm.delete(syncs).where(eq(syncs.accountId, accountKey)).run();
129
- orm.delete(messageTranscripts).where(inArray(messageTranscripts.chatId, chatsOf)).run();
130
- orm.delete(pollVotes).where(inArray(pollVotes.chatId, chatsOf)).run();
131
- orm.delete(messageReactions).where(inArray(messageReactions.chatId, chatsOf)).run();
132
- orm
133
- .delete(chatEventPeople)
134
- .where(inArray(chatEventPeople.chatEventId, orm.select({ id: chatEvents.id }).from(chatEvents).where(inArray(chatEvents.chatId, chatsOf))))
135
- .run();
136
- orm.delete(chatEvents).where(inArray(chatEvents.chatId, chatsOf)).run();
137
- orm.delete(fetchLeases).where(inArray(fetchLeases.chatId, chatsOf)).run();
138
- orm.delete(chatMembers).where(inArray(chatMembers.chatId, chatsOf)).run();
139
- const observationsOf = orm
140
- .select({ id: memberObservations.id })
141
- .from(memberObservations)
142
- .where(inArray(memberObservations.chatId, chatsOf));
143
- orm
144
- .delete(memberObservationMembers)
145
- .where(inArray(memberObservationMembers.memberObservationId, observationsOf))
146
- .run();
147
- orm.delete(memberObservations).where(inArray(memberObservations.chatId, chatsOf)).run();
148
- orm.delete(memberStays).where(inArray(memberStays.chatId, chatsOf)).run();
149
- orm.delete(memberCounts).where(inArray(memberCounts.chatId, chatsOf)).run();
150
- orm.delete(syncRanges).where(inArray(syncRanges.chatId, chatsOf)).run();
151
- orm.delete(messageRevisions).where(inArray(messageRevisions.messageId, messagesOf)).run();
152
- orm.delete(messages).where(eq(messages.accountId, accountKey)).run();
153
- orm.delete(chats).where(eq(chats.accountId, accountKey)).run();
154
- orm.delete(syncCursors).where(eq(syncCursors.accountId, accountKey)).run();
155
- orm.run(sql `DELETE FROM email_locations WHERE mailbox_id IN (SELECT id FROM mailboxes WHERE account_id = ${accountKey})`);
156
- // Deleting an email clears its recipients, mailboxes, words, attachments and tags (trigger email_bd).
157
- orm.run(sql `DELETE FROM emails WHERE account_id = ${accountKey}`);
158
- orm.run(sql `DELETE FROM taggings WHERE taggable_type = 'email_thread' AND taggable_id IN (SELECT id FROM email_threads WHERE account_id = ${accountKey})`);
159
- orm.run(sql `DELETE FROM email_threads WHERE account_id = ${accountKey}`);
160
- orm.run(sql `DELETE FROM mailboxes WHERE account_id = ${accountKey}`);
161
- // Meetings have no delete trigger: children first, then what points at a meeting, then the meetings.
162
- const meetingsOf = sql `(SELECT id FROM meetings WHERE account_id = ${accountKey})`;
163
- orm.run(sql `DELETE FROM meeting_transcript_rows WHERE meeting_transcript_id IN (SELECT id FROM meeting_transcripts WHERE meeting_id IN ${meetingsOf})`);
164
- orm.run(sql `DELETE FROM meeting_transcripts WHERE meeting_id IN ${meetingsOf}`);
165
- orm.run(sql `DELETE FROM meeting_chat_messages WHERE meeting_id IN ${meetingsOf}`);
166
- orm.run(sql `DELETE FROM meeting_summaries WHERE meeting_id IN ${meetingsOf}`);
167
- orm.run(sql `DELETE FROM meeting_participants WHERE meeting_id IN ${meetingsOf}`);
168
- orm.run(sql `DELETE FROM attachments WHERE attachable_type = 'meeting' AND attachable_id IN ${meetingsOf}`);
169
- orm.run(sql `DELETE FROM taggings WHERE taggable_type = 'meeting' AND taggable_id IN ${meetingsOf}`);
170
- orm.run(sql `DELETE FROM links WHERE (from_type = 'meeting' AND from_id IN ${meetingsOf}) OR (to_type = 'meeting' AND to_id IN ${meetingsOf})`);
171
- orm.run(sql `DELETE FROM meetings WHERE account_id = ${accountKey}`);
172
- orm.run(sql `DELETE FROM meeting_series WHERE account_id = ${accountKey}`);
173
- orm.delete(accountIdentities).where(eq(accountIdentities.accountId, accountKey)).run();
174
- // The inbox project and its tasks are the owner's; only the tie to the account goes.
175
- orm.update(projects).set({ accountId: null }).where(eq(projects.accountId, accountKey)).run();
176
- orm.run(sql `DELETE FROM files WHERE account_id = ${accountKey}`);
177
- // Deleting a document clears its pieces, words, revisions, tags and own links (trigger document_bd).
178
- const documentsOf = sql `(SELECT id FROM documents WHERE account_id = ${accountKey})`;
179
- orm.run(sql `DELETE FROM links WHERE to_type = 'document' AND to_id IN ${documentsOf}`);
180
- orm.run(sql `UPDATE files SET document_id = NULL WHERE document_id IN ${documentsOf}`);
181
- orm.run(sql `DELETE FROM documents WHERE account_id = ${accountKey}`);
182
- purgeCrmCopies(database, accountKey);
183
- orm.run(sql `DELETE FROM crm_fields WHERE account_id = ${accountKey}`);
184
- // An entity made from a record is the owner's and stays; only what the source said goes.
185
- const recordsOf = sql `(SELECT id FROM records WHERE account_id = ${accountKey})`;
186
- orm.run(sql `DELETE FROM record_relations WHERE record_id IN ${recordsOf} OR target_id IN ${recordsOf}`);
187
- orm.run(sql `DELETE FROM records WHERE account_id = ${accountKey}`);
188
- orm.delete(accounts).where(eq(accounts.id, accountKey)).run();
189
- dropOrphanPeople(database, unseenBefore);
190
- forgetDanglingEvidence(database, at);
191
- dropUnusedVectors(database, hashes);
192
- // The links' delete trigger writes a revision naming the account it is purging; the history goes with the links.
193
- orm.run(sql `DELETE FROM link_revisions WHERE account_id = ${accountKey}`);
194
- };
195
- /**
196
- * A CRM's deals, leads and pipelines with their stages, children first. Another account's lead converted from one
197
- * of these deals, and an order or contract that names one, keep their row and lose only the link.
198
- */
199
- const purgeCrmCopies = (database, accountKey) => {
200
- const run = (statement, ...params) => database.prepare(statement).run(...params);
201
- const dealsOf = "(SELECT id FROM deals WHERE account_id = ?)";
202
- const leadsOf = "(SELECT id FROM leads WHERE account_id = ?)";
203
- const pipelinesOf = "(SELECT id FROM pipelines WHERE account_id = ?)";
204
- const stagesOf = `(SELECT id FROM pipeline_stages WHERE pipeline_id IN ${pipelinesOf})`;
205
- for (const [type, ids] of [
206
- ["deal", dealsOf],
207
- ["lead", leadsOf],
208
- ]) {
209
- run(`DELETE FROM links WHERE (from_type = ? AND from_id IN ${ids}) OR (to_type = ? AND to_id IN ${ids})`, type, accountKey, type, accountKey);
210
- for (const [table, pointer] of [
211
- ["taggings", "taggable"],
212
- ["aliases", "aliasable"],
213
- ["attachments", "attachable"],
214
- ["link_reviews", "linkable"],
215
- ["entity_link_events", "linkable"],
216
- ])
217
- run(`DELETE FROM ${table} WHERE ${pointer}_type = ? AND ${pointer}_id IN ${ids}`, type, accountKey);
218
- run(`DELETE FROM pipeline_stage_changes WHERE item_type = ? AND item_id IN ${ids}`, type, accountKey);
219
- }
220
- run(`DELETE FROM pipeline_stage_changes WHERE pipeline_id IN ${pipelinesOf}`, accountKey);
221
- for (const table of ["leads", "orders", "contracts"])
222
- run(`UPDATE ${table} SET deal_id = NULL WHERE deal_id IN ${dealsOf}`, accountKey);
223
- run("DELETE FROM leads WHERE account_id = ?", accountKey);
224
- run("DELETE FROM deals WHERE account_id = ?", accountKey);
225
- run(`UPDATE pipeline_stages SET base_stage_id = NULL WHERE base_stage_id IN ${stagesOf}`, accountKey);
226
- run(`DELETE FROM pipeline_stages WHERE pipeline_id IN ${pipelinesOf}`, accountKey);
227
- run("DELETE FROM pipelines WHERE account_id = ?", accountKey);
228
- };
229
97
  /** Identity and person rows a person's own record keeps, not evidence that anyone saw them. */
230
98
  export const OWN = new Set(["identity_links", "identity_link_events", "identity_revisions"]);
231
99
  /**
@@ -1,6 +1,7 @@
1
1
  import { type CalendarInput, type EntryInput, type EventStore, type StoredCalendar, type StoredEntry } from "../../meetings/index.js";
2
2
  import type { StoreContext } from "./open.js";
3
3
  type Row = Record<string, unknown>;
4
+ export declare const calendarCursorKey: (calendarId: number) => string;
4
5
  /** The entry writes behind the calendar store, run inside the caller's transaction: the records import shares them. */
5
6
  export declare const calendarWritesOver: (context: StoreContext) => {
6
7
  entryRow: (id: number) => Row;
@@ -103,7 +103,7 @@ const REVIEWS = "SELECT r.*, CASE WHEN r.linkable_type = 'calendar_entry' THEN "
103
103
  "(SELECT calendar_id FROM calendar_entries WHERE id = r.linkable_id) END AS calendar_id FROM link_reviews r";
104
104
  const TRACKED = ["title", "starts_at", "ends_at", "location", "status", "recurrence", "recurrence_ends_at"];
105
105
  const flag = (value) => (value ? 1 : 0);
106
- const cursorKey = (calendarId) => `calendar:${calendarId}`;
106
+ export const calendarCursorKey = (calendarId) => `calendar:${calendarId}`;
107
107
  const addressOf = (email) => email.trim().toLowerCase();
108
108
  /** The `email` contact of an address: the same one mail uses, made when missing; it gets a name only when new. */
109
109
  const contactOf = (context, email, name) => {
@@ -495,12 +495,12 @@ export const calendarWritesOver = (context) => {
495
495
  if (value === null)
496
496
  database
497
497
  .prepare("DELETE FROM sync_cursors WHERE account_id = ? AND key = ?")
498
- .run(accountId, cursorKey(calendarId));
498
+ .run(accountId, calendarCursorKey(calendarId));
499
499
  else
500
500
  database
501
501
  .prepare(`INSERT INTO sync_cursors (account_id, key, value, created_at, updated_at) VALUES (?, ?, ?, ?, ?)
502
502
  ON CONFLICT (account_id, key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`)
503
- .run(accountId, cursorKey(calendarId), value, now, now);
503
+ .run(accountId, calendarCursorKey(calendarId), value, now, now);
504
504
  };
505
505
  const slotRows = (calendarId, series, window) => database
506
506
  .prepare(`SELECT * FROM calendar_entries WHERE calendar_id = ? AND kind = 'occurrence' AND series_external_id = ?
@@ -547,7 +547,7 @@ export const eventStoreOver = (context) => {
547
547
  }),
548
548
  forgetCalendar: async (calendarId, now) => write(database, () => {
549
549
  const accountId = Number(calendarRow(calendarId).account_id);
550
- return forgetCalendarRows(database, { calendarId, accountId, cursorKey: cursorKey(calendarId), now }, {
550
+ return forgetCalendarRows(database, { calendarId, accountId, cursorKey: calendarCursorKey(calendarId), now }, {
551
551
  event: refreshEvent,
552
552
  series: refreshSeries,
553
553
  });
@@ -614,7 +614,7 @@ export const eventStoreOver = (context) => {
614
614
  const { account_id } = calendarRow(calendarId);
615
615
  return str(database
616
616
  .prepare("SELECT value FROM sync_cursors WHERE account_id = ? AND key = ?")
617
- .get(Number(account_id), cursorKey(calendarId))?.value);
617
+ .get(Number(account_id), calendarCursorKey(calendarId))?.value);
618
618
  }),
619
619
  setCursor: async (calendarId, value, now) => write(database, () => putCursor(calendarId, value, now)),
620
620
  events: async (filter = {}) => listEvents(database, filter),
@@ -1,5 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
- import { defineQuery, validateQuery, walkQuery } from "@wirecat/cli-base/query";
2
+ import { defineQuery, timezoneOf, validateQuery, walkQuery, } from "@wirecat/cli-base/query";
3
3
  import { normalizeTag } from "../../domain/tags.js";
4
4
  import { fold } from "../normalize.js";
5
5
  import { syncFile } from "./files.js";
@@ -78,17 +78,6 @@ export const catalogStoreOver = ({ database, now }) => {
78
78
  throw new CliError("not_found", "catalog account is not in the local store");
79
79
  return Number(id);
80
80
  };
81
- const bound = (id, includeInactive = false) => {
82
- const scope = "account_id = ? AND json_type(metadata, '$.catalog') = 'object'" +
83
- (includeInactive ? "" : " AND json_extract(metadata, '$.catalog.active') = 1 AND deleted_at IS NULL");
84
- const budget = database
85
- .prepare(`SELECT count(*) AS entries, sum(length(metadata)) AS bytes FROM documents WHERE ${scope}`)
86
- .get(id);
87
- if (Number(budget?.bytes ?? 0) > 32 * 1024 * 1024)
88
- throw new CliError("validation_error", "catalog scope exceeds its metadata budget");
89
- if (Number(budget?.entries ?? 0) > 10000)
90
- throw new CliError("validation_error", "catalog scope exceeds 10000 entries");
91
- };
92
81
  return {
93
82
  upsert: async (accountId, inputs) => {
94
83
  const id = account(accountId);
@@ -177,8 +166,6 @@ export const catalogStoreOver = ({ database, now }) => {
177
166
  },
178
167
  reconcile: async (accountId, externalIds) => {
179
168
  const id = account(accountId);
180
- if (externalIds.length > 10000)
181
- throw new CliError("validation_error", "catalog scope exceeds 10000 entries");
182
169
  const current = [...new Set(externalIds.map((key) => field(key)))];
183
170
  return write(database, () => {
184
171
  const retired = database
@@ -265,11 +252,10 @@ export const catalogStoreOver = ({ database, now }) => {
265
252
  person: { where: person },
266
253
  tag: { where: (node) => ({ sql: `EXISTS(${tagSql})`, params: [tag(node.value)] }) },
267
254
  };
268
- const compiled = queryFilter(ast, columns);
255
+ const compiled = queryFilter(ast, columns, { zone: timezoneOf() });
269
256
  if (compiled.sql)
270
257
  add(compiled.sql, ...compiled.params);
271
258
  }
272
- bound(id, query.includeInactive);
273
259
  const found = database
274
260
  .prepare(`SELECT d.id, d.external_id, d.title, d.front_matter, d.metadata, d.deleted_at, d.body IS NOT NULL AS has_body FROM documents d WHERE ${clauses.join(" AND ")} ORDER BY d.external_id LIMIT ? OFFSET ?`)
275
261
  .all(...params, limit + 1, offset);
@@ -7,6 +7,7 @@ import { identityPk } from "./identities.js";
7
7
  import { bound } from "./query-filter.js";
8
8
  import { chatEventPeople, chatEvents, chatMembers, chats, chunks, fetchLeases, identities, involvements, memberCounts, memberObservationMembers, memberObservations, memberStays, messageReactions, messageRevisions, messages, messageTranscripts, pollVotes, syncRanges, } from "./schema.js";
9
9
  import { ensureTag } from "./tags.js";
10
+ import { trigramPart } from "./trigram-match.js";
10
11
  import { parsed, present, toIso, toMs } from "./values.js";
11
12
  import { dropUnusedVectors } from "./vector-index.js";
12
13
  /** The chat's own id, when the store key is a chat of this account. */
@@ -379,7 +380,7 @@ export const CHAT_COLUMNS = {
379
380
  ? { sql: "chats.title IS NOT NULL AND chats.title <> ''", params: [] }
380
381
  : {
381
382
  sql: "chats.id IN (SELECT rowid FROM chats_fts WHERE chats_fts MATCH ?)",
382
- params: [`"${titlePart(node.value).replaceAll('"', '""')}"`],
383
+ params: [trigramPart(titlePart(node.value))],
383
384
  },
384
385
  },
385
386
  kind: { type: "enum", sql: "chats.kind" },
@@ -1,3 +1,3 @@
1
- export declare const contextDocumentTime: string;
2
- export declare const contextDocumentTimeKind: string;
3
- export declare const contextDocumentUrl: string;
1
+ export declare const contextDocumentTime: () => string;
2
+ export declare const contextDocumentTimeKind: () => string;
3
+ export declare const contextDocumentUrl: () => string;
@@ -1,13 +1,15 @@
1
+ import { documentAccountProvidersSql } from "../../domain/providers.js";
1
2
  import { PREFERRED_FILE } from "./files.js";
3
+ // Rendered per query: a documents provider joins the registry when its CLI opens the store, after this module loads.
2
4
  // A document's preferred file holds its link and edit time; rows without one keep them in front matter.
3
- const drive = "CASE WHEN json_valid(n.front_matter) THEN json_extract(n.front_matter,'$.source')='google-drive' ELSE 0 END";
4
- const field = (name) => `CASE WHEN (${drive}) THEN
5
+ const remote = () => `CASE WHEN json_valid(n.front_matter) THEN json_extract(n.front_matter,'$.source') IN (${documentAccountProvidersSql()}) ELSE 0 END`;
6
+ const field = (name) => `CASE WHEN (${remote()}) THEN
5
7
  CASE WHEN json_type(n.front_matter,'$.${name}')='text' THEN json_extract(n.front_matter,'$.${name}') END END`;
6
8
  const preferred = (column) => `(SELECT f.${column} FROM files f JOIN documents d ON d.id = f.document_id WHERE f.document_id = n.id
7
9
  ORDER BY ${PREFERRED_FILE} LIMIT 1)`;
8
- const modified = `round(unixepoch(${field("modifiedAt")},'subsec')*1000)`;
9
- const remoteTime = `coalesce(${preferred("external_updated_at")},n.external_updated_at,${modified})`;
10
- export const contextDocumentTime = `coalesce(${remoteTime},n.updated_at)`;
11
- export const contextDocumentTimeKind = `CASE WHEN (${remoteTime}) IS NOT NULL
10
+ const modified = () => `round(unixepoch(${field("modifiedAt")},'subsec')*1000)`;
11
+ const remoteTime = () => `coalesce(${preferred("external_updated_at")},n.external_updated_at,${modified()})`;
12
+ export const contextDocumentTime = () => `coalesce(${remoteTime()},n.updated_at)`;
13
+ export const contextDocumentTimeKind = () => `CASE WHEN (${remoteTime()}) IS NOT NULL
12
14
  THEN 'source-modified' ELSE 'stored-update' END`;
13
- export const contextDocumentUrl = `coalesce(${preferred("url")},n.url,${field("sourceUrl")})`;
15
+ export const contextDocumentUrl = () => `coalesce(${preferred("url")},n.url,${field("sourceUrl")})`;
@@ -45,11 +45,17 @@ const corpora = {
45
45
  index: "document_words",
46
46
  title: "n.title",
47
47
  body: "n.body",
48
- url: contextDocumentUrl,
49
- at: contextDocumentTime,
48
+ get url() {
49
+ return contextDocumentUrl();
50
+ },
51
+ get at() {
52
+ return contextDocumentTime();
53
+ },
50
54
  revision: "n.revision",
51
55
  chat: "NULL",
52
- timeKind: contextDocumentTimeKind,
56
+ get timeKind() {
57
+ return contextDocumentTimeKind();
58
+ },
53
59
  join: "",
54
60
  where: "n.body IS NOT NULL AND CASE WHEN json_valid(n.metadata) THEN coalesce(json_extract(n.metadata, '$.catalog.active'),1) ELSE 1 END=1",
55
61
  chats: null,
@@ -1,4 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
+ import { timezoneOf } from "@wirecat/cli-base/query";
2
3
  import { normalizeTag } from "../../domain/tags.js";
3
4
  import { PREFERRED_FILE, subtreeOf } from "./files.js";
4
5
  import { accountOf } from "./meeting-listing.js";
@@ -183,7 +184,7 @@ const treeOf = (paths, depth) => {
183
184
  };
184
185
  export const documentListingOver = (context) => {
185
186
  const { database } = context;
186
- const whereOf = (query, zone, now) => query && queryFilter(query, columns(context), { ...(zone ? { zone } : {}), ...(now ? { now } : {}) });
187
+ const whereOf = (query, zone, now) => query && queryFilter(query, columns(context), { zone: timezoneOf(zone), ...(now ? { now } : {}) });
187
188
  return {
188
189
  documentAccounts: async () => database
189
190
  .prepare(`SELECT id, provider, external_id, name FROM accounts WHERE id IN (SELECT d.account_id FROM documents d ` +
@@ -1,3 +1,4 @@
1
+ import { timezoneOf } from "@wirecat/cli-base/query";
1
2
  import { joinKeyOf, } from "../../meetings/index.js";
2
3
  import { queryFilter } from "./query-filter.js";
3
4
  import { write } from "./transaction.js";
@@ -51,7 +52,7 @@ export const events = (database, query) => {
51
52
  ends_at: { type: "time", sql: "ends_at" },
52
53
  created_at: { type: "time", sql: "created_at" },
53
54
  updated_at: { type: "time", sql: "updated_at" },
54
- });
55
+ }, { zone: timezoneOf() });
55
56
  return database
56
57
  .prepare(`SELECT * FROM events WHERE deleted_at IS NULL${where ? ` AND (${where.sql})` : ""} ORDER BY id`)
57
58
  .all(...(where?.params ?? []))
@@ -0,0 +1,6 @@
1
+ import type { CacheDatabase } from "../driver.js";
2
+ /**
3
+ * The document row of the live file at `path` in an account, shaped as `notes({ folderId })` lists it. A local folder
4
+ * names its files by their own path; any other account by its document's key.
5
+ */
6
+ export declare const fileNoteRow: (database: CacheDatabase, account: number, local: boolean, path: string) => Record<string, unknown> | undefined;
@@ -0,0 +1,15 @@
1
+ const LIVE = "f.deleted_at IS NULL AND d.deleted_at IS NULL AND coalesce(json_extract(d.metadata, '$.catalog.active'), 1)=1";
2
+ /**
3
+ * The document row of the live file at `path` in an account, shaped as `notes({ folderId })` lists it. A local folder
4
+ * names its files by their own path; any other account by its document's key.
5
+ */
6
+ export const fileNoteRow = (database, account, local, path) => database
7
+ .prepare(local
8
+ ? "SELECT d.*, f.account_id AS account_id, f.external_id AS external_id, " +
9
+ "coalesce(f.external_updated_at, d.external_updated_at) AS external_updated_at FROM files f " +
10
+ `JOIN documents d ON d.id = f.document_id WHERE f.account_id = ? AND f.external_id = ? AND ${LIVE} ` +
11
+ "ORDER BY d.created_at, d.id LIMIT 1"
12
+ : "SELECT d.*, f.account_id AS account_id, coalesce(f.external_updated_at, d.external_updated_at) AS " +
13
+ "external_updated_at FROM documents d JOIN files f ON f.document_id = d.id AND f.account_id = d.account_id " +
14
+ `WHERE d.account_id = ? AND d.external_id = ? AND ${LIVE} LIMIT 1`)
15
+ .get(account, path);
@@ -20,8 +20,9 @@ export declare const driveFileTarget: (fileId: string) => string;
20
20
  /** The document of the Drive file with this id; `null` when no Drive account holds it, or two do. */
21
21
  export declare const driveDocumentOf: (database: CacheDatabase, fileId: string) => number | null;
22
22
  /**
23
- * Writes the `files` row of one document from the document as it is now: the document's source record. A Drive
24
- * document (catalog metadata or Drive front matter) is keyed by its Drive file id and placed under its first parent;
23
+ * Writes the `files` row of one document from the document as it is now: the document's source record. A documents
24
+ * provider's document (catalog metadata, or front matter whose `source` names the provider) is keyed by its file id
25
+ * (`fileId` in the front matter, else its own key) and placed under its first parent;
25
26
  * a local one by its path, under folder rows made from that path. `seen` marks a sync or import that returned it.
26
27
  * `place` names a local file of the document other than the one its own columns name: a copy in another folder.
27
28
  */
@@ -1,4 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
+ import { isDocumentAccountProvider } from "../../domain/providers.js";
2
3
  import { fold } from "../normalize.js";
3
4
  import { write, writeBatch } from "./transaction.js";
4
5
  const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
@@ -79,8 +80,9 @@ const movePaths = (database, accountId, from, to) => {
79
80
  .run(to, from.length + 1, accountId, from.length + 1, `${from}/`);
80
81
  };
81
82
  /**
82
- * Writes the `files` row of one document from the document as it is now: the document's source record. A Drive
83
- * document (catalog metadata or Drive front matter) is keyed by its Drive file id and placed under its first parent;
83
+ * Writes the `files` row of one document from the document as it is now: the document's source record. A documents
84
+ * provider's document (catalog metadata, or front matter whose `source` names the provider) is keyed by its file id
85
+ * (`fileId` in the front matter, else its own key) and placed under its first parent;
84
86
  * a local one by its path, under folder rows made from that path. `seen` marks a sync or import that returned it.
85
87
  * `place` names a local file of the document other than the one its own columns name: a copy in another folder.
86
88
  */
@@ -93,7 +95,7 @@ export const syncFile = (database, now, documentId, { seen = true, depth = 0, pl
93
95
  const catalog = place ? undefined : objectOf(objectOf(doc.metadata)?.catalog);
94
96
  const provider = database.prepare("SELECT provider FROM accounts WHERE id = ?").get(accountId)?.provider;
95
97
  // A vault file may carry an exported Drive file's front matter and still be a file on disk.
96
- const remote = catalog !== undefined || (front?.source === "google-drive" && !LOCAL.has(String(provider)));
98
+ const remote = catalog !== undefined || (isDocumentAccountProvider(front?.source) && !LOCAL.has(String(provider)));
97
99
  const externalId = (remote && stringOf(front?.fileId)) || (place?.path ?? String(doc.external_id));
98
100
  const kind = doc.kind === "folder" ? "folder" : doc.kind === "page" ? "page" : "file";
99
101
  let name;
@@ -7,6 +7,7 @@ import { holdingText } from "./note-index.js";
7
7
  import { resolvePersonLinks } from "./person-resolution.js";
8
8
  import { bound } from "./query-filter.js";
9
9
  import { accountIdentities, accounts, aliases, chatMembers, chats, identities, identityLinkEvents, identityLinks, identityRevisions, messages, persons, } from "./schema.js";
10
+ import { trigramPart } from "./trigram-match.js";
10
11
  import { toIso } from "./values.js";
11
12
  /** The source's every phone and address as a JSON patch of `metadata`; `undefined` when it gave no list. */
12
13
  const contactsOf = ({ phones, emails }) => {
@@ -244,7 +245,7 @@ const contactsWhere = (accountKey, key, { query, notes, email, phone }) => {
244
245
  WHERE ${chatMembers.identityId} = ${identities.id} AND ${chats.accountId} = ${accountIdentities.accountId}
245
246
  AND ${chats.kind} = 'dialog')`, query === undefined
246
247
  ? undefined
247
- : sql `(${identities.id} IN (SELECT rowid FROM identities_fts WHERE identities_fts MATCH ${`"${query.trim().replaceAll('"', '""')}"`}) OR EXISTS (SELECT 1 FROM aliases ca WHERE ca.aliasable_type='identity' AND ca.display=1 AND ca.account_id=${accountKey} AND ca.aliasable_id=${identities.id} AND instr(ca.name_folded, ${fold(query.trim())}) > 0))`, notes === undefined
248
+ : sql `(${identities.id} IN (SELECT rowid FROM identities_fts WHERE identities_fts MATCH ${trigramPart(query.trim())}) OR EXISTS (SELECT 1 FROM aliases ca WHERE ca.aliasable_type='identity' AND ca.display=1 AND ca.account_id=${accountKey} AND ca.aliasable_id=${identities.id} AND instr(ca.name_folded, ${fold(query.trim())}) > 0))`, notes === undefined
248
249
  ? undefined
249
250
  : sql `EXISTS (SELECT 1 FROM notes n WHERE n.notable_type='identity' AND n.notable_id=${identities.id} AND n.deleted_at IS NULL${noted ? sql ` AND ${bound(noted)}` : sql ``})`, email === undefined
250
251
  ? undefined