@wirecat/cli-core 0.687.0 → 0.689.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 +96 -0
- package/dist/background/daily-archive-timer.d.ts +1 -1
- package/dist/cli/documents/index.d.ts +1 -0
- package/dist/cli/documents/index.js +1 -0
- package/dist/cli/documents/library.d.ts +107 -0
- package/dist/cli/documents/library.js +514 -0
- package/dist/cli/documents/testing/source-contract.d.ts +11 -6
- package/dist/cli/documents/testing/source-contract.js +54 -23
- package/dist/cli/documents/testing/source.d.ts +11 -3
- package/dist/cli/documents/testing/source.js +15 -10
- package/dist/cli/documents/words.d.ts +1 -1
- package/dist/cli/envelope.js +2 -3
- package/dist/cli/meeting-batch.js +5 -1
- package/dist/cli/meeting-passage-text.d.ts +1 -1
- package/dist/cli/meeting-passage-text.js +3 -5
- package/dist/cli/messenger/conversations-command.js +4 -0
- package/dist/cli/messenger/messages-search-command.js +6 -1
- package/dist/cli/messenger/search-answers.js +2 -0
- package/dist/cli/search-left-out.d.ts +3 -0
- package/dist/cli/search-left-out.js +12 -0
- package/dist/cli/store-settings.js +23 -4
- package/dist/cli/untrusted-marks.d.ts +2 -0
- package/dist/cli/untrusted-marks.js +6 -0
- package/dist/crm/cli/files.d.ts +68 -0
- package/dist/crm/cli/files.js +616 -0
- package/dist/crm/cli/index.d.ts +1 -0
- package/dist/crm/cli/index.js +3 -0
- package/dist/crm/cli/search-all.js +3 -2
- package/dist/crm/file-fetch.d.ts +15 -0
- package/dist/crm/file-fetch.js +61 -0
- package/dist/crm/index.d.ts +1 -0
- package/dist/crm/index.js +1 -0
- package/dist/crm/testing/files-contract.d.ts +17 -0
- package/dist/crm/testing/files-contract.js +142 -0
- package/dist/crm/testing/index.d.ts +1 -0
- package/dist/crm/testing/index.js +1 -0
- package/dist/crm/testing/source.d.ts +5 -0
- package/dist/crm/testing/source.js +3 -1
- package/dist/documents/index.d.ts +3 -1
- package/dist/documents/index.js +2 -0
- package/dist/documents/model.d.ts +20 -6
- package/dist/documents/model.js +2 -1
- package/dist/entities/hit.d.ts +3 -3
- package/dist/entities/hit.js +14 -3
- package/dist/entities/index.d.ts +1 -1
- package/dist/errors/reasons.d.ts +1 -1
- package/dist/errors/reasons.js +23 -1
- package/dist/files/safe-name.d.ts +2 -1
- package/dist/files/safe-name.js +21 -3
- package/dist/meetings/mcp/passage.d.ts +6 -2
- package/dist/meetings/mcp/passage.js +7 -3
- package/dist/resolve.d.ts +1 -1
- package/dist/resolve.js +1 -1
- package/dist/search/account-list.d.ts +2 -0
- package/dist/search/account-list.js +32 -4
- package/dist/search/respell.d.ts +10 -0
- package/dist/search/respell.js +63 -0
- package/dist/search/stem.d.ts +16 -3
- package/dist/search/stem.js +32 -4
- package/dist/services/documents/file-text.d.ts +13 -0
- package/dist/services/documents/file-text.js +33 -0
- package/dist/services/documents/plan.d.ts +3 -2
- package/dist/services/documents/plan.js +50 -16
- package/dist/services/documents/ports.d.ts +2 -2
- package/dist/services/documents/sync.js +2 -2
- package/dist/services/embeddings-search.js +169 -141
- package/dist/services/embeddings.d.ts +8 -0
- package/dist/services/message-resolution.d.ts +1 -1
- package/dist/services/message-resolution.js +1 -1
- package/dist/services/messages-archive-search.js +55 -3
- package/dist/services/messages-search.d.ts +2 -1
- package/dist/services/messages-search.js +19 -7
- package/dist/services/messages.d.ts +8 -0
- package/dist/services/metadata.d.ts +1 -1
- package/dist/services/named-chat.d.ts +20 -0
- package/dist/services/named-chat.js +63 -0
- package/dist/services/search-all.d.ts +7 -2
- package/dist/services/search-all.js +35 -1
- package/dist/store/exports.d.ts +1 -1
- package/dist/store/exports.js +1 -1
- package/dist/store/search-index.d.ts +2 -0
- package/dist/store/search-index.js +1 -0
- package/dist/store/sqlite/crm-files.d.ts +3 -0
- package/dist/store/sqlite/crm-files.js +2 -0
- package/dist/store/sqlite/crm-settings.d.ts +42 -1
- package/dist/store/sqlite/crm-settings.js +46 -2
- package/dist/store/sqlite/lucene-fields.d.ts +2 -0
- package/dist/store/sqlite/lucene-fields.js +6 -2
- package/dist/store/sqlite/lucene.js +2 -2
- package/dist/store/sqlite/manifest.js +2 -0
- package/dist/store/sqlite/migrations.generated.js +20 -0
- package/dist/store/sqlite/schema.d.ts +169 -0
- package/dist/store/sqlite/schema.js +18 -0
- package/dist/store/sqlite/stems.d.ts +2 -0
- package/dist/store/sqlite/stems.js +5 -0
- package/dist/store/sqlite/vectors.d.ts +26 -1
- package/dist/store/sqlite/vectors.js +72 -15
- package/dist/store/vectors.js +6 -2
- package/package.json +2 -2
|
@@ -3,12 +3,12 @@ import { formatLocator, parseLocator } from "../domain/locator.js";
|
|
|
3
3
|
import { meaningFloor } from "../embeddings/models.js";
|
|
4
4
|
import { fuseRanked } from "../search/fusion.js";
|
|
5
5
|
import { isQueryLimit, QUERY_LIMITS, searchError } from "../search/lucene/types.js";
|
|
6
|
-
import {
|
|
7
|
-
import { normalize } from "../store/normalize.js";
|
|
6
|
+
import { respelled } from "../search/respell.js";
|
|
8
7
|
import { threadConversation } from "../store/store.js";
|
|
9
8
|
import { embeddingsMaintenance, embeddingTarget, isStale, notBuiltError, readinessOf, shaped, withEmbedder, } from "./embeddings-maintenance.js";
|
|
10
9
|
import { storedChatId } from "./message-resolution.js";
|
|
11
10
|
import { prepareLucene } from "./messages-search.js";
|
|
11
|
+
import { namedChat, queryWords, without } from "./named-chat.js";
|
|
12
12
|
import { MAIL } from "./search-kind.js";
|
|
13
13
|
import { refreshSearch } from "./search-refresh.js";
|
|
14
14
|
/** How deep each list is read before the two are merged. */
|
|
@@ -30,27 +30,28 @@ export const embeddingsSearch = (deps) => {
|
|
|
30
30
|
/**
|
|
31
31
|
* The conversations holding messages that share a word with the query, best message first. Every word
|
|
32
32
|
* is one side of an OR, so a sentence ranks what shares any of it, and nothing in it is read as a filter.
|
|
33
|
-
* Only whole words and their beginnings count
|
|
34
|
-
*
|
|
33
|
+
* Only whole words and their beginnings count, except for a word no message holds at all: that one is read as
|
|
34
|
+
* the words it may stand for (`respelled`), its Latin spelling and the nearest spellings the store holds.
|
|
35
35
|
*/
|
|
36
36
|
const byWords = async (query, prepared, conversations, since, timeLimitMs) => {
|
|
37
|
-
const
|
|
38
|
-
// `что*` OR `какие*` reads most of a large store and runs out of time before the words that matter count.
|
|
39
|
-
const content = all.filter((word) => !STOP_WORDS.has(normalize(word)));
|
|
40
|
-
const words = content.length ? content : all;
|
|
37
|
+
const words = queryWords(query);
|
|
41
38
|
const outside = new Map();
|
|
42
39
|
if (!words.length || !prepared.scopeAccounts.length)
|
|
43
|
-
return { hits: [], outside, sources: new Map() };
|
|
40
|
+
return { hits: [], outside, sources: new Map(), respellings: new Map() };
|
|
44
41
|
const store = await deps.store();
|
|
42
|
+
const respellings = await respelled(store.searchIndex, words);
|
|
45
43
|
const lexical = await prepareLucene(store, await deps.account(), {
|
|
46
|
-
text: words
|
|
44
|
+
text: words
|
|
45
|
+
.flatMap((word) => [word, ...(respellings.get(word) ?? [])])
|
|
46
|
+
.map((word) => (word.length >= 3 ? `${word}*` : `"${word}"`))
|
|
47
|
+
.join(" OR "),
|
|
47
48
|
accounts: prepared.scopeAccounts,
|
|
48
49
|
limit: WORD_HITS,
|
|
49
50
|
...(timeLimitMs === undefined ? {} : { timeLimitMs }),
|
|
50
51
|
}, deps.messenger);
|
|
51
52
|
const { items } = await store.queries.matchQuery({
|
|
52
53
|
...lexical.execution,
|
|
53
|
-
perChat: PER_CHAT,
|
|
54
|
+
...(prepared.selectedChat ? {} : { perChat: PER_CHAT }),
|
|
54
55
|
...(prepared.selectedChat ? { chat: prepared.selectedChat } : {}),
|
|
55
56
|
...(conversations === undefined ? {} : { conversationIds: conversations }),
|
|
56
57
|
...(since === undefined ? {} : { conversationSince: Date.parse(since) }),
|
|
@@ -136,140 +137,167 @@ export const embeddingsSearch = (deps) => {
|
|
|
136
137
|
seen.add(summary.id);
|
|
137
138
|
return [{ summary, chunk }];
|
|
138
139
|
});
|
|
139
|
-
return { hits, outside, sources };
|
|
140
|
+
return { hits, outside, sources, respellings };
|
|
140
141
|
};
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
142
|
+
const search = async (query, { chat, model: choice, since, limit, filter, source, timezone, syncFirst, signal, refresh, timeLimitMs }) => {
|
|
143
|
+
if (!query.trim())
|
|
144
|
+
searchError("query.invalid-syntax", { start: 0, end: query.length }, "give words to search for");
|
|
145
|
+
if (new TextEncoder().encode(query).length > QUERY_LIMITS.bytes)
|
|
146
|
+
searchError("query.too-large", { start: 0, end: query.length }, "query is longer than 8 KiB");
|
|
147
|
+
const refreshed = await refreshSearch(deps, {
|
|
148
|
+
chat,
|
|
149
|
+
limit,
|
|
150
|
+
syncFirst,
|
|
151
|
+
signal,
|
|
152
|
+
text: filter,
|
|
153
|
+
source,
|
|
154
|
+
timezone,
|
|
155
|
+
});
|
|
156
|
+
const locallyRefreshed = refresh
|
|
157
|
+
? await embeddingsMaintenance(deps).refresh({ ...refresh, messages: false })
|
|
158
|
+
: undefined;
|
|
159
|
+
const store = await deps.store();
|
|
160
|
+
const account = await deps.account();
|
|
161
|
+
const target = embeddingTarget(deps, choice);
|
|
162
|
+
const stop = Date.now() + 200;
|
|
163
|
+
await store.searchIndex.fillSearchIndex({ until: () => Date.now() >= stop });
|
|
164
|
+
await store.searchIndex.fillStems({ until: () => Date.now() >= stop });
|
|
165
|
+
const prepared = await prepareLucene(store, account, {
|
|
166
|
+
...(filter === undefined ? {} : { text: filter }),
|
|
167
|
+
...(source === undefined ? {} : { source }),
|
|
168
|
+
...(chat === undefined ? {} : { chat }),
|
|
169
|
+
...(timezone === undefined ? {} : { timezone }),
|
|
170
|
+
limit,
|
|
171
|
+
}, deps.messenger);
|
|
172
|
+
const eligibility = filter === undefined ? undefined : await store.queries.conversationEligibility(prepared.execution);
|
|
173
|
+
const selected = prepared.selectedChat;
|
|
174
|
+
const scopeOf = (one) => selected
|
|
175
|
+
? selected.account.provider === one.provider && selected.account.account === one.account
|
|
176
|
+
? { chatId: selected.chatId }
|
|
177
|
+
: null
|
|
178
|
+
: {};
|
|
179
|
+
// Out of time in words still leaves the meaning half, the one a sentence needs most.
|
|
180
|
+
let wordsOutOfTime = false;
|
|
181
|
+
const words = await byWords(query, prepared, eligibility?.conversations, since, timeLimitMs).catch((error) => {
|
|
182
|
+
if (!isQueryLimit(error))
|
|
183
|
+
throw error;
|
|
184
|
+
wordsOutOfTime = true;
|
|
185
|
+
return {
|
|
186
|
+
hits: [],
|
|
187
|
+
outside: new Map(),
|
|
188
|
+
sources: new Map(),
|
|
189
|
+
respellings: new Map(),
|
|
190
|
+
};
|
|
191
|
+
});
|
|
192
|
+
const meaning = [];
|
|
193
|
+
const sources = words.sources;
|
|
194
|
+
if (target.installed && prepared.scopeAccounts.length && eligibility?.conversations.length !== 0) {
|
|
195
|
+
await withEmbedder(deps, target, choice, {}, async (embedder) => {
|
|
196
|
+
const [vector] = await embedder.embed([query], "query");
|
|
197
|
+
for (const one of prepared.scopeAccounts) {
|
|
198
|
+
const scope = scopeOf(one);
|
|
199
|
+
if (scope === null)
|
|
200
|
+
continue;
|
|
201
|
+
// One chat needs no share, and mail's threads are too many to share among.
|
|
202
|
+
const whole = "chatId" in scope || one.provider === MAIL;
|
|
203
|
+
const hits = await store.vectors.nearestConversations(one, {
|
|
204
|
+
...scope,
|
|
205
|
+
...(since === undefined ? {} : { since }),
|
|
206
|
+
model: target.key,
|
|
207
|
+
limit: whole ? Math.max(limit, CANDIDATES) : Math.max(limit, ACROSS_CHATS),
|
|
208
|
+
query: vector,
|
|
209
|
+
...(eligibility ? { conversations: eligibility.conversations } : {}),
|
|
210
|
+
});
|
|
211
|
+
const images = await store.vectors.nearestImages(one, {
|
|
212
|
+
...scope,
|
|
213
|
+
...(since === undefined ? {} : { since }),
|
|
214
|
+
model: target.key,
|
|
215
|
+
limit: Math.max(limit, CANDIDATES),
|
|
216
|
+
query: vector,
|
|
217
|
+
});
|
|
218
|
+
const found = [
|
|
219
|
+
...hits,
|
|
220
|
+
...images.filter((hit) => !eligibility || eligibility.conversations.includes(hit.summary.id)),
|
|
221
|
+
].sort((a, b) => b.score - a.score);
|
|
222
|
+
for (const hit of found)
|
|
223
|
+
sources.set(hit.summary.id, one);
|
|
224
|
+
meaning.push(...(whole ? found.map((hit) => ({ hit, lead: hit.score })) : shared(found, limit)));
|
|
225
|
+
}
|
|
155
226
|
});
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
const
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
const
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
227
|
+
}
|
|
228
|
+
meaning.sort((a, b) => b.lead - a.lead);
|
|
229
|
+
const scoped = [];
|
|
230
|
+
const elsewhere = [];
|
|
231
|
+
for (const one of prepared.scopeAccounts) {
|
|
232
|
+
const scope = scopeOf(one);
|
|
233
|
+
if (scope === null)
|
|
234
|
+
continue;
|
|
235
|
+
const eligibleChats = eligibility?.chats
|
|
236
|
+
.filter(({ account }) => account.provider === one.provider && account.account === one.account)
|
|
237
|
+
.map(({ chat }) => chat);
|
|
238
|
+
const rows = eligibleChats === undefined
|
|
239
|
+
? await store.vectors.readiness(one, { ...scope, model: target.key, searchableOnly: true })
|
|
240
|
+
: (await Promise.all(eligibleChats.map((chatId) => store.vectors.readiness(one, { chatId, model: target.key })))).flat();
|
|
241
|
+
const readiness = searchReadiness(rows.map(shaped), target.installed, words.outside.get(JSON.stringify(one))?.chats ?? new Set());
|
|
242
|
+
scoped.push({ source: one, readiness });
|
|
243
|
+
const other = await store.vectors.embeddedOnlyElsewhere(one, { ...scope, model: target.key });
|
|
244
|
+
elsewhere.push(...other
|
|
245
|
+
.filter((id) => eligibleChats === undefined || eligibleChats.includes(id))
|
|
246
|
+
.map((id) => prepared.scopeAccounts.length > 1 ? [one.provider, one.account, id].map(encodeURIComponent).join("/") : id));
|
|
247
|
+
}
|
|
248
|
+
const readiness = { searchedByMeaning: [], wordsOnly: [], partial: [], stale: [], notBuilt: [] };
|
|
249
|
+
for (const key of ["searchedByMeaning", "wordsOnly", "partial", "stale", "notBuilt"])
|
|
250
|
+
readiness[key] = [
|
|
251
|
+
...new Set(scoped.flatMap(({ source, readiness }) => readiness[key].map((id) => scoped.length > 1 ? [source.provider, source.account, id].map(encodeURIComponent).join("/") : id))),
|
|
252
|
+
].sort();
|
|
253
|
+
if (scoped.length > 1)
|
|
254
|
+
readiness.scopes = scoped;
|
|
255
|
+
return {
|
|
256
|
+
accounts: prepared.scopeAccounts,
|
|
257
|
+
model: target.id,
|
|
258
|
+
meaning: target.installed ? "searched" : "unavailable",
|
|
259
|
+
...(wordsOutOfTime ? { words: "out-of-time" } : {}),
|
|
260
|
+
...(words.respellings.size ? { respelled: Object.fromEntries(words.respellings) } : {}),
|
|
261
|
+
hits: fused(meaning.map(({ hit }) => hit), words.hits, meaningFloor(target.key))
|
|
262
|
+
.slice(0, limit)
|
|
263
|
+
.map((hit) => {
|
|
264
|
+
const source = sources.get(hit.summary.id);
|
|
265
|
+
return {
|
|
266
|
+
...hit,
|
|
267
|
+
source,
|
|
268
|
+
locator: formatLocator({ ...source, chat: hit.summary.chatId, message: hit.chunk.firstMessageId }),
|
|
269
|
+
};
|
|
270
|
+
}),
|
|
271
|
+
readiness,
|
|
272
|
+
...(locallyRefreshed ? { prepared: locallyRefreshed } : {}),
|
|
273
|
+
...(refreshed
|
|
274
|
+
? { refreshed, coverage: { state: refreshed.complete ? "partial" : "stale" } }
|
|
275
|
+
: {}),
|
|
276
|
+
embeddedOnlyElsewhere: elsewhere,
|
|
277
|
+
};
|
|
278
|
+
};
|
|
279
|
+
return {
|
|
280
|
+
/** Over every chat, a query that names someone by a name their private chat uses has that chat's hits first. */
|
|
281
|
+
search: async (query, options) => {
|
|
282
|
+
const found = await search(query, options);
|
|
283
|
+
if (options.chat !== undefined || options.filter !== undefined || found.accounts?.length !== 1)
|
|
284
|
+
return found;
|
|
285
|
+
const named = await namedChat(await deps.store(), await deps.account(), deps.messenger, found.accounts, queryWords(query)).catch((error) => {
|
|
286
|
+
if (isQueryLimit(error))
|
|
287
|
+
return undefined;
|
|
288
|
+
throw error;
|
|
186
289
|
});
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
if (scope === null)
|
|
195
|
-
continue;
|
|
196
|
-
// One chat needs no share, and mail's threads are too many to share among.
|
|
197
|
-
const whole = "chatId" in scope || one.provider === MAIL;
|
|
198
|
-
const hits = await store.vectors.nearestConversations(one, {
|
|
199
|
-
...scope,
|
|
200
|
-
...(since === undefined ? {} : { since }),
|
|
201
|
-
model: target.key,
|
|
202
|
-
limit: whole ? Math.max(limit, CANDIDATES) : Math.max(limit, ACROSS_CHATS),
|
|
203
|
-
query: vector,
|
|
204
|
-
...(eligibility ? { conversations: eligibility.conversations } : {}),
|
|
205
|
-
});
|
|
206
|
-
const images = await store.vectors.nearestImages(one, {
|
|
207
|
-
...scope,
|
|
208
|
-
...(since === undefined ? {} : { since }),
|
|
209
|
-
model: target.key,
|
|
210
|
-
limit: Math.max(limit, CANDIDATES),
|
|
211
|
-
query: vector,
|
|
212
|
-
});
|
|
213
|
-
const found = [
|
|
214
|
-
...hits,
|
|
215
|
-
...images.filter((hit) => !eligibility || eligibility.conversations.includes(hit.summary.id)),
|
|
216
|
-
].sort((a, b) => b.score - a.score);
|
|
217
|
-
for (const hit of found)
|
|
218
|
-
sources.set(hit.summary.id, one);
|
|
219
|
-
meaning.push(...(whole ? found.map((hit) => ({ hit, lead: hit.score })) : shared(found, limit)));
|
|
220
|
-
}
|
|
221
|
-
});
|
|
222
|
-
}
|
|
223
|
-
meaning.sort((a, b) => b.lead - a.lead);
|
|
224
|
-
const scoped = [];
|
|
225
|
-
const elsewhere = [];
|
|
226
|
-
for (const one of prepared.scopeAccounts) {
|
|
227
|
-
const scope = scopeOf(one);
|
|
228
|
-
if (scope === null)
|
|
229
|
-
continue;
|
|
230
|
-
const eligibleChats = eligibility?.chats
|
|
231
|
-
.filter(({ account }) => account.provider === one.provider && account.account === one.account)
|
|
232
|
-
.map(({ chat }) => chat);
|
|
233
|
-
const rows = eligibleChats === undefined
|
|
234
|
-
? await store.vectors.readiness(one, { ...scope, model: target.key, searchableOnly: true })
|
|
235
|
-
: (await Promise.all(eligibleChats.map((chatId) => store.vectors.readiness(one, { chatId, model: target.key })))).flat();
|
|
236
|
-
const readiness = searchReadiness(rows.map(shaped), target.installed, words.outside.get(JSON.stringify(one))?.chats ?? new Set());
|
|
237
|
-
scoped.push({ source: one, readiness });
|
|
238
|
-
const other = await store.vectors.embeddedOnlyElsewhere(one, { ...scope, model: target.key });
|
|
239
|
-
elsewhere.push(...other
|
|
240
|
-
.filter((id) => eligibleChats === undefined || eligibleChats.includes(id))
|
|
241
|
-
.map((id) => prepared.scopeAccounts.length > 1
|
|
242
|
-
? [one.provider, one.account, id].map(encodeURIComponent).join("/")
|
|
243
|
-
: id));
|
|
244
|
-
}
|
|
245
|
-
const readiness = { searchedByMeaning: [], wordsOnly: [], partial: [], stale: [], notBuilt: [] };
|
|
246
|
-
for (const key of ["searchedByMeaning", "wordsOnly", "partial", "stale", "notBuilt"])
|
|
247
|
-
readiness[key] = [
|
|
248
|
-
...new Set(scoped.flatMap(({ source, readiness }) => readiness[key].map((id) => scoped.length > 1 ? [source.provider, source.account, id].map(encodeURIComponent).join("/") : id))),
|
|
249
|
-
].sort();
|
|
250
|
-
if (scoped.length > 1)
|
|
251
|
-
readiness.scopes = scoped;
|
|
290
|
+
if (!named)
|
|
291
|
+
return found;
|
|
292
|
+
// Inside the chat the name is in every other message, so it would only add noise there.
|
|
293
|
+
const rest = without(query, named.word);
|
|
294
|
+
const { syncFirst: _, refresh: __, ...plain } = options;
|
|
295
|
+
const inside = await search(rest || query, { ...plain, chat: named.chatId });
|
|
296
|
+
const shown = new Set(inside.hits.map(({ summary }) => summary.id));
|
|
252
297
|
return {
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
...(wordsOutOfTime ? { words: "out-of-time" } : {}),
|
|
257
|
-
hits: fused(meaning.map(({ hit }) => hit), words.hits, meaningFloor(target.key))
|
|
258
|
-
.slice(0, limit)
|
|
259
|
-
.map((hit) => {
|
|
260
|
-
const source = sources.get(hit.summary.id);
|
|
261
|
-
return {
|
|
262
|
-
...hit,
|
|
263
|
-
source,
|
|
264
|
-
locator: formatLocator({ ...source, chat: hit.summary.chatId, message: hit.chunk.firstMessageId }),
|
|
265
|
-
};
|
|
266
|
-
}),
|
|
267
|
-
readiness,
|
|
268
|
-
...(locallyRefreshed ? { prepared: locallyRefreshed } : {}),
|
|
269
|
-
...(refreshed
|
|
270
|
-
? { refreshed, coverage: { state: refreshed.complete ? "partial" : "stale" } }
|
|
271
|
-
: {}),
|
|
272
|
-
embeddedOnlyElsewhere: elsewhere,
|
|
298
|
+
...found,
|
|
299
|
+
named: { word: named.word, chatId: named.chatId, title: named.title },
|
|
300
|
+
hits: [...inside.hits, ...found.hits.filter(({ summary }) => !shown.has(summary.id))].slice(0, options.limit),
|
|
273
301
|
};
|
|
274
302
|
},
|
|
275
303
|
related: async (chat, message, { model: choice, limit }) => {
|
|
@@ -139,6 +139,14 @@ export interface FoundConversations {
|
|
|
139
139
|
meaning: "searched" | "unavailable";
|
|
140
140
|
/** `out-of-time`: the word half hit its time limit, so the hits are by meaning alone. */
|
|
141
141
|
words?: "out-of-time";
|
|
142
|
+
/** Words no message holds, each with the words searched in its place: its Latin spelling and near spellings. */
|
|
143
|
+
respelled?: Record<string, string[]>;
|
|
144
|
+
/** The private chat a word of the query names, whose hits come first. */
|
|
145
|
+
named?: {
|
|
146
|
+
word: string;
|
|
147
|
+
chatId: Id;
|
|
148
|
+
title: string | null;
|
|
149
|
+
};
|
|
142
150
|
hits: FoundConversation[];
|
|
143
151
|
readiness: SearchReadiness;
|
|
144
152
|
/** Kept for callers of 0.141.0 and before; `readiness.wordsOnly` says more. */
|
|
@@ -36,7 +36,7 @@ export declare const senderAmong: (store: MessageStore, accounts: AccountKey[],
|
|
|
36
36
|
}>;
|
|
37
37
|
/** The most people or chats one name pattern may stand for in a search. */
|
|
38
38
|
export declare const MOST_NAME_MATCHES = 50;
|
|
39
|
-
/** Every sender a name pattern (`from
|
|
39
|
+
/** Every sender a name pattern (`from:Станислав*`) fits, through the names each messenger's accounts have seen. */
|
|
40
40
|
export declare const sendersMatching: (store: MessageStore, accounts: AccountKey[], field: string, pattern: string) => Promise<{
|
|
41
41
|
provider: Provider;
|
|
42
42
|
id: Id;
|
|
@@ -198,7 +198,7 @@ const patternRefused = (field, pattern, what, found, near) => {
|
|
|
198
198
|
}
|
|
199
199
|
throw new CliError("validation_error", `${field}:${pattern} fits ${found} ${what}, more than ${MOST_NAME_MATCHES} — write more of the name`, { reason: "query.too-large", budget: "name matches", limit: MOST_NAME_MATCHES, complete: false });
|
|
200
200
|
};
|
|
201
|
-
/** Every sender a name pattern (`from
|
|
201
|
+
/** Every sender a name pattern (`from:Станислав*`) fits, through the names each messenger's accounts have seen. */
|
|
202
202
|
export const sendersMatching = async (store, accounts, field, pattern) => {
|
|
203
203
|
const providers = [...new Set(accounts.map(({ provider }) => provider))];
|
|
204
204
|
const seen = await Promise.all(providers.map(async (provider) => {
|
|
@@ -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
|
|
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
|
-
|
|
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;
|