@wirecat/cli-core 0.662.0 → 0.664.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 (247) hide show
  1. package/CHANGELOG.md +213 -0
  2. package/dist/calendar/cli/bodies.js +2 -1
  3. package/dist/calendar/cli/index.js +13 -10
  4. package/dist/calendar/mcp/index.d.ts +3 -1
  5. package/dist/calendar/mcp/index.js +4 -4
  6. package/dist/cli/call-stats-command.d.ts +18 -0
  7. package/dist/cli/call-stats-command.js +52 -0
  8. package/dist/cli/chat-sending-command.d.ts +14 -0
  9. package/dist/cli/chat-sending-command.js +64 -0
  10. package/dist/cli/context.d.ts +7 -0
  11. package/dist/cli/context.js +12 -4
  12. package/dist/cli/contract-templates.js +2 -0
  13. package/dist/cli/envelope.d.ts +0 -5
  14. package/dist/cli/envelope.js +25 -0
  15. package/dist/cli/index.d.ts +4 -1
  16. package/dist/cli/index.js +4 -1
  17. package/dist/cli/meeting-batch.d.ts +2 -1
  18. package/dist/cli/meeting-batch.js +7 -5
  19. package/dist/cli/meeting-meaning-command.d.ts +47 -0
  20. package/dist/cli/meeting-meaning-command.js +136 -0
  21. package/dist/cli/meeting-preparation-answer.d.ts +6 -0
  22. package/dist/cli/meeting-preparation-command.js +5 -5
  23. package/dist/cli/meeting-preparation-projects.d.ts +6 -0
  24. package/dist/cli/meeting-preparation-read.d.ts +11 -5
  25. package/dist/cli/meeting-preparation-read.js +13 -21
  26. package/dist/cli/meeting-series-inventory-command.js +2 -2
  27. package/dist/cli/meeting-series-inventory-read.d.ts +2 -2
  28. package/dist/cli/meeting-series-inventory-read.js +7 -15
  29. package/dist/cli/meeting-tags-command.d.ts +18 -0
  30. package/dist/cli/meeting-tags-command.js +74 -0
  31. package/dist/cli/messenger/admin-statistics-command.js +2 -2
  32. package/dist/cli/messenger/conversation-answers.d.ts +1 -1
  33. package/dist/cli/messenger/conversation-answers.js +1 -0
  34. package/dist/cli/messenger/conversations-command.js +38 -12
  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/models-command.js +7 -0
  41. package/dist/cli/messenger/rankings-command.js +3 -3
  42. package/dist/cli/messenger/records-command.d.ts +4 -1
  43. package/dist/cli/messenger/records-command.js +6 -1
  44. package/dist/cli/messenger/tags-command.js +7 -2
  45. package/dist/cli/messenger/tasks-command.js +2 -2
  46. package/dist/cli/model-catalogue-command.js +2 -0
  47. package/dist/cli/paging.d.ts +10 -0
  48. package/dist/cli/paging.js +29 -0
  49. package/dist/cli/profile-token.d.ts +15 -1
  50. package/dist/cli/profile-token.js +103 -7
  51. package/dist/cli/program.js +2 -2
  52. package/dist/cli/runs/command.js +6 -4
  53. package/dist/cli/runs/search-command.js +9 -5
  54. package/dist/cli/schedule/schedule-command.js +1 -5
  55. package/dist/domain/links.d.ts +11 -0
  56. package/dist/domain/links.js +4 -0
  57. package/dist/domain/moment.d.ts +29 -0
  58. package/dist/domain/moment.js +58 -0
  59. package/dist/domain/providers.d.ts +6 -4
  60. package/dist/domain/providers.js +10 -5
  61. package/dist/domain/send-time.d.ts +3 -4
  62. package/dist/domain/send-time.js +10 -24
  63. package/dist/entities/chat-sending.d.ts +10 -0
  64. package/dist/entities/chat-sending.js +11 -0
  65. package/dist/entities/fields.d.ts +2 -2
  66. package/dist/entities/fields.js +2 -2
  67. package/dist/entities/index.d.ts +135 -2
  68. package/dist/entities/index.js +8 -3
  69. package/dist/entities/meeting-preparation.d.ts +6 -0
  70. package/dist/entities/meeting.d.ts +1 -1
  71. package/dist/entities/meeting.js +1 -1
  72. package/dist/errors/reasons.js +25 -2
  73. package/dist/mail/cli/index.js +4 -2
  74. package/dist/mail/facts.d.ts +5 -2
  75. package/dist/mail/facts.js +6 -3
  76. package/dist/mail/index.d.ts +1 -1
  77. package/dist/mail/meeting-notes.js +1 -1
  78. package/dist/mail/probe.d.ts +5 -2
  79. package/dist/mail/probe.js +9 -5
  80. package/dist/mail/server-search.js +1 -1
  81. package/dist/mail/sync.js +1 -1
  82. package/dist/mcp/meeting-preparation.d.ts +6 -0
  83. package/dist/mcp/meeting-preparation.js +1 -1
  84. package/dist/mcp/meeting-series-inventory.js +1 -1
  85. package/dist/mcp/prompts.js +6 -9
  86. package/dist/meetings/answers.d.ts +7 -0
  87. package/dist/meetings/answers.js +4 -0
  88. package/dist/meetings/call-answers.d.ts +106 -0
  89. package/dist/meetings/call-answers.js +171 -0
  90. package/dist/meetings/call-stats.d.ts +121 -0
  91. package/dist/meetings/call-stats.js +211 -0
  92. package/dist/meetings/calls.d.ts +76 -0
  93. package/dist/meetings/calls.js +78 -0
  94. package/dist/meetings/cli/index.d.ts +8 -0
  95. package/dist/meetings/cli/index.js +10 -22
  96. package/dist/meetings/cli/search.d.ts +9 -2
  97. package/dist/meetings/cli/search.js +16 -26
  98. package/dist/meetings/index.d.ts +4 -0
  99. package/dist/meetings/index.js +4 -0
  100. package/dist/meetings/mcp/index.d.ts +6 -3
  101. package/dist/meetings/mcp/index.js +2 -4
  102. package/dist/meetings/mcp/search.d.ts +12 -1
  103. package/dist/meetings/mcp/search.js +3 -3
  104. package/dist/meetings/project-evidence-answer.d.ts +6 -0
  105. package/dist/meetings/read-through.d.ts +2 -1
  106. package/dist/meetings/read-through.js +10 -1
  107. package/dist/meetings/stats.d.ts +3 -0
  108. package/dist/meetings/stats.js +3 -3
  109. package/dist/meetings/tag-answers.d.ts +43 -0
  110. package/dist/meetings/tag-answers.js +41 -0
  111. package/dist/meetings/testing/index.d.ts +1 -0
  112. package/dist/meetings/testing/index.js +1 -0
  113. package/dist/meetings/testing/paging.d.ts +6 -0
  114. package/dist/meetings/testing/paging.js +5 -0
  115. package/dist/models/chat-sending.d.ts +24 -0
  116. package/dist/models/chat-sending.js +40 -0
  117. package/dist/moderation/rules.d.ts +2 -0
  118. package/dist/moderation/rules.js +16 -2
  119. package/dist/runs/events.d.ts +1 -1
  120. package/dist/search/fusion.d.ts +17 -0
  121. package/dist/search/fusion.js +17 -0
  122. package/dist/search/lucene/resolved.d.ts +2 -0
  123. package/dist/search/question-plan.d.ts +4 -0
  124. package/dist/search/question-plan.js +7 -0
  125. package/dist/search/service-query.d.ts +6 -1
  126. package/dist/search/service-query.js +9 -1
  127. package/dist/search/task-similarity.d.ts +1 -0
  128. package/dist/search/task-similarity.js +1 -1
  129. package/dist/services/agenda-mail.js +2 -1
  130. package/dist/services/agenda.js +5 -3
  131. package/dist/services/attachments.js +4 -2
  132. package/dist/services/call-stats.d.ts +17 -0
  133. package/dist/services/call-stats.js +41 -0
  134. package/dist/services/chats.js +4 -2
  135. package/dist/services/conversations.js +4 -2
  136. package/dist/services/deps.d.ts +1 -1
  137. package/dist/services/document-source.d.ts +1 -1
  138. package/dist/services/document-source.js +4 -3
  139. package/dist/services/documents/ingestion.js +11 -40
  140. package/dist/services/documents/plan.d.ts +1 -1
  141. package/dist/services/documents/plan.js +30 -17
  142. package/dist/services/documents/ports.d.ts +5 -0
  143. package/dist/services/documents/sync.js +1 -1
  144. package/dist/services/embeddings-search.js +39 -9
  145. package/dist/services/embeddings.d.ts +4 -0
  146. package/dist/services/events-search.js +2 -1
  147. package/dist/services/index.d.ts +3 -0
  148. package/dist/services/index.js +3 -0
  149. package/dist/services/mail-search.d.ts +1 -1
  150. package/dist/services/mail-search.js +10 -11
  151. package/dist/services/media-archive-move.js +2 -4
  152. package/dist/services/media-archive.d.ts +0 -1
  153. package/dist/services/media-archive.js +2 -12
  154. package/dist/services/meeting-combined.js +1 -1
  155. package/dist/services/meeting-meaning.d.ts +47 -0
  156. package/dist/services/meeting-meaning.js +158 -0
  157. package/dist/services/meeting-tags.d.ts +27 -0
  158. package/dist/services/meeting-tags.js +81 -0
  159. package/dist/services/messages-combined.js +15 -4
  160. package/dist/services/messages-discovery.js +2 -2
  161. package/dist/services/moderation.js +10 -2
  162. package/dist/services/moment.d.ts +4 -10
  163. package/dist/services/moment.js +16 -44
  164. package/dist/services/notes-search.d.ts +0 -2
  165. package/dist/services/notes-search.js +1 -2
  166. package/dist/services/search-all.js +2 -1
  167. package/dist/services/tags.js +4 -2
  168. package/dist/services/task-stats.js +2 -2
  169. package/dist/services/tasks.js +2 -2
  170. package/dist/sftp/index.d.ts +1 -1
  171. package/dist/sftp/index.js +1 -1
  172. package/dist/sftp/session.d.ts +30 -4
  173. package/dist/sftp/session.js +195 -11
  174. package/dist/sftp/ssh2.d.ts +19 -4
  175. package/dist/sftp/ssh2.js +144 -17
  176. package/dist/speech/cloud.d.ts +47 -0
  177. package/dist/speech/cloud.js +73 -0
  178. package/dist/speech/decode.d.ts +36 -9
  179. package/dist/speech/decode.js +208 -61
  180. package/dist/speech/index.d.ts +2 -1
  181. package/dist/speech/index.js +2 -1
  182. package/dist/speech/openai.d.ts +4 -0
  183. package/dist/speech/openai.js +13 -12
  184. package/dist/sql/index.d.ts +1 -0
  185. package/dist/sql/index.js +1 -0
  186. package/dist/sql/reader.d.ts +95 -0
  187. package/dist/sql/reader.js +214 -0
  188. package/dist/store/accounts.js +2 -1
  189. package/dist/store/sqlite/account-purge.d.ts +3 -0
  190. package/dist/store/sqlite/account-purge.js +143 -0
  191. package/dist/store/sqlite/accounts.d.ts +0 -2
  192. package/dist/store/sqlite/accounts.js +2 -134
  193. package/dist/store/sqlite/calendar.d.ts +1 -0
  194. package/dist/store/sqlite/calendar.js +5 -5
  195. package/dist/store/sqlite/catalog.js +2 -16
  196. package/dist/store/sqlite/chats.js +2 -1
  197. package/dist/store/sqlite/context-document-source.d.ts +3 -3
  198. package/dist/store/sqlite/context-document-source.js +9 -7
  199. package/dist/store/sqlite/context-evidence.js +9 -3
  200. package/dist/store/sqlite/document-listing.js +2 -1
  201. package/dist/store/sqlite/drizzle/bun.js +4 -4
  202. package/dist/store/sqlite/drizzle/bun.js.map +1 -1
  203. package/dist/store/sqlite/drizzle/core.js +5 -5
  204. package/dist/store/sqlite/drizzle/core.js.map +1 -1
  205. package/dist/store/sqlite/drizzle/node.js +4 -4
  206. package/dist/store/sqlite/drizzle/node.js.map +1 -1
  207. package/dist/store/sqlite/drizzle/{shared-55XJMTPA.js → shared-5XR7K42U.js} +58 -58
  208. package/dist/store/sqlite/drizzle/{shared-55XJMTPA.js.map → shared-5XR7K42U.js.map} +1 -1
  209. package/dist/store/sqlite/events.js +2 -1
  210. package/dist/store/sqlite/file-note.d.ts +6 -0
  211. package/dist/store/sqlite/file-note.js +15 -0
  212. package/dist/store/sqlite/files.d.ts +3 -2
  213. package/dist/store/sqlite/files.js +5 -3
  214. package/dist/store/sqlite/identities.js +2 -1
  215. package/dist/store/sqlite/imported-documents.js +2 -2
  216. package/dist/store/sqlite/knowledge.d.ts +1 -1
  217. package/dist/store/sqlite/knowledge.js +27 -23
  218. package/dist/store/sqlite/labelled.d.ts +5 -0
  219. package/dist/store/sqlite/labelled.js +6 -0
  220. package/dist/store/sqlite/link-row.d.ts +1 -0
  221. package/dist/store/sqlite/link-row.js +2 -0
  222. package/dist/store/sqlite/lucene-fields.js +8 -12
  223. package/dist/store/sqlite/mail-rules.js +2 -1
  224. package/dist/store/sqlite/meeting-calls.d.ts +4 -0
  225. package/dist/store/sqlite/meeting-calls.js +66 -0
  226. package/dist/store/sqlite/meetings.d.ts +2 -2
  227. package/dist/store/sqlite/meetings.js +4 -1
  228. package/dist/store/sqlite/mention-sources.js +2 -1
  229. package/dist/store/sqlite/mentions.js +2 -2
  230. package/dist/store/sqlite/messages.js +6 -1
  231. package/dist/store/sqlite/note-search.js +8 -11
  232. package/dist/store/sqlite/notes.d.ts +3 -1
  233. package/dist/store/sqlite/notes.js +25 -14
  234. package/dist/store/sqlite/organizations.js +2 -2
  235. package/dist/store/sqlite/people-list.js +3 -3
  236. package/dist/store/sqlite/query-filter.d.ts +3 -3
  237. package/dist/store/sqlite/query-filter.js +3 -3
  238. package/dist/store/sqlite/reads.d.ts +4 -4
  239. package/dist/store/sqlite/reads.js +4 -4
  240. package/dist/store/sqlite/search.js +11 -7
  241. package/dist/store/sqlite/test-accounts.js +1 -1
  242. package/dist/store/sqlite/trigram-match.d.ts +9 -0
  243. package/dist/store/sqlite/trigram-match.js +28 -0
  244. package/dist/store/sqlite/work-tasks.js +1 -1
  245. package/package.json +18 -3
  246. package/parity.json +20 -1
  247. package/skills/link-conversations/SKILL.md +1 -1
@@ -0,0 +1,214 @@
1
+ import { CliError, isCliError } from "@wirecat/cli-base";
2
+ import { providerEvent, providerRequest } from "../cli/command-runs.js";
3
+ export const SQL_CONNECT_TIMEOUT_MS = 15_000;
4
+ export const SQL_QUERY_TIMEOUT_MS = 120_000;
5
+ const PAGE = 5_000;
6
+ const MOST_PAGE = 50_000;
7
+ const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_$]{0,63}$/;
8
+ const checked = (identifier) => {
9
+ const parts = identifier.split(".");
10
+ if (parts.length > 2 || !parts.every((part) => IDENTIFIER.test(part)))
11
+ throw new CliError("validation_error", "a table or column name is letters, digits and _, as name or schema.name", {
12
+ reason: "sql.bad-identifier",
13
+ });
14
+ return parts;
15
+ };
16
+ export const quoteSql = (kind, identifier) => checked(identifier)
17
+ .map((part) => (kind === "mysql" ? `\`${part}\`` : `"${part}"`))
18
+ .join(".");
19
+ const library = (name, load) => load().catch(() => {
20
+ throw new CliError("configuration_error", `this database needs the ${name} package: add ${name} to this CLI`, {
21
+ reason: "sql.library-missing",
22
+ });
23
+ });
24
+ /**
25
+ * The driver's refusal, without its text: it can quote the host, the user or the statement (WC-SECR-6). The reasons
26
+ * are the host's to word again (`db.no-table` → "set db_table").
27
+ */
28
+ export const sqlFailure = (kind, error) => {
29
+ if (isCliError(error))
30
+ return error;
31
+ const code = String(error?.code ?? "");
32
+ const where = `the ${kind === "mysql" ? "MySQL" : "PostgreSQL"} server`;
33
+ if (["ER_ACCESS_DENIED_ERROR", "28P01", "28000"].includes(code))
34
+ return new CliError("authentication_error", `${where} refused the user or password`, { reason: "db.refused" });
35
+ if (["ER_BAD_DB_ERROR", "3D000"].includes(code))
36
+ return new CliError("not_found", `${where} has no such database`, { reason: "db.no-database" });
37
+ if (["ER_NO_SUCH_TABLE", "42P01"].includes(code))
38
+ return new CliError("not_found", `${where} has no such table`, { reason: "db.no-table" });
39
+ if (["ER_TABLEACCESS_DENIED_ERROR", "ER_COLUMNACCESS_DENIED_ERROR", "42501"].includes(code))
40
+ return new CliError("permission_error", `the user may not read that table; grant it SELECT`, {
41
+ reason: "db.no-select",
42
+ });
43
+ if (["ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION", "25006"].includes(code))
44
+ return new CliError("permission_error", `${where} refused a write: this connection only reads`, {
45
+ reason: "db.read-only",
46
+ });
47
+ if (["ETIMEDOUT", "PROTOCOL_SEQUENCE_TIMEOUT", "57014"].includes(code) || /timeout/i.test(String(error)))
48
+ return new CliError("timeout", `${where} did not answer in time`, { reason: "db.timeout", retryable: true });
49
+ if (["ECONNREFUSED", "ENOTFOUND", "EHOSTUNREACH", "ECONNRESET", "EAI_AGAIN", "EPIPE"].includes(code))
50
+ return new CliError("network_error", `${where} could not be reached`, { reason: "network.failed", retryable: true });
51
+ return new CliError("provider_error", `${where} failed the query (${/^[\w-]{1,40}$/.test(code) ? code : "no code"})`, {
52
+ reason: "db.failed",
53
+ });
54
+ };
55
+ const mysqlDriver = async (options, socket) => {
56
+ const { createConnection } = await library("mysql2", () => import("mysql2/promise"));
57
+ const queryMs = options.queryTimeoutMs ?? SQL_QUERY_TIMEOUT_MS;
58
+ const connection = await createConnection({
59
+ host: options.host,
60
+ port: options.port ?? 3306,
61
+ user: options.user,
62
+ password: options.password,
63
+ database: options.database,
64
+ connectTimeout: options.connectTimeoutMs ?? SQL_CONNECT_TIMEOUT_MS,
65
+ // DATETIME stays the wall time it is; the host's zone reads it, not this computer's.
66
+ dateStrings: true,
67
+ supportBigNumbers: true,
68
+ bigNumberStrings: true,
69
+ ...(socket ? { stream: socket } : {}),
70
+ ...(options.tls ? { ssl: { rejectUnauthorized: true } } : {}),
71
+ });
72
+ try {
73
+ await connection.query("SET SESSION TRANSACTION READ ONLY");
74
+ }
75
+ catch (error) {
76
+ await connection.end().catch(() => undefined);
77
+ throw error;
78
+ }
79
+ return {
80
+ columns: async (sql) => {
81
+ const [, fields] = await connection.query({ sql, timeout: queryMs });
82
+ return (fields ?? []).map((field) => ({ name: field.name, zoned: false }));
83
+ },
84
+ query: async (sql, params) => {
85
+ const [rows] = await connection.query({ sql, timeout: queryMs }, params);
86
+ return rows;
87
+ },
88
+ close: () => connection.end(),
89
+ };
90
+ };
91
+ const TIMESTAMP_WITHOUT_ZONE = 1114;
92
+ const TIMESTAMP_WITH_ZONE = 1184;
93
+ const postgresDriver = async (options, socket) => {
94
+ const { default: pg } = await library("pg", () => import("pg"));
95
+ const queryMs = options.queryTimeoutMs ?? SQL_QUERY_TIMEOUT_MS;
96
+ const client = new pg.Client({
97
+ host: options.host,
98
+ port: options.port ?? 5432,
99
+ user: options.user,
100
+ password: options.password,
101
+ database: options.database,
102
+ connectionTimeoutMillis: options.connectTimeoutMs ?? SQL_CONNECT_TIMEOUT_MS,
103
+ query_timeout: queryMs,
104
+ statement_timeout: queryMs,
105
+ options: "-c default_transaction_read_only=on",
106
+ ...(socket ? { stream: () => socket } : {}),
107
+ ...(options.tls ? { ssl: { rejectUnauthorized: true, servername: options.host } } : {}),
108
+ types: {
109
+ getTypeParser: ((oid, format) => oid === TIMESTAMP_WITHOUT_ZONE
110
+ ? (value) => value
111
+ : pg.types.getTypeParser(oid, format)),
112
+ },
113
+ });
114
+ await client.connect();
115
+ return {
116
+ columns: async (sql) => (await client.query(sql)).fields.map(({ name, dataTypeID }) => ({
117
+ name,
118
+ zoned: dataTypeID === TIMESTAMP_WITH_ZONE,
119
+ })),
120
+ query: async (sql, params) => (await client.query(sql, params)).rows,
121
+ close: () => client.end(),
122
+ };
123
+ };
124
+ const OPERATORS = new Set(["=", "<", "<=", ">", ">="]);
125
+ /**
126
+ * A MySQL, MariaDB or PostgreSQL database, read only: the session is opened read-only, and a paged read is one SELECT
127
+ * whose names were checked as identifiers and whose values are parameters. The host brings its own schema: which
128
+ * table, which columns, which order. Every connect and page is a request in the run's events, with no statement,
129
+ * value or name in it.
130
+ */
131
+ export const openSqlReader = async (options) => {
132
+ const { kind } = options;
133
+ const events = options.events ?? providerEvent;
134
+ const traced = async (operation, work, counts) => {
135
+ const answered = providerRequest(operation, events, { transport: "sql" });
136
+ try {
137
+ const value = await work();
138
+ answered({ ids: { host: options.host }, ...(counts ? { counts: counts(value) } : {}) });
139
+ return value;
140
+ }
141
+ catch (error) {
142
+ const failure = options.signal?.aborted
143
+ ? new CliError("cancelled", "the database read was stopped", { reason: "command.cancelled" })
144
+ : sqlFailure(kind, error);
145
+ answered({ ids: { host: options.host }, error: failure, errorCode: failure.code });
146
+ throw failure;
147
+ }
148
+ };
149
+ options.signal?.throwIfAborted();
150
+ const driver = await traced("sql.connect", async () => {
151
+ const socket = options.socket ? await options.socket() : undefined;
152
+ return (options.driver ?? (kind === "mysql" ? mysqlDriver : postgresDriver))(options, socket);
153
+ });
154
+ const stop = () => void driver.close().catch(() => undefined);
155
+ options.signal?.addEventListener("abort", stop, { once: true });
156
+ const quote = (identifier) => quoteSql(kind, identifier);
157
+ const placeholder = (index) => (kind === "mysql" ? "?" : `$${index}`);
158
+ const stopped = () => {
159
+ if (options.signal?.aborted)
160
+ throw new CliError("cancelled", "the database read was stopped", { reason: "command.cancelled" });
161
+ };
162
+ return {
163
+ kind,
164
+ quote,
165
+ placeholder,
166
+ columns: (table) => traced("sql.columns", () => driver.columns(`SELECT * FROM ${quote(table)} LIMIT 0`), (columns) => ({ columns: columns.length })),
167
+ query: (sql, params = []) => {
168
+ stopped();
169
+ return traced("sql.query", () => driver.query(sql, params), (rows) => ({ rows: rows.length }));
170
+ },
171
+ async *pages(read) {
172
+ const size = read.pageSize ?? PAGE;
173
+ if (!Number.isSafeInteger(size) || size < 1 || size > MOST_PAGE)
174
+ throw new CliError("validation_error", `a page is 1 to ${MOST_PAGE} rows`, { reason: "input.invalid" });
175
+ if (read.orderBy.length === 0)
176
+ throw new CliError("validation_error", "a paged read needs an order", { reason: "input.invalid" });
177
+ const conditions = read.where ?? [];
178
+ for (const { op } of conditions)
179
+ if (!OPERATORS.has(op))
180
+ throw new CliError("validation_error", "an unknown comparison", { reason: "input.invalid" });
181
+ const table = quote(read.table);
182
+ const order = read.orderBy.map(quote);
183
+ const filters = conditions.map(({ column, op }, index) => `${quote(column)} ${op} ${placeholder(index + 1)}`);
184
+ const values = conditions.map(({ value }) => value);
185
+ const keyset = read.unique === true;
186
+ let last;
187
+ for (let offset = 0;; offset += size) {
188
+ stopped();
189
+ const after = keyset && last !== undefined;
190
+ const where = [
191
+ ...filters,
192
+ ...(after
193
+ ? [
194
+ `(${order.join(", ")}) > (${read.orderBy.map((_, index) => placeholder(conditions.length + index + 1)).join(", ")})`,
195
+ ]
196
+ : []),
197
+ ];
198
+ const params = after ? [...values, ...read.orderBy.map((name) => last?.[name] ?? null)] : values;
199
+ const sql = `SELECT * FROM ${table}${where.length ? ` WHERE ${where.join(" AND ")}` : ""} ORDER BY ${order.join(", ")} ` +
200
+ `LIMIT ${size}${keyset ? "" : ` OFFSET ${offset}`}`;
201
+ const page = await traced("sql.rows", () => driver.query(sql, params), (rows) => ({ rows: rows.length }));
202
+ if (page.length > 0)
203
+ yield page;
204
+ last = page.at(-1);
205
+ if (page.length < size)
206
+ return;
207
+ }
208
+ },
209
+ close: async () => {
210
+ options.signal?.removeEventListener("abort", stop);
211
+ await driver.close();
212
+ },
213
+ };
214
+ };
@@ -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);