@wirecat/cli-core 0.728.0 → 0.730.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 +31 -0
- package/dist/background/daily-archive-timer.d.ts +1 -1
- package/dist/cli/documents/file-mirrors.d.ts +70 -0
- package/dist/cli/documents/file-mirrors.js +718 -0
- package/dist/cli/documents/index.d.ts +1 -0
- package/dist/cli/documents/index.js +1 -0
- package/dist/cli/documents/library.js +6 -1
- package/dist/errors/reasons.js +5 -0
- 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.js +76 -9
- package/package.json +2 -2
|
@@ -12,6 +12,7 @@ export { addDocumentCatalogCommands, CATALOG_FIELDS, type CatalogTree, type Cata
|
|
|
12
12
|
export { addLocalDocumentCommands, type ImportedDocument, type LocalDocumentCommands } from "./documents.js";
|
|
13
13
|
export { type FileConflictCommands, type FileConflictConnection, fileConflictsCommand } from "./file-conflicts.js";
|
|
14
14
|
export { addFileEditCommands, type FileEditCommands } from "./file-edit.js";
|
|
15
|
+
export { type FileMirrorCommands, type FileMirrorRemote, type FileMirrorWrite, fileMirrorsCommand, } from "./file-mirrors.js";
|
|
15
16
|
export { addFileUpdateCommand, type FileUpdateCommands, type FileUpdatePort } from "./file-update.js";
|
|
16
17
|
export { addDocumentFolderCommands, type DocumentFolderCommands } from "./folders.js";
|
|
17
18
|
export { addDocumentHistoryCommands, DOCUMENT_HISTORY_SETTINGS, type DocumentHistoryCommands, type DocumentHistoryPort, keepVersionsForDays, } from "./history.js";
|
|
@@ -10,6 +10,7 @@ export { addDocumentCatalogCommands, CATALOG_FIELDS, catalogId, catalogOutput, c
|
|
|
10
10
|
export { addLocalDocumentCommands } from "./documents.js";
|
|
11
11
|
export { fileConflictsCommand } from "./file-conflicts.js";
|
|
12
12
|
export { addFileEditCommands } from "./file-edit.js";
|
|
13
|
+
export { fileMirrorsCommand, } from "./file-mirrors.js";
|
|
13
14
|
export { addFileUpdateCommand } from "./file-update.js";
|
|
14
15
|
export { addDocumentFolderCommands } from "./folders.js";
|
|
15
16
|
export { addDocumentHistoryCommands, DOCUMENT_HISTORY_SETTINGS, keepVersionsForDays, } from "./history.js";
|
|
@@ -374,7 +374,12 @@ const libraryOf = (options, withSync) => {
|
|
|
374
374
|
const { embedNotes } = await import("../../services/notes-search.js");
|
|
375
375
|
return {
|
|
376
376
|
...result,
|
|
377
|
-
embeddings: await embedNotes(store, {
|
|
377
|
+
embeddings: await embedNotes(store, {
|
|
378
|
+
maxChunks: 600,
|
|
379
|
+
env: env(),
|
|
380
|
+
command: app.command,
|
|
381
|
+
...(deadline ? { deadline } : {}),
|
|
382
|
+
}),
|
|
378
383
|
};
|
|
379
384
|
}));
|
|
380
385
|
}, deadline);
|
package/dist/errors/reasons.js
CHANGED
|
@@ -271,6 +271,11 @@ const OTHERS = [
|
|
|
271
271
|
"the email could not be read again, so its skipped attachments have no text",
|
|
272
272
|
],
|
|
273
273
|
["mirror.partial", "provider_error", "some mirrored files were not synced"],
|
|
274
|
+
[
|
|
275
|
+
"mirror.stopped",
|
|
276
|
+
"timeout",
|
|
277
|
+
"the mirror's run reached its deadline before it was done; run it again with more time",
|
|
278
|
+
],
|
|
274
279
|
["mirror.none", "not_found", "the profile has no mirrors; add one with mirrors add"],
|
|
275
280
|
["mirror.not-found", "not_found", "no such mirror in this profile; see mirrors list"],
|
|
276
281
|
validation("mirror.not-folder", "the path to mirror is not a folder"),
|
package/dist/services/index.d.ts
CHANGED
|
@@ -231,3 +231,4 @@ export { createStoredMeetingProjectCandidateReader } from "./stored-meeting-proj
|
|
|
231
231
|
export { applyTaskRulesSinceLastPass, applyTaskRulesToStored, type RuleResult } from "./task-rules.js";
|
|
232
232
|
export type { ThreadContext, ThreadOptions } from "./thread-context.js";
|
|
233
233
|
export { readThreadContext, THREAD_BOUNDS } from "./thread-context.js";
|
|
234
|
+
export { embedTracker, nearestTracker } from "./tracker-meaning.js";
|
package/dist/services/index.js
CHANGED
|
@@ -179,3 +179,4 @@ export { SERVER_BOUNDS, SERVER_SEARCH_KEY, } from "./server-search.js";
|
|
|
179
179
|
export { createStoredMeetingProjectCandidateReader } from "./stored-meeting-project-candidates.js";
|
|
180
180
|
export { applyTaskRulesSinceLastPass, applyTaskRulesToStored } from "./task-rules.js";
|
|
181
181
|
export { readThreadContext, THREAD_BOUNDS } from "./thread-context.js";
|
|
182
|
+
export { embedTracker, nearestTracker } from "./tracker-meaning.js";
|
|
@@ -84,6 +84,18 @@ export declare const localModel: (choice: string | undefined, env: NodeJS.Proces
|
|
|
84
84
|
key: string;
|
|
85
85
|
};
|
|
86
86
|
export declare const withLocal: <T>(model: TextModel, directory: string, threads: number | undefined, work: (embedder: Embedder) => Promise<T>, shared?: Pick<WarmEmbedders, "get">) => Promise<T>;
|
|
87
|
+
/**
|
|
88
|
+
* Embeds the notes' chunks that have no vector of the model yet, with the same model, prefixes and key
|
|
89
|
+
* as conversations, so a chunk whose text a conversation shares is embedded once. A missing model is
|
|
90
|
+
* an error naming the download command; nothing is downloaded.
|
|
91
|
+
*/
|
|
92
|
+
/** When a run with this deadline stops: its margin before the end, as the word index after a sync does. */
|
|
93
|
+
export declare const stopsAt: (deadline: Deadline | undefined) => number;
|
|
94
|
+
export declare const embedChunks: (store: MessageStore, source: Pick<MessageStore["notes"] | MessageStore["calendar"] | MessageStore["tracker"], "chunksToEmbed"> & {
|
|
95
|
+
chunksLeft?(model: string): Promise<number>;
|
|
96
|
+
}, { model: choice, maxChunks, env, threads, command, deadline, signal, }?: NotesEmbedOptions & {
|
|
97
|
+
command?: string;
|
|
98
|
+
}) => Promise<NotesEmbedded>;
|
|
87
99
|
export declare const embedNotes: (store: MessageStore, options?: NotesEmbedOptions & {
|
|
88
100
|
command?: string;
|
|
89
101
|
}) => Promise<NotesEmbedded>;
|
|
@@ -97,7 +109,7 @@ export declare const embedMail: (store: MessageStore, options?: NotesEmbedOption
|
|
|
97
109
|
}) => Promise<NotesEmbedded>;
|
|
98
110
|
/** Notes nearest in meaning to the query, best first; only notes already embedded can be found. */
|
|
99
111
|
export declare const nearestNotes: (store: MessageStore, query: string, options: NearestOptions) => Promise<NearestNote[]>;
|
|
100
|
-
type NearestOptions = Omit<NotesEmbedOptions, "maxChunks"> & {
|
|
112
|
+
export type NearestOptions = Omit<NotesEmbedOptions, "maxChunks"> & {
|
|
101
113
|
limit: number;
|
|
102
114
|
folderIds?: string[];
|
|
103
115
|
withInternal?: boolean;
|
|
@@ -235,4 +247,3 @@ export declare const searchNotesOf: (store: MessageStore, account: AccountKey, t
|
|
|
235
247
|
app?: AppIdentity;
|
|
236
248
|
env?: NodeJS.ProcessEnv;
|
|
237
249
|
}) => Promise<NotesFoundOf>;
|
|
238
|
-
export {};
|
|
@@ -103,8 +103,8 @@ export const withLocal = async (model, directory, threads, work, shared) => {
|
|
|
103
103
|
* an error naming the download command; nothing is downloaded.
|
|
104
104
|
*/
|
|
105
105
|
/** When a run with this deadline stops: its margin before the end, as the word index after a sync does. */
|
|
106
|
-
const stopsAt = (deadline) => deadline ? deadline.endsAt - deadlineMargin(deadline) : Number.POSITIVE_INFINITY;
|
|
107
|
-
const embedChunks = async (store, source, { model: choice, maxChunks = Number.POSITIVE_INFINITY, env, threads, command, deadline, signal, } = {}) => {
|
|
106
|
+
export const stopsAt = (deadline) => deadline ? deadline.endsAt - deadlineMargin(deadline) : Number.POSITIVE_INFINITY;
|
|
107
|
+
export const embedChunks = async (store, source, { model: choice, maxChunks = Number.POSITIVE_INFINITY, env, threads, command, deadline, signal, } = {}) => {
|
|
108
108
|
const { model, directory, key } = localModel(choice, env, command);
|
|
109
109
|
if ((await source.chunksToEmbed(key, { limit: 1 })).length === 0)
|
|
110
110
|
return { model: model.id, embedded: 0, left: false };
|
|
@@ -101,6 +101,11 @@ export interface SearchAllFound {
|
|
|
101
101
|
by: "words" | "words and meaning";
|
|
102
102
|
meaningSkipped?: string;
|
|
103
103
|
};
|
|
104
|
+
/** How issues, projects and comments were searched, when they were; never by meaning with `exact`. */
|
|
105
|
+
tracker?: {
|
|
106
|
+
by: "words" | "words and meaning";
|
|
107
|
+
meaningSkipped?: string;
|
|
108
|
+
};
|
|
104
109
|
/** How the messages were searched, when they were; never by meaning with `exact` or the server alone. */
|
|
105
110
|
messages?: {
|
|
106
111
|
by: "words" | "words and meaning";
|
|
@@ -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;
|