@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
@@ -256,6 +256,8 @@ export declare const ENTITIES: {
256
256
  readonly name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
257
257
  readonly owner: v.BooleanSchema<undefined>;
258
258
  }, undefined>, undefined>;
259
+ readonly contact_name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
260
+ readonly company_name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
259
261
  readonly currency: v.NullableSchema<v.StringSchema<undefined>, undefined>;
260
262
  readonly amount: v.NullableSchema<v.StringSchema<undefined>, undefined>;
261
263
  readonly close_date: v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>, undefined>;
@@ -315,6 +317,8 @@ export declare const ENTITIES: {
315
317
  readonly name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
316
318
  readonly owner: v.BooleanSchema<undefined>;
317
319
  }, undefined>, undefined>;
320
+ readonly contact_name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
321
+ readonly company_name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
318
322
  readonly currency: v.NullableSchema<v.StringSchema<undefined>, undefined>;
319
323
  readonly amount: v.NullableSchema<v.StringSchema<undefined>, undefined>;
320
324
  readonly close_date: v.NullableSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>, undefined>;
@@ -2718,6 +2722,8 @@ export declare const ENTITIES: {
2718
2722
  readonly username: v.NullableSchema<v.StringSchema<undefined>, undefined>;
2719
2723
  readonly phone: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
2720
2724
  readonly email: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
2725
+ readonly phones: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
2726
+ readonly emails: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
2721
2727
  readonly is_bot: v.NullableSchema<v.BooleanSchema<undefined>, undefined>;
2722
2728
  readonly accounts: v.ArraySchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>, undefined>;
2723
2729
  readonly seen_in: v.ArraySchema<v.StrictObjectSchema<{
@@ -3507,6 +3513,8 @@ export declare const ENTITIES: {
3507
3513
  readonly username: v.NullableSchema<v.StringSchema<undefined>, undefined>;
3508
3514
  readonly phone: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
3509
3515
  readonly email: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
3516
+ readonly phones: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
3517
+ readonly emails: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
3510
3518
  readonly is_bot: v.NullableSchema<v.BooleanSchema<undefined>, undefined>;
3511
3519
  readonly accounts: v.ArraySchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>, undefined>;
3512
3520
  readonly seen_in: v.ArraySchema<v.StrictObjectSchema<{
@@ -3810,6 +3818,8 @@ export declare const ENTITIES: {
3810
3818
  readonly username: v.NullableSchema<v.StringSchema<undefined>, undefined>;
3811
3819
  readonly phone: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
3812
3820
  readonly email: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
3821
+ readonly phones: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
3822
+ readonly emails: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
3813
3823
  readonly is_bot: v.NullableSchema<v.BooleanSchema<undefined>, undefined>;
3814
3824
  readonly accounts: v.ArraySchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>, undefined>;
3815
3825
  readonly seen_in: v.ArraySchema<v.StrictObjectSchema<{
@@ -378,7 +378,8 @@ const OTHERS = [
378
378
  ["person.no-owner", "not_found", "no person is marked as the owner in the store"],
379
379
  ["person.unknown", "not_found", "the store has no person by that reference; people list gives person:<uid>"],
380
380
  ["person.no-doubt", "not_found", "nothing about that person is in doubt; people links check lists who is"],
381
- validation("person.test-data", "the person is in doubt only as test data, which is not kept; remove the test data"),
381
+ validation("person.owner", "the owner's own person is not test data"),
382
+ validation("person.no-identity", "a person with no identity is not test data; there is nothing to hide"),
382
383
  validation("person.from-required", "say whom the identity leaves: --from person:<uid>, or person:me for the owner"),
383
384
  [
384
385
  "identity.separated",
package/dist/resolve.d.ts CHANGED
@@ -27,3 +27,11 @@ export declare const pickChat: (reference: string, chats: Chat[]) => Chat;
27
27
  * `lower()` folds ASCII only, and most of these names are Cyrillic.
28
28
  */
29
29
  export declare const pickPerson: (reference: string, people: PeopleLookup) => Contact;
30
+ /** Everyone a name pattern such as `Ярослав*` or `*Орлов*` fits by their alias, name or @username. */
31
+ export declare const peopleMatching: (pattern: string, people: Contact[], { byAddress }?: {
32
+ byAddress?: boolean | undefined;
33
+ }) => Contact[];
34
+ /** Every chat a name pattern fits by its title or @username. */
35
+ export declare const chatsMatching: (pattern: string, chats: Chat[]) => Chat[];
36
+ /** The items whose names are closest to what a pattern spells, for a refusal to offer: a typo finds nobody. */
37
+ export declare const nearest: <T>(pattern: string, items: T[], names: (item: T) => string[], most?: number) => T[];
package/dist/resolve.js CHANGED
@@ -1,5 +1,7 @@
1
1
  import { CliError, singleLine } from "@wirecat/cli-base";
2
2
  import { contactReferenceOf } from "./domain/ref-arguments.js";
3
+ import { compileAutomaton, wildcardPattern } from "./search/lucene/automaton.js";
4
+ import { trigrams } from "./search/trigrams.js";
3
5
  /** Shaped like a Telegram or MAX id. Another messenger's ids may be any string, so a miss here is not "not an id". */
4
6
  export const isId = (reference) => /^-?\d+$/.test(reference.trim());
5
7
  /**
@@ -47,15 +49,55 @@ export const pickPerson = (reference, people) => {
47
49
  throw new CliError("not_found", `no person ${trimmed} in what this account has seen`);
48
50
  const wanted = foldName(trimmed.replace(/^@/, ""));
49
51
  const everyone = people.all().toSorted((a, b) => (a.name ?? "").localeCompare(b.name ?? ""));
50
- const fields = (person) => [person.alias, person.name, person.username].filter(isPresent).map(foldName);
51
- const exact = everyone.filter((person) => fields(person).includes(wanted));
52
- const matches = exact.length > 0 ? exact : everyone.filter((person) => fields(person).some((one) => one.includes(wanted)));
53
- if (matches.length === 1 && matches[0])
54
- return matches[0];
55
- if (matches.length === 0)
52
+ const exact = everyone.filter((person) => namesOf(person).includes(wanted));
53
+ const containing = everyone.filter((person) => namesOf(person).some((one) => one.includes(wanted)));
54
+ if (exact.length === 1 && exact[0])
55
+ return exact[0];
56
+ if (containing.length === 1 && containing[0])
57
+ return containing[0];
58
+ if (containing.length === 0)
56
59
  throw new CliError("not_found", `nobody matches "${reference}"`);
60
+ // Several people are named exactly this: the ones it is only part of the name of are as likely meant.
61
+ const matches = exact.length > 0 ? [...exact, ...containing.filter((person) => !exact.includes(person))] : containing;
57
62
  throw ambiguous(reference, "people", matches.map(({ id, name, username }) => ({ id, name, username })), ({ name, username }) => singleLine([name, username && `@${username}`].filter(isPresent).join(" ")));
58
63
  };
64
+ const namesOf = (person, byAddress = false) => [person.alias, person.name, person.username, byAddress ? person.id : undefined].filter(isPresent).map(foldName);
65
+ const chatNamesOf = (chat) => [chat.title, chat.providerMetadata?.username]
66
+ .filter((one) => typeof one === "string" && one !== "")
67
+ .map(foldName);
68
+ /** A name pattern with Lucene's `*` and `?`, matched against a whole name folded as `foldName` folds it. */
69
+ const namePattern = (pattern) => {
70
+ const automaton = compileAutomaton(wildcardPattern(foldName(pattern.trim().replace(/^@/, ""))));
71
+ return (names) => names.some((one) => automaton.test(one));
72
+ };
73
+ /** Everyone a name pattern such as `Ярослав*` or `*Орлов*` fits by their alias, name or @username. */
74
+ export const peopleMatching = (pattern, people, { byAddress = false } = {}) => {
75
+ const fits = namePattern(pattern);
76
+ return people.filter((person) => fits(namesOf(person, byAddress)));
77
+ };
78
+ /** Every chat a name pattern fits by its title or @username. */
79
+ export const chatsMatching = (pattern, chats) => {
80
+ const fits = namePattern(pattern);
81
+ return chats.filter((chat) => fits(chatNamesOf(chat)));
82
+ };
83
+ /** The items whose names are closest to what a pattern spells, for a refusal to offer: a typo finds nobody. */
84
+ export const nearest = (pattern, items, names, most = 5) => {
85
+ const pieces = (text) => foldName(text).split(/\s+/u).flatMap(trigrams);
86
+ const wanted = new Set(pieces(pattern.replace(/\\(.)/gu, "$1").replace(/[*?@]/gu, " ").trim()));
87
+ if (wanted.size === 0)
88
+ return [];
89
+ return items
90
+ .map((item) => ({
91
+ item,
92
+ score: names(item)
93
+ .flatMap(pieces)
94
+ .filter((piece) => wanted.has(piece)).length,
95
+ }))
96
+ .filter(({ score }) => score > 1)
97
+ .toSorted((a, b) => b.score - a.score)
98
+ .slice(0, most)
99
+ .map(({ item }) => item);
100
+ };
59
101
  const ambiguous = (reference, what, candidates, label) => {
60
102
  const width = Math.max(...candidates.map(({ id }) => id.length));
61
103
  const lines = candidates.map((candidate) => ` ${candidate.id.padEnd(width)} ${label(candidate)}`).join("\n");
@@ -73,7 +73,15 @@ export interface StoreEvent {
73
73
  op: "insert" | "update" | "delete";
74
74
  n: number;
75
75
  }
76
- export type DiagnosticEvent = RequestEvent | CacheEvent | WarningEvent | StoreEvent;
76
+ /** What a long command showed as its progress, so a run's log says what its window drew: counts, never a name. */
77
+ export interface ProgressEvent {
78
+ event: "progress";
79
+ /** `sync.progress`: the step that drew it. */
80
+ operation: string;
81
+ kind: "progress";
82
+ counts: Record<string, number>;
83
+ }
84
+ export type DiagnosticEvent = RequestEvent | CacheEvent | WarningEvent | StoreEvent | ProgressEvent;
77
85
  export type EventSink = (event: DiagnosticEvent) => void;
78
86
  /** A sentence for a person, and the warning event it stands for when there is one: a log record keeps only the event. */
79
87
  export type Warn = (message: string, warning?: WarningEvent) => void;
@@ -11,6 +11,10 @@ export const providerErrorKey = (value) => typeof value === "string" && /^[A-Za-
11
11
  export const renderEvent = (event) => {
12
12
  if (event.event === "store")
13
13
  return `${MARK.store} ${event.operation.padEnd(16)} ${event.table} ${event.op} ${event.n}`;
14
+ if (event.event === "progress")
15
+ return `${MARK.progress} ${event.operation.padEnd(16)} ${Object.entries(event.counts)
16
+ .map(([field, count]) => `${count} ${field}`)
17
+ .join(" ")}`;
14
18
  if (event.event === "warning") {
15
19
  const counts = Object.entries(event.counts ?? {}).map(([field, count]) => `${count} ${field}`);
16
20
  return [`${MARK.warning} ${(event.operation ?? "").padEnd(16)} ${event.code}`, ...counts, event.detail]
@@ -55,6 +59,6 @@ export const renderEvent = (event) => {
55
59
  }
56
60
  return `${MARK[event.event]} ${event.operation.padEnd(16)} ${parts.join(" ")}`.trimEnd();
57
61
  };
58
- const MARK = { request: "→", response: "←", cache: "•", warning: "!", store: "+" };
62
+ const MARK = { request: "→", response: "←", cache: "•", warning: "!", store: "+", progress: "…" };
59
63
  const age = (ms) => (ms < 1000 ? `${ms}ms` : `${Math.round(ms / 1000)}s`);
60
64
  const size = (bytes) => (bytes < 1000 ? `${bytes} B` : `${(bytes / 1000).toFixed(1)} kB`);
@@ -10,6 +10,7 @@ export const CORE_LOG_EVENTS = defineLogEvents([
10
10
  keys: ["operation", "reason"],
11
11
  },
12
12
  { id: "store.write", meaning: "a committed write changed rows of one store table", keys: ["table", "op", "n"] },
13
+ { id: "sync.progress", meaning: "what a sync's progress line showed: chats and messages so far", keys: ["counts"] },
13
14
  { id: "command.crashed", meaning: "a command failed on a bug; where, never what", keys: ["error_class", "frames"] },
14
15
  {
15
16
  id: "events.dropped",
@@ -34,4 +35,5 @@ export const DIAGNOSTIC_LOG_EVENTS = {
34
35
  warning: "client.warning",
35
36
  cache: "cache.answered",
36
37
  store: "store.write",
38
+ progress: "sync.progress",
37
39
  };
@@ -31,7 +31,7 @@ const validateSize = (node) => {
31
31
  parseBytes(bound, node.span);
32
32
  };
33
33
  const validateTag = (node) => {
34
- if (tagOf(node.value) === undefined)
34
+ if (node.operator === "wildcard" ? !/^[a-z0-9*?-]{1,32}$/iu.test(node.value) : tagOf(node.value) === undefined)
35
35
  searchError("query.invalid-tag", node.span, "a tag is 1-32 letters a-z, digits and hyphens");
36
36
  };
37
37
  const validateMentioned = (node) => {
@@ -43,6 +43,8 @@ const validateTopic = (node) => {
43
43
  searchError("query.invalid-topic", node.span, "use a thread id in one chat");
44
44
  };
45
45
  const terms = ["term", "phrase"];
46
+ const names = [...terms, "wildcard"];
47
+ const NAMES = "account-scoped: an id or contact: reference as is; with * or ? a pattern over alias, name, @username (up to 50); else a name";
46
48
  export const QUERY_FIELDS = [
47
49
  {
48
50
  name: "text",
@@ -76,12 +78,12 @@ export const QUERY_FIELDS = [
76
78
  },
77
79
  {
78
80
  name: "from",
79
- example: 'from:"Alice Synthetic"',
81
+ example: "from:Alice*",
80
82
  index: "identities / sender index",
81
83
  aliases: [],
82
84
  type: "kw",
83
- operators: terms,
84
- normalization: "account-scoped resolution",
85
+ operators: names,
86
+ normalization: NAMES,
85
87
  support: "A1",
86
88
  },
87
89
  ...["to", "cc", "bcc"].map((name) => ({
@@ -90,8 +92,8 @@ export const QUERY_FIELDS = [
90
92
  index: "email_recipients",
91
93
  aliases: [],
92
94
  type: "kw",
93
- operators: terms,
94
- normalization: "account-scoped resolution; mail only",
95
+ operators: names,
96
+ normalization: `${NAMES}; mail only`,
95
97
  support: "A1",
96
98
  })),
97
99
  {
@@ -100,7 +102,7 @@ export const QUERY_FIELDS = [
100
102
  index: "email_words, then the subject",
101
103
  aliases: [],
102
104
  type: "txt",
103
- operators: terms,
105
+ operators: [...terms, "wildcard"],
104
106
  normalization: "every word, folded as text is; mail only",
105
107
  support: "A1",
106
108
  validate: filled,
@@ -111,7 +113,7 @@ export const QUERY_FIELDS = [
111
113
  index: "email_mailboxes",
112
114
  aliases: [],
113
115
  type: "kw",
114
- operators: terms,
116
+ operators: [...terms, "wildcard"],
115
117
  normalization: "a folder or label by its id (ASCII case folded) or name (case folded in any script); mail only",
116
118
  support: "A1",
117
119
  },
@@ -121,7 +123,7 @@ export const QUERY_FIELDS = [
121
123
  index: "email_mailboxes",
122
124
  aliases: [],
123
125
  type: "kw",
124
- operators: terms,
126
+ operators: [...terms, "wildcard"],
125
127
  normalization: "the same as mailbox:; mail only",
126
128
  support: "A1",
127
129
  },
@@ -149,12 +151,12 @@ export const QUERY_FIELDS = [
149
151
  },
150
152
  {
151
153
  name: "chat",
152
- example: 'chat:"Work fixture"',
154
+ example: "chat:*fixture*",
153
155
  index: "chats / message time index",
154
156
  aliases: [],
155
157
  type: "kw",
156
- operators: terms,
157
- normalization: "account-scoped resolution",
158
+ operators: names,
159
+ normalization: "account-scoped: an id or chat: reference as is; with * or ? a pattern over title, @username (up to 50); else a title",
158
160
  support: "A1",
159
161
  },
160
162
  {
@@ -319,7 +321,7 @@ export const QUERY_FIELDS = [
319
321
  index: "attachment_words",
320
322
  aliases: [],
321
323
  type: "txt",
322
- operators: terms,
324
+ operators: [...terms, "wildcard"],
323
325
  normalization: "NFKD/marks/NFC/lowercase v1; the text of files attachments extract read or an agent wrote",
324
326
  support: "A2",
325
327
  validate: filled,
@@ -330,7 +332,7 @@ export const QUERY_FIELDS = [
330
332
  index: "attachment_words ∪ transcript_stems; garbled spellings from transcript_words_vocab",
331
333
  aliases: [],
332
334
  type: "txt",
333
- operators: terms,
335
+ operators: [...terms, "wildcard"],
334
336
  normalization: "any form of the word (Snowball), widened to spellings speech recognition garbles; what a voice message said",
335
337
  support: "A2",
336
338
  validate: filled,
@@ -424,7 +426,7 @@ export const QUERY_FIELDS = [
424
426
  index: "tags: the message, its chat or its sender",
425
427
  aliases: [],
426
428
  type: "kw",
427
- operators: terms,
429
+ operators: [...terms, "wildcard"],
428
430
  normalization: "lowercase a-z, 0-9 and -, 1-32 characters",
429
431
  support: "A2",
430
432
  validate: validateTag,
@@ -1,5 +1,6 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { isUsable } from "../domain/relations.js";
3
+ import { isClosedState } from "../tasks/index.js";
3
4
  import { coverageFor, edgesOf, grouped, namesOf, notRejected, organizationCategories, SECTION_LIMIT, STORE_PAGE, scopeOf, sectionOf, } from "./business-context.js";
4
5
  import { communicationsOf } from "./communications.js";
5
6
  import { moneyOf } from "./money-context.js";
@@ -74,6 +75,22 @@ export const dealContext = async (store, reference, { accounts, limit = SECTION_
74
75
  const said = talks.counts.messages + talks.counts.mail + talks.counts.meetings;
75
76
  const stages = await store.deals.stages(deal.ref);
76
77
  const tasks = await openTasksOf(store, project ? [{ ref: project.ref, key: project.key }] : []);
78
+ const opened = await store.tasks.find({
79
+ where: { sql: "t.source_group = ?", params: [deal.ref] },
80
+ limit: STORE_PAGE,
81
+ });
82
+ for (const task of opened)
83
+ if (!isClosedState(task.status) && !tasks.tasks.some((one) => one.ref === task.ref))
84
+ tasks.tasks.push({
85
+ ref: task.ref,
86
+ key: task.key,
87
+ title: task.title,
88
+ status: task.status,
89
+ project: task.project,
90
+ dueAt: task.dueAt,
91
+ });
92
+ tasks.full ||= opened.length >= STORE_PAGE;
93
+ tasks.tasks.sort((a, b) => (a.dueAt ?? "~").localeCompare(b.dueAt ?? "~") || a.ref.localeCompare(b.ref));
77
94
  return {
78
95
  deal,
79
96
  stages: sectionOf(stages, limit, null, { newest: true }),
@@ -30,7 +30,19 @@ export declare const chatAmong: (messenger: Saved, store: MessageStore, accounts
30
30
  chatId: Id;
31
31
  }>;
32
32
  /** A sender, through the names each messenger's accounts have seen; `from:` names one person. */
33
- export declare const senderAmong: (store: MessageStore, accounts: AccountKey[], reference: string) => Promise<{
33
+ export declare const senderAmong: (store: MessageStore, accounts: AccountKey[], reference: string, field?: string) => Promise<{
34
34
  provider: string;
35
35
  id: string;
36
36
  }>;
37
+ /** The most people or chats one name pattern may stand for in a search. */
38
+ export declare const MOST_NAME_MATCHES = 50;
39
+ /** Every sender a name pattern (`from:Ярослав*`) fits, through the names each messenger's accounts have seen. */
40
+ export declare const sendersMatching: (store: MessageStore, accounts: AccountKey[], field: string, pattern: string) => Promise<{
41
+ provider: Provider;
42
+ id: Id;
43
+ }[]>;
44
+ /** Every stored chat a name pattern (`chat:*отчёт*`) fits, left ones included: a search reads kept history. */
45
+ export declare const chatsMatchingIn: (store: MessageStore, accounts: AccountKey[], pattern: string) => Promise<{
46
+ account: AccountKey;
47
+ chatId: Id;
48
+ }[]>;
@@ -1,9 +1,10 @@
1
1
  import { CliError, singleLine } from "@wirecat/cli-base";
2
2
  import { chatReferenceOf, ensureAccount } from "../domain/ref-arguments.js";
3
3
  import { profilesOn } from "../domain/ref-summaries.js";
4
- import { isId, pickChat, pickPerson } from "../resolve.js";
4
+ import { chatsMatching, isId, nearest, peopleMatching, pickChat, pickPerson } from "../resolve.js";
5
5
  import { codeOf } from "../sends/guarded.js";
6
6
  import { nothingStored } from "./deps.js";
7
+ import { MAIL } from "./search-kind.js";
7
8
  /**
8
9
  * The chat a store read is about. Offline, a chat with nothing kept answers empty, as it always has;
9
10
  * in store mode the store is the only source, so an empty answer would pass for "nothing was said".
@@ -148,7 +149,7 @@ export const chatAmong = async (messenger, store, accounts, reference) => {
148
149
  })));
149
150
  };
150
151
  /** A sender, through the names each messenger's accounts have seen; `from:` names one person. */
151
- export const senderAmong = async (store, accounts, reference) => {
152
+ export const senderAmong = async (store, accounts, reference, field = "from") => {
152
153
  const providers = [...new Set(accounts.map(({ provider }) => provider))];
153
154
  const [only] = accounts;
154
155
  try {
@@ -174,8 +175,48 @@ export const senderAmong = async (store, accounts, reference) => {
174
175
  }
175
176
  catch (error) {
176
177
  if (error instanceof CliError && error.code === "not_found") {
177
- throw new CliError("not_found", `from:${reference} — ${error.message}`);
178
+ throw new CliError("not_found", `${field}:${reference} — ${error.message}`);
178
179
  }
179
180
  throw error;
180
181
  }
181
182
  };
183
+ /** The most people or chats one name pattern may stand for in a search. */
184
+ export const MOST_NAME_MATCHES = 50;
185
+ /** `candidates` are shaped as an ambiguous name's are: `{id, name, username}` for people, `{id, title}` for chats. */
186
+ const patternRefused = (field, pattern, what, found, near) => {
187
+ if (found === 0)
188
+ throw new CliError("not_found", `${field}:${pattern} — no ${what} fits${near.length ? `; near: ${near.map(({ label }) => label).join(", ")}` : ""}`, { candidates: near.map(({ candidate }) => candidate) });
189
+ throw new CliError("validation_error", `${field}:${pattern} fits ${found} ${what}, more than ${MOST_NAME_MATCHES} — write more of the name`, { reason: "query.too-large", budget: "name matches", limit: MOST_NAME_MATCHES, complete: false });
190
+ };
191
+ /** Every sender a name pattern (`from:Ярослав*`) fits, through the names each messenger's accounts have seen. */
192
+ export const sendersMatching = async (store, accounts, field, pattern) => {
193
+ const providers = [...new Set(accounts.map(({ provider }) => provider))];
194
+ const seen = await Promise.all(providers.map(async (provider) => {
195
+ const ids = accounts.filter((one) => one.provider === provider).map(({ account }) => account);
196
+ // One account's people carry its aliases; several accounts' do not.
197
+ const scope = ids.length === 1 ? { account: ids[0] } : { accounts: ids };
198
+ return { provider, people: (await store.people.people(provider, scope)).all() };
199
+ }));
200
+ const found = seen.flatMap(({ provider, people }) => peopleMatching(pattern, people, { byAddress: provider === MAIL }).map(({ id }) => ({ provider, id })));
201
+ if (found.length === 0 || found.length > MOST_NAME_MATCHES) {
202
+ const people = seen.flatMap(({ people }) => people);
203
+ const near = nearest(pattern, people, ({ name, alias }) => [name, alias].filter(isText));
204
+ patternRefused(field, pattern, "person", found.length, near.map(({ id, name, username }) => ({ id, label: name ?? id, candidate: { id, name, username } })));
205
+ }
206
+ return found;
207
+ };
208
+ /** Every stored chat a name pattern (`chat:*отчёт*`) fits, left ones included: a search reads kept history. */
209
+ export const chatsMatchingIn = async (store, accounts, pattern) => {
210
+ const held = await Promise.all(accounts.map(async (account) => ({
211
+ account,
212
+ chats: (await store.chats.chats(account, { includeLeft: true })).items,
213
+ })));
214
+ const found = held.flatMap(({ account, chats }) => chatsMatching(pattern, chats).map((chat) => ({ account, chatId: chat.id })));
215
+ if (found.length === 0 || found.length > MOST_NAME_MATCHES) {
216
+ const chats = held.flatMap(({ chats }) => chats);
217
+ const near = nearest(pattern, chats, ({ title }) => [title].filter(isText));
218
+ patternRefused("chat", pattern, "chat", found.length, near.map(({ id, title }) => ({ id, label: title ?? id, candidate: { id, title } })));
219
+ }
220
+ return found;
221
+ };
222
+ const isText = (value) => typeof value === "string" && value !== "";
@@ -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 MAIL_FIELDS = new Set(["to", "cc", "bcc", "subject", "mailbox", "label", "is"]);
17
- import { dateRange, parseLucene, timezoneOf, walkQuery } from "@wirecat/cli-base/query";
16
+ const PERSON_FIELDS = new Set(["from", "to", "cc", "bcc"]);
17
+ const MAIL_FIELDS = new Set(["to", "cc", "bcc", "subject", "mailbox", "label", "is", "list"]);
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")
107
- return { ...node, resolution: { sender: await senderAmong(store, scopeAccounts, node.value) } };
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)
113
+ return { ...node, resolution: { sender: await senderAmong(store, scopeAccounts, node.value, node.field) } };
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);
@@ -319,14 +324,19 @@ export const searchLucene = async (store, account, request, messenger = {}) => {
319
324
  const prepared = await prepareLucene(store, account, request, messenger);
320
325
  const execute = store.queries.matchQuery.bind(store.queries);
321
326
  const mailAccounts = prepared.scopeAccounts.filter(({ provider }) => provider === MAIL);
327
+ let mailLeftOut;
322
328
  const inMailTables = async () => {
323
329
  try {
324
330
  return await execute({ ...prepared.execution, accounts: mailAccounts, corpus: "mail" });
325
331
  }
326
332
  catch (error) {
327
- // A messenger field (`kind:`, `topic:`) leaves mail out of a search that names messenger accounts too.
328
- if (request.kind !== "mail" && error instanceof CliError && error.code === "validation_error")
333
+ // A messenger field (`kind:`, `topic:`) leaves mail out of a search that names messenger accounts too; any
334
+ // other refusal (`*word*` over a large mailbox) is said, or the answer would look complete.
335
+ if (request.kind !== "mail" && error instanceof CliError && error.code === "validation_error") {
336
+ if (error.details.reason !== "query.unsupported-field")
337
+ mailLeftOut = { source: MAIL, code: "validation_error", reason: error.message };
329
338
  return { items: [], hasMore: false };
339
+ }
330
340
  throw error;
331
341
  }
332
342
  };
@@ -362,7 +372,9 @@ export const searchLucene = async (store, account, request, messenger = {}) => {
362
372
  completeness,
363
373
  query: queryOf(prepared.timezone, request.newest, prepared.stemming),
364
374
  ...(coverage ? { coverage } : {}),
365
- ...(prepared.skipped ? { skipped: prepared.skipped } : {}),
375
+ ...(prepared.skipped || mailLeftOut
376
+ ? { skipped: [...(prepared.skipped ?? []), ...(mailLeftOut ? [mailLeftOut] : [])] }
377
+ : {}),
366
378
  ...(request.kind === "mail"
367
379
  ? { accounts: mailAccounts.map(({ provider, account }) => ({ resource: "mail", provider, account })) }
368
380
  : {}),
@@ -403,6 +415,15 @@ const QUERY_PAGE_LIMIT = 1000;
403
415
  const oldestFetch = (chats) => chats.length === 0 || chats.some(({ fetchedAt }) => fetchedAt === null)
404
416
  ? null
405
417
  : chats.map(({ fetchedAt }) => fetchedAt).sort()[0];
418
+ /** A name pattern's leaf as an OR of one resolved leaf per fit, so every compiler still reads one sender or chat. */
419
+ const anyOf = (node, found, resolution) => ({
420
+ kind: "boolean",
421
+ span: node.span,
422
+ clauses: found.map((one) => ({
423
+ occur: "should",
424
+ node: { ...node, operator: "term", resolution: resolution(one) },
425
+ })),
426
+ });
406
427
  const requiresChat = (node, chat) => node === chat ||
407
428
  (node.kind === "boolean" && node.clauses.some((clause) => clause.occur === "must" && requiresChat(clause.node, chat)));
408
429
  /** 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;
@@ -38,8 +38,15 @@ export interface SearchAllRecordItem {
38
38
  email?: MailFields;
39
39
  /** A message's or a mail's files, as `search messages` names them. */
40
40
  attachments?: HitFile[];
41
- /** Which search found it: words, meaning or both. */
41
+ /** Which search found it: words, meaning or both; a deal or a lead by `title`, or `words` of its company or contacts. */
42
42
  foundBy: ("title" | "words" | "meaning")[];
43
+ /** A deal's or a lead's: `corrected` when it matched only once a misspelt query word was corrected. */
44
+ match?: "corrected";
45
+ /** For a `corrected` hit, the stored words each corrected query word became. */
46
+ corrections?: {
47
+ from: string;
48
+ to: string[];
49
+ }[];
43
50
  /** A business hit's: whether the owner confirmed it, or it waits for him. */
44
51
  review?: "proposed" | "confirmed";
45
52
  /** A business hit's source record, when an import made it. */
@@ -155,8 +162,8 @@ export type SearchAllMessenger = Partial<Pick<MessengerTraits, "savedChatId" | "
155
162
  hintCommand?: string | null;
156
163
  };
157
164
  /**
158
- * What a deal or a lead is found by: words or phrases of its title, all of them, or any with OR. Anything else is
159
- * refused, so `search all` skips deals with the reason instead of matching a field they do not have.
165
+ * What a deal or a lead is found by: plain words or phrases, all of them, or any with OR. Anything else is refused,
166
+ * so `search all` skips deals with the reason instead of matching a field they do not have.
160
167
  */
161
168
  export declare const titleWords: (text: string, refused?: string) => {
162
169
  words: string[];
@@ -46,10 +46,10 @@ const filtersBeside = (text) => {
46
46
  : undefined;
47
47
  };
48
48
  /**
49
- * What a deal or a lead is found by: words or phrases of its title, all of them, or any with OR. Anything else is
50
- * refused, so `search all` skips deals with the reason instead of matching a field they do not have.
49
+ * What a deal or a lead is found by: plain words or phrases, all of them, or any with OR. Anything else is refused,
50
+ * so `search all` skips deals with the reason instead of matching a field they do not have.
51
51
  */
52
- export const titleWords = (text, refused = "deals and leads are found by the words of their title only") => {
52
+ export const titleWords = (text, refused = "deals and leads are found by the words of their title, company and contacts only") => {
53
53
  const { root } = parseLucene(text, SEARCH_QUERY);
54
54
  const clauses = root.kind === "boolean" ? root.clauses : [{ node: root, occur: "must" }];
55
55
  const words = clauses.map(({ node, occur }) => occur !== "must_not" &&
@@ -313,11 +313,16 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
313
313
  accounts.push(...read.map(({ provider, account }) => ({ resource, provider, account })));
314
314
  }
315
315
  else if (resource === "crm") {
316
+ // `plainQuery` made `stage:won` a phrase, which would find nothing and still call the answer complete.
317
+ const field = /(?:^|\s)[+-]?(stage|status|pipeline):/iu.exec(asked.text)?.[1]?.toLowerCase();
318
+ if (field)
319
+ throw new CliError("validation_error", `deals and leads are not searched by ${field}; list them by it with \`deals list ${field}:<value>\``);
316
320
  const { words, anyWord } = titleWords(request.text);
317
321
  const chosen = scope?.crm;
318
322
  const found = await store.deals.find({
319
323
  words,
320
324
  anyWord: anyWord || discover,
325
+ ...(request.exact ? { exact: true } : {}),
321
326
  ...(request.crmKinds === undefined ? {} : { kinds: request.crmKinds }),
322
327
  limit: Math.min(depth + 1, 500),
323
328
  ...(chosen === undefined ? {} : { accounts: chosen }),
@@ -331,7 +336,8 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
331
336
  title: deal.title,
332
337
  timestamp: deal.updatedAt,
333
338
  text: deal.summary,
334
- foundBy: ["title"],
339
+ foundBy: deal.matched.includes("title") ? ["title"] : ["words"],
340
+ ...(deal.corrections ? { match: "corrected", corrections: deal.corrections } : {}),
335
341
  })));
336
342
  const read = chosen ?? [...(await crmAccounts(store)), { provider: "crm", account: INTERNAL_NOTES }];
337
343
  for (const { provider, account } of read)