@wirecat/cli-core 0.662.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 (173) hide show
  1. package/CHANGELOG.md +88 -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/call-stats-command.d.ts +18 -0
  8. package/dist/cli/call-stats-command.js +52 -0
  9. package/dist/cli/contract-templates.js +2 -0
  10. package/dist/cli/envelope.d.ts +0 -5
  11. package/dist/cli/envelope.js +25 -0
  12. package/dist/cli/index.d.ts +2 -1
  13. package/dist/cli/index.js +2 -1
  14. package/dist/cli/meeting-batch.d.ts +2 -1
  15. package/dist/cli/meeting-batch.js +7 -5
  16. package/dist/cli/meeting-preparation-command.js +5 -5
  17. package/dist/cli/meeting-preparation-read.d.ts +5 -5
  18. package/dist/cli/meeting-preparation-read.js +13 -21
  19. package/dist/cli/meeting-series-inventory-command.js +2 -2
  20. package/dist/cli/meeting-series-inventory-read.d.ts +2 -2
  21. package/dist/cli/meeting-series-inventory-read.js +7 -15
  22. package/dist/cli/messenger/admin-statistics-command.js +2 -2
  23. package/dist/cli/messenger/counters-command.js +2 -2
  24. package/dist/cli/messenger/media-archive-command.js +5 -4
  25. package/dist/cli/messenger/media-archive-move-command.js +1 -1
  26. package/dist/cli/messenger/media-archive-timer-command.js +5 -4
  27. package/dist/cli/messenger/metadata-command.js +3 -3
  28. package/dist/cli/messenger/rankings-command.js +3 -3
  29. package/dist/cli/messenger/tags-command.js +7 -2
  30. package/dist/cli/messenger/tasks-command.js +2 -2
  31. package/dist/cli/paging.d.ts +10 -0
  32. package/dist/cli/paging.js +29 -0
  33. package/dist/cli/runs/command.js +6 -4
  34. package/dist/cli/runs/search-command.js +9 -5
  35. package/dist/cli/schedule/schedule-command.js +1 -5
  36. package/dist/domain/moment.d.ts +29 -0
  37. package/dist/domain/moment.js +58 -0
  38. package/dist/domain/providers.d.ts +6 -4
  39. package/dist/domain/providers.js +10 -5
  40. package/dist/domain/send-time.d.ts +3 -4
  41. package/dist/domain/send-time.js +10 -24
  42. package/dist/entities/fields.d.ts +2 -2
  43. package/dist/entities/fields.js +2 -2
  44. package/dist/entities/index.d.ts +92 -1
  45. package/dist/entities/index.js +3 -2
  46. package/dist/entities/meeting.d.ts +1 -1
  47. package/dist/entities/meeting.js +1 -1
  48. package/dist/errors/reasons.js +0 -1
  49. package/dist/mail/cli/index.js +4 -2
  50. package/dist/mail/facts.d.ts +5 -2
  51. package/dist/mail/facts.js +6 -3
  52. package/dist/mail/index.d.ts +1 -1
  53. package/dist/mail/meeting-notes.js +1 -1
  54. package/dist/mail/probe.d.ts +5 -2
  55. package/dist/mail/probe.js +9 -5
  56. package/dist/mail/server-search.js +1 -1
  57. package/dist/mail/sync.js +1 -1
  58. package/dist/mcp/meeting-preparation.js +1 -1
  59. package/dist/mcp/meeting-series-inventory.js +1 -1
  60. package/dist/mcp/prompts.js +6 -9
  61. package/dist/meetings/call-answers.d.ts +106 -0
  62. package/dist/meetings/call-answers.js +171 -0
  63. package/dist/meetings/call-stats.d.ts +121 -0
  64. package/dist/meetings/call-stats.js +211 -0
  65. package/dist/meetings/calls.d.ts +76 -0
  66. package/dist/meetings/calls.js +78 -0
  67. package/dist/meetings/cli/index.d.ts +8 -0
  68. package/dist/meetings/cli/index.js +10 -22
  69. package/dist/meetings/cli/search.d.ts +9 -2
  70. package/dist/meetings/cli/search.js +16 -26
  71. package/dist/meetings/index.d.ts +3 -0
  72. package/dist/meetings/index.js +3 -0
  73. package/dist/meetings/mcp/index.d.ts +6 -3
  74. package/dist/meetings/mcp/index.js +2 -4
  75. package/dist/meetings/mcp/search.d.ts +6 -1
  76. package/dist/meetings/mcp/search.js +3 -3
  77. package/dist/meetings/read-through.d.ts +2 -1
  78. package/dist/meetings/read-through.js +10 -1
  79. package/dist/meetings/stats.d.ts +3 -0
  80. package/dist/meetings/stats.js +3 -3
  81. package/dist/meetings/testing/index.d.ts +1 -0
  82. package/dist/meetings/testing/index.js +1 -0
  83. package/dist/meetings/testing/paging.d.ts +6 -0
  84. package/dist/meetings/testing/paging.js +5 -0
  85. package/dist/moderation/rules.d.ts +2 -0
  86. package/dist/moderation/rules.js +16 -2
  87. package/dist/search/fusion.d.ts +17 -0
  88. package/dist/search/fusion.js +17 -0
  89. package/dist/search/lucene/resolved.d.ts +2 -0
  90. package/dist/search/question-plan.d.ts +2 -0
  91. package/dist/search/question-plan.js +5 -0
  92. package/dist/search/service-query.d.ts +6 -1
  93. package/dist/search/service-query.js +9 -1
  94. package/dist/services/agenda-mail.js +2 -1
  95. package/dist/services/agenda.js +5 -3
  96. package/dist/services/attachments.js +4 -2
  97. package/dist/services/call-stats.d.ts +17 -0
  98. package/dist/services/call-stats.js +41 -0
  99. package/dist/services/chats.js +4 -2
  100. package/dist/services/conversations.js +4 -2
  101. package/dist/services/deps.d.ts +1 -1
  102. package/dist/services/document-source.d.ts +1 -1
  103. package/dist/services/document-source.js +4 -3
  104. package/dist/services/documents/ingestion.js +11 -40
  105. package/dist/services/documents/plan.d.ts +1 -1
  106. package/dist/services/documents/plan.js +30 -17
  107. package/dist/services/documents/ports.d.ts +5 -0
  108. package/dist/services/documents/sync.js +1 -1
  109. package/dist/services/embeddings-search.js +20 -4
  110. package/dist/services/events-search.js +2 -1
  111. package/dist/services/index.d.ts +1 -0
  112. package/dist/services/index.js +1 -0
  113. package/dist/services/mail-search.d.ts +1 -1
  114. package/dist/services/mail-search.js +10 -11
  115. package/dist/services/media-archive-move.js +2 -4
  116. package/dist/services/media-archive.d.ts +0 -1
  117. package/dist/services/media-archive.js +2 -12
  118. package/dist/services/meeting-combined.js +1 -1
  119. package/dist/services/messages-combined.js +15 -4
  120. package/dist/services/moderation.js +10 -2
  121. package/dist/services/moment.d.ts +4 -10
  122. package/dist/services/moment.js +16 -44
  123. package/dist/services/notes-search.d.ts +0 -2
  124. package/dist/services/notes-search.js +1 -2
  125. package/dist/services/search-all.js +2 -1
  126. package/dist/services/tags.js +4 -2
  127. package/dist/services/task-stats.js +2 -2
  128. package/dist/services/tasks.js +2 -2
  129. package/dist/store/accounts.js +2 -1
  130. package/dist/store/sqlite/account-purge.d.ts +3 -0
  131. package/dist/store/sqlite/account-purge.js +143 -0
  132. package/dist/store/sqlite/accounts.d.ts +0 -2
  133. package/dist/store/sqlite/accounts.js +2 -134
  134. package/dist/store/sqlite/calendar.d.ts +1 -0
  135. package/dist/store/sqlite/calendar.js +5 -5
  136. package/dist/store/sqlite/catalog.js +2 -16
  137. package/dist/store/sqlite/chats.js +2 -1
  138. package/dist/store/sqlite/context-document-source.d.ts +3 -3
  139. package/dist/store/sqlite/context-document-source.js +9 -7
  140. package/dist/store/sqlite/context-evidence.js +9 -3
  141. package/dist/store/sqlite/document-listing.js +2 -1
  142. package/dist/store/sqlite/events.js +2 -1
  143. package/dist/store/sqlite/file-note.d.ts +6 -0
  144. package/dist/store/sqlite/file-note.js +15 -0
  145. package/dist/store/sqlite/files.d.ts +3 -2
  146. package/dist/store/sqlite/files.js +5 -3
  147. package/dist/store/sqlite/identities.js +2 -1
  148. package/dist/store/sqlite/imported-documents.js +2 -2
  149. package/dist/store/sqlite/knowledge.js +19 -19
  150. package/dist/store/sqlite/lucene-fields.js +8 -12
  151. package/dist/store/sqlite/mail-rules.js +2 -1
  152. package/dist/store/sqlite/meeting-calls.d.ts +4 -0
  153. package/dist/store/sqlite/meeting-calls.js +66 -0
  154. package/dist/store/sqlite/meetings.d.ts +2 -2
  155. package/dist/store/sqlite/meetings.js +4 -1
  156. package/dist/store/sqlite/mention-sources.js +2 -1
  157. package/dist/store/sqlite/mentions.js +2 -2
  158. package/dist/store/sqlite/messages.js +6 -1
  159. package/dist/store/sqlite/note-search.js +8 -11
  160. package/dist/store/sqlite/notes.d.ts +2 -0
  161. package/dist/store/sqlite/notes.js +24 -13
  162. package/dist/store/sqlite/organizations.js +2 -2
  163. package/dist/store/sqlite/people-list.js +3 -3
  164. package/dist/store/sqlite/query-filter.d.ts +3 -3
  165. package/dist/store/sqlite/query-filter.js +3 -3
  166. package/dist/store/sqlite/reads.d.ts +4 -4
  167. package/dist/store/sqlite/reads.js +4 -4
  168. package/dist/store/sqlite/search.js +11 -7
  169. package/dist/store/sqlite/test-accounts.js +1 -1
  170. package/dist/store/sqlite/trigram-match.d.ts +9 -0
  171. package/dist/store/sqlite/trigram-match.js +28 -0
  172. package/dist/store/sqlite/work-tasks.js +1 -1
  173. package/package.json +3 -3
@@ -1,12 +1,20 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { gather, MAX_ACTIONS } from "../moderation/check.js";
3
- import { defaultRules, ModerationRules, moderationPathFor } from "../moderation/rules.js";
3
+ import { defaultRules, ModerationRules, moderationPathFor, moderationProfiles, } from "../moderation/rules.js";
4
4
  import { moderateWith } from "../moderation/run.js";
5
5
  import { capability } from "../ports/messenger.js";
6
6
  import { guardedWrite } from "../sends/guarded.js";
7
7
  import { newOperationId } from "../sends/send-id.js";
8
8
  export const moderationService = (deps) => {
9
- const file = () => new ModerationRules(moderationPathFor(deps.messenger.app, deps.profile ?? "default", deps.env ?? process.env));
9
+ // Checked at first use, not here: every service is built for every command, most of them without a profile.
10
+ const file = () => {
11
+ const env = deps.env ?? process.env;
12
+ if (deps.profile === undefined) {
13
+ const choices = moderationProfiles(deps.messenger.app, env);
14
+ throw new CliError("validation_error", `name a profile: moderation rules are kept per profile — ${choices.length ? `profiles here: ${choices.join(", ")}` : "there is none on this computer yet"}`, { profiles: choices });
15
+ }
16
+ return new ModerationRules(moderationPathFor(deps.messenger.app, deps.profile, env));
17
+ };
10
18
  const group = async (chat) => {
11
19
  if (deps.offline)
12
20
  throw new CliError("validation_error", "a group's rules are kept by its id, which the messenger gives");
@@ -1,17 +1,11 @@
1
- import { type MomentZone } from "../domain/moment.js";
1
+ import { aheadOf, type MomentZone } from "../domain/moment.js";
2
2
  export type { MomentZone };
3
- /** Shaped like a moment `momentOf` reads, whether or not it is a valid one. */
4
- export declare const isMoment: (reference: string) => boolean;
3
+ export { aheadOf };
5
4
  /**
6
- * `--since` as a moment: ISO 8601, or `30m`, `2h`, `1d` ago. Unlike max-cli, never a message id —
7
- * a MAX id carries its time, and a Telegram id is only a counter within one chat.
5
+ * `--since` as a moment, in the shared time grammar (`readMoment`). Unlike max-cli, never a message id — a MAX id
6
+ * carries its time, and a Telegram id is only a counter within one chat.
8
7
  */
9
8
  export declare const momentOf: (reference: string, flag?: string, now?: number, at?: MomentZone) => number;
10
- /**
11
- * A time ahead, for a due date or the next check: ISO 8601, or `30m`, `2h`, `3d` from now. `none`
12
- * is not a time; a caller that clears a date checks for it first.
13
- */
14
- export declare const aheadOf: (reference: string, flag: string, now?: number, at?: MomentZone) => number;
15
9
  export interface DateWindow {
16
10
  since?: number;
17
11
  until?: number;
@@ -1,54 +1,26 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { timezoneOf } from "@wirecat/cli-base/query";
3
- import { calendarMoment } from "../domain/moment.js";
4
- const AGO = /^(\d+)(m|h|d)$/;
5
- const AGO_MS = { m: 60_000, h: 3_600_000, d: 86_400_000 };
6
- const DATE = /^\d{4}-\d{2}-\d{2}/;
7
- /** Shaped like a moment `momentOf` reads, whether or not it is a valid one. */
8
- export const isMoment = (reference) => {
9
- const wanted = reference.trim();
10
- return AGO.test(wanted) || DATE.test(wanted);
3
+ import { aheadOf, readMoment } from "../domain/moment.js";
4
+ export { aheadOf };
5
+ const read = (reference, flag, now, at) => {
6
+ const found = readMoment(reference, flag, { ...at, now });
7
+ if (found === undefined)
8
+ throw new CliError("validation_error", `${flag} takes an ISO 8601 time, today, yesterday, or 30m, 2h, 1d ago — not "${reference.trim()}"`);
9
+ return found;
11
10
  };
12
11
  /**
13
- * `--since` as a moment: ISO 8601, or `30m`, `2h`, `1d` ago. Unlike max-cli, never a message id —
14
- * a MAX id carries its time, and a Telegram id is only a counter within one chat.
12
+ * `--since` as a moment, in the shared time grammar (`readMoment`). Unlike max-cli, never a message id — a MAX id
13
+ * carries its time, and a Telegram id is only a counter within one chat.
15
14
  */
16
- export const momentOf = (reference, flag = "--since", now = Date.now(), at = {}) => {
17
- const wanted = reference.trim();
18
- const [, amount, unit] = AGO.exec(wanted) ?? [];
19
- // By shape: `Date.parse("12345")` is the year 12345, so a message id would pass as a date.
20
- const time = amount && unit
21
- ? now - Number(amount) * (AGO_MS[unit] ?? 0)
22
- : DATE.test(wanted)
23
- ? calendarMoment(wanted, flag, at)
24
- : Number.NaN;
25
- if (Number.isNaN(time)) {
26
- throw new CliError("validation_error", `${flag} takes an ISO 8601 time or 30m, 2h, 1d ago — not "${wanted}"`);
27
- }
28
- return time;
29
- };
30
- /**
31
- * A time ahead, for a due date or the next check: ISO 8601, or `30m`, `2h`, `3d` from now. `none`
32
- * is not a time; a caller that clears a date checks for it first.
33
- */
34
- export const aheadOf = (reference, flag, now = Date.now(), at = {}) => {
35
- const wanted = reference.trim();
36
- const [, amount, unit] = AGO.exec(wanted) ?? [];
37
- const time = amount && unit
38
- ? now + Number(amount) * (AGO_MS[unit] ?? 0)
39
- : DATE.test(wanted)
40
- ? calendarMoment(wanted, flag, at)
41
- : Number.NaN;
42
- if (Number.isNaN(time)) {
43
- throw new CliError("validation_error", `${flag} takes an ISO 8601 time or 30m, 2h, 3d from now — not "${wanted}"`);
44
- }
45
- return time;
46
- };
15
+ export const momentOf = (reference, flag = "--since", now = Date.now(), at = {}) => read(reference, flag, now, at).time;
47
16
  /** `--since-time` and `--until-time` together, as the filter and the `meta` an answer reports it by. */
48
17
  export const dateWindow = ({ sinceTime, untilTime, zone, now = Date.now(), names = ["--since-time", "--until-time"], }) => {
49
- const since = sinceTime === undefined ? undefined : momentOf(sinceTime, names[0], now, { zone });
50
- const until = untilTime === undefined ? undefined : momentOf(untilTime, names[1], now, { zone, end: true });
51
- const readInZone = [sinceTime, untilTime].some((value) => value !== undefined && DATE.test(value.trim()) && !/(?:Z|[+-]\d{2}:?\d{2})$/i.test(value.trim()));
18
+ const at = zone === undefined ? {} : { zone };
19
+ const lower = sinceTime === undefined ? undefined : read(sinceTime, names[0], now, at);
20
+ const upper = untilTime === undefined ? undefined : read(untilTime, names[1], now, { ...at, end: true });
21
+ const since = lower?.time;
22
+ const until = upper?.time;
23
+ const readInZone = lower?.local === true || upper?.local === true;
52
24
  const window = {
53
25
  ...(since === undefined ? {} : { since: new Date(since).toISOString() }),
54
26
  ...(until === undefined ? {} : { until: new Date(until).toISOString() }),
@@ -179,8 +179,6 @@ export interface NotesQuery {
179
179
  /** An open picture embedder, for tests and callers that keep one; opened and closed here when absent. */
180
180
  pictureEmbedder?: PictureEmbedder;
181
181
  }
182
- /** Reciprocal rank fusion's usual constant, as conversations use. */
183
- export declare const RRF_K = 60;
184
182
  /**
185
183
  * A `source:` every hit must match, and the query without it. The meaning half and the picture lane cannot read a
186
184
  * field, so they get the source and the rest of the words; the words half still compiles the field itself.
@@ -6,6 +6,7 @@ import { defaultThreads, isTextModelInstalled, openEmbedder, textModelsDirectory
6
6
  import { chosenTextModel, meaningFloor, textModel, vectorModelKey } from "../embeddings/models.js";
7
7
  import { DEFAULT_IMAGE_MODEL, imageModel } from "../images/picture/models.js";
8
8
  import { entriesOfList, fitting, sourceOf } from "../search/account-list.js";
9
+ import { RRF_K } from "../search/fusion.js";
9
10
  import { OWNER_NOTES } from "../search/groups.js";
10
11
  import { fieldsOfQuery as fieldsOf, meaningWords } from "../search/lucene/meaning-parts.js";
11
12
  import { plainQuery } from "../search/lucene/plain.js";
@@ -201,8 +202,6 @@ const MAX_LINE = 200;
201
202
  const MAX_NOTES_OFFSET = 1000;
202
203
  /** How deep each half is read before the two are merged. */
203
204
  const CANDIDATES = 50;
204
- /** Reciprocal rank fusion's usual constant, as conversations use. */
205
- export const RRF_K = 60;
206
205
  const firstLine = (text, query) => {
207
206
  const words = query
208
207
  .toLowerCase()
@@ -8,6 +8,7 @@ import { runEmbedders } from "../embeddings/embed.js";
8
8
  import { chosenTextModel } from "../embeddings/models.js";
9
9
  import { formatMeetingReference } from "../meetings/index.js";
10
10
  import { entriesOfList, fitting, listedHolds } from "../search/account-list.js";
11
+ import { RRF_K } from "../search/fusion.js";
11
12
  import { plainQuery } from "../search/lucene/plain.js";
12
13
  import { MESSAGE_PARSING, SEARCH_QUERY } from "../search/lucene/types.js";
13
14
  import { questionPeriod } from "../search/question-period.js";
@@ -16,7 +17,7 @@ import { calendarAccounts, searchEvents } from "./events-search.js";
16
17
  import { excerpt } from "./excerpt.js";
17
18
  import { MAX_SEARCH_OFFSET, searchStore } from "./messages-archive-search.js";
18
19
  import { nearEligible } from "./messages-discovery.js";
19
- import { importAccounts, notesScopeOf, RRF_K, searchNotes } from "./notes-search.js";
20
+ import { importAccounts, notesScopeOf, searchNotes } from "./notes-search.js";
20
21
  import { BUSINESS_WORDS_ONLY, searchBusiness } from "./search-all-business.js";
21
22
  import { meetingLane } from "./search-all-meetings.js";
22
23
  import { HARDER_CANDIDATES, reorderHarder } from "./search-harder.js";
@@ -1,5 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
- import { queryFieldsOf } from "@wirecat/cli-base/query";
2
+ import { queryFieldsOf, timezoneOf } from "@wirecat/cli-base/query";
3
3
  import { formatLocator, isLocator, parseLocator } from "../domain/locator.js";
4
4
  import { formatReference } from "../domain/references.js";
5
5
  import { normalizeTag } from "../domain/tags.js";
@@ -93,7 +93,9 @@ export const tagsService = (deps) => {
93
93
  return { target: viewOf(account, target), removed, unchanged: tags.filter((tag) => !removed.includes(tag)) };
94
94
  }),
95
95
  list: ({ query, limit, offset }) => inStore(async (store, account) => {
96
- const where = query ? queryFilter(query, TAGGING_COLUMNS, { command: "tags list" }) : undefined;
96
+ const where = query
97
+ ? queryFilter(query, TAGGING_COLUMNS, { command: "tags list", zone: timezoneOf() })
98
+ : undefined;
97
99
  const rows = await store.tags.tags(account, {
98
100
  ...(where ? { where } : {}),
99
101
  window: { limit: limit + 1, offset },
@@ -1,5 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
- import { walkQuery } from "@wirecat/cli-base/query";
2
+ import { timezoneOf, walkQuery } from "@wirecat/cli-base/query";
3
3
  import { parseMeetingReference } from "../meetings/index.js";
4
4
  import { withoutField } from "../store/index.js";
5
5
  import { queryFilter } from "../store/store.js";
@@ -59,7 +59,7 @@ export const taskStatsOf = async (store, accounts, { by = "chat", query, timezon
59
59
  ...(kind === undefined ? [] : [{ sql: "t.type = ?", params: [kind] }]),
60
60
  ...(by === "meeting" ? [{ sql: "t.source_kind = 'meeting'", params: [] }] : []),
61
61
  ];
62
- const options = { command: "stats tasks show", now, ...(timezone === undefined ? {} : { zone: timezone }) };
62
+ const options = { command: "stats tasks show", now, zone: timezoneOf(timezone) };
63
63
  const where = (ast, more = []) => and([...fixed, ...more, ...(ast ? [queryFilter(ast, read, options)] : [])]);
64
64
  // Project tasks belong to no account: one board read, whatever the accounts.
65
65
  const scopes = by === "project"
@@ -1,5 +1,5 @@
1
1
  import { CliError, isCliError, singleLine } from "@wirecat/cli-base";
2
- import { OPERATORS_BY_TYPE, queryFieldsOf, walkQuery } from "@wirecat/cli-base/query";
2
+ import { OPERATORS_BY_TYPE, queryFieldsOf, timezoneOf, walkQuery, } from "@wirecat/cli-base/query";
3
3
  import { isLocator, parseLocator } from "../domain/locator.js";
4
4
  import { formatReference } from "../domain/references.js";
5
5
  import { task as taskEntity } from "../entities/task.js";
@@ -230,7 +230,7 @@ export const tasksService = (deps, categories) => {
230
230
  return {
231
231
  list: ({ query, limit, offset, previews }) => inStore(async (store, account) => {
232
232
  const where = query
233
- ? queryFilter(query, await queryColumns(store, account, query), { command: "tasks list" })
233
+ ? queryFilter(query, await queryColumns(store, account, query), { command: "tasks list", zone: timezoneOf() })
234
234
  : undefined;
235
235
  const rows = await store.tasks.query(taskAccount(account), where, { limit: limit + 1, offset });
236
236
  const shown = rows.slice(0, limit);
@@ -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),