@wirecat/cli-core 0.717.0 → 0.718.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 +62 -0
- package/dist/cli/documents/index.d.ts +2 -0
- package/dist/cli/documents/index.js +2 -0
- package/dist/cli/documents/manifest/manifest.d.ts +82 -0
- package/dist/cli/documents/manifest/manifest.js +97 -0
- package/dist/cli/documents/manifest/source.d.ts +35 -0
- package/dist/cli/documents/manifest/source.js +257 -0
- package/dist/cli/documents/words.d.ts +1 -1
- package/dist/cli/messenger/conversation-answers.d.ts +1 -1
- package/dist/cli/messenger/conversation-answers.js +4 -2
- package/dist/cli/messenger/conversations-command.js +13 -4
- package/dist/cli/service-api-manifest.d.ts +2 -0
- package/dist/cli/service-api-manifest.js +6 -6
- package/dist/content/manifest/writer.js +5 -1
- package/dist/documents/model.d.ts +6 -0
- package/dist/entities/conversation-results.d.ts +5 -0
- package/dist/entities/conversation-results.js +6 -1
- package/dist/entities/index.d.ts +3 -0
- package/dist/errors/reasons.js +8 -0
- package/dist/manifest/index.d.ts +22 -3
- package/dist/manifest/index.js +13 -2
- package/dist/search/lucene/resolved.d.ts +2 -0
- package/dist/services/documents/plan.d.ts +2 -0
- package/dist/services/documents/plan.js +12 -0
- package/dist/services/embeddings-search.d.ts +9 -0
- package/dist/services/embeddings-search.js +189 -69
- package/dist/services/embeddings.d.ts +6 -0
- package/dist/services/metadata.d.ts +1 -1
- package/dist/services/named-chat.d.ts +3 -3
- package/dist/services/named-chat.js +12 -3
- package/dist/store/conversations.d.ts +21 -0
- package/dist/store/conversations.js +13 -0
- package/dist/store/slow-queries.d.ts +7 -0
- package/dist/store/slow-queries.js +47 -0
- package/dist/store/sqlite/conversations.d.ts +21 -0
- package/dist/store/sqlite/conversations.js +50 -0
- package/dist/store/sqlite/lucene-fields.d.ts +2 -0
- package/dist/store/sqlite/lucene-fields.js +22 -0
- package/dist/store/sqlite/lucene.js +30 -42
- package/dist/store/sqlite/open.js +3 -0
- package/dist/store/sqlite/vector-index.d.ts +3 -1
- package/dist/store/sqlite/vector-index.js +5 -3
- package/dist/store/sqlite/vectors.js +20 -11
- package/dist/store/sqlite/word-rarity.d.ts +14 -0
- package/dist/store/sqlite/word-rarity.js +22 -0
- package/package.json +2 -2
- package/parity.json +5 -0
|
@@ -32,6 +32,8 @@ export interface Corpus {
|
|
|
32
32
|
item: string;
|
|
33
33
|
thread: string;
|
|
34
34
|
}
|
|
35
|
+
export declare const MESSAGES: Corpus;
|
|
36
|
+
export declare const MAIL: Corpus;
|
|
35
37
|
/**
|
|
36
38
|
* A voice note's transcript is its attachment's text, whoever wrote it: speech recognition (`speech:<model>`) or an
|
|
37
39
|
* agent, which writes the text of a voice attachment as `agent`. The voice attachment is the one
|
|
@@ -14,6 +14,28 @@ import { linkMatch } from "./mention-links.js";
|
|
|
14
14
|
import { valueMatch } from "./phone-countries.js";
|
|
15
15
|
import { canonicalTagNamed } from "./tags.js";
|
|
16
16
|
import { yoSpellings } from "./trigram-match.js";
|
|
17
|
+
export const MESSAGES = {
|
|
18
|
+
rows: "messages",
|
|
19
|
+
threads: "chats",
|
|
20
|
+
words: "message_words",
|
|
21
|
+
stems: "message_stems",
|
|
22
|
+
vocab: "message_words_vocab",
|
|
23
|
+
item: "message",
|
|
24
|
+
thread: "chat",
|
|
25
|
+
};
|
|
26
|
+
// The same column names as messages and chats, so every rule reads mail as it reads messages. The text is the
|
|
27
|
+
// subject, a blank line, then the body, so `subject:` reads the subject back from it.
|
|
28
|
+
export const MAIL = {
|
|
29
|
+
rows: `(SELECT id, account_id, email_thread_id AS chat_id, external_id, deleted_at, from_identity_id AS sender_identity_id,
|
|
30
|
+
outgoing, read, flagged, coalesce(sent_at, received_at) AS sent_at,
|
|
31
|
+
coalesce(subject, '') || char(10, 10) || coalesce(body_text, '') AS text FROM emails)`,
|
|
32
|
+
threads: "(SELECT id, account_id, external_id, subject AS title, 1 AS searchable FROM email_threads)",
|
|
33
|
+
words: "email_words",
|
|
34
|
+
stems: "email_stems",
|
|
35
|
+
vocab: "email_words_vocab",
|
|
36
|
+
item: "email",
|
|
37
|
+
thread: "email_thread",
|
|
38
|
+
};
|
|
17
39
|
/**
|
|
18
40
|
* A voice note's transcript is its attachment's text, whoever wrote it: speech recognition (`speech:<model>`) or an
|
|
19
41
|
* agent, which writes the text of a voice attachment as `agent`. The voice attachment is the one
|
|
@@ -6,34 +6,13 @@ import { exhausted, outOfTime, QUERY_LIMITS, searchError, sqliteLimit, tooWideTe
|
|
|
6
6
|
import { TIME_LIMIT_FUNCTION, TimeLimitReached } from "../driver.js";
|
|
7
7
|
import { emailHitsByPk } from "./emails.js";
|
|
8
8
|
import { placeHits } from "./hit-places.js";
|
|
9
|
-
import { combine, FIELD_COMPILERS, ftsMatch, present, quoted, SPEECH, } from "./lucene-fields.js";
|
|
9
|
+
import { combine, FIELD_COMPILERS, ftsMatch, MAIL, MESSAGES, present, quoted, SPEECH, } from "./lucene-fields.js";
|
|
10
10
|
import { GROUPS } from "./lucene-groups.js";
|
|
11
11
|
import { hitsByPk } from "./search.js";
|
|
12
12
|
import { read } from "./transaction.js";
|
|
13
13
|
import { transcriptItems, transcriptTerms } from "./transcript-query.js";
|
|
14
|
+
import { RARITY_ORDER, withRarity } from "./word-rarity.js";
|
|
14
15
|
export { prefixOf } from "./lucene-fields.js";
|
|
15
|
-
const MESSAGES = {
|
|
16
|
-
rows: "messages",
|
|
17
|
-
threads: "chats",
|
|
18
|
-
words: "message_words",
|
|
19
|
-
stems: "message_stems",
|
|
20
|
-
vocab: "message_words_vocab",
|
|
21
|
-
item: "message",
|
|
22
|
-
thread: "chat",
|
|
23
|
-
};
|
|
24
|
-
// The same column names as messages and chats, so every rule reads mail as it reads messages. The text is the
|
|
25
|
-
// subject, a blank line, then the body, so `subject:` reads the subject back from it.
|
|
26
|
-
const MAIL = {
|
|
27
|
-
rows: `(SELECT id, account_id, email_thread_id AS chat_id, external_id, deleted_at, from_identity_id AS sender_identity_id,
|
|
28
|
-
outgoing, read, flagged, coalesce(sent_at, received_at) AS sent_at,
|
|
29
|
-
coalesce(subject, '') || char(10, 10) || coalesce(body_text, '') AS text FROM emails)`,
|
|
30
|
-
threads: "(SELECT id, account_id, external_id, subject AS title, 1 AS searchable FROM email_threads)",
|
|
31
|
-
words: "email_words",
|
|
32
|
-
stems: "email_stems",
|
|
33
|
-
vocab: "email_words_vocab",
|
|
34
|
-
item: "email",
|
|
35
|
-
thread: "email_thread",
|
|
36
|
-
};
|
|
37
16
|
export const matchQuery = (context, execution) => runQuery(context, execution);
|
|
38
17
|
/** Every match counted once, grouped; the work and candidate budgets of a search still apply. */
|
|
39
18
|
export const countQuery = (context, execution, by) => runQuery(context, execution, by);
|
|
@@ -237,19 +216,18 @@ const compileQuery = (context, execution, boundedAttachments = false) => {
|
|
|
237
216
|
const rowsFrom = `FROM ${corpus.rows} m`;
|
|
238
217
|
const joinedFrom = `${rowsFrom} JOIN ${corpus.threads} c ON c.id=m.chat_id JOIN accounts ac ON ac.id=m.account_id LEFT JOIN identities i ON i.id=m.sender_identity_id`;
|
|
239
218
|
let baseFrom = joinedFrom;
|
|
240
|
-
const requiredText = (node, index = "fts") => {
|
|
219
|
+
const requiredText = (node, index = "fts", partial = false) => {
|
|
241
220
|
if (node.kind === "predicate")
|
|
242
221
|
return fragments.get(node)?.fragment[index];
|
|
243
222
|
const required = node.clauses.filter(({ occur }) => occur === "must");
|
|
244
223
|
const optional = node.clauses.filter(({ occur }) => occur === "should");
|
|
245
224
|
if (required.length) {
|
|
246
|
-
const parts = required.flatMap(({ node }) => requiredText(node, index) ?? []);
|
|
225
|
+
const parts = required.flatMap(({ node }) => requiredText(node, index, partial) ?? []);
|
|
247
226
|
return parts.length ? parts.map((part) => `(${part})`).join(" AND ") : undefined;
|
|
248
227
|
}
|
|
249
|
-
const parts = optional.
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
: undefined;
|
|
228
|
+
const parts = optional.flatMap(({ node }) => requiredText(node, index, partial) ?? []);
|
|
229
|
+
const whole = partial || parts.length === optional.length;
|
|
230
|
+
return parts.length && whole ? parts.map((part) => `(${part})`).join(" OR ") : undefined;
|
|
253
231
|
};
|
|
254
232
|
const stemmed = [...fragments.keys()].some(isStemmed);
|
|
255
233
|
// A word found only in a file is not in the word index, so neither may filter: they rank, joined LEFT.
|
|
@@ -308,10 +286,10 @@ const compileQuery = (context, execution, boundedAttachments = false) => {
|
|
|
308
286
|
], "AND");
|
|
309
287
|
// A stemmed search ranks by stems but must not filter by them, so its ranking is a set computed once and
|
|
310
288
|
// joined LEFT; joined row by row, the same query took 420 ms instead of 5 at 100k (stemming gate).
|
|
311
|
-
|
|
312
|
-
const
|
|
313
|
-
|
|
314
|
-
|
|
289
|
+
// One word without stems (a word's start) or without any indexed form must not cost the others their bm25.
|
|
290
|
+
const byStems = stemmed ? requiredText(execution.root, "stems") : undefined;
|
|
291
|
+
const ranking = byStems ?? (stemmed || elsewhere ? requiredText(execution.root, "fts", true) : undefined);
|
|
292
|
+
const rankIndex = { table: byStems ? corpus.stems : corpus.words, column: byStems ? "stems" : "normalized_text" };
|
|
315
293
|
const exactTier = stemmed ? requiredText(execution.root) : undefined;
|
|
316
294
|
const ranked = driver
|
|
317
295
|
? { sql: [`d(id) AS MATERIALIZED (${driver.sql})`], params: [...driver.params] }
|
|
@@ -335,20 +313,29 @@ const compileQuery = (context, execution, boundedAttachments = false) => {
|
|
|
335
313
|
ranked.params.push(places.join(" OR "), places.join(" OR "), ...parts.flatMap(({ params }) => params));
|
|
336
314
|
}
|
|
337
315
|
const placeTier = places.length && !execution.newest ? "coalesce((SELECT min(tier) FROM s WHERE s.id=m.id), 6)," : "";
|
|
316
|
+
const rarity = execution.rareWordsFirst &&
|
|
317
|
+
!execution.newest &&
|
|
318
|
+
!mail &&
|
|
319
|
+
withRarity(database, corpus.words, [...fragments.values()], ranked);
|
|
338
320
|
if (exactTier) {
|
|
339
321
|
ranked.sql.push(`x(id) AS MATERIALIZED (SELECT rowid FROM ${corpus.words} WHERE ${corpus.words} MATCH ?)`);
|
|
340
322
|
ranked.params.push(`normalized_text : (${exactTier})`);
|
|
341
323
|
}
|
|
342
324
|
const withRanking = ranked.sql.length ? `WITH ${ranked.sql.join(", ")} ` : "";
|
|
343
|
-
|
|
325
|
+
// Joined, not read by a subquery: inside a window SQLite scanned the whole set once per row.
|
|
326
|
+
const rankedFrom = `${ranking && !execution.newest ? `${from} LEFT JOIN f ON f.id=m.id` : from}${rarity ? " LEFT JOIN rarity ON rarity.id=m.id" : ""}`;
|
|
344
327
|
const exactColumn = exactTier ? ", m.id IN (SELECT id FROM x) AS exact" : "";
|
|
345
328
|
const relevance = rankMatch ? "f.rank" : ranking && !execution.newest ? "f.rank" : "NULL";
|
|
346
|
-
const tiers = execution.newest
|
|
329
|
+
const tiers = (rare) => execution.newest
|
|
347
330
|
? ""
|
|
348
331
|
: rankMatch
|
|
349
|
-
?
|
|
350
|
-
: `${exactTier ? "m.id IN (SELECT id FROM x) DESC," : ""}${ranking ? `f.rank IS NULL, ${placeTier}f.rank,` : placeTier}`;
|
|
351
|
-
const
|
|
332
|
+
? `${rare}f.rank,`
|
|
333
|
+
: `${exactTier ? "m.id IN (SELECT id FROM x) DESC," : ""}${ranking ? `f.rank IS NULL, ${placeTier}${rare}f.rank,` : `${placeTier}${rare}`}`;
|
|
334
|
+
const ties = "m.sent_at DESC, ac.provider, ac.external_id, c.external_id, m.external_id DESC";
|
|
335
|
+
const order = `${tiers(rarity ? RARITY_ORDER : "")}${ties}`;
|
|
336
|
+
// Rarity picks a chat's hits; today's order picks the chats. Rare words of big groups otherwise filled the page,
|
|
337
|
+
// and a small chat's answer fell past it.
|
|
338
|
+
const acrossChats = `${tiers("")}${ties}`;
|
|
352
339
|
const leaves = [...fragments.values()];
|
|
353
340
|
const exact = leaves.filter(({ test }) => test === undefined);
|
|
354
341
|
const projection = exact.map(({ fragment }, index) => `coalesce(${fragment.sql},0) AS q${index}`).join(",");
|
|
@@ -403,6 +390,7 @@ const compileQuery = (context, execution, boundedAttachments = false) => {
|
|
|
403
390
|
rankedFrom,
|
|
404
391
|
exactColumn,
|
|
405
392
|
order,
|
|
393
|
+
acrossChats,
|
|
406
394
|
placeTier,
|
|
407
395
|
projection,
|
|
408
396
|
projectionParams,
|
|
@@ -469,7 +457,7 @@ const runQuery = (context, execution, by) => {
|
|
|
469
457
|
}
|
|
470
458
|
};
|
|
471
459
|
const runCompiled = async (context, execution, by) => {
|
|
472
|
-
const { corpus, rowsFrom, hits, database, check, grouped, where, from, withRanking, ranked, leaves, stemmed, exactTier, driver, baseFrom, filtered, ranking, relevance, rankedFrom, exactColumn, order, placeTier, projection, projectionParams, joinedFrom, evaluate, } = compileQuery(context, execution);
|
|
460
|
+
const { corpus, rowsFrom, hits, database, check, grouped, where, from, withRanking, ranked, leaves, stemmed, exactTier, driver, baseFrom, filtered, ranking, relevance, rankedFrom, exactColumn, order, acrossChats, placeTier, projection, projectionParams, joinedFrom, evaluate, } = compileQuery(context, execution);
|
|
473
461
|
if (by === "pks" && leaves.every(({ test }) => !test)) {
|
|
474
462
|
const rows = database
|
|
475
463
|
.prepare(`${withRanking}SELECT m.id AS id ${from} WHERE ${where.sql}`)
|
|
@@ -482,8 +470,8 @@ const runCompiled = async (context, execution, by) => {
|
|
|
482
470
|
return grouped(by, where.sql, [...ranked.params, ...where.params], from, withRanking);
|
|
483
471
|
// Exact forms come first, so a page they fill needs neither the stems nor their bm25: for a word in a few
|
|
484
472
|
// percent of messages that was most of the cost (PERF-9). The exact tier is ranked as exact search ranks it.
|
|
485
|
-
const { newest, perChat } = execution;
|
|
486
|
-
if (stemmed && exactTier && driver && !newest && !perChat && leaves.every(({ test }) => !test)) {
|
|
473
|
+
const { newest, perChat, rareWordsFirst } = execution;
|
|
474
|
+
if (stemmed && exactTier && driver && !newest && !perChat && !rareWordsFirst && leaves.every(({ test }) => !test)) {
|
|
487
475
|
const exactRows = database
|
|
488
476
|
.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 ?`)
|
|
489
477
|
.all(`normalized_text : (${exactTier})`, ...filtered.params, execution.limit + 1);
|
|
@@ -514,7 +502,7 @@ const runCompiled = async (context, execution, by) => {
|
|
|
514
502
|
const rows = database
|
|
515
503
|
.prepare(perChat === undefined
|
|
516
504
|
? `${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 ${
|
|
505
|
+
: `${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 ${acrossChats}) AS place ${rankedFrom} WHERE ${where.sql}) WHERE in_chat <= ${perChat} ORDER BY place LIMIT ?`)
|
|
518
506
|
.all(...ranked.params, ...where.params, execution.limit + 1);
|
|
519
507
|
await new Promise((resolve) => setImmediate(resolve));
|
|
520
508
|
check();
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { PRAGMAS } from "../driver.js";
|
|
2
2
|
import { refuseOwnerStoreInTests } from "../path.js";
|
|
3
|
+
import { timeQueries } from "../slow-queries.js";
|
|
3
4
|
import { quietSqliteWarning } from "../sqlite-warning.js";
|
|
4
5
|
import { countWrites, shareCounts } from "../write-events.js";
|
|
5
6
|
/**
|
|
@@ -28,6 +29,7 @@ const openUnderNode = async (path, readOnly) => {
|
|
|
28
29
|
try {
|
|
29
30
|
if (!readOnly)
|
|
30
31
|
countWrites(client, ["prepare"], () => client.isTransaction);
|
|
32
|
+
timeQueries(client, ["prepare"]);
|
|
31
33
|
const database = cacheOverNodeSqlite(client);
|
|
32
34
|
shareCounts(client, database);
|
|
33
35
|
return { database, orm: drizzle({ client }) };
|
|
@@ -44,6 +46,7 @@ const openUnderBun = async (path, readOnly) => {
|
|
|
44
46
|
try {
|
|
45
47
|
if (!readOnly)
|
|
46
48
|
countWrites(client, ["prepare", "query"], () => client.inTransaction);
|
|
49
|
+
timeQueries(client, ["prepare", "query"]);
|
|
47
50
|
const database = cacheOverBunSqlite(client);
|
|
48
51
|
shareCounts(client, database);
|
|
49
52
|
return { database, orm: drizzle({ client }) };
|
|
@@ -46,11 +46,13 @@ export interface Candidate {
|
|
|
46
46
|
* candidate by more than `NEAR_TIE`: every row nearer than that is among the candidates, and the rest cannot outrank
|
|
47
47
|
* them even where float32 and float64 disagree. A text many
|
|
48
48
|
* chunks share has one vector, so a tie that crosses the last candidate asks for more, as the scan's order decides it.
|
|
49
|
+
* With `nearestOnly` the most candidates are asked for at once and what they hold is the answer: across all chats the
|
|
50
|
+
* exact answer was rarely within them, and the scan that followed read every vector of the store (15 s cold).
|
|
49
51
|
*/
|
|
50
52
|
export declare const searchIndex: <T>(database: CacheDatabase, model: string, filter: IndexFilter, query: Float32Array, limit: number, survivors: (candidates: Candidate[]) => {
|
|
51
53
|
results: T[];
|
|
52
54
|
best: number[];
|
|
53
|
-
}) => T[] | undefined;
|
|
55
|
+
}, nearestOnly?: boolean) => T[] | undefined;
|
|
54
56
|
/**
|
|
55
57
|
* Per model, `store check`'s safety net: the rows its index holds against the rows `source` derives now, compared
|
|
56
58
|
* whole (chunk, kind, account, chat, time, hash, vector) both ways. `missing` are rows the index lacks or holds
|
|
@@ -137,12 +137,14 @@ BigInt(filter.account), ...[filter.chat, filter.since, filter.before].flatMap((v
|
|
|
137
137
|
* candidate by more than `NEAR_TIE`: every row nearer than that is among the candidates, and the rest cannot outrank
|
|
138
138
|
* them even where float32 and float64 disagree. A text many
|
|
139
139
|
* chunks share has one vector, so a tie that crosses the last candidate asks for more, as the scan's order decides it.
|
|
140
|
+
* With `nearestOnly` the most candidates are asked for at once and what they hold is the answer: across all chats the
|
|
141
|
+
* exact answer was rarely within them, and the scan that followed read every vector of the store (15 s cold).
|
|
140
142
|
*/
|
|
141
|
-
export const searchIndex = (database, model, filter, query, limit, survivors) => {
|
|
143
|
+
export const searchIndex = (database, model, filter, query, limit, survivors, nearestOnly = false) => {
|
|
142
144
|
const index = vectorIndexOf(database, model);
|
|
143
145
|
if (!index?.ready || index.dims !== query.length)
|
|
144
146
|
return undefined;
|
|
145
|
-
let k = Math.min(MAX_K, Math.max(100, limit * 4));
|
|
147
|
+
let k = nearestOnly ? MAX_K : Math.min(MAX_K, Math.max(100, limit * 4));
|
|
146
148
|
for (;;) {
|
|
147
149
|
const candidates = knn(database, index, filter, query, k);
|
|
148
150
|
const { results, best } = survivors(candidates);
|
|
@@ -155,7 +157,7 @@ export const searchIndex = (database, model, filter, query, limit, survivors) =>
|
|
|
155
157
|
if (best.length >= limit && best.every(nearer))
|
|
156
158
|
return results;
|
|
157
159
|
if (k === MAX_K)
|
|
158
|
-
return undefined;
|
|
160
|
+
return nearestOnly ? results : undefined;
|
|
159
161
|
k = Math.min(MAX_K, k * 4);
|
|
160
162
|
}
|
|
161
163
|
};
|
|
@@ -247,22 +247,31 @@ export const nearestChunks = (context, accountPk, filter) => {
|
|
|
247
247
|
keepBest(best, row);
|
|
248
248
|
const results = ranked([...best.values()]);
|
|
249
249
|
return { results, best: results.map(({ id }) => id) };
|
|
250
|
-
});
|
|
250
|
+
}, chatKey === undefined);
|
|
251
251
|
if (indexed)
|
|
252
252
|
return plain(indexed);
|
|
253
253
|
if (fromOwner) {
|
|
254
|
-
// The owner's chunks are few: find them by the owner's messages, then score only those.
|
|
255
|
-
|
|
254
|
+
// The owner's chunks are few: find them by the owner's messages, then score only those. The owner's own identity
|
|
255
|
+
// (the account's provider and id) leads, through the sender index: led by the chunks, SQLite read every message
|
|
256
|
+
// row of the account (0.7 GB, 17 s from a cold disk on a 954k-message store). An owner with no identity yet falls
|
|
257
|
+
// back to that.
|
|
258
|
+
const owned = (byIdentity) => orm
|
|
256
259
|
.all(sql `SELECT DISTINCT k.id FROM messages m
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
260
|
+
CROSS JOIN conversation_messages om ON om.message_id = m.id
|
|
261
|
+
CROSS JOIN conversations c ON c.id = om.conversation_id
|
|
262
|
+
JOIN conversation_state s ON s.chat_id = c.chat_id AND s.current_build = c.build
|
|
263
|
+
JOIN chats ch ON ch.id = c.chat_id
|
|
264
|
+
CROSS JOIN chunks k ON k.chunkable_type = 'conversation' AND k.chunkable_id = c.id
|
|
265
|
+
CROSS JOIN chunk_messages r ON r.chunk_id = k.id AND m.id BETWEEN r.first_message_id AND r.last_message_id
|
|
266
|
+
WHERE m.outgoing = 1 AND ch.account_id = ${accountPk}
|
|
267
|
+
${byIdentity
|
|
268
|
+
? sql `AND m.sender_identity_id IN (SELECT i.id FROM identities i JOIN accounts a
|
|
269
|
+
ON a.provider = i.provider AND a.external_id = i.external_id WHERE a.id = ${accountPk})`
|
|
270
|
+
: sql ``}
|
|
271
|
+
${chatKey === undefined ? sql `AND ch.searchable = 1` : sql `AND c.chat_id = ${chatKey}`}`)
|
|
265
272
|
.map(({ id }) => id);
|
|
273
|
+
const found = owned(true);
|
|
274
|
+
const ids = found.length ? found : owned(false);
|
|
266
275
|
const best = new Map();
|
|
267
276
|
for (const row of rows({ ids }))
|
|
268
277
|
keepBest(best, row);
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { CacheDatabase, SqlValue } from "../driver.js";
|
|
2
|
+
import type { Leaf } from "./lucene-fields.js";
|
|
3
|
+
/**
|
|
4
|
+
* Adds a `rarity(id, score)` set for an OR of words: each message scores the sum of log(N/df) over the query words it
|
|
5
|
+
* holds, df counting the messages that hold any form of the word. bm25 weighs every expanded form on its own, so one
|
|
6
|
+
* rare form of a common word ranked like a rare word, and short messages holding it outranked the answer. False when
|
|
7
|
+
* no word reads the word index, so there is nothing to rank by.
|
|
8
|
+
*/
|
|
9
|
+
export declare const withRarity: (database: CacheDatabase, words: string, leaves: Leaf[], ranked: {
|
|
10
|
+
sql: string[];
|
|
11
|
+
params: SqlValue[];
|
|
12
|
+
}) => boolean;
|
|
13
|
+
/** A fifth of bm25 keeps a message that holds a word many times from ranking only by which words it holds. */
|
|
14
|
+
export declare const RARITY_ORDER = "coalesce(rarity.score, 0) - 0.2 * coalesce(f.rank, 0) DESC, ";
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Adds a `rarity(id, score)` set for an OR of words: each message scores the sum of log(N/df) over the query words it
|
|
3
|
+
* holds, df counting the messages that hold any form of the word. bm25 weighs every expanded form on its own, so one
|
|
4
|
+
* rare form of a common word ranked like a rare word, and short messages holding it outranked the answer. False when
|
|
5
|
+
* no word reads the word index, so there is nothing to rank by.
|
|
6
|
+
*/
|
|
7
|
+
export const withRarity = (database, words, leaves, ranked) => {
|
|
8
|
+
const matches = [...new Set(leaves.flatMap(({ fragment }) => fragment.fts ?? []))];
|
|
9
|
+
if (!matches.length)
|
|
10
|
+
return false;
|
|
11
|
+
const total = Number(database.prepare(`SELECT count(*) AS n FROM ${words}_docsize`).get()?.n ?? 0);
|
|
12
|
+
const sets = matches.map((fts) => {
|
|
13
|
+
const match = `normalized_text : (${fts})`;
|
|
14
|
+
const df = Number(database.prepare(`SELECT count(*) AS n FROM ${words} WHERE ${words} MATCH ?`).get(match)?.n ?? 0);
|
|
15
|
+
ranked.params.push(match);
|
|
16
|
+
return `SELECT rowid AS id, ${df ? Math.log(total / df) : 0} AS w FROM ${words} WHERE ${words} MATCH ?`;
|
|
17
|
+
});
|
|
18
|
+
ranked.sql.push(`rarity(id, score) AS MATERIALIZED (SELECT id, sum(w) FROM (${sets.join(" UNION ALL ")}) GROUP BY id)`);
|
|
19
|
+
return true;
|
|
20
|
+
};
|
|
21
|
+
/** A fifth of bm25 keeps a message that holds a word many times from ranking only by which words it holds. */
|
|
22
|
+
export const RARITY_ORDER = "coalesce(rarity.score, 0) - 0.2 * coalesce(f.rank, 0) DESC, ";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wirecat/cli-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.718.0",
|
|
4
4
|
"description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Viacheslav Ptsarev",
|
|
@@ -330,7 +330,7 @@
|
|
|
330
330
|
"@types/pngjs": "6.0.5",
|
|
331
331
|
"@types/ssh2": "1.15.5",
|
|
332
332
|
"@vitest/coverage-v8": "^5.0.5",
|
|
333
|
-
"@wirecat/cli-base": "0.125.
|
|
333
|
+
"@wirecat/cli-base": "0.125.3",
|
|
334
334
|
"@wirecat/cli-core-legacy-tags": "npm:@wirecat/cli-core@0.414.0",
|
|
335
335
|
"ajv": "8.17.1",
|
|
336
336
|
"commander": "15.0.0",
|
package/parity.json
CHANGED
|
@@ -541,6 +541,10 @@
|
|
|
541
541
|
"--left": {
|
|
542
542
|
"meaning": "only the chats this account has left"
|
|
543
543
|
},
|
|
544
|
+
"--like": {
|
|
545
|
+
"value": "<text>",
|
|
546
|
+
"meaning": "a made-up example of the text sought, such as a reply that would answer the question, searched by meaning beside the query"
|
|
547
|
+
},
|
|
544
548
|
"--limit": {
|
|
545
549
|
"value": "<n>",
|
|
546
550
|
"meaning": "how many: rows to show, or messages one run fetches",
|
|
@@ -4275,6 +4279,7 @@
|
|
|
4275
4279
|
"--filter": {
|
|
4276
4280
|
"in": "all"
|
|
4277
4281
|
},
|
|
4282
|
+
"--like": "all",
|
|
4278
4283
|
"--limit": "all",
|
|
4279
4284
|
"--max-chats": {
|
|
4280
4285
|
"in": "all"
|