@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
@@ -0,0 +1,174 @@
1
+ import { sep } from "node:path";
2
+ import { fold, normalize } from "../normalize.js";
3
+ import { accountPk, findAccountPk } from "./accounts.js";
4
+ import { crmFileLimits } from "./crm-settings.js";
5
+ import { pageOfRows } from "./rows-page.js";
6
+ import { write } from "./transaction.js";
7
+ const MOST = 500;
8
+ const CURRENTLY = (table) => `EXISTS (SELECT 1 FROM ${table} r WHERE r.account_id = f.account_id AND r.external_id = f.owner_id ` +
9
+ "AND r.deleted_at IS NULL AND json_extract(r.metadata, '$.assignee') = ?)";
10
+ const EXCERPT = 240;
11
+ const COLUMNS = "f.external_id, f.owner_kind, f.owner_id, f.owner_assignee, f.source, f.name, f.mime, f.size, " +
12
+ "f.external_created_at, f.local_path, f.content_sha256, f.extraction, f.extraction_error, f.downloaded_by, " +
13
+ "f.downloaded_at";
14
+ const text = (value) => (value === null || value === undefined ? null : String(value));
15
+ const number = (value) => (value === null || value === undefined ? null : Number(value));
16
+ const rowOf = (row) => ({
17
+ externalId: String(row.external_id),
18
+ ownerKind: String(row.owner_kind),
19
+ ownerId: String(row.owner_id),
20
+ ownerAssignee: text(row.owner_assignee),
21
+ source: String(row.source),
22
+ name: String(row.name),
23
+ mime: text(row.mime),
24
+ size: number(row.size),
25
+ externalCreatedAt: number(row.external_created_at),
26
+ localPath: text(row.local_path),
27
+ contentSha256: text(row.content_sha256),
28
+ extraction: text(row.extraction),
29
+ extractionError: text(row.extraction_error),
30
+ downloadedBy: text(row.downloaded_by),
31
+ downloadedAt: Number(row.downloaded_at),
32
+ });
33
+ /** One FTS5 phrase per word, quoted so no word is read as syntax; a word may start a longer one unless `exact`. */
34
+ const matchOf = (words, anyWord, exact) => {
35
+ const phrases = words
36
+ .map((word) => normalize(word).trim())
37
+ .filter(Boolean)
38
+ .map((word) => {
39
+ const quoted = `"${word.replaceAll('"', '""')}"`;
40
+ return exact || /\s/u.test(word) || word.length < 3 ? quoted : `${quoted}*`;
41
+ });
42
+ return phrases.length ? [...new Set(phrases)].join(anyWord ? " OR " : " AND ") : undefined;
43
+ };
44
+ const excerptOf = (body, words) => {
45
+ const folded = fold(body);
46
+ const at = words
47
+ .map((word) => folded.indexOf(fold(word).trim()))
48
+ .filter((index) => index >= 0)
49
+ .sort((a, b) => a - b)[0];
50
+ const start = Math.max(0, (at ?? 0) - EXCERPT / 4);
51
+ return body
52
+ .slice(start, start + EXCERPT)
53
+ .replace(/\s+/gu, " ")
54
+ .trim();
55
+ };
56
+ /** `store rebuild`: the normalized copies follow the current normalizer, then the word index is filled again. */
57
+ export const resetCrmFileWords = (database) => {
58
+ if (!database.prepare("SELECT 1 FROM sqlite_master WHERE name = 'crm_file_words'").get())
59
+ return 0;
60
+ return write(database, () => {
61
+ const update = database.prepare("UPDATE crm_files SET normalized_text = ? WHERE id = ?");
62
+ for (const row of database
63
+ .prepare("SELECT id, text, normalized_text FROM crm_files WHERE text IS NOT NULL")
64
+ .all()) {
65
+ const normalized = normalize(String(row.text));
66
+ if (normalized !== row.normalized_text)
67
+ update.run(normalized, Number(row.id));
68
+ }
69
+ database.exec("INSERT INTO crm_file_words (crm_file_words) VALUES ('delete-all')");
70
+ const { changes } = database
71
+ .prepare("INSERT INTO crm_file_words (rowid, normalized_text) SELECT id, normalized_text FROM crm_files " +
72
+ "WHERE normalized_text <> ''")
73
+ .run();
74
+ return Number(changes);
75
+ });
76
+ };
77
+ export const crmFilesOver = (context) => {
78
+ const { database } = context;
79
+ const under = "substr(f.local_path, 1, length(?)) = ?";
80
+ // `…/portal` must not take in `…/portal2/…`: the folder is matched with its separator.
81
+ const inside = (folder) => (folder.endsWith(sep) ? folder : `${folder}${sep}`);
82
+ const save = (key, file) => write(database, () => {
83
+ const accountId = accountPk(context, key);
84
+ database
85
+ .prepare("INSERT INTO crm_files (account_id, external_id, owner_kind, owner_id, owner_assignee, source, name, " +
86
+ "name_folded, mime, size, external_created_at, local_path, content_sha256, text, normalized_text, " +
87
+ "extraction, extraction_error, downloaded_by, downloaded_at) " +
88
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " +
89
+ "ON CONFLICT (account_id, external_id) DO UPDATE SET owner_assignee = excluded.owner_assignee, " +
90
+ "source = excluded.source, name = excluded.name, name_folded = excluded.name_folded, " +
91
+ "mime = excluded.mime, size = excluded.size, external_created_at = excluded.external_created_at, " +
92
+ "local_path = excluded.local_path, content_sha256 = excluded.content_sha256, text = excluded.text, " +
93
+ "normalized_text = excluded.normalized_text, extraction = excluded.extraction, " +
94
+ "extraction_error = excluded.extraction_error, downloaded_by = excluded.downloaded_by, " +
95
+ "downloaded_at = excluded.downloaded_at")
96
+ .run(accountId, file.externalId, file.ownerKind, file.ownerId, file.ownerAssignee, file.source, file.name, fold(file.name), file.mime, file.size, file.externalCreatedAt, file.localPath, file.contentSha256, file.text, file.text === null ? null : normalize(file.text), file.extraction, file.extractionError, file.downloadedBy, file.downloadedAt);
97
+ });
98
+ const rowsOf = (key, columns, where, ...params) => {
99
+ const accountId = findAccountPk(context, key);
100
+ if (accountId === undefined)
101
+ return [];
102
+ return database
103
+ .prepare(`SELECT ${columns} FROM crm_files f WHERE f.account_id = ? AND ${where}`)
104
+ .all(accountId, ...params);
105
+ };
106
+ const find = ({ words, anyWord = false, exact = false, accounts, viewers = [], limit }) => {
107
+ const match = matchOf(words, anyWord, exact);
108
+ if (!match)
109
+ return { items: [], hasMore: false };
110
+ const most = Math.min(Math.max(limit ?? 100, 1), MOST);
111
+ const scoped = accounts?.map((one) => findAccountPk(context, one)).filter((one) => one !== undefined) ?? [];
112
+ if (accounts !== undefined && !scoped.length)
113
+ return { items: [], hasMore: false };
114
+ // A viewer limits only its own account; another account's rows pass it, as `seenBy` lets them.
115
+ const limits = viewers.flatMap((viewer) => {
116
+ const id = findAccountPk(context, viewer.account);
117
+ return id === undefined ? [] : [{ id, assignee: viewer.assignee }];
118
+ });
119
+ const params = [match];
120
+ let sql = `SELECT ${COLUMNS}, f.text, a.provider, a.external_id AS account FROM crm_files f ` +
121
+ "JOIN accounts a ON a.id = f.account_id " +
122
+ "JOIN (SELECT rowid, rank FROM crm_file_words WHERE crm_file_words MATCH ?) w ON w.rowid = f.id WHERE 1";
123
+ if (accounts !== undefined) {
124
+ sql += ` AND f.account_id IN (${scoped.map(() => "?").join(", ")})`;
125
+ for (const id of scoped)
126
+ params.push(id);
127
+ }
128
+ for (const one of limits) {
129
+ if (one.assignee === null) {
130
+ sql += " AND f.account_id <> ?";
131
+ params.push(one.id);
132
+ continue;
133
+ }
134
+ // A deal's or lead's file follows the copy's current assignee, so a reassigned deal takes its files along.
135
+ sql +=
136
+ " AND (f.account_id <> ? OR CASE f.owner_kind " +
137
+ `WHEN 'deal' THEN ${CURRENTLY("deals")} WHEN 'lead' THEN ${CURRENTLY("leads")} ` +
138
+ "ELSE f.owner_assignee = ? END)";
139
+ params.push(one.id, one.assignee, one.assignee, one.assignee);
140
+ }
141
+ sql += " ORDER BY w.rank, f.downloaded_at DESC, f.id DESC LIMIT ?";
142
+ params.push(most + 1);
143
+ const hits = database
144
+ .prepare(sql)
145
+ .all(...params)
146
+ .map((row) => ({
147
+ account: { provider: String(row.provider), account: String(row.account) },
148
+ file: rowOf(row),
149
+ excerpt: excerptOf(String(row.text ?? ""), words),
150
+ }));
151
+ return pageOfRows(hits, most);
152
+ };
153
+ return {
154
+ save: async (key, file) => save(key, file),
155
+ get: async (key, externalId) => {
156
+ const [row] = rowsOf(key, `${COLUMNS}, f.text`, "f.external_id = ?", externalId);
157
+ return row ? { ...rowOf(row), text: text(row.text) } : undefined;
158
+ },
159
+ ofOwner: async (key, kind, id) => rowsOf(key, COLUMNS, "f.owner_kind = ? AND f.owner_id = ? ORDER BY f.downloaded_at DESC, f.id DESC", kind, id).map(rowOf),
160
+ storedBytes: async (key, folder) => rowsOf(key, "coalesce(sum(f.size), 0) AS bytes", `f.local_path IS NOT NULL AND ${under}`, inside(folder), inside(folder)).reduce((sum, row) => sum + Number(row.bytes), 0),
161
+ droppable: async (key, folder) => rowsOf(key, COLUMNS, `f.local_path IS NOT NULL AND ${under} AND coalesce(f.text, '') <> '' ORDER BY f.downloaded_at, f.id`, inside(folder), inside(folder)).map(rowOf),
162
+ savedPaths: async (key) => rowsOf(key, "f.local_path", "f.local_path IS NOT NULL ORDER BY f.id").map((row) => String(row.local_path)),
163
+ forgetFile: async (key, externalId) => {
164
+ const accountId = findAccountPk(context, key);
165
+ if (accountId === undefined)
166
+ return;
167
+ write(database, () => database
168
+ .prepare("UPDATE crm_files SET local_path = NULL WHERE account_id = ? AND external_id = ?")
169
+ .run(accountId, externalId));
170
+ },
171
+ find: async (search) => find(search),
172
+ limits: async (key) => crmFileLimits(database, key),
173
+ };
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;
@@ -347,7 +347,7 @@ const compileQuery = (context, execution, boundedAttachments = false) => {
347
347
  ? ""
348
348
  : rankMatch
349
349
  ? "f.rank,"
350
- : `${exactTier ? "exact DESC," : ""}${ranking ? `f.rank IS NULL, ${placeTier}f.rank,` : placeTier}`;
350
+ : `${exactTier ? "m.id IN (SELECT id FROM x) DESC," : ""}${ranking ? `f.rank IS NULL, ${placeTier}f.rank,` : placeTier}`;
351
351
  const order = `${tiers}m.sent_at DESC, ac.provider, ac.external_id, c.external_id, m.external_id DESC`;
352
352
  const leaves = [...fragments.values()];
353
353
  const exact = leaves.filter(({ test }) => test === undefined);
@@ -482,7 +482,8 @@ const runCompiled = async (context, execution, by) => {
482
482
  return grouped(by, where.sql, [...ranked.params, ...where.params], from, withRanking);
483
483
  // Exact forms come first, so a page they fill needs neither the stems nor their bm25: for a word in a few
484
484
  // percent of messages that was most of the cost (PERF-9). The exact tier is ranked as exact search ranks it.
485
- if (stemmed && exactTier && driver && !execution.newest && leaves.every(({ test }) => !test)) {
485
+ const { newest, perChat } = execution;
486
+ if (stemmed && exactTier && driver && !newest && !perChat && leaves.every(({ test }) => !test)) {
486
487
  const exactRows = database
487
488
  .prepare(`SELECT m.id AS id, w.rank AS relevance ${baseFrom.replace(rowsFrom, `FROM ${corpus.words} w CROSS JOIN ${corpus.rows} m`)} WHERE ${corpus.words} MATCH ? AND w.rank MATCH 'bm25(1.0, 0.0)' AND m.id=w.rowid AND ${filtered.sql} ORDER BY w.rank, m.sent_at DESC, ac.provider, ac.external_id, c.external_id, m.external_id DESC LIMIT ?`)
488
489
  .all(`normalized_text : (${exactTier})`, ...filtered.params, execution.limit + 1);
@@ -511,7 +512,9 @@ const runCompiled = async (context, execution, by) => {
511
512
  }
512
513
  if (leaves.every(({ test }) => !test)) {
513
514
  const rows = database
514
- .prepare(`${withRanking}SELECT m.id AS id, ${relevance} AS relevance${exactColumn} ${rankedFrom} WHERE ${where.sql} ORDER BY ${order} LIMIT ?`)
515
+ .prepare(perChat === undefined
516
+ ? `${withRanking}SELECT m.id AS id, ${relevance} AS relevance${exactColumn} ${rankedFrom} WHERE ${where.sql} ORDER BY ${order} LIMIT ?`
517
+ : `${withRanking}SELECT id, relevance${exactColumn ? ", exact" : ""} FROM (SELECT m.id AS id, ${relevance} AS relevance${exactColumn}, ROW_NUMBER() OVER (PARTITION BY m.chat_id ORDER BY ${order}) AS in_chat, ROW_NUMBER() OVER (ORDER BY ${order}) AS place ${rankedFrom} WHERE ${where.sql}) WHERE in_chat <= ${perChat} ORDER BY place LIMIT ?`)
515
518
  .all(...ranked.params, ...where.params, execution.limit + 1);
516
519
  await new Promise((resolve) => setImmediate(resolve));
517
520
  check();
@@ -525,7 +528,7 @@ const runCompiled = async (context, execution, by) => {
525
528
  };
526
529
  }
527
530
  const candidates = database
528
- .prepare(`${withRanking}SELECT m.id AS id, ${relevance} AS relevance${exactColumn}, length(cast(m.text AS BLOB)) AS bytes ${rankedFrom} WHERE ${where.sql} ORDER BY ${order} LIMIT ?`)
531
+ .prepare(`${withRanking}SELECT m.id AS id, m.chat_id AS chat, ${relevance} AS relevance${exactColumn}, length(cast(m.text AS BLOB)) AS bytes ${rankedFrom} WHERE ${where.sql} ORDER BY ${order} LIMIT ?`)
529
532
  .all(...ranked.params, ...where.params, QUERY_LIMITS.candidates + 1);
530
533
  await new Promise((resolve) => setImmediate(resolve));
531
534
  check();
@@ -539,6 +542,8 @@ const runCompiled = async (context, execution, by) => {
539
542
  const found = [];
540
543
  const scores = new Map(candidates.map((row) => [Number(row.id), row.relevance == null ? null : -Number(row.relevance)]));
541
544
  const exactness = new Map(candidates.map((row) => [Number(row.id), Number(row.exact) === 1]));
545
+ const [chatOf, inChat] = [new Map(candidates.map((row) => [Number(row.id), Number(row.chat)])), new Map()];
546
+ const roomInChat = (chat) => (inChat.set(chat, (inChat.get(chat) ?? 0) + 1).get(chat) ?? 0) <= (by || !perChat ? Infinity : perChat);
542
547
  for (let offset = 0; offset < candidates.length; offset += 500) {
543
548
  if (offset > 0)
544
549
  await new Promise((resolve) => setImmediate(resolve));
@@ -556,7 +561,8 @@ const runCompiled = async (context, execution, by) => {
556
561
  check();
557
562
  const row = byPk.get(id);
558
563
  const attachments = JSON.parse(String(row.attachment_kinds));
559
- if (evaluate(execution.root, row, String(row.body), Array.isArray(attachments) ? attachments.map(String) : []))
564
+ if (evaluate(execution.root, row, String(row.body), Array.isArray(attachments) ? attachments.map(String) : []) &&
565
+ roomInChat(chatOf.get(id)))
560
566
  found.push(id);
561
567
  if (!by && found.length > execution.limit)
562
568
  break;
@@ -132,6 +132,8 @@ export const MANIFEST = [
132
132
  { name: "20261110182602_version-65-found-task-titles", version: 65, minCompatible: 56 },
133
133
  { name: "20261110233711_version-66-identity-name-trigger", version: 66, minCompatible: 56 },
134
134
  { name: "20261113154357_version-67-fact-removals-call-fields", version: 67, minCompatible: 56 },
135
+ { name: "20261116204138_version-68-crm-files", version: 68, minCompatible: 56 },
136
+ { name: "20261116204204_version-68-crm-file-words", version: 68, minCompatible: 56 },
135
137
  ];
136
138
  export const generatedMigrations = (manifest = MANIFEST, generated = GENERATED) => {
137
139
  const migrations = [];
@@ -1344,5 +1344,22 @@ export const GENERATED = [
1344
1344
  "ALTER TABLE `meetings` ADD `client_phone` text;",
1345
1345
  "CREATE INDEX `fact_removals_by_removed_at` ON `fact_removals` (`removed_at`);"
1346
1346
  ]
1347
+ },
1348
+ {
1349
+ "name": "20261116204138_version-68-crm-files",
1350
+ "statements": [
1351
+ "CREATE TABLE `crm_files` (\n\t`id` integer PRIMARY KEY,\n\t`account_id` integer NOT NULL,\n\t`external_id` text NOT NULL,\n\t`owner_kind` text NOT NULL,\n\t`owner_id` text NOT NULL,\n\t`owner_assignee` text,\n\t`source` text NOT NULL,\n\t`name` text NOT NULL,\n\t`name_folded` text NOT NULL,\n\t`mime` text,\n\t`size` integer,\n\t`external_created_at` integer,\n\t`local_path` text,\n\t`content_sha256` text,\n\t`text` text,\n\t`normalized_text` text,\n\t`extraction` text,\n\t`extraction_error` text,\n\t`downloaded_by` text,\n\t`downloaded_at` integer NOT NULL,\n\tCONSTRAINT `fk_crm_files_account_id_accounts_id_fk` FOREIGN KEY (`account_id`) REFERENCES `accounts`(`id`),\n\tCONSTRAINT `crm_files_account_id_external_id_unique` UNIQUE(`account_id`,`external_id`)\n);",
1352
+ "CREATE INDEX `crm_files_by_account_id_owner_kind_owner_id` ON `crm_files` (`account_id`,`owner_kind`,`owner_id`);"
1353
+ ]
1354
+ },
1355
+ {
1356
+ "name": "20261116204204_version-68-crm-file-words",
1357
+ "statements": [
1358
+ "-- Words of a downloaded CRM file's text, rowid = crm_files.id. Apart from attachment_words, so no generic\n-- reader of attachments finds a colleague's file: only CRM code reads it, under the copy's viewer rule.\nCREATE VIRTUAL TABLE crm_file_words USING fts5(\n normalized_text,\n content = '', contentless_delete = 1,\n tokenize = 'unicode61 remove_diacritics 2', prefix = '3');",
1359
+ "CREATE VIRTUAL TABLE crm_file_words_vocab USING fts5vocab(crm_file_words, 'col');",
1360
+ "CREATE TRIGGER crm_file_words_ai AFTER INSERT ON crm_files WHEN new.normalized_text <> '' BEGIN\n INSERT INTO crm_file_words (rowid, normalized_text) VALUES (new.id, new.normalized_text);\nEND;",
1361
+ "CREATE TRIGGER crm_file_words_au AFTER UPDATE OF normalized_text ON crm_files\n WHEN old.normalized_text IS NOT new.normalized_text BEGIN\n DELETE FROM crm_file_words WHERE rowid = old.id;\n INSERT INTO crm_file_words (rowid, normalized_text)\n SELECT new.id, new.normalized_text WHERE new.normalized_text <> '';\nEND;",
1362
+ "CREATE TRIGGER crm_file_words_ad AFTER DELETE ON crm_files BEGIN\n DELETE FROM crm_file_words WHERE rowid = old.id;\nEND;"
1363
+ ]
1347
1364
  }
1348
1365
  ];