@wirecat/cli-core 0.609.0 → 0.610.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 (51) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/dist/cli/messenger/search-answers.js +12 -0
  3. package/dist/cli/search-left-out.d.ts +1 -0
  4. package/dist/cli/search-left-out.js +2 -0
  5. package/dist/domain/business.d.ts +3 -0
  6. package/dist/domain/business.js +2 -0
  7. package/dist/entities/hit.d.ts +13 -2
  8. package/dist/entities/hit.js +10 -2
  9. package/dist/entities/index.d.ts +7 -1
  10. package/dist/errors/reasons.js +4 -0
  11. package/dist/search/account-list.d.ts +3 -2
  12. package/dist/search/account-list.js +5 -4
  13. package/dist/services/link-scorers/chat-senders.d.ts +2 -1
  14. package/dist/services/link-scorers/chat-senders.js +13 -4
  15. package/dist/services/link-scorers/types.d.ts +1 -1
  16. package/dist/services/metadata.d.ts +1 -1
  17. package/dist/services/proposals/kinds/relationship.js +1 -0
  18. package/dist/services/proposals/registry.js +3 -1
  19. package/dist/services/proposals/types.d.ts +2 -0
  20. package/dist/services/search-all-business.d.ts +18 -0
  21. package/dist/services/search-all-business.js +38 -0
  22. package/dist/services/search-all-meetings.d.ts +1 -1
  23. package/dist/services/search-all-meetings.js +7 -2
  24. package/dist/services/search-all.d.ts +10 -6
  25. package/dist/services/search-all.js +18 -4
  26. package/dist/store/exports.d.ts +2 -0
  27. package/dist/store/exports.js +2 -0
  28. package/dist/store/index.d.ts +4 -1
  29. package/dist/store/index.js +2 -0
  30. package/dist/store/sqlite/business-search.d.ts +44 -0
  31. package/dist/store/sqlite/business-search.js +141 -0
  32. package/dist/store/sqlite/finance.d.ts +12 -0
  33. package/dist/store/sqlite/finance.js +38 -2
  34. package/dist/store/sqlite/involvement-queue.d.ts +2 -7
  35. package/dist/store/sqlite/involvement-queue.js +11 -14
  36. package/dist/store/sqlite/money-lines.d.ts +12 -1
  37. package/dist/store/sqlite/money-lines.js +50 -4
  38. package/dist/store/sqlite/orders.js +5 -25
  39. package/dist/store/sqlite/proposed-actions.d.ts +2 -0
  40. package/dist/store/sqlite/proposed-actions.js +4 -3
  41. package/dist/store/sqlite/records.d.ts +21 -0
  42. package/dist/store/sqlite/records.js +74 -13
  43. package/dist/store/sqlite/ref-summaries.d.ts +3 -1
  44. package/dist/store/sqlite/ref-summaries.js +4 -1
  45. package/dist/store/sqlite/reported-relations.d.ts +1 -0
  46. package/dist/store/sqlite/reported-relations.js +1 -1
  47. package/dist/store/store.d.ts +2 -0
  48. package/dist/store/store.js +4 -4
  49. package/dist/terminal/prompt.d.ts +4 -0
  50. package/dist/terminal/prompt.js +21 -2
  51. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -5,6 +5,63 @@ Notable changes to `@wirecat/cli-core` (`@wirecat/cli-messaging` up to 0.261.0,
5
5
  minor version may break callers, and says how under "Changed — may break callers". `pnpm docs:check` checks the
6
6
  shape of this file.
7
7
 
8
+ ## 0.610.0 — 08.11.2026
9
+
10
+ ### Added
11
+
12
+ - **A scan's group senders can be found and decided together.** `chat-senders@3` names the chat and its size in its
13
+ reason ("wrote 40 messages in «Sales» (25 people) since 2026-08-10"), and its evidence leads with the chat's ref.
14
+ `ProposalFilter.via` keeps the proposals whose evidence holds a reference, and `store.proposedActions.list` takes
15
+ `evidence` to filter in the query, so `via` pages stored relationship proposals in full. A pending `chat-senders@2`
16
+ proposal takes the new reason and evidence on the next scan, under the same id.
17
+ - **`search all` has a `business` lane.** `searchAll` finds invoices, payments, orders, contracts, subscriptions,
18
+ products and wallets by the words of their numbers and names (an invoice's counterparty, a payment's payer or payee,
19
+ an order's shop and lines), each word where a word starts, folded in memory like the `crm` lane, with no index.
20
+ Each hit carries its `review` (`proposed` or `confirmed`). A row an import made (its `source` is
21
+ `import:<provider>`) carries `source_record` (`provider`, `account`, `external_id`): the oldest live record that
22
+ maps to it, else the oldest deleted one, which also decides its account; the owner's and agents' rows are
23
+ `business:internal`. `scope.business` and `--source` read the import accounts they name. Transactions, `custom:`
24
+ records and rejected rows are left out. `store.business.find` and `store.business.accounts` back it.
25
+ - **Permission key `business.list`** (or `business`): a profile that denies it leaves the `business` lane out of
26
+ `search all` and says so under `missing`, as `deals.list` does for deals (`deniedKinds`). memo reads the lane by
27
+ default once it takes this release; that key turns it off.
28
+ - **`store.finance.addInvoiceLine` and `removeInvoiceLine` change an invoice's lines, as `store.orders` does an
29
+ order's.** A `product` reference copies the product's name and price, and a later price change leaves the line as it
30
+ is. The owner changes any invoice's lines but a void, rejected or deleted one's; a bot only those of an invoice it
31
+ proposed that is still proposed (`finance.owner-only`). The total follows the lines, and the status follows the total
32
+ against what confirmed payments settled. Refused: removing the last line (`finance.line`), a position with no line
33
+ (`finance.no-line`), and lines totalling less than is paid (`finance.below-paid`).
34
+ - **`store.records.list` takes `entity`, `batch` and `deleted`, and `store.records.incoming` lists what points at a
35
+ record or an entity**, for a `records show` that shows relations both ways. `entity` is a ref and lists the records
36
+ mapped to it; `batch` is a `batch_id`; `deleted: true` lists only deleted records, `false` only live ones, and left
37
+ out lists both, as before. `incoming(key)` gives the live records whose relations resolve to that record;
38
+ `incoming({ entity })` those naming the entity by ref, from every account, and those resolved to a record mapped to
39
+ it. Each names its record's provider, account, type and id, with the role, `as` and `amount`.
40
+
41
+ ### Changed — may break callers
42
+
43
+ - **`RESOURCES_SEARCHED` ends with `business`**, so `searchAll` and `searchAllWithMeetings` read it when `only` is
44
+ left out, and `SearchAllItem.kind` and the `hit` entity's `kind` take `invoice`, `payment`, `order`, `contract`,
45
+ `subscription`, `product` and `wallet`. A switch over hit kinds needs those branches; pass `only` to keep the old
46
+ lanes. The source tools' `search all` (`SOURCE_SEARCHED`) is unchanged.
47
+ - **`MessageStore.business` is a new required member**: a hand-made store object or test double needs it.
48
+ - **`SearchedResource`, `ResourceWithMeetings` and `SearchAllRequest.scope` take `business`**, and the strict `hit`
49
+ entity takes `review` and `source_record`; an exhaustive switch or a copy of the schema needs them.
50
+
51
+ ### Fixed
52
+
53
+ - **A hidden prompt asks again when nothing arrived.** `readSecret` at a terminal took an empty Enter as the answer,
54
+ so a paste that never landed (Ctrl+V in a Linux terminal) failed at once with "no token was given", and the hidden
55
+ input showed nothing to tell it apart from a paste that worked. An empty hidden answer now prints "Nothing arrived.
56
+ To paste in a terminal, use Ctrl+Shift+V (or right-click → Paste)." (Cmd+V on macOS) and asks again, up to three
57
+ times, then fails with `validation_error`, reason `input.empty`. A piped empty answer still comes back empty at once,
58
+ an echoed prompt keeps its empty answer, and Ctrl-C still cancels at once.
59
+
60
+ - **A large CRM sync takes a third less time and a sixth of the memory** (#2682). Keeping the involvement index
61
+ current built a new SQL text for every item it recomputed, so SQLite prepared each one again and the process kept
62
+ them all. The item's id is now a bound parameter, one statement per kind of item. On the same synthetic data, the
63
+ 20,000 sync peaks at 0.6 GB instead of 3.7 GB and takes 19 s instead of 30 s, its `--rescan` 13 s instead of 21 s.
64
+
8
65
  ## 0.609.0 — 08.11.2026
9
66
 
10
67
  ### Added
@@ -1,4 +1,5 @@
1
1
  import { hitFiles } from "../../domain/attachments.js";
2
+ import { BUSINESS_KINDS } from "../../domain/business.js";
2
3
  import { formatLocator, parseLocator } from "../../domain/locator.js";
3
4
  import { senderIsMe } from "../../domain/models.js";
4
5
  import { chosenTextModel } from "../../embeddings/models.js";
@@ -279,6 +280,8 @@ export const messagesAnswer = (command, found, { limit, page, again }, query = "
279
280
  */
280
281
  const DOCUMENT_HIT_UNTRUSTED = ["title", "excerpt"];
281
282
  export const noteHitItem = (hit) => defined({ ...hit, untrusted: hit.kind === "document" ? DOCUMENT_HIT_UNTRUSTED : undefined });
283
+ // Numbers and names come from the other side's documents or an import.
284
+ const BUSINESS_UNTRUSTED = Object.fromEntries(BUSINESS_KINDS.map((kind) => [kind, ["title", "excerpt", "source_record.external_id"]]));
282
285
  /** The text of each kind of `search all` hit that someone other than the owner may have written. */
283
286
  const ALL_HIT_UNTRUSTED = {
284
287
  message: ["title", "excerpt", "sender_name", "attachments.name"],
@@ -290,6 +293,7 @@ const ALL_HIT_UNTRUSTED = {
290
293
  // A CRM's copy is typed by the CRM's users; the owner's own deal is his, but one rule keeps a hit's marking simple.
291
294
  deal: ["title", "excerpt"],
292
295
  lead: ["title", "excerpt"],
296
+ ...BUSINESS_UNTRUSTED,
293
297
  };
294
298
  export const allHitItem = (item) => item.kind === "meeting"
295
299
  ? {
@@ -326,6 +330,14 @@ export const allHitItem = (item) => item.kind === "meeting"
326
330
  sender_is_me: item.senderIsMe,
327
331
  sender_ref: item.from?.ref,
328
332
  found_by: item.foundBy,
333
+ review: item.review,
334
+ source_record: item.sourceRecord === undefined
335
+ ? undefined
336
+ : {
337
+ provider: item.sourceRecord.provider,
338
+ account: item.sourceRecord.account,
339
+ external_id: item.sourceRecord.externalId,
340
+ },
329
341
  attachments: item.attachments === undefined ? undefined : nonEmpty(item.attachments),
330
342
  untrusted: ALL_HIT_UNTRUSTED[item.kind],
331
343
  });
@@ -5,6 +5,7 @@ import { type PermissionKey } from "../sends/permissions.js";
5
5
  declare const LIST_KEYS: {
6
6
  readonly deal: "deals.list";
7
7
  readonly lead: "leads.list";
8
+ readonly business: "business.list";
8
9
  readonly messages: "messages.list";
9
10
  readonly mail: "mail.list";
10
11
  readonly notes: "notes.list";
@@ -5,6 +5,8 @@ import { settingsFor } from "./settings.js";
5
5
  const LIST_KEYS = {
6
6
  deal: "deals.list",
7
7
  lead: "leads.list",
8
+ // No command lists business data across its types yet; the key is the lane's own, so a profile can turn it off.
9
+ business: "business.list",
8
10
  messages: "messages.list",
9
11
  mail: "mail.list",
10
12
  notes: "notes.list",
@@ -1,5 +1,8 @@
1
1
  import { type FinanceReview, type MoneyDirection } from "./finance.js";
2
2
  export declare const CATALOG_KINDS: readonly ["product", "service"];
3
+ /** What the `business` lane of `search all` reads; transactions are too many to fold per query. */
4
+ export declare const BUSINESS_KINDS: readonly ["invoice", "payment", "order", "contract", "subscription", "product", "wallet"];
5
+ export type BusinessKind = (typeof BUSINESS_KINDS)[number];
3
6
  export declare const CONTRACT_KINDS: readonly ["sale", "purchase", "service", "lease", "employment", "nda", "license", "other"];
4
7
  export declare const CONTRACT_STATUSES: readonly ["draft", "active", "ended", "terminated"];
5
8
  export declare const PERIOD_UNITS: readonly ["day", "week", "month", "year"];
@@ -2,6 +2,8 @@ import { CliError } from "@wirecat/cli-base";
2
2
  import { dayMonth, notes } from "./finance.js";
3
3
  import { moneyLabel } from "./money.js";
4
4
  export const CATALOG_KINDS = ["product", "service"];
5
+ /** What the `business` lane of `search all` reads; transactions are too many to fold per query. */
6
+ export const BUSINESS_KINDS = ["invoice", "payment", "order", "contract", "subscription", "product", "wallet"];
5
7
  export const CONTRACT_KINDS = ["sale", "purchase", "service", "lease", "employment", "nda", "license", "other"];
6
8
  export const CONTRACT_STATUSES = ["draft", "active", "ended", "terminated"];
7
9
  export const PERIOD_UNITS = ["day", "week", "month", "year"];
@@ -1,7 +1,10 @@
1
1
  import * as v from "valibot";
2
- /** One result of `search all`: a message, a mail, a note, a calendar event, a meeting passage, a deal or a lead. */
2
+ /**
3
+ * One result of `search all`: a message, a mail, a note, a calendar event, a meeting passage, a deal, a lead, or an
4
+ * invoice, payment, order, contract, subscription, product or wallet.
5
+ */
3
6
  export declare const hit: v.StrictObjectSchema<{
4
- readonly kind: v.PicklistSchema<["message", "mail", "note", "document", "event", "meeting", "deal", "lead"], undefined>;
7
+ readonly kind: v.PicklistSchema<["message", "mail", "note", "document", "event", "meeting", "deal", "lead", "invoice", "payment", "order", "contract", "subscription", "product", "wallet"], undefined>;
5
8
  readonly ref: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>;
6
9
  readonly provider: v.StringSchema<undefined>;
7
10
  readonly url: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
@@ -31,6 +34,14 @@ export declare const hit: v.StrictObjectSchema<{
31
34
  readonly lines_total: v.OptionalSchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>, undefined>;
32
35
  /** A meeting passage's stored line, so two passages of one meeting stay apart; `search meetings` gives the same. */
33
36
  readonly id: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>, undefined>;
37
+ /** A business hit's: `proposed` waits for the owner; a product or a wallet has no review and is `confirmed`. */
38
+ readonly review: v.OptionalSchema<v.PicklistSchema<["proposed", "confirmed"], undefined>, undefined>;
39
+ /** A business hit's record in the import that made it; absent for one the owner or an agent wrote. */
40
+ readonly source_record: v.OptionalSchema<v.StrictObjectSchema<{
41
+ readonly provider: v.StringSchema<undefined>;
42
+ readonly account: v.StringSchema<undefined>;
43
+ readonly external_id: v.StringSchema<undefined>;
44
+ }, undefined>, undefined>;
34
45
  /** A message's files; absent when it has none. */
35
46
  readonly attachments: v.OptionalSchema<v.ArraySchema<v.StrictObjectSchema<{
36
47
  readonly position: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
@@ -1,9 +1,13 @@
1
1
  import * as v from "valibot";
2
+ import { BUSINESS_KINDS } from "../domain/business.js";
2
3
  import { hitFile } from "./attachment.js";
3
4
  import { count, reference, text, time, untrusted } from "./fields.js";
4
- /** One result of `search all`: a message, a mail, a note, a calendar event, a meeting passage, a deal or a lead. */
5
+ /**
6
+ * One result of `search all`: a message, a mail, a note, a calendar event, a meeting passage, a deal, a lead, or an
7
+ * invoice, payment, order, contract, subscription, product or wallet.
8
+ */
5
9
  export const hit = v.strictObject({
6
- kind: v.picklist(["message", "mail", "note", "document", "event", "meeting", "deal", "lead"]),
10
+ kind: v.picklist(["message", "mail", "note", "document", "event", "meeting", "deal", "lead", ...BUSINESS_KINDS]),
7
11
  ref: reference,
8
12
  provider: text,
9
13
  url: v.optional(text),
@@ -33,6 +37,10 @@ export const hit = v.strictObject({
33
37
  lines_total: v.optional(count),
34
38
  /** A meeting passage's stored line, so two passages of one meeting stay apart; `search meetings` gives the same. */
35
39
  id: v.optional(v.pipe(v.string(), v.minLength(1))),
40
+ /** A business hit's: `proposed` waits for the owner; a product or a wallet has no review and is `confirmed`. */
41
+ review: v.optional(v.picklist(["proposed", "confirmed"])),
42
+ /** A business hit's record in the import that made it; absent for one the owner or an agent wrote. */
43
+ source_record: v.optional(v.strictObject({ provider: text, account: text, external_id: text })),
36
44
  /** A message's files; absent when it has none. */
37
45
  attachments: v.optional(v.array(hitFile)),
38
46
  /** Absent on a note hit: the owner wrote it. */
@@ -4261,7 +4261,7 @@ export declare const ENTITIES: {
4261
4261
  readonly untrusted: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
4262
4262
  }, undefined>;
4263
4263
  readonly hit: v.StrictObjectSchema<{
4264
- readonly kind: v.PicklistSchema<["message", "mail", "note", "document", "event", "meeting", "deal", "lead"], undefined>;
4264
+ readonly kind: v.PicklistSchema<["message", "mail", "note", "document", "event", "meeting", "deal", "lead", "invoice", "payment", "order", "contract", "subscription", "product", "wallet"], undefined>;
4265
4265
  readonly ref: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "a reference such as `note:42`">]>;
4266
4266
  readonly provider: v.StringSchema<undefined>;
4267
4267
  readonly url: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
@@ -4280,6 +4280,12 @@ export declare const ENTITIES: {
4280
4280
  readonly line: v.OptionalSchema<v.SchemaWithPipe<readonly [v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>, v.MinValueAction<number, 1, undefined>]>, undefined>;
4281
4281
  readonly lines_total: v.OptionalSchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>, undefined>;
4282
4282
  readonly id: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>, undefined>;
4283
+ readonly review: v.OptionalSchema<v.PicklistSchema<["proposed", "confirmed"], undefined>, undefined>;
4284
+ readonly source_record: v.OptionalSchema<v.StrictObjectSchema<{
4285
+ readonly provider: v.StringSchema<undefined>;
4286
+ readonly account: v.StringSchema<undefined>;
4287
+ readonly external_id: v.StringSchema<undefined>;
4288
+ }, undefined>, undefined>;
4283
4289
  readonly attachments: v.OptionalSchema<v.ArraySchema<v.StrictObjectSchema<{
4284
4290
  readonly position: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
4285
4291
  readonly kind: v.StringSchema<undefined>;
@@ -211,6 +211,7 @@ const OTHERS = [
211
211
  validation("evidence.row-too-large", "one evidence row is over its size limit"),
212
212
  validation("index.not-ready", "the search index is still being built"),
213
213
  validation("input.closed", "the input closed before the answer"),
214
+ validation("input.empty", "a hidden prompt got an empty answer three times"),
214
215
  validation("input.required", "the command needs an answer and cannot ask for one"),
215
216
  validation("input.too-large", "the input is over its size limit"),
216
217
  ["meeting-project.stale", "configuration_error", "the meeting's project changed meanwhile"],
@@ -219,10 +220,13 @@ const OTHERS = [
219
220
  validation("fact.payment-retired", "a payment is a payments row in store.finance, not a fact"),
220
221
  validation("fact.revoke-correction", "an accepted correction cannot be revoked; its superseded fact stays"),
221
222
  validation("finance.allocate", "the invoice or payment cannot take an allocation in its state"),
223
+ validation("finance.below-paid", "the invoice's lines would total less than is paid on it"),
222
224
  validation("finance.currency", "the payment and the invoice are in different currencies; nothing is converted"),
223
225
  validation("finance.field", "a field of the invoice or payment is not valid"),
224
226
  validation("finance.line-amount", "an invoice line's amount is not its quantity times its unit price"),
227
+ validation("finance.line", "an invoice keeps at least one line: reject or void it instead"),
225
228
  validation("finance.lines", "the invoice's lines are not valid"),
229
+ ["finance.no-line", "not_found", "the invoice has no line at that position"],
226
230
  ["finance.not-allocated", "not_found", "the payment is not allocated to that invoice"],
227
231
  validation("finance.over-invoice", "the allocation would settle more than the invoice's total"),
228
232
  validation("finance.over-payment", "the allocation would use more than the payment's amount"),
@@ -56,9 +56,10 @@ export interface SkippedSource {
56
56
  }
57
57
  /**
58
58
  * The accounts of `kinds` the entries name, and each entry that names none of them with the reason. A search
59
- * fails only when nothing fits: `what` names the search in that error.
59
+ * fails only when nothing fits: `what` names the search in that error. `alsoFits` takes an account no kind names,
60
+ * such as one a records import wrote business data into.
60
61
  */
61
- export declare const fitting: (entries: readonly ListedEntry[], kinds: readonly Kind[], what: string, reasonOf?: (kind: Kind) => string) => {
62
+ export declare const fitting: (entries: readonly ListedEntry[], kinds: readonly Kind[], what: string, reasonOf?: (kind: Kind) => string, alsoFits?: (account: AccountKey) => boolean) => {
62
63
  accounts: AccountKey[];
63
64
  skipped: SkippedSource[];
64
65
  };
@@ -218,18 +218,19 @@ const READS = {
218
218
  };
219
219
  /**
220
220
  * The accounts of `kinds` the entries name, and each entry that names none of them with the reason. A search
221
- * fails only when nothing fits: `what` names the search in that error.
221
+ * fails only when nothing fits: `what` names the search in that error. `alsoFits` takes an account no kind names,
222
+ * such as one a records import wrote business data into.
222
223
  */
223
- export const fitting = (entries, kinds, what, reasonOf = (kind) => READS[kind]) => {
224
+ export const fitting = (entries, kinds, what, reasonOf = (kind) => READS[kind], alsoFits = () => false) => {
224
225
  const chosen = new Map();
225
226
  const skipped = [];
226
227
  for (const { entry, accounts } of entries) {
227
- const fits = accounts.filter((one) => kinds.some((kind) => listedHolds(one, kind)));
228
+ const fits = accounts.filter((one) => kinds.some((kind) => listedHolds(one, kind)) || alsoFits(one));
228
229
  for (const { provider, account } of fits)
229
230
  if (!chosen.has(keyOf({ provider, account })))
230
231
  chosen.set(keyOf({ provider, account }), { provider, account });
231
232
  const known = accounts.filter(({ kind }) => kind !== undefined);
232
- const unknown = accounts.filter(({ kind }) => kind === undefined);
233
+ const unknown = accounts.filter((one) => one.kind === undefined && !alsoFits(one));
233
234
  if (known.length)
234
235
  for (const { provider, account } of unknown)
235
236
  skipped.push({ source: `${provider}:${account}`, code: "not_found", reason: UNKNOWN_PROVIDER });
@@ -2,6 +2,7 @@ import type { LinkScorer } from "./types.js";
2
2
  /**
3
3
  * A person who wrote 5 or more messages in the window in one of the project's confirmed chats, or any in a dialog or a
4
4
  * group of 10 people or fewer, found by the sender's identity, never by the name a message shows. In a group of more
5
- * than 30 people writing there says less.
5
+ * than 30 people writing there says less. The reason names the chat and its size, and the evidence leads with the chat,
6
+ * so the owner can find and decide one group's senders together (`memo review list via:<chat>`).
6
7
  */
7
8
  export declare const chatSenders: LinkScorer;
@@ -6,14 +6,22 @@ const LARGE_GROUP = 30;
6
6
  const SMALL_CHAT = 10;
7
7
  const MIN_MESSAGES = 5;
8
8
  const READ_LIMIT = 2000;
9
+ const TITLE_WIDTH = 60;
10
+ const named = (title, chat) => {
11
+ const flat = (title ?? "").replace(/\s+/gu, " ").trim();
12
+ if (!flat)
13
+ return chat;
14
+ return `«${flat.length > TITLE_WIDTH ? `${flat.slice(0, TITLE_WIDTH - 1)}…` : flat}»`;
15
+ };
9
16
  /**
10
17
  * A person who wrote 5 or more messages in the window in one of the project's confirmed chats, or any in a dialog or a
11
18
  * group of 10 people or fewer, found by the sender's identity, never by the name a message shows. In a group of more
12
- * than 30 people writing there says less.
19
+ * than 30 people writing there says less. The reason names the chat and its size, and the evidence leads with the chat,
20
+ * so the owner can find and decide one group's senders together (`memo review list via:<chat>`).
13
21
  */
14
22
  export const chatSenders = {
15
23
  id: "chat-senders",
16
- version: 2,
24
+ version: 3,
17
25
  spreads: true,
18
26
  candidates: async ({ store, project, confirmed, sources, since, owner, signal }) => {
19
27
  if (!project)
@@ -37,6 +45,7 @@ export const chatSenders = {
37
45
  }
38
46
  const size = Math.max((await store.roster.members(key, reference.chat)).length, senders.size);
39
47
  const weight = size > LARGE_GROUP ? LARGE_GROUP_WEIGHT : WEIGHT;
48
+ const where = named(await store.chats.chatTitle(key, reference.chat), chat);
40
49
  for (const [id, { count, last }] of senders) {
41
50
  if (size > SMALL_CHAT && count < MIN_MESSAGES)
42
51
  continue;
@@ -48,8 +57,8 @@ export const chatSenders = {
48
57
  to: project.ref,
49
58
  kind: "member-of",
50
59
  weight,
51
- why: `${count} messages since ${since.slice(0, 10)} in a project chat (${chat})${size > LARGE_GROUP ? `, a group of ${size}` : ""}`,
52
- evidence: [formatReference({ ...reference, type: "message", message: last })],
60
+ why: `wrote ${count} message${count === 1 ? "" : "s"} in ${where} (${size} people) since ${since.slice(0, 10)}`,
61
+ evidence: [chat, formatReference({ ...reference, type: "message", message: last })],
53
62
  identity: contactRef(key.provider, id),
54
63
  });
55
64
  }
@@ -10,7 +10,7 @@ export interface LinkCandidate {
10
10
  kind: "member-of" | "related-to";
11
11
  /** 0..1. */
12
12
  weight: number;
13
- /** Ids and counts only, never message text. */
13
+ /** Ids, counts and at most a chat's title, never message text. */
14
14
  why: string;
15
15
  evidence: string[];
16
16
  /**
@@ -14,12 +14,12 @@ export declare const metadataService: (deps: ServiceDeps) => {
14
14
  dryRun?: boolean;
15
15
  }) => Promise<{
16
16
  items: ({
17
+ error?: undefined;
17
18
  chatId: string;
18
19
  tags: import("../domain/channel-tags.js").ChannelTagMatch[];
19
20
  algorithm: string;
20
21
  fetchedAt: string | null;
21
22
  source: string;
22
- error?: undefined;
23
23
  } | {
24
24
  tags?: undefined;
25
25
  algorithm?: undefined;
@@ -65,6 +65,7 @@ export const relationshipKind = (store) => {
65
65
  kinds: ["relationship"],
66
66
  ...(status === undefined ? {} : { status }),
67
67
  ...pushed(filter),
68
+ ...(filter.via === undefined ? {} : { evidence: filter.via }),
68
69
  });
69
70
  const links = (filter.status ?? "proposed") === "rejected" ? [] : await legacy();
70
71
  return kept([...stored.map(storedRow), ...links.map(linkRow)], filter);
@@ -60,7 +60,9 @@ export const emptyProposalRegistry = (store) => {
60
60
  throw new CliError("validation_error", "a proposal list takes a nonnegative offset");
61
61
  const asked = filter.kinds === undefined ? kinds : kinds.filter((kind) => filter.kinds?.includes(kind.kind));
62
62
  const wide = { ...filter, offset: 0, limit: filter.offset + filter.limit + 1 };
63
- const rows = (await Promise.all(asked.map(async (kind) => (await kind.list(wide)).map((row) => marked(kind, row))))).flat();
63
+ const rows = (await Promise.all(asked.map(async (kind) => (await kind.list(wide)).map((row) => marked(kind, row)))))
64
+ .flat()
65
+ .filter((row) => filter.via === undefined || row.evidence.includes(filter.via));
64
66
  rows.sort((a, b) => b.createdAt.localeCompare(a.createdAt) || b.id.localeCompare(a.id));
65
67
  const page = rows.slice(filter.offset, filter.offset + filter.limit + 1);
66
68
  return { items: page.slice(0, filter.limit), hasMore: page.length > filter.limit };
@@ -38,6 +38,8 @@ export interface ProposalFilter {
38
38
  bot: string;
39
39
  };
40
40
  status?: ProposalRow["status"] | "all";
41
+ /** A reference among the proposal's evidence, such as the chat a scan found a group's senders in. */
42
+ via?: string;
41
43
  limit: number;
42
44
  offset: number;
43
45
  }
@@ -0,0 +1,18 @@
1
+ import { type AccountKey, type MessageStore } from "../store/store.js";
2
+ import type { SearchAllItem } from "./search-all.js";
3
+ /** The account a hit of the owner's own invoice, product or wallet names: no import made it. */
4
+ export declare const OWN_BUSINESS: AccountKey;
5
+ export declare const BUSINESS_WORDS_ONLY: string;
6
+ export interface BusinessLane {
7
+ items: SearchAllItem[];
8
+ hasMore: boolean;
9
+ /** Every account read. */
10
+ read: AccountKey[];
11
+ }
12
+ /** The `business` lane: numbers and names folded in memory, each hit titled as its ref reads everywhere else. */
13
+ export declare const searchBusiness: (store: MessageStore, { words, anyWord, window, accounts, }: {
14
+ words: string[];
15
+ anyWord: boolean;
16
+ window: number;
17
+ accounts: AccountKey[] | undefined;
18
+ }) => Promise<BusinessLane>;
@@ -0,0 +1,38 @@
1
+ import { INTERNAL_NOTES } from "../domain/providers.js";
2
+ import { BUSINESS_FIND_MAX } from "../store/store.js";
3
+ /** The account a hit of the owner's own invoice, product or wallet names: no import made it. */
4
+ export const OWN_BUSINESS = { provider: "business", account: INTERNAL_NOTES };
5
+ export const BUSINESS_WORDS_ONLY = "invoices, payments, orders, contracts, subscriptions, products and wallets are found by the words of their " +
6
+ "numbers and names only";
7
+ /**
8
+ * A hit's account is its source record's. An imported row whose records all moved to other entities keeps its import
9
+ * provider with no account, so it is never taken for the owner's own.
10
+ */
11
+ const placeOf = ({ source, imported }) => source ?? (imported === undefined ? OWN_BUSINESS : { provider: imported, account: "" });
12
+ /** The `business` lane: numbers and names folded in memory, each hit titled as its ref reads everywhere else. */
13
+ export const searchBusiness = async (store, { words, anyWord, window, accounts, }) => {
14
+ const asked = Math.min(window + 1, BUSINESS_FIND_MAX);
15
+ const found = await store.business.find({
16
+ words,
17
+ anyWord,
18
+ limit: asked,
19
+ ...(accounts === undefined ? {} : { accounts }),
20
+ });
21
+ const page = found.slice(0, window);
22
+ const titles = await store.refs.summaries(page.map(({ ref }) => ref));
23
+ return {
24
+ items: page.map((hit) => ({
25
+ kind: hit.kind,
26
+ ref: hit.ref,
27
+ ...placeOf(hit),
28
+ title: titles.get(hit.ref)?.title ?? null,
29
+ timestamp: new Date(hit.updatedAt).toISOString(),
30
+ text: hit.text,
31
+ review: hit.review,
32
+ ...(hit.source === undefined ? {} : { sourceRecord: hit.source }),
33
+ foundBy: ["title"],
34
+ })),
35
+ hasMore: found.length > window || (asked < window + 1 && found.length === asked),
36
+ read: accounts ?? [...(await store.business.accounts()), OWN_BUSINESS],
37
+ };
38
+ };
@@ -3,7 +3,7 @@ import type { AccountKey, MessageStore } from "../store/store.js";
3
3
  import type { SearchFound, SearchQuery } from "./messages.js";
4
4
  import type { MeaningLane } from "./messages-discovery.js";
5
5
  import { type SearchAllFound, type SearchAllItem, type SearchAllMessenger, type SearchAllRequest, type Skipped } from "./search-all.js";
6
- export declare const RESOURCES_SEARCHED_WITH_MEETINGS: readonly ["messages", "mail", "notes", "events", "crm", "meetings"];
6
+ export declare const RESOURCES_SEARCHED_WITH_MEETINGS: readonly ["messages", "mail", "notes", "events", "crm", "business", "meetings"];
7
7
  export type ResourceWithMeetings = (typeof RESOURCES_SEARCHED_WITH_MEETINGS)[number];
8
8
  export interface MeetingSearchItem {
9
9
  kind: "meeting";
@@ -243,14 +243,18 @@ const holdingMeetings = async (store, named) => {
243
243
  }
244
244
  return holding.length ? holding : named;
245
245
  };
246
+ const keyOf = ({ provider, account }) => `${provider}\u0000${account}`;
246
247
  const searchAllOfSource = async (store, account, source, request, messenger, searchMessages, meaning) => {
247
248
  const only = request.only ?? RESOURCES_SEARCHED_WITH_MEETINGS;
248
249
  const entries = entriesOfList(source, await listContextOf(store, account, messenger.app));
249
- const { skipped } = fitting(entries, only, "search all", (kind) => `--only leaves ${kind} out`);
250
+ // Any provider's import may write business data, so its accounts are the ones that hold some, whatever their kind.
251
+ const imported = only.includes("business") ? new Set((await store.business.accounts()).map(keyOf)) : new Set();
252
+ const holdsBusiness = (one) => imported.has(keyOf(one));
253
+ const { skipped } = fitting(entries, only.filter((one) => one !== "business"), "search all", (kind) => `--only leaves ${kind} out`, holdsBusiness);
250
254
  const named = (resource) => [
251
255
  ...new Map(entries
252
256
  .flatMap(({ accounts }) => accounts)
253
- .filter((one) => listedHolds(one, resource))
257
+ .filter((one) => (resource === "business" ? holdsBusiness(one) : listedHolds(one, resource)))
254
258
  .map(({ provider, account }) => [`${provider}\u0000${account}`, { provider, account }])).values(),
255
259
  ];
256
260
  const meetings = await holdingMeetings(store, named("meetings"));
@@ -275,6 +279,7 @@ const searchAllOfSource = async (store, account, source, request, messenger, sea
275
279
  notes: named("notes"),
276
280
  events: named("events"),
277
281
  crm: named("crm"),
282
+ business: named("business"),
278
283
  },
279
284
  ...(meetings[0] ? { meetingAccount: meetings[0] } : {}),
280
285
  }, messenger, searchMessages, meaning);
@@ -3,16 +3,16 @@ import { type HitFile } from "../domain/attachments.js";
3
3
  import type { DealKind } from "../domain/deals.js";
4
4
  import { type MailFields } from "../domain/models.js";
5
5
  import type { MessengerTraits } from "../ports/traits.js";
6
- import type { AccountKey, MessageStore } from "../store/store.js";
6
+ import type { AccountKey, BusinessKind, BusinessSource, MessageStore } from "../store/store.js";
7
7
  import type { SearchFound, SearchQuery } from "./messages.js";
8
8
  import { type MeaningLane, type MeaningSkipped } from "./messages-discovery.js";
9
9
  import type { SearchCoverage } from "./messages-search.js";
10
10
  import type { Backend, ServerOptions, ServerSearched } from "./server-search.js";
11
- export declare const RESOURCES_SEARCHED: readonly ["messages", "mail", "notes", "events", "crm"];
11
+ export declare const RESOURCES_SEARCHED: readonly ["messages", "mail", "notes", "events", "crm", "business"];
12
12
  export type SearchedResource = (typeof RESOURCES_SEARCHED)[number];
13
13
  export interface SearchAllItem {
14
- kind: "message" | "mail" | "note" | "document" | "event" | "deal" | "lead";
15
- /** `msg:…` for a message or a mail, `note:…` for a note, `event:…` for a calendar event, `deal:…`, `lead:…`. */
14
+ kind: "message" | "mail" | "note" | "document" | "event" | "deal" | "lead" | BusinessKind;
15
+ /** `msg:…` for a message or a mail, `note:…`, `event:…`, `deal:…`, `lead:…`, or a business ref: `invoice:…`. */
16
16
  ref: string;
17
17
  provider: string;
18
18
  /** The account it was found in; a note's folder id, or `internal` for a note written in memo. */
@@ -36,6 +36,10 @@ export interface SearchAllItem {
36
36
  attachments?: HitFile[];
37
37
  /** Which search found it: words, meaning or both. */
38
38
  foundBy: ("title" | "words" | "meaning")[];
39
+ /** A business hit's: whether the owner confirmed it, or it waits for him. */
40
+ review?: "proposed" | "confirmed";
41
+ /** A business hit's source record, when an import made it. */
42
+ sourceRecord?: BusinessSource;
39
43
  }
40
44
  /** One account a search read, by the kind it was read for: the shape memo's `search all` answers too. */
41
45
  export interface SearchedAccount {
@@ -127,14 +131,14 @@ export type SearchAllMessenger = Partial<Pick<MessengerTraits, "savedChatId" | "
127
131
  * 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
128
132
  * refused, so `search all` skips deals with the reason instead of matching a field they do not have.
129
133
  */
130
- export declare const titleWords: (text: string) => {
134
+ export declare const titleWords: (text: string, refused?: string) => {
131
135
  words: string[];
132
136
  anyWord: boolean;
133
137
  };
134
138
  /** The accounts of every CRM the store holds copies of. */
135
139
  export declare const crmAccounts: (store: MessageStore) => Promise<AccountKey[]>;
136
140
  /**
137
- * `search all`: messages, mail, notes, calendar events and CRM deals and leads from the local store — messages also from the messenger's
141
+ * `search all`: messages, mail, notes, calendar events, CRM deals and leads, and business data from the local store — messages also from the messenger's
138
142
  * server, as `search messages` asks it — each list best first, merged by reciprocal rank so no
139
143
  * resource's own scores have to be compared with another's. Events are read only when the store holds a calendar.
140
144
  */
@@ -14,7 +14,8 @@ import { excerpt } from "./excerpt.js";
14
14
  import { MAX_SEARCH_OFFSET, searchStore } from "./messages-archive-search.js";
15
15
  import { nearEligible } from "./messages-discovery.js";
16
16
  import { notesScopeOf, RRF_K, searchNotes } from "./notes-search.js";
17
- export const RESOURCES_SEARCHED = ["messages", "mail", "notes", "events", "crm"];
17
+ import { BUSINESS_WORDS_ONLY, searchBusiness } from "./search-all-business.js";
18
+ export const RESOURCES_SEARCHED = ["messages", "mail", "notes", "events", "crm", "business"];
18
19
  const refusal = (error, text) => {
19
20
  const { reason, span } = (error.details ?? {});
20
21
  const why = typeof reason === "string" ? reason : undefined;
@@ -43,7 +44,7 @@ const filtersBeside = (text) => {
43
44
  * 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
44
45
  * refused, so `search all` skips deals with the reason instead of matching a field they do not have.
45
46
  */
46
- export const titleWords = (text) => {
47
+ export const titleWords = (text, refused = "deals and leads are found by the words of their title only") => {
47
48
  const { root } = parseLucene(text, SEARCH_QUERY);
48
49
  const clauses = root.kind === "boolean" ? root.clauses : [{ node: root, occur: "must" }];
49
50
  const words = clauses.map(({ node, occur }) => occur !== "must_not" &&
@@ -53,7 +54,7 @@ export const titleWords = (text) => {
53
54
  ? // A title holds "invoice", not the question mark of "invoice?".
54
55
  node.value.replace(/\?+$/u, "") || node.value
55
56
  : (() => {
56
- throw new CliError("validation_error", "deals and leads are found by the words of their title only");
57
+ throw new CliError("validation_error", refused);
57
58
  })());
58
59
  return { words, anyWord: clauses.length > 1 && clauses.every(({ occur }) => occur === "should") };
59
60
  };
@@ -73,7 +74,7 @@ const strictWords = (text) => {
73
74
  /** The accounts of every CRM the store holds copies of. */
74
75
  export const crmAccounts = async (store) => (await store.accounts.accounts()).filter(({ provider }) => holdsKind(provider, "crm"));
75
76
  /**
76
- * `search all`: messages, mail, notes, calendar events and CRM deals and leads from the local store — messages also from the messenger's
77
+ * `search all`: messages, mail, notes, calendar events, CRM deals and leads, and business data from the local store — messages also from the messenger's
77
78
  * server, as `search messages` asks it — each list best first, merged by reciprocal rank so no
78
79
  * resource's own scores have to be compared with another's. Events are read only when the store holds a calendar.
79
80
  */
@@ -300,6 +301,19 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
300
301
  for (const { provider, account } of read)
301
302
  accounts.push({ resource, provider, account });
302
303
  }
304
+ else if (resource === "business") {
305
+ const { words, anyWord } = titleWords(request.text, BUSINESS_WORDS_ONLY);
306
+ const found = await searchBusiness(store, {
307
+ words,
308
+ anyWord: anyWord || discover,
309
+ window,
310
+ accounts: request.scope?.business,
311
+ });
312
+ hasMore ||= found.hasMore;
313
+ lists.push(found.items);
314
+ for (const { provider, account } of found.read)
315
+ accounts.push({ resource, provider, account });
316
+ }
303
317
  else
304
318
  lists.push(await messagesOf(resource));
305
319
  searched.push(resource);
@@ -1,3 +1,4 @@
1
+ export { BUSINESS_KINDS, type BusinessKind } from "../domain/business.js";
1
2
  export type { CounterField, CounterObservations, CounterState } from "../domain/counters.js";
2
3
  export type { RetentionOptions } from "../domain/retention.js";
3
4
  export type { AccountAccounts, AccountsStore } from "./accounts.js";
@@ -17,6 +18,7 @@ export { accountGroupsOf } from "./sqlite/account-groups.js";
17
18
  export type { AdminStoreRequest, AdminStoreResult } from "./sqlite/admin-statistics.js";
18
19
  export { type AttachmentTextEntry, type AttachmentView, attachmentColumns, type FileAttachment, resetAttachmentWords, type TextOrigin, } from "./sqlite/attachment-texts.js";
19
20
  export { pendingNormalization } from "./sqlite/backfill.js";
21
+ export { BUSINESS_FIND_MAX, type BusinessHit, type BusinessSearch, type BusinessSearchStore, type BusinessSource, } from "./sqlite/business-search.js";
20
22
  export type { ChatRekey, ChatRekeys } from "./sqlite/chat-rekey.js";
21
23
  export { CHAT_COLUMNS, TRACKED_CHAT_COLUMNS, titlePart } from "./sqlite/chats.js";
22
24
  export { storeClients } from "./sqlite/clients.js";