@wirecat/cli-core 0.729.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 +20 -0
- package/dist/background/daily-archive-timer.d.ts +1 -1
- package/dist/cli/documents/library.js +6 -1
- 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 +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,26 @@ Notable changes to `@wirecat/cli-core` (`@wirecat/cli-messaging` up to 0.261.0,
|
|
|
5
5
|
minor version may break callers, and says how under "Changed — may break callers". `pnpm docs:check` checks the
|
|
6
6
|
shape of this file.
|
|
7
7
|
|
|
8
|
+
## 0.730.0 — 23.11.2026
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- **`search all` finds issues, projects and comments by meaning.** A tracker's issues, projects and comments get
|
|
13
|
+
chunks as notes do (`tracker_item`), kept in step by `save` and `removeUnlisted`, and `embedTracker` embeds them
|
|
14
|
+
with the shared text model. The tracker lane fuses words and meaning by reciprocal rank, says how it searched under
|
|
15
|
+
`tracker: { by, meaningSkipped? }`, and marks each hit's `foundBy`. A tracker CLI's `sync --embed` embeds new items,
|
|
16
|
+
the combined sync with documents too, within the deadline; a model not downloaded keeps the sync's answer and is
|
|
17
|
+
named in `meta.issues`. Items synced before are embedded at the next `sync --embed`
|
|
18
|
+
([TRACKER.md](docs/dev/TRACKER.md#search-all)).
|
|
19
|
+
|
|
20
|
+
### Fixed
|
|
21
|
+
|
|
22
|
+
- **A documents `sync --embed` stops embedding before the run's deadline.** `embedNotes` now gets the deadline the
|
|
23
|
+
sync had, so `--timeout` bounds the embedding too and the answer says when it stopped
|
|
24
|
+
([DOCUMENTS.md](docs/dev/DOCUMENTS.md#walks-over-several-syncs)).
|
|
25
|
+
- A tracker's combined `sync` that cannot reach the tracker and has no documents folder chosen fails as a tracker-only
|
|
26
|
+
`sync` does (for example `authentication_error` before sign-in) instead of a partial answer that exits 0.
|
|
27
|
+
|
|
8
28
|
## 0.729.0 — 23.11.2026
|
|
9
29
|
|
|
10
30
|
### Added
|
|
@@ -24,12 +24,12 @@ export interface DailyArchiveTimerInput {
|
|
|
24
24
|
}
|
|
25
25
|
export declare const dailyArchiveTimer: (input: DailyArchiveTimerInput) => DailyArchiveTimer;
|
|
26
26
|
export declare const manageDailyArchiveTimer: (plan: DailyArchiveTimer, action: "install" | "start" | "stop" | "status" | "uninstall", system: Pick<ServerSystem, "platform" | "run">, env: NodeJS.ProcessEnv, signal?: AbortSignal) => Promise<{
|
|
27
|
+
action?: undefined;
|
|
27
28
|
name: string;
|
|
28
29
|
installed: boolean;
|
|
29
30
|
active: boolean;
|
|
30
31
|
servicePath: string;
|
|
31
32
|
timerPath: string;
|
|
32
|
-
action?: undefined;
|
|
33
33
|
} | {
|
|
34
34
|
active?: undefined;
|
|
35
35
|
name: string;
|
|
@@ -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/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;
|
|
@@ -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
|
};
|
|
@@ -11,10 +11,14 @@ import { listQuery, nativeTermLists, queryTerms, termField, typedQuery, withQuer
|
|
|
11
11
|
import { aheadOf } from "../../domain/moment.js";
|
|
12
12
|
import { STATE_TYPES, TRACKER_KINDS, } from "../../domain/tracker.js";
|
|
13
13
|
import { count, text } from "../../entities/fields.js";
|
|
14
|
+
import { embedTracker } from "../../services/tracker-meaning.js";
|
|
14
15
|
import { syncTracker } from "../sync.js";
|
|
15
16
|
import { trackerIssueTask } from "../tasks.js";
|
|
16
17
|
import { addTrackerWriteCommands } from "./writes.js";
|
|
17
18
|
const MOST = 500;
|
|
19
|
+
// The documents' own answer has a `skipped` list of files; a part that did not run says why in a string.
|
|
20
|
+
const isSkipped = (item) => typeof item.skipped === "string";
|
|
21
|
+
const EMBED_MAX = 600;
|
|
18
22
|
const integer = (most) => (value) => {
|
|
19
23
|
const number = Number(value);
|
|
20
24
|
if (!Number.isSafeInteger(number) || number < 1 || number > most)
|
|
@@ -90,6 +94,14 @@ const trackerSync = v.strictObject({
|
|
|
90
94
|
v.strictObject({ opened: count, closed: count, reopened: count, renamed: count }),
|
|
91
95
|
v.strictObject({ skipped: text }),
|
|
92
96
|
])),
|
|
97
|
+
/** What `sync --embed` embedded of the issues, projects and comments: `embedTracker`'s answer. */
|
|
98
|
+
embeddings: v.optional(v.strictObject({
|
|
99
|
+
model: text,
|
|
100
|
+
embedded: count,
|
|
101
|
+
left: v.boolean(),
|
|
102
|
+
stopped: v.optional(v.picklist(["deadline", "cancelled"])),
|
|
103
|
+
remaining: v.optional(count),
|
|
104
|
+
})),
|
|
93
105
|
});
|
|
94
106
|
const partError = v.strictObject({ code: text, reason: v.optional(text), message: text });
|
|
95
107
|
/** The tracker's answer as `tracker_sync` has it, or the error it failed with, and the documents' answer or error. */
|
|
@@ -109,7 +121,11 @@ const resumeStep = (opts, why, extra = {}) => ({
|
|
|
109
121
|
kind: "command",
|
|
110
122
|
step: "tracker.sync",
|
|
111
123
|
command: "sync",
|
|
112
|
-
args: {
|
|
124
|
+
args: {
|
|
125
|
+
...(opts.maxPages === undefined ? {} : { max_pages: opts.maxPages }),
|
|
126
|
+
...(opts.embed ? { embed: true } : {}),
|
|
127
|
+
...extra,
|
|
128
|
+
},
|
|
113
129
|
why,
|
|
114
130
|
safe_to_auto_execute: true,
|
|
115
131
|
});
|
|
@@ -132,8 +148,13 @@ const trackerNext = (report, opts) => report.state === "partial" && report.progr
|
|
|
132
148
|
: "the sync stopped before its end; running it again goes on from there"),
|
|
133
149
|
]
|
|
134
150
|
: [];
|
|
135
|
-
|
|
136
|
-
|
|
151
|
+
/** Why `--embed` failed after the sync saved its report: a model not downloaded. */
|
|
152
|
+
const embeddingIssue = (error) => {
|
|
153
|
+
const { code, reason } = errorOf(error);
|
|
154
|
+
return { code, reason: reason ?? "sync.failed", source: "tracker:embeddings" };
|
|
155
|
+
};
|
|
156
|
+
const trackerAnswer = (report, opts, embedError) => {
|
|
157
|
+
const issues = [...trackerIssues(report), ...(embedError === undefined ? [] : [embeddingIssue(embedError)])];
|
|
137
158
|
const next = trackerNext(report, opts);
|
|
138
159
|
return itemOf(report, {
|
|
139
160
|
...(report.state === "partial" || issues.length
|
|
@@ -156,7 +177,7 @@ const errorOf = (error) => {
|
|
|
156
177
|
* Both parts in one answer: the tracker's report as `tracker_sync` has it, the documents' under `documents`. A part
|
|
157
178
|
* that fails is named in its place and in `meta.issues`, so the other's answer still shows; `complete` is both parts'.
|
|
158
179
|
*/
|
|
159
|
-
const combinedAnswer = (tracker, documents, opts) => {
|
|
180
|
+
const combinedAnswer = (tracker, documents, opts, embedError) => {
|
|
160
181
|
const failed = (part, error) => ({
|
|
161
182
|
code: error.code,
|
|
162
183
|
reason: error.reason ?? "sync.failed",
|
|
@@ -169,6 +190,7 @@ const combinedAnswer = (tracker, documents, opts) => {
|
|
|
169
190
|
const issues = [
|
|
170
191
|
...(report ? trackerIssues(report) : []),
|
|
171
192
|
...(trackerError ? [failed("tracker", trackerError)] : []),
|
|
193
|
+
...(embedError === undefined ? [] : [embeddingIssue(embedError)]),
|
|
172
194
|
...(outcome?.meta.issues ?? []),
|
|
173
195
|
...(documentsError ? [failed("documents", documentsError)] : []),
|
|
174
196
|
];
|
|
@@ -180,7 +202,6 @@ const combinedAnswer = (tracker, documents, opts) => {
|
|
|
180
202
|
? [
|
|
181
203
|
resumeStep(opts, trackerStep?.why ?? "the sync stopped before its end; running it again goes on from there", {
|
|
182
204
|
...(opts.timeout === undefined ? {} : { timeout: opts.timeout }),
|
|
183
|
-
...(opts.embed ? { embed: true } : {}),
|
|
184
205
|
}),
|
|
185
206
|
]
|
|
186
207
|
: []),
|
|
@@ -255,6 +276,21 @@ const addTrackerCommandsDefinition = (program, options) => {
|
|
|
255
276
|
...(opts.rescan ? { rescan: true } : {}),
|
|
256
277
|
});
|
|
257
278
|
};
|
|
279
|
+
// A run its budget stopped has no time left for the model; the run that finishes the round embeds.
|
|
280
|
+
const embedOf = async (command, run, report) => {
|
|
281
|
+
if (report.stopped)
|
|
282
|
+
return report;
|
|
283
|
+
const { signal, env } = environmentOf(command);
|
|
284
|
+
const deadline = environmentOf(command).deadline?.();
|
|
285
|
+
const embeddings = await embedTracker(run.store, {
|
|
286
|
+
maxChunks: EMBED_MAX,
|
|
287
|
+
...(deadline ? { deadline } : {}),
|
|
288
|
+
...(signal ? { signal } : {}),
|
|
289
|
+
...(env ? { env } : {}),
|
|
290
|
+
command: options.app.command,
|
|
291
|
+
});
|
|
292
|
+
return { ...report, embeddings };
|
|
293
|
+
};
|
|
258
294
|
const trackerPart = (command, opts, opened = () => { }) => inCommandRun(command, async () => {
|
|
259
295
|
const run = await options.open(command, { readOnly: false });
|
|
260
296
|
opened(run.account);
|
|
@@ -283,12 +319,28 @@ const addTrackerCommandsDefinition = (program, options) => {
|
|
|
283
319
|
? "at most this many requests for the issues in this run, and as many for the documents"
|
|
284
320
|
: "at most this many requests to the tracker in this run", integer(100_000));
|
|
285
321
|
if (!documents)
|
|
286
|
-
sync
|
|
287
|
-
|
|
322
|
+
sync
|
|
323
|
+
.option("--embed", "also index new issues, projects and comments for meaning search, with a model already downloaded")
|
|
324
|
+
.action(async (opts, command) => {
|
|
325
|
+
await within(command, false, async (run) => {
|
|
326
|
+
const report = await syncOf(command, opts)(run);
|
|
327
|
+
if (!opts.embed)
|
|
328
|
+
return trackerAnswer(report, opts);
|
|
329
|
+
try {
|
|
330
|
+
return trackerAnswer(await embedOf(command, run, report), opts);
|
|
331
|
+
}
|
|
332
|
+
catch (error) {
|
|
333
|
+
// What the sync saved is answered; a cancel still ends the command.
|
|
334
|
+
if (environmentOf(command).signal?.aborted)
|
|
335
|
+
throw error;
|
|
336
|
+
return trackerAnswer(report, opts, error);
|
|
337
|
+
}
|
|
338
|
+
});
|
|
288
339
|
});
|
|
289
340
|
else
|
|
290
341
|
sync
|
|
291
|
-
.option("--embed", "also index the documents' pending text for meaning search, with a
|
|
342
|
+
.option("--embed", "also index new issues, projects and comments and the documents' pending text for meaning search, with a " +
|
|
343
|
+
"model already downloaded")
|
|
292
344
|
.addOption(new Option("--limit <n>", "refused: it would count documents only").hideHelp().argParser(() => {
|
|
293
345
|
throw new InvalidArgumentError("--limit counts documents only, and this sync brings the issues too; --max-pages bounds both parts");
|
|
294
346
|
}))
|
|
@@ -314,6 +366,21 @@ const addTrackerCommandsDefinition = (program, options) => {
|
|
|
314
366
|
...(opts.embed ? { embed: true } : {}),
|
|
315
367
|
...(deadline ? { deadline } : {}),
|
|
316
368
|
}));
|
|
369
|
+
// A skipped documents part did not run, so a failed tracker part is the whole answer, as without documents.
|
|
370
|
+
if ("error" in tracker && "value" in docs && isSkipped(docs.value.item))
|
|
371
|
+
throw tracker.error;
|
|
372
|
+
// After both parts, so the documents get their sync's time first; outside the tracker's run, which has ended.
|
|
373
|
+
const embedded = opts.embed && "value" in tracker
|
|
374
|
+
? await settled(async () => {
|
|
375
|
+
const run = await options.open(command, { readOnly: false });
|
|
376
|
+
try {
|
|
377
|
+
return await embedOf(command, run, tracker.value);
|
|
378
|
+
}
|
|
379
|
+
finally {
|
|
380
|
+
await run.close?.();
|
|
381
|
+
}
|
|
382
|
+
})
|
|
383
|
+
: undefined;
|
|
317
384
|
if ("error" in tracker && "error" in docs) {
|
|
318
385
|
const failed = errorOf(docs.error);
|
|
319
386
|
// An error envelope has no meta and keeps only the details its reason registers, so the documents'
|
|
@@ -324,7 +391,7 @@ const addTrackerCommandsDefinition = (program, options) => {
|
|
|
324
391
|
: tracker.error;
|
|
325
392
|
}
|
|
326
393
|
const timeout = command.optsWithGlobals().timeout;
|
|
327
|
-
const answer = combinedAnswer(tracker, docs, { ...opts, ...(timeout === undefined ? {} : { timeout }) });
|
|
394
|
+
const answer = combinedAnswer(embedded && "value" in embedded ? embedded : tracker, docs, { ...opts, ...(timeout === undefined ? {} : { timeout }) }, embedded && "error" in embedded ? embedded.error : undefined);
|
|
328
395
|
renderAnswer(command, outputFor(command), answer);
|
|
329
396
|
if ("value" in docs)
|
|
330
397
|
for (const line of docs.value.diagnostics)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wirecat/cli-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.730.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",
|