@wirecat/cli-core 0.687.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 (67) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/cli/documents/words.d.ts +1 -1
  4. package/dist/cli/envelope.js +2 -3
  5. package/dist/cli/meeting-batch.js +5 -1
  6. package/dist/cli/meeting-passage-text.d.ts +1 -1
  7. package/dist/cli/meeting-passage-text.js +3 -5
  8. package/dist/cli/messenger/conversations-command.js +4 -0
  9. package/dist/cli/messenger/messages-search-command.js +6 -1
  10. package/dist/cli/messenger/search-answers.js +2 -0
  11. package/dist/cli/search-left-out.d.ts +3 -0
  12. package/dist/cli/search-left-out.js +12 -0
  13. package/dist/cli/store-settings.js +23 -4
  14. package/dist/cli/untrusted-marks.d.ts +2 -0
  15. package/dist/cli/untrusted-marks.js +6 -0
  16. package/dist/crm/cli/files.d.ts +68 -0
  17. package/dist/crm/cli/files.js +616 -0
  18. package/dist/crm/cli/index.d.ts +1 -0
  19. package/dist/crm/cli/index.js +3 -0
  20. package/dist/crm/cli/search-all.js +3 -2
  21. package/dist/crm/file-fetch.d.ts +15 -0
  22. package/dist/crm/file-fetch.js +61 -0
  23. package/dist/crm/index.d.ts +1 -0
  24. package/dist/crm/index.js +1 -0
  25. package/dist/crm/testing/files-contract.d.ts +17 -0
  26. package/dist/crm/testing/files-contract.js +142 -0
  27. package/dist/crm/testing/index.d.ts +1 -0
  28. package/dist/crm/testing/index.js +1 -0
  29. package/dist/crm/testing/source.d.ts +5 -0
  30. package/dist/crm/testing/source.js +3 -1
  31. package/dist/entities/hit.d.ts +3 -3
  32. package/dist/entities/hit.js +14 -3
  33. package/dist/entities/index.d.ts +1 -1
  34. package/dist/errors/reasons.js +12 -1
  35. package/dist/files/safe-name.d.ts +2 -1
  36. package/dist/files/safe-name.js +21 -3
  37. package/dist/meetings/mcp/passage.d.ts +6 -2
  38. package/dist/meetings/mcp/passage.js +7 -3
  39. package/dist/search/respell.d.ts +10 -0
  40. package/dist/search/respell.js +63 -0
  41. package/dist/search/stem.d.ts +16 -3
  42. package/dist/search/stem.js +32 -4
  43. package/dist/services/embeddings-search.js +169 -141
  44. package/dist/services/embeddings.d.ts +8 -0
  45. package/dist/services/messages-archive-search.js +55 -3
  46. package/dist/services/messages-search.d.ts +2 -1
  47. package/dist/services/messages-search.js +19 -7
  48. package/dist/services/messages.d.ts +8 -0
  49. package/dist/services/metadata.d.ts +1 -1
  50. package/dist/services/named-chat.d.ts +20 -0
  51. package/dist/services/named-chat.js +63 -0
  52. package/dist/services/search-all.d.ts +7 -2
  53. package/dist/services/search-all.js +35 -1
  54. package/dist/store/exports.d.ts +1 -1
  55. package/dist/store/exports.js +1 -1
  56. package/dist/store/search-index.d.ts +2 -0
  57. package/dist/store/search-index.js +1 -0
  58. package/dist/store/sqlite/crm-files.d.ts +3 -0
  59. package/dist/store/sqlite/crm-files.js +2 -0
  60. package/dist/store/sqlite/crm-settings.d.ts +42 -1
  61. package/dist/store/sqlite/crm-settings.js +46 -2
  62. package/dist/store/sqlite/lucene-fields.d.ts +2 -0
  63. package/dist/store/sqlite/lucene-fields.js +6 -2
  64. package/dist/store/sqlite/lucene.js +2 -2
  65. package/dist/store/sqlite/stems.d.ts +2 -0
  66. package/dist/store/sqlite/stems.js +5 -0
  67. package/package.json +1 -1
@@ -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 });
@@ -29,7 +29,7 @@ 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
31
  export { type CrmFileHit, type CrmFileRow, type CrmFileSearch, type CrmFileStore, resetCrmFileWords, } from "./sqlite/crm-files.js";
32
- export { crmSettingsOf, parseCrmSetting, parseCrmSettingValue, saveCrmSetting } from "./sqlite/crm-settings.js";
32
+ export { CRM_FILE_LIMITS, type CrmFileLimit, type CrmFileLimits, crmSettingsOf, parseCrmSetting, parseCrmSettingValue, saveCrmSetting, } from "./sqlite/crm-settings.js";
33
33
  export { type EmailMarks, MAIL_AGENDA_COLUMNS, type MarkedEmail, type NewestEmail, type ThreadActivity, } from "./sqlite/email-activity.js";
34
34
  export { messageOfEmail, threadConversation } from "./sqlite/emails.js";
35
35
  export { ENRICHMENT_SUBJECTS, type EnrichmentCandidate, type EnrichmentCounts, type EnrichmentNarrowing, type EnrichmentStore, type EnrichmentSubject, type SavedEnrichment, } from "./sqlite/enrichments.js";
@@ -10,7 +10,7 @@ export { CHAT_LIST_KEY, fetchedKey, historyStartKey, } from "./sqlite/completene
10
10
  export { CONVERSATION_COLUMNS } from "./sqlite/conversations.js";
11
11
  export { seenBy } from "./sqlite/copy-viewer.js";
12
12
  export { resetCrmFileWords, } from "./sqlite/crm-files.js";
13
- export { crmSettingsOf, parseCrmSetting, parseCrmSettingValue, saveCrmSetting } from "./sqlite/crm-settings.js";
13
+ export { CRM_FILE_LIMITS, crmSettingsOf, parseCrmSetting, parseCrmSettingValue, saveCrmSetting, } from "./sqlite/crm-settings.js";
14
14
  export { MAIL_AGENDA_COLUMNS, } from "./sqlite/email-activity.js";
15
15
  export { messageOfEmail, threadConversation } from "./sqlite/emails.js";
16
16
  export { ENRICHMENT_SUBJECTS, } from "./sqlite/enrichments.js";
@@ -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 };
@@ -1,6 +1,7 @@
1
1
  import type { CacheDatabase } from "../driver.js";
2
2
  import type { AccountKey } from "../types.js";
3
3
  import type { CopyViewer } from "./copy-viewer.js";
4
+ import { type CrmFileLimits } from "./crm-settings.js";
4
5
  import type { StoreContext } from "./open.js";
5
6
  /** A downloaded file of a CRM record as the store keeps it: never a download link. */
6
7
  export interface CrmFileRow {
@@ -61,6 +62,8 @@ export interface CrmFileStore {
61
62
  items: CrmFileHit[];
62
63
  hasMore: boolean;
63
64
  }>;
65
+ /** The account's `files.*` settings, each its default unless the owner set one in range. */
66
+ limits(key: AccountKey): Promise<CrmFileLimits>;
64
67
  }
65
68
  /** `store rebuild`: the normalized copies follow the current normalizer, then the word index is filled again. */
66
69
  export declare const resetCrmFileWords: (database: CacheDatabase) => number;
@@ -1,6 +1,7 @@
1
1
  import { sep } from "node:path";
2
2
  import { fold, normalize } from "../normalize.js";
3
3
  import { accountPk, findAccountPk } from "./accounts.js";
4
+ import { crmFileLimits } from "./crm-settings.js";
4
5
  import { pageOfRows } from "./rows-page.js";
5
6
  import { write } from "./transaction.js";
6
7
  const MOST = 500;
@@ -168,5 +169,6 @@ export const crmFilesOver = (context) => {
168
169
  .run(accountId, externalId));
169
170
  },
170
171
  find: async (search) => find(search),
172
+ limits: async (key) => crmFileLimits(database, key),
171
173
  };
172
174
  };
@@ -12,7 +12,46 @@ export type CompanyTypeMeaning = (typeof COMPANY_TYPE_MEANINGS)[number];
12
12
  export declare const CRM_SCOPES: readonly ["mine", "all"];
13
13
  /** `activities`: whether a sync also reads the activities and tasks on the deals and leads it keeps; off by default. */
14
14
  export declare const CRM_ACTIVITIES: readonly ["on", "off"];
15
- declare const NAMES: readonly ["links", "company-types", "scope", "unassigned", "self", "stage-tasks", "activities"];
15
+ /**
16
+ * What `files sync` and `files download` may take (NEED-2708 B): a run's files, a prefetched file's and a run's
17
+ * megabytes, a run's minutes, how many days back a run looks, and the account's folder's megabytes. A value outside
18
+ * its range is refused, never clamped.
19
+ */
20
+ export declare const CRM_FILE_LIMITS: {
21
+ readonly max_files: {
22
+ readonly default: 50;
23
+ readonly min: 1;
24
+ readonly max: 500;
25
+ };
26
+ readonly max_file_mb: {
27
+ readonly default: 20;
28
+ readonly min: 1;
29
+ readonly max: 50;
30
+ };
31
+ readonly max_run_mb: {
32
+ readonly default: 200;
33
+ readonly min: 10;
34
+ readonly max: 2000;
35
+ };
36
+ readonly run_minutes: {
37
+ readonly default: 10;
38
+ readonly min: 1;
39
+ readonly max: 60;
40
+ };
41
+ readonly days: {
42
+ readonly default: 7;
43
+ readonly min: 1;
44
+ readonly max: 90;
45
+ };
46
+ readonly max_total_mb: {
47
+ readonly default: 2000;
48
+ readonly min: 100;
49
+ readonly max: 50000;
50
+ };
51
+ };
52
+ export type CrmFileLimit = keyof typeof CRM_FILE_LIMITS;
53
+ export type CrmFileLimits = Record<CrmFileLimit, number>;
54
+ declare const NAMES: readonly ["links", "company-types", "scope", "unassigned", "self", "stage-tasks", "activities", ...("files.days" | "files.max_file_mb" | "files.max_files" | "files.max_run_mb" | "files.max_total_mb" | "files.run_minutes")[]];
16
55
  type CrmSettingName = (typeof NAMES)[number];
17
56
  export declare const crmSettingKey: (key: AccountKey, name: CrmSettingName) => string;
18
57
  /** The account and the setting a key names; a portal's account may hold dots, so it is read from both ends. */
@@ -65,6 +104,8 @@ export interface CrmStageMove {
65
104
  export declare const crmStageTasksSince: (database: CacheDatabase, key: AccountKey) => number | null;
66
105
  /** `at` stays when the rules were first set: the stage history counts from then, whenever the history arrives. */
67
106
  export declare const saveStageMovesMark: (database: CacheDatabase, key: AccountKey, through: number, now: number) => void;
107
+ /** The account's file limits, each the owner's value when it is a whole number in range, else the default. */
108
+ export declare const crmFileLimits: (database: CacheDatabase, key: AccountKey) => CrmFileLimits;
68
109
  export declare const parseCrmSettingValue: (name: CrmSettingName, value: string) => unknown;
69
110
  export declare const saveCrmSetting: (database: CacheDatabase, setting: string, value: unknown, now: number) => void;
70
111
  export declare const crmSettingsOf: (database: CacheDatabase) => {
@@ -8,8 +8,31 @@ export const COMPANY_TYPE_MEANINGS = ["customer-of", "supplier", "partner-of"];
8
8
  export const CRM_SCOPES = ["mine", "all"];
9
9
  /** `activities`: whether a sync also reads the activities and tasks on the deals and leads it keeps; off by default. */
10
10
  export const CRM_ACTIVITIES = ["on", "off"];
11
- const NAMES = ["links", "company-types", "scope", "unassigned", "self", "stage-tasks", "activities"];
12
- const SETTING = new RegExp(`^crm\\.([a-z0-9-]+):(.+)\\.(${NAMES.join("|")})$`);
11
+ /**
12
+ * What `files sync` and `files download` may take (NEED-2708 B): a run's files, a prefetched file's and a run's
13
+ * megabytes, a run's minutes, how many days back a run looks, and the account's folder's megabytes. A value outside
14
+ * its range is refused, never clamped.
15
+ */
16
+ export const CRM_FILE_LIMITS = {
17
+ max_files: { default: 50, min: 1, max: 500 },
18
+ max_file_mb: { default: 20, min: 1, max: 50 },
19
+ max_run_mb: { default: 200, min: 10, max: 2000 },
20
+ run_minutes: { default: 10, min: 1, max: 60 },
21
+ days: { default: 7, min: 1, max: 90 },
22
+ max_total_mb: { default: 2000, min: 100, max: 50000 },
23
+ };
24
+ const FILE_LIMIT_NAMES = Object.keys(CRM_FILE_LIMITS).map((name) => `files.${name}`);
25
+ const NAMES = [
26
+ "links",
27
+ "company-types",
28
+ "scope",
29
+ "unassigned",
30
+ "self",
31
+ "stage-tasks",
32
+ "activities",
33
+ ...FILE_LIMIT_NAMES,
34
+ ];
35
+ const SETTING = new RegExp(`^crm\\.([a-z0-9-]+):(.+)\\.(${NAMES.map((name) => name.replace(".", "\\.")).join("|")})$`);
13
36
  export const crmSettingKey = (key, name) => `crm.${key.provider}:${key.account}.${name}`;
14
37
  /** The account and the setting a key names; a portal's account may hold dots, so it is read from both ends. */
15
38
  export const parseCrmSetting = (setting) => {
@@ -169,8 +192,26 @@ export const saveStageMovesMark = (database, key, through, now) => {
169
192
  .prepare("INSERT INTO store_settings (key, value, at) VALUES (?, ?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value")
170
193
  .run(stageTasksMark(crmSettingKey(key, "stage-tasks")), JSON.stringify(through), now);
171
194
  };
195
+ const fileLimitOf = (name) => name.startsWith("files.") ? name.slice("files.".length) : undefined;
196
+ /** The account's file limits, each the owner's value when it is a whole number in range, else the default. */
197
+ export const crmFileLimits = (database, key) => Object.fromEntries(Object.entries(CRM_FILE_LIMITS).map(([name, range]) => {
198
+ const value = stored(database, crmSettingKey(key, `files.${name}`));
199
+ const fits = Number.isSafeInteger(value) && value >= range.min && value <= range.max;
200
+ return [name, fits ? value : range.default];
201
+ }));
172
202
  export const parseCrmSettingValue = (name, value) => {
173
203
  const text = value.trim();
204
+ const limit = fileLimitOf(name);
205
+ if (limit) {
206
+ const { min, max } = CRM_FILE_LIMITS[limit];
207
+ if (!/^\d+$/u.test(text) || Number(text) < min || Number(text) > max)
208
+ throw new CliError("validation_error", `${name} takes a whole number from ${min} to ${max}, not "${text}"`, {
209
+ reason: "crm.files-limit-range",
210
+ min,
211
+ max,
212
+ });
213
+ return Number(text);
214
+ }
174
215
  if (name === "stage-tasks")
175
216
  return parseStageTasks(text);
176
217
  if (name === "links")
@@ -235,6 +276,9 @@ const settingValue = (database, key, name) => {
235
276
  return stored(database, crmSettingKey(key, name)) ?? {};
236
277
  if (name === "activities")
237
278
  return crmActivitiesOn(database, key) ? "on" : "off";
279
+ const limit = fileLimitOf(name);
280
+ if (limit)
281
+ return crmFileLimits(database, key)[limit];
238
282
  return userIds(stored(database, crmSettingKey(key, name)));
239
283
  };
240
284
  export const crmSettingsOf = (database) => database
@@ -7,6 +7,8 @@ export interface Fragment {
7
7
  params: SqlValue[];
8
8
  exact: boolean;
9
9
  fts?: string;
10
+ /** What a stemmed leaf finds in the word index when that is more than `fts`, the form that ranks first. */
11
+ begins?: string;
10
12
  /** The leaf as a phrase of stems, for ranking a stemmed search by `message_stems`. */
11
13
  stems?: string;
12
14
  /** A bare word's other places — transcripts, file text, file names — as a set of item ids. */
@@ -8,7 +8,7 @@ import { parseBytes } from "../../search/lucene/registry.js";
8
8
  import { isStemmed } from "../../search/lucene/resolved.js";
9
9
  import { exhausted, QUERY_LIMITS, searchError } from "../../search/lucene/types.js";
10
10
  import { inSource } from "../../search/query.js";
11
- import { STEM_SEPARATOR } from "../../search/stem.js";
11
+ import { START_LETTERS, STEM_SEPARATOR } from "../../search/stem.js";
12
12
  import { fold, normalize } from "../normalize.js";
13
13
  import { linkMatch } from "./mention-links.js";
14
14
  import { valueMatch } from "./phone-countries.js";
@@ -150,6 +150,9 @@ const stemmedText = (node, scope) => {
150
150
  throw new Error("a stemmed leaf reached the compiler without the store's stemmer");
151
151
  const text = normalize(node.value);
152
152
  const match = ftsMatch(node);
153
+ // Snowball stems a word's forms apart («журнал» → «журна», «журналом» → «журнал»), so a word of 4 letters or more
154
+ // also finds every word it begins, as grep finds them; a shorter one would find most of the store.
155
+ const start = node.operator === "term" && /^[\p{L}\p{N}]+$/u.test(text) && [...text].length >= START_LETTERS ? text : undefined;
153
156
  const stems = stemsOf(scope, node);
154
157
  const byStems = stems && node.slop !== undefined
155
158
  ? nearStems(scope, node, stems)
@@ -160,9 +163,10 @@ const stemmedText = (node, scope) => {
160
163
  return always(/[\p{L}\p{N}]/u.test(text)
161
164
  ? scope.everywhere(node, {
162
165
  sql: `m.id IN (SELECT rowid FROM ${corpus.words} WHERE ${corpus.words} MATCH ?)${byStems ? ` OR ${byStems.sql}` : ""}`,
163
- params: [`normalized_text : (${match})`, ...(byStems?.params ?? [])],
166
+ params: [`normalized_text : (${start ? `${match} *` : match})`, ...(byStems?.params ?? [])],
164
167
  exact: true,
165
168
  fts: match,
169
+ ...(start ? { begins: `${match} *` } : {}),
166
170
  ...(stems ? { stems } : {}),
167
171
  })
168
172
  : bound("0"));
@@ -263,14 +263,14 @@ const compileQuery = (context, execution, boundedAttachments = false) => {
263
263
  // message of the account and tests each against the index sets.
264
264
  const driverOf = (node) => {
265
265
  if (node.kind === "predicate") {
266
- const { fts, stems, elsewhere: other } = fragments.get(node)?.fragment ?? {};
266
+ const { fts, stems, elsewhere: other, begins } = fragments.get(node)?.fragment ?? {};
267
267
  if (fts === undefined)
268
268
  return undefined;
269
269
  const words = `SELECT rowid AS id FROM ${corpus.words} WHERE ${corpus.words} MATCH ?`;
270
270
  const own = isStemmed(node) && stems
271
271
  ? {
272
272
  sql: `${words} UNION SELECT rowid FROM ${corpus.stems} WHERE ${corpus.stems} MATCH ?`,
273
- params: [`normalized_text : (${fts})`, `stems : (${stems})`],
273
+ params: [`normalized_text : (${begins ?? fts})`, `stems : (${stems})`],
274
274
  }
275
275
  : { sql: words, params: [`normalized_text : (${fts})`] };
276
276
  return other ? { sql: `${own.sql} UNION ${other.sql}`, params: [...own.params, ...other.params] } : own;
@@ -45,6 +45,8 @@ export declare const stemmersOrigin: (database: CacheDatabase) => {
45
45
  origin: "default";
46
46
  defaults: number;
47
47
  } | undefined;
48
+ /** Of these stems, those some message's words were stemmed to. */
49
+ export declare const heldStems: (database: CacheDatabase, stems: string[]) => Set<string>;
48
50
  /** `undefined` on a file before version 15. */
49
51
  export declare const stemsState: (database: CacheDatabase) => StemsState | undefined;
50
52
  /**
@@ -54,6 +54,11 @@ export const stemmersOrigin = (database) => {
54
54
  return { origin: "owner" };
55
55
  }
56
56
  };
57
+ /** Of these stems, those some message's words were stemmed to. */
58
+ export const heldStems = (database, stems) => {
59
+ const lookup = database.prepare(`SELECT 1 FROM ${INDEX} WHERE ${INDEX} MATCH ? LIMIT 1`);
60
+ return new Set(stems.filter((stem) => lookup.get(`stems : "${stem.replaceAll('"', '""')}"`) !== undefined));
61
+ };
57
62
  /** `undefined` on a file before version 15. */
58
63
  export const stemsState = (database) => {
59
64
  const row = indexRow(database, INDEX);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.687.0",
3
+ "version": "0.688.0",
4
4
  "description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Viacheslav Ptsarev",