@wirecat/cli-core 0.729.0 → 0.731.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/background/daily-archive-timer.d.ts +1 -1
- package/dist/cli/documents/catalog.js +6 -3
- package/dist/cli/documents/documents.js +3 -2
- package/dist/cli/documents/file-conflicts.js +15 -2
- package/dist/cli/documents/file-edit.js +7 -2
- package/dist/cli/documents/folders.js +2 -1
- package/dist/cli/documents/history.js +3 -2
- package/dist/cli/documents/index.d.ts +1 -0
- package/dist/cli/documents/index.js +1 -0
- package/dist/cli/documents/knowledge.js +6 -2
- package/dist/cli/documents/library.js +9 -2
- package/dist/cli/documents/search.js +4 -1
- package/dist/cli/untrusted-marks.d.ts +10 -0
- package/dist/cli/untrusted-marks.js +19 -0
- package/dist/documents/model.d.ts +2 -0
- package/dist/domain/tracker.d.ts +2 -0
- package/dist/domain/tracker.js +2 -0
- package/dist/services/documents/plan.js +36 -10
- package/dist/services/index.d.ts +1 -0
- package/dist/services/index.js +1 -0
- package/dist/services/notes-search.d.ts +13 -2
- package/dist/services/notes-search.js +2 -2
- package/dist/services/search-all.d.ts +5 -0
- package/dist/services/search-all.js +76 -6
- package/dist/services/tracker-meaning.d.ts +17 -0
- package/dist/services/tracker-meaning.js +27 -0
- package/dist/store/exports.d.ts +1 -1
- package/dist/store/sqlite/tracker-chunks.d.ts +52 -0
- package/dist/store/sqlite/tracker-chunks.js +190 -0
- package/dist/store/sqlite/tracker.d.ts +37 -0
- package/dist/store/sqlite/tracker.js +50 -4
- package/dist/tracker/cli/index.d.ts +6 -3
- package/dist/tracker/cli/index.js +82 -12
- package/dist/tracker/cli/writes.d.ts +2 -2
- package/dist/tracker/cli/writes.js +18 -12
- package/dist/tracker/writer.d.ts +1 -1
- package/dist/tracker/writer.js +3 -4
- package/dist/tracker/writes.d.ts +1 -1
- package/dist/tracker/writes.js +14 -13
- package/package.json +2 -2
|
@@ -5,16 +5,17 @@ import { hitFiles } from "../domain/attachments.js";
|
|
|
5
5
|
import { parseLocator } from "../domain/locator.js";
|
|
6
6
|
import { senderIsMe } from "../domain/models.js";
|
|
7
7
|
import { holdsKind, INTERNAL_NOTES, isDocumentAccountProvider } from "../domain/providers.js";
|
|
8
|
-
import { trackerTitleOf } from "../domain/tracker.js";
|
|
8
|
+
import { trackerBodyOf, trackerTitleOf } from "../domain/tracker.js";
|
|
9
9
|
import { runEmbedders } from "../embeddings/embed.js";
|
|
10
10
|
import { chosenTextModel } from "../embeddings/models.js";
|
|
11
11
|
import { formatMeetingReference } from "../meetings/index.js";
|
|
12
12
|
import { entriesOfList, fitting, listedHolds } from "../search/account-list.js";
|
|
13
13
|
import { RRF_K } from "../search/fusion.js";
|
|
14
|
+
import { meaningWords } from "../search/lucene/meaning-parts.js";
|
|
14
15
|
import { plainQuery } from "../search/lucene/plain.js";
|
|
15
16
|
import { MESSAGE_PARSING, SEARCH_QUERY } from "../search/lucene/types.js";
|
|
16
17
|
import { questionPeriod } from "../search/question-period.js";
|
|
17
|
-
import { planQuestion, questionLookup } from "../search/question-plan.js";
|
|
18
|
+
import { planQuestion, questionLookup, questionText } from "../search/question-plan.js";
|
|
18
19
|
import { calendarAccounts, searchEvents } from "./events-search.js";
|
|
19
20
|
import { excerpt } from "./excerpt.js";
|
|
20
21
|
import { MAX_SEARCH_OFFSET, searchStore } from "./messages-archive-search.js";
|
|
@@ -24,6 +25,7 @@ import { BUSINESS_WORDS_ONLY, searchBusiness } from "./search-all-business.js";
|
|
|
24
25
|
import { meetingLane } from "./search-all-meetings.js";
|
|
25
26
|
import { HARDER_CANDIDATES, reorderHarder } from "./search-harder.js";
|
|
26
27
|
import { listContextOf } from "./search-kind.js";
|
|
28
|
+
import { nearestTracker } from "./tracker-meaning.js";
|
|
27
29
|
export const RESOURCES_SEARCHED = [
|
|
28
30
|
"messages",
|
|
29
31
|
"mail",
|
|
@@ -146,6 +148,23 @@ const trackerTitle = ({ kind, record }) => {
|
|
|
146
148
|
const key = kind === "issue" ? record.key : undefined;
|
|
147
149
|
return key ? `${key} ${title}` : title;
|
|
148
150
|
};
|
|
151
|
+
/**
|
|
152
|
+
* What the meaning half embeds: the words and phrases asked for, OR included, as notes take them. `title:` narrows to
|
|
153
|
+
* the title, which a hit by meaning cannot be held to, so such a query is searched by words only.
|
|
154
|
+
*/
|
|
155
|
+
const trackerMeaningWords = (text) => {
|
|
156
|
+
try {
|
|
157
|
+
const { root } = parseLucene(text, SEARCH_QUERY);
|
|
158
|
+
const nodes = root.kind === "boolean" ? root.clauses.map(({ node }) => node) : [root];
|
|
159
|
+
if (!nodes.every((node) => node.kind === "predicate" && node.field === "text"))
|
|
160
|
+
return undefined;
|
|
161
|
+
return meaningWords(root) || undefined;
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
return undefined;
|
|
165
|
+
}
|
|
166
|
+
};
|
|
167
|
+
const trackerExcerpt = ({ kind, record }, query) => excerpt([trackerTitleOf(kind, record), trackerBodyOf(kind, record)].filter(Boolean).join("\n"), query);
|
|
149
168
|
/** The accounts of every CRM the store holds copies of. */
|
|
150
169
|
export const crmAccounts = async (store) => (await store.accounts.accounts()).filter(({ provider }) => holdsKind(provider, "crm"));
|
|
151
170
|
/**
|
|
@@ -178,6 +197,7 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
|
|
|
178
197
|
let hasMore = false;
|
|
179
198
|
let notes;
|
|
180
199
|
let events;
|
|
200
|
+
let tracker;
|
|
181
201
|
const by = {};
|
|
182
202
|
let server;
|
|
183
203
|
// Every word of a sentence is rarely in one record: a question finds what holds some of them, as `--discover` does.
|
|
@@ -423,7 +443,7 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
|
|
|
423
443
|
const read = scope?.tracker ?? (await trackerAccounts(store));
|
|
424
444
|
if (!read.length)
|
|
425
445
|
continue;
|
|
426
|
-
const { words, anyWord } = titleWords(request.text, "issues, projects and comments are found by the words of their title and text only");
|
|
446
|
+
const { words, anyWord } = titleWords(request.text, "issues, projects and comments are found by the words and meaning of their title and text only");
|
|
427
447
|
const found = await store.tracker.find({
|
|
428
448
|
words,
|
|
429
449
|
anyWord: anyWord || discover,
|
|
@@ -433,7 +453,7 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
|
|
|
433
453
|
accounts: read,
|
|
434
454
|
});
|
|
435
455
|
hasMore ||= found.hasMore;
|
|
436
|
-
|
|
456
|
+
const hitOf = (at, item, text, foundBy) => ({
|
|
437
457
|
kind: TRACKER_HIT_KINDS[item.kind],
|
|
438
458
|
// Two sign-ins see the same issue under the same id, so the account keeps their hits apart.
|
|
439
459
|
ref: `tracker:${at.provider}/${at.account}/${item.kind}/${item.record.externalId}`,
|
|
@@ -443,8 +463,57 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
|
|
|
443
463
|
title: trackerTitle(item),
|
|
444
464
|
timestamp: new Date(item.record.updatedAt ?? item.syncedAt).toISOString(),
|
|
445
465
|
text,
|
|
446
|
-
foundBy
|
|
447
|
-
})
|
|
466
|
+
foundBy,
|
|
467
|
+
});
|
|
468
|
+
const byWords = found.items.map(({ account: at, item, excerpt: text }) => hitOf(at, item, text, ["words"]));
|
|
469
|
+
const plain = trackerMeaningWords(discover ? questionText(request.text) : request.text);
|
|
470
|
+
let near;
|
|
471
|
+
let meaningSkipped;
|
|
472
|
+
if (request.exact)
|
|
473
|
+
meaningSkipped = "--exact searches words as written";
|
|
474
|
+
else if (plain === undefined)
|
|
475
|
+
meaningSkipped = "the query names a title, which meaning cannot follow";
|
|
476
|
+
else
|
|
477
|
+
try {
|
|
478
|
+
near = await nearestTracker(store, plain, {
|
|
479
|
+
limit: Math.min(depth, 500),
|
|
480
|
+
accounts: read,
|
|
481
|
+
embedders,
|
|
482
|
+
...(command === undefined ? {} : { command }),
|
|
483
|
+
...(request.env === undefined ? {} : { env: request.env }),
|
|
484
|
+
});
|
|
485
|
+
}
|
|
486
|
+
catch (error) {
|
|
487
|
+
if (!(error instanceof CliError && error.code === "not_found"))
|
|
488
|
+
throw error;
|
|
489
|
+
meaningSkipped = error.message;
|
|
490
|
+
}
|
|
491
|
+
tracker = {
|
|
492
|
+
by: near === undefined ? "words" : "words and meaning",
|
|
493
|
+
...(meaningSkipped === undefined ? {} : { meaningSkipped }),
|
|
494
|
+
};
|
|
495
|
+
if (near === undefined)
|
|
496
|
+
lists.push(byWords);
|
|
497
|
+
else {
|
|
498
|
+
// As notes and messages fuse theirs: one list for the lane, a question's hit voting once.
|
|
499
|
+
const fused = new Map();
|
|
500
|
+
byWords.forEach((item, rank) => {
|
|
501
|
+
fused.set(item.ref, { item, score: 1 / (RRF_K + rank + 1) });
|
|
502
|
+
});
|
|
503
|
+
near.forEach(({ account: at, item, score }, rank) => {
|
|
504
|
+
const hit = hitOf(at, item, trackerExcerpt(item, request.text), ["meaning"]);
|
|
505
|
+
cosines.set(hit.ref, score);
|
|
506
|
+
const held = fused.get(hit.ref);
|
|
507
|
+
if (held)
|
|
508
|
+
held.item.foundBy = ["words", "meaning"];
|
|
509
|
+
const vote = 1 / (RRF_K + rank + 1);
|
|
510
|
+
if (held && discover)
|
|
511
|
+
held.score = Math.max(held.score, vote);
|
|
512
|
+
else
|
|
513
|
+
fused.set(hit.ref, { item: held?.item ?? hit, score: (held?.score ?? 0) + vote });
|
|
514
|
+
});
|
|
515
|
+
lists.push([...fused.values()].sort((a, b) => b.score - a.score).map(({ item }) => item));
|
|
516
|
+
}
|
|
448
517
|
for (const { provider, account } of read)
|
|
449
518
|
accounts.push({ resource, provider, account });
|
|
450
519
|
}
|
|
@@ -533,6 +602,7 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
|
|
|
533
602
|
skipped,
|
|
534
603
|
...(notes === undefined ? {} : { notes }),
|
|
535
604
|
...(events === undefined ? {} : { events }),
|
|
605
|
+
...(tracker === undefined ? {} : { tracker }),
|
|
536
606
|
...(by.messages === undefined ? {} : { messages: by.messages }),
|
|
537
607
|
...(by.mail === undefined ? {} : { mail: by.mail }),
|
|
538
608
|
...(server === undefined ? {} : { server }),
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { AccountKey, MessageStore, TrackerNearest } from "../store/store.js";
|
|
2
|
+
import { type NearestOptions, type NotesEmbedOptions } from "./notes-search.js";
|
|
3
|
+
/**
|
|
4
|
+
* Embeds issues', projects' and comments' chunks as notes' are embedded. Items gone since lose theirs first, and items
|
|
5
|
+
* saved before tracker items were searched by meaning get theirs.
|
|
6
|
+
*/
|
|
7
|
+
export declare const embedTracker: (store: MessageStore, options?: NotesEmbedOptions & {
|
|
8
|
+
command?: string;
|
|
9
|
+
}) => Promise<import("./notes-search.js").NotesEmbedded>;
|
|
10
|
+
/**
|
|
11
|
+
* Issues, projects and comments of these accounts nearest in meaning to plain words, nearer than the model's floor,
|
|
12
|
+
* best first; only items already embedded are found.
|
|
13
|
+
*/
|
|
14
|
+
export declare const nearestTracker: (store: MessageStore, words: string, { limit, accounts, env, command, embedders, }: Pick<NearestOptions, "env" | "command" | "embedders"> & {
|
|
15
|
+
limit: number;
|
|
16
|
+
accounts: readonly AccountKey[];
|
|
17
|
+
}) => Promise<TrackerNearest[]>;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { meaningFloor } from "../embeddings/models.js";
|
|
3
|
+
import { meaningModel } from "./meaning-model.js";
|
|
4
|
+
import { embedChunks, localModel, stopsAt, withLocal, } from "./notes-search.js";
|
|
5
|
+
/**
|
|
6
|
+
* Embeds issues', projects' and comments' chunks as notes' are embedded. Items gone since lose theirs first, and items
|
|
7
|
+
* saved before tracker items were searched by meaning get theirs.
|
|
8
|
+
*/
|
|
9
|
+
export const embedTracker = async (store, options = {}) => {
|
|
10
|
+
// A missing model fails before anything is written; the refresh stops where the embedding would.
|
|
11
|
+
localModel(options.model, options.env, options.command);
|
|
12
|
+
const until = stopsAt(options.deadline);
|
|
13
|
+
await store.tracker.refreshChunks({ until: () => options.signal?.aborted === true || Date.now() >= until });
|
|
14
|
+
return embedChunks(store, store.tracker, options);
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* Issues, projects and comments of these accounts nearest in meaning to plain words, nearer than the model's floor,
|
|
18
|
+
* best first; only items already embedded are found.
|
|
19
|
+
*/
|
|
20
|
+
export const nearestTracker = async (store, words, { limit, accounts, env, command, embedders, }) => {
|
|
21
|
+
const { model, directory, key } = localModel(await meaningModel(store, env), env, command);
|
|
22
|
+
if (!(await store.tracker.embedded(key, accounts)))
|
|
23
|
+
throw new CliError("not_found", `no issue, project or comment has vectors of ${model.id} yet, so only words were matched`);
|
|
24
|
+
const [vector] = await withLocal(model, directory, undefined, (embedder) => embedder.embed([words], "query"), embedders);
|
|
25
|
+
const floor = meaningFloor(key);
|
|
26
|
+
return (await store.tracker.nearest(key, vector, { limit, accounts })).filter(({ score }) => score > floor);
|
|
27
|
+
};
|
package/dist/store/exports.d.ts
CHANGED
|
@@ -68,7 +68,7 @@ export { DEFAULT_FIRST_PASS_PER_CHAT, firstPassPerChatOf, savedFirstPassPerChat
|
|
|
68
68
|
export { inboxKey } from "./sqlite/tasks.js";
|
|
69
69
|
export { storedTemplateBodies, type TemplateAddress } from "./sqlite/templates.js";
|
|
70
70
|
export { THREAD_COLUMNS } from "./sqlite/thread-columns.js";
|
|
71
|
-
export { resetTrackerItemWords, type TrackerFilter, type TrackerHit, type TrackerItem, type TrackerPerson, type TrackerSearch, type TrackerStore, } from "./sqlite/tracker.js";
|
|
71
|
+
export { resetTrackerItemWords, type TrackerFilter, type TrackerHit, type TrackerItem, type TrackerNearest, type TrackerPerson, type TrackerSearch, type TrackerStore, } from "./sqlite/tracker.js";
|
|
72
72
|
export { dropAllUnusedVectors, vectorIndexCounts } from "./sqlite/vector-index.js";
|
|
73
73
|
export type { MatchPlace, ScoredHit } from "./sqlite/words.js";
|
|
74
74
|
export type { TaskDetails } from "./sqlite/work-tasks.js";
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { type CacheDatabase } from "../driver.js";
|
|
2
|
+
/** `chunks.chunkable_type` of an issue's, a project's or a comment's pieces; `chunkable_id` is `tracker_items.id`. */
|
|
3
|
+
export declare const TRACKER_CHUNK = "tracker_item";
|
|
4
|
+
export declare const isChunkedTrackerKind: (kind: string) => boolean;
|
|
5
|
+
export interface ChunkedItem {
|
|
6
|
+
id: number;
|
|
7
|
+
accountId: number;
|
|
8
|
+
kind: string;
|
|
9
|
+
title: string;
|
|
10
|
+
body: string | null;
|
|
11
|
+
occurredAt: number;
|
|
12
|
+
scope: string | null;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Inside the caller's write: makes each item's chunks its text's, and answers the hashes it released, or `undefined`
|
|
16
|
+
* when they already were. The caller drops the vectors of those once every new chunk is in, so a text another item or
|
|
17
|
+
* account still holds keeps its vector.
|
|
18
|
+
*/
|
|
19
|
+
export declare const trackerChunkWriter: (database: CacheDatabase) => (item: ChunkedItem, at: number) => string[] | undefined;
|
|
20
|
+
/** Inside the caller's write: drops the chunks of these items and the vectors no other chunk holds. */
|
|
21
|
+
export declare const dropTrackerChunks: (database: CacheDatabase, ids: readonly number[]) => void;
|
|
22
|
+
/**
|
|
23
|
+
* Drops the chunks of items the tracker no longer lists, then cuts the chunks of live items that have none: those
|
|
24
|
+
* saved before tracker items were searched by meaning. Short write transactions, `until` asked before each, so a
|
|
25
|
+
* deadline stops it with `left`; nothing under a read-only store.
|
|
26
|
+
*/
|
|
27
|
+
export declare const refreshTrackerChunks: (database: CacheDatabase, now: number, until?: () => boolean) => {
|
|
28
|
+
dropped: number;
|
|
29
|
+
added: number;
|
|
30
|
+
left: boolean;
|
|
31
|
+
};
|
|
32
|
+
export declare const trackerChunksLeft: (database: CacheDatabase, model: string) => number;
|
|
33
|
+
/** Live items' chunks with no vector of `model`, by hash from `after`, each with its text cut again. */
|
|
34
|
+
export declare const trackerChunksToEmbed: (database: CacheDatabase, model: string, { after, limit }: {
|
|
35
|
+
after?: string;
|
|
36
|
+
limit: number;
|
|
37
|
+
}) => {
|
|
38
|
+
hash: string;
|
|
39
|
+
text: string;
|
|
40
|
+
}[];
|
|
41
|
+
export declare const trackerEmbedded: (database: CacheDatabase, model: string, accountIds: readonly number[]) => boolean;
|
|
42
|
+
/**
|
|
43
|
+
* The account's live items nearest to `query` by their best chunk's vector of `model`, archived ones too: by the
|
|
44
|
+
* model's vector index, or by a scan of the account's chunks while it has none.
|
|
45
|
+
*/
|
|
46
|
+
export declare const nearestTrackerItems: (database: CacheDatabase, model: string, query: Float32Array, { accountId, limit }: {
|
|
47
|
+
accountId: number;
|
|
48
|
+
limit: number;
|
|
49
|
+
}) => {
|
|
50
|
+
owner: number;
|
|
51
|
+
score: number;
|
|
52
|
+
}[];
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { CHUNK_CHARS, chunkHash, splitText } from "../../conversations/chunks.js";
|
|
2
|
+
import { isQueryOnly } from "../driver.js";
|
|
3
|
+
import { noteIndexText } from "./index-text.js";
|
|
4
|
+
import { write } from "./transaction.js";
|
|
5
|
+
import { dropUnusedVectors, searchIndex } from "./vector-index.js";
|
|
6
|
+
import { dot } from "./vectors.js";
|
|
7
|
+
/** `chunks.chunkable_type` of an issue's, a project's or a comment's pieces; `chunkable_id` is `tracker_items.id`. */
|
|
8
|
+
export const TRACKER_CHUNK = "tracker_item";
|
|
9
|
+
/** The kinds searched by meaning; teams, users, states and labels are names, found by their words. */
|
|
10
|
+
const CHUNKED = new Set(["issue", "project", "comment"]);
|
|
11
|
+
const CHUNKED_SQL = "('issue', 'project', 'comment')";
|
|
12
|
+
export const isChunkedTrackerKind = (kind) => CHUNKED.has(kind);
|
|
13
|
+
/** What an item is embedded as, from its stored columns: chunk offsets point into it. */
|
|
14
|
+
const textOf = (kind, title, body) => kind === "comment" ? (body ?? "") : noteIndexText(title, body ?? "");
|
|
15
|
+
const piecesOf = (kind, title, body) => {
|
|
16
|
+
if (!CHUNKED.has(kind))
|
|
17
|
+
return [];
|
|
18
|
+
const text = textOf(kind, title, body);
|
|
19
|
+
if (!text.trim())
|
|
20
|
+
return [];
|
|
21
|
+
return splitText(text, CHUNK_CHARS).map(({ start, end }) => ({ start, end, hash: chunkHash(text.slice(start, end)) }));
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* Inside the caller's write: makes each item's chunks its text's, and answers the hashes it released, or `undefined`
|
|
25
|
+
* when they already were. The caller drops the vectors of those once every new chunk is in, so a text another item or
|
|
26
|
+
* account still holds keeps its vector.
|
|
27
|
+
*/
|
|
28
|
+
export const trackerChunkWriter = (database) => {
|
|
29
|
+
const held = database.prepare(`SELECT start_offset AS start, end_offset AS end, content_hash AS hash FROM chunks
|
|
30
|
+
WHERE chunkable_type = '${TRACKER_CHUNK}' AND chunkable_id = ? ORDER BY position`);
|
|
31
|
+
const drop = database.prepare(`DELETE FROM chunks WHERE chunkable_type = '${TRACKER_CHUNK}' AND chunkable_id = ?`);
|
|
32
|
+
const insert = database.prepare("INSERT INTO chunks (chunkable_type, chunkable_id, position, start_offset, end_offset, content_hash, scope, " +
|
|
33
|
+
`account_id, occurred_at, created_at, updated_at) VALUES ('${TRACKER_CHUNK}', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
|
34
|
+
return (item, at) => {
|
|
35
|
+
const wanted = piecesOf(item.kind, item.title, item.body);
|
|
36
|
+
const before = held.all(item.id).map((row) => ({
|
|
37
|
+
start: Number(row.start),
|
|
38
|
+
end: Number(row.end),
|
|
39
|
+
hash: String(row.hash),
|
|
40
|
+
}));
|
|
41
|
+
const same = before.length === wanted.length &&
|
|
42
|
+
before.every((one, at) => {
|
|
43
|
+
const other = wanted[at];
|
|
44
|
+
return other !== undefined && one.start === other.start && one.end === other.end && one.hash === other.hash;
|
|
45
|
+
});
|
|
46
|
+
if (same)
|
|
47
|
+
return undefined;
|
|
48
|
+
drop.run(item.id);
|
|
49
|
+
wanted.forEach(({ start, end, hash }, position) => {
|
|
50
|
+
insert.run(item.id, position, start, end, hash, item.scope, item.accountId, item.occurredAt, at, at);
|
|
51
|
+
});
|
|
52
|
+
return before.map(({ hash }) => hash);
|
|
53
|
+
};
|
|
54
|
+
};
|
|
55
|
+
/** Inside the caller's write: drops the chunks of these items and the vectors no other chunk holds. */
|
|
56
|
+
export const dropTrackerChunks = (database, ids) => {
|
|
57
|
+
if (!ids.length)
|
|
58
|
+
return;
|
|
59
|
+
const released = database
|
|
60
|
+
.prepare(`DELETE FROM chunks WHERE chunkable_type = '${TRACKER_CHUNK}' AND chunkable_id IN (SELECT value FROM json_each(?))
|
|
61
|
+
RETURNING content_hash AS hash`)
|
|
62
|
+
.all(JSON.stringify(ids))
|
|
63
|
+
.map(({ hash }) => String(hash));
|
|
64
|
+
dropUnusedVectors(database, released);
|
|
65
|
+
};
|
|
66
|
+
const BACKFILL = 200;
|
|
67
|
+
/**
|
|
68
|
+
* Drops the chunks of items the tracker no longer lists, then cuts the chunks of live items that have none: those
|
|
69
|
+
* saved before tracker items were searched by meaning. Short write transactions, `until` asked before each, so a
|
|
70
|
+
* deadline stops it with `left`; nothing under a read-only store.
|
|
71
|
+
*/
|
|
72
|
+
export const refreshTrackerChunks = (database, now, until = () => false) => {
|
|
73
|
+
if (isQueryOnly(database))
|
|
74
|
+
return { dropped: 0, added: 0, left: false };
|
|
75
|
+
const dropped = write(database, () => {
|
|
76
|
+
const gone = database
|
|
77
|
+
.prepare(`DELETE FROM chunks WHERE chunkable_type = '${TRACKER_CHUNK}' AND NOT EXISTS (SELECT 1 FROM tracker_items t
|
|
78
|
+
WHERE t.id = chunkable_id AND t.deleted_at IS NULL AND t.kind IN ${CHUNKED_SQL})
|
|
79
|
+
RETURNING content_hash AS hash`)
|
|
80
|
+
.all()
|
|
81
|
+
.map(({ hash }) => String(hash));
|
|
82
|
+
dropUnusedVectors(database, gone);
|
|
83
|
+
return gone.length;
|
|
84
|
+
});
|
|
85
|
+
// An item with no text never gets a chunk: reading it again at every embed would find nothing.
|
|
86
|
+
const page = database.prepare(`SELECT t.id, t.account_id, t.kind, t.title, t.body, coalesce(t.source_updated_at, t.synced_at) AS at, a.scope
|
|
87
|
+
FROM tracker_items t JOIN accounts a ON a.id = t.account_id
|
|
88
|
+
WHERE t.id > ? AND t.deleted_at IS NULL AND t.kind IN ${CHUNKED_SQL}
|
|
89
|
+
AND trim(CASE t.kind WHEN 'comment' THEN coalesce(t.body, '') ELSE t.title || coalesce(t.body, '') END) <> ''
|
|
90
|
+
AND NOT EXISTS (SELECT 1 FROM chunks k WHERE k.chunkable_type = '${TRACKER_CHUNK}' AND k.chunkable_id = t.id)
|
|
91
|
+
ORDER BY t.id LIMIT ?`);
|
|
92
|
+
const chunk = trackerChunkWriter(database);
|
|
93
|
+
let added = 0;
|
|
94
|
+
let after = 0;
|
|
95
|
+
for (;;) {
|
|
96
|
+
if (until())
|
|
97
|
+
return { dropped, added, left: page.all(after, 1).length > 0 };
|
|
98
|
+
const rows = write(database, () => {
|
|
99
|
+
const found = page.all(after, BACKFILL);
|
|
100
|
+
for (const row of found) {
|
|
101
|
+
const written = chunk({
|
|
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)
|
|
111
|
+
added += 1;
|
|
112
|
+
}
|
|
113
|
+
return found;
|
|
114
|
+
});
|
|
115
|
+
const last = rows.at(-1);
|
|
116
|
+
if (!last || rows.length < BACKFILL)
|
|
117
|
+
break;
|
|
118
|
+
after = Number(last.id);
|
|
119
|
+
}
|
|
120
|
+
return { dropped, added, left: false };
|
|
121
|
+
};
|
|
122
|
+
const LIVE = `k.chunkable_type = '${TRACKER_CHUNK}' AND EXISTS (SELECT 1 FROM tracker_items t WHERE t.id = k.chunkable_id ` +
|
|
123
|
+
"AND t.deleted_at IS NULL)";
|
|
124
|
+
const UNEMBEDDED = `${LIVE} AND NOT EXISTS (SELECT 1 FROM embeddings v WHERE v.model = ? AND v.content_hash = k.content_hash)`;
|
|
125
|
+
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
|
+
/** Live items' chunks with no vector of `model`, by hash from `after`, each with its text cut again. */
|
|
127
|
+
export const trackerChunksToEmbed = (database, model, { after, limit }) => {
|
|
128
|
+
const item = database.prepare("SELECT kind, title, body FROM tracker_items WHERE id = ?");
|
|
129
|
+
return database
|
|
130
|
+
.prepare(`SELECT k.content_hash AS hash, min(k.chunkable_id) AS owner, k.start_offset AS start, k.end_offset AS end
|
|
131
|
+
FROM chunks k WHERE k.content_hash > ? AND ${UNEMBEDDED}
|
|
132
|
+
GROUP BY k.content_hash ORDER BY k.content_hash LIMIT ?`)
|
|
133
|
+
.all(after ?? "", model, limit)
|
|
134
|
+
.flatMap((row) => {
|
|
135
|
+
const found = item.get(Number(row.owner));
|
|
136
|
+
if (!found)
|
|
137
|
+
return [];
|
|
138
|
+
const text = textOf(String(found.kind), String(found.title), found.body == null ? null : String(found.body));
|
|
139
|
+
return [{ hash: String(row.hash), text: text.slice(Number(row.start), Number(row.end)) }];
|
|
140
|
+
});
|
|
141
|
+
};
|
|
142
|
+
export const trackerEmbedded = (database, model, accountIds) => accountIds.length > 0 &&
|
|
143
|
+
database
|
|
144
|
+
.prepare(`SELECT 1 FROM chunks k JOIN embeddings v ON v.model = ? AND v.content_hash = k.content_hash
|
|
145
|
+
WHERE ${LIVE} AND k.account_id IN (SELECT value FROM json_each(?)) LIMIT 1`)
|
|
146
|
+
.get(model, JSON.stringify(accountIds)) !== undefined;
|
|
147
|
+
const SCAN_PAGE = 5_000;
|
|
148
|
+
/** Each item scored by its best chunk, best first; equal scores by item, so the index and the scan agree. */
|
|
149
|
+
const ranked = (best, limit) => [...best.values()].sort((a, b) => b.score - a.score || a.owner - b.owner).slice(0, limit);
|
|
150
|
+
/**
|
|
151
|
+
* The account's live items nearest to `query` by their best chunk's vector of `model`, archived ones too: by the
|
|
152
|
+
* model's vector index, or by a scan of the account's chunks while it has none.
|
|
153
|
+
*/
|
|
154
|
+
export const nearestTrackerItems = (database, model, query, { accountId, limit }) => {
|
|
155
|
+
const columns = `k.id, k.chunkable_id AS owner, k.content_hash AS hash, v.vector
|
|
156
|
+
FROM chunks k JOIN embeddings v ON v.model = ? AND v.content_hash = k.content_hash
|
|
157
|
+
WHERE ${LIVE} AND k.account_id = ?`;
|
|
158
|
+
const keep = (best, row) => {
|
|
159
|
+
const score = dot(query, row.vector);
|
|
160
|
+
const owner = Number(row.owner);
|
|
161
|
+
if (score > (best.get(owner)?.score ?? Number.NEGATIVE_INFINITY))
|
|
162
|
+
best.set(owner, { owner, chunk: Number(row.id), score });
|
|
163
|
+
};
|
|
164
|
+
const candidates = database.prepare(`SELECT ${columns} AND k.id IN (SELECT value FROM json_each(?)) ORDER BY k.id`);
|
|
165
|
+
const indexed = searchIndex(database, model, { kind: TRACKER_CHUNK, account: accountId }, query, limit, (near) => {
|
|
166
|
+
const hashes = new Map(near.map(({ id, hash }) => [id, hash]));
|
|
167
|
+
const best = new Map();
|
|
168
|
+
for (const row of candidates.all(model, accountId, JSON.stringify([...hashes.keys()])))
|
|
169
|
+
if (hashes.get(Number(row.id)) === row.hash)
|
|
170
|
+
keep(best, row);
|
|
171
|
+
const results = ranked(best, limit);
|
|
172
|
+
return { results, best: results.map(({ chunk }) => chunk) };
|
|
173
|
+
});
|
|
174
|
+
const plain = (found) => found.map(({ owner, score }) => ({ owner, score }));
|
|
175
|
+
if (indexed)
|
|
176
|
+
return plain(indexed);
|
|
177
|
+
const page = database.prepare(`SELECT ${columns} AND k.id > ? ORDER BY k.id LIMIT ?`);
|
|
178
|
+
const best = new Map();
|
|
179
|
+
let after = 0;
|
|
180
|
+
for (;;) {
|
|
181
|
+
const rows = page.all(model, accountId, after, SCAN_PAGE);
|
|
182
|
+
for (const row of rows)
|
|
183
|
+
keep(best, row);
|
|
184
|
+
const last = rows.at(-1);
|
|
185
|
+
if (!last || rows.length < SCAN_PAGE)
|
|
186
|
+
break;
|
|
187
|
+
after = Number(last.id);
|
|
188
|
+
}
|
|
189
|
+
return plain(ranked(best, limit));
|
|
190
|
+
};
|
|
@@ -41,6 +41,12 @@ export interface TrackerSearch {
|
|
|
41
41
|
limit?: number;
|
|
42
42
|
offset?: number;
|
|
43
43
|
}
|
|
44
|
+
/** An issue, a project or a comment found by meaning: the cosine of its nearest chunk. */
|
|
45
|
+
export interface TrackerNearest {
|
|
46
|
+
account: AccountKey;
|
|
47
|
+
item: TrackerItem;
|
|
48
|
+
score: number;
|
|
49
|
+
}
|
|
44
50
|
/** A tracker user joined to the one person the store knows by the same e-mail. */
|
|
45
51
|
export interface TrackerPerson {
|
|
46
52
|
user: string;
|
|
@@ -76,6 +82,37 @@ export interface TrackerStore {
|
|
|
76
82
|
count(key: AccountKey, kind: TrackerKind): Promise<number>;
|
|
77
83
|
/** The tracker users among `users` whose e-mail, in any letter case, an identity linked to one person has. */
|
|
78
84
|
people(key: AccountKey, users: readonly string[]): Promise<TrackerPerson[]>;
|
|
85
|
+
/**
|
|
86
|
+
* Before embedding: drops the chunks of issues, projects and comments the tracker no longer lists, and cuts those
|
|
87
|
+
* of live ones saved before they were searched by meaning. `save` and `removeUnlisted` keep the rest in step.
|
|
88
|
+
*/
|
|
89
|
+
refreshChunks(options?: {
|
|
90
|
+
until?: () => boolean;
|
|
91
|
+
}): Promise<{
|
|
92
|
+
dropped: number;
|
|
93
|
+
added: number;
|
|
94
|
+
left: boolean;
|
|
95
|
+
}>;
|
|
96
|
+
/** Live issues', projects' and comments' chunks with no vector of `model`, by hash from `after`, with their text. */
|
|
97
|
+
chunksToEmbed(model: string, options: {
|
|
98
|
+
after?: string;
|
|
99
|
+
limit: number;
|
|
100
|
+
}): Promise<{
|
|
101
|
+
hash: string;
|
|
102
|
+
text: string;
|
|
103
|
+
}[]>;
|
|
104
|
+
/** How many chunks `chunksToEmbed` would still give, at most. */
|
|
105
|
+
chunksLeft(model: string): Promise<number>;
|
|
106
|
+
/** Whether a live item of these accounts has a vector of `model`. */
|
|
107
|
+
embedded(model: string, accounts: readonly AccountKey[]): Promise<boolean>;
|
|
108
|
+
/**
|
|
109
|
+
* Live issues, projects and comments of these accounts nearest in meaning to `query`, archived ones too, each by its
|
|
110
|
+
* best chunk, best first. Vectors are unit length.
|
|
111
|
+
*/
|
|
112
|
+
nearest(model: string, query: Float32Array, options: {
|
|
113
|
+
limit: number;
|
|
114
|
+
accounts: readonly AccountKey[];
|
|
115
|
+
}): Promise<TrackerNearest[]>;
|
|
79
116
|
}
|
|
80
117
|
/** `store rebuild`: the normalized copies follow the current normalizer, then the word index is filled again. */
|
|
81
118
|
export declare const resetTrackerItemWords: (database: CacheDatabase) => number;
|
|
@@ -2,7 +2,9 @@ import { trackerBodyOf, trackerParentOf, trackerTitleOf, } from "../../domain/tr
|
|
|
2
2
|
import { fold, normalize } from "../normalize.js";
|
|
3
3
|
import { accountPk, findAccountPk } from "./accounts.js";
|
|
4
4
|
import { excerptOf, matchOf } from "./crm-files.js";
|
|
5
|
+
import { dropTrackerChunks, isChunkedTrackerKind, nearestTrackerItems, refreshTrackerChunks, trackerChunksLeft, trackerChunksToEmbed, trackerChunkWriter, trackerEmbedded, } from "./tracker-chunks.js";
|
|
5
6
|
import { write } from "./transaction.js";
|
|
7
|
+
import { dropUnusedVectors } from "./vector-index.js";
|
|
6
8
|
const MOST = 500;
|
|
7
9
|
const itemOf = (row) => ({
|
|
8
10
|
kind: String(row.kind),
|
|
@@ -36,7 +38,11 @@ export const trackerStoreOver = (context) => {
|
|
|
36
38
|
const { database } = context;
|
|
37
39
|
const save = (key, kind, records, now) => write(database, () => {
|
|
38
40
|
const accountId = accountPk(context, key);
|
|
39
|
-
const stored = database.prepare("SELECT data FROM tracker_items WHERE account_id = ? AND kind = ? AND external_id = ?");
|
|
41
|
+
const stored = database.prepare("SELECT data, title, body, deleted_at FROM tracker_items WHERE account_id = ? AND kind = ? AND external_id = ?");
|
|
42
|
+
const scope = database.prepare("SELECT scope FROM accounts WHERE id = ?").get(accountId)?.scope;
|
|
43
|
+
const chunked = isChunkedTrackerKind(kind);
|
|
44
|
+
const chunk = trackerChunkWriter(database);
|
|
45
|
+
const released = [];
|
|
40
46
|
const upsert = database.prepare("INSERT INTO tracker_items (account_id, kind, external_id, parent_id, title, title_folded, body, " +
|
|
41
47
|
"normalized_text, data, source_created_at, source_updated_at, archived_at, deleted_at, synced_at) " +
|
|
42
48
|
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?) " +
|
|
@@ -44,7 +50,7 @@ export const trackerStoreOver = (context) => {
|
|
|
44
50
|
"title = excluded.title, title_folded = excluded.title_folded, body = excluded.body, " +
|
|
45
51
|
"normalized_text = excluded.normalized_text, data = excluded.data, " +
|
|
46
52
|
"source_created_at = excluded.source_created_at, source_updated_at = excluded.source_updated_at, " +
|
|
47
|
-
"archived_at = excluded.archived_at, deleted_at = NULL, synced_at = excluded.synced_at");
|
|
53
|
+
"archived_at = excluded.archived_at, deleted_at = NULL, synced_at = excluded.synced_at RETURNING id");
|
|
48
54
|
for (const record of records) {
|
|
49
55
|
const before = stored.get(accountId, kind, record.externalId);
|
|
50
56
|
// A field the tracker left out of this read keeps what the store knew: a read never erases by omission.
|
|
@@ -54,8 +60,24 @@ export const trackerStoreOver = (context) => {
|
|
|
54
60
|
};
|
|
55
61
|
const title = trackerTitleOf(kind, merged);
|
|
56
62
|
const body = trackerBodyOf(kind, merged) ?? null;
|
|
57
|
-
upsert.
|
|
63
|
+
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
|
+
// Most rows of a sync come back with the text they had; their chunks stay, and only a revived row needs new.
|
|
65
|
+
const same = before?.deleted_at == null && before?.title === title && (before?.body ?? null) === body;
|
|
66
|
+
if (!chunked || same)
|
|
67
|
+
continue;
|
|
68
|
+
const freed = chunk({
|
|
69
|
+
id: Number(saved?.id),
|
|
70
|
+
accountId,
|
|
71
|
+
kind,
|
|
72
|
+
title,
|
|
73
|
+
body,
|
|
74
|
+
occurredAt: merged.updatedAt ?? now,
|
|
75
|
+
scope: scope == null ? null : String(scope),
|
|
76
|
+
}, now);
|
|
77
|
+
for (const hash of freed ?? [])
|
|
78
|
+
released.push(hash);
|
|
58
79
|
}
|
|
80
|
+
dropUnusedVectors(database, released);
|
|
59
81
|
return records.length;
|
|
60
82
|
});
|
|
61
83
|
const removeUnlisted = (key, kind, listed, before, now, { dryRun = false } = {}) => {
|
|
@@ -66,16 +88,21 @@ export const trackerStoreOver = (context) => {
|
|
|
66
88
|
return write(database, () => {
|
|
67
89
|
const mark = database.prepare("UPDATE tracker_items SET deleted_at = ? WHERE id = ?");
|
|
68
90
|
let removed = 0;
|
|
91
|
+
const marked = [];
|
|
69
92
|
for (const row of database
|
|
70
93
|
.prepare("SELECT id, external_id FROM tracker_items WHERE account_id = ? AND kind = ? AND deleted_at IS NULL " +
|
|
71
94
|
"AND synced_at < ?")
|
|
72
95
|
.all(accountId, kind, before)) {
|
|
73
96
|
if (keep.has(String(row.external_id)))
|
|
74
97
|
continue;
|
|
75
|
-
if (!dryRun)
|
|
98
|
+
if (!dryRun) {
|
|
76
99
|
mark.run(now, Number(row.id));
|
|
100
|
+
marked.push(Number(row.id));
|
|
101
|
+
}
|
|
77
102
|
removed += 1;
|
|
78
103
|
}
|
|
104
|
+
if (isChunkedTrackerKind(kind))
|
|
105
|
+
dropTrackerChunks(database, marked);
|
|
79
106
|
return removed;
|
|
80
107
|
});
|
|
81
108
|
};
|
|
@@ -156,6 +183,20 @@ export const trackerStoreOver = (context) => {
|
|
|
156
183
|
hasMore: rows.length > most,
|
|
157
184
|
};
|
|
158
185
|
};
|
|
186
|
+
const accountIdsOf = (accounts) => accounts.flatMap((one) => {
|
|
187
|
+
const id = findAccountPk(context, one);
|
|
188
|
+
return id === undefined ? [] : [{ id, key: { provider: one.provider, account: one.account } }];
|
|
189
|
+
});
|
|
190
|
+
const nearest = (model, query, limit, accounts) => {
|
|
191
|
+
const item = database.prepare(`SELECT ${COLUMNS} FROM tracker_items t WHERE t.id = ?`);
|
|
192
|
+
return accountIdsOf(accounts)
|
|
193
|
+
.flatMap(({ id, key }) => nearestTrackerItems(database, model, query, { accountId: id, limit }).flatMap(({ owner, score }) => {
|
|
194
|
+
const row = item.get(owner);
|
|
195
|
+
return row ? [{ account: key, item: itemOf(row), score }] : [];
|
|
196
|
+
}))
|
|
197
|
+
.sort((a, b) => b.score - a.score)
|
|
198
|
+
.slice(0, limit);
|
|
199
|
+
};
|
|
159
200
|
return {
|
|
160
201
|
save: async (key, kind, records, now) => save(key, kind, records, now),
|
|
161
202
|
removeUnlisted: async (key, kind, listed, before, now, options) => removeUnlisted(key, kind, listed, before, now, options),
|
|
@@ -206,5 +247,10 @@ export const trackerStoreOver = (context) => {
|
|
|
206
247
|
name: row.name == null ? null : String(row.name),
|
|
207
248
|
}));
|
|
208
249
|
},
|
|
250
|
+
refreshChunks: async ({ until } = {}) => refreshTrackerChunks(database, context.now(), until),
|
|
251
|
+
chunksToEmbed: async (model, options) => trackerChunksToEmbed(database, model, options),
|
|
252
|
+
chunksLeft: async (model) => trackerChunksLeft(database, model),
|
|
253
|
+
embedded: async (model, accounts) => trackerEmbedded(database, model, accountIdsOf(accounts).map(({ id }) => id)),
|
|
254
|
+
nearest: async (model, query, { limit, accounts }) => nearest(model, query, limit, accounts),
|
|
209
255
|
};
|
|
210
256
|
};
|
|
@@ -23,7 +23,10 @@ export interface TrackerCommandOptions {
|
|
|
23
23
|
open: (command: Command, access: {
|
|
24
24
|
readOnly: boolean;
|
|
25
25
|
}) => Promise<TrackerRun>;
|
|
26
|
-
/**
|
|
26
|
+
/**
|
|
27
|
+
* What the tracker's writer takes (`TrackerWriter.writes`): mounts `issues create`, `issues update` and
|
|
28
|
+
* `issues comments create`.
|
|
29
|
+
*/
|
|
27
30
|
writes?: readonly TrackerWrite[];
|
|
28
31
|
/**
|
|
29
32
|
* The documents half of `sync`, from `documentLibrary`, for a CLI that mounts the shared documents commands too:
|
|
@@ -33,7 +36,7 @@ export interface TrackerCommandOptions {
|
|
|
33
36
|
now?: () => number;
|
|
34
37
|
}
|
|
35
38
|
/**
|
|
36
|
-
* The tracker's commands: `sync`, `issues list|show|search|assign`, `issues create|update
|
|
37
|
-
* `writes`, and a `list` of each other kind.
|
|
39
|
+
* The tracker's commands: `sync`, `issues list|show|search|assign`, `issues create|update` and
|
|
40
|
+
* `issues comments create` for the writes in `writes`, and a `list` of each other kind.
|
|
38
41
|
*/
|
|
39
42
|
export declare const addTrackerCommands: (program: Command, options: TrackerCommandOptions) => void;
|