@wirecat/cli-core 0.639.0 → 0.640.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 (38) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/dist/domain/crm.d.ts +3 -0
  3. package/dist/domain/name-variants.d.ts +2 -0
  4. package/dist/domain/name-variants.js +107 -0
  5. package/dist/domain/person-kinds.d.ts +6 -3
  6. package/dist/domain/person-kinds.js +5 -2
  7. package/dist/entities/contact-activity.d.ts +3 -0
  8. package/dist/entities/contact-activity.js +3 -0
  9. package/dist/entities/contact-context.d.ts +6 -0
  10. package/dist/entities/index.d.ts +6 -0
  11. package/dist/errors/reasons.js +2 -1
  12. package/dist/resolve.d.ts +8 -0
  13. package/dist/resolve.js +48 -6
  14. package/dist/search/lucene/registry.js +17 -15
  15. package/dist/services/message-resolution.d.ts +12 -0
  16. package/dist/services/message-resolution.js +42 -1
  17. package/dist/services/messages-search.js +29 -15
  18. package/dist/services/metadata.d.ts +1 -1
  19. package/dist/store/index.d.ts +1 -1
  20. package/dist/store/people.d.ts +10 -3
  21. package/dist/store/people.js +2 -1
  22. package/dist/store/sqlite/accounts.js +2 -0
  23. package/dist/store/sqlite/crm.js +5 -0
  24. package/dist/store/sqlite/hit-places.js +19 -6
  25. package/dist/store/sqlite/identities.js +21 -1
  26. package/dist/store/sqlite/lucene-fields.d.ts +2 -1
  27. package/dist/store/sqlite/lucene-fields.js +76 -16
  28. package/dist/store/sqlite/lucene.js +8 -8
  29. package/dist/store/sqlite/note-search.js +9 -0
  30. package/dist/store/sqlite/people-list.js +14 -8
  31. package/dist/store/sqlite/person-doubts.d.ts +13 -3
  32. package/dist/store/sqlite/person-doubts.js +92 -48
  33. package/dist/store/sqlite/person-links.js +15 -2
  34. package/dist/store/sqlite/test-people.d.ts +24 -0
  35. package/dist/store/sqlite/test-people.js +92 -0
  36. package/dist/store/types.d.ts +6 -0
  37. package/docs/search/recipes.json +3 -0
  38. package/package.json +1 -1
@@ -5,16 +5,17 @@ import { isImportedProvider, kindIn, UNKNOWN_PROVIDER } from "../domain/provider
5
5
  import { syncsOneChat } from "../ports/traits.js";
6
6
  import { PRESET_VERSION } from "../search/lucene/presets.js";
7
7
  import { FIELD_VERSION, validateAst, validateFields } from "../search/lucene/registry.js";
8
- import { hasStems, hasText, isStemmed } from "../search/lucene/resolved.js";
8
+ import { hasStems, hasText, isStemmed, } from "../search/lucene/resolved.js";
9
9
  import { inSource, sourceOf } from "../search/query.js";
10
10
  import { createStemmer, DEFAULT_STEMMERS } from "../search/stem.js";
11
11
  import { CHAT_LIST_KEY, } from "../store/store.js";
12
12
  import { withExcerpt } from "./excerpt.js";
13
13
  import { mailAround, mergeMail, withMailThreads } from "./mail-search.js";
14
- import { chatAmong, senderAmong } from "./message-resolution.js";
14
+ import { chatAmong, chatsMatchingIn, senderAmong, sendersMatching } from "./message-resolution.js";
15
15
  import { accountsOfKind, listedAccounts, MAIL } from "./search-kind.js";
16
+ const PERSON_FIELDS = new Set(["from", "to", "cc", "bcc"]);
16
17
  const MAIL_FIELDS = new Set(["to", "cc", "bcc", "subject", "mailbox", "label", "is"]);
17
- import { dateRange, parseLucene, timezoneOf, walkQuery } from "@wirecat/cli-base/query";
18
+ import { dateRange, parseLucene, timezoneOf, walkQuery, } from "@wirecat/cli-base/query";
18
19
  import { MESSAGE_PARSING, searchError } from "../search/lucene/types.js";
19
20
  const positiveSources = (node) => node.kind === "predicate"
20
21
  ? node.field === "in"
@@ -101,14 +102,17 @@ export const prepareLucene = async (store, account, request, messenger) => {
101
102
  ...node,
102
103
  clauses: await Promise.all(node.clauses.map(async ({ occur, node }) => ({ occur, node: await resolve(node) }))),
103
104
  };
105
+ if (node.field === "chat" && node.operator === "wildcard")
106
+ return anyOf(node, await chatsMatchingIn(chatLookup, scopeAccounts, node.value), (chat) => ({ chat }));
104
107
  if (node.field === "chat")
105
108
  return { ...node, resolution: { chat: await chatAmong(messenger, chatLookup, scopeAccounts, node.value) } };
106
- if (node.field === "to" || node.field === "cc" || node.field === "bcc")
109
+ const person = PERSON_FIELDS.has(node.field) && !(node.field === "from" && node.value.toLowerCase() === "me");
110
+ if (person && node.operator === "wildcard")
111
+ return anyOf(node, await sendersMatching(store, scopeAccounts, node.field, node.value), (sender) => ({ sender }));
112
+ if (person)
107
113
  return { ...node, resolution: { sender: await senderAmong(store, scopeAccounts, node.value) } };
108
114
  if (node.field === "from")
109
- return node.value.toLowerCase() === "me"
110
- ? { ...node, resolution: { outgoing: true } }
111
- : { ...node, resolution: { sender: await senderAmong(store, scopeAccounts, node.value) } };
115
+ return { ...node, resolution: { outgoing: true } };
112
116
  if (node.field === "date")
113
117
  return {
114
118
  ...node,
@@ -120,14 +124,15 @@ export const prepareLucene = async (store, account, request, messenger) => {
120
124
  };
121
125
  const root = await resolve(ast.root);
122
126
  const chats = leaves.filter(({ field }) => field === "chat");
123
- const selectedChat = globalChat ??
124
- (chats.length === 1 && requiresChat(ast.root, chats[0])
125
- ? await chatAmong(messenger, chatLookup, scopeAccounts, chats[0].value)
126
- : undefined);
127
- if (leaves.some(({ field }) => field === "topic")) {
128
- if (!globalChat && (chats.length !== 1 || !requiresChat(ast.root, chats[0])))
129
- searchError("query.topic-scope", { start: 0, end: 0 }, "name one chat with chat:, required");
130
- }
127
+ const [lone] = chats.length === 1 && chats[0] && requiresChat(ast.root, chats[0]) ? chats : [];
128
+ const loneChats = lone === undefined || globalChat
129
+ ? []
130
+ : lone.operator === "wildcard"
131
+ ? await chatsMatchingIn(chatLookup, scopeAccounts, lone.value)
132
+ : [await chatAmong(messenger, chatLookup, scopeAccounts, lone.value)];
133
+ const selectedChat = globalChat ?? (loneChats.length === 1 ? loneChats[0] : undefined);
134
+ if (leaves.some(({ field }) => field === "topic") && !selectedChat)
135
+ searchError("query.topic-scope", { start: 0, end: 0 }, "name one chat with chat:, required");
131
136
  const wordsReady = (await store.searchIndex.searchIndexState())?.ready === true;
132
137
  if (hasText(ast.root) && !wordsReady)
133
138
  await indexNotReady(store, messenger.app?.command);
@@ -403,6 +408,15 @@ const QUERY_PAGE_LIMIT = 1000;
403
408
  const oldestFetch = (chats) => chats.length === 0 || chats.some(({ fetchedAt }) => fetchedAt === null)
404
409
  ? null
405
410
  : chats.map(({ fetchedAt }) => fetchedAt).sort()[0];
411
+ /** A name pattern's leaf as an OR of one resolved leaf per fit, so every compiler still reads one sender or chat. */
412
+ const anyOf = (node, found, resolution) => ({
413
+ kind: "boolean",
414
+ span: node.span,
415
+ clauses: found.map((one) => ({
416
+ occur: "should",
417
+ node: { ...node, operator: "term", resolution: resolution(one) },
418
+ })),
419
+ });
406
420
  const requiresChat = (node, chat) => node === chat ||
407
421
  (node.kind === "boolean" && node.clauses.some((clause) => clause.occur === "must" && requiresChat(clause.node, chat)));
408
422
  /** Distinct matching messages counted by chat, sender, or calendar day/hour in the query's timezone. */
@@ -14,12 +14,12 @@ export declare const metadataService: (deps: ServiceDeps) => {
14
14
  dryRun?: boolean;
15
15
  }) => Promise<{
16
16
  items: ({
17
- error?: undefined;
18
17
  chatId: string;
19
18
  tags: import("../domain/channel-tags.js").ChannelTagMatch[];
20
19
  algorithm: string;
21
20
  fetchedAt: string | null;
22
21
  source: string;
22
+ error?: undefined;
23
23
  } | {
24
24
  tags?: undefined;
25
25
  algorithm?: undefined;
@@ -80,7 +80,7 @@ export type { Order, OrderDetail, OrderFilter, OrderInput, OrdersStore } from ".
80
80
  export type { OrganizationFilter } from "./sqlite/organization-categories.js";
81
81
  export { DEFAULT_OWNER_LANGUAGES, ownerLanguages } from "./sqlite/owner-languages.js";
82
82
  export { type ListedPerson, PEOPLE_SORTS, type PeopleList, type PeopleListOptions, type PeopleSort, type SimilarPerson, } from "./sqlite/people-list.js";
83
- export { DOUBT_REASONS, type DoubtIdentity, type DoubtMove, type DoubtReason, type KeptPerson, type PersonDoubt, type PersonDoubts, } from "./sqlite/person-doubts.js";
83
+ export { DOUBT_REASONS, type DoubtIdentity, type DoubtMove, type DoubtReason, type KeptPerson, type PersonDoubt, type PersonDoubts, type TestDataPerson, } from "./sqlite/person-doubts.js";
84
84
  export { mergeId, type PersonMerge, parseMergeId } from "./sqlite/person-merges.js";
85
85
  export { ALWAYS_SHOWN, PERSON_TIES, type PersonTie, type ShownBecause, SMALL_GROUP_MEMBERS, } from "./sqlite/person-ties.js";
86
86
  export type { PrivateContact, PrivateContactNote } from "./sqlite/private-people.js";
@@ -7,7 +7,7 @@ import type { IdentitySplitDecision, IdentitySplitFilter, IdentitySplitInput, Id
7
7
  import type { ContactFilter } from "./sqlite/identities.js";
8
8
  import type { StoreContext } from "./sqlite/open.js";
9
9
  import { type PeopleList, type PeopleListOptions, type SimilarPerson } from "./sqlite/people-list.js";
10
- import { type KeptPerson, type PersonDoubts } from "./sqlite/person-doubts.js";
10
+ import { type KeptPerson, type PersonDoubts, type TestDataPerson } from "./sqlite/person-doubts.js";
11
11
  import type { PersonMerge } from "./sqlite/person-merges.js";
12
12
  import { type PersonPreparationRead } from "./sqlite/person-preparation.js";
13
13
  import { type ShownBecause } from "./sqlite/person-ties.js";
@@ -130,9 +130,15 @@ export interface PeopleStore extends AccountPeople {
130
130
  }): Promise<PersonDoubts>;
131
131
  /**
132
132
  * The owner says a person in doubt is right as they are: the identities in doubt stop being listed until one of them
133
- * moves. The owner's alone; refused with `person.no-doubt` when nothing about the person is in doubt.
133
+ * moves, and what looked like test data is a real contact, shown again even when memo hid it. The owner's alone;
134
+ * refused with `person.no-doubt` when nothing about the person is in doubt or hidden.
134
135
  */
135
136
  keep(person: string, by: Decider): Promise<KeptPerson>;
137
+ /**
138
+ * The owner says a person is test data: hidden from every list, `list({ kind: "test" })` lists them, until `keep`.
139
+ * The owner's alone; refused for the owner's own person.
140
+ */
141
+ markTestData(person: string, by: Decider): Promise<TestDataPerson>;
136
142
  /** The identity, and everyone linked with it, is the owner. */
137
143
  linkToOwner(identity: IdentityRef): Promise<PersonRecord>;
138
144
  /** A person known by name only, with no identity yet: someone to assign a task to before any message names them. */
@@ -143,7 +149,8 @@ export interface PeopleStore extends AccountPeople {
143
149
  * People of one kind with their shown name, contact, interactions and ties, a page at a time. `person` (the default)
144
150
  * is the owner, people added by hand, task assignees, and named people with a tie (a one-to-one chat, a small group,
145
151
  * mail the owner wrote, a meeting, a CRM, the address book); `automated`, `organization`, `stranger` (a
146
- * name, no tie) and `unsorted` (nothing to show as a name) hold the rest.
152
+ * name, no tie) and `unsorted` (nothing to show as a name) hold the rest. `test` holds what a test run left: a seed
153
+ * id, an address at a reserved domain, or what the owner called test data; `all` and every other kind leave it out.
147
154
  */
148
155
  list(options: PeopleListOptions): Promise<PeopleList>;
149
156
  /** How many people of each kind match a name or username, or the whole store: `list`'s `counts` without a page. */
@@ -6,7 +6,7 @@ import * as identityProposals from "./sqlite/identity-proposals.js";
6
6
  import * as identitySplits from "./sqlite/identity-split-proposals.js";
7
7
  import { linkToOwner } from "./sqlite/own-identities.js";
8
8
  import { countPeople, listPeople, similarPeople, } from "./sqlite/people-list.js";
9
- import { keepPerson, personDoubts } from "./sqlite/person-doubts.js";
9
+ import { keepPerson, markTestData, personDoubts, } from "./sqlite/person-doubts.js";
10
10
  import * as personLinks from "./sqlite/person-links.js";
11
11
  import { PROPOSAL_SCORE, RULE, scanMatches } from "./sqlite/person-match-scan.js";
12
12
  import * as personMerges from "./sqlite/person-merges.js";
@@ -136,6 +136,7 @@ export const peopleStoreOver = (context, keyed) => {
136
136
  splitProposals: async (filter) => identitySplits.identitySplitRows(context, filter),
137
137
  doubts: async (page) => personDoubts(context, page),
138
138
  keep: async (person, by) => write(database, () => keepPerson(context, person, by)),
139
+ markTestData: async (person, by) => write(database, () => markTestData(context, person, by)),
139
140
  linkToOwner: async (identity) => linkToOwner(context, identity),
140
141
  list: async (options) => listPeople(database, options),
141
142
  counts: async (query) => countPeople(database, query),
@@ -6,6 +6,7 @@ import { forgetErasedLinks } from "./identity-link-rows.js";
6
6
  import { forgetErasedSplits } from "./identity-split-proposals.js";
7
7
  import { mergeSql } from "./merged-persons.js";
8
8
  import { accountIdentities, accounts, aliases, botUpdates, chatEventPeople, chatEvents, chatMembers, chats, chunks, fetchLeases, involvements, memberCounts, memberObservationMembers, memberObservations, memberStays, messageReactions, messageRevisions, messages, messageTranscripts, pollVotes, projects, syncCursors, syncRanges, syncs, } from "./schema.js";
9
+ import { forgetErasedTestData } from "./test-people.js";
9
10
  import { dropUnusedVectors } from "./vector-index.js";
10
11
  /**
11
12
  * An account's row, made on first sight; a name only replaces what was known when there is one. `startScope` is the
@@ -249,6 +250,7 @@ export const dropOrphanPeople = (database, unseenBefore) => {
249
250
  database.prepare("DELETE FROM identities WHERE id IN (SELECT value FROM json_each(?))").run(gone);
250
251
  forgetErasedLinks(database);
251
252
  forgetErasedSplits(database);
253
+ forgetErasedTestData(database);
252
254
  database
253
255
  .prepare(`DELETE FROM persons WHERE id IN (SELECT value FROM json_each(?)) AND owner = 0
254
256
  AND NOT EXISTS (SELECT 1 FROM identity_links l WHERE l.person_id = persons.id)
@@ -21,6 +21,9 @@ const relationNotes = ({ issues, skippedOwnerRejected, unlistedUsers, droppedPen
21
21
  ...(unlistedUsers ? { unlistedUsers } : {}),
22
22
  ...(droppedPending ? { droppedPending } : {}),
23
23
  });
24
+ /** At most this many of a contact's phones or addresses: a CRM field holds what people typed into it. */
25
+ const MOST_CONTACTS = 20;
26
+ const listOf = (values, most) => values.flatMap((value) => textOf(value, most) ?? []).slice(0, MOST_CONTACTS);
24
27
  export const crmCopiesOver = (context, people) => {
25
28
  const { database, now } = context;
26
29
  const { savePipeline, saveItemRow } = crmRowsOver(context);
@@ -517,6 +520,8 @@ export const crmCopiesOver = (context, people) => {
517
520
  name: textOf(contact.name, 200),
518
521
  email: textOf(contact.email, 320)?.toLowerCase() ?? null,
519
522
  phone: textOf(contact.phone, 64),
523
+ ...(contact.phones === undefined ? {} : { phones: listOf(contact.phones, 64) }),
524
+ ...(contact.emails === undefined ? {} : { emails: listOf(contact.emails, 320) }),
520
525
  })));
521
526
  return write(database, () => {
522
527
  const accountId = account(key);
@@ -1,20 +1,28 @@
1
1
  import { normalize } from "../normalize.js";
2
- import { ftsMatch, SPEECH } from "./lucene-fields.js";
2
+ import { ftsMatch, quoted, SPEECH } from "./lucene-fields.js";
3
3
  import { spokenTranscripts } from "./transcript-query.js";
4
+ /** A bare word's start (`hero*`), which is looked for where a bare word is. */
5
+ const startOf = (node) => node.operator === "wildcard" && node.implicit ? /^([\p{L}\p{N}]+)\*$/u.exec(normalize(node.value))?.[1] : undefined;
6
+ const matchOf = (node) => {
7
+ const start = startOf(node);
8
+ return start === undefined ? ftsMatch(node) : `${quoted(start)} *`;
9
+ };
4
10
  /**
5
11
  * Which place of each hit holds the words, first match wins in the order of `MatchPlace`; a hit its transcript
6
12
  * holds only through a spelling speech recognition garbled is `corrected`.
7
13
  */
8
14
  export const placeHits = (database, corpus, leaves, transcripts, found, pks) => {
9
- const placeLeaves = leaves.filter(({ node }) => (node.operator === "term" || node.operator === "phrase") &&
10
- (node.implicit || node.field === "content" || node.field === "transcript"));
15
+ const placeLeaves = leaves.filter(({ node }) => ((node.operator === "term" || node.operator === "phrase") &&
16
+ (node.implicit || node.field === "content" || node.field === "transcript")) ||
17
+ startOf(node) !== undefined);
11
18
  if (!placeLeaves.length || !pks.length || found.length !== pks.length)
12
19
  return found;
13
20
  const keys = JSON.stringify(pks);
14
21
  const wordy = placeLeaves.filter(({ node }) => /[\p{L}\p{N}]/u.test(normalize(node.value)));
15
22
  if (!wordy.length)
16
23
  return found;
17
- const match = wordy.map(({ node }) => ftsMatch(node)).join(" OR ");
24
+ const match = wordy.map(({ node }) => matchOf(node)).join(" OR ");
25
+ const starts = wordy.flatMap(({ node }) => startOf(node) ?? []);
18
26
  const implicit = placeLeaves.some(({ node }) => node.implicit);
19
27
  const inText = new Set(implicit
20
28
  ? database
@@ -32,6 +40,7 @@ export const placeHits = (database, corpus, leaves, transcripts, found, pks) =>
32
40
  const files = database
33
41
  .prepare(`SELECT att.attachable_id AS id, att.text AS text, ${SPEECH} AS speech FROM attachments att WHERE att.attachable_type='${corpus.item}' AND att.attachable_id IN (SELECT value FROM json_each(?)) AND att.id IN (SELECT rowid FROM attachment_words WHERE attachment_words MATCH ?) ORDER BY att.position`)
34
42
  .all(keys, match);
43
+ const startSaid = (pk) => starts.length ? files.find((row) => Number(row.id) === pk && Number(row.speech) === 1) : undefined;
35
44
  const fileFields = new Set(placeLeaves.flatMap(({ node }) => (node.implicit ? ["transcript", "content"] : [node.field])));
36
45
  const spoken = spokenTranscripts(database, corpus.item, wordy.flatMap(({ node }) => transcripts.get(node) ?? []), keys);
37
46
  const allNames = implicit
@@ -41,13 +50,17 @@ export const placeHits = (database, corpus, leaves, transcripts, found, pks) =>
41
50
  : [];
42
51
  return found.map((hit, index) => {
43
52
  const pk = pks[index];
44
- const transcript = spoken.get(pk);
53
+ const transcript = spoken.get(pk) ?? startSaid(pk);
45
54
  const file = files.find((row) => Number(row.id) === pk && Number(row.speech) !== 1);
46
55
  const name = allNames.find((row) => {
47
56
  if (Number(row.id) !== pk)
48
57
  return false;
49
58
  const words = normalize(String(row.name)).split(/[^\p{L}\p{N}]+/u);
59
+ if (words.some((word) => starts.some((start) => word.startsWith(start))))
60
+ return true;
50
61
  return wordy.some(({ node }) => {
62
+ if (startOf(node) !== undefined)
63
+ return false;
51
64
  const phrase = normalize(node.value).match(/[\p{L}\p{N}]+/gu) ?? [];
52
65
  if (node.slop !== undefined)
53
66
  return phrase.every((word) => words.includes(word));
@@ -65,7 +78,7 @@ export const placeHits = (database, corpus, leaves, transcripts, found, pks) =>
65
78
  : undefined;
66
79
  if (!place)
67
80
  return hit;
68
- const fixes = place[0] === "transcript" ? (transcript?.corrections ?? []) : [];
81
+ const fixes = place[0] === "transcript" ? (spoken.get(pk)?.corrections ?? []) : [];
69
82
  return {
70
83
  ...hit,
71
84
  matchedIn: place[0],
@@ -7,6 +7,18 @@ import { resolvePersonLinks } from "./person-resolution.js";
7
7
  import { bound } from "./query-filter.js";
8
8
  import { accountIdentities, accounts, aliases, chatMembers, chats, identities, identityLinkEvents, identityLinks, identityRevisions, messages, persons, } from "./schema.js";
9
9
  import { toIso } from "./values.js";
10
+ /** The source's every phone and address as a JSON patch of `metadata`; `undefined` when it gave no list. */
11
+ const contactsOf = ({ phones, emails }) => {
12
+ if (phones === undefined && emails === undefined)
13
+ return undefined;
14
+ const clean = (values, lower) => [
15
+ ...new Set(values.map((one) => (lower ? one.trim().toLowerCase() : one.trim())).filter((one) => one !== "")),
16
+ ];
17
+ return JSON.stringify({
18
+ ...(phones === undefined ? {} : { phones: clean(phones, false) }),
19
+ ...(emails === undefined ? {} : { emails: clean(emails, true) }),
20
+ });
21
+ };
10
22
  const flag = (value) => (value === undefined || value === null ? null : Number(value));
11
23
  const prepare = (orm) => ({
12
24
  find: orm
@@ -136,6 +148,12 @@ const saveIdentity = ({ orm, now, database }, provider, nativeId, name, facts, r
136
148
  .where(eq(identities.id, found.pk))
137
149
  .run();
138
150
  }
151
+ const contacts = contactsOf(facts);
152
+ if (contacts !== undefined)
153
+ database
154
+ .prepare("UPDATE identities SET metadata = json_patch(coalesce(metadata, '{}'), ?) WHERE id = ? " +
155
+ "AND json_patch(coalesce(metadata, '{}'), ?) IS NOT coalesce(metadata, '{}')")
156
+ .run(contacts, found.pk, contacts);
139
157
  const renamed = changed.name !== found.name || changed.username !== found.username;
140
158
  if (renamed && resolveLinks)
141
159
  resolvePersonLinks(database, [changed.name, changed.username]);
@@ -153,7 +171,9 @@ const saveIdentity = ({ orm, now, database }, provider, nativeId, name, facts, r
153
171
  externalId: nativeId,
154
172
  name,
155
173
  nameFolded: folded(name),
156
- metadata: facts.metadata == null ? null : JSON.stringify(facts.metadata),
174
+ metadata: facts.metadata == null && contactsOf(facts) === undefined
175
+ ? null
176
+ : JSON.stringify({ ...facts.metadata, ...JSON.parse(contactsOf(facts) ?? "{}") }),
157
177
  username: facts.username ?? null,
158
178
  bot: flag(facts.isBot),
159
179
  description: facts.description ?? null,
@@ -70,7 +70,8 @@ export interface FieldScope {
70
70
  sql: string;
71
71
  params: SqlValue[];
72
72
  };
73
- everywhere: (node: ResolvedPredicate, fragment: Fragment) => Fragment;
73
+ /** With `start`, a word's start: every word in a file, a transcript or a file name that begins so. */
74
+ everywhere: (node: ResolvedPredicate, fragment: Fragment, start?: string) => Fragment;
74
75
  /** Counts the patterns' expanded words against the query's budget. */
75
76
  expand: (count: number) => number;
76
77
  }
@@ -61,9 +61,14 @@ export const wordMatch = (corpus, match) => ({
61
61
  fts: match,
62
62
  });
63
63
  // The vocabulary is the whole store's, so a chat or date filter does not shorten it.
64
- const tooManyWords = ({ field, operator, value, span }, alone) => {
64
+ const tooManyWords = ({ field, operator, value, span }, alone, prefix) => {
65
65
  const term = `${field}:${operator === "regex" ? `/${value}/` : value}`;
66
- throw new CliError("validation_error", `search: ${term}${alone ? " matches" : " and the patterns before it match"} more than ${QUERY_LIMITS.expansions} indexed words, the term expansions budget — use a longer prefix, or body:/…/ inside one chat`, {
66
+ const spelled = operator === "wildcard" ? value.replace(/[*?]+/gu, " ").trim().split(/\s+/u)[0] : "";
67
+ // Measured on a synthetic 1M-word vocabulary: reading every word takes 1-2 s, the whole search's time.
68
+ const instead = !prefix && spelled
69
+ ? `a pattern that starts with * reads every indexed word — write the start of the word: ${spelled}* (it also finds the word's other forms)`
70
+ : "use a longer prefix, or body:/…/ inside one chat";
71
+ throw new CliError("validation_error", `search: ${term}${alone ? " matches" : " and the patterns before it match"} more than ${QUERY_LIMITS.expansions} indexed words, the term expansions budget — ${instead}`, {
67
72
  reason: "query.too-large",
68
73
  budget: "term expansions",
69
74
  complete: false,
@@ -175,22 +180,25 @@ const words = (node, scope) => {
175
180
  }
176
181
  const pattern = operator === "wildcard" ? wildcardPattern(normalize(value)) : foldRegex(value, node.span);
177
182
  const automaton = scope.patternOf(pattern, node);
183
+ // A bare word's start reads where a bare word does: transcripts, file text and file names too.
184
+ const start = operator === "wildcard" && node.implicit ? /^([\p{L}\p{N}]+)\*$/u.exec(normalize(value))?.[1] : undefined;
185
+ const widened = (fragment) => (start ? scope.everywhere(node, fragment, start) : fragment);
178
186
  const cached = scope.expanded.get(pattern);
179
187
  if (cached)
180
- return { node, fragment: cached };
188
+ return { node, fragment: widened(cached) };
181
189
  const prefix = prefixOf(pattern);
182
190
  const terms = scope.database
183
191
  .prepare(`SELECT term FROM ${corpus.vocab} WHERE col='normalized_text'${prefix ? " AND term>=? AND term<=?" : ""} ORDER BY term LIMIT ?`)
184
192
  .all(...(prefix ? [prefix, `${prefix}\u{10ffff}`] : []), QUERY_LIMITS.expansions + 1);
185
193
  if (scope.expand(terms.length) > QUERY_LIMITS.expansions)
186
- tooManyWords(node, terms.length > QUERY_LIMITS.expansions);
194
+ tooManyWords(node, terms.length > QUERY_LIMITS.expansions, prefix);
187
195
  const matches = terms.flatMap(({ term }) => {
188
196
  scope.check();
189
197
  return automaton.test(String(term), scope.budget) ? [quoted(String(term))] : [];
190
198
  });
191
199
  const fragment = matches.length ? wordMatch(corpus, matches.join(" OR ")) : bound("0");
192
200
  scope.expanded.set(pattern, fragment);
193
- return always(fragment);
201
+ return always(widened(fragment));
194
202
  };
195
203
  const body = (node, scope) => {
196
204
  const { operator, value } = node;
@@ -265,6 +273,14 @@ const size = (node, { corpus }) => {
265
273
  };
266
274
  const attachmentText = (which) => (node, scope) => {
267
275
  const text = normalize(node.value);
276
+ if (node.operator === "wildcard") {
277
+ // FTS5 finds a word by its start in the index itself; any other pattern would read every word of every file.
278
+ const start = /^([\p{L}\p{N}]+)\*$/u.exec(text)?.[1];
279
+ if (start === undefined)
280
+ searchError("query.unsupported-operator", node.span, `${node.field}: takes a word's start only, e.g. ${node.field}:invoice*`);
281
+ const set = scope.attachmentWords(`${quoted(start)} *`, which);
282
+ return always(bound(`m.id IN (${set.sql})`, ...set.params));
283
+ }
268
284
  // Never `fts`: the ranking ANDs every required word into message_words, where a file's words are not.
269
285
  const set = which === "transcript" ? scope.transcripts(node) : scope.attachmentWords(ftsMatch(node), which);
270
286
  return always(/[\p{L}\p{N}]/u.test(text) ? bound(`m.id IN (${set.sql})`, ...set.params) : bound("0"));
@@ -326,14 +342,30 @@ const found = ({ field, value }, scope) => {
326
342
  ? mentioned(scope, "mn.domain = ? AND mn.status <> 'dismissed'", [siteOf(value.toLowerCase())])
327
343
  : mentioned(scope, `mn.kind = ? AND ${match.sql} AND mn.status <> 'dismissed'`, [field, ...match.params]));
328
344
  };
329
- const tag = (node, { corpus, database }) => {
345
+ const tag = (node, scope) => {
346
+ const { corpus, database } = scope;
347
+ const names = node.operator === "wildcard"
348
+ ? tagsFitting(node, scope)
349
+ : [canonicalTagNamed(database, tagNamed(node))?.name ?? tagNamed(node)];
350
+ const named = "t.name IN (SELECT value FROM json_each(?))";
351
+ const list = JSON.stringify(names);
352
+ return always(bound(`m.id IN (SELECT tg.taggable_id FROM taggings tg JOIN resolved_tags t ON t.id=tg.tag_id WHERE ${named} AND tg.taggable_type='${corpus.item}') OR ` +
353
+ `m.chat_id IN (SELECT tg.taggable_id FROM taggings tg JOIN resolved_tags t ON t.id=tg.tag_id WHERE ${named} AND tg.taggable_type='${corpus.thread}') OR ` +
354
+ `m.sender_identity_id IN (SELECT tg.taggable_id FROM taggings tg JOIN resolved_tags t ON t.id=tg.tag_id WHERE ${named} AND tg.taggable_type='identity')`, list, list, list));
355
+ };
356
+ const tagNamed = (node) => {
330
357
  const selected = tagOf(node.value);
331
358
  if (selected === undefined)
332
359
  searchError("query.invalid-tag", node.span);
333
- const name = canonicalTagNamed(database, selected)?.name ?? selected;
334
- return always(bound(`m.id IN (SELECT tg.taggable_id FROM taggings tg JOIN resolved_tags t ON t.id=tg.tag_id WHERE t.name=? AND tg.taggable_type='${corpus.item}') OR ` +
335
- `m.chat_id IN (SELECT tg.taggable_id FROM taggings tg JOIN resolved_tags t ON t.id=tg.tag_id WHERE t.name=? AND tg.taggable_type='${corpus.thread}') OR ` +
336
- "m.sender_identity_id IN (SELECT tg.taggable_id FROM taggings tg JOIN resolved_tags t ON t.id=tg.tag_id WHERE t.name=? AND tg.taggable_type='identity')", name, name, name));
360
+ return selected;
361
+ };
362
+ const tagsFitting = (node, scope) => {
363
+ const automaton = scope.patternOf(wildcardPattern(node.value.toLowerCase()), node);
364
+ return scope.database
365
+ .prepare("SELECT DISTINCT name FROM resolved_tags")
366
+ .all()
367
+ .map(({ name }) => String(name))
368
+ .filter((name) => automaton.test(name, scope.budget));
337
369
  };
338
370
  const messengerOnly = (compile) => (node, scope) => {
339
371
  if (scope.mail)
@@ -394,13 +426,26 @@ const recipient = (node, { mail }) => {
394
426
  };
395
427
  // What a page says about itself, and whether a note is written or a file, exist for notes only.
396
428
  const notesOnly = () => always(bound("0"));
397
- const mailbox = ({ value }, { mail }) => always(mail
398
- ? bound(
429
+ const mailbox = (node, scope) => {
430
+ const { value, operator } = node;
431
+ if (!scope.mail)
432
+ return always(bound("0"));
433
+ if (operator === "wildcard") {
434
+ // A store holds tens of mailboxes: every one is read and the pattern tried on its id and its name.
435
+ const automaton = scope.patternOf(wildcardPattern(fold(value)), node);
436
+ const ids = scope.database
437
+ .prepare("SELECT id, external_id, name_folded FROM mailboxes")
438
+ .all()
439
+ .filter((row) => [fold(String(row.external_id)), String(row.name_folded ?? "")].some((one) => automaton.test(one, scope.budget)))
440
+ .map(({ id }) => Number(id));
441
+ return always(bound("m.id IN (SELECT em.email_id FROM email_mailboxes em WHERE em.mailbox_id IN (SELECT value FROM json_each(?)))", JSON.stringify(ids)));
442
+ }
443
+ return always(bound(
399
444
  // Not tied to m.account_id: a correlated subquery re-reads every mailbox link for each email (minutes on
400
445
  // 880k links), and an email only ever links to its own account's mailboxes anyway.
401
446
  `m.id IN (SELECT em.email_id FROM email_mailboxes em WHERE em.mailbox_id IN
402
- (SELECT b.id FROM mailboxes b WHERE lower(b.external_id) = lower(?) OR b.name_folded = ?))`, value, fold(value))
403
- : bound("0"));
447
+ (SELECT b.id FROM mailboxes b WHERE lower(b.external_id) = lower(?) OR b.name_folded = ?))`, value, fold(value)));
448
+ };
404
449
  // Mail stored in full keeps List-Id in its headers; mail only recorded, in its metadata.
405
450
  const list = ({ value }, { mail }) => {
406
451
  const wanted = value.trim().toLowerCase();
@@ -417,22 +462,37 @@ const is = ({ value }, { mail }) => {
417
462
  ? bound("0")
418
463
  : bound("m.read = ?", state === "read" ? 1 : 0));
419
464
  };
420
- const subject = ({ operator, value }, { corpus, mail }) => {
465
+ const subject = (node, scope) => {
466
+ const { operator, value } = node;
467
+ const { corpus, mail } = scope;
421
468
  const wanted = normalize(value);
422
469
  const parts = wanted.match(/[\p{L}\p{N}]+/gu) ?? [];
423
470
  if (!mail || !parts.length)
424
471
  return always(bound("0"));
472
+ if (operator === "wildcard") {
473
+ // The word index holds a mailbox's every word: a pattern without a start would read all of them.
474
+ const pattern = wildcardPattern(wanted);
475
+ const start = prefixOf(pattern);
476
+ if (!start)
477
+ searchError("query.unsupported-operator", node.span, "subject: takes a word's start, e.g. subject:invoice*");
478
+ const automaton = scope.patternOf(pattern, node);
479
+ return {
480
+ fragment: { ...wordMatch(corpus, `${quoted(start)} *`), exact: false },
481
+ test: (text) => (headingOf(text).match(/[\p{L}\p{N}]+/gu) ?? []).some((word) => automaton.test(word, scope.budget)),
482
+ };
483
+ }
425
484
  // The word index holds subject and body together: it narrows, the subject itself decides.
426
485
  return {
427
486
  fragment: { ...wordMatch(corpus, parts.map(quoted).join(" AND ")), exact: false },
428
487
  test: (text) => {
429
- const heading = normalize(text.slice(0, Math.max(0, text.indexOf("\n\n"))));
488
+ const heading = headingOf(text);
430
489
  return operator === "phrase"
431
490
  ? heading.includes(wanted)
432
491
  : parts.every((word) => new RegExp(`(^|[^\\p{L}\\p{N}])${word}`, "u").test(heading));
433
492
  },
434
493
  };
435
494
  };
495
+ const headingOf = (text) => normalize(text.slice(0, Math.max(0, text.indexOf("\n\n"))));
436
496
  /** One compiler per field of `QUERY_FIELDS`, by its name: a leaf compiles by a lookup, never a branch. */
437
497
  export const FIELD_COMPILERS = {
438
498
  text: words,
@@ -5,7 +5,7 @@ import { exhausted, outOfTime, QUERY_LIMITS, searchError } from "../../search/lu
5
5
  import { TIME_LIMIT_FUNCTION, TimeLimitReached } from "../driver.js";
6
6
  import { emailHitsByPk } from "./emails.js";
7
7
  import { placeHits } from "./hit-places.js";
8
- import { combine, FIELD_COMPILERS, ftsMatch, SPEECH, } from "./lucene-fields.js";
8
+ import { combine, FIELD_COMPILERS, ftsMatch, quoted, SPEECH, } from "./lucene-fields.js";
9
9
  import { GROUPS } from "./lucene-groups.js";
10
10
  import { hitsByPk } from "./search.js";
11
11
  import { read } from "./transaction.js";
@@ -110,15 +110,15 @@ const compileQuery = (context, execution, boundedAttachments = false) => {
110
110
  const transcripts = transcriptTerms(database, execution.root, corpus.item);
111
111
  const said = (node, part) => transcriptItems(corpus.item, transcripts.get(node) ?? { match: ftsMatch(node), widened: [], from: node.value }, part);
112
112
  /** A bare word also matches a transcript, a file's text and a word of a file's name. */
113
- const everywhere = (node, fragment) => {
114
- if (!node.implicit || fragment.sql === "0")
113
+ const everywhere = (node, fragment, start) => {
114
+ if (!node.implicit || (fragment.sql === "0" && start === undefined))
115
115
  return fragment;
116
- const match = ftsMatch(node);
117
- const files = attachmentWords(match, "file");
118
- const spoken = said(node);
116
+ const match = start === undefined ? ftsMatch(node) : `${quoted(start)} *`;
117
+ const files = attachmentWords(match, start === undefined ? "file" : "any");
118
+ const spoken = start === undefined ? said(node) : undefined;
119
119
  const elsewhere = {
120
- sql: `${files.sql} UNION ${spoken.sql} UNION ${namedSql}`,
121
- params: [...files.params, ...spoken.params, match],
120
+ sql: `${files.sql}${spoken ? ` UNION ${spoken.sql}` : ""} UNION ${namedSql}`,
121
+ params: [...files.params, ...(spoken?.params ?? []), match],
122
122
  };
123
123
  return {
124
124
  ...fragment,
@@ -187,6 +187,15 @@ export const searchCorpus = (context, query, corpus) => {
187
187
  tests.set(node, (text) => matcher.test(text, budget));
188
188
  return { sql: "1", params: [], exact: false };
189
189
  }
190
+ if (field === "tag" && operator === "wildcard") {
191
+ const matcher = automaton(wildcardPattern(value.toLowerCase()), node);
192
+ const names = database
193
+ .prepare("SELECT DISTINCT name FROM resolved_tags")
194
+ .all()
195
+ .map(({ name }) => String(name))
196
+ .filter((name) => matcher.test(name, budget));
197
+ return combine(names.flatMap((name) => corpus.tagged?.(name) ?? []), "OR");
198
+ }
190
199
  if (field === "tag") {
191
200
  const tag = tagOf(value);
192
201
  if (tag === undefined)
@@ -8,6 +8,7 @@ import { fold } from "../normalize.js";
8
8
  import { mergedAwaySql } from "./merged-persons.js";
9
9
  import { ALWAYS_SHOWN, shownReasons } from "./person-ties.js";
10
10
  import { mergedAssignees } from "./task-board.js";
11
+ import { hiddenTestPeople } from "./test-people.js";
11
12
  import { read, writeBatch } from "./transaction.js";
12
13
  export const PEOPLE_SORTS = ["interactions", "recent", "name", "tasks"];
13
14
  const MIN_QUERY = 3;
@@ -110,7 +111,9 @@ const lastContacts = (database, scope) => new Map(database
110
111
  /** One misfiled letter is no newsletter. */
111
112
  const BULK_MIN = 3;
112
113
  /** The first rule that holds; the list's contract in the people-clients-digests plan names the same order. */
113
- const kindOf = (shown, facts, ties, mail) => {
114
+ const kindOf = (shown, facts, ties, mail, test) => {
115
+ if (test)
116
+ return { kind: "test", signals: ["test-data"] };
114
117
  const always = ties.filter((tie) => ALWAYS_SHOWN.includes(tie));
115
118
  if (always.length > 0)
116
119
  return { kind: "person", signals: ties };
@@ -140,6 +143,7 @@ const kindOf = (shown, facts, ties, mail) => {
140
143
  /** Each person with their kind, contact and counts; the last contact is added for the page alone. */
141
144
  const classified = (database, people, scope, reasons = shownReasons(database, scope === "all" ? undefined : scope)) => {
142
145
  const facts = factsOf(database, scope);
146
+ const test = hiddenTestPeople(database);
143
147
  const tasks = countsOf(database, TASK_COUNTS, mergedAssignees(database));
144
148
  const messages = countsOf(database, MESSAGE_COUNTS(scope), ...scopeParams(scope));
145
149
  const mail = new Map(database
@@ -151,7 +155,7 @@ const classified = (database, people, scope, reasons = shownReasons(database, sc
151
155
  const contact = { username: own?.username ?? null, phone: own?.phone ?? null, email: own?.email ?? null };
152
156
  const shown = displayName(name, { ...contact, name: own?.name ?? null });
153
157
  const ties = reasons.get(id) ?? [];
154
- const { kind, signals } = kindOf(shown, own, ties, mail.get(id));
158
+ const { kind, signals } = kindOf(shown, own, ties, mail.get(id), test.has(id));
155
159
  return {
156
160
  id,
157
161
  nameOrder: nameOrderOf(shown),
@@ -185,7 +189,7 @@ const byName = (a, b) => a.nameOrder < b.nameOrder ? -1 : a.nameOrder > b.nameOr
185
189
  * Bump when what decides a kind, a name's order or a count changes in code (the word lists, `BULK_MIN`, the ties):
186
190
  * every stored one is worked out again on the next list.
187
191
  */
188
- const KIND_RULES = "3";
192
+ const KIND_RULES = "4";
189
193
  const RULES_KEY = "people.kind_rules";
190
194
  /** Past this many people to work out, one pass over everyone beats a lookup per person. */
191
195
  const WHOLE_PASS = 20_000;
@@ -288,6 +292,8 @@ const storedCounts = (database, filter) => {
288
292
  counts[row.kind] = Number(row.n);
289
293
  return counts;
290
294
  };
295
+ /** Everyone but test data, which `all` leaves out as every list does. */
296
+ const allOf = (counts) => Object.entries(counts).reduce((sum, [kind, n]) => (kind === "test" ? sum : sum + n), 0);
291
297
  const checked = (options) => {
292
298
  const { kind = "person", sort = "interactions" } = options;
293
299
  if (kind !== "all" && !PERSON_KINDS.includes(kind))
@@ -309,11 +315,11 @@ export const listPeople = (database, options) => {
309
315
  const { limit, offset = 0 } = options;
310
316
  return read(database, () => {
311
317
  const counts = storedCounts(database, filter);
312
- const total = kind === "all" ? Object.values(counts).reduce((a, b) => a + b, 0) : counts[kind];
318
+ const total = kind === "all" ? allOf(counts) : counts[kind];
313
319
  const rows = database
314
- .prepare(`SELECT p.id, p.name, p.owner, p.last_contact FROM persons p WHERE p.kind ${kind === "all" ? "<>" : "="} ?` +
320
+ .prepare(`SELECT p.id, p.name, p.owner, p.last_contact FROM persons p WHERE p.kind ${kind === "all" ? "NOT IN (?, ?)" : "= ?"}` +
315
321
  `${filter.sql} ORDER BY p.owner DESC, ${STORED_ORDER[sort]}p.name_order, p.id LIMIT ? OFFSET ?`)
316
- .all(kind === "all" ? MERGED : kind, ...filter.params, limit, offset);
322
+ .all(...(kind === "all" ? [MERGED, "test"] : [kind]), ...filter.params, limit, offset);
317
323
  const page = rows.map(candidateOf);
318
324
  const contacts = new Map(rows.filter((row) => row.last_contact != null).map((row) => [Number(row.id), Number(row.last_contact)]));
319
325
  return {
@@ -337,7 +343,7 @@ const listInMemory = (database, options) => {
337
343
  const counts = noCounts();
338
344
  for (const person of everyone)
339
345
  counts[person.kind] += 1;
340
- const chosen = kind === "all" ? everyone : everyone.filter((person) => person.kind === kind);
346
+ const chosen = everyone.filter((person) => (kind === "all" ? person.kind !== "test" : person.kind === kind));
341
347
  // The newest contact of every person reads every message; only this order needs it.
342
348
  const recent = sort === "recent" ? lastContacts(database, "all") : undefined;
343
349
  const order = sort === "name"
@@ -425,7 +431,7 @@ export const similarPeople = (database, typed, limit) => {
425
431
  }));
426
432
  const byId = new Map(people.map((person) => [person.id, person]));
427
433
  const ordered = [...sameName.keys()].flatMap((id) => byId.get(id) ?? []);
428
- const rows = classified(database, ordered, [...sameName.keys()], ties);
434
+ const rows = classified(database, ordered, [...sameName.keys()], ties).filter(({ kind }) => kind !== "test");
429
435
  const same = rows.map(({ id }) => sameName.get(id) === true);
430
436
  return withLastContact(database, rows).map((person, at) => ({ ...person, sameName: same[at] === true }));
431
437
  };