@wirecat/cli-core 0.685.0 → 0.687.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.
- package/CHANGELOG.md +78 -0
- package/dist/cli/account-remove.js +21 -3
- package/dist/cli/documents/testing/source-contract.js +18 -9
- package/dist/cli/messenger/store-maintenance-command.js +3 -2
- package/dist/crm/files.d.ts +16 -0
- package/dist/crm/files.js +56 -0
- package/dist/crm/foreign-contacts.d.ts +16 -4
- package/dist/crm/foreign-contacts.js +8 -4
- package/dist/crm/index.d.ts +2 -1
- package/dist/crm/index.js +2 -0
- package/dist/crm/source.d.ts +37 -0
- package/dist/crm/source.js +2 -1
- package/dist/crm/testing/index.d.ts +1 -1
- package/dist/crm/testing/index.js +1 -1
- package/dist/crm/testing/source.d.ts +31 -1
- package/dist/crm/testing/source.js +53 -1
- package/dist/crm/values.d.ts +2 -1
- package/dist/crm/values.js +4 -2
- package/dist/documents/model.d.ts +1 -0
- package/dist/meetings/cli/index.d.ts +1 -1
- package/dist/meetings/cli/index.js +10 -6
- package/dist/meetings/mcp/index.d.ts +15 -15
- package/dist/meetings/read-through.d.ts +2 -0
- package/dist/meetings/read-through.js +7 -2
- package/dist/meetings/source.d.ts +2 -2
- package/dist/oauth/storage.js +21 -4
- package/dist/search/lucene/resolved.d.ts +2 -0
- package/dist/services/documents/ingestion.d.ts +4 -1
- package/dist/services/documents/ingestion.js +11 -0
- package/dist/services/documents/knowledge.js +18 -3
- package/dist/services/documents/plan.js +26 -5
- package/dist/services/documents/ports.d.ts +2 -0
- package/dist/services/documents/sync.js +6 -1
- package/dist/services/embeddings-search.js +33 -11
- package/dist/store/accounts.d.ts +2 -1
- package/dist/store/exports.d.ts +1 -0
- package/dist/store/exports.js +1 -0
- package/dist/store/recover.js +2 -0
- package/dist/store/sqlite/account-purge.js +1 -0
- package/dist/store/sqlite/crm-files.d.ts +67 -0
- package/dist/store/sqlite/crm-files.js +172 -0
- package/dist/store/sqlite/lucene.js +11 -5
- package/dist/store/sqlite/manifest.js +2 -0
- package/dist/store/sqlite/migrations.generated.js +17 -0
- package/dist/store/sqlite/note-search.js +4 -3
- package/dist/store/sqlite/schema.d.ts +329 -0
- package/dist/store/sqlite/schema.js +28 -0
- package/dist/store/store.d.ts +3 -0
- package/dist/store/store.js +5 -0
- package/package.json +2 -2
package/dist/store/recover.js
CHANGED
|
@@ -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, " +
|
|
@@ -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,67 @@
|
|
|
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 { StoreContext } from "./open.js";
|
|
5
|
+
/** A downloaded file of a CRM record as the store keeps it: never a download link. */
|
|
6
|
+
export interface CrmFileRow {
|
|
7
|
+
/** `<owner kind>:<owner id>:<source kind>:<provider id>`. */
|
|
8
|
+
externalId: string;
|
|
9
|
+
ownerKind: string;
|
|
10
|
+
ownerId: string;
|
|
11
|
+
/** The identity `<account>/user/<id>` the owner record was assigned to at download, as a deal's assignee is kept. */
|
|
12
|
+
ownerAssignee: string | null;
|
|
13
|
+
source: string;
|
|
14
|
+
name: string;
|
|
15
|
+
mime: string | null;
|
|
16
|
+
size: number | null;
|
|
17
|
+
externalCreatedAt: number | null;
|
|
18
|
+
/** Null once the disk cap dropped the file; its text stays. */
|
|
19
|
+
localPath: string | null;
|
|
20
|
+
contentSha256: string | null;
|
|
21
|
+
text: string | null;
|
|
22
|
+
/** The `Extraction` status reading the text ended with. */
|
|
23
|
+
extraction: string | null;
|
|
24
|
+
extractionError: string | null;
|
|
25
|
+
/** The CRM user id of the sign-in that downloaded it. */
|
|
26
|
+
downloadedBy: string | null;
|
|
27
|
+
downloadedAt: number;
|
|
28
|
+
}
|
|
29
|
+
export interface CrmFileHit {
|
|
30
|
+
account: AccountKey;
|
|
31
|
+
file: Omit<CrmFileRow, "text">;
|
|
32
|
+
/** Some text around the first word found. */
|
|
33
|
+
excerpt: string;
|
|
34
|
+
}
|
|
35
|
+
export interface CrmFileSearch {
|
|
36
|
+
words: string[];
|
|
37
|
+
anyWord?: boolean;
|
|
38
|
+
/** Whole words only, no word they begin. */
|
|
39
|
+
exact?: boolean;
|
|
40
|
+
/** Absent: every CRM account's. */
|
|
41
|
+
accounts?: AccountKey[];
|
|
42
|
+
/** Each limits its own account's rows to the files of records assigned to its user (NEED-2707 A). */
|
|
43
|
+
viewers?: CopyViewer[];
|
|
44
|
+
limit?: number;
|
|
45
|
+
}
|
|
46
|
+
export interface CrmFileStore {
|
|
47
|
+
/** One downloaded file, replacing an earlier download of the same id. */
|
|
48
|
+
save(key: AccountKey, file: CrmFileRow): Promise<void>;
|
|
49
|
+
get(key: AccountKey, externalId: string): Promise<CrmFileRow | undefined>;
|
|
50
|
+
/** The downloaded files of one record, without their text. */
|
|
51
|
+
ofOwner(key: AccountKey, kind: string, id: string): Promise<Omit<CrmFileRow, "text">[]>;
|
|
52
|
+
/** The bytes of the files saved under `folder`; a copy saved elsewhere is the owner's and not counted. */
|
|
53
|
+
storedBytes(key: AccountKey, folder: string): Promise<number>;
|
|
54
|
+
/** Files under `folder` whose text is stored, oldest download first: what the disk cap may drop. */
|
|
55
|
+
droppable(key: AccountKey, folder: string): Promise<Omit<CrmFileRow, "text">[]>;
|
|
56
|
+
/** Where the account's downloaded files were saved, for `account remove` to list and delete. */
|
|
57
|
+
savedPaths(key: AccountKey): Promise<string[]>;
|
|
58
|
+
/** The saved file is gone; the row and its text stay, so search still finds it. */
|
|
59
|
+
forgetFile(key: AccountKey, externalId: string): Promise<void>;
|
|
60
|
+
find(search: CrmFileSearch): Promise<{
|
|
61
|
+
items: CrmFileHit[];
|
|
62
|
+
hasMore: boolean;
|
|
63
|
+
}>;
|
|
64
|
+
}
|
|
65
|
+
/** `store rebuild`: the normalized copies follow the current normalizer, then the word index is filled again. */
|
|
66
|
+
export declare const resetCrmFileWords: (database: CacheDatabase) => number;
|
|
67
|
+
export declare const crmFilesOver: (context: StoreContext) => CrmFileStore;
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { sep } from "node:path";
|
|
2
|
+
import { fold, normalize } from "../normalize.js";
|
|
3
|
+
import { accountPk, findAccountPk } from "./accounts.js";
|
|
4
|
+
import { pageOfRows } from "./rows-page.js";
|
|
5
|
+
import { write } from "./transaction.js";
|
|
6
|
+
const MOST = 500;
|
|
7
|
+
const CURRENTLY = (table) => `EXISTS (SELECT 1 FROM ${table} r WHERE r.account_id = f.account_id AND r.external_id = f.owner_id ` +
|
|
8
|
+
"AND r.deleted_at IS NULL AND json_extract(r.metadata, '$.assignee') = ?)";
|
|
9
|
+
const EXCERPT = 240;
|
|
10
|
+
const COLUMNS = "f.external_id, f.owner_kind, f.owner_id, f.owner_assignee, f.source, f.name, f.mime, f.size, " +
|
|
11
|
+
"f.external_created_at, f.local_path, f.content_sha256, f.extraction, f.extraction_error, f.downloaded_by, " +
|
|
12
|
+
"f.downloaded_at";
|
|
13
|
+
const text = (value) => (value === null || value === undefined ? null : String(value));
|
|
14
|
+
const number = (value) => (value === null || value === undefined ? null : Number(value));
|
|
15
|
+
const rowOf = (row) => ({
|
|
16
|
+
externalId: String(row.external_id),
|
|
17
|
+
ownerKind: String(row.owner_kind),
|
|
18
|
+
ownerId: String(row.owner_id),
|
|
19
|
+
ownerAssignee: text(row.owner_assignee),
|
|
20
|
+
source: String(row.source),
|
|
21
|
+
name: String(row.name),
|
|
22
|
+
mime: text(row.mime),
|
|
23
|
+
size: number(row.size),
|
|
24
|
+
externalCreatedAt: number(row.external_created_at),
|
|
25
|
+
localPath: text(row.local_path),
|
|
26
|
+
contentSha256: text(row.content_sha256),
|
|
27
|
+
extraction: text(row.extraction),
|
|
28
|
+
extractionError: text(row.extraction_error),
|
|
29
|
+
downloadedBy: text(row.downloaded_by),
|
|
30
|
+
downloadedAt: Number(row.downloaded_at),
|
|
31
|
+
});
|
|
32
|
+
/** One FTS5 phrase per word, quoted so no word is read as syntax; a word may start a longer one unless `exact`. */
|
|
33
|
+
const matchOf = (words, anyWord, exact) => {
|
|
34
|
+
const phrases = words
|
|
35
|
+
.map((word) => normalize(word).trim())
|
|
36
|
+
.filter(Boolean)
|
|
37
|
+
.map((word) => {
|
|
38
|
+
const quoted = `"${word.replaceAll('"', '""')}"`;
|
|
39
|
+
return exact || /\s/u.test(word) || word.length < 3 ? quoted : `${quoted}*`;
|
|
40
|
+
});
|
|
41
|
+
return phrases.length ? [...new Set(phrases)].join(anyWord ? " OR " : " AND ") : undefined;
|
|
42
|
+
};
|
|
43
|
+
const excerptOf = (body, words) => {
|
|
44
|
+
const folded = fold(body);
|
|
45
|
+
const at = words
|
|
46
|
+
.map((word) => folded.indexOf(fold(word).trim()))
|
|
47
|
+
.filter((index) => index >= 0)
|
|
48
|
+
.sort((a, b) => a - b)[0];
|
|
49
|
+
const start = Math.max(0, (at ?? 0) - EXCERPT / 4);
|
|
50
|
+
return body
|
|
51
|
+
.slice(start, start + EXCERPT)
|
|
52
|
+
.replace(/\s+/gu, " ")
|
|
53
|
+
.trim();
|
|
54
|
+
};
|
|
55
|
+
/** `store rebuild`: the normalized copies follow the current normalizer, then the word index is filled again. */
|
|
56
|
+
export const resetCrmFileWords = (database) => {
|
|
57
|
+
if (!database.prepare("SELECT 1 FROM sqlite_master WHERE name = 'crm_file_words'").get())
|
|
58
|
+
return 0;
|
|
59
|
+
return write(database, () => {
|
|
60
|
+
const update = database.prepare("UPDATE crm_files SET normalized_text = ? WHERE id = ?");
|
|
61
|
+
for (const row of database
|
|
62
|
+
.prepare("SELECT id, text, normalized_text FROM crm_files WHERE text IS NOT NULL")
|
|
63
|
+
.all()) {
|
|
64
|
+
const normalized = normalize(String(row.text));
|
|
65
|
+
if (normalized !== row.normalized_text)
|
|
66
|
+
update.run(normalized, Number(row.id));
|
|
67
|
+
}
|
|
68
|
+
database.exec("INSERT INTO crm_file_words (crm_file_words) VALUES ('delete-all')");
|
|
69
|
+
const { changes } = database
|
|
70
|
+
.prepare("INSERT INTO crm_file_words (rowid, normalized_text) SELECT id, normalized_text FROM crm_files " +
|
|
71
|
+
"WHERE normalized_text <> ''")
|
|
72
|
+
.run();
|
|
73
|
+
return Number(changes);
|
|
74
|
+
});
|
|
75
|
+
};
|
|
76
|
+
export const crmFilesOver = (context) => {
|
|
77
|
+
const { database } = context;
|
|
78
|
+
const under = "substr(f.local_path, 1, length(?)) = ?";
|
|
79
|
+
// `…/portal` must not take in `…/portal2/…`: the folder is matched with its separator.
|
|
80
|
+
const inside = (folder) => (folder.endsWith(sep) ? folder : `${folder}${sep}`);
|
|
81
|
+
const save = (key, file) => write(database, () => {
|
|
82
|
+
const accountId = accountPk(context, key);
|
|
83
|
+
database
|
|
84
|
+
.prepare("INSERT INTO crm_files (account_id, external_id, owner_kind, owner_id, owner_assignee, source, name, " +
|
|
85
|
+
"name_folded, mime, size, external_created_at, local_path, content_sha256, text, normalized_text, " +
|
|
86
|
+
"extraction, extraction_error, downloaded_by, downloaded_at) " +
|
|
87
|
+
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " +
|
|
88
|
+
"ON CONFLICT (account_id, external_id) DO UPDATE SET owner_assignee = excluded.owner_assignee, " +
|
|
89
|
+
"source = excluded.source, name = excluded.name, name_folded = excluded.name_folded, " +
|
|
90
|
+
"mime = excluded.mime, size = excluded.size, external_created_at = excluded.external_created_at, " +
|
|
91
|
+
"local_path = excluded.local_path, content_sha256 = excluded.content_sha256, text = excluded.text, " +
|
|
92
|
+
"normalized_text = excluded.normalized_text, extraction = excluded.extraction, " +
|
|
93
|
+
"extraction_error = excluded.extraction_error, downloaded_by = excluded.downloaded_by, " +
|
|
94
|
+
"downloaded_at = excluded.downloaded_at")
|
|
95
|
+
.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);
|
|
96
|
+
});
|
|
97
|
+
const rowsOf = (key, columns, where, ...params) => {
|
|
98
|
+
const accountId = findAccountPk(context, key);
|
|
99
|
+
if (accountId === undefined)
|
|
100
|
+
return [];
|
|
101
|
+
return database
|
|
102
|
+
.prepare(`SELECT ${columns} FROM crm_files f WHERE f.account_id = ? AND ${where}`)
|
|
103
|
+
.all(accountId, ...params);
|
|
104
|
+
};
|
|
105
|
+
const find = ({ words, anyWord = false, exact = false, accounts, viewers = [], limit }) => {
|
|
106
|
+
const match = matchOf(words, anyWord, exact);
|
|
107
|
+
if (!match)
|
|
108
|
+
return { items: [], hasMore: false };
|
|
109
|
+
const most = Math.min(Math.max(limit ?? 100, 1), MOST);
|
|
110
|
+
const scoped = accounts?.map((one) => findAccountPk(context, one)).filter((one) => one !== undefined) ?? [];
|
|
111
|
+
if (accounts !== undefined && !scoped.length)
|
|
112
|
+
return { items: [], hasMore: false };
|
|
113
|
+
// A viewer limits only its own account; another account's rows pass it, as `seenBy` lets them.
|
|
114
|
+
const limits = viewers.flatMap((viewer) => {
|
|
115
|
+
const id = findAccountPk(context, viewer.account);
|
|
116
|
+
return id === undefined ? [] : [{ id, assignee: viewer.assignee }];
|
|
117
|
+
});
|
|
118
|
+
const params = [match];
|
|
119
|
+
let sql = `SELECT ${COLUMNS}, f.text, a.provider, a.external_id AS account FROM crm_files f ` +
|
|
120
|
+
"JOIN accounts a ON a.id = f.account_id " +
|
|
121
|
+
"JOIN (SELECT rowid, rank FROM crm_file_words WHERE crm_file_words MATCH ?) w ON w.rowid = f.id WHERE 1";
|
|
122
|
+
if (accounts !== undefined) {
|
|
123
|
+
sql += ` AND f.account_id IN (${scoped.map(() => "?").join(", ")})`;
|
|
124
|
+
for (const id of scoped)
|
|
125
|
+
params.push(id);
|
|
126
|
+
}
|
|
127
|
+
for (const one of limits) {
|
|
128
|
+
if (one.assignee === null) {
|
|
129
|
+
sql += " AND f.account_id <> ?";
|
|
130
|
+
params.push(one.id);
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
// A deal's or lead's file follows the copy's current assignee, so a reassigned deal takes its files along.
|
|
134
|
+
sql +=
|
|
135
|
+
" AND (f.account_id <> ? OR CASE f.owner_kind " +
|
|
136
|
+
`WHEN 'deal' THEN ${CURRENTLY("deals")} WHEN 'lead' THEN ${CURRENTLY("leads")} ` +
|
|
137
|
+
"ELSE f.owner_assignee = ? END)";
|
|
138
|
+
params.push(one.id, one.assignee, one.assignee, one.assignee);
|
|
139
|
+
}
|
|
140
|
+
sql += " ORDER BY w.rank, f.downloaded_at DESC, f.id DESC LIMIT ?";
|
|
141
|
+
params.push(most + 1);
|
|
142
|
+
const hits = database
|
|
143
|
+
.prepare(sql)
|
|
144
|
+
.all(...params)
|
|
145
|
+
.map((row) => ({
|
|
146
|
+
account: { provider: String(row.provider), account: String(row.account) },
|
|
147
|
+
file: rowOf(row),
|
|
148
|
+
excerpt: excerptOf(String(row.text ?? ""), words),
|
|
149
|
+
}));
|
|
150
|
+
return pageOfRows(hits, most);
|
|
151
|
+
};
|
|
152
|
+
return {
|
|
153
|
+
save: async (key, file) => save(key, file),
|
|
154
|
+
get: async (key, externalId) => {
|
|
155
|
+
const [row] = rowsOf(key, `${COLUMNS}, f.text`, "f.external_id = ?", externalId);
|
|
156
|
+
return row ? { ...rowOf(row), text: text(row.text) } : undefined;
|
|
157
|
+
},
|
|
158
|
+
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),
|
|
159
|
+
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),
|
|
160
|
+
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),
|
|
161
|
+
savedPaths: async (key) => rowsOf(key, "f.local_path", "f.local_path IS NOT NULL ORDER BY f.id").map((row) => String(row.local_path)),
|
|
162
|
+
forgetFile: async (key, externalId) => {
|
|
163
|
+
const accountId = findAccountPk(context, key);
|
|
164
|
+
if (accountId === undefined)
|
|
165
|
+
return;
|
|
166
|
+
write(database, () => database
|
|
167
|
+
.prepare("UPDATE crm_files SET local_path = NULL WHERE account_id = ? AND external_id = ?")
|
|
168
|
+
.run(accountId, externalId));
|
|
169
|
+
},
|
|
170
|
+
find: async (search) => find(search),
|
|
171
|
+
};
|
|
172
|
+
};
|
|
@@ -347,7 +347,7 @@ const compileQuery = (context, execution, boundedAttachments = false) => {
|
|
|
347
347
|
? ""
|
|
348
348
|
: rankMatch
|
|
349
349
|
? "f.rank,"
|
|
350
|
-
: `${exactTier ? "
|
|
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
|
-
|
|
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(
|
|
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
|
];
|
|
@@ -47,11 +47,12 @@ const CORPORA = [
|
|
|
47
47
|
noun: "note",
|
|
48
48
|
fields: NOTE_FIELDS,
|
|
49
49
|
get view() {
|
|
50
|
-
return `(SELECT n.id, n.account_id AS folder_id, n.external_id AS path, n.title, coalesce(n.body, '') AS text, n.metadata, ${contextDocumentTime()} AS at, n.deleted_at FROM documents n)`;
|
|
50
|
+
return `(SELECT n.id, n.account_id AS folder_id, n.external_id AS path, n.title, coalesce(n.body, '') AS text, n.metadata, ${contextDocumentTime()} AS at, n.deleted_at, n.kind FROM documents n)`;
|
|
51
51
|
},
|
|
52
52
|
words: "document_words",
|
|
53
53
|
stems: "document_stems",
|
|
54
|
-
|
|
54
|
+
// A folder (a Drive folder, a Notion workspace or database) is a catalog entry, not a document to open.
|
|
55
|
+
live: "n.kind <> 'folder' AND coalesce(json_extract(n.metadata, '$.catalog.active'), 1)=1",
|
|
55
56
|
inAccounts: (ids) => bound("n.folder_id IN (SELECT CAST(value AS INTEGER) FROM json_each(?))", ids),
|
|
56
57
|
tagged: (tag) => bound("(n.id IN (SELECT g.taggable_id FROM taggings g JOIN resolved_tags t ON t.id=g.tag_id WHERE t.name = ? AND g.taggable_type = 'document') " +
|
|
57
58
|
"OR n.folder_id IN (SELECT g.taggable_id FROM taggings g JOIN resolved_tags t ON t.id=g.tag_id WHERE t.name = ? AND g.taggable_type = 'account') " +
|
|
@@ -339,7 +340,7 @@ export const searchCorpus = (context, query, corpus) => {
|
|
|
339
340
|
const SCAN_PAGE = 5_000;
|
|
340
341
|
const SETTLE_BATCH = 50;
|
|
341
342
|
/** The live documents and notes of a chunk scan, narrowed by folder and source. */
|
|
342
|
-
const LIVE = "((k.chunkable_type = 'document' AND EXISTS (SELECT 1 FROM documents d WHERE d.id = k.chunkable_id AND d.deleted_at IS NULL AND coalesce(json_extract(d.metadata, '$.catalog.active'), 1)=1 " +
|
|
343
|
+
const LIVE = "((k.chunkable_type = 'document' AND EXISTS (SELECT 1 FROM documents d WHERE d.id = k.chunkable_id AND d.deleted_at IS NULL AND d.kind <> 'folder' AND coalesce(json_extract(d.metadata, '$.catalog.active'), 1)=1 " +
|
|
343
344
|
"AND (? IS NULL OR d.account_id IN (SELECT CAST(value AS INTEGER) FROM json_each(?))))) " +
|
|
344
345
|
"OR (k.chunkable_type = 'note' AND ? IS NULL AND EXISTS (SELECT 1 FROM notes n WHERE n.id = k.chunkable_id AND n.deleted_at IS NULL)))";
|
|
345
346
|
export const noteSearchOver = (context) => {
|