@wirecat/cli-core 0.686.0 → 0.688.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 (97) hide show
  1. package/CHANGELOG.md +114 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/cli/account-remove.js +21 -3
  4. package/dist/cli/documents/testing/source-contract.js +18 -9
  5. package/dist/cli/documents/words.d.ts +1 -1
  6. package/dist/cli/envelope.js +2 -3
  7. package/dist/cli/meeting-batch.js +5 -1
  8. package/dist/cli/meeting-passage-text.d.ts +1 -1
  9. package/dist/cli/meeting-passage-text.js +3 -5
  10. package/dist/cli/messenger/conversations-command.js +4 -0
  11. package/dist/cli/messenger/messages-search-command.js +6 -1
  12. package/dist/cli/messenger/search-answers.js +2 -0
  13. package/dist/cli/messenger/store-maintenance-command.js +3 -2
  14. package/dist/cli/search-left-out.d.ts +3 -0
  15. package/dist/cli/search-left-out.js +12 -0
  16. package/dist/cli/store-settings.js +23 -4
  17. package/dist/cli/untrusted-marks.d.ts +2 -0
  18. package/dist/cli/untrusted-marks.js +6 -0
  19. package/dist/crm/cli/files.d.ts +68 -0
  20. package/dist/crm/cli/files.js +616 -0
  21. package/dist/crm/cli/index.d.ts +1 -0
  22. package/dist/crm/cli/index.js +3 -0
  23. package/dist/crm/cli/search-all.js +3 -2
  24. package/dist/crm/file-fetch.d.ts +15 -0
  25. package/dist/crm/file-fetch.js +61 -0
  26. package/dist/crm/files.d.ts +16 -0
  27. package/dist/crm/files.js +56 -0
  28. package/dist/crm/foreign-contacts.d.ts +16 -4
  29. package/dist/crm/foreign-contacts.js +8 -4
  30. package/dist/crm/index.d.ts +3 -1
  31. package/dist/crm/index.js +3 -0
  32. package/dist/crm/source.d.ts +37 -0
  33. package/dist/crm/source.js +2 -1
  34. package/dist/crm/testing/files-contract.d.ts +17 -0
  35. package/dist/crm/testing/files-contract.js +142 -0
  36. package/dist/crm/testing/index.d.ts +2 -1
  37. package/dist/crm/testing/index.js +2 -1
  38. package/dist/crm/testing/source.d.ts +36 -1
  39. package/dist/crm/testing/source.js +55 -1
  40. package/dist/crm/values.d.ts +2 -1
  41. package/dist/crm/values.js +4 -2
  42. package/dist/entities/hit.d.ts +3 -3
  43. package/dist/entities/hit.js +14 -3
  44. package/dist/entities/index.d.ts +1 -1
  45. package/dist/errors/reasons.js +12 -1
  46. package/dist/files/safe-name.d.ts +2 -1
  47. package/dist/files/safe-name.js +21 -3
  48. package/dist/meetings/cli/index.d.ts +1 -1
  49. package/dist/meetings/cli/index.js +10 -6
  50. package/dist/meetings/mcp/index.d.ts +15 -15
  51. package/dist/meetings/mcp/passage.d.ts +6 -2
  52. package/dist/meetings/mcp/passage.js +7 -3
  53. package/dist/meetings/read-through.d.ts +2 -0
  54. package/dist/meetings/read-through.js +7 -2
  55. package/dist/meetings/source.d.ts +2 -2
  56. package/dist/oauth/storage.js +21 -4
  57. package/dist/search/lucene/resolved.d.ts +2 -0
  58. package/dist/search/respell.d.ts +10 -0
  59. package/dist/search/respell.js +63 -0
  60. package/dist/search/stem.d.ts +16 -3
  61. package/dist/search/stem.js +32 -4
  62. package/dist/services/documents/plan.js +26 -5
  63. package/dist/services/documents/sync.js +4 -1
  64. package/dist/services/embeddings-search.js +190 -140
  65. package/dist/services/embeddings.d.ts +8 -0
  66. package/dist/services/messages-archive-search.js +55 -3
  67. package/dist/services/messages-search.d.ts +2 -1
  68. package/dist/services/messages-search.js +19 -7
  69. package/dist/services/messages.d.ts +8 -0
  70. package/dist/services/metadata.d.ts +1 -1
  71. package/dist/services/named-chat.d.ts +20 -0
  72. package/dist/services/named-chat.js +63 -0
  73. package/dist/services/search-all.d.ts +7 -2
  74. package/dist/services/search-all.js +35 -1
  75. package/dist/store/accounts.d.ts +2 -1
  76. package/dist/store/exports.d.ts +2 -1
  77. package/dist/store/exports.js +2 -1
  78. package/dist/store/recover.js +2 -0
  79. package/dist/store/search-index.d.ts +2 -0
  80. package/dist/store/search-index.js +1 -0
  81. package/dist/store/sqlite/account-purge.js +1 -0
  82. package/dist/store/sqlite/crm-files.d.ts +70 -0
  83. package/dist/store/sqlite/crm-files.js +174 -0
  84. package/dist/store/sqlite/crm-settings.d.ts +42 -1
  85. package/dist/store/sqlite/crm-settings.js +46 -2
  86. package/dist/store/sqlite/lucene-fields.d.ts +2 -0
  87. package/dist/store/sqlite/lucene-fields.js +6 -2
  88. package/dist/store/sqlite/lucene.js +13 -7
  89. package/dist/store/sqlite/manifest.js +2 -0
  90. package/dist/store/sqlite/migrations.generated.js +17 -0
  91. package/dist/store/sqlite/schema.d.ts +329 -0
  92. package/dist/store/sqlite/schema.js +28 -0
  93. package/dist/store/sqlite/stems.d.ts +2 -0
  94. package/dist/store/sqlite/stems.js +5 -0
  95. package/dist/store/store.d.ts +3 -0
  96. package/dist/store/store.js +5 -0
  97. package/package.json +2 -2
@@ -2,9 +2,11 @@ import { CliError } from "@wirecat/cli-base";
2
2
  import { parseLocator } from "../domain/locator.js";
3
3
  import { plainQuery } from "../search/lucene/plain.js";
4
4
  import { isQueryLimit } from "../search/lucene/types.js";
5
+ import { respelled } from "../search/respell.js";
5
6
  import { TOTAL_CAP, totalOf } from "../search/total.js";
6
7
  import { discoveryRequest, searchDiscovery } from "./messages-discovery.js";
7
8
  import { countLucene, searchLucene, statsLucene } from "./messages-search.js";
9
+ import { namedChat, queryWords, without } from "./named-chat.js";
8
10
  import { readThreadContext, threadBounds } from "./thread-context.js";
9
11
  /** How long a search may spend building the word index, then the stems, first (phase 2 plan S3: about 200 ms). */
10
12
  export const SEARCH_FILL_MS = 200;
@@ -47,12 +49,30 @@ export const MAX_SEARCH_OFFSET = 1000;
47
49
  * the next page starts. A page is the hits up to `offset + limit` read again and cut, so deep pages cost more.
48
50
  */
49
51
  export const searchStore = async (store, account, request, messenger = {}, meaning, rerank) => {
50
- if (request.text !== undefined)
51
- request = { ...request, text: plainQuery(request.text) };
52
52
  const offset = request.offset ?? 0;
53
53
  if (!Number.isInteger(offset) || offset < 0 || offset > MAX_SEARCH_OFFSET)
54
54
  throw new CliError("validation_error", `offset takes a whole number from 0 to ${MAX_SEARCH_OFFSET}`);
55
- const found = await searchPage(store, account, { ...request, limit: request.limit + offset }, messenger, meaning, rerank);
55
+ const typed = request.text;
56
+ const helped = await helpPlainWords(store, account, request, messenger);
57
+ if (helped.text !== undefined)
58
+ request = { ...request, text: plainQuery(helped.text) };
59
+ const page = (asked) => searchPage(store, account, { ...asked, limit: asked.limit + offset }, messenger, meaning, rerank);
60
+ const all = await page(request);
61
+ const { named } = helped;
62
+ const inside = named && typed !== undefined
63
+ ? await page({
64
+ ...request,
65
+ text: plainQuery(without(helped.text ?? typed, named.word) || typed),
66
+ chat: named.chatId,
67
+ })
68
+ : undefined;
69
+ const shown = new Set(inside?.items.map(({ locator }) => locator));
70
+ const found = inside
71
+ ? {
72
+ ...all,
73
+ items: [...inside.items, ...all.items.filter(({ locator }) => !shown.has(locator))].slice(0, request.limit + offset),
74
+ }
75
+ : all;
56
76
  const discovery = found.query?.discovery;
57
77
  const total = discovery
58
78
  ? totalOf(discovery.candidates, found.items.length, found.hasMore, !discovery.truncated)
@@ -63,11 +83,43 @@ export const searchStore = async (store, account, request, messenger = {}, meani
63
83
  }), found.items.length, found.hasMore);
64
84
  return {
65
85
  ...found,
86
+ ...(named ? { named: { word: named.word, chatId: named.chatId, title: named.title } } : {}),
87
+ ...(helped.respelled.size ? { respelled: Object.fromEntries(helped.respelled) } : {}),
66
88
  total,
67
89
  items: found.items.slice(offset),
68
90
  ...(found.hasMore && offset + request.limit <= MAX_SEARCH_OFFSET ? { nextOffset: offset + request.limit } : {}),
69
91
  };
70
92
  };
93
+ // Plain words only: a query with fields, quotes, groups or operators says exactly what it wants.
94
+ const PLAIN = /^[\p{L}\p{N}\s,.?!]+$/u;
95
+ const OPERATORS = /(?<![\p{L}\p{N}])(?:AND|OR|NOT)(?![\p{L}\p{N}])/u;
96
+ /**
97
+ * For a query of plain words over every chat: each word no message holds also searched as the words it may stand for
98
+ * (`respelled`), and the private chat a word names (`namedChat`), searched first.
99
+ */
100
+ const helpPlainWords = async (store, account, request, messenger) => {
101
+ const none = { text: request.text, respelled: new Map(), named: undefined };
102
+ const { text } = request;
103
+ if (text === undefined || request.exact || request.discover || request.kind === "mail" || request.only)
104
+ return none;
105
+ const chat = /(?<!\S)chat:\S+/gu;
106
+ const bare = text.replace(chat, " ");
107
+ if (!PLAIN.test(bare) || OPERATORS.test(bare))
108
+ return none;
109
+ const words = queryWords(bare);
110
+ const respellings = await respelled(store.searchIndex, words);
111
+ let helped = text;
112
+ for (const [word, forms] of respellings)
113
+ helped = helped.replace(new RegExp(`(?<![\\p{L}\\p{N}])${word}(?![\\p{L}\\p{N}])`, "giu"), `(${[word, ...forms].join(" OR ")})`);
114
+ const named = request.chat === undefined && bare === text
115
+ ? await namedChat(store, account, messenger, request.accounts, words).catch((error) => {
116
+ if (isQueryLimit(error))
117
+ return undefined;
118
+ throw error;
119
+ })
120
+ : undefined;
121
+ return { text: helped, respelled: respellings, named };
122
+ };
71
123
  const searchPage = async (store, account, request, messenger, meaning, rerank) => {
72
124
  if (request.signal?.aborted)
73
125
  throw new CliError("validation_error", "search was aborted", { reason: "query.aborted", complete: false });
@@ -4,6 +4,7 @@ import { type QueryExecution } from "../search/lucene/resolved.js";
4
4
  import { type Stemmer } from "../search/stem.js";
5
5
  import { type AccountKey, type ChatCompleteness, type MessageStore } from "../store/store.js";
6
6
  import type { SearchFound, SearchQuery } from "./messages.js";
7
+ import { type QueryNode } from "@wirecat/cli-base/query";
7
8
  import type { SearchRefreshed } from "./search-refresh.js";
8
9
  export interface QueryMetadata {
9
10
  language: "lucene-v1";
@@ -110,7 +111,7 @@ export declare const prepareLucene: (store: MessageStore, account: AccountKey, r
110
111
  * tool, none: a half-built stem index would silently drop matches, while the word index answers each
111
112
  * word's own form. Stems waiting for the owner's `store rebuild` still refuse.
112
113
  */
113
- export declare const searchStemming: (store: MessageStore, command?: string) => Promise<{
114
+ export declare const searchStemming: (store: MessageStore, command?: string, root?: QueryNode) => Promise<{
114
115
  stemmer?: Stemmer;
115
116
  unstemmed?: QueryStemming;
116
117
  }>;
@@ -7,7 +7,8 @@ import { PRESET_VERSION } from "../search/lucene/presets.js";
7
7
  import { FIELD_VERSION, isPresence, validateAst, validateFields } from "../search/lucene/registry.js";
8
8
  import { hasStems, hasText, isStemmed, } from "../search/lucene/resolved.js";
9
9
  import { inSource, sourceOf } from "../search/query.js";
10
- import { createStemmer, DEFAULT_STEMMERS } from "../search/stem.js";
10
+ import { createStemmer, cutsDeep, DEFAULT_STEMMERS } from "../search/stem.js";
11
+ import { normalize } from "../store/normalize.js";
11
12
  import { CHAT_LIST_KEY, } from "../store/store.js";
12
13
  import { withExcerpt } from "./excerpt.js";
13
14
  import { mailAround, mergeMail, withMailThreads } from "./mail-search.js";
@@ -139,7 +140,7 @@ export const prepareLucene = async (store, account, request, messenger) => {
139
140
  await indexNotReady(store, messenger.app?.command);
140
141
  const stems = await store.searchIndex.stemsState();
141
142
  const stemsReady = stems?.ready === true;
142
- const { stemmer, unstemmed } = hasStems(ast.root) ? await searchStemming(store, messenger.app?.command) : {};
143
+ const { stemmer, unstemmed } = hasStems(ast.root) ? await searchStemming(store, messenger.app?.command, root) : {};
143
144
  const execution = {
144
145
  root,
145
146
  accounts: scopeAccounts,
@@ -169,11 +170,22 @@ export const prepareLucene = async (store, account, request, messenger) => {
169
170
  * tool, none: a half-built stem index would silently drop matches, while the word index answers each
170
171
  * word's own form. Stems waiting for the owner's `store rebuild` still refuse.
171
172
  */
172
- export const searchStemming = async (store, command) => {
173
+ export const searchStemming = async (store, command, root) => {
173
174
  const stems = await store.searchIndex.stemsState();
174
175
  // Ready means the setting is one this build knows, so `null` cannot reach here.
175
- if (stems?.ready)
176
- return { stemmer: createStemmer((await store.searchIndex.stemmers()) ?? DEFAULT_STEMMERS) };
176
+ if (stems?.ready) {
177
+ const choices = (await store.searchIndex.stemmers()) ?? DEFAULT_STEMMERS;
178
+ const stemmer = createStemmer(choices);
179
+ const deep = root
180
+ ? walkQuery(root)
181
+ .filter(isStemmed)
182
+ .flatMap(({ value }) => normalize(value).match(/[\p{L}\p{N}]+/gu) ?? [])
183
+ .filter((word) => cutsDeep(stemmer, word))
184
+ : [];
185
+ if (!deep.length)
186
+ return { stemmer };
187
+ return { stemmer: createStemmer(choices, { whole: await store.searchIndex.heldStems(deep) }) };
188
+ }
177
189
  if (stems?.cause !== "building" && stems?.cause !== "stemmer_unknown")
178
190
  return stemsNotReady(stems, command);
179
191
  return {
@@ -190,7 +202,7 @@ export const searchStemming = async (store, command) => {
190
202
  export const stemExecution = async (execution, store) => {
191
203
  if (!hasStems(execution.root))
192
204
  return;
193
- const { stemmer, unstemmed } = await searchStemming(store);
205
+ const { stemmer, unstemmed } = await searchStemming(store, undefined, execution.root);
194
206
  if (stemmer)
195
207
  execution.stemmer = stemmer;
196
208
  if (unstemmed)
@@ -201,7 +213,7 @@ const stemmingOf = (root, stemmer) => ({
201
213
  analyzer: stemmer.identity,
202
214
  terms: walkQuery(root)
203
215
  .filter(isStemmed)
204
- .flatMap(({ value }) => stemmer.explain(value)),
216
+ .flatMap(({ value }) => stemmer.explain(value, { query: true })),
205
217
  });
206
218
  const stemsNotReady = (state, command) => {
207
219
  const cli = command ? `${command} ` : "";
@@ -108,6 +108,14 @@ export type FoundMessage = StoredHit & {
108
108
  export interface SearchFound extends Page<FoundMessage> {
109
109
  /** Where the next page starts, as `offset`; absent on the last page. */
110
110
  nextOffset?: number;
111
+ /** The private chat a word of the query names, whose hits come first. */
112
+ named?: {
113
+ word: string;
114
+ chatId: Id;
115
+ title: string | null;
116
+ };
117
+ /** Words no message holds, each with the words searched beside it: its Latin spelling and near spellings. */
118
+ respelled?: Record<string, string[]>;
111
119
  /** How many messages match, every page together, as Elasticsearch's `hits.total`; set by the archive search. */
112
120
  total?: SearchTotal;
113
121
  refreshed?: SearchRefreshed;
@@ -14,12 +14,12 @@ export declare const metadataService: (deps: ServiceDeps) => {
14
14
  dryRun?: boolean;
15
15
  }) => Promise<{
16
16
  items: ({
17
+ error?: undefined;
17
18
  chatId: string;
18
19
  tags: import("../domain/channel-tags.js").ChannelTagMatch[];
19
20
  algorithm: string;
20
21
  fetchedAt: string | null;
21
22
  source: string;
22
- error?: undefined;
23
23
  } | {
24
24
  tags?: undefined;
25
25
  algorithm?: undefined;
@@ -0,0 +1,20 @@
1
+ import type { Id } from "../domain/models.js";
2
+ import type { AccountKey, MessageStore } from "../store/store.js";
3
+ import type { Saved } from "./message-resolution.js";
4
+ export interface NamedChat {
5
+ word: string;
6
+ source: AccountKey;
7
+ chatId: Id;
8
+ title: string | null;
9
+ }
10
+ /**
11
+ * The private chat a query names by a word the two people there write as a name («Петька, привет»), learned from the
12
+ * messages: the one private chat holding most of the word's uses, at least twice as many as any other private chat,
13
+ * where it is capitalised nearly every time. An ordinary word («счёт») is spread over many chats and written in
14
+ * lower case, so it names none.
15
+ */
16
+ export declare const namedChat: (store: MessageStore, account: AccountKey, messenger: Saved, accounts: AccountKey[] | undefined, words: string[]) => Promise<NamedChat | undefined>;
17
+ /** The query's words, lower case, without the ones nearly every message holds (unless it holds nothing else). */
18
+ export declare const queryWords: (query: string) => string[];
19
+ /** The query without one of its words, matched whole in any case. */
20
+ export declare const without: (query: string, word: string) => string;
@@ -0,0 +1,63 @@
1
+ import { createStemmer } from "../search/stem.js";
2
+ import { STOP_WORDS } from "../search/task-similarity.js";
3
+ import { normalize } from "../store/normalize.js";
4
+ import { prepareLucene } from "./messages-search.js";
5
+ /** Fewer uses than this in one private chat is no evidence of a name. */
6
+ const LEAST_USES = 3;
7
+ /** How many of a word's messages in its private chat are read to see whether it is written as a name. */
8
+ const SAMPLE = 50;
9
+ /** The share of those uses written with a capital letter that makes the word a name there. */
10
+ const CAPITALISED = 0.8;
11
+ /**
12
+ * The private chat a query names by a word the two people there write as a name («Петька, привет»), learned from the
13
+ * messages: the one private chat holding most of the word's uses, at least twice as many as any other private chat,
14
+ * where it is capitalised nearly every time. An ordinary word («счёт») is spread over many chats and written in
15
+ * lower case, so it names none.
16
+ */
17
+ export const namedChat = async (store, account, messenger, accounts, words) => {
18
+ for (const word of words) {
19
+ if (word.length < 3 || /^\p{N}+$/u.test(word))
20
+ continue;
21
+ const { execution } = await prepareLucene(store, account,
22
+ // Quoted, a word is its forms without the longer words it begins: a name, not every word starting like it.
23
+ { text: `"${word}"`, ...(accounts ? { accounts } : {}), limit: SAMPLE }, messenger);
24
+ const groups = (await store.queries.countQuery(execution, "chat")).sort((a, b) => b.count - a.count);
25
+ const dialogs = [];
26
+ for (const group of groups) {
27
+ if (dialogs.length === 2)
28
+ break;
29
+ const source = { provider: group.provider, account: group.account };
30
+ if (group.id === null || (await store.chats.chatKind(source, group.id)) !== "dialog")
31
+ continue;
32
+ dialogs.push({ word, source, chatId: group.id, title: group.name, count: group.count });
33
+ }
34
+ const [best, next] = dialogs;
35
+ if (!best || best.count < LEAST_USES || (next && next.count * 2 > best.count))
36
+ continue;
37
+ const { items } = await store.queries.matchQuery({
38
+ ...execution,
39
+ chat: { account: best.source, chatId: best.chatId },
40
+ });
41
+ const stemmer = execution.stemmer ?? createStemmer();
42
+ const stem = stemmer.stemToken(word);
43
+ const uses = items.flatMap(({ text }) => (text?.match(/[\p{L}\p{N}]+/gu) ?? []).filter((token) => stemmer.stemToken(token) === stem));
44
+ const capitalised = uses.filter((token) => token[0] !== token[0]?.toLowerCase()).length;
45
+ if (uses.length >= LEAST_USES && capitalised >= uses.length * CAPITALISED) {
46
+ const { count: _, ...named } = best;
47
+ return named;
48
+ }
49
+ }
50
+ return undefined;
51
+ };
52
+ /** The query's words, lower case, without the ones nearly every message holds (unless it holds nothing else). */
53
+ export const queryWords = (query) => {
54
+ const all = [...new Set(query.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [])];
55
+ // `что*` OR `какие*` reads most of a large store and runs out of time before the words that matter count.
56
+ const content = all.filter((word) => !STOP_WORDS.has(normalize(word)));
57
+ return content.length ? content : all;
58
+ };
59
+ /** The query without one of its words, matched whole in any case. */
60
+ export const without = (query, word) => query
61
+ .replace(new RegExp(`(?<![\\p{L}\\p{N}])${word}(?![\\p{L}\\p{N}])`, "giu"), " ")
62
+ .replace(/\s+/gu, " ")
63
+ .trim();
@@ -15,8 +15,11 @@ export type SearchedResource = (typeof RESOURCES_SEARCHED)[number];
15
15
  /** One hit of `search all`: a stored record, or a passage of a meeting. */
16
16
  export type SearchAllItem = SearchAllRecordItem | MeetingSearchItem;
17
17
  export interface SearchAllRecordItem {
18
- kind: "message" | "mail" | "note" | "document" | "event" | "deal" | "lead" | BusinessKind;
19
- /** `msg:…` for a message or a mail, `note:…`, `event:…`, `deal:…`, `lead:…`, or a business ref: `invoice:…`. */
18
+ kind: "message" | "mail" | "note" | "document" | "event" | "deal" | "lead" | "crm_file" | BusinessKind;
19
+ /**
20
+ * `msg:…` for a message or a mail, `note:…`, `event:…`, `deal:…`, `lead:…`, `crmfile:<file id>` for a downloaded CRM
21
+ * file, or a business ref: `invoice:…`.
22
+ */
20
23
  ref: string;
21
24
  provider: string;
22
25
  /** The account it was found in; a note's folder id, or `internal` for a note written in memo. */
@@ -152,6 +155,8 @@ export interface SearchAllRequest {
152
155
  crmKinds?: readonly DealKind[];
153
156
  /** The CRM accounts' copies a CRM CLI's profile may read only part of, each by its own rule (SEC-197). */
154
157
  crmViewers?: CopyViewer[];
158
+ /** `crm` also reads the text of downloaded CRM files under the same viewers; false when the profile denies it. */
159
+ crmFiles?: boolean;
155
160
  /**
156
161
  * Search harder: a hosted model reorders the first 30 hits, only with the owner's consent and a key. Absent, nothing
157
162
  * is read of the consent or the key and nothing is sent.
@@ -1,5 +1,6 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { parseLucene, timezoneOf } from "@wirecat/cli-base/query";
3
+ import { crmViewerOf } from "../crm/index.js";
3
4
  import { hitFiles } from "../domain/attachments.js";
4
5
  import { parseLocator } from "../domain/locator.js";
5
6
  import { senderIsMe } from "../domain/models.js";
@@ -106,6 +107,16 @@ const sourceScope = async (store, account, source, asked, messenger) => {
106
107
  .map((resource) => ({ resource, code: "not_found", reason: `--source names no ${resource} account` }));
107
108
  return { only, scope, skipped: [...skipped, ...unnamed] };
108
109
  };
110
+ /** Each CRM copy's viewer for the user its own sync signed in as (SEC-197): what a run outside its CLI may read. */
111
+ const copyViewers = async (store) => {
112
+ const viewers = [];
113
+ for (const account of await crmAccounts(store)) {
114
+ const { viewer } = await crmViewerOf(store, account, (await store.crm.ownUser(account)) ?? null);
115
+ if (viewer)
116
+ viewers.push(viewer);
117
+ }
118
+ return viewers;
119
+ };
109
120
  /** The accounts of every CRM the store holds copies of. */
110
121
  export const crmAccounts = async (store) => (await store.accounts.accounts()).filter(({ provider }) => holdsKind(provider, "crm"));
111
122
  /**
@@ -326,12 +337,14 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
326
337
  else if (resource === "crm") {
327
338
  const { words, anyWord } = titleWords(request.text);
328
339
  const chosen = scope?.crm;
340
+ // memo's, tg's and the MCP's search all pass no viewers: each copy's own rule decides, as a CRM CLI's does.
341
+ const viewers = request.crmViewers ?? (await copyViewers(store));
329
342
  const found = await store.deals.find({
330
343
  words,
331
344
  anyWord: anyWord || discover,
332
345
  ...(request.exact ? { exact: true } : {}),
333
346
  ...(request.crmKinds === undefined ? {} : { kinds: request.crmKinds }),
334
- ...(request.crmViewers === undefined ? {} : { viewers: request.crmViewers }),
347
+ viewers,
335
348
  limit: Math.min(depth, 500),
336
349
  ...(chosen === undefined ? {} : { accounts: chosen }),
337
350
  });
@@ -350,6 +363,27 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
350
363
  foundBy: deal.matched.includes("title") ? ["title"] : ["words"],
351
364
  ...(deal.corrections ? { match: "corrected", corrections: deal.corrections } : {}),
352
365
  })));
366
+ if (request.crmFiles !== false) {
367
+ const files = await store.crmFiles.find({
368
+ words,
369
+ anyWord: anyWord || discover,
370
+ ...(request.exact ? { exact: true } : {}),
371
+ ...(chosen === undefined ? {} : { accounts: chosen }),
372
+ viewers,
373
+ limit: Math.min(depth, 500),
374
+ });
375
+ hasMore ||= files.hasMore;
376
+ lists.push(files.items.map((hit) => ({
377
+ kind: "crm_file",
378
+ ref: `crmfile:${hit.file.externalId}`,
379
+ provider: hit.account.provider,
380
+ account: hit.account.account,
381
+ title: hit.file.name,
382
+ timestamp: new Date(hit.file.downloadedAt).toISOString(),
383
+ text: hit.excerpt,
384
+ foundBy: ["words"],
385
+ })));
386
+ }
353
387
  const read = chosen ?? [...(await crmAccounts(store)), { provider: "crm", account: INTERNAL_NOTES }];
354
388
  for (const { provider, account } of read)
355
389
  accounts.push({ resource, provider, account });
@@ -17,7 +17,8 @@ export interface AccountAccounts {
17
17
  accountName(key: AccountKey): Promise<string | null>;
18
18
  /**
19
19
  * Everything one account holds — its chats, messages, members, state, leases, transcripts and whom
20
- * it has seen — for `cache clear`. Other accounts, and identities they share, stay.
20
+ * it has seen — for `cache clear`. Other accounts, and identities they share, stay. The store never touches a file
21
+ * on disk: `account remove` deletes the downloaded CRM files `crmFiles.savedPaths` names.
21
22
  */
22
23
  purge(key: AccountKey): Promise<void>;
23
24
  }
@@ -28,7 +28,8 @@ export { CHAT_LIST_KEY, type ChatCompleteness, type ChatCoverage, fetchedKey, hi
28
28
  export { CONVERSATION_COLUMNS } from "./sqlite/conversations.js";
29
29
  export { type CopyViewer, seenBy } from "./sqlite/copy-viewer.js";
30
30
  export type { CounterTarget } from "./sqlite/counters.js";
31
- export { crmSettingsOf, parseCrmSetting, parseCrmSettingValue, saveCrmSetting } from "./sqlite/crm-settings.js";
31
+ export { type CrmFileHit, type CrmFileRow, type CrmFileSearch, type CrmFileStore, resetCrmFileWords, } from "./sqlite/crm-files.js";
32
+ export { CRM_FILE_LIMITS, type CrmFileLimit, type CrmFileLimits, crmSettingsOf, parseCrmSetting, parseCrmSettingValue, saveCrmSetting, } from "./sqlite/crm-settings.js";
32
33
  export { type EmailMarks, MAIL_AGENDA_COLUMNS, type MarkedEmail, type NewestEmail, type ThreadActivity, } from "./sqlite/email-activity.js";
33
34
  export { messageOfEmail, threadConversation } from "./sqlite/emails.js";
34
35
  export { ENRICHMENT_SUBJECTS, type EnrichmentCandidate, type EnrichmentCounts, type EnrichmentNarrowing, type EnrichmentStore, type EnrichmentSubject, type SavedEnrichment, } from "./sqlite/enrichments.js";
@@ -9,7 +9,8 @@ export { storeClients } from "./sqlite/clients.js";
9
9
  export { CHAT_LIST_KEY, fetchedKey, historyStartKey, } from "./sqlite/completeness.js";
10
10
  export { CONVERSATION_COLUMNS } from "./sqlite/conversations.js";
11
11
  export { seenBy } from "./sqlite/copy-viewer.js";
12
- export { crmSettingsOf, parseCrmSetting, parseCrmSettingValue, saveCrmSetting } from "./sqlite/crm-settings.js";
12
+ export { resetCrmFileWords, } from "./sqlite/crm-files.js";
13
+ export { CRM_FILE_LIMITS, crmSettingsOf, parseCrmSetting, parseCrmSettingValue, saveCrmSetting, } from "./sqlite/crm-settings.js";
13
14
  export { MAIL_AGENDA_COLUMNS, } from "./sqlite/email-activity.js";
14
15
  export { messageOfEmail, threadConversation } from "./sqlite/emails.js";
15
16
  export { ENRICHMENT_SUBJECTS, } from "./sqlite/enrichments.js";
@@ -11,6 +11,7 @@ import { readHealthMark, recordDeepCheck } from "./marks.js";
11
11
  import { migrate } from "./migrations.js";
12
12
  import { forgetCoverageSince, REFILL_MARGIN_MS } from "./refill.js";
13
13
  import { resetAttachmentWords } from "./sqlite/attachment-texts.js";
14
+ import { resetCrmFileWords } from "./sqlite/crm-files.js";
14
15
  import { involvementStoreOver } from "./sqlite/involvements.js";
15
16
  import { drainMeetingIndex } from "./sqlite/meetings.js";
16
17
  import { rebuildMentions } from "./sqlite/mentions.js";
@@ -381,6 +382,7 @@ const FILLERS = {
381
382
  fillStems(database, { now });
382
383
  },
383
384
  attachment_words: (database) => void resetAttachmentWords(database),
385
+ crm_file_words: (database) => void resetCrmFileWords(database),
384
386
  attachment_name_words: (database) =>
385
387
  // As migration 20 filled it: й and ё fold as the triggers fold them.
386
388
  database.exec("INSERT INTO attachment_name_words (rowid, name) SELECT id, " +
@@ -24,6 +24,8 @@ export interface SearchIndexStore {
24
24
  }): Promise<SearchIndexFill>;
25
25
  /** How far the stems are built, and by which stemmer choices; `undefined` on a file before they existed. */
26
26
  stemsState(): Promise<StemsState | undefined>;
27
+ /** Of these stems, those some message's words were stemmed to. */
28
+ heldStems(stems: string[]): Promise<Set<string>>;
27
29
  /**
28
30
  * Builds the stems towards "ready" in short batches until done or `until` says stop; never rebuilds. Then the
29
31
  * voice-note transcripts written since, which are few, so they keep up with any stemmer choice.
@@ -16,6 +16,7 @@ export const searchIndexStoreOver = (context) => {
16
16
  ? { normalized: 0, indexed: 0, terms: 0 }
17
17
  : searchIndex.fillSearchIndex(database, { now: context.now, ...(until ? { until } : {}) }),
18
18
  stemsState: async () => stems.stemsState(database),
19
+ heldStems: async (held) => stems.heldStems(database, held),
19
20
  fillStems: async ({ until } = {}) => {
20
21
  if (isQueryOnly(database))
21
22
  return { stemmed: 0, drained: 0 };
@@ -96,6 +96,7 @@ export const purgeAccount = (context, accountKey) => {
96
96
  orm.run(sql `DELETE FROM documents WHERE account_id = ${accountKey}`);
97
97
  purgeCrmCopies(database, accountKey);
98
98
  orm.run(sql `DELETE FROM crm_fields WHERE account_id = ${accountKey}`);
99
+ orm.run(sql `DELETE FROM crm_files WHERE account_id = ${accountKey}`);
99
100
  // An entity made from a record is the owner's and stays; only what the source said goes.
100
101
  const recordsOf = sql `(SELECT id FROM records WHERE account_id = ${accountKey})`;
101
102
  orm.run(sql `DELETE FROM record_relations WHERE record_id IN ${recordsOf} OR target_id IN ${recordsOf}`);
@@ -0,0 +1,70 @@
1
+ import type { CacheDatabase } from "../driver.js";
2
+ import type { AccountKey } from "../types.js";
3
+ import type { CopyViewer } from "./copy-viewer.js";
4
+ import { type CrmFileLimits } from "./crm-settings.js";
5
+ import type { StoreContext } from "./open.js";
6
+ /** A downloaded file of a CRM record as the store keeps it: never a download link. */
7
+ export interface CrmFileRow {
8
+ /** `<owner kind>:<owner id>:<source kind>:<provider id>`. */
9
+ externalId: string;
10
+ ownerKind: string;
11
+ ownerId: string;
12
+ /** The identity `<account>/user/<id>` the owner record was assigned to at download, as a deal's assignee is kept. */
13
+ ownerAssignee: string | null;
14
+ source: string;
15
+ name: string;
16
+ mime: string | null;
17
+ size: number | null;
18
+ externalCreatedAt: number | null;
19
+ /** Null once the disk cap dropped the file; its text stays. */
20
+ localPath: string | null;
21
+ contentSha256: string | null;
22
+ text: string | null;
23
+ /** The `Extraction` status reading the text ended with. */
24
+ extraction: string | null;
25
+ extractionError: string | null;
26
+ /** The CRM user id of the sign-in that downloaded it. */
27
+ downloadedBy: string | null;
28
+ downloadedAt: number;
29
+ }
30
+ export interface CrmFileHit {
31
+ account: AccountKey;
32
+ file: Omit<CrmFileRow, "text">;
33
+ /** Some text around the first word found. */
34
+ excerpt: string;
35
+ }
36
+ export interface CrmFileSearch {
37
+ words: string[];
38
+ anyWord?: boolean;
39
+ /** Whole words only, no word they begin. */
40
+ exact?: boolean;
41
+ /** Absent: every CRM account's. */
42
+ accounts?: AccountKey[];
43
+ /** Each limits its own account's rows to the files of records assigned to its user (NEED-2707 A). */
44
+ viewers?: CopyViewer[];
45
+ limit?: number;
46
+ }
47
+ export interface CrmFileStore {
48
+ /** One downloaded file, replacing an earlier download of the same id. */
49
+ save(key: AccountKey, file: CrmFileRow): Promise<void>;
50
+ get(key: AccountKey, externalId: string): Promise<CrmFileRow | undefined>;
51
+ /** The downloaded files of one record, without their text. */
52
+ ofOwner(key: AccountKey, kind: string, id: string): Promise<Omit<CrmFileRow, "text">[]>;
53
+ /** The bytes of the files saved under `folder`; a copy saved elsewhere is the owner's and not counted. */
54
+ storedBytes(key: AccountKey, folder: string): Promise<number>;
55
+ /** Files under `folder` whose text is stored, oldest download first: what the disk cap may drop. */
56
+ droppable(key: AccountKey, folder: string): Promise<Omit<CrmFileRow, "text">[]>;
57
+ /** Where the account's downloaded files were saved, for `account remove` to list and delete. */
58
+ savedPaths(key: AccountKey): Promise<string[]>;
59
+ /** The saved file is gone; the row and its text stay, so search still finds it. */
60
+ forgetFile(key: AccountKey, externalId: string): Promise<void>;
61
+ find(search: CrmFileSearch): Promise<{
62
+ items: CrmFileHit[];
63
+ hasMore: boolean;
64
+ }>;
65
+ /** The account's `files.*` settings, each its default unless the owner set one in range. */
66
+ limits(key: AccountKey): Promise<CrmFileLimits>;
67
+ }
68
+ /** `store rebuild`: the normalized copies follow the current normalizer, then the word index is filled again. */
69
+ export declare const resetCrmFileWords: (database: CacheDatabase) => number;
70
+ export declare const crmFilesOver: (context: StoreContext) => CrmFileStore;