@wirecat/cli-core 0.661.0 → 0.663.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (201) hide show
  1. package/CHANGELOG.md +109 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/calendar/cli/bodies.js +2 -1
  4. package/dist/calendar/cli/index.js +13 -10
  5. package/dist/calendar/mcp/index.d.ts +3 -1
  6. package/dist/calendar/mcp/index.js +4 -4
  7. package/dist/cli/ai-model-command.js +3 -3
  8. package/dist/cli/call-stats-command.d.ts +18 -0
  9. package/dist/cli/call-stats-command.js +52 -0
  10. package/dist/cli/command-availability.d.ts +1 -1
  11. package/dist/cli/command-availability.js +4 -4
  12. package/dist/cli/contract-templates.js +2 -0
  13. package/dist/cli/dry-run-guard.js +7 -5
  14. package/dist/cli/early-refusal.d.ts +1 -1
  15. package/dist/cli/early-refusal.js +2 -2
  16. package/dist/cli/effects.d.ts +9 -2
  17. package/dist/cli/effects.js +16 -4
  18. package/dist/cli/envelope.d.ts +0 -5
  19. package/dist/cli/envelope.js +25 -0
  20. package/dist/cli/index.d.ts +3 -2
  21. package/dist/cli/index.js +3 -2
  22. package/dist/cli/meeting-batch.d.ts +2 -1
  23. package/dist/cli/meeting-batch.js +7 -5
  24. package/dist/cli/meeting-preparation-command.js +5 -5
  25. package/dist/cli/meeting-preparation-read.d.ts +5 -5
  26. package/dist/cli/meeting-preparation-read.js +13 -21
  27. package/dist/cli/meeting-series-inventory-command.js +2 -2
  28. package/dist/cli/meeting-series-inventory-read.d.ts +2 -2
  29. package/dist/cli/meeting-series-inventory-read.js +7 -15
  30. package/dist/cli/messenger/admin-moderation-command.js +2 -2
  31. package/dist/cli/messenger/admin-statistics-command.js +2 -2
  32. package/dist/cli/messenger/archive-commands.js +2 -2
  33. package/dist/cli/messenger/context.d.ts +2 -2
  34. package/dist/cli/messenger/context.js +5 -3
  35. package/dist/cli/messenger/counters-command.js +2 -2
  36. package/dist/cli/messenger/media-archive-command.js +5 -4
  37. package/dist/cli/messenger/media-archive-move-command.js +1 -1
  38. package/dist/cli/messenger/media-archive-timer-command.js +5 -4
  39. package/dist/cli/messenger/metadata-command.js +3 -3
  40. package/dist/cli/messenger/rankings-command.js +3 -3
  41. package/dist/cli/messenger/tags-command.js +7 -2
  42. package/dist/cli/messenger/tasks-command.js +4 -3
  43. package/dist/cli/paging.d.ts +10 -0
  44. package/dist/cli/paging.js +29 -0
  45. package/dist/cli/preview.js +3 -5
  46. package/dist/cli/program.js +2 -2
  47. package/dist/cli/runs/command.js +6 -4
  48. package/dist/cli/runs/search-command.js +9 -5
  49. package/dist/cli/schedule/schedule-command.js +1 -5
  50. package/dist/cli/shadowed-options.d.ts +7 -0
  51. package/dist/cli/shadowed-options.js +26 -0
  52. package/dist/crm/cli/index.js +4 -2
  53. package/dist/domain/moment.d.ts +29 -0
  54. package/dist/domain/moment.js +58 -0
  55. package/dist/domain/providers.d.ts +6 -4
  56. package/dist/domain/providers.js +10 -5
  57. package/dist/domain/send-time.d.ts +3 -4
  58. package/dist/domain/send-time.js +10 -24
  59. package/dist/entities/fields.d.ts +2 -2
  60. package/dist/entities/fields.js +2 -2
  61. package/dist/entities/index.d.ts +92 -1
  62. package/dist/entities/index.js +3 -2
  63. package/dist/entities/meeting.d.ts +1 -1
  64. package/dist/entities/meeting.js +1 -1
  65. package/dist/errors/reasons.js +0 -1
  66. package/dist/kit/sync-after-install.d.ts +10 -1
  67. package/dist/kit/sync-after-install.js +35 -11
  68. package/dist/mail/cli/index.js +4 -2
  69. package/dist/mail/facts.d.ts +5 -2
  70. package/dist/mail/facts.js +6 -3
  71. package/dist/mail/index.d.ts +1 -1
  72. package/dist/mail/meeting-notes.js +1 -1
  73. package/dist/mail/probe.d.ts +5 -2
  74. package/dist/mail/probe.js +9 -5
  75. package/dist/mail/server-search.js +4 -4
  76. package/dist/mail/sync.js +1 -1
  77. package/dist/mcp/meeting-preparation.js +1 -1
  78. package/dist/mcp/meeting-series-inventory.js +1 -1
  79. package/dist/mcp/prompts.js +6 -9
  80. package/dist/mcp/server.js +4 -4
  81. package/dist/mcp/tool.js +3 -3
  82. package/dist/meetings/call-answers.d.ts +106 -0
  83. package/dist/meetings/call-answers.js +171 -0
  84. package/dist/meetings/call-stats.d.ts +121 -0
  85. package/dist/meetings/call-stats.js +211 -0
  86. package/dist/meetings/calls.d.ts +76 -0
  87. package/dist/meetings/calls.js +78 -0
  88. package/dist/meetings/cli/index.d.ts +8 -0
  89. package/dist/meetings/cli/index.js +10 -22
  90. package/dist/meetings/cli/search.d.ts +9 -2
  91. package/dist/meetings/cli/search.js +16 -26
  92. package/dist/meetings/index.d.ts +3 -0
  93. package/dist/meetings/index.js +3 -0
  94. package/dist/meetings/mcp/index.d.ts +21 -18
  95. package/dist/meetings/mcp/index.js +2 -4
  96. package/dist/meetings/mcp/search.d.ts +6 -1
  97. package/dist/meetings/mcp/search.js +3 -3
  98. package/dist/meetings/read-through.d.ts +2 -1
  99. package/dist/meetings/read-through.js +10 -1
  100. package/dist/meetings/stats.d.ts +3 -0
  101. package/dist/meetings/stats.js +3 -3
  102. package/dist/meetings/testing/index.d.ts +1 -0
  103. package/dist/meetings/testing/index.js +1 -0
  104. package/dist/meetings/testing/paging.d.ts +6 -0
  105. package/dist/meetings/testing/paging.js +5 -0
  106. package/dist/moderation/rules.d.ts +2 -0
  107. package/dist/moderation/rules.js +16 -2
  108. package/dist/search/fusion.d.ts +17 -0
  109. package/dist/search/fusion.js +17 -0
  110. package/dist/search/lucene/resolved.d.ts +2 -0
  111. package/dist/search/question-plan.d.ts +2 -0
  112. package/dist/search/question-plan.js +5 -0
  113. package/dist/search/service-query.d.ts +6 -1
  114. package/dist/search/service-query.js +9 -1
  115. package/dist/sends/guard.js +4 -20
  116. package/dist/sends/keyed-guard.d.ts +1 -1
  117. package/dist/sends/keyed-guard.js +2 -1
  118. package/dist/sends/permissions.d.ts +14 -0
  119. package/dist/sends/permissions.js +32 -0
  120. package/dist/services/agenda-mail.js +2 -1
  121. package/dist/services/agenda.js +5 -3
  122. package/dist/services/attachments.js +4 -2
  123. package/dist/services/call-stats.d.ts +17 -0
  124. package/dist/services/call-stats.js +41 -0
  125. package/dist/services/chats.js +4 -2
  126. package/dist/services/conversations.js +4 -2
  127. package/dist/services/deps.d.ts +1 -1
  128. package/dist/services/document-source.d.ts +1 -1
  129. package/dist/services/document-source.js +4 -3
  130. package/dist/services/documents/ingestion.js +11 -40
  131. package/dist/services/documents/plan.d.ts +1 -1
  132. package/dist/services/documents/plan.js +30 -17
  133. package/dist/services/documents/ports.d.ts +5 -0
  134. package/dist/services/documents/sync.js +1 -1
  135. package/dist/services/embeddings-search.js +20 -4
  136. package/dist/services/events-search.js +2 -1
  137. package/dist/services/index.d.ts +1 -0
  138. package/dist/services/index.js +1 -0
  139. package/dist/services/mail-search.d.ts +1 -1
  140. package/dist/services/mail-search.js +10 -11
  141. package/dist/services/media-archive-move.js +2 -4
  142. package/dist/services/media-archive.d.ts +0 -1
  143. package/dist/services/media-archive.js +2 -12
  144. package/dist/services/meeting-combined.js +1 -1
  145. package/dist/services/messages-combined.js +15 -4
  146. package/dist/services/moderation.js +10 -2
  147. package/dist/services/moment.d.ts +4 -10
  148. package/dist/services/moment.js +16 -44
  149. package/dist/services/notes-search.d.ts +0 -2
  150. package/dist/services/notes-search.js +1 -2
  151. package/dist/services/search-all.js +2 -1
  152. package/dist/services/server-search.js +1 -1
  153. package/dist/services/tags.js +4 -2
  154. package/dist/services/task-stats.js +2 -2
  155. package/dist/services/tasks.js +2 -2
  156. package/dist/store/accounts.js +2 -1
  157. package/dist/store/sqlite/account-purge.d.ts +3 -0
  158. package/dist/store/sqlite/account-purge.js +143 -0
  159. package/dist/store/sqlite/accounts.d.ts +0 -2
  160. package/dist/store/sqlite/accounts.js +2 -134
  161. package/dist/store/sqlite/calendar.d.ts +1 -0
  162. package/dist/store/sqlite/calendar.js +5 -5
  163. package/dist/store/sqlite/catalog.js +2 -16
  164. package/dist/store/sqlite/chats.js +2 -1
  165. package/dist/store/sqlite/context-document-source.d.ts +3 -3
  166. package/dist/store/sqlite/context-document-source.js +9 -7
  167. package/dist/store/sqlite/context-evidence.js +9 -3
  168. package/dist/store/sqlite/document-listing.js +2 -1
  169. package/dist/store/sqlite/events.js +2 -1
  170. package/dist/store/sqlite/file-note.d.ts +6 -0
  171. package/dist/store/sqlite/file-note.js +15 -0
  172. package/dist/store/sqlite/files.d.ts +3 -2
  173. package/dist/store/sqlite/files.js +5 -3
  174. package/dist/store/sqlite/identities.js +2 -1
  175. package/dist/store/sqlite/imported-documents.js +2 -2
  176. package/dist/store/sqlite/knowledge.js +19 -19
  177. package/dist/store/sqlite/lucene-fields.js +8 -12
  178. package/dist/store/sqlite/mail-rules.js +2 -1
  179. package/dist/store/sqlite/meeting-calls.d.ts +4 -0
  180. package/dist/store/sqlite/meeting-calls.js +66 -0
  181. package/dist/store/sqlite/meetings.d.ts +2 -2
  182. package/dist/store/sqlite/meetings.js +4 -1
  183. package/dist/store/sqlite/mention-sources.js +2 -1
  184. package/dist/store/sqlite/mentions.js +2 -2
  185. package/dist/store/sqlite/messages.js +6 -1
  186. package/dist/store/sqlite/note-search.js +8 -11
  187. package/dist/store/sqlite/notes.d.ts +2 -0
  188. package/dist/store/sqlite/notes.js +24 -13
  189. package/dist/store/sqlite/organizations.js +2 -2
  190. package/dist/store/sqlite/people-list.js +3 -3
  191. package/dist/store/sqlite/query-filter.d.ts +3 -3
  192. package/dist/store/sqlite/query-filter.js +3 -3
  193. package/dist/store/sqlite/reads.d.ts +4 -4
  194. package/dist/store/sqlite/reads.js +4 -4
  195. package/dist/store/sqlite/search.js +11 -7
  196. package/dist/store/sqlite/test-accounts.js +1 -1
  197. package/dist/store/sqlite/trigram-match.d.ts +9 -0
  198. package/dist/store/sqlite/trigram-match.js +28 -0
  199. package/dist/store/sqlite/work-tasks.js +1 -1
  200. package/package.json +3 -3
  201. package/parity.json +2 -1
@@ -1,4 +1,4 @@
1
- import { defineQuery, validateQuery } from "@wirecat/cli-base/query";
1
+ import { defineQuery, timezoneOf, validateQuery } from "@wirecat/cli-base/query";
2
2
  import { normalizeTag } from "../../domain/tags.js";
3
3
  import { idsOf } from "./merged-persons.js";
4
4
  import { queryFilter } from "./query-filter.js";
@@ -51,5 +51,5 @@ export const importedDocumentWhere = (database, query) => {
51
51
  },
52
52
  },
53
53
  };
54
- return queryFilter(validateQuery(query, IMPORTED_DOCUMENT_QUERY), columns);
54
+ return queryFilter(validateQuery(query, IMPORTED_DOCUMENT_QUERY), columns, { zone: timezoneOf() });
55
55
  };
@@ -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 { parseLocator } from "../../domain/locator.js";
4
4
  import { isBusinessType } from "../../domain/record-types.js";
5
5
  import { formatReference, parseReference } from "../../domain/references.js";
@@ -64,6 +64,22 @@ const oneOf = (value, allowed, what) => {
64
64
  /** What a relationship may connect; a deal or a lead only as the end its people hang from. */
65
65
  const RELATED = ["person", "organization", "project", "task"];
66
66
  const DEALS = ["deal", "lead"];
67
+ const PROJECT_COLUMNS = {
68
+ id: { type: "kw", sql: "CAST(id AS TEXT)" },
69
+ key: { type: "kw", sql: "key" },
70
+ name: { type: "kw", sql: "name_folded", folded: true },
71
+ kind: { type: "enum", sql: `CASE WHEN length(key) = ${INBOX_KEY_LENGTH} THEN 'inbox' ELSE 'project' END` },
72
+ type: { type: "enum", sql: "type" },
73
+ organization_id: { type: "kw", sql: "CAST(organization_id AS TEXT)" },
74
+ scope: { type: "enum", sql: "scope" },
75
+ created_at: { type: "time", sql: "created_at" },
76
+ };
77
+ const REMINDER_COLUMNS = {
78
+ id: { type: "kw", sql: "CAST(id AS TEXT)" },
79
+ state: { type: "enum", sql: "state" },
80
+ due_at: { type: "time", sql: "due_at" },
81
+ revision: { type: "num", sql: "revision" },
82
+ };
67
83
  export const knowledgeStoreOver = (context) => {
68
84
  const { database, now } = context;
69
85
  const ids = (thing) => thing ? idsOf(database, thing.type, thing.id) : null;
@@ -455,17 +471,7 @@ export const knowledgeStoreOver = (context) => {
455
471
  addProject: async (input) => write(database, () => projectOf(insertProject(context, input))),
456
472
  projects: async (query) => {
457
473
  const asksKind = query !== undefined && walkQuery(query.root).some((node) => node.field === "kind");
458
- const where = query &&
459
- queryFilter(query, {
460
- id: { type: "kw", sql: "CAST(id AS TEXT)" },
461
- key: { type: "kw", sql: "key" },
462
- name: { type: "kw", sql: "name_folded", folded: true },
463
- kind: { type: "enum", sql: `CASE WHEN length(key) = ${INBOX_KEY_LENGTH} THEN 'inbox' ELSE 'project' END` },
464
- type: { type: "enum", sql: "type" },
465
- organization_id: { type: "kw", sql: "CAST(organization_id AS TEXT)" },
466
- scope: { type: "enum", sql: "scope" },
467
- created_at: { type: "time", sql: "created_at" },
468
- });
474
+ const where = query && queryFilter(query, PROJECT_COLUMNS, { zone: timezoneOf() });
469
475
  return database
470
476
  .prepare(`SELECT * FROM projects WHERE deleted_at IS NULL${asksKind ? "" : ` AND length(key) <> ${INBOX_KEY_LENGTH}`}${where ? ` AND (${where.sql})` : ""} ORDER BY name, id LIMIT 500`)
471
477
  .all(...(where?.params ?? []))
@@ -579,13 +585,7 @@ export const knowledgeStoreOver = (context) => {
579
585
  return reminder(key, String(made?.id));
580
586
  },
581
587
  reminders: async (key, query) => {
582
- const where = query &&
583
- queryFilter(query, {
584
- id: { type: "kw", sql: "CAST(id AS TEXT)" },
585
- state: { type: "enum", sql: "state" },
586
- due_at: { type: "time", sql: "due_at" },
587
- revision: { type: "num", sql: "revision" },
588
- });
588
+ const where = query && queryFilter(query, REMINDER_COLUMNS, { zone: timezoneOf() });
589
589
  return database
590
590
  .prepare(`SELECT * FROM reminders WHERE account_id=?${where ? ` AND (${where.sql})` : ""} ORDER BY due_at, id LIMIT 500`)
591
591
  .all(account(key), ...(where?.params ?? []))
@@ -13,6 +13,7 @@ import { fold, normalize } from "../normalize.js";
13
13
  import { linkMatch } from "./mention-links.js";
14
14
  import { valueMatch } from "./phone-countries.js";
15
15
  import { canonicalTagNamed } from "./tags.js";
16
+ import { yoSpellings } from "./trigram-match.js";
16
17
  /**
17
18
  * A voice note's transcript is its attachment's text, whoever wrote it: speech recognition (`speech:<model>`) or an
18
19
  * agent, which writes the text of a voice attachment as `agent`. The voice attachment is the one
@@ -181,17 +182,6 @@ const literalRuns = (value) => {
181
182
  }
182
183
  return runs.filter(Boolean);
183
184
  };
184
- const MOST_YO_SPELLINGS = 64;
185
- /** Every spelling of `run` with each е or ё as either: the trigram index keeps the text as written. */
186
- const yoSpellings = (run) => {
187
- let spellings = [""];
188
- for (const c of run) {
189
- spellings = spellings.flatMap((start) => (c === "е" || c === "ё" ? [`${start}е`, `${start}ё`] : [`${start}${c}`]));
190
- if (spellings.length > MOST_YO_SPELLINGS)
191
- return undefined;
192
- }
193
- return spellings;
194
- };
195
185
  /**
196
186
  * A pattern with no start to read the word list from (`*договор*`, `*ость`), in chat messages: the trigram index of
197
187
  * their text finds where its longest part occurs, so a large store does not refuse it: the whole search took 0.5–1 s at
@@ -243,8 +233,14 @@ const words = (node, scope) => {
243
233
  const terms = scope.database
244
234
  .prepare(`SELECT term FROM ${corpus.vocab} WHERE col='normalized_text'${prefix ? " AND term>=? AND term<=?" : ""} ORDER BY term LIMIT ?`)
245
235
  .all(...(prefix ? [prefix, `${prefix}\u{10ffff}`] : []), QUERY_LIMITS.expansions + 1);
246
- if (scope.expand(terms.length) > QUERY_LIMITS.expansions)
236
+ if (scope.expand(terms.length) > QUERY_LIMITS.expansions) {
237
+ if (node.widened) {
238
+ scope.expand(-terms.length);
239
+ const { widened: _, ...typed } = node;
240
+ return words({ ...typed, operator: "term", value: node.value.replace(/\*$/u, "") }, scope);
241
+ }
247
242
  tooManyWords(node, terms.length > QUERY_LIMITS.expansions, prefix, scope.mail);
243
+ }
248
244
  const matches = terms.flatMap(({ term }) => {
249
245
  scope.check();
250
246
  return automaton.test(String(term), scope.budget) ? [quoted(String(term))] : [];
@@ -1,3 +1,4 @@
1
+ import { timezoneOf } from "@wirecat/cli-base/query";
1
2
  import { queryFilter } from "./query-filter.js";
2
3
  import { write } from "./transaction.js";
3
4
  const sorted = (value) => Array.isArray(value)
@@ -30,7 +31,7 @@ export const mailRulesOver = (database) => ({
30
31
  id: { type: "num", sql: "id" },
31
32
  protected: { type: "bool", sql: "protected" },
32
33
  source: { type: "kw", sql: "source" },
33
- });
34
+ }, { zone: timezoneOf() });
34
35
  return database
35
36
  .prepare(`SELECT * FROM mail_rules WHERE account_id = ?${where ? ` AND (${where.sql})` : ""} ORDER BY id`)
36
37
  .all(accountId, ...(where?.params ?? []))
@@ -0,0 +1,4 @@
1
+ import type { MeetingCallsStore } from "../../meetings/index.js";
2
+ import type { StoreContext } from "./open.js";
3
+ /** The selected meetings with their metadata and people, through the same filters as meeting search and stats. */
4
+ export declare const meetingCallsOver: ({ database }: StoreContext) => MeetingCallsStore;
@@ -0,0 +1,66 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { int, str } from "./events.js";
3
+ import { checkMeetingCancelled } from "./meeting-operation.js";
4
+ import { positiveReadInteger } from "./meeting-reads.js";
5
+ import { meetingSelectionSql } from "./meeting-selection.js";
6
+ import { read } from "./transaction.js";
7
+ const MOST_CALLS = 200_000;
8
+ // The store keeps what the provider wrote; one unreadable value must not fail the whole report.
9
+ const parsed = (value) => {
10
+ if (typeof value !== "string")
11
+ return null;
12
+ try {
13
+ return JSON.parse(value);
14
+ }
15
+ catch {
16
+ return null;
17
+ }
18
+ };
19
+ /** The selected meetings with their metadata and people, through the same filters as meeting search and stats. */
20
+ export const meetingCallsOver = ({ database }) => ({
21
+ async meetingCalls(input) {
22
+ checkMeetingCancelled(input.signal);
23
+ positiveReadInteger(input.accountId, "accountId");
24
+ const maxRows = input.maxRows ?? MOST_CALLS;
25
+ if (!Number.isSafeInteger(maxRows) || maxRows < 1 || maxRows > MOST_CALLS)
26
+ throw new CliError("validation_error", `call stats read 1 through ${MOST_CALLS} calls`);
27
+ return read(database, () => {
28
+ const { clauses, params } = meetingSelectionSql(input);
29
+ const meetings = database
30
+ .prepare(`SELECT m.id, m.started_at, coalesce(m.duration_ms, m.ended_at - m.started_at) AS duration_ms, m.metadata
31
+ FROM meetings m WHERE ${clauses.join(" AND ")} ORDER BY m.started_at, m.id LIMIT ?`)
32
+ .all(...params, maxRows + 1);
33
+ if (meetings.length > maxRows)
34
+ throw new CliError("validation_error", `the selection has more than ${maxRows} meetings; narrow it`);
35
+ checkMeetingCancelled(input.signal);
36
+ const people = new Map();
37
+ const rows = database
38
+ .prepare(`SELECT p.meeting_id, p.identity_id, i.external_id AS identity_key, p.role,
39
+ coalesce(p.display_name, i.name) AS name, p.external_id
40
+ FROM meeting_participants p JOIN identities i ON i.id = p.identity_id
41
+ WHERE p.meeting_id IN (SELECT m.id FROM meetings m WHERE ${clauses.join(" AND ")})
42
+ ORDER BY p.id`)
43
+ .all(...params);
44
+ for (const row of rows) {
45
+ const meetingId = Number(row.meeting_id);
46
+ people.set(meetingId, [
47
+ ...(people.get(meetingId) ?? []),
48
+ {
49
+ identityId: Number(row.identity_id),
50
+ identityKey: String(row.identity_key),
51
+ role: str(row.role),
52
+ name: str(row.name),
53
+ externalId: str(row.external_id),
54
+ },
55
+ ]);
56
+ }
57
+ return meetings.map((row) => ({
58
+ meetingId: Number(row.id),
59
+ startedAt: int(row.started_at),
60
+ durationMs: int(row.duration_ms),
61
+ metadata: parsed(row.metadata),
62
+ participants: people.get(Number(row.id)) ?? [],
63
+ }));
64
+ });
65
+ },
66
+ });
@@ -1,4 +1,4 @@
1
- import type { Attachment, MeetingChatLinesStore, MeetingContextStore, MeetingParticipantSearchStore, MeetingPreparationContextStore, MeetingPreparationKnowledgeStore, MeetingPreparationNotesStore, MeetingRelatedHistoryStore, MeetingReviewStore, MeetingSearchIndexStore, MeetingSearchStore, MeetingSeriesHistoryStore, MeetingStatsStore, MeetingStore, MeetingTranscriptDocumentStore, MeetingTranscriptReceiptStore, MeetingTranscriptStore, NewRecord } from "../../meetings/index.js";
1
+ import type { Attachment, MeetingCallsStore, MeetingChatLinesStore, MeetingContextStore, MeetingParticipantSearchStore, MeetingPreparationContextStore, MeetingPreparationKnowledgeStore, MeetingPreparationNotesStore, MeetingRelatedHistoryStore, MeetingReviewStore, MeetingSearchIndexStore, MeetingSearchStore, MeetingSeriesHistoryStore, MeetingStatsStore, MeetingStore, MeetingTranscriptDocumentStore, MeetingTranscriptReceiptStore, MeetingTranscriptStore, NewRecord } from "../../meetings/index.js";
2
2
  import type { CacheDatabase } from "../driver.js";
3
3
  import { type MeetingLanguageStore } from "./meeting-languages.js";
4
4
  import { type MeetingContextReadCapabilities, type MeetingReadCapabilities } from "./meeting-reads.js";
@@ -12,7 +12,7 @@ export declare const saveAttachment: (database: CacheDatabase, type: string, par
12
12
  export declare const drainMeetingIndex: (database: CacheDatabase, batch?: number) => number;
13
13
  /** Each word of the query, as a prefix, all required. */
14
14
  export declare const wordsQuery: (query: string) => string | null;
15
- export type StoredMeetings = MeetingStore & MeetingPreparationContextStore & MeetingPreparationKnowledgeStore & MeetingPreparationNotesStore & MeetingRelatedHistoryStore & MeetingSeriesHistoryStore & MeetingTranscriptStore & MeetingReadCapabilities & MeetingContextReadCapabilities & MeetingParticipantSearchStore & MeetingSearchStore & MeetingTranscriptReceiptStore & MeetingContextStore & MeetingSearchIndexStore & MeetingStatsStore & MeetingReviewStore & MeetingChatLinesStore & MeetingLanguageStore & MeetingTranscriptDocumentStore;
15
+ export type StoredMeetings = MeetingStore & MeetingPreparationContextStore & MeetingPreparationKnowledgeStore & MeetingPreparationNotesStore & MeetingRelatedHistoryStore & MeetingSeriesHistoryStore & MeetingTranscriptStore & MeetingReadCapabilities & MeetingContextReadCapabilities & MeetingParticipantSearchStore & MeetingSearchStore & MeetingTranscriptReceiptStore & MeetingContextStore & MeetingSearchIndexStore & MeetingStatsStore & MeetingCallsStore & MeetingReviewStore & MeetingChatLinesStore & MeetingLanguageStore & MeetingTranscriptDocumentStore;
16
16
  /** The `MeetingStore` of `src/meetings/` over the shared store. */
17
17
  export declare const meetingStoreOver: (context: StoreContext) => StoredMeetings;
18
18
  export {};
@@ -1,4 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
+ import { timezoneOf } from "@wirecat/cli-base/query";
2
3
  import { formatMeetingReference, joinKeyOf, MeetingError } from "../../meetings/index.js";
3
4
  import { normalize } from "../normalize.js";
4
5
  import * as eventQueries from "./events.js";
@@ -6,6 +7,7 @@ import { fromJson, int, page, str, toJson } from "./events.js";
6
7
  import { folded } from "./folded.js";
7
8
  import { meetingIdentityPk } from "./identities.js";
8
9
  import { reviewLink } from "./link-reviews.js";
10
+ import { meetingCallsOver } from "./meeting-calls.js";
9
11
  import { meetingChatLinesOver } from "./meeting-chat-lines.js";
10
12
  import { meetingContextLinksOver } from "./meeting-context-links.js";
11
13
  import { attachListedDocument, attachTranscriptFile, meetingDocumentsOf, meetingTranscriptDocumentsOver, } from "./meeting-documents.js";
@@ -459,7 +461,7 @@ const filtered = (filter = {}) => {
459
461
  if (filter.query !== undefined) {
460
462
  const compiled = queryFilter(filter.query, MEETING_COLUMNS, {
461
463
  command: "meetings list",
462
- ...(filter.timezone === undefined ? {} : { zone: filter.timezone }),
464
+ zone: timezoneOf(filter.timezone),
463
465
  ...(filter.now === undefined ? {} : { now: filter.now }),
464
466
  });
465
467
  where.push(`(${compiled.sql})`);
@@ -621,6 +623,7 @@ export const meetingStoreOver = (context) => {
621
623
  ...meetingRelatedHistoryOver(context),
622
624
  ...meetingHitSearchOver(context),
623
625
  ...meetingStatsOver(context),
626
+ ...meetingCallsOver(context),
624
627
  ...meetingReviewOver(context),
625
628
  ...meetingChatLinesOver(context),
626
629
  ...meetingParticipantSearchOver(context),
@@ -1,4 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
+ import { timezoneOf } from "@wirecat/cli-base/query";
2
3
  import { findAccountPk } from "./accounts.js";
3
4
  import { candidatesOf, columnsOf, confirmMention, mentionOwner, rejectMention, } from "./mentions.js";
4
5
  import { queryFilter } from "./query-filter.js";
@@ -67,7 +68,7 @@ export const sourceMentionStoreOver = (context) => {
67
68
  const where = [scope.sql];
68
69
  let params = scope.params;
69
70
  if (query) {
70
- const compiled = queryFilter(query, columnsOf(database));
71
+ const compiled = queryFilter(query, columnsOf(database), { zone: timezoneOf() });
71
72
  if (compiled.sql) {
72
73
  where.push(`AND (${compiled.sql}) `);
73
74
  params = params.concat(compiled.params);
@@ -1,5 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
- import { defineQuery } from "@wirecat/cli-base/query";
2
+ import { defineQuery, timezoneOf } from "@wirecat/cli-base/query";
3
3
  import { MENTION_KINDS, siteOf } from "../../domain/mentions.js";
4
4
  import { findNames, nameIndex } from "../../domain/person-names.js";
5
5
  import { createStemmer } from "../../search/stem.js";
@@ -130,7 +130,7 @@ export const listMentions = (database, accountPk, query, { limit, offset, foundA
130
130
  params.push(foundAfter);
131
131
  }
132
132
  if (query) {
133
- const compiled = queryFilter(query, columnsOf(database));
133
+ const compiled = queryFilter(query, columnsOf(database), { zone: timezoneOf() });
134
134
  if (compiled.sql) {
135
135
  where.push(`(${compiled.sql})`);
136
136
  params.push(...compiled.params);
@@ -188,8 +188,13 @@ export const upsertMessage = (context, key, accountKey, chatKey, received, via,
188
188
  orm.update(messages).set({ text: message.text }).where(eq(messages.id, pk)).run();
189
189
  purgeVectorsOf(context, pk);
190
190
  }
191
+ // Saved anew for `changes`: a reader told it was deleted must hear that it is back.
191
192
  if (revived)
192
- orm.update(messages).set({ deletedAt: null, text: message.text }).where(eq(messages.id, pk)).run();
193
+ orm
194
+ .update(messages)
195
+ .set({ deletedAt: null, text: message.text, createdAt: now() })
196
+ .where(eq(messages.id, pk))
197
+ .run();
193
198
  }
194
199
  const derived = derivedReactions(context, chatKey, message.id);
195
200
  if (derived)
@@ -1,5 +1,6 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { tagOf } from "../../domain/tags.js";
3
+ import { fuseRanked } from "../../search/fusion.js";
3
4
  import { compileAutomaton, foldRegex, wildcardPattern, } from "../../search/lucene/automaton.js";
4
5
  import { isStemmed } from "../../search/lucene/resolved.js";
5
6
  import { exhausted, outOfTime, QUERY_LIMITS, searchError } from "../../search/lucene/types.js";
@@ -44,7 +45,9 @@ const CORPORA = [
44
45
  type: "document",
45
46
  noun: "note",
46
47
  fields: NOTE_FIELDS,
47
- view: `(SELECT n.id, n.account_id AS folder_id, n.external_id AS path, n.title, coalesce(n.body, '') AS text, n.metadata, ${contextDocumentTime} AS at, n.deleted_at FROM documents n)`,
48
+ get view() {
49
+ return `(SELECT n.id, n.account_id AS folder_id, n.external_id AS path, n.title, coalesce(n.body, '') AS text, n.metadata, ${contextDocumentTime()} AS at, n.deleted_at FROM documents n)`;
50
+ },
48
51
  words: "document_words",
49
52
  stems: "document_stems",
50
53
  live: "coalesce(json_extract(n.metadata, '$.catalog.active'), 1)=1",
@@ -68,21 +71,15 @@ const matchedRows = (context, query) => {
68
71
  const chosen = CORPORA.filter(({ type }) => (query.source === undefined || (query.source === "file") === (type === "document")) &&
69
72
  (!query.folderIds?.length || query.withInternal === true || type === "document"));
70
73
  const idsOf = (type) => query.refs?.flatMap((ref) => (ref.startsWith(`${type}:`) ? [Number(ref.slice(type.length + 1))] : []));
71
- const rows = chosen.flatMap((corpus) => {
74
+ const lists = chosen.map((corpus) => {
72
75
  const ids = idsOf(corpus.type);
73
76
  if (ids?.length === 0)
74
77
  return [];
75
78
  return searchCorpus(context, { ...query, ...(query.folderIds ? { accountIds: query.folderIds } : {}), ...(ids ? { ids } : {}) }, corpus);
76
79
  });
77
- const exactFirst = rows.some((row) => row.exact !== undefined);
78
- rows.sort((a, b) => query.newest
79
- ? (b.at ?? 0) - (a.at ?? 0) || a.id - b.id
80
- : (exactFirst ? Number(b.exact === true) - Number(a.exact === true) : 0) ||
81
- Number(a.relevance === null) - Number(b.relevance === null) ||
82
- (a.relevance ?? 0) - (b.relevance ?? 0) ||
83
- (b.at ?? 0) - (a.at ?? 0) ||
84
- a.id - b.id);
85
- return rows;
80
+ if (query.newest)
81
+ return lists.flat().sort((a, b) => (b.at ?? 0) - (a.at ?? 0) || a.id - b.id);
82
+ return fuseRanked(lists, (row) => ({ exact: row.exact, ranked: row.relevance !== null, at: row.at ?? 0 }));
86
83
  };
87
84
  /** Notes matching a parsed query, by the same language as messages: files and written notes, merged. */
88
85
  export const searchNotes = (context, query) => {
@@ -155,6 +155,8 @@ export interface NotesStore extends NoteSearch, ImportedDocuments, AddedSources
155
155
  note(reference: string): Promise<Note>;
156
156
  resolveNote(reference: string): Promise<Note | undefined>;
157
157
  noteReferences(reference: string): Promise<string[]>;
158
+ /** The live file note at this path of a folder or documents account, as `notes({ folderId })` lists it. */
159
+ fileNote(folderId: string, path: string): Promise<Note | undefined>;
158
160
  notes(options?: {
159
161
  folderId?: string;
160
162
  source?: Note["source"];
@@ -1,7 +1,7 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { MAX_TEXT_CHARS } from "../../attachments/limits.js";
3
3
  import { googleDocumentLinks } from "../../domain/google-documents.js";
4
- import { ADDED_PROVIDER, DOCUMENT_ACCOUNT_PROVIDERS, filesAccountSql, folderProviderOf, folderProviderSql, isDocumentAccountProvider, notAdded, } from "../../domain/providers.js";
4
+ import { ADDED_PROVIDER, documentAccountProviders, filesAccountSql, folderProviderOf, folderProviderSql, isDocumentAccountProvider, notAdded, } from "../../domain/providers.js";
5
5
  import { parseReference } from "../../domain/references.js";
6
6
  import { isRelationKind } from "../../domain/relations.js";
7
7
  import { normalizeTag } from "../../domain/tags.js";
@@ -11,6 +11,7 @@ import { ulid } from "../ulid.js";
11
11
  import { ownerPerson } from "./actors.js";
12
12
  import { encodeDocumentMetadata, languageOf } from "./document-metadata.js";
13
13
  import { deleteDocumentRow, forgetEvidenceToRow } from "./evidence-signature.js";
14
+ import { fileNoteRow } from "./file-note.js";
14
15
  import { PREFERRED_FILE, syncFile } from "./files.js";
15
16
  import { importedDocumentWhere } from "./imported-documents.js";
16
17
  import { LINK_KINDS, LINK_ORIGINS, linkKind, RELATION_KINDS } from "./link-kinds.js";
@@ -24,6 +25,7 @@ import { addTags, ensureTag, labelsOf } from "./tags.js";
24
25
  import { oneOf, textOf } from "./text-input.js";
25
26
  import { thingOf } from "./things.js";
26
27
  import { write } from "./transaction.js";
28
+ import { trigramPart } from "./trigram-match.js";
27
29
  export const NOTE_FORMATS = ["obsidian", "markdown"];
28
30
  export { LINK_ORIGINS } from "./link-kinds.js";
29
31
  const RELATIONSHIPS = RELATION_KINDS.map(linkKind).join(", ");
@@ -95,7 +97,7 @@ const personsNamed = (database, key) => {
95
97
  const rows = database
96
98
  .prepare("SELECT i.name, i.username, il.person_id FROM identities_fts f JOIN identities i ON i.id = f.rowid " +
97
99
  "JOIN identity_links il ON il.identity_id = i.id WHERE identities_fts MATCH ?")
98
- .all(`"${key.replaceAll('"', '""')}"`);
100
+ .all(trigramPart(key));
99
101
  for (const row of rows) {
100
102
  const names = [row.name, row.username].filter((one) => one != null).map((one) => targetKey(String(one)));
101
103
  if (names.includes(key))
@@ -278,13 +280,14 @@ export const notesStoreOver = (context) => {
278
280
  const isLocal = (accountId) => database
279
281
  .prepare(`SELECT 1 FROM accounts WHERE id = ? AND provider IN ('local', 'obsidian')`)
280
282
  .get(Number(accountId)) !== undefined;
281
- /** Drive's documents are found by its folder and `<id>.md`, whichever account that folder is now. */
282
- const remoteDocument = (row) => {
283
- const front = frontMatterObject(row.front_matter);
284
- return front?.source === "google-drive" || frontMatterObject(row.metadata)?.catalog !== undefined;
285
- };
286
- /** Drive's own saves keep their documents by folder and `<id>.md`; only files on disk join by content. */
287
- const localSave = (folder, frontMatter) => isLocal(folder) && frontMatter?.source !== "google-drive";
283
+ /**
284
+ * A documents provider's documents (their front matter's `source` names it) are found by their account and
285
+ * `<id>.md`, whichever account holds them now.
286
+ */
287
+ const remoteDocument = (row) => isDocumentAccountProvider(frontMatterObject(row.front_matter)?.source) ||
288
+ frontMatterObject(row.metadata)?.catalog !== undefined;
289
+ /** A documents provider's own saves keep their documents by account and `<id>.md`; only files on disk join by content. */
290
+ const localSave = (folder, frontMatter) => isLocal(folder) && !isDocumentAccountProvider(frontMatter?.source);
288
291
  /**
289
292
  * The documents whose shown file has this content: live ones, else gone ones no file holds any more, so a file
290
293
  * moved to another folder is the same document whichever folder syncs first. Empty text matches nothing.
@@ -362,10 +365,13 @@ export const notesStoreOver = (context) => {
362
365
  .run(provider, textOf(account, "an account's id", 200), JSON.stringify({ format: "markdown" }), at, at);
363
366
  return folderOf(find());
364
367
  },
365
- documentsAccounts: async () => database
366
- .prepare(`SELECT * FROM accounts WHERE provider IN (${DOCUMENT_ACCOUNT_PROVIDERS.map(() => "?").join(", ")}) ORDER BY provider, external_id`)
367
- .all(...DOCUMENT_ACCOUNT_PROVIDERS)
368
- .map(folderOf),
368
+ documentsAccounts: async () => {
369
+ const providers = documentAccountProviders();
370
+ return database
371
+ .prepare(`SELECT * FROM accounts WHERE provider IN (${providers.map(() => "?").join(", ") || "NULL"}) ORDER BY provider, external_id`)
372
+ .all(...providers)
373
+ .map(folderOf);
374
+ },
369
375
  saveFileNote: async (input) => write(database, () => {
370
376
  const folder = Number(folderRow(input.folderId, true).id);
371
377
  const path = textOf(input.path, "a note's path", 4096);
@@ -536,6 +542,11 @@ export const notesStoreOver = (context) => {
536
542
  return parsed.type === "note" || parsed.type === "document" ? noteRowOf(database, reference) : undefined;
537
543
  },
538
544
  noteReferences: async (reference) => [anyNote(reference).ref],
545
+ fileNote: async (folderId, path) => {
546
+ const folder = Number(folderRow(folderId).id);
547
+ const row = fileNoteRow(database, folder, isLocal(folder), path);
548
+ return row ? documentOf(row) : undefined;
549
+ },
539
550
  notes: async (options = {}) => {
540
551
  const { limit, offset } = bounded(options.limit, options.offset);
541
552
  if (options.source !== undefined)
@@ -1,5 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
- import { evaluate, walkQuery } from "@wirecat/cli-base/query";
2
+ import { evaluate, timezoneOf, walkQuery } from "@wirecat/cli-base/query";
3
3
  import { ORGANIZATIONS_QUERY } from "../knowledge-query.js";
4
4
  import { categorySql } from "./organization-categories.js";
5
5
  import { queryFilter } from "./query-filter.js";
@@ -31,7 +31,7 @@ export const organizationsStoreOver = ({ database, now }) => ({
31
31
  kind: { type: "enum", sql: "kind" },
32
32
  scope: { type: "enum", sql: "scope" },
33
33
  created_at: { type: "time", sql: "created_at" },
34
- });
34
+ }, { zone: timezoneOf() });
35
35
  return database
36
36
  .prepare(`SELECT * FROM organizations o WHERE deleted_at IS NULL${where ? ` AND (${where.sql})` : ""}${inCategory} ` +
37
37
  "ORDER BY name, id LIMIT 500")
@@ -10,9 +10,9 @@ import { ALWAYS_SHOWN, shownReasons } from "./person-ties.js";
10
10
  import { mergedAssignees } from "./task-board.js";
11
11
  import { hiddenTestPeople } from "./test-people.js";
12
12
  import { read, writeBatch } from "./transaction.js";
13
+ import { trigramPart } from "./trigram-match.js";
13
14
  export const PEOPLE_SORTS = ["interactions", "recent", "name", "tasks"];
14
15
  const MIN_QUERY = 3;
15
- const ftsPhrase = (text) => `"${text.replaceAll('"', '""')}"`;
16
16
  const matching = (query) => {
17
17
  if (query === undefined)
18
18
  return { sql: "", params: [] };
@@ -27,7 +27,7 @@ const matching = (query) => {
27
27
  "(SELECT rowid FROM identities_fts WHERE identities_fts MATCH ?)) OR " +
28
28
  forms.map(() => "p.name LIKE ? ESCAPE '\\'").join(" OR ") +
29
29
  ")",
30
- params: [forms.map(ftsPhrase).join(" OR "), ...forms.map(like)],
30
+ params: [forms.map(trigramPart).join(" OR "), ...forms.map(like)],
31
31
  };
32
32
  };
33
33
  const TASK_COUNTS = "WITH merged AS (SELECT json_extract(value, '$[0]') AS id, json_extract(value, '$[1]') AS now FROM json_each(?)) " +
@@ -440,7 +440,7 @@ export const similarPeople = (database, typed, limit) => {
440
440
  ? database
441
441
  .prepare("SELECT l.person_id AS person, i.name, i.username FROM identities_fts f JOIN identities i ON i.id = f.rowid " +
442
442
  "JOIN identity_links l ON l.identity_id = i.id WHERE identities_fts MATCH ?")
443
- .all(spellings(longest).map(ftsPhrase).join(" OR "))
443
+ .all(spellings(longest).map(trigramPart).join(" OR "))
444
444
  : database
445
445
  .prepare("SELECT l.person_id AS person, i.name, i.username FROM identities i " +
446
446
  "JOIN identity_links l ON l.identity_id = i.id WHERE i.name_folded LIKE ? ESCAPE '\\'")
@@ -21,8 +21,8 @@ export type ColumnMap = Readonly<Record<string, {
21
21
  where: (node: Predicate) => Where;
22
22
  }>>;
23
23
  export interface FilterOptions extends QueryContext {
24
- /** Where `today` and a bare date start; the machine's zone when absent, as search reads them. */
25
- zone?: string;
24
+ /** Where `today`, a bare date and a time without an offset are read: the zone the answer reports. Never a default. */
25
+ zone: string;
26
26
  now?: number;
27
27
  }
28
28
  /** A folded text column read by its words: each word of a term, or a whole phrase, is found inside it; a pattern matches it whole. */
@@ -34,6 +34,6 @@ export declare const foldedWords: (column: string) => {
34
34
  * and ref compare without case (a `folded` column for names in any script), a lone NOT means everything else, and a
35
35
  * `should` clause counts only when nothing is required.
36
36
  */
37
- export declare const queryFilter: (ast: QueryAst, columns: ColumnMap, options?: FilterOptions) => Where;
37
+ export declare const queryFilter: (ast: QueryAst, columns: ColumnMap, options: FilterOptions) => Where;
38
38
  /** The SQL a list query compiled to, with its values bound, for a Drizzle `where`. */
39
39
  export declare const bound: ({ sql: text, params }: Where) => SQL;
@@ -1,4 +1,4 @@
1
- import { dateRange, queryError, timezoneOf, } from "@wirecat/cli-base/query";
1
+ import { dateRange, queryError, } from "@wirecat/cli-base/query";
2
2
  import { fold } from "../normalize.js";
3
3
  import { sql } from "./drizzle/core.js";
4
4
  /** A wildcard term as a GLOB pattern: `\x` is a literal x, and a literal `*`, `?` or `[` is bracketed. */
@@ -53,7 +53,7 @@ const leaf = (node, columns, options) => {
53
53
  const range = node.operator === "range"
54
54
  ? [node.value, node.upper ?? "*", node.lower_inclusive ?? true, node.upper_inclusive ?? true]
55
55
  : [node.value, node.value, true, true];
56
- const { lower, upper, lower_inclusive, upper_inclusive } = dateRange(range[0], range[1], range[2], range[3], timezoneOf(options.zone), node.span, options.now);
56
+ const { lower, upper, lower_inclusive, upper_inclusive } = dateRange(range[0], range[1], range[2], range[3], options.zone, node.span, options.now);
57
57
  return all([
58
58
  { sql: `${sql} IS NOT NULL`, params: [] },
59
59
  ...(lower === undefined ? [] : [{ sql: `${sql} ${lower_inclusive ? ">=" : ">"} ?`, params: [lower] }]),
@@ -97,6 +97,6 @@ const compile = (node, columns, options) => {
97
97
  * and ref compare without case (a `folded` column for names in any script), a lone NOT means everything else, and a
98
98
  * `should` clause counts only when nothing is required.
99
99
  */
100
- export const queryFilter = (ast, columns, options = {}) => compile(ast.root, columns, options);
100
+ export const queryFilter = (ast, columns, options) => compile(ast.root, columns, options);
101
101
  /** The SQL a list query compiled to, with its values bound, for a Drizzle `where`. */
102
102
  export const bound = ({ sql: text, params }) => sql.join(text.split("?").map((part, at) => (at < params.length ? sql `${sql.raw(part)}${params[at]}` : sql.raw(part))), sql ``);
@@ -884,10 +884,10 @@ export declare const before: (sentAt: number, pk: number) => SQL<unknown>;
884
884
  export declare const toMessages: ({ orm }: StoreContext, rows: MessageRow[]) => Message[];
885
885
  export declare const countMessages: ({ orm }: StoreContext, chatKey: number, since: string | undefined, until?: string) => number;
886
886
  /**
887
- * What changed in a chat after `at`, a time on this machine's clock: messages first saved or edited
888
- * since, oldest first, and the ids deleted since. Send time cannot answer it — an edit made today to
889
- * a message from last year was sent last year. A change to reactions alone leaves no time, so it is
890
- * not here.
887
+ * What changed in a chat after `at`, a time on this machine's clock: messages first saved, brought back
888
+ * after a deletion or edited since, oldest first, and the ids deleted since. Send time cannot answer it —
889
+ * an edit made today to a message from last year was sent last year. A change to reactions alone leaves
890
+ * no time, so it is not here.
891
891
  */
892
892
  export declare const changesSince: (context: StoreContext, chatKey: number, at: number) => {
893
893
  messages: Message[];
@@ -57,10 +57,10 @@ export const countMessages = ({ orm }, chatKey, since, until) => Number(orm
57
57
  .where(live(chatKey, since === undefined ? undefined : gte(messages.sentAt, toMs(since)), until === undefined ? undefined : lte(messages.sentAt, toMs(until))))
58
58
  .get()?.n);
59
59
  /**
60
- * What changed in a chat after `at`, a time on this machine's clock: messages first saved or edited
61
- * since, oldest first, and the ids deleted since. Send time cannot answer it — an edit made today to
62
- * a message from last year was sent last year. A change to reactions alone leaves no time, so it is
63
- * not here.
60
+ * What changed in a chat after `at`, a time on this machine's clock: messages first saved, brought back
61
+ * after a deletion or edited since, oldest first, and the ids deleted since. Send time cannot answer it —
62
+ * an edit made today to a message from last year was sent last year. A change to reactions alone leaves
63
+ * no time, so it is not here.
64
64
  */
65
65
  export const changesSince = (context, chatKey, at) => {
66
66
  const edited = context.orm
@@ -4,18 +4,24 @@ import { exhausted, QUERY_LIMITS } from "../../search/lucene/types.js";
4
4
  import { alias, and, desc, eq, inArray, isNull, lte, sql } from "./drizzle/core.js";
5
5
  import { MESSAGE_FIELDS, newestFirst, toMessages } from "./reads.js";
6
6
  import { accounts, chats, identities, messages } from "./schema.js";
7
+ import { anyCaseGlob, trigramPart } from "./trigram-match.js";
7
8
  const HIT_FIELDS = {
8
9
  ...MESSAGE_FIELDS,
9
10
  chatTitle: sql `${chats.title}`.as("chat_title"),
10
11
  provider: sql `${accounts.provider}`.as("provider"),
11
12
  accountNativeId: sql `${accounts.externalId}`.as("account_native_id"),
12
13
  };
13
- /** Every word of three characters or more, found anywhere inside the text; a trigram index cannot match a shorter one. */
14
+ /**
15
+ * Every word of three characters or more through the trigram index, found anywhere inside the text; a shorter word,
16
+ * which a trigram cannot match, is checked on those messages' text.
17
+ */
14
18
  const wordsOf = (text) => {
15
- const words = (text.match(/[\p{L}\p{N}]+/gu) ?? []).filter((word) => [...word].length >= 3);
16
- if (words.length === 0)
19
+ const words = text.match(/[\p{L}\p{N}]+/gu) ?? [];
20
+ const long = words.filter((word) => [...word].length >= 3);
21
+ if (long.length === 0)
17
22
  throw new CliError("validation_error", "search needs a word of three letters or more");
18
- return words.map((word) => `"${word}"`).join(" ");
23
+ const short = words.filter((word) => [...word].length < 3);
24
+ return and(sql `${messages.id} IN (SELECT rowid FROM messages_fts WHERE messages_fts MATCH ${long.map(trigramPart).join(" AND ")})`, ...short.map((word) => sql `${messages.text} GLOB ${anyCaseGlob(word)}`));
19
25
  };
20
26
  /** What `find` keeps, as one condition. */
21
27
  export const matching = (context, { provider, account, accounts: within, senders, together = false, text, chatId }) => {
@@ -33,9 +39,7 @@ export const matching = (context, { provider, account, accounts: within, senders
33
39
  throw new CliError("validation_error", "a read across accounts names their provider");
34
40
  }
35
41
  const ids = senders?.length ? [...new Set(senders)] : undefined;
36
- return and(isNull(messages.deletedAt), trimmed
37
- ? sql `${messages.id} IN (SELECT rowid FROM messages_fts WHERE messages_fts MATCH ${wordsOf(trimmed)})`
38
- : undefined, scopeProvider === undefined ? undefined : eq(accounts.provider, scopeProvider), account ? eq(accounts.externalId, account.account) : undefined, within ? inArray(accounts.externalId, within) : undefined, chatId === undefined ? eq(chats.searchable, 1) : eq(chats.externalId, chatId), ids ? and(eq(identities.provider, accounts.provider), inArray(identities.externalId, ids)) : undefined, ids && together ? inArray(messages.chatId, everyoneWrote(context, ids, scopeProvider)) : undefined);
42
+ return and(isNull(messages.deletedAt), trimmed ? wordsOf(trimmed) : undefined, scopeProvider === undefined ? undefined : eq(accounts.provider, scopeProvider), account ? eq(accounts.externalId, account.account) : undefined, within ? inArray(accounts.externalId, within) : undefined, chatId === undefined ? eq(chats.searchable, 1) : eq(chats.externalId, chatId), ids ? and(eq(identities.provider, accounts.provider), inArray(identities.externalId, ids)) : undefined, ids && together ? inArray(messages.chatId, everyoneWrote(context, ids, scopeProvider)) : undefined);
39
43
  };
40
44
  /** The chats where every one of `ids` has a message — the outer row's provider when no scope names one. */
41
45
  const everyoneWrote = ({ orm }, ids, scopeProvider) => {
@@ -1,4 +1,4 @@
1
- import { purgeAccount } from "./accounts.js";
1
+ import { purgeAccount } from "./account-purge.js";
2
2
  import { write } from "./transaction.js";
3
3
  /** Set by store version 48 and deleted once the purge ran. */
4
4
  export const TEST_ACCOUNTS_TO_PURGE = "test_accounts_to_purge";