@wirecat/cli-core 0.750.0 → 0.752.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/dist/cli/messenger/backfill-command.js +3 -1
  3. package/dist/crm/cli/index.js +1 -1
  4. package/dist/crm/source.d.ts +5 -0
  5. package/dist/crm/sync.d.ts +3 -1
  6. package/dist/crm/sync.js +31 -3
  7. package/dist/domain/addresses.d.ts +8 -3
  8. package/dist/domain/addresses.js +24 -6
  9. package/dist/domain/person-kinds.d.ts +1 -1
  10. package/dist/errors/reasons.js +2 -0
  11. package/dist/mail/email-input.d.ts +1 -1
  12. package/dist/mail/email-input.js +3 -2
  13. package/dist/mail/folders.d.ts +6 -1
  14. package/dist/mail/folders.js +10 -5
  15. package/dist/mail/own.d.ts +15 -0
  16. package/dist/mail/own.js +35 -0
  17. package/dist/mail/partial.js +4 -1
  18. package/dist/mail/server-search.js +3 -1
  19. package/dist/mail/source.d.ts +5 -1
  20. package/dist/mail/sync-types.d.ts +2 -0
  21. package/dist/mail/sync.js +16 -4
  22. package/dist/mail/testing/fake.d.ts +4 -0
  23. package/dist/mail/testing/fake.js +3 -1
  24. package/dist/mail/whole.js +3 -1
  25. package/dist/store/sqlite/crm-activities.d.ts +14 -0
  26. package/dist/store/sqlite/crm-activities.js +25 -1
  27. package/dist/store/sqlite/crm.d.ts +3 -5
  28. package/dist/store/sqlite/crm.js +2 -2
  29. package/dist/store/sqlite/email-state.d.ts +8 -0
  30. package/dist/store/sqlite/email-state.js +23 -0
  31. package/dist/store/sqlite/emails.d.ts +9 -0
  32. package/dist/store/sqlite/emails.js +2 -1
  33. package/dist/store/sqlite/own-identities.d.ts +2 -0
  34. package/dist/store/sqlite/own-identities.js +24 -1
  35. package/dist/store/sqlite/people-list.d.ts +7 -0
  36. package/dist/store/sqlite/people-list.js +4 -3
  37. package/dist/store/sqlite/person-match-scan.js +34 -4
  38. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -5,6 +5,47 @@ 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.752.0 — 25.11.2026
9
+
10
+ ### Added
11
+
12
+ - **A mail source names the IMAP Sent folder.** `MailSource.folders()` may answer `sent`: the folder the server marks
13
+ `\Sent` (RFC 6154), else one by a common name when the server marks none. `mailFolders` then reads `INBOX` and that
14
+ folder for `mode: "imap"`, and `MailAccount.addresses` takes the owner's other addresses on the mailbox, such as
15
+ aliases ([MAIL.md](docs/dev/MAIL.md#syncmailsource-store-options)).
16
+
17
+ ### Fixed
18
+
19
+ - **Mail the owner sent from an alias is outgoing, and the alias is the owner's.** Mail in Sent or under Gmail's `Sent`
20
+ label, and mail from one of the owner's addresses, counted as incoming when its From was not the account's address,
21
+ so the people the owner wrote to from an alias had no mail tie and showed as strangers. Now it is outgoing, mail stored
22
+ earlier is marked too, the senders of Sent mail are kept under `mail_own_addresses`, and their identities join the
23
+ owner when the account's own identity is the owner's. An IMAP adapter that answers `sent` gets the same for its Sent
24
+ folder.
25
+ - **`people.list` finds no-reply and notification senders by any part of the address.** `noreply-12345@`,
26
+ `service-noreply@` and `bank.no-reply@` are no-reply addresses now, and `notify@`, `alerts@` or `bank-notifications@`
27
+ make a sender `automated` (signal `notification-address`), so banks and service alerts no longer show under
28
+ strangers. `bounce` counts only as a whole part (`bounce-8812@`), so `bouncer.joe@` stays a person. Someone the owner
29
+ answers in a private chat stays a `person`. Every stored kind is worked out again on the next list.
30
+ - **The people scan never proposes a bot, an automated sender or an organization as the same person by name.** One
31
+ newsletter that sends from many `+tag` addresses under one name no longer fills the review with pairs. The next scan
32
+ deletes the open `name` proposals that name such a sender, and is a full pass once.
33
+ - **`messages sync <chat> --full-history --background` reads the chat in full.** The background job was started
34
+ without `--full-history`, so a group above `history_group_members_max` ended at once with `fetched: 0` and
35
+ `limited: "group_too_large"`, and its log asked for the flag that was given. The job now gets the flag, and
36
+ `store jobs retry` keeps it (tg-cli [#916](https://github.com/WireCatLabs/tg-cli/issues/916)).
37
+
38
+ ## 0.751.0 — 25.11.2026
39
+
40
+ ### Fixed
41
+
42
+ - **A note or task deleted in the CRM leaves the copy.** The sync kept every activity it had once stored. It now marks
43
+ deleted the ones a source's page names in `removed`. A source that lists every activity on each run sets
44
+ `listedAll` on its last page, and then a stored activity it did not list is marked deleted too, when the round was
45
+ read whole and no list was refused. A list that would mark most of ten or more is held with
46
+ `crm.activities-unlisted-held` until `sync --rescan`. `sync` counts them in `activities.removed`
47
+ ([CRM](docs/dev/CRM.md#activities-changes-and-the-digest)).
48
+
8
49
  ## 0.750.0 — 24.11.2026
9
50
 
10
51
  ### Added
@@ -148,6 +148,7 @@ export const syncCommand = (messenger) => {
148
148
  pageSize,
149
149
  pause,
150
150
  catchUp: prepare,
151
+ ...(include ? { fullHistory: true } : {}),
151
152
  ...(withMuted ? { withMuted } : {}),
152
153
  ...(catchUpChunks === undefined ? {} : { catchUpChunks }),
153
154
  ...(catchUpMessages === undefined ? {} : { catchUpMessages }),
@@ -402,7 +403,7 @@ const findJob = (messenger, context, id) => {
402
403
  }
403
404
  return job;
404
405
  };
405
- const fetchArgv = (command, { chat, limit, pageSize, pause, since, last, catchUp, withMuted, catchUpChunks, catchUpMessages, catchUpTime, }) => {
406
+ const fetchArgv = (command, { chat, limit, pageSize, pause, since, last, catchUp, fullHistory, withMuted, catchUpChunks, catchUpMessages, catchUpTime, }) => {
406
407
  const { timeout } = command.optsWithGlobals();
407
408
  return [
408
409
  "messages",
@@ -417,6 +418,7 @@ const fetchArgv = (command, { chat, limit, pageSize, pause, since, last, catchUp
417
418
  ...(since === undefined ? [] : ["--since-time", since]),
418
419
  ...(last === undefined ? [] : ["--last", String(last)]),
419
420
  ...(catchUp === undefined ? [] : [catchUp ? "--catch-up" : "--no-catch-up"]),
421
+ ...(fullHistory ? ["--full-history"] : []),
420
422
  ...(withMuted ? ["--with-muted"] : []),
421
423
  ...(catchUpChunks === undefined ? [] : ["--catch-up-chunks", String(catchUpChunks)]),
422
424
  ...(catchUpMessages === undefined ? [] : ["--catch-up-messages", String(catchUpMessages)]),
@@ -107,7 +107,7 @@ const crmSync = v.strictObject({
107
107
  skipped_owner_rejected: count,
108
108
  contacts_removed: v.optional(crmContactsRemoved),
109
109
  stage_tasks: count,
110
- activities: v.optional(v.strictObject({ saved: count, out_of_scope: count, state: v.picklist(["partial", "complete"]) })),
110
+ activities: v.optional(v.strictObject({ saved: count, out_of_scope: count, removed: count, state: v.picklist(["partial", "complete"]) })),
111
111
  synced: v.array(v.strictObject({
112
112
  kind: v.picklist(CRM_KINDS),
113
113
  round: v.picklist(["full", "changes"]),
@@ -20,6 +20,11 @@ export interface CrmPage<T> {
20
20
  nextCursor?: string;
21
21
  /** On the last page: the cursor the next run reads changes after; `null` when the CRM keeps none. */
22
22
  cursor?: string | null;
23
+ /**
24
+ * On the last page of activities: the round listed every one the CRM holds, whatever `since` asked (Attio's notes
25
+ * take no time filter), so one stored that it did not list was deleted.
26
+ */
27
+ listedAll?: boolean;
23
28
  }
24
29
  /** `reset`: the cursor is dead, and the CRM must be listed in full again. */
25
30
  export type CrmChanges<T> = CrmPage<T> | {
@@ -50,7 +50,7 @@ export interface CrmSyncOptions {
50
50
  export interface CrmSyncIssue {
51
51
  /** `user`: the account's users and departments. */
52
52
  kind: CrmKind | "user";
53
- reason: CrmSkipped["reason"] | CrmRelationIssue["reason"] | "crm.unlisted-held" | "crm.narrowing-held" | "crm.unassigned-dropped" | "crm.not-reported" | "crm.pending-dropped" | "crm.activities-failed" | "crm.stage-history-failed";
53
+ reason: CrmSkipped["reason"] | CrmRelationIssue["reason"] | "crm.unlisted-held" | "crm.narrowing-held" | "crm.unassigned-dropped" | "crm.not-reported" | "crm.pending-dropped" | "crm.activities-failed" | "crm.activities-unlisted-held" | "crm.stage-history-failed";
54
54
  message: string;
55
55
  externalId?: string;
56
56
  }
@@ -107,6 +107,8 @@ export interface CrmSyncReport {
107
107
  activities?: {
108
108
  saved: number;
109
109
  outOfScope: number;
110
+ /** Ones the CRM said it deleted, or a full list no longer named, now marked deleted. */
111
+ removed: number;
110
112
  state: "partial" | "complete";
111
113
  };
112
114
  hint?: string;
package/dist/crm/sync.js CHANGED
@@ -169,18 +169,40 @@ const activityCursor = (value) => {
169
169
  return undefined;
170
170
  }
171
171
  };
172
+ /** As the id pass of a kind does, a list that would mark most of the stored activities deleted is held. */
173
+ const removeUnlistedActivities = async (run, options, seen) => {
174
+ const { store, account, source } = run;
175
+ const { stored, unlisted } = await store.crm.removeUnlistedActivities(account, seen, { dryRun: true });
176
+ if (unlisted === 0)
177
+ return;
178
+ if (!options.rescan && (seen.length === 0 || (stored >= GUARDED_FROM && unlisted > stored * MOST_UNLISTED))) {
179
+ run.report.issues.push({
180
+ kind: "deal",
181
+ reason: "crm.activities-unlisted-held",
182
+ message: `${source.provider} listed ${seen.length} activities, so ${unlisted} of the ${stored} stored would be marked ` +
183
+ "deleted; nothing was — check the sign-in's rights, then run sync --rescan to let it through",
184
+ });
185
+ return;
186
+ }
187
+ const done = await store.crm.removeUnlistedActivities(account, seen);
188
+ if (run.report.activities)
189
+ run.report.activities.removed += done.unlisted;
190
+ };
172
191
  /**
173
192
  * Activities and tasks changed since the last read, after every deal and lead of the run is stored: each is kept only
174
193
  * on the deals and leads this copy holds. Pages go on from where a stopped run left them.
175
194
  */
176
- const readActivities = async (run) => {
195
+ const readActivities = async (run, options) => {
177
196
  const { source, store, account } = run;
178
197
  if (!source.activities || !(await store.crm.activitiesOn(account)))
179
198
  return null;
180
- const read = { saved: 0, outOfScope: 0, state: "partial" };
199
+ const read = { saved: 0, outOfScope: 0, removed: 0, state: "partial" };
181
200
  run.report.activities = read;
182
201
  const saved = activityCursor((await store.sync.syncState(account, ACTIVITIES))?.value);
183
202
  const cursor = saved ?? { since: run.now - ACTIVITY_DAYS * DAY, newest: 0 };
203
+ // Only a round read whole in this run, with no list refused, may show what was deleted: a resumed one lost its start.
204
+ const seen = cursor.page === undefined ? new Set() : undefined;
205
+ const gaps = run.gaps.length;
184
206
  for (;;) {
185
207
  const why = run.budget.take();
186
208
  if (why)
@@ -200,6 +222,10 @@ const readActivities = async (run) => {
200
222
  const done = await store.crm.saveActivities(account, page.items);
201
223
  read.saved += done.saved;
202
224
  read.outOfScope += done.outOfScope;
225
+ if (page.removed?.length)
226
+ read.removed += await store.crm.removeActivities(account, page.removed);
227
+ for (const one of page.items)
228
+ seen?.add(one.externalId);
203
229
  cursor.newest = Math.max(cursor.newest, ...page.items.map((one) => one.updatedAt));
204
230
  run.moved();
205
231
  if (page.hasMore && page.nextCursor !== undefined) {
@@ -209,6 +235,8 @@ const readActivities = async (run) => {
209
235
  return "cancelled";
210
236
  continue;
211
237
  }
238
+ if (page.listedAll && seen && run.gaps.length === gaps)
239
+ await removeUnlistedActivities(run, options, [...seen]);
212
240
  const next = page.cursor != null ? Number(page.cursor) : cursor.newest || cursor.since;
213
241
  await store.sync.setSyncState(account, ACTIVITIES, JSON.stringify({ since: next, newest: 0 }));
214
242
  read.state = "complete";
@@ -635,7 +663,7 @@ export const syncCrm = async (source, store, account, options = {}) => {
635
663
  const rowsStopped = stopped;
636
664
  if (!stopped && kinds.some(isItemKind)) {
637
665
  try {
638
- stopped = await stopping(() => readActivities(run));
666
+ stopped = await stopping(() => readActivities(run, options));
639
667
  }
640
668
  catch (error) {
641
669
  if (options.signal?.aborted)
@@ -7,9 +7,14 @@ export declare const ROLE_ADDRESS_WORDS: {
7
7
  readonly noReply: readonly ["noreply", "no-reply", "donotreply", "do-not-reply", "mailer-daemon", "bounce", "bounces"];
8
8
  readonly shared: readonly ["info", "hello", "hi", "contact", "contacts", "support", "help", "helpdesk", "service", "sales", "office", "admin", "team", "billing", "accounts", "accounting", "invoices", "finance", "hr", "jobs", "careers", "press", "media", "marketing", "partners", "legal", "privacy", "security", "abuse", "postmaster", "webmaster", "mail", "inbox", "enquiries", "inquiries", "booking", "reservations", "orders", "feedback", "newsletter", "notifications", "alerts"];
9
9
  };
10
- /** Whether the whole local part, `+tag` and `.`/`-`/`_` aside, is a role word: `info@`, `Hello+news@`, `no_reply@`. */
10
+ /** Whether the address is a no-reply one, which belongs to no person: `noreply-12345@`, `service.no-reply@`. */
11
+ export declare const isNoReplyAddress: (address: string) => boolean;
12
+ /**
13
+ * Whether the whole local part, `+tag` and `.`/`-`/`_` aside, is a role word (`info@`, `Hello+news@`, `no_reply@`),
14
+ * or the address is a no-reply one.
15
+ */
11
16
  export declare const isRoleAddress: (address: string) => boolean;
12
17
  /** Whether the address is a role address that one person often reads alone, such as `hr@`. */
13
18
  export declare const isPersonLikeRoleAddress: (address: string) => boolean;
14
- /** Whether the address is a no-reply one, which belongs to no person. */
15
- export declare const isNoReplyAddress: (address: string) => boolean;
19
+ /** Whether a program sends from the address: `notify@`, `alerts@`, `bank-notifications@`. */
20
+ export declare const isNotificationAddress: (address: string) => boolean;
@@ -53,12 +53,30 @@ export const ROLE_ADDRESS_WORDS = {
53
53
  const bare = (word) => word.replace(/[.\-_]/gu, "");
54
54
  const NO_REPLY = new Set(ROLE_ADDRESS_WORDS.noReply.map(bare));
55
55
  const ROLE = new Set([...ROLE_ADDRESS_WORDS.shared, ...ROLE_ADDRESS_WORDS.noReply].map(bare));
56
- const localWord = (address) => {
56
+ /** Words people's names start with too (`bouncer.joe@`), so they count only as a whole part of the address. */
57
+ const PART_ONLY = new Set(["bounce", "bounces"]);
58
+ const NOTIFY = new Set(["notify", "notification", "notifications", "alert", "alerts"]);
59
+ const localPart = (address) => {
57
60
  const local = address.trim().toLowerCase().split("@")[0] ?? "";
58
- return bare(local.split("+")[0] ?? "");
61
+ return local.split("+")[0] ?? "";
59
62
  };
60
- /** Whether the whole local part, `+tag` and `.`/`-`/`_` aside, is a role word: `info@`, `Hello+news@`, `no_reply@`. */
61
- export const isRoleAddress = (address) => ROLE.has(localWord(address));
63
+ const localWord = (address) => bare(localPart(address));
64
+ const SEPARATORS = /[.\-_]/u;
65
+ const partsOf = (address) => localPart(address).split(SEPARATORS);
66
+ const NO_REPLY_PARTS = ROLE_ADDRESS_WORDS.noReply.map((word) => `.${word.split(SEPARATORS).join(".")}.`);
67
+ /** Whether the address is a no-reply one, which belongs to no person: `noreply-12345@`, `service.no-reply@`. */
68
+ export const isNoReplyAddress = (address) => {
69
+ const word = localWord(address);
70
+ const parts = `.${partsOf(address).join(".")}.`;
71
+ if (NO_REPLY_PARTS.some((one) => parts.includes(one)))
72
+ return true;
73
+ return [...NO_REPLY].some((one) => !PART_ONLY.has(one) && (word.startsWith(one) || word.endsWith(one)));
74
+ };
75
+ /**
76
+ * Whether the whole local part, `+tag` and `.`/`-`/`_` aside, is a role word (`info@`, `Hello+news@`, `no_reply@`),
77
+ * or the address is a no-reply one.
78
+ */
79
+ export const isRoleAddress = (address) => ROLE.has(localWord(address)) || isNoReplyAddress(address);
62
80
  /**
63
81
  * Role words that one person often reads alone: a small company's `hr@` is its HR manager. Still a role address, so it
64
82
  * joins no one, but weaker evidence of a company's mailbox than `info@`, and it never makes a contact a company.
@@ -66,5 +84,5 @@ export const isRoleAddress = (address) => ROLE.has(localWord(address));
66
84
  const PERSON_LIKE = new Set(["hr"]);
67
85
  /** Whether the address is a role address that one person often reads alone, such as `hr@`. */
68
86
  export const isPersonLikeRoleAddress = (address) => PERSON_LIKE.has(localWord(address));
69
- /** Whether the address is a no-reply one, which belongs to no person. */
70
- export const isNoReplyAddress = (address) => NO_REPLY.has(localWord(address));
87
+ /** Whether a program sends from the address: `notify@`, `alerts@`, `bank-notifications@`. */
88
+ export const isNotificationAddress = (address) => partsOf(address).some((part) => NOTIFY.has(part));
@@ -5,7 +5,7 @@
5
5
  export declare const PERSON_KINDS: readonly ["person", "organization", "automated", "stranger", "unsorted", "test"];
6
6
  export type PersonKind = (typeof PERSON_KINDS)[number];
7
7
  /** What decided a kind, besides the ties that make someone a `person`. */
8
- export type KindSignal = "test-data" | "bot" | "no-reply" | "bulk-mail" | "bulk-never-replied" | "automated-name" | "organization" | "role-address" | "company-name" | "no-tie" | "no-name";
8
+ export type KindSignal = "test-data" | "bot" | "no-reply" | "notification-address" | "bulk-mail" | "bulk-never-replied" | "automated-name" | "organization" | "role-address" | "company-name" | "no-tie" | "no-name";
9
9
  /** A sender that is a program: «Notifications», «Рассылка», «no-reply». */
10
10
  export declare const isAutomatedName: (name: string | null) => boolean;
11
11
  /** A legal form or a word only a business calls itself: «ООО Ромашка», «CZECH AIRLINES», «OpenWeather Team». */
@@ -599,6 +599,7 @@ const OTHERS = [
599
599
  validation("crm.reference-unknown", "a CRM row names a contact, company or user the store does not hold; that link was not made"),
600
600
  validation("crm.pending-dropped", "relationships waited too long for an end that never came; they were dropped"),
601
601
  validation("crm.activities-failed", "the activities and tasks could not be read; the deals and leads were synced"),
602
+ validation("crm.activities-unlisted-held", "a full list would mark most activities deleted; held until --rescan"),
602
603
  validation("crm.stage-history-failed", "the CRM's stage history could not be read; stage tasks wait for the next sync"),
603
604
  validation("crm.email-ambiguous", "a CRM contact's email belongs to more than one person; the owner decides"),
604
605
  validation("crm.own-unknown", "no own company of the CRM account is stored, so its users are no one's employees yet"),
@@ -688,6 +689,7 @@ const OTHERS = [
688
689
  validation("organization.ambiguous", "more than one organization matches; name the one meant as a reference"),
689
690
  validation("identity.shared-phone", "more than six people share the phone number, so it proposes no one"),
690
691
  validation("identity.common-name", "more than six people have the name, so it proposes no one"),
692
+ validation("identity.not-a-person", "a bot, a program or an organization is never proposed as a person by name"),
691
693
  validation("identity.owner", "one side is the owner's person, and only the owner joins anyone to themselves"),
692
694
  validation("identity.shared-email", "more than six people share the address, so it proposes no one"),
693
695
  validation("identity-link.dedicated-review", "an identity link is staged and decided through the people review"),
@@ -4,4 +4,4 @@ import type { Listed } from "./source.js";
4
4
  /** The Date header, or the server's internal date when the header is missing or unreadable. */
5
5
  export declare const sentAtOf: (date: string | null, receivedAt: string) => number;
6
6
  /** What one read email stores of itself, whichever run read it; where it is filed is the caller's. */
7
- export declare const parsedEmail: (mail: ParsedMail, item: Listed, header: Record<string, string | boolean>, address: string) => Omit<EmailInput, "mailboxes">;
7
+ export declare const parsedEmail: (mail: ParsedMail, item: Listed, header: Record<string, string | boolean>, own: ReadonlySet<string>, inSent?: boolean) => Omit<EmailInput, "mailboxes">;
@@ -1,11 +1,12 @@
1
1
  import { addressOf } from "./attachments.js";
2
+ import { sentByOwner } from "./own.js";
2
3
  /** The Date header, or the server's internal date when the header is missing or unreadable. */
3
4
  export const sentAtOf = (date, receivedAt) => {
4
5
  const sent = date === null ? Number.NaN : Date.parse(date);
5
6
  return Number.isNaN(sent) ? Date.parse(receivedAt) : sent;
6
7
  };
7
8
  /** What one read email stores of itself, whichever run read it; where it is filed is the caller's. */
8
- export const parsedEmail = (mail, item, header, address) => ({
9
+ export const parsedEmail = (mail, item, header, own, inSent = false) => ({
9
10
  externalId: item.messageId,
10
11
  subject: mail.subject,
11
12
  from: mail.from === null ? null : addressOf(mail.from),
@@ -17,5 +18,5 @@ export const parsedEmail = (mail, item, header, address) => ({
17
18
  bodyText: mail.text || null,
18
19
  size: item.size ?? null,
19
20
  ...(Object.keys(header).length ? { headers: header } : {}),
20
- outgoing: mail.from === null ? null : mail.from.email === address,
21
+ outgoing: sentByOwner(mail.from?.email, own, inSent),
21
22
  });
@@ -1,8 +1,13 @@
1
1
  import type { MailSource } from "./source.js";
2
2
  export declare const GMAIL_ALL_MAIL = "[Gmail]/All Mail";
3
+ /** The IMAP folder of mail the owner sent, as the source names it; Gmail's sent mail is in All Mail. */
4
+ export declare const sentFolder: (account: {
5
+ mode?: string;
6
+ }, source?: Pick<MailSource, "folders">) => Promise<string | undefined>;
3
7
  /**
4
8
  * The folders to read. Gmail names All Mail in the account's language, so it is found by its role; a source that
5
- * cannot say, or a listing without it, falls back to the English name and the read reports a missing folder.
9
+ * cannot say, or a listing without it, falls back to the English name and the read reports a missing folder. IMAP
10
+ * reads INBOX and the Sent folder, since a contact's tie is mail the owner wrote.
6
11
  */
7
12
  export declare const mailFolders: (account: {
8
13
  mode?: string;
@@ -1,13 +1,18 @@
1
1
  export const GMAIL_ALL_MAIL = "[Gmail]/All Mail";
2
+ const listedFolders = (source) => source?.folders?.().then((found) => found, () => undefined);
3
+ /** The IMAP folder of mail the owner sent, as the source names it; Gmail's sent mail is in All Mail. */
4
+ export const sentFolder = async (account, source) => (account.mode === "imap" ? (await listedFolders(source))?.sent : undefined);
2
5
  /**
3
6
  * The folders to read. Gmail names All Mail in the account's language, so it is found by its role; a source that
4
- * cannot say, or a listing without it, falls back to the English name and the read reports a missing folder.
7
+ * cannot say, or a listing without it, falls back to the English name and the read reports a missing folder. IMAP
8
+ * reads INBOX and the Sent folder, since a contact's tie is mail the owner wrote.
5
9
  */
6
10
  export const mailFolders = async (account, source) => {
7
11
  if (account.folders)
8
12
  return account.folders;
9
- if (account.mode === "imap")
10
- return ["INBOX"];
11
- const all = await source?.folders?.().then(({ all }) => all, () => undefined);
12
- return [all ?? GMAIL_ALL_MAIL];
13
+ if (account.mode === "imap") {
14
+ const sent = await sentFolder(account, source);
15
+ return sent === undefined || sent === "INBOX" ? ["INBOX"] : ["INBOX", sent];
16
+ }
17
+ return [(await listedFolders(source))?.all ?? GMAIL_ALL_MAIL];
13
18
  };
@@ -0,0 +1,15 @@
1
+ import type { AccountKey, MessageStore } from "../store/index.js";
2
+ /** Gmail's label on mail the account sent, as `decodedLabelName` gives `\\Sent`. */
3
+ export declare const SENT_LABEL = "Sent";
4
+ /** The mailbox address, the addresses the owner configured, and those the account's sent mail came from. */
5
+ export declare const ownAddresses: (store: MessageStore, key: AccountKey, configured?: readonly string[]) => Promise<Set<string>>;
6
+ /** Mail in the Sent folder or under Gmail's Sent label is the owner's whatever its From; otherwise its From says. */
7
+ export declare const sentByOwner: (from: string | null | undefined, own: ReadonlySet<string>, inSent?: boolean) => boolean | null;
8
+ /**
9
+ * After a sync: the senders of the mail in Sent join the owner's addresses, the account's mail from any of them
10
+ * becomes outgoing, and their identities join the owner as the account's own does.
11
+ */
12
+ export declare const settleOwnMail: (store: MessageStore, key: AccountKey, accountId: number, own: ReadonlySet<string>, mailboxes: readonly string[], { name, now }: {
13
+ name: string;
14
+ now: number;
15
+ }) => Promise<void>;
@@ -0,0 +1,35 @@
1
+ import { OWN_MAIL_ADDRESSES as OWN_ADDRESSES } from "../store/sqlite/own-identities.js";
2
+ /** Gmail's label on mail the account sent, as `decodedLabelName` gives `\\Sent`. */
3
+ export const SENT_LABEL = "Sent";
4
+ const normal = (address) => address.trim().toLowerCase();
5
+ const storedOwn = async (store, key) => {
6
+ const value = (await store.sync.syncState(key, OWN_ADDRESSES))?.value;
7
+ if (value === undefined)
8
+ return [];
9
+ try {
10
+ const parsed = JSON.parse(value);
11
+ return Array.isArray(parsed) ? parsed.filter((item) => typeof item === "string") : [];
12
+ }
13
+ catch {
14
+ return [];
15
+ }
16
+ };
17
+ /** The mailbox address, the addresses the owner configured, and those the account's sent mail came from. */
18
+ export const ownAddresses = async (store, key, configured = []) => new Set([key.account, ...configured, ...(await storedOwn(store, key))].map(normal));
19
+ /** Mail in the Sent folder or under Gmail's Sent label is the owner's whatever its From; otherwise its From says. */
20
+ export const sentByOwner = (from, own, inSent = false) => (inSent ? true : from == null ? null : own.has(normal(from)));
21
+ /**
22
+ * After a sync: the senders of the mail in Sent join the owner's addresses, the account's mail from any of them
23
+ * becomes outgoing, and their identities join the owner as the account's own does.
24
+ */
25
+ export const settleOwnMail = async (store, key, accountId, own, mailboxes, { name, now }) => {
26
+ const before = await storedOwn(store, key);
27
+ const found = await store.mail.markOwnMail(accountId, { addresses: [...own], mailboxes }, now);
28
+ const others = found.filter((address) => address !== normal(key.account));
29
+ if (others.length === 0 && before.length === 0)
30
+ return;
31
+ if (JSON.stringify(others) !== JSON.stringify([...before].sort()))
32
+ await store.sync.setSyncState(key, OWN_ADDRESSES, JSON.stringify(others));
33
+ // Saving the account again is what links its own identities, now with these addresses.
34
+ await store.accounts.saveAccount(key, { name });
35
+ };
@@ -1,6 +1,8 @@
1
+ import { mailAccountKey } from "./account-key.js";
1
2
  import { FETCH_CHUNK, readAttachments } from "./attachments.js";
2
3
  import { parsedEmail } from "./email-input.js";
3
4
  import { mailHeadersOf } from "./headers.js";
5
+ import { ownAddresses, SENT_LABEL } from "./own.js";
4
6
  import { parseMail } from "./parse.js";
5
7
  /** The `emails.metadata` key of an email stored from its first bytes: `{ bytes }` read of its `size`. */
6
8
  export const PARTIAL = "partial";
@@ -19,6 +21,7 @@ export const completePartial = async ({ store, source, accountId, address, folde
19
21
  const { emails, total, stuck } = await store.mail.partialEmails(accountId, PARTIAL_PER_RUN);
20
22
  if (emails.length === 0)
21
23
  return { completed: 0, left: 0, stuck };
24
+ const own = await ownAddresses(store, mailAccountKey(address));
22
25
  let given = 0;
23
26
  // A failed read is counted, so an email the server no longer gives is not read whole on every sync forever.
24
27
  const failed = async (email, forGood = false) => {
@@ -98,7 +101,7 @@ export const completePartial = async ({ store, source, accountId, address, folde
98
101
  now,
99
102
  emails: [
100
103
  {
101
- ...parsedEmail(mail, whole, mailHeadersOf(raw), address),
104
+ ...parsedEmail(mail, whole, mailHeadersOf(raw), own, whole.labels?.includes(SENT_LABEL)),
102
105
  receivedAt: email.receivedAt,
103
106
  size: raw.byteLength,
104
107
  metadata,
@@ -8,6 +8,7 @@ import { bulkBox } from "./bulk.js";
8
8
  import { parsedEmail } from "./email-input.js";
9
9
  import { factsOf } from "./facts.js";
10
10
  import { mailHeadersOf } from "./headers.js";
11
+ import { ownAddresses, SENT_LABEL } from "./own.js";
11
12
  import { parseMail } from "./parse.js";
12
13
  import { PARTIAL } from "./partial.js";
13
14
  import { storedMailRules } from "./rule-stored.js";
@@ -80,6 +81,7 @@ export const searchMailServer = async (store, mailbox, access, request) => {
80
81
  report.failed.push({ chat: call?.folder ?? null, reason });
81
82
  };
82
83
  const accountId = await store.accounts.saveAccount(mailbox, { name: mailbox.account });
84
+ const own = await ownAddresses(store, mailbox);
83
85
  const fresh = [];
84
86
  let rules = [];
85
87
  const ruled = new Map();
@@ -179,7 +181,7 @@ export const searchMailServer = async (store, mailbox, access, request) => {
179
181
  now,
180
182
  emails: [
181
183
  {
182
- ...parsedEmail(mail, item, mailHeadersOf(raw), mailbox.account),
184
+ ...parsedEmail(mail, item, mailHeadersOf(raw), own, item.labels?.includes(SENT_LABEL)),
183
185
  mailboxes: [
184
186
  { externalId: folder, name: folder, kind: null },
185
187
  ...(item.labels ?? []).map((name) => ({ externalId: `label:${name}`, name, kind: "label" })),
@@ -97,10 +97,14 @@ export interface MailSource {
97
97
  moved: string[];
98
98
  missing: string[];
99
99
  }>;
100
- /** All Mail and Trash under the names this account's language gives them. */
100
+ /**
101
+ * All Mail and Trash under the names this account's language gives them, and on IMAP the folder the server marks
102
+ * `\Sent` (RFC 6154), else the one a common name gives when the server marks no folder at all.
103
+ */
101
104
  folders?(): Promise<{
102
105
  all: string;
103
106
  trash: string;
107
+ sent?: string;
104
108
  }>;
105
109
  /** Which of these UIDs `folder` still holds. */
106
110
  present?(uids: readonly string[], folder: string): Promise<string[]>;
@@ -12,6 +12,8 @@ export interface MailAccount {
12
12
  address: string;
13
13
  mode?: "gmail" | "imap" | "mbox";
14
14
  folders?: string[];
15
+ /** The owner's other addresses on this mailbox, such as aliases: mail from them is the owner's. */
16
+ addresses?: string[];
15
17
  rules?: MailRule[];
16
18
  }
17
19
  /** What an index step reports, as memo's embedding does; the sync only passes it on. */
package/dist/mail/sync.js CHANGED
@@ -7,11 +7,12 @@ import { DEFAULT_ATTACHMENT_POLICY, FETCH_CHUNK, MAX_ATTACHMENT_CHARS, readAttac
7
7
  import { BULK, bulkBox } from "./bulk.js";
8
8
  import { parsedEmail } from "./email-input.js";
9
9
  import { factsOf } from "./facts.js";
10
- import { GMAIL_ALL_MAIL, mailFolders } from "./folders.js";
10
+ import { GMAIL_ALL_MAIL, mailFolders, sentFolder } from "./folders.js";
11
11
  import { dropMissing, tooManyGone } from "./gone.js";
12
12
  import { mailHeadersOf } from "./headers.js";
13
13
  import { flagsToRefresh, proveByLocation } from "./locations.js";
14
14
  import { saveMeetingNotes } from "./meeting-notes.js";
15
+ import { ownAddresses, SENT_LABEL, sentByOwner, settleOwnMail } from "./own.js";
15
16
  import { MAX_BODY_CHARS, parseMail } from "./parse.js";
16
17
  import { completePartial } from "./partial.js";
17
18
  import { FETCH_SLICE, keyOf, readQuick } from "./quick.js";
@@ -201,7 +202,12 @@ const syncRound = async (source, store, { account, since, max = 200, maxBodyChar
201
202
  const startedAt = now();
202
203
  const key = mailAccountKey(account.address);
203
204
  const accountId = await store.accounts.saveAccount(key, { name: account.address });
204
- const folders = await mailFolders(account, source);
205
+ const list = source.folders?.bind(source);
206
+ let listing;
207
+ const named = list ? { folders: () => (listing ??= list()) } : {};
208
+ const folders = await mailFolders(account, named);
209
+ const sent = await sentFolder(account, named);
210
+ const own = await ownAddresses(store, key, account.addresses);
205
211
  if (folders.length < 1 || folders.length > 50)
206
212
  throw new Error("select 1–50 mail folders");
207
213
  const rules = account.rules ?? [];
@@ -571,6 +577,8 @@ const syncRound = async (source, store, { account, since, max = 200, maxBodyChar
571
577
  ...[...(foundFolders.get(item.messageId) ?? [])].map(mailbox),
572
578
  ...(labelsOf.get(item.messageId)?.labels ?? []).map(label),
573
579
  ];
580
+ const inSent = (item) => (sent !== undefined && (foundFolders.get(item.messageId)?.has(sent) ?? false)) ||
581
+ (labelsOf.get(item.messageId)?.labels ?? []).includes(SENT_LABEL);
574
582
  const flagsOf = (item) => {
575
583
  const { seen, flagged } = labelsOf.get(item.messageId) ?? {};
576
584
  return { ...(seen === undefined ? {} : { read: seen }), ...(flagged === undefined ? {} : { flagged }) };
@@ -707,7 +715,7 @@ const syncRound = async (source, store, { account, since, max = 200, maxBodyChar
707
715
  receivedAt: Date.parse(item.receivedAt),
708
716
  bodyText: null,
709
717
  size: item.size ?? null,
710
- outgoing: headers?.from === key.account,
718
+ outgoing: sentByOwner(headers?.from, own, inSent(item)) ?? false,
711
719
  mailboxes: [...inMailboxes(item), envelopeBox(rule.match)],
712
720
  ...locationOf(item),
713
721
  ...flagsOf(item),
@@ -788,7 +796,7 @@ const syncRound = async (source, store, { account, since, max = 200, maxBodyChar
788
796
  now: startedAt,
789
797
  emails: [
790
798
  {
791
- ...parsedEmail(mail, item, header, key.account),
799
+ ...parsedEmail(mail, item, header, own, inSent(item)),
792
800
  mailboxes: inMailboxes(item),
793
801
  ...locationOf(item),
794
802
  ...flagsOf(item),
@@ -839,6 +847,10 @@ const syncRound = async (source, store, { account, since, max = 200, maxBodyChar
839
847
  await store.sync.setSyncState(key, "mail_folder_scope", scope);
840
848
  if (!snapshot)
841
849
  await store.mail.backfillSentAt(accountId, SENT_AT_BACKFILL_PER_RUN);
850
+ await settleOwnMail(store, key, accountId, own, [...(sent ? [sent] : []), `label:${SENT_LABEL}`], {
851
+ name: account.address,
852
+ now: startedAt,
853
+ });
842
854
  await stopIfAborted();
843
855
  const indexed = await index?.(store, key);
844
856
  const coverage = {
@@ -29,6 +29,8 @@ export interface FakeMail {
29
29
  flagged?: boolean;
30
30
  /** `trash` puts it in the trash folder; otherwise it is in All Mail, which INBOX also shows. */
31
31
  folder?: "trash";
32
+ /** Also in the mailbox's `sent` folder, as an IMAP server files mail the owner sent. */
33
+ sent?: boolean;
32
34
  /** Folders that do not hold it although its `folder` says they do, as a server's delete from one folder leaves it. */
33
35
  absentFrom?: string[];
34
36
  /** Listed without headers even when they are asked for, as a server does when it cannot read them. */
@@ -40,6 +42,8 @@ export interface FakeMailbox {
40
42
  /** All Mail under the account's language, as Gmail names it. */
41
43
  allMail?: string;
42
44
  trash?: string;
45
+ /** An IMAP Sent folder: `folders` names it, and it holds the mail marked `sent`. */
46
+ sent?: string;
43
47
  validity?: number;
44
48
  /** Each answer of `search` and `list` ends in this failure. */
45
49
  searchFails?: string;
@@ -72,6 +72,8 @@ export const fakeMailSource = (mailbox) => {
72
72
  const all = () => mailbox.allMail ?? GMAIL_ALL_MAIL;
73
73
  const trash = () => mailbox.trash ?? TRASH;
74
74
  const inFolder = (folder) => {
75
+ if (folder === mailbox.sent)
76
+ return mailbox.messages.filter((m) => m.sent && !m.absentFrom?.includes(folder));
75
77
  if (![all(), trash(), "INBOX"].includes(folder))
76
78
  throw failure(`Gmail has no such mailbox: ${folder}`);
77
79
  return mailbox.messages.filter((m) => (folder === trash() ? m.folder === "trash" : m.folder !== "trash") && !m.absentFrom?.includes(folder));
@@ -182,7 +184,7 @@ export const fakeMailSource = (mailbox) => {
182
184
  const moved = here.map((m) => m.messageId);
183
185
  return { moved, missing: messageIds.filter((id) => !moved.includes(id)) };
184
186
  },
185
- folders: async () => ({ all: all(), trash: trash() }),
187
+ folders: async () => ({ all: all(), trash: trash(), ...(mailbox.sent ? { sent: mailbox.sent } : {}) }),
186
188
  present: async (uids, folder) => inFolder(folder).flatMap((m) => (uids.includes(m.uid) ? [m.uid] : [])),
187
189
  label: async (messageIds, folder, labels) => {
188
190
  for (const m of inFolder(folder))
@@ -4,6 +4,7 @@ import { mailAccountKey } from "./account-key.js";
4
4
  import { MAX_ATTACHMENT_CHARS, readAttachments } from "./attachments.js";
5
5
  import { parsedEmail } from "./email-input.js";
6
6
  import { mailHeadersOf } from "./headers.js";
7
+ import { ownAddresses, SENT_LABEL } from "./own.js";
7
8
  import { MAX_BODY_CHARS, parseMail } from "./parse.js";
8
9
  import { PARTIAL } from "./partial.js";
9
10
  /**
@@ -42,6 +43,7 @@ export const readEmailWhole = async ({ store, source, address, externalId, folde
42
43
  if (!source.find && source.identify?.(raw, item).messageId !== externalId)
43
44
  throw new CliError("not_found", `the mail server holds another email where ${externalId} was`);
44
45
  const mail = await parseMail(raw, maxBodyChars);
46
+ const own = await ownAddresses(store, mailAccountKey(address));
45
47
  const log = [];
46
48
  const files = await readAttachments(mail, externalId, { loadEngine, maxAttachmentChars, at: now }, log);
47
49
  const { [PARTIAL]: _partial, ...metadata } = stored.metadata ?? {};
@@ -52,7 +54,7 @@ export const readEmailWhole = async ({ store, source, address, externalId, folde
52
54
  now,
53
55
  emails: [
54
56
  {
55
- ...parsedEmail(mail, whole, mailHeadersOf(raw), address),
57
+ ...parsedEmail(mail, whole, mailHeadersOf(raw), own, whole.labels?.includes(SENT_LABEL)),
56
58
  receivedAt: stored.receivedAt,
57
59
  size: raw.byteLength,
58
60
  metadata,
@@ -60,6 +60,19 @@ export interface ListedActivity extends StoredActivity {
60
60
  }
61
61
  /** The subjects and texts of the activities on each deal or lead of a kind, by `<account id>\u0000<external id>`. */
62
62
  export declare const activityTexts: (database: StoreContext["database"], kind: DealKind) => Map<string, string[]>;
63
+ export interface CrmActivityWrites {
64
+ /** Activities and tasks, each on the kept deals and leads it names; one on none of them is not stored. */
65
+ saveActivities(key: AccountKey, activities: readonly CrmActivity[]): Promise<CrmActivitiesSaved>;
66
+ /** Marks deleted the stored activities the CRM says it deleted; answers how many. */
67
+ removeActivities(key: AccountKey, externalIds: readonly string[]): Promise<number>;
68
+ /** The stored ones a list of every activity did not name, marked deleted; `dryRun` only counts them. */
69
+ removeUnlistedActivities(key: AccountKey, seen: readonly string[], options?: {
70
+ dryRun?: boolean;
71
+ }): Promise<{
72
+ stored: number;
73
+ unlisted: number;
74
+ }>;
75
+ }
63
76
  export interface CrmActivitiesSaved {
64
77
  saved: number;
65
78
  /** On no deal, lead, contact or company this copy keeps, so not stored. */
@@ -67,6 +80,7 @@ export interface CrmActivitiesSaved {
67
80
  }
68
81
  export declare const crmActivitiesOver: (context: StoreContext) => {
69
82
  save: (key: AccountKey, activities: readonly CrmActivity[]) => CrmActivitiesSaved;
83
+ writes: CrmActivityWrites;
70
84
  of: (key: AccountKey, kind: DealKind, externalId: string, limit: number) => StoredActivity[];
71
85
  list: (key: AccountKey, filter: ActivityFilter) => {
72
86
  items: ListedActivity[];
@@ -143,6 +143,25 @@ export const crmActivitiesOver = (context) => {
143
143
  }
144
144
  return { saved, outOfScope };
145
145
  });
146
+ const remove = (key, externalIds) => write(database, () => {
147
+ const forgotten = database
148
+ .prepare("UPDATE records SET deleted_at = ? WHERE account_id = ? AND type = ? AND deleted_at IS NULL " +
149
+ "AND external_id IN (SELECT value FROM json_each(?)) RETURNING id")
150
+ .all(now(), accountPk(context, key), ACTIVITY_RECORD, JSON.stringify(externalIds))
151
+ .map(({ id }) => Number(id));
152
+ dropCrmActivityChunks(database, forgotten);
153
+ return forgotten.length;
154
+ });
155
+ const removeUnlisted = (key, seen, { dryRun = false } = {}) => {
156
+ const accountId = accountPk(context, key);
157
+ const live = "account_id = ? AND type = ? AND deleted_at IS NULL";
158
+ const stored = Number(database.prepare(`SELECT count(*) AS n FROM records WHERE ${live}`).get(accountId, ACTIVITY_RECORD)?.n ?? 0);
159
+ const ids = database
160
+ .prepare(`SELECT external_id FROM records WHERE ${live} AND external_id NOT IN (SELECT value FROM json_each(?))`)
161
+ .all(accountId, ACTIVITY_RECORD, JSON.stringify(seen))
162
+ .map(({ external_id }) => String(external_id));
163
+ return { stored, unlisted: dryRun || ids.length === 0 ? ids.length : remove(key, ids) };
164
+ };
146
165
  /** The activities on one deal or lead: open ones first by due time, then the rest, newest first. */
147
166
  const of = (key, kind, externalId, limit) => {
148
167
  const accountId = findAccountPk(context, key);
@@ -282,7 +301,12 @@ export const crmActivitiesOver = (context) => {
282
301
  where.map(({ sql }) => `AND ${sql}`).join(" "))
283
302
  .get(accountId, ACTIVITY_RECORD, ...where.flatMap(({ params }) => params))?.n ?? 0);
284
303
  };
285
- return { save, of, list, count };
304
+ const writes = {
305
+ saveActivities: async (key, activities) => save(key, activities),
306
+ removeActivities: async (key, externalIds) => remove(key, externalIds),
307
+ removeUnlistedActivities: async (key, seen, options) => removeUnlisted(key, seen, options),
308
+ };
309
+ return { save, writes, of, list, count };
286
310
  };
287
311
  /** An activity a viewer may read: on one of its deals or leads, or on contacts alone and assigned to it. */
288
312
  const seenSql = (viewer) => {
@@ -1,8 +1,8 @@
1
- import { type CrmActivity, type CrmDepartment, type CrmField, type CrmItem, type CrmKind, type CrmOrganization, type CrmPerson, type CrmPipeline, type CrmScopeSetting, type CrmStageEntry, type CrmUser } from "../../domain/crm.js";
1
+ import { type CrmDepartment, type CrmField, type CrmItem, type CrmKind, type CrmOrganization, type CrmPerson, type CrmPipeline, type CrmScopeSetting, type CrmStageEntry, type CrmUser } from "../../domain/crm.js";
2
2
  import { type DealKind } from "../../domain/deals.js";
3
3
  import type { AccountPeople } from "../people.js";
4
4
  import type { AccountKey } from "../types.js";
5
- import { type CrmActivitiesSaved, type StoredActivity } from "./crm-activities.js";
5
+ import { type CrmActivityWrites, type StoredActivity } from "./crm-activities.js";
6
6
  import { type CrmActivityChunks } from "./crm-activity-chunks.js";
7
7
  import { type CrmReads } from "./crm-changes.js";
8
8
  import { type CrmContactsRemoved } from "./crm-contacts.js";
@@ -37,7 +37,7 @@ export interface CrmSaved {
37
37
  * nothing is ever matched by name (WC-DATA-6). Rows the CRM no longer has are marked deleted, never removed
38
38
  * (WC-DATA-7). Every write is one transaction per call.
39
39
  */
40
- export interface CrmCopies extends CrmReads {
40
+ export interface CrmCopies extends CrmReads, CrmActivityWrites {
41
41
  /** One kind's pipelines and their stages, by the CRM's ids. A stage the CRM dropped stays: deals may stand in it. */
42
42
  savePipelines(key: AccountKey, kind: DealKind, pipelines: CrmPipeline[]): Promise<CrmSaved>;
43
43
  /** Deals or leads; one whose stage is not stored, or whose fields the store refuses, is skipped and named. */
@@ -113,8 +113,6 @@ export interface CrmCopies extends CrmReads {
113
113
  expireStageEntries(key: AccountKey): Promise<number>;
114
114
  /** Whether the owner turned on reading activities and tasks (`activities` setting). */
115
115
  activitiesOn(key: AccountKey): Promise<boolean>;
116
- /** Activities and tasks, each on the kept deals and leads it names; one on none of them is not stored. */
117
- saveActivities(key: AccountKey, activities: readonly CrmActivity[]): Promise<CrmActivitiesSaved>;
118
116
  /** One deal's or lead's activities, open ones first. */
119
117
  activitiesOf(key: AccountKey, kind: DealKind, externalId: string, limit: number): Promise<StoredActivity[]>;
120
118
  /** The activities' pieces searched by meaning, as `embedCrmActivities` and `search all` read them. */
@@ -4,7 +4,7 @@ import { DEAL_ROLES } from "../../domain/deals.js";
4
4
  import { recordFingerprint } from "../../domain/records.js";
5
5
  import { accountPk, findAccountPk } from "./accounts.js";
6
6
  import { suggestBaseStages } from "./base-suggest.js";
7
- import { crmActivitiesOver, forgetActivitiesOn, } from "./crm-activities.js";
7
+ import { crmActivitiesOver, forgetActivitiesOn } from "./crm-activities.js";
8
8
  import { crmActivityChunksOver } from "./crm-activity-chunks.js";
9
9
  import { crmReadsOver } from "./crm-changes.js";
10
10
  import { removeCrmContacts } from "./crm-contacts.js";
@@ -670,7 +670,7 @@ export const crmCopiesOver = (context, people) => {
670
670
  handleStageEntries: async (ids) => stageEntryStore.handled(ids),
671
671
  expireStageEntries: async (key) => stageEntryStore.expire(key),
672
672
  activitiesOn: async (key) => crmActivitiesOn(database, key),
673
- saveActivities: async (key, activities) => activityStore.save(key, activities),
673
+ ...activityStore.writes,
674
674
  activitiesOf: async (key, kind, externalId, limit) => activityStore.of(key, kind, externalId, limit),
675
675
  activityChunks: crmActivityChunksOver(context),
676
676
  ...crmReadsOver(context),
@@ -8,3 +8,11 @@ export declare const setEmailFlags: (database: CacheDatabase, accountId: number,
8
8
  }>, now: number) => number;
9
9
  export declare const markEmailsDeleted: (database: CacheDatabase, accountId: number, externalIds: string[], now: number) => number;
10
10
  export declare const markEmailsRestored: (database: CacheDatabase, accountId: number, externalIds: string[], now: number) => number;
11
+ /**
12
+ * Takes the senders of the live mail in `mailboxes` as the owner's, beside `addresses`, and marks every email of the
13
+ * account from any of them outgoing. Answers the addresses, lower case.
14
+ */
15
+ export declare const markOwnMail: (database: CacheDatabase, accountId: number, { addresses, mailboxes }: {
16
+ addresses: readonly string[];
17
+ mailboxes: readonly string[];
18
+ }, now: number) => string[];
@@ -51,3 +51,26 @@ export const markEmailsRestored = (database, accountId, externalIds, now) => {
51
51
  recountEmailThread(database, id, now);
52
52
  return threads.length;
53
53
  };
54
+ /**
55
+ * Takes the senders of the live mail in `mailboxes` as the owner's, beside `addresses`, and marks every email of the
56
+ * account from any of them outgoing. Answers the addresses, lower case.
57
+ */
58
+ export const markOwnMail = (database, accountId, { addresses, mailboxes }, now) => {
59
+ const own = new Set(addresses.map((address) => address.trim().toLowerCase()));
60
+ if (mailboxes.length > 0)
61
+ for (const row of database
62
+ .prepare(`SELECT DISTINCT lower(trim(e.from_address)) AS address FROM mailboxes b
63
+ JOIN email_mailboxes m ON m.mailbox_id = b.id JOIN emails e ON e.id = m.email_id
64
+ WHERE b.account_id = ? AND b.external_id IN (SELECT value FROM json_each(?))
65
+ AND e.deleted_at IS NULL AND e.from_address IS NOT NULL`)
66
+ .all(accountId, JSON.stringify(mailboxes)))
67
+ if (typeof row.address === "string" && row.address !== "")
68
+ own.add(row.address);
69
+ if (own.size > 0)
70
+ database
71
+ .prepare(`UPDATE emails SET outgoing = 1, updated_at = ? WHERE account_id = ? AND outgoing IS NOT 1
72
+ AND from_identity_id IN (SELECT id FROM identities WHERE provider = 'email'
73
+ AND external_id IN (SELECT value FROM json_each(?)))`)
74
+ .run(now, accountId, JSON.stringify([...own]));
75
+ return [...own].sort();
76
+ };
@@ -239,6 +239,15 @@ export interface MailStore extends PartialMailStore, MailActivityStore {
239
239
  read?: boolean;
240
240
  flagged?: boolean;
241
241
  }>, now: number): Promise<number>;
242
+ /**
243
+ * Takes the senders of the live mail in `mailboxes` (the Sent folder, Gmail's `label:Sent`) as the owner's, beside
244
+ * `addresses`, and marks the account's mail from any of them outgoing, so mail stored before it was known counts.
245
+ * Answers the addresses, lower case.
246
+ */
247
+ markOwnMail(accountId: number, own: {
248
+ addresses: readonly string[];
249
+ mailboxes: readonly string[];
250
+ }, now: number): Promise<string[]>;
242
251
  /** Gives up to `limit` emails stored without `sent_at` their internal date; answers how many. */
243
252
  backfillSentAt(accountId: number, limit: number): Promise<number>;
244
253
  /** The live emails whose location in `folder` has this UIDVALIDITY, oldest UID first. */
@@ -4,7 +4,7 @@ import { fold, normalize } from "../normalize.js";
4
4
  import { mailActivity, threadEmailIds } from "./email-activity.js";
5
5
  import { chunkAttachments, drainEmailIndex, dropAttachmentChunks, MAIL_PIECES, queueThreads, threadPieces, titleOf, } from "./email-index.js";
6
6
  import { backfillSentAt, folderEmails, forgetLocations, locate, partialMail, setLocations, storedWhole, } from "./email-locations.js";
7
- import { markEmailsDeleted, markEmailsRestored, recountEmailThread as recount, setEmailFlags } from "./email-state.js";
7
+ import { markEmailsDeleted, markEmailsRestored, markOwnMail, recountEmailThread as recount, setEmailFlags, } from "./email-state.js";
8
8
  import { EMAIL_ENRICHMENT, enrichmentText } from "./enrichments.js";
9
9
  import { bool, flag, fromJson, int, page, str, toJson } from "./events.js";
10
10
  import { folded } from "./folded.js";
@@ -560,6 +560,7 @@ export const mailStoreOver = ({ database, orm, now }, stemmerFor = stemmerCache(
560
560
  });
561
561
  },
562
562
  setFlags: async (accountId, flags, now) => write(database, () => setEmailFlags(database, accountId, flags, now)),
563
+ markOwnMail: async (accountId, own, at) => write(database, () => markOwnMail(database, accountId, own, at)),
563
564
  backfillSentAt: async (accountId, limit) => write(database, () => backfillSentAt(database, accountId, limit)),
564
565
  folderEmails: async (accountId, folder, uidvalidity) => folderEmails(database, accountId, folder, uidvalidity),
565
566
  setLocations: async (accountId, folder, uidvalidity, found) => write(database, () => setLocations(database, accountId, folder, uidvalidity, found)),
@@ -1,5 +1,7 @@
1
1
  import type { IdentityRef, PersonRecord } from "../types.js";
2
2
  import type { StoreContext } from "./open.js";
3
+ /** Sync state under a mail account: the owner's other addresses on it, lower case, as a JSON array. */
4
+ export declare const OWN_MAIL_ADDRESSES = "mail_own_addresses";
3
5
  /**
4
6
  * An account's own identity (same provider and id as the account) is usually the owner. Messengers save it like anyone
5
7
  * else's, as a person of its own, so the owner's name counted as a contact's. Links that person to the owner when every
@@ -7,6 +7,8 @@ import { mergePerson, personOf } from "./person-links.js";
7
7
  import { RULE } from "./person-match-scan.js";
8
8
  import { separated } from "./person-separation.js";
9
9
  import { write } from "./transaction.js";
10
+ /** Sync state under a mail account: the owner's other addresses on it, lower case, as a JSON array. */
11
+ export const OWN_MAIL_ADDRESSES = "mail_own_addresses";
10
12
  const ACCOUNT_REASON = "an account you connected, under another name: a mailbox or messenger you read may be someone else's";
11
13
  const ownerNames = ({ database }, owner) => database
12
14
  .prepare("SELECT i.name FROM identity_links l JOIN identities i ON i.id = l.identity_id WHERE l.person_id = ?")
@@ -49,7 +51,7 @@ export const linkOwnIdentities = (context) => {
49
51
  own.push({ identity: Number(row.identity), person, name: typeof row.name === "string" ? row.name : null });
50
52
  byPerson.set(person, own);
51
53
  }
52
- if (byPerson.size === 0)
54
+ if (byPerson.size === 0 && aliasPeople(context, owner).length === 0)
53
55
  return 0;
54
56
  return write(context.database, () => {
55
57
  let joined = 0;
@@ -74,9 +76,30 @@ export const linkOwnIdentities = (context) => {
74
76
  reason: ACCOUNT_REASON,
75
77
  });
76
78
  }
79
+ for (const person of aliasPeople(context, owner)) {
80
+ if (separated(context, person, owner))
81
+ continue;
82
+ mergePerson(context, person, owner, { method: "account", by: "rules" });
83
+ joined += 1;
84
+ }
77
85
  return joined;
78
86
  });
79
87
  };
88
+ /**
89
+ * People holding one of a mail account's other own addresses (`OWN_MAIL_ADDRESSES`), once the account's own identity
90
+ * is the owner's: an alias follows the account, whatever name its mail carries. A partner's mailbox keeps its aliases.
91
+ */
92
+ const aliasPeople = ({ database }, owner) => database
93
+ .prepare("SELECT DISTINCT l.person_id AS person FROM sync_cursors s " +
94
+ "JOIN accounts a ON a.id = s.account_id AND a.provider = 'email' " +
95
+ "JOIN json_each(CASE WHEN json_valid(s.value) THEN s.value ELSE '[]' END) j " +
96
+ "JOIN identities i ON i.provider = 'email' AND i.external_id = j.value AND i.bot IS NOT 1 " +
97
+ "JOIN identity_links l ON l.identity_id = i.id " +
98
+ "WHERE s.key = ? AND l.person_id <> ? AND EXISTS (SELECT 1 FROM identities ai " +
99
+ "JOIN identity_links al ON al.identity_id = ai.id " +
100
+ "WHERE ai.provider = a.provider AND ai.external_id = a.external_id AND al.person_id = ?) ORDER BY l.person_id")
101
+ .all(OWN_MAIL_ADDRESSES, owner, owner)
102
+ .map(({ person }) => Number(person));
80
103
  /** `contacts link <person> me`: an identity the account id does not name, a Zoom user for one, is the owner. */
81
104
  export const linkToOwner = (context, ref) => {
82
105
  const owner = ownerPerson(context.database).id;
@@ -52,6 +52,13 @@ export interface SimilarPerson extends ListedPerson {
52
52
  /** The same name once case, quotes, punctuation and word order are set aside: maybe the same person. */
53
53
  sameName: boolean;
54
54
  }
55
+ /**
56
+ * Works out and keeps the kind, name order and counts of every person whose stored ones the triggers cleared.
57
+ * A few, as a sync leaves, are worked out under the write lock. Everyone, after an upgrade, would hold the lock for
58
+ * seconds: that pass runs outside it and is kept only when no other process wrote meanwhile, else it runs again.
59
+ * Answers whether every stored one is current.
60
+ */
61
+ export declare const storeKinds: (database: CacheDatabase) => boolean;
55
62
  /** How many people of each kind match the query, every kind at once. */
56
63
  export declare const countPeople: (database: CacheDatabase, query?: string) => Record<PersonKind, number>;
57
64
  /** People of one kind, the owner first, in the order asked; `counts` says how many each kind holds. */
@@ -1,5 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
- import { isNoReplyAddress, isPersonLikeRoleAddress, isRoleAddress } from "../../domain/addresses.js";
2
+ import { isNoReplyAddress, isNotificationAddress, isPersonLikeRoleAddress, isRoleAddress, } from "../../domain/addresses.js";
3
3
  import { displayName, isReadable, nameKey, noFallbacks, takeFallbacks } from "../../domain/display-names.js";
4
4
  import { spellings, variantKey } from "../../domain/name-variants.js";
5
5
  import { isAutomatedName, isCompanyName, PERSON_KINDS, } from "../../domain/person-kinds.js";
@@ -164,6 +164,7 @@ const kindOf = (shown, facts, ties, mail, test) => {
164
164
  const automated = [
165
165
  ...(facts?.bot ? ["bot"] : []),
166
166
  ...(emails.some(isNoReplyAddress) ? ["no-reply"] : []),
167
+ ...(emails.some(isNotificationAddress) ? ["notification-address"] : []),
167
168
  ...(mail !== undefined && mail.n >= BULK_MIN && mail.bulk * 2 > mail.n ? ["bulk-mail"] : []),
168
169
  ...(facts?.neverReplied ? ["bulk-never-replied"] : []),
169
170
  ...(isAutomatedName(shown) ? ["automated-name"] : []),
@@ -234,7 +235,7 @@ const byName = (a, b) => a.nameOrder < b.nameOrder ? -1 : a.nameOrder > b.nameOr
234
235
  * Bump when what decides a kind, a name's order or a count changes in code (the word lists, `BULK_MIN`, the ties):
235
236
  * every stored one is worked out again on the next list.
236
237
  */
237
- const KIND_RULES = "4";
238
+ const KIND_RULES = "5";
238
239
  const RULES_KEY = "people.kind_rules";
239
240
  /** Past this many people to work out, one pass over everyone beats a lookup per person. */
240
241
  const WHOLE_PASS = 20_000;
@@ -288,7 +289,7 @@ const keep = (database, worked) => {
288
289
  * seconds: that pass runs outside it and is kept only when no other process wrote meanwhile, else it runs again.
289
290
  * Answers whether every stored one is current.
290
291
  */
291
- const storeKinds = (database) => {
292
+ export const storeKinds = (database) => {
292
293
  if (isQueryOnly(database))
293
294
  return (rulesOf(database) === KIND_RULES &&
294
295
  database.prepare("SELECT 1 FROM persons WHERE kind IS NULL LIMIT 1").get() === undefined);
@@ -2,9 +2,10 @@ import { isEmailAddress, isNoReplyAddress, isPersonLikeRoleAddress, isRoleAddres
2
2
  import { displayName, isReadable } from "../../domain/display-names.js";
3
3
  import { variantKey } from "../../domain/name-variants.js";
4
4
  import { BARE_INTERNATIONAL_PROVIDERS, isMobilePhone, nationalPhone, storedPhone } from "../../domain/phones.js";
5
- import { linkIndex, settleLinks } from "./identity-link-rows.js";
5
+ import { linkIndex, linkRows, settleLinks } from "./identity-link-rows.js";
6
6
  import { openIdentityLink } from "./identity-proposals.js";
7
7
  import { peopleByNameKey, sharedTraces } from "./name-traces.js";
8
+ import { storeKinds } from "./people-list.js";
8
9
  import { isOwner, mergePerson } from "./person-links.js";
9
10
  import { personsByIdentifiers } from "./person-matcher.js";
10
11
  import { resolvePersonLinks } from "./person-resolution.js";
@@ -19,7 +20,7 @@ export const RULE = { bot: "rule", kind: "rule" };
19
20
  const MOST_SHARING = 6;
20
21
  const CURSOR = "people.scan";
21
22
  /** Raised when a rule changes what a pass finds in values nobody touched: the next pass then reads everything once. */
22
- const RULES = 6;
23
+ const RULES = 7;
23
24
  /**
24
25
  * NEED-2526: a shared mailbox says little alone, so its proposal is scored by what else the two people have in common.
25
26
  * The owner's word (2026-11-11): `hr@` is often one person's, so it starts below `info@`.
@@ -391,7 +392,14 @@ const strongEnough = (context, from, to, trace) => {
391
392
  * One name and a shared trace (a phone, an address, a chat, a company's domain) only proposes: a name is common, so
392
393
  * the owner decides every merge. More than `MOST_SHARING` people on one name is too common to propose from.
393
394
  */
394
- const sameName = (pass, people, name) => {
395
+ const sameName = (pass, named, name) => {
396
+ const people = named.filter((one) => !pass.notByName.has(one));
397
+ if (people.length < named.length)
398
+ pass.result.skipped.push({
399
+ persons: named.filter((one) => pass.notByName.has(one)).map(String),
400
+ signal: "name",
401
+ reason: "identity.not-a-person",
402
+ });
395
403
  if (people.length > MOST_SHARING) {
396
404
  pass.result.skipped.push({ persons: people.map(String), signal: "name", reason: "identity.common-name" });
397
405
  return;
@@ -445,7 +453,7 @@ const sameNameInChats = (pass, holders) => {
445
453
  const people = new Map();
446
454
  for (const holder of holders) {
447
455
  const person = personOf(pass.context, holder.identity);
448
- if (person !== undefined && !people.has(person))
456
+ if (person !== undefined && !pass.notByName.has(person) && !people.has(person))
449
457
  people.set(person, holder);
450
458
  }
451
459
  if (people.size < 2)
@@ -536,6 +544,24 @@ const guestRows = (database) => database
536
544
  email: row.email,
537
545
  meeting: Number(row.meeting),
538
546
  }));
547
+ /**
548
+ * Kinds are worked out first, since a join above clears them; anyone whose kind is still not worked out (another
549
+ * writer won the race) is taken for a person this pass.
550
+ */
551
+ const notByNameOf = (database) => {
552
+ storeKinds(database);
553
+ return new Set(database
554
+ .prepare("SELECT id FROM persons WHERE kind IN ('automated', 'organization') UNION SELECT l.person_id " +
555
+ `FROM identity_links l JOIN identities i ON i.id = l.identity_id WHERE NOT (${NOT_A_BOT})`)
556
+ .all()
557
+ .map((row) => Number(row.id)));
558
+ };
559
+ /** Open name proposals made before one side was known to be no person, which nobody should review now. */
560
+ const forgetNameProposals = (database, notByName) => {
561
+ for (const row of linkRows(database, ["proposed"]))
562
+ if (row.payload.signal === "name" && row.pair?.some((person) => notByName.has(person)))
563
+ database.prepare("DELETE FROM proposed_actions WHERE id = ?").run(Number(row.id));
564
+ };
539
565
  /**
540
566
  * One pass of the people matcher. It reads what may match outside any transaction and takes the write lock only for
541
567
  * each group it changes, so other writers are never kept waiting for the whole pass. After the first pass, only the
@@ -554,6 +580,7 @@ export const scanMatches = (context, { full = false } = {}) => {
554
580
  index: linkIndex(database),
555
581
  result: { full: changed === undefined, merged: [], proposed: [], skipped: [] },
556
582
  shared: [],
583
+ notByName: new Set(),
557
584
  };
558
585
  for (const [address, holders] of emailHolders(database))
559
586
  if (holders.length > 1 && touched(holders))
@@ -566,6 +593,8 @@ export const scanMatches = (context, { full = false } = {}) => {
566
593
  for (const row of guestRows(database))
567
594
  if ((changed === undefined || changed.has(row.identity)) && !pass.index.names(row.ref))
568
595
  write(database, () => guestEmail(pass, row));
596
+ pass.notByName = notByNameOf(database);
597
+ write(database, () => forgetNameProposals(database, pass.notByName));
569
598
  const changedPeople = changed === undefined ? undefined : peopleOfIdentities(context, changed);
570
599
  for (const { people, name } of peopleByNameKey(database).values())
571
600
  if (people.length > 1 && (changedPeople === undefined || people.some((one) => changedPeople.has(one))))
@@ -592,6 +621,7 @@ export const linkPhones = (context, identities) => {
592
621
  index: linkIndex(database),
593
622
  result: { full: false, merged: [], proposed: [], skipped: [] },
594
623
  shared: [],
624
+ notByName: new Set(),
595
625
  };
596
626
  for (const [phone, holders] of phoneHolders(database))
597
627
  if (holders.length > 1 && holders.some(({ identity }) => identities.has(identity)))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.750.0",
3
+ "version": "0.752.0",
4
4
  "description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Viacheslav Ptsarev",