@wirecat/cli-core 1.0.0-rc.0 → 1.1.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.
Files changed (96) hide show
  1. package/CHANGELOG.md +186 -0
  2. package/THIRD_PARTY_NOTICES +47 -0
  3. package/dist/cli/account-rename.js +1 -1
  4. package/dist/cli/bot/api-input.d.ts +5 -0
  5. package/dist/cli/bot/api-input.js +6 -1
  6. package/dist/cli/bot/api.js +7 -1
  7. package/dist/cli/domain-lists-command.d.ts +16 -0
  8. package/dist/cli/domain-lists-command.js +88 -0
  9. package/dist/cli/index.d.ts +4 -3
  10. package/dist/cli/index.js +3 -2
  11. package/dist/cli/model-catalogue-command.d.ts +6 -0
  12. package/dist/cli/model-catalogue-command.js +1 -1
  13. package/dist/cli/oauth-session.d.ts +38 -4
  14. package/dist/cli/oauth-session.js +66 -22
  15. package/dist/cli/service-api.js +3 -1
  16. package/dist/cli/shared-command-exports.d.ts +2 -0
  17. package/dist/cli/shared-command-exports.js +3 -0
  18. package/dist/cli/token-session.d.ts +9 -0
  19. package/dist/cli/token-session.js +29 -2
  20. package/dist/crm/manifest/map.d.ts +5 -2
  21. package/dist/crm/manifest/map.js +14 -2
  22. package/dist/domain/domain-lists.d.ts +86 -0
  23. package/dist/domain/domain-lists.js +110 -0
  24. package/dist/domain/free-mail-domains.generated.d.ts +1 -0
  25. package/dist/domain/free-mail-domains.generated.js +4 -0
  26. package/dist/domain/organization-sectors.d.ts +16 -0
  27. package/dist/domain/organization-sectors.generated.d.ts +12 -0
  28. package/dist/domain/organization-sectors.generated.js +15 -0
  29. package/dist/domain/organization-sectors.js +22 -0
  30. package/dist/domain/person-kinds.d.ts +5 -0
  31. package/dist/domain/person-kinds.js +5 -0
  32. package/dist/entities/domain-list.d.ts +27 -0
  33. package/dist/entities/domain-list.js +28 -0
  34. package/dist/entities/index.d.ts +20 -1
  35. package/dist/entities/index.js +3 -1
  36. package/dist/entities/knowledge-lists.d.ts +1 -0
  37. package/dist/entities/knowledge-lists.js +2 -0
  38. package/dist/errors/reasons.js +14 -3
  39. package/dist/mail/mail-types.d.ts +48 -0
  40. package/dist/mail/mail-types.js +218 -0
  41. package/dist/mail/score.d.ts +2 -0
  42. package/dist/mail/score.js +9 -2
  43. package/dist/oauth/index.d.ts +1 -1
  44. package/dist/oauth/storage.d.ts +10 -2
  45. package/dist/oauth/storage.js +23 -9
  46. package/dist/services/domain-lists-download.d.ts +26 -0
  47. package/dist/services/domain-lists-download.js +155 -0
  48. package/dist/services/search-all-rank.d.ts +44 -0
  49. package/dist/services/search-all-rank.js +112 -0
  50. package/dist/services/search-all-tracker.d.ts +58 -0
  51. package/dist/services/search-all-tracker.js +155 -0
  52. package/dist/services/search-all.d.ts +1 -8
  53. package/dist/services/search-all.js +18 -199
  54. package/dist/services/tracker-meaning.js +1 -1
  55. package/dist/store/areas.d.ts +1 -0
  56. package/dist/store/index.d.ts +2 -1
  57. package/dist/store/index.js +1 -1
  58. package/dist/store/people.d.ts +30 -0
  59. package/dist/store/people.js +16 -1
  60. package/dist/store/sqlite/accounts.js +3 -1
  61. package/dist/store/sqlite/domain-organizations.d.ts +36 -0
  62. package/dist/store/sqlite/domain-organizations.js +288 -0
  63. package/dist/store/sqlite/email-types.d.ts +79 -0
  64. package/dist/store/sqlite/email-types.js +261 -0
  65. package/dist/store/sqlite/emails.d.ts +11 -2
  66. package/dist/store/sqlite/emails.js +18 -7
  67. package/dist/store/sqlite/identities.d.ts +4 -1
  68. package/dist/store/sqlite/identities.js +11 -2
  69. package/dist/store/sqlite/identity-rekey.js +2 -0
  70. package/dist/store/sqlite/knowledge.d.ts +2 -9
  71. package/dist/store/sqlite/manifest.js +6 -0
  72. package/dist/store/sqlite/merged-persons.d.ts +3 -2
  73. package/dist/store/sqlite/merged-persons.js +5 -3
  74. package/dist/store/sqlite/migrations.generated.js +77 -0
  75. package/dist/store/sqlite/organizations.d.ts +12 -1
  76. package/dist/store/sqlite/organizations.js +9 -1
  77. package/dist/store/sqlite/people-list.js +69 -11
  78. package/dist/store/sqlite/person-links.js +13 -3
  79. package/dist/store/sqlite/person-match-scan.js +14 -1
  80. package/dist/store/sqlite/schema/sender-bots.d.ts +344 -0
  81. package/dist/store/sqlite/schema/sender-bots.js +30 -0
  82. package/dist/store/sqlite/schema.d.ts +49 -0
  83. package/dist/store/sqlite/schema.js +7 -0
  84. package/dist/store/sqlite/sender-bots.d.ts +108 -0
  85. package/dist/store/sqlite/sender-bots.js +431 -0
  86. package/dist/store/sqlite/sender-signals.d.ts +13 -3
  87. package/dist/store/sqlite/sender-signals.js +17 -13
  88. package/dist/store/sqlite/tracker.d.ts +11 -9
  89. package/dist/store/sqlite/tracker.js +27 -12
  90. package/dist/store/sqlite/work-tasks.js +2 -0
  91. package/dist/tracker/cli/index.d.ts +1 -1
  92. package/dist/tracker/cli/index.js +83 -24
  93. package/dist/tracker/sync.js +43 -20
  94. package/dist/tracker/writes.d.ts +28 -0
  95. package/dist/tracker/writes.js +141 -19
  96. package/package.json +3 -3
@@ -69,12 +69,20 @@ export declare const googleTokenCodec: TokenCodec;
69
69
  export declare const accountTokenCodec: (providerId: string) => TokenCodec;
70
70
  /** zm's entry as zoom-cli writes it today: `{accessToken, refreshToken, expiresAt, scopes}`, all four required. */
71
71
  export declare const zoomTokenCodec: TokenCodec;
72
+ /** An older entry: an account under the same service, or one an older version kept under another service. */
73
+ export type LegacyAccount = string | {
74
+ service: string;
75
+ account: string;
76
+ };
72
77
  export interface CredentialStorageOptions {
73
78
  /** What the CLI passes `Credentials` today; the same options address the same entry. */
74
79
  credentials: CredentialsOptions;
75
80
  account: string;
76
- /** Older accounts read when `account` is empty; a hit is copied to `account` and left in place. */
77
- legacyAccounts?: readonly string[];
81
+ /**
82
+ * Older entries read when `account` is empty. A hit is copied to `account`, in the store it was read from, and left
83
+ * in place; `remove` removes them too. A run with moved folders only reads them.
84
+ */
85
+ legacyAccounts?: readonly LegacyAccount[];
78
86
  codec: TokenCodec;
79
87
  }
80
88
  export declare const credentialStorage: (options: CredentialStorageOptions) => TokenStorage;
@@ -217,9 +217,12 @@ export const credentialStorage = (options) => {
217
217
  (options.credentials.keyring === systemKeyring &&
218
218
  isMovedRun({ appName: options.credentials.service, env: options.credentials.env ?? process.env }));
219
219
  const service = keyringService(options.credentials.service, options.credentials.configDir, options.credentials.isolated);
220
- const raw = (name) => {
220
+ const legacies = (options.legacyAccounts ?? []).map((legacy) => typeof legacy === "string"
221
+ ? { account: legacy, store: credentials }
222
+ : { account: legacy.account, store: new Credentials({ ...options.credentials, service: legacy.service }) });
223
+ const sourced = (name, store = credentials) => {
221
224
  try {
222
- return credentials.read(name)?.secret;
225
+ return store.read(name);
223
226
  }
224
227
  catch (error) {
225
228
  // cli-base's own error already says what to do, in words safe for the answer.
@@ -228,6 +231,7 @@ export const credentialStorage = (options) => {
228
231
  throw keyringFailure(error);
229
232
  }
230
233
  };
234
+ const raw = (name) => sourced(name)?.secret;
231
235
  // A sign-in on a machine with no keyring writes to the file, so an old entry it cannot read is no old entry. With
232
236
  // `storage: "keyring"` there is no file to fall back on: the save would fail too, after the browser.
233
237
  const fallsBack = options.credentials.storage !== "keyring";
@@ -253,14 +257,22 @@ export const credentialStorage = (options) => {
253
257
  const own = raw(account);
254
258
  if (own !== undefined)
255
259
  return own;
256
- for (const legacy of options.legacyAccounts ?? []) {
257
- const found = raw(legacy);
260
+ for (const legacy of legacies) {
261
+ const found = sourced(legacy.account, legacy.store);
258
262
  if (found === undefined)
259
263
  continue;
260
- codec.decode(found);
261
- if (!moved)
262
- save(found);
263
- return found;
264
+ codec.decode(found.secret);
265
+ // A sign-in the owner kept in the file must not move to the keyring by being copied.
266
+ if (!moved && found.source === "file")
267
+ try {
268
+ new Credentials({ ...options.credentials, storage: "file" }).write(account, found.secret);
269
+ }
270
+ catch (error) {
271
+ throw keyringFailure(error, found.secret);
272
+ }
273
+ else if (!moved)
274
+ save(found.secret);
275
+ return found.secret;
264
276
  }
265
277
  return undefined;
266
278
  };
@@ -278,7 +290,9 @@ export const credentialStorage = (options) => {
278
290
  write: (input, writeOptions) => save(codec.encode({ ...input, previous: replaced(account), ...(writeOptions?.signIn ? { signIn: true } : {}) }), writeOptions),
279
291
  remove: () => {
280
292
  try {
281
- return credentials.remove(account);
293
+ // The next read would copy an older entry back and sign the profile in again.
294
+ const older = moved ? [] : legacies.flatMap((legacy) => legacy.store.remove(legacy.account));
295
+ return [...new Set([...credentials.remove(account), ...older])];
282
296
  }
283
297
  catch (error) {
284
298
  throw keyringFailure(error);
@@ -0,0 +1,26 @@
1
+ import { type InstalledPack, type PackManifest } from "../domain/domain-lists.js";
2
+ import { type Fetch } from "../speech/install.js";
3
+ export interface DomainListsUpdateOptions {
4
+ env: NodeJS.ProcessEnv;
5
+ /** Leave out `non-commercial` sources, and remove those already here. */
6
+ commercialOnly?: boolean;
7
+ fetch?: Fetch;
8
+ manifestUrl?: string;
9
+ progress?: (line: string) => void;
10
+ bytes?: (done: number, total: number) => void;
11
+ }
12
+ export interface DomainListsUpdate {
13
+ pack: InstalledPack;
14
+ updated: boolean;
15
+ previous: string | null;
16
+ }
17
+ /** The hosts a download may reach, each once: `hostFetch` refuses a list that names one twice. */
18
+ export declare const packHosts: (urls: readonly string[]) => string[];
19
+ /** The manifest as a release serves it, refused whole when a source would write outside the pack or skip its check. */
20
+ export declare const parseManifest: (value: unknown) => PackManifest;
21
+ /**
22
+ * Brings the pack to the newest release: every file checked against the manifest's sha256 as it arrives, then the
23
+ * whole folder swapped at once, so a failed download leaves the pack as it was. Nothing is downloaded when the pack
24
+ * here is already that version with the same sources.
25
+ */
26
+ export declare const updateDomainLists: ({ env, commercialOnly, fetch: given, manifestUrl, progress, bytes, }: DomainListsUpdateOptions) => Promise<DomainListsUpdate>;
@@ -0,0 +1,155 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { createReadStream, createWriteStream, mkdirSync, writeFileSync } from "node:fs";
3
+ import { rename, rm } from "node:fs/promises";
4
+ import { dirname, join } from "node:path";
5
+ import { pipeline } from "node:stream/promises";
6
+ import { createGunzip } from "node:zlib";
7
+ import { CliError } from "@wirecat/cli-base";
8
+ import { hostFetch } from "@wirecat/cli-base/http";
9
+ import { domainListsDirectory, installedPack, listFile, PACK_MANIFEST_URL, } from "../domain/domain-lists.js";
10
+ import { installFiles, megabytes } from "../speech/install.js";
11
+ /** Where a release asset is served from: GitHub answers with a redirect to its asset host. */
12
+ const RELEASE_HOSTS = ["github.com", "release-assets.githubusercontent.com", "objects.githubusercontent.com"];
13
+ const DOWNLOAD_MS = 10 * 60_000;
14
+ /** The hosts a download may reach, each once: `hostFetch` refuses a list that names one twice. */
15
+ export const packHosts = (urls) => [
16
+ ...new Set([...RELEASE_HOSTS, ...urls.map((url) => new URL(url).hostname)]),
17
+ ];
18
+ const ID = /^[a-z0-9][a-z0-9-]{0,62}$/;
19
+ const SHA256 = /^[0-9a-f]{64}$/;
20
+ const DOMAIN = /^[a-z0-9_]([a-z0-9_.-]*[a-z0-9])?$/;
21
+ const invalid = (what) => new CliError("invalid_response", `the domain-list manifest ${what}`);
22
+ /** The manifest as a release serves it, refused whole when a source would write outside the pack or skip its check. */
23
+ export const parseManifest = (value) => {
24
+ const manifest = value;
25
+ if (typeof manifest?.version !== "string" || !Array.isArray(manifest.sources))
26
+ throw invalid("has no version or sources");
27
+ const ids = new Set();
28
+ for (const source of manifest.sources) {
29
+ if (typeof source.id !== "string" || !ID.test(source.id) || ids.has(source.id))
30
+ throw invalid(`names a bad or repeated source id: ${String(source.id)}`);
31
+ ids.add(source.id);
32
+ if (typeof source.url !== "string" || !source.url.startsWith("https://"))
33
+ throw invalid(`gives ${source.id} a url that is not https`);
34
+ if (!["sector", "freemail", "bad"].includes(source.signal))
35
+ throw invalid(`gives ${source.id} no signal`);
36
+ if (source.class !== "commercial-ok" && source.class !== "non-commercial")
37
+ throw invalid(`gives ${source.id} no licence class`);
38
+ if (source.upstream === true) {
39
+ if (!Number.isSafeInteger(source.max_bytes))
40
+ throw invalid(`gives upstream ${source.id} no size limit`);
41
+ }
42
+ else if (!SHA256.test(source.sha256 ?? "") || !Number.isSafeInteger(source.bytes))
43
+ throw invalid(`gives ${source.id} no sha256 and size`);
44
+ }
45
+ return manifest;
46
+ };
47
+ const fetchManifest = async (url, get) => {
48
+ const response = await get(url, { signal: AbortSignal.timeout(60_000) });
49
+ if (!response.ok) {
50
+ await response.body?.cancel();
51
+ throw new CliError("network_error", `the domain-list manifest could not be downloaded: HTTP ${response.status}`);
52
+ }
53
+ try {
54
+ return parseManifest(await response.json());
55
+ }
56
+ catch (error) {
57
+ if (error instanceof CliError)
58
+ throw error;
59
+ throw invalid("is not JSON");
60
+ }
61
+ };
62
+ const gunzipTo = async (from, to) => pipeline(createReadStream(from), createGunzip(), createWriteStream(to, { flags: "wx", mode: 0o600 }));
63
+ /**
64
+ * A list the source does not let us redistribute, fetched from the source itself, whole. Nothing pins its bytes, so
65
+ * its sha256 is recorded as it arrived, and only lines that read as a domain are kept.
66
+ */
67
+ const fetchUpstream = async (source, path, get) => {
68
+ const response = await get(source.url, { signal: AbortSignal.timeout(120_000) });
69
+ if (!response.ok || !response.body) {
70
+ await response.body?.cancel();
71
+ throw new CliError("network_error", `${source.id} could not be downloaded from its source: HTTP ${response.status}`);
72
+ }
73
+ const limit = source.max_bytes ?? 0;
74
+ const hash = createHash("sha256");
75
+ const chunks = [];
76
+ let bytes = 0;
77
+ for await (const chunk of response.body) {
78
+ bytes += chunk.length;
79
+ if (bytes > limit)
80
+ throw new CliError("invalid_response", `${source.id} is larger than ${megabytes(limit)}`);
81
+ hash.update(chunk);
82
+ chunks.push(Buffer.from(chunk));
83
+ }
84
+ const lines = [
85
+ ...new Set(Buffer.concat(chunks)
86
+ .toString("utf8")
87
+ .split("\n")
88
+ .map((line) => line.trim().toLowerCase())
89
+ .filter((line) => DOMAIN.test(line) && line.includes("."))),
90
+ ];
91
+ writeFileSync(path, lines.length === 0 ? "" : `${lines.join("\n")}\n`, { flag: "wx", mode: 0o600 });
92
+ return { sha256: hash.digest("hex"), lines: lines.length, bytes };
93
+ };
94
+ /**
95
+ * Brings the pack to the newest release: every file checked against the manifest's sha256 as it arrives, then the
96
+ * whole folder swapped at once, so a failed download leaves the pack as it was. Nothing is downloaded when the pack
97
+ * here is already that version with the same sources.
98
+ */
99
+ export const updateDomainLists = async ({ env, commercialOnly = false, fetch: given, manifestUrl = PACK_MANIFEST_URL, progress = () => { }, bytes, }) => {
100
+ const manifest = await fetchManifest(manifestUrl, given ?? hostFetch({ hosts: packHosts([manifestUrl]), timeoutMs: 60_000 }));
101
+ const get = given ??
102
+ hostFetch({
103
+ hosts: packHosts(manifest.sources.map((one) => one.url)),
104
+ timeoutMs: DOWNLOAD_MS,
105
+ });
106
+ const before = installedPack(env);
107
+ const sources = manifest.sources.filter((one) => !commercialOnly || one.class === "commercial-ok");
108
+ if (before !== undefined &&
109
+ before.version === manifest.version &&
110
+ before.commercial_only === commercialOnly &&
111
+ sources.every((one) => before.files[one.id] !== undefined))
112
+ return { pack: before, updated: false, previous: before.version };
113
+ const directory = domainListsDirectory(env);
114
+ const staging = `${directory}.${randomUUID()}.part`;
115
+ mkdirSync(staging, { recursive: true, mode: 0o700 });
116
+ try {
117
+ const published = sources.filter((one) => !one.upstream);
118
+ const weight = published.reduce((sum, one) => sum + (one.bytes ?? 0), 0);
119
+ progress(`domain lists ${manifest.version}: ${megabytes(weight)} from the WireCat release`);
120
+ await installFiles(published.map((one) => [
121
+ { name: `${one.id}.txt.gz`, url: one.url, sha256: one.sha256 ?? "", bytes: one.bytes ?? 0 },
122
+ `${listFile(staging, one.id)}.gz`,
123
+ ]), { fetch: get, progress, ...(bytes ? { bytes } : {}) });
124
+ const files = {};
125
+ for (const source of published) {
126
+ const path = listFile(staging, source.id);
127
+ await gunzipTo(`${path}.gz`, path);
128
+ await rm(`${path}.gz`);
129
+ files[source.id] = { sha256: source.sha256 ?? "", lines: source.count ?? 0, bytes: source.bytes ?? 0 };
130
+ }
131
+ for (const source of sources.filter((one) => one.upstream)) {
132
+ progress(`${source.id}: from ${new URL(source.url).host}, under its own terms (${source.licence})`);
133
+ files[source.id] = await fetchUpstream(source, listFile(staging, source.id), get);
134
+ }
135
+ const pack = {
136
+ ...manifest,
137
+ installed_at: new Date().toISOString(),
138
+ commercial_only: commercialOnly,
139
+ files,
140
+ };
141
+ writeFileSync(join(staging, "manifest.json"), `${JSON.stringify(pack, null, 2)}\n`, { mode: 0o600 });
142
+ mkdirSync(dirname(directory), { recursive: true, mode: 0o700 });
143
+ const old = `${directory}.${randomUUID()}.old`;
144
+ await rename(directory, old).catch((error) => {
145
+ if (error.code !== "ENOENT")
146
+ throw error;
147
+ });
148
+ await rename(staging, directory);
149
+ await rm(old, { recursive: true, force: true });
150
+ return { pack, updated: true, previous: before?.version ?? null };
151
+ }
152
+ finally {
153
+ await rm(staging, { recursive: true, force: true });
154
+ }
155
+ };
@@ -0,0 +1,44 @@
1
+ import type { Period } from "../search/question-period.js";
2
+ import type { SearchAllItem, SearchAllRecordItem } from "./search-all.js";
3
+ /**
4
+ * What a deal or a lead is found by: plain words or phrases, all of them, or any with OR. Anything else is refused,
5
+ * so `search all` skips deals with the reason instead of matching a field they do not have.
6
+ */
7
+ export declare const titleWords: (text: string, refused?: string) => {
8
+ words: string[];
9
+ anyWord: boolean;
10
+ };
11
+ /** A question finds by any of its words, so «что», «кто» or "the" would match nearly every record. */
12
+ export declare const contentWords: (found: {
13
+ words: string[];
14
+ anyWord: boolean;
15
+ }, discover: boolean) => {
16
+ words: string[];
17
+ anyWord: boolean;
18
+ };
19
+ /**
20
+ * What the meaning half embeds: the words and phrases asked for, OR included, as notes take them. `title:` narrows to
21
+ * the title, which a hit by meaning cannot be held to, so such a query is searched by words only.
22
+ */
23
+ export declare const meaningWordsOf: (text: string) => string | undefined;
24
+ /**
25
+ * One list for a lane found both ways, as notes and messages fuse theirs: each hit's rank in either list votes, a
26
+ * question's hit voting once; a hit found both ways keeps its words' text and is found by meaning too.
27
+ */
28
+ export declare const fusedLane: (byWords: SearchAllRecordItem[], byMeaning: {
29
+ hit: SearchAllRecordItem;
30
+ score: number;
31
+ }[], discover: boolean, cosines: Map<string, number>) => SearchAllRecordItem[];
32
+ /**
33
+ * Every source's hits as one list: each source's best hit first, then every other hit by cosine, then by its rank in
34
+ * its source. Taking turns by rank (MEMO-37) gave each of two sources half of a ten-hit page however weak its hits;
35
+ * one model scores every source, so cosine compares across them. A hit only words found takes the cosine of
36
+ * the hit above it in its source: its source ranked it there, and with none it would follow every hit meaning found.
37
+ */
38
+ export declare const oneList: (lists: SearchAllItem[][], cosines: Map<string, number>) => SearchAllItem[];
39
+ export declare const PERIOD_DEPTH = 100;
40
+ /**
41
+ * A hit dated inside the question's period gains 0.5 over its place, 1 - rank/100: by rank, because only some hits have
42
+ * a cosine to compare. One scale for every page, so paging past the first 100 never reorders what came before.
43
+ */
44
+ export declare const insidePeriodFirst: (ordered: SearchAllItem[], period: Period | undefined) => SearchAllItem[];
@@ -0,0 +1,112 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { parseLucene } from "@wirecat/cli-base/query";
3
+ import { RRF_K } from "../search/fusion.js";
4
+ import { meaningWords } from "../search/lucene/meaning-parts.js";
5
+ import { SEARCH_QUERY } from "../search/lucene/types.js";
6
+ import { isFunctionWord, words as plainWords } from "../search/question-plan.js";
7
+ /**
8
+ * What a deal or a lead is found by: plain words or phrases, all of them, or any with OR. Anything else is refused,
9
+ * so `search all` skips deals with the reason instead of matching a field they do not have.
10
+ */
11
+ export const titleWords = (text, refused = "deals and leads are found by the words of their title, company, contacts and activities only") => {
12
+ const { root } = parseLucene(text, SEARCH_QUERY);
13
+ const clauses = root.kind === "boolean" ? root.clauses : [{ node: root, occur: "must" }];
14
+ const words = clauses.map(({ node, occur }) => occur !== "must_not" &&
15
+ node.kind === "predicate" &&
16
+ (node.field === "text" || node.field === "title") &&
17
+ (node.operator === "term" || node.operator === "phrase")
18
+ ? // A title holds "invoice", not the question mark of "invoice?".
19
+ node.value.replace(/\?+$/u, "") || node.value
20
+ : (() => {
21
+ throw new CliError("validation_error", refused);
22
+ })());
23
+ return { words, anyWord: clauses.length > 1 && clauses.every(({ occur }) => occur === "should") };
24
+ };
25
+ /** A question finds by any of its words, so «что», «кто» or "the" would match nearly every record. */
26
+ export const contentWords = (found, discover) => {
27
+ if (!discover)
28
+ return found;
29
+ const content = found.words.filter((word) => !plainWords(word).every(isFunctionWord));
30
+ return content.length ? { ...found, words: content } : found;
31
+ };
32
+ /**
33
+ * What the meaning half embeds: the words and phrases asked for, OR included, as notes take them. `title:` narrows to
34
+ * the title, which a hit by meaning cannot be held to, so such a query is searched by words only.
35
+ */
36
+ export const meaningWordsOf = (text) => {
37
+ try {
38
+ const { root } = parseLucene(text, SEARCH_QUERY);
39
+ const nodes = root.kind === "boolean" ? root.clauses.map(({ node }) => node) : [root];
40
+ if (!nodes.every((node) => node.kind === "predicate" && node.field === "text"))
41
+ return undefined;
42
+ return meaningWords(root) || undefined;
43
+ }
44
+ catch {
45
+ return undefined;
46
+ }
47
+ };
48
+ /**
49
+ * One list for a lane found both ways, as notes and messages fuse theirs: each hit's rank in either list votes, a
50
+ * question's hit voting once; a hit found both ways keeps its words' text and is found by meaning too.
51
+ */
52
+ export const fusedLane = (byWords, byMeaning, discover, cosines) => {
53
+ const fused = new Map();
54
+ byWords.forEach((item, rank) => {
55
+ fused.set(item.ref, { item, score: 1 / (RRF_K + rank + 1) });
56
+ });
57
+ byMeaning.forEach(({ hit, score }, rank) => {
58
+ cosines.set(hit.ref, score);
59
+ const held = fused.get(hit.ref);
60
+ if (held && !held.item.foundBy.includes("meaning"))
61
+ held.item.foundBy = [...held.item.foundBy, "meaning"];
62
+ const vote = 1 / (RRF_K + rank + 1);
63
+ if (held && discover)
64
+ held.score = Math.max(held.score, vote);
65
+ else
66
+ fused.set(hit.ref, { item: held?.item ?? hit, score: (held?.score ?? 0) + vote });
67
+ });
68
+ return [...fused.values()].sort((a, b) => b.score - a.score).map(({ item }) => item);
69
+ };
70
+ /** Passages of one meeting share its `ref`, the reference evidence cites; each is still a hit of its own. */
71
+ const hitKey = (item) => item.kind === "meeting" ? `${item.ref}\u0000${item.scope}\u0000${item.id}` : item.ref;
72
+ /**
73
+ * Every source's hits as one list: each source's best hit first, then every other hit by cosine, then by its rank in
74
+ * its source. Taking turns by rank (MEMO-37) gave each of two sources half of a ten-hit page however weak its hits;
75
+ * one model scores every source, so cosine compares across them. A hit only words found takes the cosine of
76
+ * the hit above it in its source: its source ranked it there, and with none it would follow every hit meaning found.
77
+ */
78
+ export const oneList = (lists, cosines) => {
79
+ const place = new Map();
80
+ for (const list of lists) {
81
+ let above = Number.NEGATIVE_INFINITY;
82
+ list.forEach((item, rank) => {
83
+ const key = hitKey(item);
84
+ above = cosines.get(item.ref) ?? above;
85
+ const held = place.get(key);
86
+ if (!held || rank < held.rank)
87
+ place.set(key, { item, rank, cosine: above });
88
+ });
89
+ }
90
+ const head = (rank) => Math.min(rank, 1);
91
+ return [...place.values()]
92
+ .sort((a, b) => head(a.rank) - head(b.rank) || b.cosine - a.cosine || a.rank - b.rank)
93
+ .map(({ item }) => item);
94
+ };
95
+ export const PERIOD_DEPTH = 100;
96
+ const PERIOD_BOOST = 0.5;
97
+ /**
98
+ * A hit dated inside the question's period gains 0.5 over its place, 1 - rank/100: by rank, because only some hits have
99
+ * a cosine to compare. One scale for every page, so paging past the first 100 never reorders what came before.
100
+ */
101
+ export const insidePeriodFirst = (ordered, period) => {
102
+ if (!period)
103
+ return ordered;
104
+ const inside = ({ timestamp }) => {
105
+ const at = timestamp === null ? Number.NaN : Date.parse(timestamp);
106
+ return at >= period.from && at < period.to;
107
+ };
108
+ return ordered
109
+ .map((item, rank) => ({ item, score: 1 - rank / PERIOD_DEPTH + (inside(item) ? PERIOD_BOOST : 0) }))
110
+ .sort((a, b) => b.score - a.score)
111
+ .map(({ item }) => item);
112
+ };
@@ -0,0 +1,58 @@
1
+ import { type WarmEmbedders } from "../embeddings/embed.js";
2
+ import type { AccountKey, MessageStore, TrackerItem } from "../store/store.js";
3
+ import type { SearchAllRecordItem } from "./search-all.js";
4
+ interface TrackerLaneRequest {
5
+ text: string;
6
+ accounts: AccountKey[];
7
+ depth: number;
8
+ discover: boolean;
9
+ exact?: boolean;
10
+ /** Filled with each hit found by meaning, by its cosine. */
11
+ cosines: Map<string, number>;
12
+ embedders: Pick<WarmEmbedders, "get">;
13
+ command?: string;
14
+ env?: NodeJS.ProcessEnv;
15
+ }
16
+ /**
17
+ * Issues, projects and comments by words, and by meaning when the model and some vectors are there, fused as notes
18
+ * fuse theirs; `records` gives each hit's record by its ref. A query naming a field an issue lacks is a `validation_error`.
19
+ */
20
+ export declare const trackerLane: (store: MessageStore, { text, accounts: read, depth, discover, exact, cosines, embedders, command, env }: TrackerLaneRequest) => Promise<{
21
+ hits: SearchAllRecordItem[];
22
+ records: Map<string, TrackerItem<"comment" | "issue" | "label" | "project" | "sprint" | "state" | "team" | "user">>;
23
+ hasMore: boolean;
24
+ tracker: {
25
+ by: "words" | "words and meaning";
26
+ meaningSkipped?: string;
27
+ };
28
+ meaningReason?: string | undefined;
29
+ }>;
30
+ /** One hit of `searchTracker`: the record beside how `search all` shows it. */
31
+ export interface TrackerSearchHit {
32
+ hit: SearchAllRecordItem;
33
+ item: TrackerItem;
34
+ }
35
+ export interface TrackerSearchFound {
36
+ items: TrackerSearchHit[];
37
+ hasMore: boolean;
38
+ by: "words" | "words and meaning";
39
+ /** Why meaning was not searched, when it was not. */
40
+ meaningSkipped?: string;
41
+ /** `model.not-downloaded`, or `tracker.no-vectors` when the model is there but nothing is embedded with it. */
42
+ meaningReason?: string;
43
+ }
44
+ /**
45
+ * A tracker CLI's own search over its accounts' copies, ranked as the tracker lane of `search all` ranks them: words,
46
+ * and meaning once `sync --embed` built the vectors; a question finds what holds some of its words.
47
+ */
48
+ export declare const searchTracker: (store: MessageStore, request: {
49
+ text: string;
50
+ accounts: AccountKey[];
51
+ limit: number;
52
+ offset?: number;
53
+ now?: number;
54
+ timezone?: string;
55
+ command?: string;
56
+ env?: NodeJS.ProcessEnv;
57
+ }) => Promise<TrackerSearchFound>;
58
+ export {};
@@ -0,0 +1,155 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { timezoneOf } from "@wirecat/cli-base/query";
3
+ import { hasGlobalItemIds } from "../domain/providers.js";
4
+ import { trackerBodyOf, trackerTitleOf } from "../domain/tracker.js";
5
+ import { runEmbedders } from "../embeddings/embed.js";
6
+ import { plainQuery } from "../search/lucene/plain.js";
7
+ import { questionPeriod } from "../search/question-period.js";
8
+ import { questionLookup, questionText } from "../search/question-plan.js";
9
+ import { excerpt } from "./excerpt.js";
10
+ import { contentWords, fusedLane, insidePeriodFirst, meaningWordsOf, oneList, PERIOD_DEPTH, titleWords, } from "./search-all-rank.js";
11
+ import { nearestTracker } from "./tracker-meaning.js";
12
+ const TRACKER_HIT_KINDS = { issue: "issue", project: "project", comment: "issue_comment" };
13
+ /** An issue is titled as people say it, `ENG-12 Fix login`; anything else by its name or its first line. */
14
+ const trackerTitle = ({ kind, record }) => {
15
+ const title = trackerTitleOf(kind, record);
16
+ const key = kind === "issue" ? record.key : undefined;
17
+ return key ? `${key} ${title}` : title;
18
+ };
19
+ const trackerExcerpt = ({ kind, record }, query) => excerpt([trackerTitleOf(kind, record), trackerBodyOf(kind, record)].filter(Boolean).join("\n"), query);
20
+ /**
21
+ * One hit per tracker item, best first: the copies other sign-ins hold of one item (`items` maps a hit's ref to the
22
+ * 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.
23
+ */
24
+ const oneHitPerItem = (ordered, cosines, items) => {
25
+ const kept = new Map();
26
+ for (const hit of ordered) {
27
+ const key = items.get(hit.ref) ?? hit.ref;
28
+ const held = kept.get(key);
29
+ if (!held) {
30
+ kept.set(key, hit);
31
+ continue;
32
+ }
33
+ held.accounts = [...(held.accounts ?? [held.account]), hit.account];
34
+ held.foundBy = ["words", "meaning"].filter((by) => [held, hit].some(({ foundBy }) => foundBy.includes(by)));
35
+ const cosine = cosines.get(hit.ref);
36
+ if (cosine !== undefined && cosine > (cosines.get(held.ref) ?? Number.NEGATIVE_INFINITY))
37
+ cosines.set(held.ref, cosine);
38
+ }
39
+ return [...kept.values()];
40
+ };
41
+ const TRACKER_DEPTH = 500;
42
+ /**
43
+ * Issues, projects and comments by words, and by meaning when the model and some vectors are there, fused as notes
44
+ * fuse theirs; `records` gives each hit's record by its ref. A query naming a field an issue lacks is a `validation_error`.
45
+ */
46
+ export const trackerLane = async (store, { text, accounts: read, depth, discover, exact, cosines, embedders, command, env }) => {
47
+ const { words, anyWord } = contentWords(titleWords(text, "issues, projects and comments are found by the words and meaning of their title and text only"), discover);
48
+ // Two sign-ins to one workspace hold each item twice, and the copies fold into one hit: read deep enough that the
49
+ // folded list still fills the page.
50
+ const deep = Math.min(depth * read.length, TRACKER_DEPTH);
51
+ const found = await store.tracker.find({
52
+ words,
53
+ anyWord: anyWord || discover,
54
+ ...(exact ? { exact: true } : {}),
55
+ kinds: ["issue", "project", "comment"],
56
+ limit: deep,
57
+ accounts: read,
58
+ });
59
+ const items = new Map();
60
+ const records = new Map();
61
+ const hitOf = (at, item, excerpt, foundBy) => {
62
+ const ref = `tracker:${at.provider}/${at.account}/${item.kind}/${item.record.externalId}`;
63
+ if (hasGlobalItemIds(at.provider))
64
+ items.set(ref, JSON.stringify([at.provider, item.kind, item.record.externalId]));
65
+ records.set(ref, item);
66
+ return {
67
+ kind: TRACKER_HIT_KINDS[item.kind],
68
+ // Two sign-ins see the same issue under the same id, so the account keeps their hits apart.
69
+ ref,
70
+ provider: at.provider,
71
+ account: at.account,
72
+ ...(item.record.url ? { url: item.record.url } : {}),
73
+ title: trackerTitle(item),
74
+ timestamp: new Date(item.record.updatedAt ?? item.syncedAt).toISOString(),
75
+ text: excerpt,
76
+ foundBy,
77
+ };
78
+ };
79
+ const byWords = found.items.map(({ account: at, item, excerpt: text }) => hitOf(at, item, text, ["words"]));
80
+ const plain = meaningWordsOf(discover ? questionText(text) : text);
81
+ let near;
82
+ let meaningSkipped;
83
+ let meaningReason;
84
+ if (exact)
85
+ meaningSkipped = "--exact searches words as written";
86
+ else if (plain === undefined)
87
+ meaningSkipped = "the query names a title, which meaning cannot follow";
88
+ else
89
+ try {
90
+ near = await nearestTracker(store, plain, {
91
+ limit: deep,
92
+ accounts: read,
93
+ embedders,
94
+ ...(command === undefined ? {} : { command }),
95
+ ...(env === undefined ? {} : { env }),
96
+ });
97
+ }
98
+ catch (error) {
99
+ if (!(error instanceof CliError && error.code === "not_found"))
100
+ throw error;
101
+ meaningSkipped = error.message;
102
+ const { reason } = error.details;
103
+ if (typeof reason === "string")
104
+ meaningReason = reason;
105
+ }
106
+ const tracker = {
107
+ by: near === undefined ? "words" : "words and meaning",
108
+ ...(meaningSkipped === undefined ? {} : { meaningSkipped }),
109
+ };
110
+ const hits = near === undefined
111
+ ? oneHitPerItem(byWords, cosines, items)
112
+ : oneHitPerItem(fusedLane(byWords, near.map(({ account: at, item, score }) => ({
113
+ hit: hitOf(at, item, trackerExcerpt(item, text), ["meaning"]),
114
+ score,
115
+ })), discover, cosines), cosines, items);
116
+ return { hits, records, hasMore: found.hasMore, tracker, ...(meaningReason ? { meaningReason } : {}) };
117
+ };
118
+ /**
119
+ * A tracker CLI's own search over its accounts' copies, ranked as the tracker lane of `search all` ranks them: words,
120
+ * and meaning once `sync --embed` built the vectors; a question finds what holds some of its words.
121
+ */
122
+ export const searchTracker = async (store, request) => {
123
+ if (!request.text.trim())
124
+ throw new CliError("validation_error", "say what to find");
125
+ const text = plainQuery(request.text);
126
+ const offset = request.offset ?? 0;
127
+ const window = offset + request.limit;
128
+ const period = questionPeriod(text, request.now ?? Date.now(), timezoneOf(request.timezone));
129
+ const cosines = new Map();
130
+ const embedders = runEmbedders();
131
+ try {
132
+ const found = await trackerLane(store, {
133
+ text,
134
+ accounts: request.accounts,
135
+ depth: Math.max(window, period ? PERIOD_DEPTH : 0),
136
+ discover: questionLookup(text) !== undefined,
137
+ cosines,
138
+ embedders,
139
+ ...(request.command === undefined ? {} : { command: request.command }),
140
+ ...(request.env === undefined ? {} : { env: request.env }),
141
+ });
142
+ const ordered = insidePeriodFirst(oneList([found.hits], cosines), period);
143
+ return {
144
+ items: ordered.slice(offset, window).map((hit) => ({ hit, item: found.records.get(hit.ref) })),
145
+ // The lane reads at most 500 rows, so a page past them would be empty and say there are more.
146
+ hasMore: window < TRACKER_DEPTH && (found.hasMore || ordered.length > window),
147
+ by: found.tracker.by,
148
+ ...(found.tracker.meaningSkipped === undefined ? {} : { meaningSkipped: found.tracker.meaningSkipped }),
149
+ ...(found.meaningReason === undefined ? {} : { meaningReason: found.meaningReason }),
150
+ };
151
+ }
152
+ finally {
153
+ await embedders.close();
154
+ }
155
+ };
@@ -10,6 +10,7 @@ import type { SearchCoverage } from "./messages-search.js";
10
10
  import { type MeetingAccountCoverage, type MeetingSearchItem } from "./search-all-meetings.js";
11
11
  import { type HarderOptions, type HarderResult } from "./search-harder.js";
12
12
  import type { Backend, ServerOptions, ServerSearched } from "./server-search.js";
13
+ export { titleWords } from "./search-all-rank.js";
13
14
  export declare const RESOURCES_SEARCHED: readonly ["messages", "mail", "notes", "events", "crm", "business", "meetings", "tracker"];
14
15
  export type SearchedResource = (typeof RESOURCES_SEARCHED)[number];
15
16
  /** One hit of `search all`: a stored record, or a passage of a meeting. */
@@ -189,14 +190,6 @@ export type SearchAllMessenger = Partial<Pick<MessengerTraits, "savedChatId" | "
189
190
  */
190
191
  hintCommand?: string | null;
191
192
  };
192
- /**
193
- * What a deal or a lead is found by: plain words or phrases, all of them, or any with OR. Anything else is refused,
194
- * so `search all` skips deals with the reason instead of matching a field they do not have.
195
- */
196
- export declare const titleWords: (text: string, refused?: string) => {
197
- words: string[];
198
- anyWord: boolean;
199
- };
200
193
  /** A tracker hit's kind: a comment is named for the issue it is on, beside a CRM's and a message's kinds. */
201
194
  export type TrackerHitKind = "issue" | "project" | "issue_comment";
202
195
  /** The accounts of every tracker the store holds copies of. */