@wirecat/cli-core 0.752.0 → 0.753.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.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,26 @@ 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.753.0 — 25.11.2026
9
+
10
+ ### Added
11
+
12
+ - **A CRM CLI built from a manifest can add notes and tasks.** `crmManifestWrites` and `crmManifestWriteCapabilities`
13
+ take `activities`: the CLI's own functions for a comment, a task and a task marked done, and the operation each
14
+ sends. They mount `activities create` and `activities close` under the same guard and journal as any CRM write.
15
+ Each also checks its operation's `api` keys, so `api.<operation>: deny` stops it, and `crmAlsoChecks` takes
16
+ `crmManifestActivityKeys` so `--dry-run` names them ([CRM](docs/dev/CRM.md#writes-from-a-manifest)).
17
+
18
+ ### Fixed
19
+
20
+ - **Mail to one of the owner's aliases is owed an answer.** `review --unanswered` and `tasks agenda` took mail as
21
+ addressed to the owner only when the account's own address was in To or Cc, so mail sent to an alias was never owed.
22
+ Now any address under `mail_own_addresses` counts: those configured in `MailAccount.addresses` and the senders of
23
+ Sent mail.
24
+ - **A long sync stays fast as the chat grows.** Each saved message looked through the whole chat for replies
25
+ waiting for it as their thread's root, so a page of 100 took 78 ms at 10,000 stored messages and 919 ms at 90,000.
26
+ That search now runs once per page (tg-cli [#917](https://github.com/WireCatLabs/tg-cli/issues/917)).
27
+
8
28
  ## 0.752.0 — 25.11.2026
9
29
 
10
30
  ### Added
@@ -4,7 +4,7 @@ export { DAILY_FOREIGN_CONTACTS, type ForeignContacts, foreignContacts, foreignC
4
4
  export { type CrmAfterHook, type CrmChangesCall, type CrmFixedValue, type CrmManifest, type CrmManifestEntity, type CrmManifestFields, type CrmManifestHooks, type CrmManifestPipelines, type CrmManifestWrite, type CrmOperationCall, type CrmRule, type CrmWriteRule, parseCrmManifest, } from "./manifest/manifest.js";
5
5
  export { crmManifestProblems } from "./manifest/paths.js";
6
6
  export { type CrmManifestSource, type CrmManifestSourceOptions, crmSourceFromManifest } from "./manifest/source.js";
7
- export { type CrmManifestWritesOptions, crmManifestWriteCapabilities, crmManifestWriteKeys, crmManifestWrites, } from "./manifest/writer.js";
7
+ export { type CrmManifestActivities, type CrmManifestWritesOptions, crmManifestActivityKeys, crmManifestWriteCapabilities, crmManifestWriteKeys, crmManifestWrites, } from "./manifest/writer.js";
8
8
  export { type ProviderCallOptions, providerCall } from "./provider-call.js";
9
9
  export { type CrmConditionHooks, type CrmQueryField, conditionsOf, customConditions, customNames, filterableFields, selectedCodes, wantedCodes, withCustomFields, } from "./query.js";
10
10
  export { CRM_FILE_SOURCES, type CrmCallContext, type CrmChanges, type CrmCondition, type CrmFile, type CrmFileOwner, type CrmFileSourceKind, type CrmFiles, type CrmGap, type CrmIdPage, type CrmLiveKind, type CrmLiveQuery, type CrmOpenableFile, type CrmPage, type CrmSource, type CrmSourceTraits, } from "./source.js";
package/dist/crm/index.js CHANGED
@@ -4,7 +4,7 @@ export { DAILY_FOREIGN_CONTACTS, foreignContacts, foreignContactsPathFor, refuse
4
4
  export { parseCrmManifest, } from "./manifest/manifest.js";
5
5
  export { crmManifestProblems } from "./manifest/paths.js";
6
6
  export { crmSourceFromManifest } from "./manifest/source.js";
7
- export { crmManifestWriteCapabilities, crmManifestWriteKeys, crmManifestWrites, } from "./manifest/writer.js";
7
+ export { crmManifestActivityKeys, crmManifestWriteCapabilities, crmManifestWriteKeys, crmManifestWrites, } from "./manifest/writer.js";
8
8
  export { providerCall } from "./provider-call.js";
9
9
  export { conditionsOf, customConditions, customNames, filterableFields, selectedCodes, wantedCodes, withCustomFields, } from "./query.js";
10
10
  export { CRM_FILE_SOURCES, } from "./source.js";
@@ -1,11 +1,26 @@
1
1
  import { type ServiceApiPermissionsInput } from "../../cli/service-api.js";
2
2
  import { type ServiceApiCall, type ServiceApiCallOptions } from "../../cli/service-api-call.js";
3
3
  import type { ServiceApiManifest } from "../../cli/service-api-manifest.js";
4
- import type { CrmKind } from "../../domain/crm.js";
4
+ import type { CrmActivity, CrmKind } from "../../domain/crm.js";
5
5
  import type { PermissionKey } from "../../sends/permissions.js";
6
- import { type CrmVerb, type CrmWriteCapabilities, type CrmWriter } from "../writer.js";
6
+ import { type CrmActivityDraft, type CrmActivityWrite, type CrmVerb, type CrmWriteCapabilities, type CrmWriter } from "../writer.js";
7
7
  import { type CrmWrites } from "../writes.js";
8
8
  import { type CrmManifestSource } from "./source.js";
9
+ /**
10
+ * Activities the manifest does not describe, written by the CLI's own functions over `send`: a comment, a task and a
11
+ * task marked done. Each answers the activity as the source's `activities` maps it, with the same id, or the next full
12
+ * sync takes it for one the CRM deleted.
13
+ */
14
+ export interface CrmManifestActivities {
15
+ /** The operation each sends, whose `api` keys the write checks too; a task needs `close` as well. */
16
+ operations: {
17
+ readonly comment?: string;
18
+ readonly task?: string;
19
+ readonly close?: string;
20
+ };
21
+ create(draft: CrmActivityDraft, send: ServiceApiCall): Promise<CrmActivity>;
22
+ complete?(externalId: string, send: ServiceApiCall): Promise<CrmActivity>;
23
+ }
9
24
  export interface CrmManifestWriterOptions {
10
25
  api: ServiceApiManifest;
11
26
  /** The service's name in messages: "Attio". */
@@ -14,14 +29,17 @@ export interface CrmManifestWriterOptions {
14
29
  send: ServiceApiCall;
15
30
  /** The source over the same manifest: the read-back after each write, and the pipelines a close looks in. */
16
31
  source: () => CrmManifestSource;
32
+ activities?: CrmManifestActivities;
17
33
  }
18
- /** What the manifest's writes take, for `addCrmCommands({ writes })`; none when it describes no writes. */
19
- export declare const crmManifestWriteCapabilities: (input: unknown, api: ServiceApiManifest) => CrmWriteCapabilities | undefined;
34
+ /** What the manifest's writes and the CLI's activities take, for `addCrmCommands({ writes })`; none when neither. */
35
+ export declare const crmManifestWriteCapabilities: (input: unknown, api: ServiceApiManifest, activities?: CrmManifestActivities) => CrmWriteCapabilities | undefined;
20
36
  /**
21
37
  * The `api` keys each CRM write also checks, those of the operation it sends, so `api.<operation>: deny` stops the
22
38
  * write too: for `CrmWrites.alsoChecks` and `crmAlsoChecks`, so `--dry-run` names them.
23
39
  */
24
40
  export declare const crmManifestWriteKeys: (input: unknown, api: ServiceApiManifest, bodyPermissions?: ServiceApiPermissionsInput["bodyPermissions"]) => ((kind: CrmKind, verb: CrmVerb) => PermissionKey[]);
41
+ /** The `api` keys of the operation each activity write sends, for `CrmWrites.activityChecks` and `crmAlsoChecks`. */
42
+ export declare const crmManifestActivityKeys: (api: ServiceApiManifest, activities: CrmManifestActivities | undefined, bodyPermissions?: ServiceApiPermissionsInput["bodyPermissions"]) => ((write: CrmActivityWrite | "close") => PermissionKey[]);
25
43
  /**
26
44
  * A `CrmWriter` from a manifest's `writes`: each of our fields goes to the service by its rule, a field with no rule is
27
45
  * refused before anything is sent, and every write is sent once and read back by the entity's `get`, as a sync maps
@@ -31,6 +49,7 @@ export declare const crmWriterFromManifest: (input: unknown, options: CrmManifes
31
49
  export interface CrmManifestWritesOptions extends ServiceApiCallOptions, Pick<ServiceApiPermissionsInput, "bodyPermissions">, Omit<CrmWrites, "writer" | "alsoChecks"> {
32
50
  /** The CLI's source over the same manifest (`crmSourceFromManifest`). */
33
51
  source: () => CrmManifestSource;
52
+ activities?: CrmManifestActivities;
34
53
  }
35
54
  /**
36
55
  * `CrmRun.writes` for a CLI whose writes its manifest describes: the writer over the CLI's fetch and token, and the
@@ -3,11 +3,21 @@ import { serviceApiOwnKeys } from "../../cli/service-api.js";
3
3
  import { serviceApiSend } from "../../cli/service-api-call.js";
4
4
  import { DEAL_KINDS } from "../../domain/deals.js";
5
5
  import { fullName, id, isRaw, text } from "../values.js";
6
- import { CRM_VERBS } from "../writer.js";
6
+ import { CRM_VERBS, } from "../writer.js";
7
7
  import { foldFieldName } from "../writes.js";
8
8
  import { parseCrmManifest, } from "./manifest.js";
9
9
  import { at } from "./map.js";
10
10
  import { fill, inputOf } from "./source.js";
11
+ const activityWritesOf = (activities) => {
12
+ if (!activities)
13
+ return [];
14
+ const { operations, complete } = activities;
15
+ if (operations.task !== undefined && (operations.close === undefined || complete === undefined))
16
+ throw new CliError("configuration_error", "source manifest: activities: a task needs close and complete", {
17
+ reason: "manifest.invalid",
18
+ });
19
+ return ["comment", "task"].filter((write) => operations[write] !== undefined);
20
+ };
11
21
  const CALL_OF = {
12
22
  create: "create",
13
23
  update: "update",
@@ -21,12 +31,13 @@ const ruleOf = (one, field) => one.fields[field];
21
31
  const takes = (kind, one, verb) => verb === "move" || verb === "close"
22
32
  ? isDealKind(kind) && one.update !== undefined && typeof ruleOf(one, "stage") === "object"
23
33
  : one[CALL_OF[verb]] !== undefined;
24
- const capabilitiesOf = (manifest) => {
34
+ const capabilitiesOf = (manifest, activities) => {
25
35
  const written = manifest.kinds.flatMap((kind) => {
26
36
  const one = manifest.writes?.[kind];
27
37
  return one ? [{ kind, one }] : [];
28
38
  });
29
- if (written.length === 0)
39
+ const activityWrites = activityWritesOf(activities);
40
+ if (written.length === 0 && activityWrites.length === 0)
30
41
  return undefined;
31
42
  return {
32
43
  kinds: written.map(({ kind }) => kind),
@@ -34,10 +45,11 @@ const capabilitiesOf = (manifest) => {
34
45
  // No slot sends the operation id, so a repeated write would be made again.
35
46
  idempotent: false,
36
47
  fields: Object.fromEntries(written.map(({ kind, one }) => [kind, [...Object.keys(one.fields), ...(one.custom ? ["custom"] : [])]])),
48
+ ...(activityWrites.length === 0 ? {} : { activities: activityWrites }),
37
49
  };
38
50
  };
39
- /** What the manifest's writes take, for `addCrmCommands({ writes })`; none when it describes no writes. */
40
- export const crmManifestWriteCapabilities = (input, api) => capabilitiesOf(parseCrmManifest(input, api));
51
+ /** What the manifest's writes and the CLI's activities take, for `addCrmCommands({ writes })`; none when neither. */
52
+ export const crmManifestWriteCapabilities = (input, api, activities) => capabilitiesOf(parseCrmManifest(input, api), activities);
41
53
  /**
42
54
  * The `api` keys each CRM write also checks, those of the operation it sends, so `api.<operation>: deny` stops the
43
55
  * write too: for `CrmWrites.alsoChecks` and `crmAlsoChecks`, so `--dry-run` names them.
@@ -51,6 +63,19 @@ export const crmManifestWriteKeys = (input, api, bodyPermissions) => {
51
63
  return operation ? serviceApiOwnKeys(operation, bodyPermissions) : [];
52
64
  };
53
65
  };
66
+ /** The `api` keys of the operation each activity write sends, for `CrmWrites.activityChecks` and `crmAlsoChecks`. */
67
+ export const crmManifestActivityKeys = (api, activities, bodyPermissions) => {
68
+ const operations = new Map(api.operations.map((one) => [one.id, one]));
69
+ return (write) => {
70
+ const id = activities?.operations[write];
71
+ const operation = id === undefined ? undefined : operations.get(id);
72
+ if (id !== undefined && !operation)
73
+ throw new CliError("configuration_error", `source manifest: activities: no operation ${id}`, {
74
+ reason: "manifest.invalid",
75
+ });
76
+ return operation ? serviceApiOwnKeys(operation, bodyPermissions) : [];
77
+ };
78
+ };
54
79
  const refused = (message, param) => new CliError("validation_error", message, { reason: "crm.record-field", sent: false, ...(param ? { param } : {}) });
55
80
  /** Our fields that write one key of the service together, by that key: Attio's name and its parts. */
56
81
  const sharedOf = (one) => {
@@ -81,7 +106,7 @@ const merged = (entries, list) => {
81
106
  */
82
107
  export const crmWriterFromManifest = (input, options) => {
83
108
  const manifest = parseCrmManifest(input, options.api);
84
- const capabilities = capabilitiesOf(manifest);
109
+ const capabilities = capabilitiesOf(manifest, options.activities);
85
110
  if (!capabilities)
86
111
  throw new CliError("configuration_error", "source manifest: writes: it describes no writes", {
87
112
  reason: "manifest.invalid",
@@ -255,9 +280,15 @@ export const crmWriterFromManifest = (input, options) => {
255
280
  throw refused(`the ${kind}'s pipeline ${item.pipeline} has no ${outcome} stage in ${service}`);
256
281
  return stage.externalId;
257
282
  };
283
+ const { activities } = options;
284
+ const complete = activities?.complete?.bind(activities);
258
285
  return {
259
286
  provider: manifest.provider,
260
287
  capabilities,
288
+ ...(activities ? { createActivity: (draft) => activities.create(draft, send) } : {}),
289
+ ...(complete && capabilities.activities?.includes("task")
290
+ ? { completeActivity: (externalId) => complete(externalId, send) }
291
+ : {}),
261
292
  async create(kind, draft, written) {
262
293
  const one = specOf(kind, "create");
263
294
  const answer = await sent(one.create, { values: await valuesOf(kind, one, draft) });
@@ -289,10 +320,17 @@ export const crmWriterFromManifest = (input, options) => {
289
320
  * `api` keys of each operation it sends as `alsoChecks`. The writes' guard asks before each one and journals it.
290
321
  */
291
322
  export const crmManifestWrites = (input, options) => {
292
- const { manifest: api, service, source, app, settings, self, ownedByDefault, env, warn } = options;
323
+ const { manifest: api, service, source, app, settings, self, ownedByDefault, env, warn, activities } = options;
293
324
  return {
294
- writer: crmWriterFromManifest(input, { api, service, send: serviceApiSend(options), source }),
325
+ writer: crmWriterFromManifest(input, {
326
+ api,
327
+ service,
328
+ send: serviceApiSend(options),
329
+ source,
330
+ ...(activities ? { activities } : {}),
331
+ }),
295
332
  alsoChecks: crmManifestWriteKeys(input, api, options.bodyPermissions),
333
+ ...(activities ? { activityChecks: crmManifestActivityKeys(api, activities, options.bodyPermissions) } : {}),
296
334
  app,
297
335
  settings,
298
336
  ...(self === undefined ? {} : { self }),
@@ -150,9 +150,10 @@ export declare const CRM_WRITE_KEYS: readonly PermissionKey[];
150
150
  /**
151
151
  * Every key a CRM write command may check beyond its own path, for `commandPermissions({ alsoChecks })`, so its
152
152
  * `--dry-run` names each: a stage implies the move key and a won or lost one the close key, an owner other than the
153
- * sign-in's `crm.assign-others`, and `also` the CLI's own (the same `CrmWrites.alsoChecks` the real run checks).
153
+ * sign-in's `crm.assign-others`, and `also` the CLI's own (the same `CrmWrites.alsoChecks` the real run checks), and
154
+ * `activities` those of an activity write (`CrmWrites.activityChecks`).
154
155
  */
155
- export declare const crmAlsoChecks: (also?: (kind: CrmKind, verb: CrmVerb) => readonly PermissionKey[]) => (path: readonly string[]) => readonly (PermissionKey | ConditionalKey)[];
156
+ export declare const crmAlsoChecks: (also?: (kind: CrmKind, verb: CrmVerb) => readonly PermissionKey[], activities?: (write: CrmActivityWrite | "close") => readonly PermissionKey[]) => (path: readonly string[]) => readonly (PermissionKey | ConditionalKey)[];
156
157
  /**
157
158
  * Built in, and only ever tightening (WC-PERM-7): an ordinary change goes ahead, a deletion asks, and a record is not
158
159
  * given to somebody else until the owner allows it.
@@ -21,12 +21,18 @@ const VERB_OF = {
21
21
  /**
22
22
  * Every key a CRM write command may check beyond its own path, for `commandPermissions({ alsoChecks })`, so its
23
23
  * `--dry-run` names each: a stage implies the move key and a won or lost one the close key, an owner other than the
24
- * sign-in's `crm.assign-others`, and `also` the CLI's own (the same `CrmWrites.alsoChecks` the real run checks).
24
+ * sign-in's `crm.assign-others`, and `also` the CLI's own (the same `CrmWrites.alsoChecks` the real run checks), and
25
+ * `activities` those of an activity write (`CrmWrites.activityChecks`).
25
26
  */
26
- export const crmAlsoChecks = (also) => (path) => {
27
+ export const crmAlsoChecks = (also, activities) => (path) => {
27
28
  const [noun, command] = path;
29
+ if (noun === "activities" && command === "close" && path.length === 2)
30
+ return activities?.("close") ?? [];
28
31
  if (noun === "activities" && command === "create" && path.length === 2)
29
- return [{ key: CRM_ASSIGN_OTHERS_KEY, when: "--owner other than the sign-in's user" }];
32
+ return [
33
+ { key: CRM_ASSIGN_OTHERS_KEY, when: "--owner other than the sign-in's user" },
34
+ ...["comment", "task"].flatMap((write) => (activities?.(write) ?? []).map((key) => ({ key, when: `a ${write}` }))),
35
+ ];
30
36
  const kind = noun === undefined ? undefined : PLURALS[noun];
31
37
  const verb = command === undefined ? undefined : VERB_OF[command];
32
38
  if (path.length !== 2 || kind === undefined || verb === undefined)
@@ -24,6 +24,8 @@ export interface CrmWrites extends ProfileWrites {
24
24
  * `crmAlsoChecks` so `--dry-run` names them.
25
25
  */
26
26
  alsoChecks?: (kind: CrmKind, verb: CrmVerb) => readonly PermissionKey[];
27
+ /** The same for an activity write, a comment, a task or a task marked done; pass it to `crmAlsoChecks` too. */
28
+ activityChecks?: (write: CrmActivityWrite | "close") => readonly PermissionKey[];
27
29
  }
28
30
  export interface CrmWriteContext {
29
31
  store: MessageStore;
@@ -552,9 +552,12 @@ const activityTargetOf = async (context, given) => {
552
552
  throw new CliError("validation_error", `--subject takes deal:<id>, lead:<id>, person:<id> or organization:<id> as the copy's lists and deals show give ` +
553
553
  `them, or person:crm:<id> or organization:crm:<id> by the CRM's id; got ${given}`, { reason: "ref.malformed", param: "--subject" });
554
554
  };
555
- const activityKeys = async (context, key, owner) => ({
555
+ const activityKeys = async (context, key, owner, write) => ({
556
556
  key,
557
- extra: owner !== undefined && owner !== (await selfOf(context)) ? [CRM_ASSIGN_OTHERS_KEY] : [],
557
+ extra: [
558
+ ...(owner !== undefined && owner !== (await selfOf(context)) ? [CRM_ASSIGN_OTHERS_KEY] : []),
559
+ ...(context.writes.activityChecks?.(write) ?? []),
560
+ ],
558
561
  });
559
562
  /** The CRM's answer into the store, as a sync saves it; a failure names the activity, which the CRM has written. */
560
563
  const keptActivity = async (context, activity, operationId) => {
@@ -615,7 +618,7 @@ export const createCrmActivity = async (context, kind, input, options = {}) => {
615
618
  on: targets.map(({ kind, externalId }) => ({ kind, externalId })),
616
619
  };
617
620
  const operationId = operationOf(context, options.operationId);
618
- const activity = await written(context, await activityKeys(context, "activities.create", owner), operationId, () => create(draft, { operationId }));
621
+ const activity = await written(context, await activityKeys(context, "activities.create", owner, kind), operationId, () => create(draft, { operationId }));
619
622
  const stored = await keptActivity(context, activity, operationId);
620
623
  return { operationId, activity, stored, on: await answeredTargets(context, activity, targets) };
621
624
  };
@@ -630,7 +633,7 @@ export const completeCrmActivity = async (context, externalId, options = {}) =>
630
633
  reason: "ref.malformed",
631
634
  });
632
635
  const operationId = operationOf(context, options.operationId);
633
- const activity = await written(context, await activityKeys(context, "activities.close", undefined), operationId, () => complete(externalId, { operationId }));
636
+ const activity = await written(context, await activityKeys(context, "activities.close", undefined, "close"), operationId, () => complete(externalId, { operationId }));
634
637
  const stored = await keptActivity(context, activity, operationId);
635
638
  return { operationId, activity, stored, on: await answeredTargets(context, activity, []) };
636
639
  };
@@ -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" | "notification-address" | "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" | "auto-submitted" | "null-return-path" | "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». */
@@ -28,18 +28,22 @@ export interface MailHeaders {
28
28
  }
29
29
  export declare const unfold: (text: string) => string;
30
30
  export declare const field: (unfolded: string, name: string) => string | undefined;
31
+ /** The verdicts in Gmail's own Authentication-Results. */
32
+ export declare const authOf: (unfolded: string) => AuthVerdicts | undefined;
31
33
  /**
32
- * The verdicts in Gmail's own Authentication-Results. Only the copy Gmail stamps as mx.google.com counts: a sender
33
- * can add one under any other name, and Gmail removes forged copies under its own (RFC 8601 §5).
34
+ * The header fields a DKIM signature Gmail passed covers, when that signature's domain is the From's own (its
35
+ * registrable domain). A sender writes every header itself; only a signature of its own domain vouches for one.
36
+ * Without Gmail's stamp nothing is trusted: other servers' Authentication-Results may be the sender's own.
34
37
  */
35
- export declare const authOf: (unfolded: string) => AuthVerdicts | undefined;
38
+ export declare const signedFieldsOf: (unfolded: string, from: string | undefined) => Set<string>;
36
39
  export declare const addressesOf: (value: string | undefined) => string[];
37
40
  /** The header fields of one email, from its header text. */
38
41
  export declare const headersOf: (text: string) => MailHeaders;
39
42
  /** The header fields of a whole email, as `headersOf` reads them from a listing. */
40
43
  export declare const headersOfRaw: (raw: Uint8Array) => MailHeaders;
41
44
  /**
42
- * List-Id, the bulk-mail fields, Reply-To and Gmail's SPF, DKIM and DMARC verdicts of a whole email, kept on mail
43
- * stored in full so a rule or a sender score can be worked out from the store later. Names are lower case.
45
+ * List-Id, the bulk-mail fields, Reply-To, Gmail's SPF, DKIM and DMARC verdicts and what marks a program or a list
46
+ * (`programSignalsOf`) of a whole email, kept on mail stored in full so a rule, a sender score or a person's kind can
47
+ * be worked out from the store later. Names are lower case.
44
48
  */
45
49
  export declare const mailHeadersOf: (raw: Uint8Array) => Record<string, string | boolean>;
@@ -1,4 +1,5 @@
1
1
  import { decodeWords } from "postal-mime";
2
+ import { registrableOf } from "./score.js";
2
3
  /**
3
4
  * The header fields memo reads at list time: enough to group mail by sender, apply the owner's rules and keep
4
5
  * an envelope of the mail a rule records without its text.
@@ -8,11 +9,13 @@ export const unfold = (text) => text.replace(/\r?\n[ \t]+/g, " ");
8
9
  export const field = (unfolded, name) => new RegExp(`^${name}:[ \\t]*(.*?)\\r?$`, "im").exec(unfolded)?.[1];
9
10
  const fieldsOf = (unfolded, name) => [...unfolded.matchAll(new RegExp(`^${name}:[ \\t]*(.*?)\\r?$`, "gim"))].map(([, value]) => value);
10
11
  /**
11
- * The verdicts in Gmail's own Authentication-Results. Only the copy Gmail stamps as mx.google.com counts: a sender
12
- * can add one under any other name, and Gmail removes forged copies under its own (RFC 8601 §5).
12
+ * Gmail's own Authentication-Results. Only the copy Gmail stamps as mx.google.com counts: a sender can add one under
13
+ * any other name, and Gmail removes forged copies under its own (RFC 8601 §5).
13
14
  */
15
+ const gmailStampOf = (unfolded) => fieldsOf(unfolded, "Authentication-Results").find((value) => /^mx\.google\.com\s*;/i.test(value));
16
+ /** The verdicts in Gmail's own Authentication-Results. */
14
17
  export const authOf = (unfolded) => {
15
- const stamped = fieldsOf(unfolded, "Authentication-Results").find((value) => /^mx\.google\.com\s*;/i.test(value));
18
+ const stamped = gmailStampOf(unfolded);
16
19
  if (stamped === undefined)
17
20
  return undefined;
18
21
  const results = [...stamped.matchAll(/\b(spf|dkim|dmarc)=([a-z]+)/gi)].map(([, method, result]) => [
@@ -28,6 +31,58 @@ export const authOf = (unfolded) => {
28
31
  }
29
32
  return Object.keys(verdicts).length ? verdicts : undefined;
30
33
  };
34
+ const tagsOf = (value) => new Map(value.split(";").flatMap((tag) => {
35
+ const at = tag.indexOf("=");
36
+ return at === -1 ? [] : [[tag.slice(0, at).trim().toLowerCase(), tag.slice(at + 1).replace(/\s+/g, "")]];
37
+ }));
38
+ /**
39
+ * The header fields a DKIM signature Gmail passed covers, when that signature's domain is the From's own (its
40
+ * registrable domain). A sender writes every header itself; only a signature of its own domain vouches for one.
41
+ * Without Gmail's stamp nothing is trusted: other servers' Authentication-Results may be the sender's own.
42
+ */
43
+ export const signedFieldsOf = (unfolded, from) => {
44
+ const stamped = gmailStampOf(unfolded);
45
+ if (stamped === undefined || from === undefined)
46
+ return new Set();
47
+ const passed = [...stamped.matchAll(/\bdkim=pass\b[^;]*?\bheader\.[id]=([^\s;]+)/gi)].map(([, identity]) => identity.slice(identity.lastIndexOf("@") + 1).toLowerCase());
48
+ const own = registrableOf(from);
49
+ const signed = new Set();
50
+ for (const signature of fieldsOf(unfolded, "DKIM-Signature")) {
51
+ const tags = tagsOf(signature);
52
+ const domain = tags.get("d")?.toLowerCase();
53
+ if (domain === undefined || registrableOf(domain) !== own)
54
+ continue;
55
+ if (!passed.some((one) => one === domain || one.endsWith(`.${domain}`)))
56
+ continue;
57
+ for (const name of (tags.get("h") ?? "").split(":"))
58
+ if (name !== "")
59
+ signed.add(name.toLowerCase());
60
+ }
61
+ return signed;
62
+ };
63
+ /**
64
+ * What says a program or a list sent the mail, each only when DKIM vouches for it (`signedFieldsOf`):
65
+ * `Auto-Submitted` other than `no` (RFC 3834), the one-click unsubscribe of RFC 8058 and Google's `Feedback-ID`.
66
+ * An empty Return-Path is the receiving server's, not the sender's, and marks a program unless it is an auto-reply,
67
+ * which RFC 3834 sends that way too: a person's out-of-office makes no bot.
68
+ */
69
+ const programSignalsOf = (unfolded, from) => {
70
+ const signed = signedFieldsOf(unfolded, from);
71
+ const submitted = field(unfolded, "Auto-Submitted")
72
+ ?.trim()
73
+ .toLowerCase()
74
+ .split(/[\s;(]/)[0];
75
+ const generated = submitted !== undefined && submitted !== "" && submitted !== "no" && submitted !== "auto-replied";
76
+ const oneClick = /list-unsubscribe\s*=\s*one-click/i.test(field(unfolded, "List-Unsubscribe-Post") ?? "");
77
+ return {
78
+ ...(generated && signed.has("auto-submitted") ? { "auto-submitted": submitted } : {}),
79
+ ...(oneClick && signed.has("list-unsubscribe-post") ? { "list-unsubscribe-post": true } : {}),
80
+ ...(field(unfolded, "Feedback-ID") !== undefined && signed.has("feedback-id") ? { "feedback-id": true } : {}),
81
+ ...(/^\s*<\s*>/.test(field(unfolded, "Return-Path") ?? "") && submitted !== "auto-replied"
82
+ ? { "null-return-path": true }
83
+ : {}),
84
+ };
85
+ };
31
86
  export const addressesOf = (value) => {
32
87
  if (value === undefined)
33
88
  return [];
@@ -74,19 +129,22 @@ const headTextOf = (raw) => {
74
129
  /** The header fields of a whole email, as `headersOf` reads them from a listing. */
75
130
  export const headersOfRaw = (raw) => headersOf(headTextOf(raw));
76
131
  /**
77
- * List-Id, the bulk-mail fields, Reply-To and Gmail's SPF, DKIM and DMARC verdicts of a whole email, kept on mail
78
- * stored in full so a rule or a sender score can be worked out from the store later. Names are lower case.
132
+ * List-Id, the bulk-mail fields, Reply-To, Gmail's SPF, DKIM and DMARC verdicts and what marks a program or a list
133
+ * (`programSignalsOf`) of a whole email, kept on mail stored in full so a rule, a sender score or a person's kind can
134
+ * be worked out from the store later. Names are lower case.
79
135
  */
80
136
  export const mailHeadersOf = (raw) => {
81
137
  const unfolded = unfold(headTextOf(raw));
82
138
  const listId = listIdOf(field(unfolded, "List-Id"));
83
139
  const precedence = field(unfolded, "Precedence")?.trim().toLowerCase();
84
140
  const [replyTo] = addressesOf(field(unfolded, "Reply-To"));
141
+ const [from] = addressesOf(field(unfolded, "From"));
85
142
  return {
86
143
  ...(listId ? { "list-id": listId } : {}),
87
144
  ...(replyTo === undefined ? {} : { "reply-to": replyTo }),
88
145
  ...authOf(unfolded),
89
146
  ...(field(unfolded, "List-Unsubscribe") === undefined ? {} : { "list-unsubscribe": true }),
90
147
  ...(precedence ? { precedence } : {}),
148
+ ...programSignalsOf(unfolded, from),
91
149
  };
92
150
  };
@@ -104,6 +104,7 @@ export type { RelationRole, RelationRoles } from "./sqlite/relation-roles.js";
104
104
  export type { RelationsStore, ReportedIssue, ReportedRelation, ReportedScope, ReportedSync, } from "./sqlite/reported-relations.js";
105
105
  export type { AuthorInfo, Party, Reviewed, Written } from "./sqlite/reviewed.js";
106
106
  export { fillSearchIndex, resetSearchIndex, type SearchIndexFill, type SearchIndexState, searchIndexState, } from "./sqlite/search-index.js";
107
+ export { REACHES, type Reach, type SenderSignal } from "./sqlite/sender-signals.js";
107
108
  export type { ChallengeInput, SourceReviewDecision } from "./sqlite/source-review.js";
108
109
  export type { PriceFilter, PriceInput, Subscription, SubscriptionDetail, SubscriptionFields, SubscriptionFilter, SubscriptionInput, SubscriptionPrice, SubscriptionsStore, SubscriptionUpdate, } from "./sqlite/subscriptions.js";
109
110
  export type { SyncStateSave } from "./sqlite/sync.js";
@@ -52,6 +52,7 @@ export { ALWAYS_SHOWN, PERSON_TIES, SMALL_GROUP_MEMBERS, } from "./sqlite/person
52
52
  export { assertGenericAction, PROPOSAL_STATUSES, proposerOfAction, } from "./sqlite/proposed-actions.js";
53
53
  export { waitingPointer, } from "./sqlite/records.js";
54
54
  export { fillSearchIndex, resetSearchIndex, searchIndexState, } from "./sqlite/search-index.js";
55
+ export { REACHES } from "./sqlite/sender-signals.js";
55
56
  export { PROJECT_TASK_FIELDS, TASK_SORTS, withoutField } from "./sqlite/task-board.js";
56
57
  export { certaintyOf } from "./sqlite/task-close.js";
57
58
  export { TASK_PAIR_DECISIONS } from "./sqlite/task-pairs.js";
@@ -22,6 +22,7 @@ export const accountMessagesOver = (context) => {
22
22
  if (upsertMessage(key, accountKey, chatKey, message, via, seenAt) && countUnread)
23
23
  messageWrites.countUnread(context, chatKey, message);
24
24
  }
25
+ messageWrites.linkThreadChildren(context, chatKey, messages.filter((message) => message.scheduledFor === undefined).map((message) => message.id));
25
26
  for (const { messageId, vote } of votes)
26
27
  messageWrites.saveVote(context, accountKey, key.provider, chatKey, messageId, vote);
27
28
  for (const { messageId, reaction } of reactions)
@@ -6,7 +6,7 @@ export interface NewestEmail {
6
6
  /** ms: when it was received, or sent when that is unknown. */
7
7
  at: number;
8
8
  outgoing: boolean;
9
- /** The mailbox's own address is in To or Cc. */
9
+ /** One of the mailbox's own addresses (its own, an alias in `mail_own_addresses`) is in To or Cc. */
10
10
  addressed: boolean;
11
11
  /** Filed in the mailbox of mail sent to many. */
12
12
  bulk: boolean;
@@ -1,6 +1,7 @@
1
1
  import { contextEvidenceFingerprint } from "../../context/evidence.js";
2
2
  import { formatLocator } from "../../domain/locator.js";
3
3
  import { int, str } from "./events.js";
4
+ import { OWN_MAIL_ADDRESSES } from "./own-identities.js";
4
5
  /** `tasks agenda` fields over `threadActivity`'s threads: an email thread counts as a dialog. */
5
6
  export const MAIL_AGENDA_COLUMNS = { chat_kind: { type: "enum", sql: "'dialog'" } };
6
7
  // The thread's own time is the Date header where sync stored one, so a thread is picked by it; the newest email is
@@ -10,7 +11,9 @@ const ACTIVITY = `
10
11
  e.external_id, coalesce(e.received_at, e.sent_at) AS at,
11
12
  coalesce(e.outgoing, lower(e.from_address) = lower(a.external_id)) AS outgoing,
12
13
  EXISTS (SELECT 1 FROM email_recipients r WHERE r.email_id = e.id AND r.role IN ('to', 'cc')
13
- AND lower(r.address) = lower(a.external_id)) AS addressed,
14
+ AND (lower(r.address) = lower(a.external_id) OR lower(trim(r.address)) IN (SELECT j.value FROM sync_cursors s,
15
+ json_each(CASE WHEN json_valid(s.value) THEN s.value ELSE '[]' END) j
16
+ WHERE s.account_id = a.id AND s.key = '${OWN_MAIL_ADDRESSES}'))) AS addressed,
14
17
  EXISTS (SELECT 1 FROM email_mailboxes m JOIN mailboxes b ON b.id = m.mailbox_id
15
18
  WHERE m.email_id = e.id AND b.kind = 'bulk') AS bulk,
16
19
  coalesce(json_extract(e.headers, '$."list-id"'), json_extract(e.metadata, '$.listId')) IS NOT NULL AS list,
@@ -1,6 +1,11 @@
1
1
  import type { Delivery, Id, Message, PersonReaction, PollVote, Provider, Reactions, Reactor } from "../../domain/models.js";
2
2
  import type { AccountKey, DeletionScope } from "../types.js";
3
3
  import type { StoreContext } from "./open.js";
4
+ /**
5
+ * Points replies saved before their thread's root at it. Run once per page: no index covers `thread_external_id`,
6
+ * so each run reads the whole chat, and once per message made a sync slow down as the chat grew (tg-cli #917).
7
+ */
8
+ export declare const linkThreadChildren: (context: StoreContext, chatKey: number, rootIds: readonly Id[]) => void;
4
9
  export declare const upsertMessage: (context: StoreContext, key: AccountKey, accountKey: number, chatKey: number, received: Message, via: string, seenAt?: number) => boolean;
5
10
  /**
6
11
  * One more unread for a message from someone else that the store first saw now, sent after the messenger's count was
@@ -114,6 +114,19 @@ const fieldsOf = (message, sender) => ({
114
114
  normalizedText: normalize(message.text),
115
115
  normalizerVersion: NORMALIZER_VERSION,
116
116
  });
117
+ /**
118
+ * Points replies saved before their thread's root at it. Run once per page: no index covers `thread_external_id`,
119
+ * so each run reads the whole chat, and once per message made a sync slow down as the chat grew (tg-cli #917).
120
+ */
121
+ export const linkThreadChildren = (context, chatKey, rootIds) => {
122
+ if (rootIds.length === 0)
123
+ return;
124
+ context.database
125
+ .prepare(`UPDATE messages SET thread_root_id=(SELECT root.id FROM messages root
126
+ WHERE root.chat_id=messages.chat_id AND root.external_id=messages.thread_external_id)
127
+ WHERE chat_id=? AND thread_root_id IS NULL AND thread_external_id IN (SELECT value FROM json_each(?))`)
128
+ .run(chatKey, JSON.stringify(rootIds.map(String)));
129
+ };
117
130
  export const upsertMessage = (context, key, accountKey, chatKey, received, via, seenAt) => {
118
131
  const { orm, now } = context;
119
132
  const message = withoutBotTokensIn(received);
@@ -224,9 +237,6 @@ export const upsertMessage = (context, key, accountKey, chatKey, received, via,
224
237
  .prepare("UPDATE messages SET thread_root_id=(SELECT id FROM messages WHERE chat_id=? AND external_id=?) WHERE id=?")
225
238
  .run(chatKey, root, pk);
226
239
  }
227
- context.database
228
- .prepare("UPDATE messages SET thread_root_id=? WHERE chat_id=? AND thread_external_id=? AND thread_root_id IS NULL")
229
- .run(pk, chatKey, message.id);
230
240
  const heardFirst = context.database
231
241
  .prepare("UPDATE message_transcripts SET message_id=? WHERE chat_id=? AND message_external_id=? AND message_id IS NULL")
232
242
  .run(pk, chatKey, message.id).changes;
@@ -1,6 +1,7 @@
1
1
  import { type KindSignal, type PersonKind } from "../../domain/person-kinds.js";
2
2
  import { type CacheDatabase } from "../driver.js";
3
3
  import { type ShownBecause } from "./person-ties.js";
4
+ import { type Reach, type SenderSignal } from "./sender-signals.js";
4
5
  export declare const PEOPLE_SORTS: readonly ["interactions", "recent", "name", "tasks"];
5
6
  export type PeopleSort = (typeof PEOPLE_SORTS)[number];
6
7
  export interface PeopleListOptions {
@@ -39,6 +40,10 @@ export interface ListedPerson {
39
40
  lastContact: string | null;
40
41
  /** Why they are shown; empty for someone hidden by default. */
41
42
  ties: ShownBecause[];
43
+ /** How their messages reached the owner (`senderSignalsOf`); `null` when nothing says. Worked out for the page. */
44
+ reach: Reach | null;
45
+ /** What their mail and addresses show about who writes and how it reached the owner. Worked out for the page. */
46
+ signals: SenderSignal[];
42
47
  }
43
48
  export interface PeopleList {
44
49
  items: ListedPerson[];
@@ -7,6 +7,7 @@ import { isQueryOnly } from "../driver.js";
7
7
  import { fold } from "../normalize.js";
8
8
  import { mergedAwaySql } from "./merged-persons.js";
9
9
  import { ALWAYS_SHOWN, shownReasons } from "./person-ties.js";
10
+ import { senderSignalsOf, sentMailOf } from "./sender-signals.js";
10
11
  import { mergedAssignees } from "./task-board.js";
11
12
  import { hiddenTestPeople } from "./test-people.js";
12
13
  import { read, writeBatch } from "./transaction.js";
@@ -48,7 +49,9 @@ const TWO_WAY = "SELECT DISTINCT s.sender_identity_id AS identity_id FROM messag
48
49
  "AND s.sender_identity_id IS NOT NULL AND s.chat_id IN (SELECT c.id FROM chats c WHERE c.kind = 'dialog' " +
49
50
  "AND EXISTS (SELECT 1 FROM messages o WHERE o.chat_id = c.id AND o.outgoing = 1))";
50
51
  const MAIL_COUNTS = (scope) => "SELECT l.person_id AS person, count(*) AS n, sum(EXISTS (SELECT 1 FROM email_mailboxes m " +
51
- "JOIN mailboxes b ON b.id = m.mailbox_id WHERE m.email_id = e.id AND b.kind = 'bulk')) AS bulk " +
52
+ "JOIN mailboxes b ON b.id = m.mailbox_id WHERE m.email_id = e.id AND b.kind = 'bulk')) AS bulk, " +
53
+ "sum(json_extract(e.headers, '$.\"auto-submitted\"') IS NOT NULL) AS auto, " +
54
+ "sum(json_extract(e.headers, '$.\"null-return-path\"') IS 1) AS null_return " +
52
55
  "FROM emails e JOIN identity_links l ON l.identity_id = e.from_identity_id " +
53
56
  `WHERE e.outgoing IS NOT 1 AND e.deleted_at IS NULL AND ${IN_SCOPE(scope, "l.person_id")} GROUP BY 1`;
54
57
  const IDENTITIES = (scope) => "SELECT l.person_id AS person, i.id, i.provider, i.external_id, i.name, i.username, i.phone, i.email, i.bot " +
@@ -168,6 +171,11 @@ const kindOf = (shown, facts, ties, mail, test) => {
168
171
  ...(mail !== undefined && mail.n >= BULK_MIN && mail.bulk * 2 > mail.n ? ["bulk-mail"] : []),
169
172
  ...(facts?.neverReplied ? ["bulk-never-replied"] : []),
170
173
  ...(isAutomatedName(shown) ? ["automated-name"] : []),
174
+ // A guess from headers never outweighs mail the owner wrote them.
175
+ ...(mail !== undefined && !ties.includes("mail") && mail.auto * 2 > mail.n ? ["auto-submitted"] : []),
176
+ ...(mail !== undefined && !ties.includes("mail") && mail.nullReturn * 2 > mail.n
177
+ ? ["null-return-path"]
178
+ : []),
171
179
  ];
172
180
  // One mailbox's newsletter signal must not hide someone the owner talks to in a private chat.
173
181
  if (automated.length > 0 && (facts?.bot || !facts?.twoWay))
@@ -195,7 +203,10 @@ const classified = (database, people, scope, reasons = shownReasons(database, sc
195
203
  const mail = new Map(database
196
204
  .prepare(MAIL_COUNTS(scope))
197
205
  .all(...scopeParams(scope))
198
- .map((row) => [Number(row.person), { n: Number(row.n), bulk: Number(row.bulk) }]));
206
+ .map((row) => [
207
+ Number(row.person),
208
+ { n: Number(row.n), bulk: Number(row.bulk), auto: Number(row.auto), nullReturn: Number(row.null_return) },
209
+ ]));
199
210
  return people.map(({ id, name, owner }) => {
200
211
  const own = facts.get(id);
201
212
  const contact = { username: own?.username ?? null, phone: own?.phone ?? null, email: own?.email ?? null };
@@ -217,15 +228,27 @@ const classified = (database, people, scope, reasons = shownReasons(database, sc
217
228
  usernameSource: own?.usernameSource ?? null,
218
229
  messagesFrom: (own?.messages ?? 0) + (mail.get(id)?.n ?? 0),
219
230
  ties,
231
+ emails: own?.emails ?? [],
232
+ twoWay: own?.twoWay ?? false,
220
233
  };
221
234
  });
222
235
  };
223
236
  const withLastContact = (database, people, known) => {
224
237
  const at = known ??
225
238
  lastContacts(database, people.map(({ id }) => id));
226
- return people.map(({ id, nameOrder: _, ...person }) => {
239
+ const sent = sentMailOf(database, people.map(({ id }) => id));
240
+ return people.map(({ id, nameOrder: _, emails, twoWay, ...person }) => {
227
241
  const time = at.get(id);
228
- return { ...person, lastContact: time === undefined ? null : new Date(time).toISOString() };
242
+ const { ties } = person;
243
+ return {
244
+ ...person,
245
+ lastContact: time === undefined ? null : new Date(time).toISOString(),
246
+ ...senderSignalsOf(sent.get(id) ?? [], {
247
+ addresses: emails,
248
+ ownerWrote: twoWay || ties.includes("mail"),
249
+ chatted: ties.includes("chat") || ties.includes("small-group"),
250
+ }),
251
+ };
229
252
  });
230
253
  };
231
254
  /** Sorted as read, case and accents aside; a name with nothing to read goes last. */
@@ -235,7 +258,7 @@ const byName = (a, b) => a.nameOrder < b.nameOrder ? -1 : a.nameOrder > b.nameOr
235
258
  * Bump when what decides a kind, a name's order or a count changes in code (the word lists, `BULK_MIN`, the ties):
236
259
  * every stored one is worked out again on the next list.
237
260
  */
238
- const KIND_RULES = "5";
261
+ const KIND_RULES = "6";
239
262
  const RULES_KEY = "people.kind_rules";
240
263
  /** Past this many people to work out, one pass over everyone beats a lookup per person. */
241
264
  const WHOLE_PASS = 20_000;
@@ -5,7 +5,7 @@ import { calendarWritesOver } from "./calendar.js";
5
5
  import { chatPkFor, findChatPk, raiseLastMessageAt, upsertChat, writeMembers } from "./chats.js";
6
6
  import { seenIdentity } from "./identities.js";
7
7
  import { COUNTERPART_ROLE, linkKind } from "./link-kinds.js";
8
- import { tombstone, upsertMessage } from "./messages.js";
8
+ import { linkThreadChildren, tombstone, upsertMessage } from "./messages.js";
9
9
  import { requiredThing } from "./notes.js";
10
10
  import { e164Of } from "./person-matcher.js";
11
11
  import { importedIdentity, linkToPerson } from "./record-matching.js";
@@ -88,6 +88,7 @@ const saveSms = (projection, tools, revive = false) => {
88
88
  };
89
89
  // Seen after its tombstone, the messenger path takes a deleted message back, its text with it.
90
90
  upsertMessage(context, account, account.pk, chatKey, message, importedBy(source).source, revive ? context.now() + 1 : undefined);
91
+ linkThreadChildren(context, chatKey, [message.id]);
91
92
  raiseLastMessageAt(context, chatKey, sentAt);
92
93
  return formatReference({
93
94
  type: "message",
@@ -0,0 +1,42 @@
1
+ import type { CacheDatabase } from "../driver.js";
2
+ /**
3
+ * How a sender's messages reached the owner: written to them or a few people, in a large group or a discussion list,
4
+ * or sent to many readers who cannot answer in place.
5
+ */
6
+ export declare const REACHES: readonly ["direct", "group", "broadcast"];
7
+ export type Reach = (typeof REACHES)[number];
8
+ /** What the mail of one sender shows about who writes and how it reached the owner. */
9
+ export type SenderSignal = "auto-submitted" | "null-return-path" | "no-reply" | "one-click-unsubscribe" | "feedback-id" | "bulk-mail" | "discussion-list" | "many-recipients" | "undisclosed-recipients";
10
+ /** One email a sender sent the owner, as the store keeps it (`mailHeadersOf`, the mailboxes, the recipients). */
11
+ export interface SentMail {
12
+ autoSubmitted: boolean;
13
+ nullReturnPath: boolean;
14
+ oneClick: boolean;
15
+ feedbackId: boolean;
16
+ /** In the bulk box: List-Id, List-Unsubscribe or `Precedence: bulk`. */
17
+ bulk: boolean;
18
+ /** A List-Id at least `DISCUSSION_SENDERS` addresses send to. */
19
+ discussionList: boolean;
20
+ /** To and Cc together; `null` when the store holds no recipients for it (mail recorded as an envelope). */
21
+ recipients: number | null;
22
+ }
23
+ /** A list three people write to is a discussion; one sender, even under `+tag` addresses, is a newsletter. */
24
+ export declare const DISCUSSION_SENDERS = 3;
25
+ /**
26
+ * A sender's signals and reach, worked out from their mail alone. Reach is the one most of their mail reached the
27
+ * owner by, the wider on a tie. Mail the owner wrote them, or a private chat both wrote in, makes it `direct`
28
+ * whatever their other mail shows; with no mail, a one-to-one chat or a small group does. `null`: nothing says.
29
+ */
30
+ export declare const senderSignalsOf: (mail: readonly SentMail[], { addresses, ownerWrote, chatted }: {
31
+ addresses: readonly string[];
32
+ ownerWrote: boolean;
33
+ chatted: boolean;
34
+ }) => {
35
+ signals: SenderSignal[];
36
+ reach: Reach | null;
37
+ };
38
+ /**
39
+ * The mail each of these people sent the owner, as `senderSignalsOf` reads it. Asked for a page of people only: it
40
+ * reads every stored email's List-Id once to tell a discussion list from a newsletter.
41
+ */
42
+ export declare const sentMailOf: (database: CacheDatabase, people: readonly number[]) => Map<number, SentMail[]>;
@@ -0,0 +1,106 @@
1
+ import { isNoReplyAddress } from "../../domain/addresses.js";
2
+ import { SMALL_GROUP_MEMBERS } from "./person-ties.js";
3
+ /**
4
+ * How a sender's messages reached the owner: written to them or a few people, in a large group or a discussion list,
5
+ * or sent to many readers who cannot answer in place.
6
+ */
7
+ export const REACHES = ["direct", "group", "broadcast"];
8
+ /** A list three people write to is a discussion; one sender, even under `+tag` addresses, is a newsletter. */
9
+ export const DISCUSSION_SENDERS = 3;
10
+ const reachOfOne = (mail) => {
11
+ if (mail.discussionList)
12
+ return { reach: "group", signal: "discussion-list" };
13
+ if (mail.oneClick)
14
+ return { reach: "broadcast", signal: "one-click-unsubscribe" };
15
+ if (mail.feedbackId)
16
+ return { reach: "broadcast", signal: "feedback-id" };
17
+ if (mail.bulk)
18
+ return { reach: "broadcast", signal: "bulk-mail" };
19
+ // The owner missing from a To or Cc that names others proves nothing: an alias the store does not know looks so.
20
+ if (mail.recipients === 0)
21
+ return { reach: "broadcast", signal: "undisclosed-recipients" };
22
+ if (mail.recipients !== null && mail.recipients > SMALL_GROUP_MEMBERS)
23
+ return { reach: "group", signal: "many-recipients" };
24
+ return { reach: "direct" };
25
+ };
26
+ /** More than half of their mail: one misfiled letter decides nothing. */
27
+ const most = (mail, holds) => mail.filter(holds).length * 2 > mail.length;
28
+ /**
29
+ * A sender's signals and reach, worked out from their mail alone. Reach is the one most of their mail reached the
30
+ * owner by, the wider on a tie. Mail the owner wrote them, or a private chat both wrote in, makes it `direct`
31
+ * whatever their other mail shows; with no mail, a one-to-one chat or a small group does. `null`: nothing says.
32
+ */
33
+ export const senderSignalsOf = (mail, { addresses, ownerWrote, chatted }) => {
34
+ const signals = new Set();
35
+ if (mail.length > 0 && most(mail, (one) => one.autoSubmitted))
36
+ signals.add("auto-submitted");
37
+ if (mail.length > 0 && most(mail, (one) => one.nullReturnPath))
38
+ signals.add("null-return-path");
39
+ if (addresses.some(isNoReplyAddress))
40
+ signals.add("no-reply");
41
+ const votes = new Map();
42
+ for (const one of mail) {
43
+ const { reach, signal } = reachOfOne(one);
44
+ votes.set(reach, (votes.get(reach) ?? 0) + 1);
45
+ if (signal !== undefined)
46
+ signals.add(signal);
47
+ }
48
+ const voted = [...REACHES].reverse().reduce((best, reach) => {
49
+ const n = votes.get(reach) ?? 0;
50
+ return n > 0 && (best === null || n > (votes.get(best) ?? 0)) ? reach : best;
51
+ }, null);
52
+ const reach = ownerWrote ? "direct" : (voted ?? (chatted ? "direct" : null));
53
+ return { signals: [...signals], reach };
54
+ };
55
+ const LIST_ID = "coalesce(json_extract(e.headers, '$.\"list-id\"'), json_extract(e.metadata, '$.listId'))";
56
+ /** `bob+news@x` and `bob@x` are one sender. */
57
+ const senderKey = (address) => address.toLowerCase().replace(/\+[^@]*@/, "@");
58
+ /**
59
+ * The mail each of these people sent the owner, as `senderSignalsOf` reads it. Asked for a page of people only: it
60
+ * reads every stored email's List-Id once to tell a discussion list from a newsletter.
61
+ */
62
+ export const sentMailOf = (database, people) => {
63
+ const found = new Map();
64
+ if (people.length === 0)
65
+ return found;
66
+ const rows = database
67
+ .prepare("SELECT l.person_id AS person, " +
68
+ `${LIST_ID} AS list, json_extract(e.headers, '$."auto-submitted"') IS NOT NULL AS auto, ` +
69
+ "json_extract(e.headers, '$.\"null-return-path\"') IS 1 AS null_return, " +
70
+ "json_extract(e.headers, '$.\"list-unsubscribe-post\"') IS 1 AS one_click, " +
71
+ "json_extract(e.headers, '$.\"feedback-id\"') IS 1 AS feedback, " +
72
+ "EXISTS (SELECT 1 FROM email_mailboxes m JOIN mailboxes b ON b.id = m.mailbox_id " +
73
+ "WHERE m.email_id = e.id AND b.kind = 'bulk') AS bulk, " +
74
+ "CASE WHEN json_extract(e.metadata, '$.rule') IS NOT NULL THEN NULL ELSE " +
75
+ "(SELECT count(*) FROM email_recipients r WHERE r.email_id = e.id AND r.role IN ('to', 'cc')) END AS recipients " +
76
+ "FROM emails e JOIN identity_links l ON l.identity_id = e.from_identity_id " +
77
+ "WHERE e.outgoing IS NOT 1 AND e.deleted_at IS NULL AND l.person_id IN (SELECT value FROM json_each(?))")
78
+ .all(JSON.stringify(people));
79
+ const lists = [...new Set(rows.flatMap((row) => (typeof row.list === "string" ? [row.list] : [])))];
80
+ const senders = new Map();
81
+ if (lists.length > 0)
82
+ for (const row of database
83
+ .prepare(`SELECT DISTINCT ${LIST_ID} AS list, e.from_address AS address FROM emails e ` +
84
+ `WHERE e.from_address IS NOT NULL AND ${LIST_ID} IN (SELECT value FROM json_each(?))`)
85
+ .all(JSON.stringify(lists))) {
86
+ const list = String(row.list);
87
+ const held = senders.get(list) ?? new Set();
88
+ held.add(senderKey(String(row.address)));
89
+ senders.set(list, held);
90
+ }
91
+ for (const row of rows) {
92
+ const person = Number(row.person);
93
+ const held = found.get(person) ?? [];
94
+ held.push({
95
+ autoSubmitted: Number(row.auto) === 1,
96
+ nullReturnPath: Number(row.null_return) === 1,
97
+ oneClick: Number(row.one_click) === 1,
98
+ feedbackId: Number(row.feedback) === 1,
99
+ bulk: Number(row.bulk) === 1,
100
+ discussionList: typeof row.list === "string" && (senders.get(row.list)?.size ?? 0) >= DISCUSSION_SENDERS,
101
+ recipients: row.recipients == null ? null : Number(row.recipients),
102
+ });
103
+ found.set(person, held);
104
+ }
105
+ return found;
106
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.752.0",
3
+ "version": "0.753.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",