@wirecat/cli-core 0.734.0 → 0.736.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 +85 -0
- package/dist/background/daily-archive-timer.d.ts +1 -1
- package/dist/background/report/messages.d.ts +4 -0
- package/dist/background/report/messages.js +2 -0
- package/dist/background/report/templates/schedule-failed.email.en.liquid +2 -1
- package/dist/background/report/templates/schedule-failed.email.ru.liquid +2 -1
- package/dist/background/report/templates/schedule-failed.sample.json +2 -1
- package/dist/background/report/templates/schedule-failed.telegram.en.liquid +2 -1
- package/dist/background/report/templates/schedule-failed.telegram.ru.liquid +2 -1
- package/dist/background/report/templates/schedule-failed.text.en.liquid +2 -1
- package/dist/background/report/templates/schedule-failed.text.ru.liquid +2 -1
- package/dist/background/schedules.js +11 -7
- package/dist/cli/documents/file-edit.d.ts +4 -4
- package/dist/cli/documents/file-edit.js +69 -5
- package/dist/cli/enrichment-consents-command.js +2 -1
- package/dist/cli/messenger/catch-up-answers.js +1 -0
- package/dist/cli/messenger/download-command.js +3 -0
- package/dist/cli/messenger/inbox.js +4 -1
- package/dist/cli/messenger/review.js +4 -1
- package/dist/cli/messenger/search-answers.js +1 -0
- package/dist/cli/schedule/schedule-command.js +10 -1
- package/dist/cli/search-harder-consents-command.js +2 -1
- package/dist/cli/templates-command.js +7 -6
- package/dist/crm/cli/records.js +16 -1
- package/dist/domain/models.d.ts +4 -0
- package/dist/domain/providers.d.ts +7 -0
- package/dist/domain/providers.js +15 -2
- package/dist/entities/hit.d.ts +2 -0
- package/dist/entities/hit.js +2 -0
- package/dist/entities/index.d.ts +1 -0
- package/dist/errors/reasons.js +9 -2
- package/dist/office/create.d.ts +34 -0
- package/dist/office/create.js +216 -0
- package/dist/office/index.d.ts +1 -0
- package/dist/office/index.js +1 -0
- package/dist/office/package.d.ts +1 -0
- package/dist/office/package.js +1 -1
- package/dist/ports/messenger.d.ts +12 -1
- package/dist/search/word-match.d.ts +16 -0
- package/dist/search/word-match.js +28 -0
- package/dist/sends/upload.d.ts +3 -0
- package/dist/sends/upload.js +2 -2
- package/dist/services/documents/ingestion.js +4 -2
- package/dist/services/file-download.js +4 -2
- package/dist/services/inbox.d.ts +1 -1
- package/dist/services/inbox.js +6 -2
- package/dist/services/metadata.d.ts +1 -1
- package/dist/services/search-all.d.ts +2 -0
- package/dist/services/search-all.js +47 -17
- package/dist/store/sqlite/crm-rows.d.ts +4 -0
- package/dist/store/sqlite/crm-rows.js +30 -0
- package/dist/store/sqlite/crm.d.ts +2 -0
- package/dist/store/sqlite/crm.js +3 -10
- package/dist/store/sqlite/deals.js +1 -24
- package/dist/store/sqlite/tracker-chunks.d.ts +24 -8
- package/dist/store/sqlite/tracker-chunks.js +137 -38
- package/dist/store/sqlite/tracker.d.ts +5 -0
- package/dist/store/sqlite/tracker.js +118 -17
- package/dist/tracker/cli/index.js +1 -1
- package/package.json +1 -1
|
@@ -10,19 +10,52 @@ export const TRACKER_CHUNK = "tracker_item";
|
|
|
10
10
|
const CHUNKED = new Set(["issue", "project", "comment"]);
|
|
11
11
|
const CHUNKED_SQL = "('issue', 'project', 'comment')";
|
|
12
12
|
export const isChunkedTrackerKind = (kind) => CHUNKED.has(kind);
|
|
13
|
-
/**
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
13
|
+
/**
|
|
14
|
+
* A comment with fewer characters than this, spaces and line breaks around it aside, is not embedded: `LGTM`, `+1`,
|
|
15
|
+
* «Спасибо» say nothing alone, and with their issue in front each became a near copy of the issue that filled the
|
|
16
|
+
* first results (cli-testing performance/search/tracker-meaning). Its words still find it.
|
|
17
|
+
*/
|
|
18
|
+
export const SHORTEST_EMBEDDED_COMMENT = 16;
|
|
19
|
+
/** What the chunks hold; raised with each change to `textOf`, so a store cut before is cut again once. */
|
|
20
|
+
const CUT = "comments after their issue's key and title";
|
|
21
|
+
const CUT_SETTING = "tracker_chunks_cut";
|
|
22
|
+
const RECUT_AFTER = "tracker_chunks_recut_after";
|
|
23
|
+
// SQLite's `trim` and `length` take spaces and code points; JavaScript's `trim` takes more, and `length` counts halves.
|
|
24
|
+
const EDGE = /^[ \t\n\r]+|[ \t\n\r]+$/gu;
|
|
25
|
+
const embeddedComment = (body) => [...(body ?? "").replace(EDGE, "")].length >= SHORTEST_EMBEDDED_COMMENT;
|
|
26
|
+
const EDGE_SQL = "' ' || char(9, 10, 13)";
|
|
27
|
+
const EMBEDDED_COMMENT_SQL = `length(trim(coalesce(t.body, ''), ${EDGE_SQL})) >= ${SHORTEST_EMBEDDED_COMMENT}`;
|
|
28
|
+
/**
|
|
29
|
+
* What an item is embedded as, from its stored columns: chunk offsets point into it. A comment's issue goes in front:
|
|
30
|
+
* "it works now" means something only beside the issue it answers.
|
|
31
|
+
*/
|
|
32
|
+
const textOf = (kind, title, body, issue) => {
|
|
33
|
+
if (kind !== "comment")
|
|
34
|
+
return noteIndexText(title, body ?? "");
|
|
35
|
+
if (!embeddedComment(body))
|
|
36
|
+
return "";
|
|
37
|
+
const heading = issue ? [issue.key, issue.title].filter(Boolean).join(" ") : "";
|
|
38
|
+
return heading ? `${heading}\n\n${body}` : (body ?? "");
|
|
39
|
+
};
|
|
40
|
+
/** The issue a comment is on, as its account holds it; a deleted one still names what the comment answered. */
|
|
41
|
+
const issueOf = (database) => {
|
|
42
|
+
const read = database.prepare("SELECT title, json_extract(data, '$.key') AS key FROM tracker_items " +
|
|
43
|
+
"WHERE account_id = ? AND kind = 'issue' AND external_id = ?");
|
|
44
|
+
return (kind, accountId, parent) => {
|
|
45
|
+
if (kind !== "comment" || parent === null)
|
|
46
|
+
return undefined;
|
|
47
|
+
const row = read.get(accountId, parent);
|
|
48
|
+
return row ? { key: row.key == null ? null : String(row.key), title: String(row.title) } : undefined;
|
|
49
|
+
};
|
|
50
|
+
};
|
|
51
|
+
const piecesOf = (text) => {
|
|
19
52
|
if (!text.trim())
|
|
20
53
|
return [];
|
|
21
54
|
return splitText(text, CHUNK_CHARS).map(({ start, end }) => ({ start, end, hash: chunkHash(text.slice(start, end)) }));
|
|
22
55
|
};
|
|
23
56
|
/**
|
|
24
|
-
* Inside the caller's write: makes each item's chunks its text's, and answers the hashes it released
|
|
25
|
-
* when they already were. The caller drops the vectors of those once every new chunk is in, so a text another item or
|
|
57
|
+
* Inside the caller's write: makes each item's chunks its text's, and answers the hashes it released and how many
|
|
58
|
+
* chunks it wrote, or `undefined` when they already were. The caller drops the vectors of those once every new chunk is in, so a text another item or
|
|
26
59
|
* account still holds keeps its vector.
|
|
27
60
|
*/
|
|
28
61
|
export const trackerChunkWriter = (database) => {
|
|
@@ -31,8 +64,11 @@ export const trackerChunkWriter = (database) => {
|
|
|
31
64
|
const drop = database.prepare(`DELETE FROM chunks WHERE chunkable_type = '${TRACKER_CHUNK}' AND chunkable_id = ?`);
|
|
32
65
|
const insert = database.prepare("INSERT INTO chunks (chunkable_type, chunkable_id, position, start_offset, end_offset, content_hash, scope, " +
|
|
33
66
|
`account_id, occurred_at, created_at, updated_at) VALUES ('${TRACKER_CHUNK}', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
|
67
|
+
const issue = issueOf(database);
|
|
34
68
|
return (item, at) => {
|
|
35
|
-
|
|
69
|
+
if (!CHUNKED.has(item.kind))
|
|
70
|
+
return undefined;
|
|
71
|
+
const wanted = piecesOf(textOf(item.kind, item.title, item.body, issue(item.kind, item.accountId, item.parent)));
|
|
36
72
|
const before = held.all(item.id).map((row) => ({
|
|
37
73
|
start: Number(row.start),
|
|
38
74
|
end: Number(row.end),
|
|
@@ -49,7 +85,7 @@ export const trackerChunkWriter = (database) => {
|
|
|
49
85
|
wanted.forEach(({ start, end, hash }, position) => {
|
|
50
86
|
insert.run(item.id, position, start, end, hash, item.scope, item.accountId, item.occurredAt, at, at);
|
|
51
87
|
});
|
|
52
|
-
return before.map(({ hash }) => hash);
|
|
88
|
+
return { released: before.map(({ hash }) => hash), written: wanted.length };
|
|
53
89
|
};
|
|
54
90
|
};
|
|
55
91
|
/** Inside the caller's write: drops the chunks of these items and the vectors no other chunk holds. */
|
|
@@ -64,10 +100,23 @@ export const dropTrackerChunks = (database, ids) => {
|
|
|
64
100
|
dropUnusedVectors(database, released);
|
|
65
101
|
};
|
|
66
102
|
const BACKFILL = 200;
|
|
103
|
+
const chunkedOf = (row) => ({
|
|
104
|
+
id: Number(row.id),
|
|
105
|
+
accountId: Number(row.account_id),
|
|
106
|
+
kind: String(row.kind),
|
|
107
|
+
title: String(row.title),
|
|
108
|
+
body: row.body == null ? null : String(row.body),
|
|
109
|
+
parent: row.parent_id == null ? null : String(row.parent_id),
|
|
110
|
+
occurredAt: Number(row.at),
|
|
111
|
+
scope: row.scope == null ? null : String(row.scope),
|
|
112
|
+
});
|
|
113
|
+
const ITEM_COLUMNS = "t.id, t.account_id, t.kind, t.title, t.body, t.parent_id, coalesce(t.source_updated_at, t.synced_at) AS at, a.scope";
|
|
114
|
+
const setting = (database, key) => database.prepare("SELECT value FROM store_settings WHERE key = ?").get(key)?.value;
|
|
67
115
|
/**
|
|
68
|
-
* Drops the chunks of items the tracker no longer lists,
|
|
69
|
-
*
|
|
70
|
-
* deadline stops it with `left
|
|
116
|
+
* Drops the chunks of items the tracker no longer lists, cuts the comments of a store cut before the current `CUT`
|
|
117
|
+
* again, then cuts the chunks of live items that have none: those saved before tracker items were searched by meaning.
|
|
118
|
+
* Short write transactions, `until` asked before each, so a deadline stops it with `left` and the next run goes on
|
|
119
|
+
* from there; nothing under a read-only store.
|
|
71
120
|
*/
|
|
72
121
|
export const refreshTrackerChunks = (database, now, until = () => false) => {
|
|
73
122
|
if (isQueryOnly(database))
|
|
@@ -82,34 +131,64 @@ export const refreshTrackerChunks = (database, now, until = () => false) => {
|
|
|
82
131
|
dropUnusedVectors(database, gone);
|
|
83
132
|
return gone.length;
|
|
84
133
|
});
|
|
134
|
+
const chunk = trackerChunkWriter(database);
|
|
135
|
+
let added = 0;
|
|
136
|
+
// A store with no tracker chunks has nothing cut the old way: every chunk it gets is cut the current way.
|
|
137
|
+
if (setting(database, CUT_SETTING) !== CUT &&
|
|
138
|
+
!database.prepare(`SELECT 1 FROM chunks WHERE chunkable_type = '${TRACKER_CHUNK}' LIMIT 1`).get())
|
|
139
|
+
write(database, () => database
|
|
140
|
+
.prepare("INSERT OR REPLACE INTO store_settings (key, value, at) VALUES (?, ?, ?)")
|
|
141
|
+
.run(CUT_SETTING, CUT, now));
|
|
142
|
+
if (setting(database, CUT_SETTING) !== CUT) {
|
|
143
|
+
const comments = database.prepare(`SELECT ${ITEM_COLUMNS} FROM tracker_items t JOIN accounts a ON a.id = t.account_id
|
|
144
|
+
WHERE t.id > ? AND t.kind = 'comment' AND t.deleted_at IS NULL ORDER BY t.id LIMIT ?`);
|
|
145
|
+
const mark = database.prepare("INSERT OR REPLACE INTO store_settings (key, value, at) VALUES (?, ?, ?)");
|
|
146
|
+
let after = Number(setting(database, RECUT_AFTER) ?? 0);
|
|
147
|
+
for (;;) {
|
|
148
|
+
if (until())
|
|
149
|
+
return { dropped, added, left: true };
|
|
150
|
+
const rows = write(database, () => {
|
|
151
|
+
const found = comments.all(after, BACKFILL);
|
|
152
|
+
const released = [];
|
|
153
|
+
for (const row of found) {
|
|
154
|
+
const freed = chunk(chunkedOf(row), now);
|
|
155
|
+
if (freed?.written)
|
|
156
|
+
added += 1;
|
|
157
|
+
for (const hash of freed?.released ?? [])
|
|
158
|
+
released.push(hash);
|
|
159
|
+
}
|
|
160
|
+
dropUnusedVectors(database, released);
|
|
161
|
+
const last = found.at(-1);
|
|
162
|
+
if (found.length < BACKFILL) {
|
|
163
|
+
database.prepare("DELETE FROM store_settings WHERE key = ?").run(RECUT_AFTER);
|
|
164
|
+
mark.run(CUT_SETTING, CUT, now);
|
|
165
|
+
}
|
|
166
|
+
else if (last)
|
|
167
|
+
mark.run(RECUT_AFTER, String(last.id), now);
|
|
168
|
+
return found;
|
|
169
|
+
});
|
|
170
|
+
const last = rows.at(-1);
|
|
171
|
+
if (!last || rows.length < BACKFILL)
|
|
172
|
+
break;
|
|
173
|
+
after = Number(last.id);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
85
176
|
// An item with no text never gets a chunk: reading it again at every embed would find nothing.
|
|
86
|
-
const page = database.prepare(`SELECT
|
|
87
|
-
FROM tracker_items t JOIN accounts a ON a.id = t.account_id
|
|
177
|
+
const page = database.prepare(`SELECT ${ITEM_COLUMNS} FROM tracker_items t JOIN accounts a ON a.id = t.account_id
|
|
88
178
|
WHERE t.id > ? AND t.deleted_at IS NULL AND t.kind IN ${CHUNKED_SQL}
|
|
89
|
-
AND
|
|
179
|
+
AND CASE t.kind WHEN 'comment' THEN ${EMBEDDED_COMMENT_SQL}
|
|
180
|
+
ELSE trim(t.title || coalesce(t.body, '')) <> '' END
|
|
90
181
|
AND NOT EXISTS (SELECT 1 FROM chunks k WHERE k.chunkable_type = '${TRACKER_CHUNK}' AND k.chunkable_id = t.id)
|
|
91
182
|
ORDER BY t.id LIMIT ?`);
|
|
92
|
-
const chunk = trackerChunkWriter(database);
|
|
93
|
-
let added = 0;
|
|
94
183
|
let after = 0;
|
|
95
184
|
for (;;) {
|
|
96
185
|
if (until())
|
|
97
186
|
return { dropped, added, left: page.all(after, 1).length > 0 };
|
|
98
187
|
const rows = write(database, () => {
|
|
99
188
|
const found = page.all(after, BACKFILL);
|
|
100
|
-
for (const row of found)
|
|
101
|
-
|
|
102
|
-
id: Number(row.id),
|
|
103
|
-
accountId: Number(row.account_id),
|
|
104
|
-
kind: String(row.kind),
|
|
105
|
-
title: String(row.title),
|
|
106
|
-
body: row.body == null ? null : String(row.body),
|
|
107
|
-
occurredAt: Number(row.at),
|
|
108
|
-
scope: row.scope == null ? null : String(row.scope),
|
|
109
|
-
}, now);
|
|
110
|
-
if (written)
|
|
189
|
+
for (const row of found)
|
|
190
|
+
if (chunk(chunkedOf(row), now)?.written)
|
|
111
191
|
added += 1;
|
|
112
|
-
}
|
|
113
192
|
return found;
|
|
114
193
|
});
|
|
115
194
|
const last = rows.at(-1);
|
|
@@ -123,21 +202,41 @@ const LIVE = `k.chunkable_type = '${TRACKER_CHUNK}' AND EXISTS (SELECT 1 FROM tr
|
|
|
123
202
|
"AND t.deleted_at IS NULL)";
|
|
124
203
|
const UNEMBEDDED = `${LIVE} AND NOT EXISTS (SELECT 1 FROM embeddings v WHERE v.model = ? AND v.content_hash = k.content_hash)`;
|
|
125
204
|
export const trackerChunksLeft = (database, model) => Number(database.prepare(`SELECT count(DISTINCT k.content_hash) AS n FROM chunks k WHERE ${UNEMBEDDED}`).get(model)?.n ?? 0);
|
|
126
|
-
/**
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
205
|
+
/**
|
|
206
|
+
* Live items' chunks with no vector of `model`, by hash from `after`, each with its text cut again. A chunk whose text
|
|
207
|
+
* no longer hashes to its hash was cut another way, by an older build sharing the store: its item is cut again (never
|
|
208
|
+
* under a read-only store) and the chunk left out, so no vector is made of other text than its hash names.
|
|
209
|
+
*/
|
|
210
|
+
export const trackerChunksToEmbed = (database, model, { after, limit }, now = Date.now()) => {
|
|
211
|
+
const item = database.prepare(`SELECT ${ITEM_COLUMNS} FROM tracker_items t JOIN accounts a ON a.id = t.account_id WHERE t.id = ?`);
|
|
212
|
+
const issue = issueOf(database);
|
|
213
|
+
const stale = [];
|
|
214
|
+
const found = database
|
|
130
215
|
.prepare(`SELECT k.content_hash AS hash, min(k.chunkable_id) AS owner, k.start_offset AS start, k.end_offset AS end
|
|
131
216
|
FROM chunks k WHERE k.content_hash > ? AND ${UNEMBEDDED}
|
|
132
217
|
GROUP BY k.content_hash ORDER BY k.content_hash LIMIT ?`)
|
|
133
218
|
.all(after ?? "", model, limit)
|
|
134
219
|
.flatMap((row) => {
|
|
135
|
-
const
|
|
136
|
-
if (!
|
|
220
|
+
const owner = item.get(Number(row.owner));
|
|
221
|
+
if (!owner)
|
|
137
222
|
return [];
|
|
138
|
-
const
|
|
139
|
-
|
|
223
|
+
const { kind, title, body, accountId, parent } = chunkedOf(owner);
|
|
224
|
+
const text = textOf(kind, title, body, issue(kind, accountId, parent)).slice(Number(row.start), Number(row.end));
|
|
225
|
+
if (chunkHash(text) === String(row.hash))
|
|
226
|
+
return [{ hash: String(row.hash), text }];
|
|
227
|
+
stale.push(owner);
|
|
228
|
+
return [];
|
|
140
229
|
});
|
|
230
|
+
if (stale.length && !isQueryOnly(database))
|
|
231
|
+
write(database, () => {
|
|
232
|
+
const chunk = trackerChunkWriter(database);
|
|
233
|
+
const released = [];
|
|
234
|
+
for (const owner of stale)
|
|
235
|
+
for (const hash of chunk(chunkedOf(owner), now)?.released ?? [])
|
|
236
|
+
released.push(hash);
|
|
237
|
+
dropUnusedVectors(database, released);
|
|
238
|
+
});
|
|
239
|
+
return found;
|
|
141
240
|
};
|
|
142
241
|
export const trackerEmbedded = (database, model, accountIds) => accountIds.length > 0 &&
|
|
143
242
|
database
|
|
@@ -74,9 +74,14 @@ export interface TrackerStore {
|
|
|
74
74
|
items: TrackerItem<K>[];
|
|
75
75
|
hasMore: boolean;
|
|
76
76
|
}>;
|
|
77
|
+
/**
|
|
78
|
+
* Issues, projects and comments by their words. `capped`: the index offered more rows than are read for one search,
|
|
79
|
+
* so a later row holding the words may be left out; `hasMore` is set while the page found any.
|
|
80
|
+
*/
|
|
77
81
|
find(search: TrackerSearch): Promise<{
|
|
78
82
|
items: TrackerHit[];
|
|
79
83
|
hasMore: boolean;
|
|
84
|
+
capped?: true;
|
|
80
85
|
}>;
|
|
81
86
|
/** Live rows of the kind, archived ones included. */
|
|
82
87
|
count(key: AccountKey, kind: TrackerKind): Promise<number>;
|
|
@@ -1,11 +1,16 @@
|
|
|
1
1
|
import { trackerBodyOf, trackerParentOf, trackerTitleOf, } from "../../domain/tracker.js";
|
|
2
|
+
import { START_LETTERS } from "../../search/stem.js";
|
|
3
|
+
import { clauseIn, probeOf, tokensOf, wordMatches, } from "../../search/word-match.js";
|
|
2
4
|
import { fold, normalize } from "../normalize.js";
|
|
3
5
|
import { accountPk, findAccountPk } from "./accounts.js";
|
|
4
|
-
import { excerptOf
|
|
6
|
+
import { excerptOf } from "./crm-files.js";
|
|
5
7
|
import { dropTrackerChunks, isChunkedTrackerKind, nearestTrackerItems, refreshTrackerChunks, trackerChunksLeft, trackerChunksToEmbed, trackerChunkWriter, trackerEmbedded, } from "./tracker-chunks.js";
|
|
6
8
|
import { write } from "./transaction.js";
|
|
7
9
|
import { dropUnusedVectors } from "./vector-index.js";
|
|
8
10
|
const MOST = 500;
|
|
11
|
+
/** How many rows the index may offer one search; each is read and its words checked. */
|
|
12
|
+
const CANDIDATES = 2_000;
|
|
13
|
+
const PAGE = 200;
|
|
9
14
|
const itemOf = (row) => ({
|
|
10
15
|
kind: String(row.kind),
|
|
11
16
|
record: JSON.parse(String(row.data)),
|
|
@@ -33,7 +38,40 @@ export const resetTrackerItemWords = (database) => {
|
|
|
33
38
|
return Number(changes);
|
|
34
39
|
});
|
|
35
40
|
};
|
|
41
|
+
const keyOf = (data) => data == null ? undefined : JSON.parse(String(data)).key;
|
|
36
42
|
const ISSUE_FIELDS = { assignee: "assignee", project: "project", state: "state" };
|
|
43
|
+
/**
|
|
44
|
+
* The words as clauses for `clauseIn`, and the index expression that finds the rows they could match: a word, a word
|
|
45
|
+
* it begins, or a word that begins with its stem. A Snowball stem begins its word, but for the English `y` it turns to
|
|
46
|
+
* `i` (`compani`), so a stem ending in `i` is looked up without it.
|
|
47
|
+
*/
|
|
48
|
+
const queryOf = (words, exact) => {
|
|
49
|
+
const seen = new Set();
|
|
50
|
+
const clauses = words
|
|
51
|
+
.map((word) => tokensOf(word).filter((token) => fold(token)))
|
|
52
|
+
.filter((tokens) => {
|
|
53
|
+
const key = tokens.map(fold).join(" ");
|
|
54
|
+
if (!tokens.length || seen.has(key))
|
|
55
|
+
return false;
|
|
56
|
+
seen.add(key);
|
|
57
|
+
return true;
|
|
58
|
+
})
|
|
59
|
+
.map((tokens) => tokens.map((token) => [probeOf(token)]));
|
|
60
|
+
if (!clauses.length)
|
|
61
|
+
return undefined;
|
|
62
|
+
const termOf = ({ literal, stems }) => {
|
|
63
|
+
const terms = new Set([exact || literal.length < START_LETTERS ? `"${literal}"` : `"${literal}"*`]);
|
|
64
|
+
if (!exact)
|
|
65
|
+
for (const stem of stems) {
|
|
66
|
+
const start = stem.endsWith("i") ? stem.slice(0, -1) : stem;
|
|
67
|
+
if (start.length >= 3)
|
|
68
|
+
terms.add(`"${start}"*`);
|
|
69
|
+
}
|
|
70
|
+
return terms.size > 1 ? `(${[...terms].join(" OR ")})` : [...terms].join("");
|
|
71
|
+
};
|
|
72
|
+
const expressions = clauses.map((clause) => `(${clause.flatMap((word) => word.map(termOf)).join(" AND ")})`);
|
|
73
|
+
return { clauses, match: (anyWord) => expressions.join(anyWord ? " OR " : " AND ") };
|
|
74
|
+
};
|
|
37
75
|
export const trackerStoreOver = (context) => {
|
|
38
76
|
const { database } = context;
|
|
39
77
|
const save = (key, kind, records, now) => write(database, () => {
|
|
@@ -43,6 +81,8 @@ export const trackerStoreOver = (context) => {
|
|
|
43
81
|
const chunked = isChunkedTrackerKind(kind);
|
|
44
82
|
const chunk = trackerChunkWriter(database);
|
|
45
83
|
const released = [];
|
|
84
|
+
const comments = database.prepare("SELECT id, title, body, coalesce(source_updated_at, synced_at) AS at FROM tracker_items " +
|
|
85
|
+
"WHERE account_id = ? AND kind = 'comment' AND parent_id = ? AND deleted_at IS NULL");
|
|
46
86
|
const upsert = database.prepare("INSERT INTO tracker_items (account_id, kind, external_id, parent_id, title, title_folded, body, " +
|
|
47
87
|
"normalized_text, data, source_created_at, source_updated_at, archived_at, deleted_at, synced_at) " +
|
|
48
88
|
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?) " +
|
|
@@ -63,6 +103,26 @@ export const trackerStoreOver = (context) => {
|
|
|
63
103
|
const saved = upsert.get(accountId, kind, merged.externalId, trackerParentOf(kind, merged) ?? null, title, fold(title), body, normalize([title, body].filter(Boolean).join("\n")), JSON.stringify(merged), merged.createdAt ?? null, merged.updatedAt ?? null, merged.archivedAt ?? null, now);
|
|
64
104
|
// Most rows of a sync come back with the text they had; their chunks stay, and only a revived row needs new.
|
|
65
105
|
const same = before?.deleted_at == null && before?.title === title && (before?.body ?? null) === body;
|
|
106
|
+
// A comment is embedded after its issue's key and title, so a new, revived, renamed or moved issue cuts its
|
|
107
|
+
// comments again.
|
|
108
|
+
if (kind === "issue" &&
|
|
109
|
+
(before?.deleted_at !== null ||
|
|
110
|
+
before.title !== title ||
|
|
111
|
+
keyOf(before.data) !== merged.key))
|
|
112
|
+
for (const row of comments.all(accountId, merged.externalId)) {
|
|
113
|
+
const freed = chunk({
|
|
114
|
+
id: Number(row.id),
|
|
115
|
+
accountId,
|
|
116
|
+
kind: "comment",
|
|
117
|
+
title: String(row.title),
|
|
118
|
+
body: row.body == null ? null : String(row.body),
|
|
119
|
+
parent: merged.externalId,
|
|
120
|
+
occurredAt: Number(row.at),
|
|
121
|
+
scope: scope == null ? null : String(scope),
|
|
122
|
+
}, now);
|
|
123
|
+
for (const hash of freed?.released ?? [])
|
|
124
|
+
released.push(hash);
|
|
125
|
+
}
|
|
66
126
|
if (!chunked || same)
|
|
67
127
|
continue;
|
|
68
128
|
const freed = chunk({
|
|
@@ -71,10 +131,11 @@ export const trackerStoreOver = (context) => {
|
|
|
71
131
|
kind,
|
|
72
132
|
title,
|
|
73
133
|
body,
|
|
134
|
+
parent: trackerParentOf(kind, merged) ?? null,
|
|
74
135
|
occurredAt: merged.updatedAt ?? now,
|
|
75
136
|
scope: scope == null ? null : String(scope),
|
|
76
137
|
}, now);
|
|
77
|
-
for (const hash of freed ?? [])
|
|
138
|
+
for (const hash of freed?.released ?? [])
|
|
78
139
|
released.push(hash);
|
|
79
140
|
}
|
|
80
141
|
dropUnusedVectors(database, released);
|
|
@@ -149,16 +210,15 @@ export const trackerStoreOver = (context) => {
|
|
|
149
210
|
return { items: rows.slice(0, limit).map((row) => itemOf(row)), hasMore: rows.length > limit };
|
|
150
211
|
};
|
|
151
212
|
const find = ({ words, anyWord = false, exact = false, accounts, kinds, limit, offset = 0 }) => {
|
|
152
|
-
const
|
|
153
|
-
if (!
|
|
213
|
+
const query = queryOf(words, exact);
|
|
214
|
+
if (!query)
|
|
154
215
|
return { items: [], hasMore: false };
|
|
155
216
|
const most = Math.min(Math.max(limit ?? 100, 1), MOST);
|
|
156
217
|
const scoped = accounts?.map((one) => findAccountPk(context, one)).filter((one) => one !== undefined) ?? [];
|
|
157
218
|
if (accounts !== undefined && !scoped.length)
|
|
158
219
|
return { items: [], hasMore: false };
|
|
159
|
-
const params = [match];
|
|
160
|
-
let sql =
|
|
161
|
-
"JOIN accounts a ON a.id = t.account_id " +
|
|
220
|
+
const params = [query.match(anyWord)];
|
|
221
|
+
let sql = "SELECT t.id FROM tracker_items t " +
|
|
162
222
|
"JOIN (SELECT rowid, rank FROM tracker_item_words WHERE tracker_item_words MATCH ?) w ON w.rowid = t.id " +
|
|
163
223
|
"WHERE t.deleted_at IS NULL";
|
|
164
224
|
if (accounts !== undefined) {
|
|
@@ -171,16 +231,57 @@ export const trackerStoreOver = (context) => {
|
|
|
171
231
|
for (const kind of kinds)
|
|
172
232
|
params.push(kind);
|
|
173
233
|
}
|
|
174
|
-
sql += " ORDER BY w.rank, t.source_updated_at DESC, t.id DESC LIMIT ?
|
|
175
|
-
|
|
176
|
-
|
|
234
|
+
sql += " ORDER BY w.rank, t.source_updated_at DESC, t.id DESC LIMIT ?";
|
|
235
|
+
// One read of the index for the ids, then the rows in pages: paging the ranked query by OFFSET ranks it again for
|
|
236
|
+
// every page.
|
|
237
|
+
const ids = database
|
|
238
|
+
.prepare(sql)
|
|
239
|
+
.all(...params, CANDIDATES + 1)
|
|
240
|
+
.map(({ id }) => Number(id));
|
|
241
|
+
const capped = ids.length > CANDIDATES;
|
|
242
|
+
const rowsOf = database.prepare(`SELECT ${COLUMNS}, t.id, t.title, t.body, a.provider, a.external_id AS account FROM tracker_items t ` +
|
|
243
|
+
"JOIN accounts a ON a.id = t.account_id WHERE t.id IN (SELECT value FROM json_each(?))");
|
|
244
|
+
const wanted = offset + most + 1;
|
|
245
|
+
const found = [];
|
|
246
|
+
let read = 0;
|
|
247
|
+
// Each candidate's own words decide. All words matched rank by the index alone, so the reading stops once the page
|
|
248
|
+
// is full; some of them rank by how many matched first, over every candidate.
|
|
249
|
+
for (let at = 0; at < Math.min(ids.length, CANDIDATES); at += PAGE) {
|
|
250
|
+
if (!anyWord && found.length >= wanted)
|
|
251
|
+
break;
|
|
252
|
+
const batch = ids.slice(at, Math.min(at + PAGE, CANDIDATES));
|
|
253
|
+
const byId = new Map(rowsOf.all(JSON.stringify(batch)).map((row) => [Number(row.id), row]));
|
|
254
|
+
for (const id of batch) {
|
|
255
|
+
const row = byId.get(id);
|
|
256
|
+
if (!row)
|
|
257
|
+
continue;
|
|
258
|
+
read += 1;
|
|
259
|
+
const held = tokensOf([row.title, row.body].filter(Boolean).join("\n")).map((token) => ({
|
|
260
|
+
token,
|
|
261
|
+
literal: fold(token),
|
|
262
|
+
}));
|
|
263
|
+
const hit = query.clauses.filter((clause) => clauseIn(clause, held, exact));
|
|
264
|
+
if (anyWord ? hit.length > 0 : hit.length === query.clauses.length)
|
|
265
|
+
found.push({ row, held, hit, score: hit.length, at: read });
|
|
266
|
+
if (!anyWord && found.length >= wanted)
|
|
267
|
+
break;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
const rows = found.sort((a, b) => b.score - a.score || a.at - b.at).slice(offset, wanted);
|
|
177
271
|
return {
|
|
178
|
-
items: rows.slice(0, most).map((row) =>
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
272
|
+
items: rows.slice(0, most).map(({ row, held, hit }) => {
|
|
273
|
+
const matched = held
|
|
274
|
+
.filter((word) => hit.some((clause) => clause.some((one) => one.some((probe) => wordMatches(probe, word, exact)))))
|
|
275
|
+
.map(({ token }) => token);
|
|
276
|
+
return {
|
|
277
|
+
account: { provider: String(row.provider), account: String(row.account) },
|
|
278
|
+
item: itemOf(row),
|
|
279
|
+
excerpt: excerptOf([row.title, row.body].filter(Boolean).join("\n"), [...words, ...matched]),
|
|
280
|
+
};
|
|
281
|
+
}),
|
|
282
|
+
// A capped search may hold more past what was read; an empty page ends the paging.
|
|
283
|
+
hasMore: rows.length > most || (capped && rows.length > 0),
|
|
284
|
+
...(capped ? { capped: true } : {}),
|
|
184
285
|
};
|
|
185
286
|
};
|
|
186
287
|
const accountIdsOf = (accounts) => accounts.flatMap((one) => {
|
|
@@ -248,7 +349,7 @@ export const trackerStoreOver = (context) => {
|
|
|
248
349
|
}));
|
|
249
350
|
},
|
|
250
351
|
refreshChunks: async ({ until } = {}) => refreshTrackerChunks(database, context.now(), until),
|
|
251
|
-
chunksToEmbed: async (model, options) => trackerChunksToEmbed(database, model, options),
|
|
352
|
+
chunksToEmbed: async (model, options) => trackerChunksToEmbed(database, model, options, context.now()),
|
|
252
353
|
chunksLeft: async (model) => trackerChunksLeft(database, model),
|
|
253
354
|
embedded: async (model, accounts) => trackerEmbedded(database, model, accountIdsOf(accounts).map(({ id }) => id)),
|
|
254
355
|
nearest: async (model, query, { limit, accounts }) => nearest(model, query, limit, accounts),
|
|
@@ -445,7 +445,7 @@ const addTrackerCommandsDefinition = (program, options) => {
|
|
|
445
445
|
});
|
|
446
446
|
example(paging(answerEntity(annotate(issues.command("search"), { effects: LOCAL_READ }), "tracker_hit", trackerView)
|
|
447
447
|
.description("find issues, projects and comments in the copy by their words")
|
|
448
|
-
.argument("<words...>", "every word must match;
|
|
448
|
+
.argument("<words...>", "every word must match, in any form; a word of four letters or more finds the words it begins")), 'issues search "invoice currency"').action(async (words, opts, command) => {
|
|
449
449
|
await within(command, true, async (run) => {
|
|
450
450
|
const found = await run.store.tracker.find({
|
|
451
451
|
words,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wirecat/cli-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.736.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",
|