@wirecat/cli-core 0.639.0 → 0.641.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 (64) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/dist/cli/messenger/backfill-command.js +16 -1
  3. package/dist/cli/messenger/search-answers.js +2 -0
  4. package/dist/cli/store-settings.d.ts +4 -1
  5. package/dist/cli/store-settings.js +26 -9
  6. package/dist/crm/cli/csv.js +2 -0
  7. package/dist/crm/cli/index.js +8 -2
  8. package/dist/crm/cli/search-all.js +4 -4
  9. package/dist/crm/stage-tasks.d.ts +8 -0
  10. package/dist/crm/stage-tasks.js +42 -0
  11. package/dist/domain/crm.d.ts +9 -0
  12. package/dist/domain/name-variants.d.ts +2 -0
  13. package/dist/domain/name-variants.js +107 -0
  14. package/dist/domain/person-kinds.d.ts +6 -3
  15. package/dist/domain/person-kinds.js +5 -2
  16. package/dist/entities/contact-activity.d.ts +3 -0
  17. package/dist/entities/contact-activity.js +3 -0
  18. package/dist/entities/contact-context.d.ts +6 -0
  19. package/dist/entities/deal.d.ts +6 -0
  20. package/dist/entities/deal.js +3 -0
  21. package/dist/entities/index.d.ts +10 -0
  22. package/dist/errors/reasons.js +2 -1
  23. package/dist/resolve.d.ts +8 -0
  24. package/dist/resolve.js +48 -6
  25. package/dist/runs/events.d.ts +9 -1
  26. package/dist/runs/events.js +5 -1
  27. package/dist/runs/log-events.js +2 -0
  28. package/dist/search/lucene/registry.js +17 -15
  29. package/dist/services/deal-context.js +17 -0
  30. package/dist/services/message-resolution.d.ts +13 -1
  31. package/dist/services/message-resolution.js +44 -3
  32. package/dist/services/messages-search.js +41 -20
  33. package/dist/services/metadata.d.ts +1 -1
  34. package/dist/services/search-all.d.ts +10 -3
  35. package/dist/services/search-all.js +10 -4
  36. package/dist/store/index.d.ts +2 -2
  37. package/dist/store/people.d.ts +10 -3
  38. package/dist/store/people.js +2 -1
  39. package/dist/store/sqlite/accounts.js +2 -0
  40. package/dist/store/sqlite/crm-rows.js +2 -0
  41. package/dist/store/sqlite/crm-settings.d.ts +26 -1
  42. package/dist/store/sqlite/crm-settings.js +104 -1
  43. package/dist/store/sqlite/crm.d.ts +12 -0
  44. package/dist/store/sqlite/crm.js +9 -1
  45. package/dist/store/sqlite/deals.d.ts +28 -5
  46. package/dist/store/sqlite/deals.js +158 -14
  47. package/dist/store/sqlite/hit-places.js +19 -6
  48. package/dist/store/sqlite/identities.js +21 -1
  49. package/dist/store/sqlite/lucene-fields.d.ts +2 -1
  50. package/dist/store/sqlite/lucene-fields.js +129 -16
  51. package/dist/store/sqlite/lucene.js +8 -8
  52. package/dist/store/sqlite/note-search.js +9 -0
  53. package/dist/store/sqlite/people-list.js +14 -8
  54. package/dist/store/sqlite/person-doubts.d.ts +13 -3
  55. package/dist/store/sqlite/person-doubts.js +92 -48
  56. package/dist/store/sqlite/person-links.js +15 -2
  57. package/dist/store/sqlite/tasks.js +9 -8
  58. package/dist/store/sqlite/test-people.d.ts +24 -0
  59. package/dist/store/sqlite/test-people.js +92 -0
  60. package/dist/store/types.d.ts +6 -0
  61. package/dist/tasks/model.d.ts +6 -2
  62. package/dist/tasks/service.d.ts +2 -0
  63. package/docs/search/recipes.json +3 -0
  64. package/package.json +1 -1
@@ -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,16 @@ 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, mail) => {
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
+ ? mail
70
+ ? `a pattern that starts with * reads every indexed word — write the start of the word: ${spelled}* (it also finds the word's other forms)`
71
+ : `a pattern without three letters in a row reads every indexed word — write three or more between the stars, or the start of the word: ${spelled}*`
72
+ : "use a longer prefix, or body:/…/ inside one chat";
73
+ 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
74
  reason: "query.too-large",
68
75
  budget: "term expansions",
69
76
  complete: false,
@@ -159,6 +166,52 @@ const stemmedText = (node, scope) => {
159
166
  })
160
167
  : bound("0"));
161
168
  };
169
+ /** A wildcard value's literal parts, split at its unescaped `*` and `?`. */
170
+ const literalRuns = (value) => {
171
+ const runs = [""];
172
+ const chars = [...value];
173
+ for (let at = 0; at < chars.length; at++) {
174
+ const c = chars[at];
175
+ if (c === "\\")
176
+ runs[runs.length - 1] += chars[++at] ?? "";
177
+ else if (c === "*" || c === "?")
178
+ runs.push("");
179
+ else
180
+ runs[runs.length - 1] += c;
181
+ }
182
+ return runs.filter(Boolean);
183
+ };
184
+ const MOST_YO_SPELLINGS = 64;
185
+ /** Every spelling of `run` with each е or ё as either: the trigram index keeps the text as written. */
186
+ const yoSpellings = (run) => {
187
+ let spellings = [""];
188
+ for (const c of run) {
189
+ spellings = spellings.flatMap((start) => (c === "е" || c === "ё" ? [`${start}е`, `${start}ё`] : [`${start}${c}`]));
190
+ if (spellings.length > MOST_YO_SPELLINGS)
191
+ return undefined;
192
+ }
193
+ return spellings;
194
+ };
195
+ /**
196
+ * A pattern with no start to read the word list from (`*договор*`, `*ость`), in chat messages: the trigram index of
197
+ * their text finds where its longest part occurs, so a large store does not refuse it: the whole search took 0.5–1 s at
198
+ * 1M messages (cli-testing performance/search/infix-chat-text). `*part*` is answered by the index alone; any other shape is
199
+ * checked word by word. It folds case, not accents: the part matches as typed, ё and е either way.
200
+ */
201
+ const insideWords = (node, automaton, scope) => {
202
+ const typed = node.value.normalize("NFC").toLowerCase();
203
+ const [longest = ""] = literalRuns(typed).sort((a, b) => [...b].length - [...a].length);
204
+ const spellings = [...longest].length >= 3 ? yoSpellings(longest) : undefined;
205
+ if (!spellings)
206
+ return undefined;
207
+ const fragment = bound("m.id IN (SELECT rowid FROM messages_fts WHERE messages_fts MATCH ?)", spellings.map(quoted).join(" OR "));
208
+ if (/^\*+[\p{L}\p{N}]+\*+$/u.test(typed))
209
+ return always(fragment);
210
+ return {
211
+ fragment: { ...fragment, exact: false },
212
+ test: (text) => (normalize(text).match(/[\p{L}\p{N}]+/gu) ?? []).some((word) => automaton.test(word, scope.budget)),
213
+ };
214
+ };
162
215
  const words = (node, scope) => {
163
216
  const { operator, value } = node;
164
217
  const { corpus } = scope;
@@ -175,22 +228,30 @@ const words = (node, scope) => {
175
228
  }
176
229
  const pattern = operator === "wildcard" ? wildcardPattern(normalize(value)) : foldRegex(value, node.span);
177
230
  const automaton = scope.patternOf(pattern, node);
231
+ // A bare word's start reads where a bare word does: transcripts, file text and file names too.
232
+ const start = operator === "wildcard" && node.implicit ? /^([\p{L}\p{N}]+)\*$/u.exec(normalize(value))?.[1] : undefined;
233
+ const widened = (fragment) => (start ? scope.everywhere(node, fragment, start) : fragment);
178
234
  const cached = scope.expanded.get(pattern);
179
235
  if (cached)
180
- return { node, fragment: cached };
236
+ return { node, fragment: widened(cached) };
181
237
  const prefix = prefixOf(pattern);
238
+ if (!scope.mail && operator === "wildcard" && [...prefix].length < 3) {
239
+ const inside = insideWords(node, automaton, scope);
240
+ if (inside)
241
+ return inside;
242
+ }
182
243
  const terms = scope.database
183
244
  .prepare(`SELECT term FROM ${corpus.vocab} WHERE col='normalized_text'${prefix ? " AND term>=? AND term<=?" : ""} ORDER BY term LIMIT ?`)
184
245
  .all(...(prefix ? [prefix, `${prefix}\u{10ffff}`] : []), QUERY_LIMITS.expansions + 1);
185
246
  if (scope.expand(terms.length) > QUERY_LIMITS.expansions)
186
- tooManyWords(node, terms.length > QUERY_LIMITS.expansions);
247
+ tooManyWords(node, terms.length > QUERY_LIMITS.expansions, prefix, scope.mail);
187
248
  const matches = terms.flatMap(({ term }) => {
188
249
  scope.check();
189
250
  return automaton.test(String(term), scope.budget) ? [quoted(String(term))] : [];
190
251
  });
191
252
  const fragment = matches.length ? wordMatch(corpus, matches.join(" OR ")) : bound("0");
192
253
  scope.expanded.set(pattern, fragment);
193
- return always(fragment);
254
+ return always(widened(fragment));
194
255
  };
195
256
  const body = (node, scope) => {
196
257
  const { operator, value } = node;
@@ -265,6 +326,14 @@ const size = (node, { corpus }) => {
265
326
  };
266
327
  const attachmentText = (which) => (node, scope) => {
267
328
  const text = normalize(node.value);
329
+ if (node.operator === "wildcard") {
330
+ // FTS5 finds a word by its start in the index itself; any other pattern would read every word of every file.
331
+ const start = /^([\p{L}\p{N}]+)\*$/u.exec(text)?.[1];
332
+ if (start === undefined)
333
+ searchError("query.unsupported-operator", node.span, `${node.field}: takes a word's start only, e.g. ${node.field}:invoice*`);
334
+ const set = scope.attachmentWords(`${quoted(start)} *`, which);
335
+ return always(bound(`m.id IN (${set.sql})`, ...set.params));
336
+ }
268
337
  // Never `fts`: the ranking ANDs every required word into message_words, where a file's words are not.
269
338
  const set = which === "transcript" ? scope.transcripts(node) : scope.attachmentWords(ftsMatch(node), which);
270
339
  return always(/[\p{L}\p{N}]/u.test(text) ? bound(`m.id IN (${set.sql})`, ...set.params) : bound("0"));
@@ -326,14 +395,30 @@ const found = ({ field, value }, scope) => {
326
395
  ? mentioned(scope, "mn.domain = ? AND mn.status <> 'dismissed'", [siteOf(value.toLowerCase())])
327
396
  : mentioned(scope, `mn.kind = ? AND ${match.sql} AND mn.status <> 'dismissed'`, [field, ...match.params]));
328
397
  };
329
- const tag = (node, { corpus, database }) => {
398
+ const tag = (node, scope) => {
399
+ const { corpus, database } = scope;
400
+ const names = node.operator === "wildcard"
401
+ ? tagsFitting(node, scope)
402
+ : [canonicalTagNamed(database, tagNamed(node))?.name ?? tagNamed(node)];
403
+ const named = "t.name IN (SELECT value FROM json_each(?))";
404
+ const list = JSON.stringify(names);
405
+ 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 ` +
406
+ `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 ` +
407
+ `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));
408
+ };
409
+ const tagNamed = (node) => {
330
410
  const selected = tagOf(node.value);
331
411
  if (selected === undefined)
332
412
  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));
413
+ return selected;
414
+ };
415
+ const tagsFitting = (node, scope) => {
416
+ const automaton = scope.patternOf(wildcardPattern(node.value.toLowerCase()), node);
417
+ return scope.database
418
+ .prepare("SELECT DISTINCT name FROM resolved_tags")
419
+ .all()
420
+ .map(({ name }) => String(name))
421
+ .filter((name) => automaton.test(name, scope.budget));
337
422
  };
338
423
  const messengerOnly = (compile) => (node, scope) => {
339
424
  if (scope.mail)
@@ -394,13 +479,26 @@ const recipient = (node, { mail }) => {
394
479
  };
395
480
  // What a page says about itself, and whether a note is written or a file, exist for notes only.
396
481
  const notesOnly = () => always(bound("0"));
397
- const mailbox = ({ value }, { mail }) => always(mail
398
- ? bound(
482
+ const mailbox = (node, scope) => {
483
+ const { value, operator } = node;
484
+ if (!scope.mail)
485
+ return always(bound("0"));
486
+ if (operator === "wildcard") {
487
+ // A store holds tens of mailboxes: every one is read and the pattern tried on its id and its name.
488
+ const automaton = scope.patternOf(wildcardPattern(fold(value)), node);
489
+ const ids = scope.database
490
+ .prepare("SELECT id, external_id, name_folded FROM mailboxes")
491
+ .all()
492
+ .filter((row) => [fold(String(row.external_id)), String(row.name_folded ?? "")].some((one) => automaton.test(one, scope.budget)))
493
+ .map(({ id }) => Number(id));
494
+ 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)));
495
+ }
496
+ return always(bound(
399
497
  // Not tied to m.account_id: a correlated subquery re-reads every mailbox link for each email (minutes on
400
498
  // 880k links), and an email only ever links to its own account's mailboxes anyway.
401
499
  `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"));
500
+ (SELECT b.id FROM mailboxes b WHERE lower(b.external_id) = lower(?) OR b.name_folded = ?))`, value, fold(value)));
501
+ };
404
502
  // Mail stored in full keeps List-Id in its headers; mail only recorded, in its metadata.
405
503
  const list = ({ value }, { mail }) => {
406
504
  const wanted = value.trim().toLowerCase();
@@ -417,22 +515,37 @@ const is = ({ value }, { mail }) => {
417
515
  ? bound("0")
418
516
  : bound("m.read = ?", state === "read" ? 1 : 0));
419
517
  };
420
- const subject = ({ operator, value }, { corpus, mail }) => {
518
+ const subject = (node, scope) => {
519
+ const { operator, value } = node;
520
+ const { corpus, mail } = scope;
421
521
  const wanted = normalize(value);
422
522
  const parts = wanted.match(/[\p{L}\p{N}]+/gu) ?? [];
423
523
  if (!mail || !parts.length)
424
524
  return always(bound("0"));
525
+ if (operator === "wildcard") {
526
+ // The word index holds a mailbox's every word: a pattern without a start would read all of them.
527
+ const pattern = wildcardPattern(wanted);
528
+ const start = prefixOf(pattern);
529
+ if (!start)
530
+ searchError("query.unsupported-operator", node.span, "subject: takes a word's start, e.g. subject:invoice*");
531
+ const automaton = scope.patternOf(pattern, node);
532
+ return {
533
+ fragment: { ...wordMatch(corpus, `${quoted(start)} *`), exact: false },
534
+ test: (text) => (headingOf(text).match(/[\p{L}\p{N}]+/gu) ?? []).some((word) => automaton.test(word, scope.budget)),
535
+ };
536
+ }
425
537
  // The word index holds subject and body together: it narrows, the subject itself decides.
426
538
  return {
427
539
  fragment: { ...wordMatch(corpus, parts.map(quoted).join(" AND ")), exact: false },
428
540
  test: (text) => {
429
- const heading = normalize(text.slice(0, Math.max(0, text.indexOf("\n\n"))));
541
+ const heading = headingOf(text);
430
542
  return operator === "phrase"
431
543
  ? heading.includes(wanted)
432
544
  : parts.every((word) => new RegExp(`(^|[^\\p{L}\\p{N}])${word}`, "u").test(heading));
433
545
  },
434
546
  };
435
547
  };
548
+ const headingOf = (text) => normalize(text.slice(0, Math.max(0, text.indexOf("\n\n"))));
436
549
  /** One compiler per field of `QUERY_FIELDS`, by its name: a leaf compiles by a lookup, never a branch. */
437
550
  export const FIELD_COMPILERS = {
438
551
  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
  };
@@ -27,7 +27,7 @@ export interface PersonDoubt {
27
27
  /** The same moves as `fix`, one each, for an app that runs them without a command line. */
28
28
  moves: DoubtMove[];
29
29
  }
30
- /** Undo a merge, or move identities to one new person. */
30
+ /** Undo a merge, move identities to one new person, or call the person test data, which hides them. */
31
31
  export type DoubtMove = {
32
32
  op: "unmerge";
33
33
  merge: string;
@@ -37,6 +37,9 @@ export type DoubtMove = {
37
37
  op: "unlink";
38
38
  identities: string[];
39
39
  from: string;
40
+ } | {
41
+ op: "test-data";
42
+ person: string;
40
43
  };
41
44
  export interface PersonDoubts {
42
45
  items: PersonDoubt[];
@@ -53,8 +56,15 @@ export interface KeptPerson {
53
56
  /** The identities the owner said belong here; a doubt about them comes back once one of them moves. */
54
57
  kept: string[];
55
58
  }
59
+ export interface TestDataPerson {
60
+ person: string;
61
+ /** The identities the owner called test data: the person is hidden from every list until called real. */
62
+ identities: string[];
63
+ }
56
64
  /**
57
- * The owner's answer to a doubt: this person is right as they are. Test data is not a link and stays listed. Refused
58
- * when nothing about the person is in doubt.
65
+ * The owner's answer to a doubt: this person is right as they are, and what looked like test data is a real contact,
66
+ * which also brings back a person memo hid as test data. Refused when nothing about the person is in doubt or hidden.
59
67
  */
60
68
  export declare const keepPerson: (context: StoreContext, uid: string, by: Decider) => KeptPerson;
69
+ /** The owner's answer to a doubt: the person is test data, hidden from every list until the owner calls them real. */
70
+ export declare const markTestData: (context: StoreContext, uid: string, by: Decider) => TestDataPerson;