@wirecat/cli-core 1.1.0 → 1.3.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 (80) hide show
  1. package/CHANGELOG.md +80 -0
  2. package/dist/cli/account-remove.d.ts +3 -0
  3. package/dist/cli/account-remove.js +1 -1
  4. package/dist/cli/contract-templates.js +3 -0
  5. package/dist/cli/documents/index.d.ts +2 -1
  6. package/dist/cli/documents/index.js +4 -1
  7. package/dist/cli/help/first-screen.js +2 -2
  8. package/dist/cli/index.d.ts +3 -3
  9. package/dist/cli/index.js +3 -3
  10. package/dist/cli/messenger/account-command.js +0 -10
  11. package/dist/cli/messenger/accounts.d.ts +1 -1
  12. package/dist/cli/messenger/accounts.js +1 -1
  13. package/dist/cli/messenger/context.d.ts +1 -1
  14. package/dist/cli/messenger/conversation-answers.d.ts +2 -0
  15. package/dist/cli/messenger/message-answers.d.ts +2 -0
  16. package/dist/cli/messenger/message-items.js +2 -0
  17. package/dist/cli/messenger/message-writes.d.ts +4 -0
  18. package/dist/cli/messenger/search-answers.js +2 -0
  19. package/dist/cli/messenger/session-commands.d.ts +1 -1
  20. package/dist/cli/messenger/session-commands.js +1 -1
  21. package/dist/cli/oauth-session.js +6 -3
  22. package/dist/cli/program.js +2 -2
  23. package/dist/cli/settings.d.ts +3 -3
  24. package/dist/cli/shared-command-exports.d.ts +2 -0
  25. package/dist/cli/shared-command-exports.js +3 -0
  26. package/dist/cli/token-session.d.ts +1 -4
  27. package/dist/cli/token-session.js +5 -1
  28. package/dist/domain/models.d.ts +5 -0
  29. package/dist/domain/person-kinds.d.ts +1 -1
  30. package/dist/entities/contact-context.d.ts +4 -0
  31. package/dist/entities/conversation-results.d.ts +4 -0
  32. package/dist/entities/evidence.d.ts +16 -0
  33. package/dist/entities/index.d.ts +36 -0
  34. package/dist/entities/listener.d.ts +8 -0
  35. package/dist/entities/message-change.d.ts +2 -0
  36. package/dist/entities/message-context.d.ts +6 -0
  37. package/dist/entities/message-write.d.ts +8 -0
  38. package/dist/entities/message.d.ts +4 -0
  39. package/dist/entities/message.js +4 -0
  40. package/dist/entities/store-maintenance.js +1 -1
  41. package/dist/entities/store-records.d.ts +2 -0
  42. package/dist/errors/failures.d.ts +6 -0
  43. package/dist/errors/failures.js +18 -4
  44. package/dist/errors/reasons.js +16 -0
  45. package/dist/errors/store-reasons.js +1 -0
  46. package/dist/mail/cli/index.js +1 -1
  47. package/dist/mail/headers.d.ts +2 -0
  48. package/dist/mail/headers.js +2 -1
  49. package/dist/mail/read.js +1 -0
  50. package/dist/mail/sort-rules.d.ts +58 -0
  51. package/dist/mail/sort-rules.js +79 -0
  52. package/dist/mcp/tool.js +2 -2
  53. package/dist/runs/recording.js +2 -2
  54. package/dist/search/lucene/registry.js +24 -0
  55. package/dist/services/messages-search.js +1 -1
  56. package/dist/store/areas.d.ts +2 -0
  57. package/dist/store/areas.js +2 -0
  58. package/dist/store/public.d.ts +1 -1
  59. package/dist/store/public.js +1 -1
  60. package/dist/store/queries.js +9 -2
  61. package/dist/store/sqlite/email-types.d.ts +8 -0
  62. package/dist/store/sqlite/email-types.js +45 -10
  63. package/dist/store/sqlite/emails.d.ts +3 -0
  64. package/dist/store/sqlite/emails.js +14 -5
  65. package/dist/store/sqlite/lucene-fields.d.ts +6 -0
  66. package/dist/store/sqlite/lucene-fields.js +10 -0
  67. package/dist/store/sqlite/lucene.js +6 -0
  68. package/dist/store/sqlite/mail-sorting.d.ts +122 -0
  69. package/dist/store/sqlite/mail-sorting.js +482 -0
  70. package/dist/store/sqlite/manifest.js +2 -0
  71. package/dist/store/sqlite/migrations.generated.js +20 -0
  72. package/dist/store/sqlite/people-list.js +65 -16
  73. package/dist/store/sqlite/schema/mail-sorting.d.ts +384 -0
  74. package/dist/store/sqlite/schema/mail-sorting.js +31 -0
  75. package/dist/store/sqlite/schema.d.ts +17 -0
  76. package/dist/store/sqlite/schema.js +3 -0
  77. package/dist/store/sqlite/sender-bots.d.ts +10 -1
  78. package/dist/store/sqlite/sender-bots.js +47 -8
  79. package/package.json +2 -2
  80. package/parity.json +9 -3
@@ -0,0 +1,122 @@
1
+ import { type MailType } from "../../mail/mail-types.js";
2
+ import { type SortAuthor, type SortIndex, type SortScope } from "../../mail/sort-rules.js";
3
+ import type { Decider } from "../decisions.js";
4
+ import type { CacheDatabase } from "../driver.js";
5
+ import type { StoreContext } from "./open.js";
6
+ /** One sorting rule. @experimental */
7
+ export interface SortRule {
8
+ id: number;
9
+ scope: SortScope;
10
+ /** The email's id, the List-Id, the subject pattern, the address or the registrable domain, as kept. */
11
+ value: string;
12
+ mailType: MailType | null;
13
+ sender: "bot" | "person" | null;
14
+ /** `organization:<id>`. */
15
+ organization: string | null;
16
+ overAddresses: boolean;
17
+ /** `false`: only mail dated from `createdAt` on. */
18
+ past: boolean;
19
+ author: SortAuthor;
20
+ decidedBy: string | null;
21
+ reason: string | null;
22
+ createdAt: number;
23
+ updatedAt: number;
24
+ removedAt: number | null;
25
+ }
26
+ /** A correction as the caller names it: its scope, and whether past mail is sorted too. @experimental */
27
+ export interface SortRuleInput {
28
+ scope: SortScope;
29
+ /** An email's id, a List-Id, a subject pattern, an address or a domain (kept as its registrable domain). */
30
+ value: string | number;
31
+ mailType?: MailType;
32
+ /** The owner's only; at `address` or `domain` scope; moves the sender for its whole history. */
33
+ sender?: "bot" | "person";
34
+ /** `organization:<id>`; the owner's only; at `address` or `domain` scope. */
35
+ organization?: string;
36
+ /** A domain rule that beats the address rules at its domain. */
37
+ overAddresses?: boolean;
38
+ /** `all`: mail already in the store too; `new`: only mail dated from now on. Always named. */
39
+ applyTo: "all" | "new";
40
+ reason?: string;
41
+ }
42
+ /** What a rule would touch, before it is set. @experimental */
43
+ export interface SortPreview {
44
+ scope: SortScope;
45
+ value: string;
46
+ /** The scope in words: "every mail from the domain gmail.com". */
47
+ label: string;
48
+ applyTo: "all" | "new";
49
+ /** The domain is a free-mail or throwaway one: the rule needs `confirm`. */
50
+ freeMail: boolean;
51
+ /** Distinct sender addresses its scope takes in. */
52
+ addresses: number;
53
+ /** Incoming emails its scope takes in. */
54
+ emails: number;
55
+ /** Of those, the emails whose type it would set now: a narrower rule or a past one left out. */
56
+ retyped: number;
57
+ /** Senders it would move to a bot or a person, or file under the organization. */
58
+ senders: number;
59
+ /** Pass to `add` to set a free-mail domain rule; it holds while these counts do. */
60
+ confirm: string | null;
61
+ }
62
+ /** @experimental */
63
+ export interface SortAddResult {
64
+ applied: boolean;
65
+ preview: SortPreview;
66
+ rule?: SortRule;
67
+ }
68
+ /** A scope a correction of one email may take, narrowest first: the domain is never offered first. @experimental */
69
+ export interface SortScopeChoice {
70
+ scope: SortScope;
71
+ value: string;
72
+ label: string;
73
+ /** A free-mail or throwaway domain: a rule there needs a dry run and its `confirm`. */
74
+ freeMail: boolean;
75
+ }
76
+ /** @experimental */
77
+ export interface SortUndo {
78
+ undid: "add" | "remove";
79
+ rule: SortRule;
80
+ }
81
+ /** @experimental */
82
+ export interface MailSorting {
83
+ /** Live rules, newest first; `removed` lists the removed ones instead. */
84
+ rules(options?: {
85
+ scope?: SortScope;
86
+ removed?: boolean;
87
+ }): Promise<SortRule[]>;
88
+ /** The scopes a correction of this email may take. */
89
+ scopes(email: number): Promise<SortScopeChoice[]>;
90
+ /**
91
+ * Sets a rule, or with `dryRun` only says what it would touch. A domain rule on a free-mail or throwaway domain is
92
+ * set only with the `confirm` of a dry run whose counts still hold. A program's rule sets a mail type only.
93
+ */
94
+ add(input: SortRuleInput, by: Decider, options?: {
95
+ dryRun?: boolean;
96
+ confirm?: string;
97
+ }): Promise<SortAddResult>;
98
+ /** Removes a rule: its mail is typed again without it, and the senders it moved go back. */
99
+ remove(rule: number, by: Decider): Promise<SortRule>;
100
+ /** Takes back the owner's newest add or removal not yet undone; `null` when there is none. */
101
+ undo(by: Decider): Promise<SortUndo | null>;
102
+ /**
103
+ * The owner's manual sorting of one sender, an address or a `person:` or `sender-bot:` ref, removed: its address
104
+ * rules and its one-mail rules. Domain and list rules stay. Answers the rules removed.
105
+ */
106
+ reset(sender: string, by: Decider): Promise<SortRule[]>;
107
+ }
108
+ /** The live rules that set a mail type, filed for `sortRuleFor`. */
109
+ export declare const typeRulesOf: (database: CacheDatabase) => SortIndex<SortRule>;
110
+ /** A free-mail or throwaway domain, whose addresses belong to anyone: a rule there sorts strangers together. */
111
+ export declare const isSharedMailDomain: (domain: string) => boolean;
112
+ /** Whether any rule moves senders or files them: sync then settles the senders it stored. */
113
+ export declare const hasSenderRules: (database: CacheDatabase) => boolean;
114
+ /**
115
+ * Each sender the winning rule has not acted on yet moves to a bot or a person through `moveToBot` and `moveToPerson`,
116
+ * or is filed under the rule's organization, and the effect is logged so a removal can put it back. A sender already
117
+ * where the rule says is logged as left. The caller holds the write lock.
118
+ */
119
+ export declare const settleSenders: (context: StoreContext, identities?: readonly number[]) => void;
120
+ export declare const mailSortingOver: (context: StoreContext) => MailSorting;
121
+ /** The senders of mail just saved in these threads, settled by the rules that move or file senders. */
122
+ export declare const settleThreads: (context: StoreContext, threads: readonly number[]) => void;
@@ -0,0 +1,482 @@
1
+ import { createHash } from "node:crypto";
2
+ import { CliError } from "@wirecat/cli-base";
3
+ import { isPackFreeMailDomain } from "../../domain/domain-lists.js";
4
+ import { isFreeMailDomain } from "../../domain/organization-sectors.js";
5
+ import { SENDER_BOT_PREFIX } from "../../domain/person-kinds.js";
6
+ import { listIdOf } from "../../mail/headers.js";
7
+ import { MAIL_TYPES } from "../../mail/mail-types.js";
8
+ import { FREE_MAIL, isDisposableDomain } from "../../mail/score.js";
9
+ import { SORT_SCOPES, sortIndexOf, sortRuleFor, sortValueOf, } from "../../mail/sort-rules.js";
10
+ import { holdAddress } from "./address-organization.js";
11
+ import { moveToBot, moveToPerson } from "./sender-bots.js";
12
+ import { LIST_ID } from "./sender-signals.js";
13
+ import { read, write } from "./transaction.js";
14
+ const COLUMNS = "id, scope, value, mail_type, sender, organization_id, over_addresses, past, author, decided_by, reason, " +
15
+ "created_at, updated_at, removed_at";
16
+ const ruleOf = (row) => ({
17
+ id: Number(row.id),
18
+ scope: String(row.scope),
19
+ value: String(row.value),
20
+ mailType: row.mail_type == null ? null : String(row.mail_type),
21
+ sender: row.sender == null ? null : String(row.sender),
22
+ organization: row.organization_id == null ? null : `organization:${row.organization_id}`,
23
+ overAddresses: Number(row.over_addresses) === 1,
24
+ past: Number(row.past) === 1,
25
+ author: String(row.author),
26
+ decidedBy: row.decided_by == null ? null : String(row.decided_by),
27
+ reason: row.reason == null ? null : String(row.reason),
28
+ createdAt: Number(row.created_at),
29
+ updatedAt: Number(row.updated_at),
30
+ removedAt: row.removed_at == null ? null : Number(row.removed_at),
31
+ });
32
+ const liveRules = (database) => database.prepare(`SELECT ${COLUMNS} FROM mail_sort_rules WHERE removed_at IS NULL`).all().map(ruleOf);
33
+ /** The live rules that set a mail type, filed for `sortRuleFor`. */
34
+ export const typeRulesOf = (database) => sortIndexOf(liveRules(database).filter((rule) => rule.mailType !== null));
35
+ /** A free-mail or throwaway domain, whose addresses belong to anyone: a rule there sorts strangers together. */
36
+ export const isSharedMailDomain = (domain) => FREE_MAIL.has(domain) || isFreeMailDomain(domain) || isPackFreeMailDomain(domain) || isDisposableDomain(domain);
37
+ const fail = (message, reason) => {
38
+ throw new CliError("validation_error", message, { reason });
39
+ };
40
+ const labelOf = (scope, value) => ({
41
+ mail: `the mail ${value}`,
42
+ list: `every mail of the list ${value}`,
43
+ subject: `every mail whose subject has "${value}"`,
44
+ address: `every mail from ${value}`,
45
+ domain: `every mail from the domain ${value}`,
46
+ })[scope];
47
+ const MAIL_ROWS = "SELECT e.id, lower(e.from_address) AS address, e.from_identity_id AS identity, e.subject, " +
48
+ `${LIST_ID} AS list, coalesce(e.received_at, e.sent_at) AS at FROM emails e ` +
49
+ "WHERE e.deleted_at IS NULL AND e.outgoing IS NOT 1";
50
+ const mailRowOf = (row) => ({
51
+ id: Number(row.id),
52
+ from: typeof row.address === "string" ? row.address : null,
53
+ subject: typeof row.subject === "string" ? row.subject : null,
54
+ list: typeof row.list === "string" ? (listIdOf(row.list) ?? null) : null,
55
+ at: row.at == null ? null : Number(row.at),
56
+ identity: row.identity == null ? null : Number(row.identity),
57
+ });
58
+ /** The incoming emails a rule's scope takes in, whatever wins over it. */
59
+ const inScope = (database, scope, value) => {
60
+ const where = {
61
+ mail: ["e.id = ?", [Number(value)]],
62
+ list: [`${LIST_ID} IS NOT NULL`, []],
63
+ subject: ["e.subject IS NOT NULL", []],
64
+ address: ["lower(e.from_address) = ?", [value]],
65
+ domain: ["(lower(e.from_address) LIKE ? OR lower(e.from_address) LIKE ?)", [`%@${value}`, `%.${value}`]],
66
+ };
67
+ const [sql, params] = where[scope];
68
+ const alone = sortIndexOf([{ id: 0, scope, value, author: "owner", overAddresses: false, past: true, createdAt: 0 }]);
69
+ return database
70
+ .prepare(`${MAIL_ROWS} AND ${sql}`)
71
+ .all(...params)
72
+ .map(mailRowOf)
73
+ .filter((row) => sortRuleFor(alone, row) !== undefined);
74
+ };
75
+ const ADDRESS_ONLY = { subject: null, list: null, at: Number.MAX_SAFE_INTEGER };
76
+ /** Where an identity sits now: `sender-bot:<id>`, `person:<id>` or `null`. */
77
+ const holderOf = (database, identity) => {
78
+ const bot = database.prepare("SELECT bot_id FROM sender_bot_identities WHERE identity_id = ?").get(identity);
79
+ if (bot !== undefined)
80
+ return `${SENDER_BOT_PREFIX}${bot.bot_id}`;
81
+ const person = database.prepare("SELECT person_id FROM identity_links WHERE identity_id = ?").get(identity);
82
+ return person === undefined ? null : `person:${person.person_id}`;
83
+ };
84
+ const isWhere = (holder, sender) => holder?.startsWith(sender === "bot" ? SENDER_BOT_PREFIX : "person:") === true;
85
+ const sendersOf = (database, identities) => database
86
+ .prepare("SELECT DISTINCT e.from_identity_id AS identity, i.external_id AS address FROM emails e " +
87
+ "JOIN identities i ON i.id = e.from_identity_id WHERE i.provider = 'email' AND e.outgoing IS NOT 1 " +
88
+ "AND e.deleted_at IS NULL" +
89
+ (identities === undefined ? "" : " AND e.from_identity_id IN (SELECT value FROM json_each(?))"))
90
+ .all(...(identities === undefined ? [] : [JSON.stringify(identities)]))
91
+ .map((row) => ({ identity: Number(row.identity), address: String(row.address).toLowerCase() }));
92
+ const hasEffect = (database, rule, identity, action) => database
93
+ .prepare("SELECT 1 FROM mail_sort_effects WHERE rule_id = ? AND identity_id = ? AND action = ? AND undone_at IS NULL")
94
+ .get(rule, identity, action) !== undefined;
95
+ const recordEffect = (database, effect) => database
96
+ .prepare("INSERT INTO mail_sort_effects (rule_id, identity_id, action, before, after, created_at) VALUES (?, ?, ?, ?, ?, ?)")
97
+ .run(effect.rule, effect.identity, effect.action, effect.before, effect.after, effect.at);
98
+ const ownerSenderRules = (database) => {
99
+ const rules = liveRules(database).filter((rule) => rule.author === "owner" && (rule.scope === "address" || rule.scope === "domain"));
100
+ return {
101
+ sender: sortIndexOf(rules.filter((rule) => rule.sender !== null)),
102
+ organization: sortIndexOf(rules.filter((rule) => rule.organization !== null)),
103
+ };
104
+ };
105
+ /** Whether any rule moves senders or files them: sync then settles the senders it stored. */
106
+ export const hasSenderRules = (database) => database
107
+ .prepare("SELECT 1 FROM mail_sort_rules WHERE removed_at IS NULL AND author = 'owner' " +
108
+ "AND (sender IS NOT NULL OR organization_id IS NOT NULL) LIMIT 1")
109
+ .get() !== undefined;
110
+ /**
111
+ * Each sender the winning rule has not acted on yet moves to a bot or a person through `moveToBot` and `moveToPerson`,
112
+ * or is filed under the rule's organization, and the effect is logged so a removal can put it back. A sender already
113
+ * where the rule says is logged as left. The caller holds the write lock.
114
+ */
115
+ export const settleSenders = (context, identities) => {
116
+ const { database } = context;
117
+ const rules = ownerSenderRules(database);
118
+ if (rules.sender.size === 0 && rules.organization.size === 0)
119
+ return;
120
+ for (const { identity, address } of sendersOf(database, identities)) {
121
+ const mail = { id: 0, from: address, ...ADDRESS_ONLY };
122
+ const at = context.now();
123
+ const mover = sortRuleFor(rules.sender, mail);
124
+ if (mover?.sender && !hasEffect(database, mover.id, identity, "sender")) {
125
+ const before = holderOf(database, identity);
126
+ if (!isWhere(before, mover.sender))
127
+ moveSender(context, address, mover);
128
+ recordEffect(database, {
129
+ rule: mover.id,
130
+ identity,
131
+ action: "sender",
132
+ before,
133
+ after: holderOf(database, identity),
134
+ at,
135
+ });
136
+ }
137
+ const filer = sortRuleFor(rules.organization, mail);
138
+ if (filer?.organization && !hasEffect(database, filer.id, identity, "organization")) {
139
+ const organization = Number(filer.organization.slice("organization:".length));
140
+ const held = database
141
+ .prepare("SELECT 1 FROM organization_identities WHERE identity_id = ? AND organization_id = ?")
142
+ .get(identity, organization) !== undefined;
143
+ if (!held)
144
+ holdAddress(context, organization, address, { method: SORT_METHOD, author: "owner" });
145
+ recordEffect(database, {
146
+ rule: filer.id,
147
+ identity,
148
+ action: "organization",
149
+ before: held ? "held" : null,
150
+ after: filer.organization,
151
+ at,
152
+ });
153
+ }
154
+ }
155
+ };
156
+ const SORT_METHOD = "sort-rule";
157
+ const moveSender = (context, address, rule) => {
158
+ const subject = { provider: "email", id: address };
159
+ const reason = rule.reason ?? `mail sorting rule ${rule.id}`;
160
+ if (rule.sender === "person")
161
+ return void moveToPerson(context, subject, { reason });
162
+ try {
163
+ moveToBot(context, subject, { reason });
164
+ }
165
+ catch (error) {
166
+ // The owner's own address under a domain rule stays the owner's.
167
+ if (!(error instanceof CliError && error.details?.reason === "sender-bot.owner"))
168
+ throw error;
169
+ }
170
+ };
171
+ /** Puts back what a rule did to its senders, then lets the rules still live settle them. */
172
+ const undoEffects = (context, rule) => {
173
+ const { database } = context;
174
+ const effects = database
175
+ .prepare("SELECT f.id, f.identity_id, f.action, f.before, f.after, i.external_id AS address FROM mail_sort_effects f " +
176
+ "JOIN identities i ON i.id = f.identity_id WHERE f.rule_id = ? AND f.undone_at IS NULL ORDER BY f.id DESC")
177
+ .all(rule);
178
+ const at = context.now();
179
+ for (const effect of effects) {
180
+ const identity = Number(effect.identity_id);
181
+ const subject = { provider: "email", id: String(effect.address) };
182
+ const before = effect.before == null ? null : String(effect.before);
183
+ if (effect.action === "sender" && before !== effect.after && before !== null) {
184
+ const now = holderOf(database, identity);
185
+ if (before.startsWith("person:") && !isWhere(now, "person"))
186
+ moveToPerson(context, subject, { reason: "undo" });
187
+ if (before.startsWith(SENDER_BOT_PREFIX) && !isWhere(now, "bot"))
188
+ moveToBot(context, subject, {
189
+ reason: "undo",
190
+ ...(database
191
+ .prepare("SELECT 1 FROM sender_bots WHERE id = ?")
192
+ .get(Number(before.slice(SENDER_BOT_PREFIX.length)))
193
+ ? { bot: before }
194
+ : {}),
195
+ });
196
+ }
197
+ if (effect.action === "organization" && before === null)
198
+ database
199
+ .prepare("DELETE FROM organization_identities WHERE identity_id = ? AND organization_id = ? AND method = ?")
200
+ .run(identity, Number(String(effect.after).slice("organization:".length)), SORT_METHOD);
201
+ database.prepare("UPDATE mail_sort_effects SET undone_at = ? WHERE id = ?").run(at, Number(effect.id));
202
+ }
203
+ const identities = [...new Set(effects.map((effect) => Number(effect.identity_id)))];
204
+ if (identities.length > 0)
205
+ settleSenders(context, identities);
206
+ };
207
+ const clearTypes = (database, ids) => database
208
+ .prepare("UPDATE emails SET mail_type = NULL, reach = NULL, type_signal = NULL " +
209
+ "WHERE mail_type IS NOT NULL AND id IN (SELECT value FROM json_each(?))")
210
+ .run(JSON.stringify(ids));
211
+ const clearRuleTypes = (database, rule) => {
212
+ database
213
+ .prepare("UPDATE emails SET mail_type = NULL, reach = NULL, type_signal = NULL WHERE mail_type IS NOT NULL AND type_signal = ?")
214
+ .run(`rule:${rule.id}`);
215
+ if (rule.mailType === null)
216
+ return;
217
+ const index = sortIndexOf([...liveRules(database).filter((one) => one.mailType !== null && one.id !== rule.id), rule]);
218
+ clearTypes(database, inScope(database, rule.scope, rule.value)
219
+ .filter((row) => sortRuleFor(index, row)?.id === rule.id)
220
+ .map((row) => row.id));
221
+ };
222
+ const checked = (database, input, by) => {
223
+ if (!SORT_SCOPES.includes(input.scope))
224
+ fail(`a rule's scope is one of ${SORT_SCOPES.join(", ")}`, "mail-sort.scope");
225
+ if (input.applyTo !== "all" && input.applyTo !== "new")
226
+ fail("a rule says whether it sorts past mail too: applyTo all or new", "mail-sort.apply-to");
227
+ const value = sortValueOf(input.scope, input.value);
228
+ if (value === undefined)
229
+ return fail(`${String(input.value)} names no ${input.scope}`, "mail-sort.value");
230
+ if (input.mailType !== undefined && !MAIL_TYPES.includes(input.mailType))
231
+ fail(`a mail type is one of ${MAIL_TYPES.join(", ")}`, "mail-sort.mail-type");
232
+ if (input.sender !== undefined && input.sender !== "bot" && input.sender !== "person")
233
+ fail("a sender becomes a bot or a person", "mail-sort.sender");
234
+ if (input.mailType === undefined && input.sender === undefined && input.organization === undefined)
235
+ fail("a rule sets a mail type, a sender or an organization", "mail-sort.no-action");
236
+ const owner = by === "owner";
237
+ const onSender = input.sender !== undefined || input.organization !== undefined;
238
+ if (onSender && !owner)
239
+ fail("only the owner's rule moves or files a sender", "mail-sort.owner-only");
240
+ if (onSender && input.scope !== "address" && input.scope !== "domain")
241
+ fail("a rule moves or files a sender at address or domain scope", "mail-sort.sender-scope");
242
+ if (onSender && input.scope === "address" && input.applyTo === "new")
243
+ fail("a sender moves with its whole history: an address rule that moves one applies to all", "mail-sort.sender-new");
244
+ if (input.overAddresses && input.scope !== "domain")
245
+ fail("only a domain rule can beat the address rules", "mail-sort.over-addresses");
246
+ if (!owner && input.scope === "domain" && isSharedMailDomain(value))
247
+ fail(`only the owner sets a rule on the free-mail domain ${value}`, "mail-sort.free-mail-program");
248
+ const organization = input.organization === undefined
249
+ ? null
250
+ : Number(/^organization:([1-9]\d*)$/.exec(input.organization)?.[1] ?? Number.NaN);
251
+ if (organization !== null &&
252
+ (Number.isNaN(organization) ||
253
+ database.prepare("SELECT 1 FROM organizations WHERE id = ? AND deleted_at IS NULL").get(organization) ===
254
+ undefined))
255
+ fail(`${input.organization} is no organization in the store`, "mail-sort.organization");
256
+ return {
257
+ scope: input.scope,
258
+ value,
259
+ mailType: input.mailType ?? null,
260
+ sender: input.sender ?? null,
261
+ organization,
262
+ overAddresses: input.overAddresses === true,
263
+ past: input.applyTo === "all",
264
+ author: owner ? "owner" : "program",
265
+ decidedBy: owner ? null : by.bot,
266
+ reason: input.reason ?? (owner ? null : by.reason),
267
+ };
268
+ };
269
+ const previewOf = (database, rule, at) => {
270
+ const rows = inScope(database, rule.scope, rule.value);
271
+ const candidate = {
272
+ id: -1,
273
+ ...rule,
274
+ organization: rule.organization === null ? null : `organization:${rule.organization}`,
275
+ createdAt: at,
276
+ updatedAt: at,
277
+ removedAt: null,
278
+ };
279
+ const live = liveRules(database);
280
+ const types = sortIndexOf([...live.filter((one) => one.mailType !== null), candidate]);
281
+ const retyped = rule.mailType === null ? 0 : rows.filter((row) => sortRuleFor(types, row)?.id === -1).length;
282
+ const movers = sortIndexOf([
283
+ ...live.filter((one) => one.author === "owner" &&
284
+ (rule.sender !== null ? one.sender !== null : one.organization !== null) &&
285
+ (one.scope === "address" || one.scope === "domain")),
286
+ candidate,
287
+ ]);
288
+ const senders = (rule.sender === null && rule.organization === null) || !rule.past
289
+ ? 0
290
+ : sendersOf(database, [...new Set(rows.flatMap((row) => row.identity ?? []))]).filter(({ identity, address }) => sortRuleFor(movers, { id: 0, from: address, ...ADDRESS_ONLY })?.id === -1 &&
291
+ (rule.sender === null || !isWhere(holderOf(database, identity), rule.sender))).length;
292
+ const addresses = new Set(rows.flatMap((row) => row.from ?? [])).size;
293
+ const freeMail = rule.scope === "domain" && isSharedMailDomain(rule.value);
294
+ const counts = { emails: rows.length, addresses, retyped, senders };
295
+ return {
296
+ scope: rule.scope,
297
+ value: rule.value,
298
+ label: labelOf(rule.scope, rule.value),
299
+ applyTo: rule.past ? "all" : "new",
300
+ freeMail,
301
+ ...counts,
302
+ confirm: freeMail
303
+ ? createHash("sha256")
304
+ .update(JSON.stringify([rule.scope, rule.value, rule.mailType, rule.sender, rule.organization, rule.past, counts]))
305
+ .digest("hex")
306
+ .slice(0, 16)
307
+ : null,
308
+ };
309
+ };
310
+ const ruleById = (database, id) => {
311
+ const row = database.prepare(`SELECT ${COLUMNS} FROM mail_sort_rules WHERE id = ?`).get(id);
312
+ if (row === undefined)
313
+ throw new CliError("not_found", `no mail sorting rule ${id}`, { reason: "mail-sort.not-found" });
314
+ return ruleOf(row);
315
+ };
316
+ /** Makes a rule live: its mail is typed again. Answers the senders it names, for `settleInChunks`. */
317
+ const applyRule = (context, rule) => {
318
+ const { database } = context;
319
+ clearRuleTypes(database, rule);
320
+ if (rule.sender === null && rule.organization === null)
321
+ return [];
322
+ const identities = [
323
+ ...new Set(inScope(database, rule.scope, rule.value).flatMap((row) => (row.identity === null ? [] : [row.identity]))),
324
+ ];
325
+ if (!rule.past)
326
+ for (const { identity } of sendersOf(database, identities)) {
327
+ const holder = holderOf(database, identity);
328
+ for (const action of [...(rule.sender ? ["sender"] : []), ...(rule.organization ? ["organization"] : [])])
329
+ recordEffect(database, {
330
+ rule: rule.id,
331
+ identity,
332
+ action,
333
+ before: action === "sender" ? holder : "held",
334
+ after: action === "sender" ? holder : "held",
335
+ at: context.now(),
336
+ });
337
+ }
338
+ return identities;
339
+ };
340
+ /** Each move takes about 10 ms: 100 per write keeps another writer's 5 s wait for the lock far away. */
341
+ const SETTLE_CHUNK = 100;
342
+ /** Settles senders a write at a time; a sender already settled is skipped, so a stopped run resumes on the next. */
343
+ const settleInChunks = (context, identities) => {
344
+ for (let at = 0; at < identities.length; at += SETTLE_CHUNK)
345
+ write(context.database, () => settleSenders(context, identities.slice(at, at + SETTLE_CHUNK)));
346
+ };
347
+ /** A change's time, later than every change before it, so undo takes changes back in order within one millisecond. */
348
+ const stampOf = ({ database, now }) => Math.max(now(), Number(database.prepare("SELECT coalesce(max(updated_at), 0) + 1 AS at FROM mail_sort_rules").get()?.at));
349
+ const takeOut = (context, rule, undone) => {
350
+ const at = stampOf(context);
351
+ context.database
352
+ .prepare("UPDATE mail_sort_rules SET removed_at = ?, updated_at = ?, undone_at = ? WHERE id = ?")
353
+ .run(at, at, undone ? at : null, rule.id);
354
+ const removed = ruleById(context.database, rule.id);
355
+ clearRuleTypes(context.database, removed);
356
+ undoEffects(context, rule.id);
357
+ return removed;
358
+ };
359
+ const ownerOnly = (by, what) => {
360
+ if (by !== "owner")
361
+ fail(`only the owner ${what}`, "mail-sort.owner-only");
362
+ };
363
+ const addressesOf = (database, sender) => {
364
+ if (sender.includes("@") && !sender.includes(":"))
365
+ return [sender.trim().toLowerCase()];
366
+ const bot = sender.startsWith(SENDER_BOT_PREFIX) ? Number(sender.slice(SENDER_BOT_PREFIX.length)) : undefined;
367
+ const person = sender.startsWith("person:") ? Number(sender.slice("person:".length)) : undefined;
368
+ if (bot === undefined && person === undefined)
369
+ return fail(`${sender} names no sender: give an address, a person: or a sender-bot: ref`, "mail-sort.sender-ref");
370
+ return database
371
+ .prepare("SELECT lower(i.external_id) AS address FROM identities i WHERE i.provider = 'email' AND i.id IN " +
372
+ (bot === undefined
373
+ ? "(SELECT identity_id FROM identity_links WHERE person_id = ?)"
374
+ : "(SELECT identity_id FROM sender_bot_identities WHERE bot_id = ?)"))
375
+ .all(bot ?? person ?? 0)
376
+ .map((row) => String(row.address));
377
+ };
378
+ export const mailSortingOver = (context) => {
379
+ const { database } = context;
380
+ return {
381
+ rules: async (options = {}) => database
382
+ .prepare(`SELECT ${COLUMNS} FROM mail_sort_rules WHERE removed_at IS ${options.removed ? "NOT NULL" : "NULL"}` +
383
+ (options.scope === undefined ? "" : " AND scope = ?") +
384
+ " ORDER BY updated_at DESC, id DESC")
385
+ .all(...(options.scope === undefined ? [] : [options.scope]))
386
+ .map(ruleOf),
387
+ scopes: async (email) => read(database, () => {
388
+ const row = database.prepare(`${MAIL_ROWS} AND e.id = ?`).get(email);
389
+ if (row === undefined)
390
+ throw new CliError("not_found", `no incoming email ${email}`, { reason: "mail-sort.email" });
391
+ const mail = mailRowOf(row);
392
+ const domain = mail.from === null ? undefined : sortValueOf("domain", mail.from);
393
+ const choices = [
394
+ { scope: "mail", value: String(mail.id) },
395
+ ...(mail.list === null ? [] : [{ scope: "list", value: mail.list }]),
396
+ ...(mail.from === null ? [] : [{ scope: "address", value: mail.from }]),
397
+ ...(domain === undefined ? [] : [{ scope: "domain", value: domain }]),
398
+ ];
399
+ return choices.map((choice) => ({
400
+ ...choice,
401
+ label: labelOf(choice.scope, choice.value),
402
+ freeMail: choice.scope === "domain" && isSharedMailDomain(choice.value),
403
+ }));
404
+ }),
405
+ add: async (input, by, options = {}) => {
406
+ const { identities, ...result } = write(database, () => {
407
+ const rule = checked(database, input, by);
408
+ const at = stampOf(context);
409
+ const preview = previewOf(database, rule, at);
410
+ if (options.dryRun)
411
+ return { applied: false, preview, identities: [] };
412
+ if (preview.freeMail && options.confirm !== preview.confirm)
413
+ fail(`${rule.value} is a free-mail domain: the rule would sort ${preview.addresses} addresses and ` +
414
+ `${preview.emails} emails together. Run it with dryRun first and pass its confirm`, "mail-sort.confirm");
415
+ const id = Number(database
416
+ .prepare("INSERT INTO mail_sort_rules (scope, value, mail_type, sender, organization_id, over_addresses, past, " +
417
+ "author, decided_by, reason, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id")
418
+ .get(rule.scope, rule.value, rule.mailType, rule.sender, rule.organization, rule.overAddresses ? 1 : 0, rule.past ? 1 : 0, rule.author, rule.decidedBy, rule.reason, at, at)?.id);
419
+ const made = ruleById(database, id);
420
+ return { applied: true, preview, rule: made, identities: applyRule(context, made) };
421
+ });
422
+ settleInChunks(context, identities);
423
+ return result;
424
+ },
425
+ remove: async (id, by) => write(database, () => {
426
+ const rule = ruleById(database, id);
427
+ if (by !== "owner" && (rule.author !== "program" || rule.decidedBy !== by.bot))
428
+ fail("a program removes only the rules it made", "mail-sort.owner-only");
429
+ if (rule.removedAt !== null)
430
+ return rule;
431
+ return takeOut(context, rule, false);
432
+ }),
433
+ undo: async (by) => {
434
+ const { identities, undone } = write(database, () => {
435
+ ownerOnly(by, "undoes a sorting change");
436
+ const row = database
437
+ .prepare(`SELECT ${COLUMNS} FROM mail_sort_rules WHERE author = 'owner' AND undone_at IS NULL ` +
438
+ "ORDER BY updated_at DESC, id DESC LIMIT 1")
439
+ .get();
440
+ if (row === undefined)
441
+ return { identities: [], undone: null };
442
+ const rule = ruleOf(row);
443
+ if (rule.removedAt === null)
444
+ return { identities: [], undone: { undid: "add", rule: takeOut(context, rule, true) } };
445
+ // Back as it was added: its add is the next change an undo takes back.
446
+ database
447
+ .prepare("UPDATE mail_sort_rules SET removed_at = NULL, updated_at = created_at WHERE id = ?")
448
+ .run(rule.id);
449
+ const back = ruleById(database, rule.id);
450
+ return { identities: applyRule(context, back), undone: { undid: "remove", rule: back } };
451
+ });
452
+ settleInChunks(context, identities);
453
+ return undone;
454
+ },
455
+ reset: async (sender, by) => write(database, () => {
456
+ ownerOnly(by, "resets the manual sorting of a sender");
457
+ const addresses = addressesOf(database, sender);
458
+ const mails = database
459
+ .prepare("SELECT id FROM emails WHERE lower(from_address) IN (SELECT value FROM json_each(?)) AND outgoing IS NOT 1")
460
+ .all(JSON.stringify(addresses))
461
+ .map((row) => String(row.id));
462
+ return database
463
+ .prepare(`SELECT ${COLUMNS} FROM mail_sort_rules WHERE removed_at IS NULL AND author = 'owner' AND ` +
464
+ "((scope = 'address' AND value IN (SELECT value FROM json_each(?))) OR " +
465
+ "(scope = 'mail' AND value IN (SELECT value FROM json_each(?)))) ORDER BY id DESC")
466
+ .all(JSON.stringify(addresses), JSON.stringify(mails))
467
+ .map((row) => takeOut(context, ruleOf(row), false));
468
+ }),
469
+ };
470
+ };
471
+ /** The senders of mail just saved in these threads, settled by the rules that move or file senders. */
472
+ export const settleThreads = (context, threads) => {
473
+ if (threads.length === 0 || !hasSenderRules(context.database))
474
+ return;
475
+ const identities = context.database
476
+ .prepare("SELECT DISTINCT from_identity_id AS identity FROM emails WHERE from_identity_id IS NOT NULL " +
477
+ "AND outgoing IS NOT 1 AND email_thread_id IN (SELECT value FROM json_each(?))")
478
+ .all(JSON.stringify(threads))
479
+ .map((row) => Number(row.identity));
480
+ if (identities.length > 0)
481
+ settleSenders(context, identities);
482
+ };
@@ -253,6 +253,8 @@ export const MANIFEST = [
253
253
  { name: "20261125111118_version-75-bot-identities-moved", version: 75, minCompatible: 73 },
254
254
  { name: "20261125183530_version-76-mail-types", version: 76, minCompatible: 73 },
255
255
  { name: "20261125183555_version-76-mail-type-triggers", version: 76, minCompatible: 73 },
256
+ { name: "20261125205013_version-77-mail-sort-rules", version: 77, minCompatible: 73 },
257
+ { name: "20261125205014_version-77-mail-sort-triggers", version: 77, minCompatible: 73 },
256
258
  ];
257
259
  export const generatedMigrations = (manifest = MANIFEST, generated = GENERATED) => {
258
260
  const migrations = [];
@@ -2170,5 +2170,25 @@ export const GENERATED = [
2170
2170
  "CREATE TRIGGER mail_type_organization_ad AFTER DELETE ON organization_identities BEGIN\n UPDATE emails SET mail_type = NULL, reach = NULL, type_signal = NULL WHERE mail_type IS NOT NULL AND from_identity_id = OLD.identity_id;\nEND;",
2171
2171
  "CREATE TRIGGER mail_type_sector_au AFTER UPDATE OF metadata, deleted_at ON organizations\nWHEN json_extract(OLD.metadata, '$.sector') IS NOT json_extract(NEW.metadata, '$.sector') OR OLD.deleted_at IS NOT NEW.deleted_at BEGIN\n UPDATE emails SET mail_type = NULL, reach = NULL, type_signal = NULL WHERE mail_type IS NOT NULL AND from_identity_id IN (SELECT identity_id FROM organization_identities WHERE organization_id = NEW.id);\nEND;"
2172
2172
  ]
2173
+ },
2174
+ {
2175
+ "name": "20261125205013_version-77-mail-sort-rules",
2176
+ "statements": [
2177
+ "CREATE TABLE `mail_sort_effects` (\n\t`id` integer PRIMARY KEY AUTOINCREMENT,\n\t`rule_id` integer NOT NULL,\n\t`identity_id` integer NOT NULL,\n\t`action` text NOT NULL,\n\t`before` text,\n\t`after` text,\n\t`created_at` integer NOT NULL,\n\t`undone_at` integer\n);",
2178
+ "CREATE TABLE `mail_sort_rules` (\n\t`id` integer PRIMARY KEY AUTOINCREMENT,\n\t`scope` text NOT NULL,\n\t`value` text NOT NULL,\n\t`mail_type` text,\n\t`sender` text,\n\t`organization_id` integer,\n\t`over_addresses` integer NOT NULL,\n\t`past` integer NOT NULL,\n\t`author` text NOT NULL,\n\t`decided_by` text,\n\t`reason` text,\n\t`created_at` integer NOT NULL,\n\t`updated_at` integer NOT NULL,\n\t`removed_at` integer,\n\t`undone_at` integer\n);",
2179
+ "ALTER TABLE `emails` ADD `sort_checked` integer;",
2180
+ "CREATE INDEX `emails_sort_to_check` ON `emails` (`id`) WHERE mail_type IS NOT NULL AND sort_checked IS NULL;",
2181
+ "CREATE INDEX `mail_sort_effects_by_rule_id` ON `mail_sort_effects` (`rule_id`);",
2182
+ "CREATE INDEX `mail_sort_effects_by_identity_id` ON `mail_sort_effects` (`identity_id`);",
2183
+ "CREATE INDEX `mail_sort_rules_by_scope_value` ON `mail_sort_rules` (`scope`,`value`);"
2184
+ ]
2185
+ },
2186
+ {
2187
+ "name": "20261125205014_version-77-mail-sort-triggers",
2188
+ "statements": [
2189
+ "UPDATE emails SET sort_checked = 1 WHERE mail_type IS NOT NULL;",
2190
+ "CREATE TRIGGER mail_sort_checked_au AFTER UPDATE OF mail_type ON emails\nWHEN NEW.mail_type IS NULL AND NEW.sort_checked IS NOT NULL BEGIN\n UPDATE emails SET sort_checked = NULL WHERE id = NEW.id;\nEND;",
2191
+ "CREATE TRIGGER mail_sort_effects_identity_ad AFTER DELETE ON identities BEGIN\n DELETE FROM mail_sort_effects WHERE identity_id = OLD.id;\nEND;"
2192
+ ]
2173
2193
  }
2174
2194
  ];