@wirecat/cli-core 0.735.0 → 0.736.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +64 -0
- package/dist/background/daily-archive-timer.d.ts +1 -1
- package/dist/background/report/messages.d.ts +4 -0
- package/dist/background/report/messages.js +2 -0
- package/dist/background/report/templates/schedule-failed.email.en.liquid +2 -1
- package/dist/background/report/templates/schedule-failed.email.ru.liquid +2 -1
- package/dist/background/report/templates/schedule-failed.sample.json +2 -1
- package/dist/background/report/templates/schedule-failed.telegram.en.liquid +2 -1
- package/dist/background/report/templates/schedule-failed.telegram.ru.liquid +2 -1
- package/dist/background/report/templates/schedule-failed.text.en.liquid +2 -1
- package/dist/background/report/templates/schedule-failed.text.ru.liquid +2 -1
- package/dist/background/schedules.js +11 -7
- package/dist/cli/documents/file-edit.d.ts +4 -4
- package/dist/cli/documents/file-edit.js +69 -5
- package/dist/cli/enrichment-consents-command.js +2 -1
- package/dist/cli/messenger/catch-up-answers.js +1 -0
- package/dist/cli/messenger/download-command.js +3 -0
- package/dist/cli/messenger/inbox.js +4 -1
- package/dist/cli/messenger/review.js +4 -1
- package/dist/cli/messenger/search-answers.js +1 -0
- package/dist/cli/schedule/schedule-command.js +10 -1
- package/dist/cli/search-harder-consents-command.js +2 -1
- package/dist/cli/templates-command.js +7 -6
- package/dist/crm/cli/records.js +16 -1
- package/dist/domain/models.d.ts +4 -0
- package/dist/domain/providers.d.ts +7 -0
- package/dist/domain/providers.js +15 -2
- package/dist/entities/hit.d.ts +2 -0
- package/dist/entities/hit.js +2 -0
- package/dist/entities/index.d.ts +1 -0
- package/dist/errors/reasons.js +9 -2
- package/dist/office/create.d.ts +34 -0
- package/dist/office/create.js +216 -0
- package/dist/office/index.d.ts +1 -0
- package/dist/office/index.js +1 -0
- package/dist/office/package.d.ts +1 -0
- package/dist/office/package.js +1 -1
- package/dist/ports/messenger.d.ts +5 -2
- package/dist/search/word-match.d.ts +16 -0
- package/dist/search/word-match.js +28 -0
- package/dist/sends/upload.d.ts +3 -0
- package/dist/sends/upload.js +2 -2
- package/dist/services/documents/ingestion.js +4 -2
- package/dist/services/file-download.js +4 -2
- package/dist/services/inbox.js +5 -2
- package/dist/services/metadata.d.ts +1 -1
- package/dist/services/search-all.d.ts +2 -0
- package/dist/services/search-all.js +47 -17
- package/dist/store/sqlite/crm-rows.d.ts +4 -0
- package/dist/store/sqlite/crm-rows.js +30 -0
- package/dist/store/sqlite/crm.d.ts +2 -0
- package/dist/store/sqlite/crm.js +3 -10
- package/dist/store/sqlite/deals.js +1 -24
- package/dist/store/sqlite/tracker-chunks.d.ts +24 -8
- package/dist/store/sqlite/tracker-chunks.js +137 -38
- package/dist/store/sqlite/tracker.d.ts +5 -0
- package/dist/store/sqlite/tracker.js +118 -17
- package/dist/tracker/cli/index.js +1 -1
- package/package.json +1 -1
|
@@ -14,12 +14,12 @@ export declare const metadataService: (deps: ServiceDeps) => {
|
|
|
14
14
|
dryRun?: boolean;
|
|
15
15
|
}) => Promise<{
|
|
16
16
|
items: ({
|
|
17
|
+
error?: undefined;
|
|
17
18
|
chatId: string;
|
|
18
19
|
tags: import("../domain/channel-tags.js").ChannelTagMatch[];
|
|
19
20
|
algorithm: string;
|
|
20
21
|
fetchedAt: string | null;
|
|
21
22
|
source: string;
|
|
22
|
-
error?: undefined;
|
|
23
23
|
} | {
|
|
24
24
|
tags?: undefined;
|
|
25
25
|
algorithm?: undefined;
|
|
@@ -41,6 +41,8 @@ export interface SearchAllRecordItem {
|
|
|
41
41
|
email?: MailFields;
|
|
42
42
|
/** A message's or a mail's files, as `search messages` names them. */
|
|
43
43
|
attachments?: HitFile[];
|
|
44
|
+
/** A tracker hit that more than one sign-in holds: every account it was found in, `account` first. */
|
|
45
|
+
accounts?: string[];
|
|
44
46
|
/** Which search found it: words, meaning or both; a deal or a lead by `title`, or `words` of its company or contacts. */
|
|
45
47
|
foundBy: ("title" | "words" | "meaning")[];
|
|
46
48
|
/** A deal's or a lead's: `corrected` when it matched only once a misspelt query word was corrected. */
|
|
@@ -4,7 +4,7 @@ import { crmViewerOf } from "../crm/index.js";
|
|
|
4
4
|
import { hitFiles } from "../domain/attachments.js";
|
|
5
5
|
import { parseLocator } from "../domain/locator.js";
|
|
6
6
|
import { senderIsMe } from "../domain/models.js";
|
|
7
|
-
import { holdsKind, INTERNAL_NOTES, isDocumentAccountProvider } from "../domain/providers.js";
|
|
7
|
+
import { hasGlobalItemIds, holdsKind, INTERNAL_NOTES, isDocumentAccountProvider } from "../domain/providers.js";
|
|
8
8
|
import { trackerBodyOf, trackerTitleOf } from "../domain/tracker.js";
|
|
9
9
|
import { runEmbedders } from "../embeddings/embed.js";
|
|
10
10
|
import { chosenTextModel } from "../embeddings/models.js";
|
|
@@ -165,6 +165,27 @@ const trackerMeaningWords = (text) => {
|
|
|
165
165
|
}
|
|
166
166
|
};
|
|
167
167
|
const trackerExcerpt = ({ kind, record }, query) => excerpt([trackerTitleOf(kind, record), trackerBodyOf(kind, record)].filter(Boolean).join("\n"), query);
|
|
168
|
+
/**
|
|
169
|
+
* One hit per tracker item, best first: the copies other sign-ins hold of one item (`items` maps a hit's ref to the
|
|
170
|
+
* item, for a provider whose ids name one item across its accounts) join the best-placed one, which names every account and takes the best cosine and every way any was found.
|
|
171
|
+
*/
|
|
172
|
+
const oneHitPerItem = (ordered, cosines, items) => {
|
|
173
|
+
const kept = new Map();
|
|
174
|
+
for (const hit of ordered) {
|
|
175
|
+
const key = items.get(hit.ref) ?? hit.ref;
|
|
176
|
+
const held = kept.get(key);
|
|
177
|
+
if (!held) {
|
|
178
|
+
kept.set(key, hit);
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
held.accounts = [...(held.accounts ?? [held.account]), hit.account];
|
|
182
|
+
held.foundBy = ["words", "meaning"].filter((by) => [held, hit].some(({ foundBy }) => foundBy.includes(by)));
|
|
183
|
+
const cosine = cosines.get(hit.ref);
|
|
184
|
+
if (cosine !== undefined && cosine > (cosines.get(held.ref) ?? Number.NEGATIVE_INFINITY))
|
|
185
|
+
cosines.set(held.ref, cosine);
|
|
186
|
+
}
|
|
187
|
+
return [...kept.values()];
|
|
188
|
+
};
|
|
168
189
|
/** The accounts of every CRM the store holds copies of. */
|
|
169
190
|
export const crmAccounts = async (store) => (await store.accounts.accounts()).filter(({ provider }) => holdsKind(provider, "crm"));
|
|
170
191
|
/**
|
|
@@ -444,27 +465,36 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
|
|
|
444
465
|
if (!read.length)
|
|
445
466
|
continue;
|
|
446
467
|
const { words, anyWord } = titleWords(request.text, "issues, projects and comments are found by the words and meaning of their title and text only");
|
|
468
|
+
// Two sign-ins to one workspace hold each item twice, and the copies fold into one hit: read deep enough
|
|
469
|
+
// that the folded list still fills the page.
|
|
470
|
+
const deep = Math.min(depth * read.length, 500);
|
|
447
471
|
const found = await store.tracker.find({
|
|
448
472
|
words,
|
|
449
473
|
anyWord: anyWord || discover,
|
|
450
474
|
...(request.exact ? { exact: true } : {}),
|
|
451
475
|
kinds: ["issue", "project", "comment"],
|
|
452
|
-
limit:
|
|
476
|
+
limit: deep,
|
|
453
477
|
accounts: read,
|
|
454
478
|
});
|
|
455
479
|
hasMore ||= found.hasMore;
|
|
456
|
-
const
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
480
|
+
const items = new Map();
|
|
481
|
+
const hitOf = (at, item, text, foundBy) => {
|
|
482
|
+
const ref = `tracker:${at.provider}/${at.account}/${item.kind}/${item.record.externalId}`;
|
|
483
|
+
if (hasGlobalItemIds(at.provider))
|
|
484
|
+
items.set(ref, JSON.stringify([at.provider, item.kind, item.record.externalId]));
|
|
485
|
+
return {
|
|
486
|
+
kind: TRACKER_HIT_KINDS[item.kind],
|
|
487
|
+
// Two sign-ins see the same issue under the same id, so the account keeps their hits apart.
|
|
488
|
+
ref,
|
|
489
|
+
provider: at.provider,
|
|
490
|
+
account: at.account,
|
|
491
|
+
...(item.record.url ? { url: item.record.url } : {}),
|
|
492
|
+
title: trackerTitle(item),
|
|
493
|
+
timestamp: new Date(item.record.updatedAt ?? item.syncedAt).toISOString(),
|
|
494
|
+
text,
|
|
495
|
+
foundBy,
|
|
496
|
+
};
|
|
497
|
+
};
|
|
468
498
|
const byWords = found.items.map(({ account: at, item, excerpt: text }) => hitOf(at, item, text, ["words"]));
|
|
469
499
|
const plain = trackerMeaningWords(discover ? questionText(request.text) : request.text);
|
|
470
500
|
let near;
|
|
@@ -476,7 +506,7 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
|
|
|
476
506
|
else
|
|
477
507
|
try {
|
|
478
508
|
near = await nearestTracker(store, plain, {
|
|
479
|
-
limit:
|
|
509
|
+
limit: deep,
|
|
480
510
|
accounts: read,
|
|
481
511
|
embedders,
|
|
482
512
|
...(command === undefined ? {} : { command }),
|
|
@@ -493,7 +523,7 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
|
|
|
493
523
|
...(meaningSkipped === undefined ? {} : { meaningSkipped }),
|
|
494
524
|
};
|
|
495
525
|
if (near === undefined)
|
|
496
|
-
lists.push(byWords);
|
|
526
|
+
lists.push(oneHitPerItem(byWords, cosines, items));
|
|
497
527
|
else {
|
|
498
528
|
// As notes and messages fuse theirs: one list for the lane, a question's hit voting once.
|
|
499
529
|
const fused = new Map();
|
|
@@ -512,7 +542,7 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
|
|
|
512
542
|
else
|
|
513
543
|
fused.set(hit.ref, { item: held?.item ?? hit, score: (held?.score ?? 0) + vote });
|
|
514
544
|
});
|
|
515
|
-
lists.push([...fused.values()].sort((a, b) => b.score - a.score).map(({ item }) => item));
|
|
545
|
+
lists.push(oneHitPerItem([...fused.values()].sort((a, b) => b.score - a.score).map(({ item }) => item), cosines, items));
|
|
516
546
|
}
|
|
517
547
|
for (const { provider, account } of read)
|
|
518
548
|
accounts.push({ resource, provider, account });
|
|
@@ -28,6 +28,10 @@ export declare const PERSON_RECORD = "crm.person";
|
|
|
28
28
|
export declare const crmIdentityId: (key: AccountKey, externalId: string, type?: "contact" | "user") => string;
|
|
29
29
|
/** What every contact identity of the account starts with. */
|
|
30
30
|
export declare const crmAccountPrefix: (key: AccountKey) => string;
|
|
31
|
+
/** The stored copy's `deal:<id>` or `lead:<id>`, deleted or not. */
|
|
32
|
+
export declare const crmRefOf: (context: StoreContext, key: AccountKey, kind: DealKind, externalId: string) => string | null;
|
|
33
|
+
/** The CRM's ids behind the copy's `organization:<id>` (its record) or `person:<id>` (its contacts, unescaped). */
|
|
34
|
+
export declare const crmExternalIdsOf: (context: StoreContext, key: AccountKey, ref: string) => string[];
|
|
31
35
|
export declare const day: (value: unknown, what: string) => string | null;
|
|
32
36
|
export declare const epoch: (value: unknown, fallback: number) => number;
|
|
33
37
|
export declare const textOf: (value: unknown, most: number) => string | null;
|
|
@@ -4,6 +4,7 @@ import { STAGE_OUTCOMES } from "../../domain/deals.js";
|
|
|
4
4
|
import { dayIn } from "../../domain/moment.js";
|
|
5
5
|
import { currencyOf, minorUnits, scaleOf } from "../../domain/money.js";
|
|
6
6
|
import { fold } from "../normalize.js";
|
|
7
|
+
import { findAccountPk } from "./accounts.js";
|
|
7
8
|
import { authorActor } from "./memories.js";
|
|
8
9
|
export const TABLES = { deal: "deals", lead: "leads" };
|
|
9
10
|
const MONEY_REFUSALS = ["money.currency", "money.amount"];
|
|
@@ -60,6 +61,35 @@ export const crmIdentityId = (key, externalId, type = "contact") => `${idPart(ke
|
|
|
60
61
|
const idPart = (value) => value.replaceAll("%", "%25").replaceAll("/", "%2F");
|
|
61
62
|
/** What every contact identity of the account starts with. */
|
|
62
63
|
export const crmAccountPrefix = (key) => `${idPart(key.account)}/`;
|
|
64
|
+
/** The stored copy's `deal:<id>` or `lead:<id>`, deleted or not. */
|
|
65
|
+
export const crmRefOf = (context, key, kind, externalId) => {
|
|
66
|
+
const accountId = findAccountPk(context, key);
|
|
67
|
+
const row = accountId === undefined
|
|
68
|
+
? undefined
|
|
69
|
+
: context.database
|
|
70
|
+
.prepare(`SELECT id FROM ${TABLES[kind]} WHERE account_id = ? AND external_id = ?`)
|
|
71
|
+
.get(accountId, externalId);
|
|
72
|
+
return row ? `${kind}:${row.id}` : null;
|
|
73
|
+
};
|
|
74
|
+
/** The CRM's ids behind the copy's `organization:<id>` (its record) or `person:<id>` (its contacts, unescaped). */
|
|
75
|
+
export const crmExternalIdsOf = (context, key, ref) => {
|
|
76
|
+
const [, kind, id] = /^(person|organization):(\d+)$/.exec(ref) ?? [];
|
|
77
|
+
const accountId = findAccountPk(context, key);
|
|
78
|
+
if (!kind || accountId === undefined)
|
|
79
|
+
return [];
|
|
80
|
+
if (kind === "organization")
|
|
81
|
+
return context.database
|
|
82
|
+
.prepare("SELECT external_id FROM records WHERE account_id = ? AND type = 'organization' " +
|
|
83
|
+
"AND entity_type = 'organization' AND entity_id = ? AND deleted_at IS NULL ORDER BY external_id")
|
|
84
|
+
.all(accountId, Number(id))
|
|
85
|
+
.map((row) => String(row.external_id));
|
|
86
|
+
const prefix = `${crmAccountPrefix(key)}contact/`;
|
|
87
|
+
return context.database
|
|
88
|
+
.prepare("SELECT i.external_id FROM identities i JOIN identity_links l ON l.identity_id = i.id " +
|
|
89
|
+
"WHERE i.provider = ? AND l.person_id = ? AND substr(i.external_id, 1, ?) = ? ORDER BY i.external_id")
|
|
90
|
+
.all(key.provider, Number(id), prefix.length, prefix)
|
|
91
|
+
.map((row) => decodeURIComponent(String(row.external_id).slice(prefix.length)));
|
|
92
|
+
};
|
|
63
93
|
export const day = (value, what) => {
|
|
64
94
|
if (value === undefined || value === null || value === "")
|
|
65
95
|
return null;
|
|
@@ -142,6 +142,8 @@ export interface CrmCopies extends CrmReads {
|
|
|
142
142
|
count(key: AccountKey, kind: CrmKind): Promise<number>;
|
|
143
143
|
/** The stored copy's `deal:<id>` or `lead:<id>`, deleted or not; `null` when the store holds none. */
|
|
144
144
|
refOf(key: AccountKey, kind: DealKind, externalId: string): Promise<string | null>;
|
|
145
|
+
/** The CRM's ids behind a deal's `organization:<id>` or `person:<id>`: two for a merged person, none for the owner. */
|
|
146
|
+
externalIdsOf(key: AccountKey, ref: string): Promise<string[]>;
|
|
145
147
|
}
|
|
146
148
|
export type { CrmActivitiesSaved, StoredActivity } from "./crm-activities.js";
|
|
147
149
|
export type { CrmContactsRemoved } from "./crm-contacts.js";
|
package/dist/store/sqlite/crm.js
CHANGED
|
@@ -7,7 +7,7 @@ import { suggestBaseStages } from "./base-suggest.js";
|
|
|
7
7
|
import { crmActivitiesOver, forgetActivitiesOn, } from "./crm-activities.js";
|
|
8
8
|
import { crmReadsOver } from "./crm-changes.js";
|
|
9
9
|
import { removeCrmContacts } from "./crm-contacts.js";
|
|
10
|
-
import { crmAccountPrefix, crmIdentityId, crmRowsOver, PERSON_RECORD, SOURCE, TABLES, textOf, } from "./crm-rows.js";
|
|
10
|
+
import { crmAccountPrefix, crmExternalIdsOf, crmIdentityId, crmRefOf, crmRowsOver, PERSON_RECORD, SOURCE, TABLES, textOf, } from "./crm-rows.js";
|
|
11
11
|
import { crmActivitiesOn, crmCompanyTypes, crmOwnUser, crmScope, crmScopeUsers, crmSettingKey, crmStageMoves, crmStageTasks, crmStageTasksSince, saveCrmSetting, saveStageMovesMark, } from "./crm-settings.js";
|
|
12
12
|
import { crmStageEntriesOver } from "./crm-stage-entries.js";
|
|
13
13
|
import { syncReportedIn } from "./reported-relations.js";
|
|
@@ -694,14 +694,7 @@ export const crmCopiesOver = (context, people) => {
|
|
|
694
694
|
.prepare("SELECT count(*) AS n FROM identities WHERE provider = ? AND substr(external_id, 1, ?) = ?")
|
|
695
695
|
.get(key.provider, crmAccountPrefix(key).length, crmAccountPrefix(key))?.n)
|
|
696
696
|
: stored(key, kind).length,
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
const row = accountId === undefined
|
|
700
|
-
? undefined
|
|
701
|
-
: database
|
|
702
|
-
.prepare(`SELECT id FROM ${TABLES[kind]} WHERE account_id = ? AND external_id = ?`)
|
|
703
|
-
.get(accountId, externalId);
|
|
704
|
-
return row ? `${kind}:${row.id}` : null;
|
|
705
|
-
},
|
|
697
|
+
externalIdsOf: async (key, ref) => crmExternalIdsOf(context, key, ref),
|
|
698
|
+
refOf: async (key, kind, externalId) => crmRefOf(context, key, kind, externalId),
|
|
706
699
|
};
|
|
707
700
|
};
|
|
@@ -5,7 +5,7 @@ import { dayIn } from "../../domain/moment.js";
|
|
|
5
5
|
import { currencyOf, formatDecimal, minorUnits, scaleOf } from "../../domain/money.js";
|
|
6
6
|
import { notOverriddenSql } from "../../domain/relations.js";
|
|
7
7
|
import { correctWords } from "../../search/correct.js";
|
|
8
|
-
import {
|
|
8
|
+
import { clauseIn, probeOf, tokensOf, wordMatches } from "../../search/word-match.js";
|
|
9
9
|
import { fold } from "../normalize.js";
|
|
10
10
|
import { proposedBySql } from "./actors.js";
|
|
11
11
|
import { suggestBaseStages } from "./base-suggest.js";
|
|
@@ -54,29 +54,6 @@ const providerMetadataOf = (metadata) => {
|
|
|
54
54
|
};
|
|
55
55
|
const accountOf = (provider, external) => provider == null ? null : { provider: String(provider), account: String(external) };
|
|
56
56
|
const DEAL_PARTS = ["title", "company", "contact", "activity"];
|
|
57
|
-
const TOKEN = /[\p{L}\p{N}\p{M}]+/gu;
|
|
58
|
-
/** A query word shorter than this matches only a whole word: «с» or "a" begins half the words of any title. */
|
|
59
|
-
const SHORTEST_BEGINNING = 4;
|
|
60
|
-
const stemmer = createStemmer(DEFAULT_STEMMERS, { cacheLimit: 20_000 });
|
|
61
|
-
const stemsOf = (token) => stemmer.stemSequences(token).flat();
|
|
62
|
-
const probeOf = (token) => ({ literal: fold(token), stems: stemsOf(token) });
|
|
63
|
-
const tokensOf = (text) => text.normalize("NFC").toLowerCase().match(TOKEN) ?? [];
|
|
64
|
-
const wordMatches = (probe, word, exact) => {
|
|
65
|
-
if (word.literal === probe.literal)
|
|
66
|
-
return true;
|
|
67
|
-
if (exact)
|
|
68
|
-
return false;
|
|
69
|
-
if (probe.literal.length >= SHORTEST_BEGINNING && word.literal.startsWith(probe.literal))
|
|
70
|
-
return true;
|
|
71
|
-
// A stem begins its word, so a word that does not start like the stem needs no stemming.
|
|
72
|
-
return (probe.stems.some((stem) => word.literal.startsWith(stem.slice(0, 3))) &&
|
|
73
|
-
stemsOf(word.token).some((stem) => probe.stems.includes(stem)));
|
|
74
|
-
};
|
|
75
|
-
/** A clause of several words, `КТП-630` or an e-mail, matches only where they follow each other. */
|
|
76
|
-
const clauseIn = (clause, words, exact) => words.some((_, at) => clause.every((alternatives, offset) => {
|
|
77
|
-
const word = words[at + offset];
|
|
78
|
-
return word !== undefined && alternatives.some((probe) => wordMatches(probe, word, exact));
|
|
79
|
-
}));
|
|
80
57
|
const listOf = (json) => {
|
|
81
58
|
if (typeof json !== "string")
|
|
82
59
|
return [];
|
|
@@ -2,27 +2,39 @@ import { type CacheDatabase } from "../driver.js";
|
|
|
2
2
|
/** `chunks.chunkable_type` of an issue's, a project's or a comment's pieces; `chunkable_id` is `tracker_items.id`. */
|
|
3
3
|
export declare const TRACKER_CHUNK = "tracker_item";
|
|
4
4
|
export declare const isChunkedTrackerKind: (kind: string) => boolean;
|
|
5
|
+
/**
|
|
6
|
+
* A comment with fewer characters than this, spaces and line breaks around it aside, is not embedded: `LGTM`, `+1`,
|
|
7
|
+
* «Спасибо» say nothing alone, and with their issue in front each became a near copy of the issue that filled the
|
|
8
|
+
* first results (cli-testing performance/search/tracker-meaning). Its words still find it.
|
|
9
|
+
*/
|
|
10
|
+
export declare const SHORTEST_EMBEDDED_COMMENT = 16;
|
|
5
11
|
export interface ChunkedItem {
|
|
6
12
|
id: number;
|
|
7
13
|
accountId: number;
|
|
8
14
|
kind: string;
|
|
9
15
|
title: string;
|
|
10
16
|
body: string | null;
|
|
17
|
+
/** A comment's issue, by the tracker's id. */
|
|
18
|
+
parent: string | null;
|
|
11
19
|
occurredAt: number;
|
|
12
20
|
scope: string | null;
|
|
13
21
|
}
|
|
14
22
|
/**
|
|
15
|
-
* Inside the caller's write: makes each item's chunks its text's, and answers the hashes it released
|
|
16
|
-
* when they already were. The caller drops the vectors of those once every new chunk is in, so a text another item or
|
|
23
|
+
* Inside the caller's write: makes each item's chunks its text's, and answers the hashes it released and how many
|
|
24
|
+
* chunks it wrote, or `undefined` when they already were. The caller drops the vectors of those once every new chunk is in, so a text another item or
|
|
17
25
|
* account still holds keeps its vector.
|
|
18
26
|
*/
|
|
19
|
-
export declare const trackerChunkWriter: (database: CacheDatabase) => (item: ChunkedItem, at: number) =>
|
|
27
|
+
export declare const trackerChunkWriter: (database: CacheDatabase) => (item: ChunkedItem, at: number) => {
|
|
28
|
+
released: string[];
|
|
29
|
+
written: number;
|
|
30
|
+
} | undefined;
|
|
20
31
|
/** Inside the caller's write: drops the chunks of these items and the vectors no other chunk holds. */
|
|
21
32
|
export declare const dropTrackerChunks: (database: CacheDatabase, ids: readonly number[]) => void;
|
|
22
33
|
/**
|
|
23
|
-
* Drops the chunks of items the tracker no longer lists,
|
|
24
|
-
*
|
|
25
|
-
* deadline stops it with `left
|
|
34
|
+
* Drops the chunks of items the tracker no longer lists, cuts the comments of a store cut before the current `CUT`
|
|
35
|
+
* again, then cuts the chunks of live items that have none: those saved before tracker items were searched by meaning.
|
|
36
|
+
* Short write transactions, `until` asked before each, so a deadline stops it with `left` and the next run goes on
|
|
37
|
+
* from there; nothing under a read-only store.
|
|
26
38
|
*/
|
|
27
39
|
export declare const refreshTrackerChunks: (database: CacheDatabase, now: number, until?: () => boolean) => {
|
|
28
40
|
dropped: number;
|
|
@@ -30,11 +42,15 @@ export declare const refreshTrackerChunks: (database: CacheDatabase, now: number
|
|
|
30
42
|
left: boolean;
|
|
31
43
|
};
|
|
32
44
|
export declare const trackerChunksLeft: (database: CacheDatabase, model: string) => number;
|
|
33
|
-
/**
|
|
45
|
+
/**
|
|
46
|
+
* Live items' chunks with no vector of `model`, by hash from `after`, each with its text cut again. A chunk whose text
|
|
47
|
+
* no longer hashes to its hash was cut another way, by an older build sharing the store: its item is cut again (never
|
|
48
|
+
* under a read-only store) and the chunk left out, so no vector is made of other text than its hash names.
|
|
49
|
+
*/
|
|
34
50
|
export declare const trackerChunksToEmbed: (database: CacheDatabase, model: string, { after, limit }: {
|
|
35
51
|
after?: string;
|
|
36
52
|
limit: number;
|
|
37
|
-
}) => {
|
|
53
|
+
}, now?: number) => {
|
|
38
54
|
hash: string;
|
|
39
55
|
text: string;
|
|
40
56
|
}[];
|
|
@@ -10,19 +10,52 @@ export const TRACKER_CHUNK = "tracker_item";
|
|
|
10
10
|
const CHUNKED = new Set(["issue", "project", "comment"]);
|
|
11
11
|
const CHUNKED_SQL = "('issue', 'project', 'comment')";
|
|
12
12
|
export const isChunkedTrackerKind = (kind) => CHUNKED.has(kind);
|
|
13
|
-
/**
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
13
|
+
/**
|
|
14
|
+
* A comment with fewer characters than this, spaces and line breaks around it aside, is not embedded: `LGTM`, `+1`,
|
|
15
|
+
* «Спасибо» say nothing alone, and with their issue in front each became a near copy of the issue that filled the
|
|
16
|
+
* first results (cli-testing performance/search/tracker-meaning). Its words still find it.
|
|
17
|
+
*/
|
|
18
|
+
export const SHORTEST_EMBEDDED_COMMENT = 16;
|
|
19
|
+
/** What the chunks hold; raised with each change to `textOf`, so a store cut before is cut again once. */
|
|
20
|
+
const CUT = "comments after their issue's key and title";
|
|
21
|
+
const CUT_SETTING = "tracker_chunks_cut";
|
|
22
|
+
const RECUT_AFTER = "tracker_chunks_recut_after";
|
|
23
|
+
// SQLite's `trim` and `length` take spaces and code points; JavaScript's `trim` takes more, and `length` counts halves.
|
|
24
|
+
const EDGE = /^[ \t\n\r]+|[ \t\n\r]+$/gu;
|
|
25
|
+
const embeddedComment = (body) => [...(body ?? "").replace(EDGE, "")].length >= SHORTEST_EMBEDDED_COMMENT;
|
|
26
|
+
const EDGE_SQL = "' ' || char(9, 10, 13)";
|
|
27
|
+
const EMBEDDED_COMMENT_SQL = `length(trim(coalesce(t.body, ''), ${EDGE_SQL})) >= ${SHORTEST_EMBEDDED_COMMENT}`;
|
|
28
|
+
/**
|
|
29
|
+
* What an item is embedded as, from its stored columns: chunk offsets point into it. A comment's issue goes in front:
|
|
30
|
+
* "it works now" means something only beside the issue it answers.
|
|
31
|
+
*/
|
|
32
|
+
const textOf = (kind, title, body, issue) => {
|
|
33
|
+
if (kind !== "comment")
|
|
34
|
+
return noteIndexText(title, body ?? "");
|
|
35
|
+
if (!embeddedComment(body))
|
|
36
|
+
return "";
|
|
37
|
+
const heading = issue ? [issue.key, issue.title].filter(Boolean).join(" ") : "";
|
|
38
|
+
return heading ? `${heading}\n\n${body}` : (body ?? "");
|
|
39
|
+
};
|
|
40
|
+
/** The issue a comment is on, as its account holds it; a deleted one still names what the comment answered. */
|
|
41
|
+
const issueOf = (database) => {
|
|
42
|
+
const read = database.prepare("SELECT title, json_extract(data, '$.key') AS key FROM tracker_items " +
|
|
43
|
+
"WHERE account_id = ? AND kind = 'issue' AND external_id = ?");
|
|
44
|
+
return (kind, accountId, parent) => {
|
|
45
|
+
if (kind !== "comment" || parent === null)
|
|
46
|
+
return undefined;
|
|
47
|
+
const row = read.get(accountId, parent);
|
|
48
|
+
return row ? { key: row.key == null ? null : String(row.key), title: String(row.title) } : undefined;
|
|
49
|
+
};
|
|
50
|
+
};
|
|
51
|
+
const piecesOf = (text) => {
|
|
19
52
|
if (!text.trim())
|
|
20
53
|
return [];
|
|
21
54
|
return splitText(text, CHUNK_CHARS).map(({ start, end }) => ({ start, end, hash: chunkHash(text.slice(start, end)) }));
|
|
22
55
|
};
|
|
23
56
|
/**
|
|
24
|
-
* Inside the caller's write: makes each item's chunks its text's, and answers the hashes it released
|
|
25
|
-
* when they already were. The caller drops the vectors of those once every new chunk is in, so a text another item or
|
|
57
|
+
* Inside the caller's write: makes each item's chunks its text's, and answers the hashes it released and how many
|
|
58
|
+
* chunks it wrote, or `undefined` when they already were. The caller drops the vectors of those once every new chunk is in, so a text another item or
|
|
26
59
|
* account still holds keeps its vector.
|
|
27
60
|
*/
|
|
28
61
|
export const trackerChunkWriter = (database) => {
|
|
@@ -31,8 +64,11 @@ export const trackerChunkWriter = (database) => {
|
|
|
31
64
|
const drop = database.prepare(`DELETE FROM chunks WHERE chunkable_type = '${TRACKER_CHUNK}' AND chunkable_id = ?`);
|
|
32
65
|
const insert = database.prepare("INSERT INTO chunks (chunkable_type, chunkable_id, position, start_offset, end_offset, content_hash, scope, " +
|
|
33
66
|
`account_id, occurred_at, created_at, updated_at) VALUES ('${TRACKER_CHUNK}', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
|
67
|
+
const issue = issueOf(database);
|
|
34
68
|
return (item, at) => {
|
|
35
|
-
|
|
69
|
+
if (!CHUNKED.has(item.kind))
|
|
70
|
+
return undefined;
|
|
71
|
+
const wanted = piecesOf(textOf(item.kind, item.title, item.body, issue(item.kind, item.accountId, item.parent)));
|
|
36
72
|
const before = held.all(item.id).map((row) => ({
|
|
37
73
|
start: Number(row.start),
|
|
38
74
|
end: Number(row.end),
|
|
@@ -49,7 +85,7 @@ export const trackerChunkWriter = (database) => {
|
|
|
49
85
|
wanted.forEach(({ start, end, hash }, position) => {
|
|
50
86
|
insert.run(item.id, position, start, end, hash, item.scope, item.accountId, item.occurredAt, at, at);
|
|
51
87
|
});
|
|
52
|
-
return before.map(({ hash }) => hash);
|
|
88
|
+
return { released: before.map(({ hash }) => hash), written: wanted.length };
|
|
53
89
|
};
|
|
54
90
|
};
|
|
55
91
|
/** Inside the caller's write: drops the chunks of these items and the vectors no other chunk holds. */
|
|
@@ -64,10 +100,23 @@ export const dropTrackerChunks = (database, ids) => {
|
|
|
64
100
|
dropUnusedVectors(database, released);
|
|
65
101
|
};
|
|
66
102
|
const BACKFILL = 200;
|
|
103
|
+
const chunkedOf = (row) => ({
|
|
104
|
+
id: Number(row.id),
|
|
105
|
+
accountId: Number(row.account_id),
|
|
106
|
+
kind: String(row.kind),
|
|
107
|
+
title: String(row.title),
|
|
108
|
+
body: row.body == null ? null : String(row.body),
|
|
109
|
+
parent: row.parent_id == null ? null : String(row.parent_id),
|
|
110
|
+
occurredAt: Number(row.at),
|
|
111
|
+
scope: row.scope == null ? null : String(row.scope),
|
|
112
|
+
});
|
|
113
|
+
const ITEM_COLUMNS = "t.id, t.account_id, t.kind, t.title, t.body, t.parent_id, coalesce(t.source_updated_at, t.synced_at) AS at, a.scope";
|
|
114
|
+
const setting = (database, key) => database.prepare("SELECT value FROM store_settings WHERE key = ?").get(key)?.value;
|
|
67
115
|
/**
|
|
68
|
-
* Drops the chunks of items the tracker no longer lists,
|
|
69
|
-
*
|
|
70
|
-
* deadline stops it with `left
|
|
116
|
+
* Drops the chunks of items the tracker no longer lists, cuts the comments of a store cut before the current `CUT`
|
|
117
|
+
* again, then cuts the chunks of live items that have none: those saved before tracker items were searched by meaning.
|
|
118
|
+
* Short write transactions, `until` asked before each, so a deadline stops it with `left` and the next run goes on
|
|
119
|
+
* from there; nothing under a read-only store.
|
|
71
120
|
*/
|
|
72
121
|
export const refreshTrackerChunks = (database, now, until = () => false) => {
|
|
73
122
|
if (isQueryOnly(database))
|
|
@@ -82,34 +131,64 @@ export const refreshTrackerChunks = (database, now, until = () => false) => {
|
|
|
82
131
|
dropUnusedVectors(database, gone);
|
|
83
132
|
return gone.length;
|
|
84
133
|
});
|
|
134
|
+
const chunk = trackerChunkWriter(database);
|
|
135
|
+
let added = 0;
|
|
136
|
+
// A store with no tracker chunks has nothing cut the old way: every chunk it gets is cut the current way.
|
|
137
|
+
if (setting(database, CUT_SETTING) !== CUT &&
|
|
138
|
+
!database.prepare(`SELECT 1 FROM chunks WHERE chunkable_type = '${TRACKER_CHUNK}' LIMIT 1`).get())
|
|
139
|
+
write(database, () => database
|
|
140
|
+
.prepare("INSERT OR REPLACE INTO store_settings (key, value, at) VALUES (?, ?, ?)")
|
|
141
|
+
.run(CUT_SETTING, CUT, now));
|
|
142
|
+
if (setting(database, CUT_SETTING) !== CUT) {
|
|
143
|
+
const comments = database.prepare(`SELECT ${ITEM_COLUMNS} FROM tracker_items t JOIN accounts a ON a.id = t.account_id
|
|
144
|
+
WHERE t.id > ? AND t.kind = 'comment' AND t.deleted_at IS NULL ORDER BY t.id LIMIT ?`);
|
|
145
|
+
const mark = database.prepare("INSERT OR REPLACE INTO store_settings (key, value, at) VALUES (?, ?, ?)");
|
|
146
|
+
let after = Number(setting(database, RECUT_AFTER) ?? 0);
|
|
147
|
+
for (;;) {
|
|
148
|
+
if (until())
|
|
149
|
+
return { dropped, added, left: true };
|
|
150
|
+
const rows = write(database, () => {
|
|
151
|
+
const found = comments.all(after, BACKFILL);
|
|
152
|
+
const released = [];
|
|
153
|
+
for (const row of found) {
|
|
154
|
+
const freed = chunk(chunkedOf(row), now);
|
|
155
|
+
if (freed?.written)
|
|
156
|
+
added += 1;
|
|
157
|
+
for (const hash of freed?.released ?? [])
|
|
158
|
+
released.push(hash);
|
|
159
|
+
}
|
|
160
|
+
dropUnusedVectors(database, released);
|
|
161
|
+
const last = found.at(-1);
|
|
162
|
+
if (found.length < BACKFILL) {
|
|
163
|
+
database.prepare("DELETE FROM store_settings WHERE key = ?").run(RECUT_AFTER);
|
|
164
|
+
mark.run(CUT_SETTING, CUT, now);
|
|
165
|
+
}
|
|
166
|
+
else if (last)
|
|
167
|
+
mark.run(RECUT_AFTER, String(last.id), now);
|
|
168
|
+
return found;
|
|
169
|
+
});
|
|
170
|
+
const last = rows.at(-1);
|
|
171
|
+
if (!last || rows.length < BACKFILL)
|
|
172
|
+
break;
|
|
173
|
+
after = Number(last.id);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
85
176
|
// An item with no text never gets a chunk: reading it again at every embed would find nothing.
|
|
86
|
-
const page = database.prepare(`SELECT
|
|
87
|
-
FROM tracker_items t JOIN accounts a ON a.id = t.account_id
|
|
177
|
+
const page = database.prepare(`SELECT ${ITEM_COLUMNS} FROM tracker_items t JOIN accounts a ON a.id = t.account_id
|
|
88
178
|
WHERE t.id > ? AND t.deleted_at IS NULL AND t.kind IN ${CHUNKED_SQL}
|
|
89
|
-
AND
|
|
179
|
+
AND CASE t.kind WHEN 'comment' THEN ${EMBEDDED_COMMENT_SQL}
|
|
180
|
+
ELSE trim(t.title || coalesce(t.body, '')) <> '' END
|
|
90
181
|
AND NOT EXISTS (SELECT 1 FROM chunks k WHERE k.chunkable_type = '${TRACKER_CHUNK}' AND k.chunkable_id = t.id)
|
|
91
182
|
ORDER BY t.id LIMIT ?`);
|
|
92
|
-
const chunk = trackerChunkWriter(database);
|
|
93
|
-
let added = 0;
|
|
94
183
|
let after = 0;
|
|
95
184
|
for (;;) {
|
|
96
185
|
if (until())
|
|
97
186
|
return { dropped, added, left: page.all(after, 1).length > 0 };
|
|
98
187
|
const rows = write(database, () => {
|
|
99
188
|
const found = page.all(after, BACKFILL);
|
|
100
|
-
for (const row of found)
|
|
101
|
-
|
|
102
|
-
id: Number(row.id),
|
|
103
|
-
accountId: Number(row.account_id),
|
|
104
|
-
kind: String(row.kind),
|
|
105
|
-
title: String(row.title),
|
|
106
|
-
body: row.body == null ? null : String(row.body),
|
|
107
|
-
occurredAt: Number(row.at),
|
|
108
|
-
scope: row.scope == null ? null : String(row.scope),
|
|
109
|
-
}, now);
|
|
110
|
-
if (written)
|
|
189
|
+
for (const row of found)
|
|
190
|
+
if (chunk(chunkedOf(row), now)?.written)
|
|
111
191
|
added += 1;
|
|
112
|
-
}
|
|
113
192
|
return found;
|
|
114
193
|
});
|
|
115
194
|
const last = rows.at(-1);
|
|
@@ -123,21 +202,41 @@ const LIVE = `k.chunkable_type = '${TRACKER_CHUNK}' AND EXISTS (SELECT 1 FROM tr
|
|
|
123
202
|
"AND t.deleted_at IS NULL)";
|
|
124
203
|
const UNEMBEDDED = `${LIVE} AND NOT EXISTS (SELECT 1 FROM embeddings v WHERE v.model = ? AND v.content_hash = k.content_hash)`;
|
|
125
204
|
export const trackerChunksLeft = (database, model) => Number(database.prepare(`SELECT count(DISTINCT k.content_hash) AS n FROM chunks k WHERE ${UNEMBEDDED}`).get(model)?.n ?? 0);
|
|
126
|
-
/**
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
205
|
+
/**
|
|
206
|
+
* Live items' chunks with no vector of `model`, by hash from `after`, each with its text cut again. A chunk whose text
|
|
207
|
+
* no longer hashes to its hash was cut another way, by an older build sharing the store: its item is cut again (never
|
|
208
|
+
* under a read-only store) and the chunk left out, so no vector is made of other text than its hash names.
|
|
209
|
+
*/
|
|
210
|
+
export const trackerChunksToEmbed = (database, model, { after, limit }, now = Date.now()) => {
|
|
211
|
+
const item = database.prepare(`SELECT ${ITEM_COLUMNS} FROM tracker_items t JOIN accounts a ON a.id = t.account_id WHERE t.id = ?`);
|
|
212
|
+
const issue = issueOf(database);
|
|
213
|
+
const stale = [];
|
|
214
|
+
const found = database
|
|
130
215
|
.prepare(`SELECT k.content_hash AS hash, min(k.chunkable_id) AS owner, k.start_offset AS start, k.end_offset AS end
|
|
131
216
|
FROM chunks k WHERE k.content_hash > ? AND ${UNEMBEDDED}
|
|
132
217
|
GROUP BY k.content_hash ORDER BY k.content_hash LIMIT ?`)
|
|
133
218
|
.all(after ?? "", model, limit)
|
|
134
219
|
.flatMap((row) => {
|
|
135
|
-
const
|
|
136
|
-
if (!
|
|
220
|
+
const owner = item.get(Number(row.owner));
|
|
221
|
+
if (!owner)
|
|
137
222
|
return [];
|
|
138
|
-
const
|
|
139
|
-
|
|
223
|
+
const { kind, title, body, accountId, parent } = chunkedOf(owner);
|
|
224
|
+
const text = textOf(kind, title, body, issue(kind, accountId, parent)).slice(Number(row.start), Number(row.end));
|
|
225
|
+
if (chunkHash(text) === String(row.hash))
|
|
226
|
+
return [{ hash: String(row.hash), text }];
|
|
227
|
+
stale.push(owner);
|
|
228
|
+
return [];
|
|
140
229
|
});
|
|
230
|
+
if (stale.length && !isQueryOnly(database))
|
|
231
|
+
write(database, () => {
|
|
232
|
+
const chunk = trackerChunkWriter(database);
|
|
233
|
+
const released = [];
|
|
234
|
+
for (const owner of stale)
|
|
235
|
+
for (const hash of chunk(chunkedOf(owner), now)?.released ?? [])
|
|
236
|
+
released.push(hash);
|
|
237
|
+
dropUnusedVectors(database, released);
|
|
238
|
+
});
|
|
239
|
+
return found;
|
|
141
240
|
};
|
|
142
241
|
export const trackerEmbedded = (database, model, accountIds) => accountIds.length > 0 &&
|
|
143
242
|
database
|
|
@@ -74,9 +74,14 @@ export interface TrackerStore {
|
|
|
74
74
|
items: TrackerItem<K>[];
|
|
75
75
|
hasMore: boolean;
|
|
76
76
|
}>;
|
|
77
|
+
/**
|
|
78
|
+
* Issues, projects and comments by their words. `capped`: the index offered more rows than are read for one search,
|
|
79
|
+
* so a later row holding the words may be left out; `hasMore` is set while the page found any.
|
|
80
|
+
*/
|
|
77
81
|
find(search: TrackerSearch): Promise<{
|
|
78
82
|
items: TrackerHit[];
|
|
79
83
|
hasMore: boolean;
|
|
84
|
+
capped?: true;
|
|
80
85
|
}>;
|
|
81
86
|
/** Live rows of the kind, archived ones included. */
|
|
82
87
|
count(key: AccountKey, kind: TrackerKind): Promise<number>;
|