@wirecat/cli-core 1.0.0 → 1.2.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 (111) hide show
  1. package/CHANGELOG.md +144 -0
  2. package/THIRD_PARTY_NOTICES +43 -0
  3. package/dist/background/daily-archive-timer.d.ts +1 -1
  4. package/dist/cli/account-remove.d.ts +3 -0
  5. package/dist/cli/account-remove.js +1 -1
  6. package/dist/cli/documents/index.d.ts +2 -1
  7. package/dist/cli/documents/index.js +4 -1
  8. package/dist/cli/documents/words.d.ts +1 -1
  9. package/dist/cli/domain-lists-command.d.ts +16 -0
  10. package/dist/cli/domain-lists-command.js +88 -0
  11. package/dist/cli/index.d.ts +4 -3
  12. package/dist/cli/index.js +4 -3
  13. package/dist/cli/messenger/conversation-answers.d.ts +2 -0
  14. package/dist/cli/messenger/message-answers.d.ts +2 -0
  15. package/dist/cli/messenger/message-items.js +2 -0
  16. package/dist/cli/messenger/message-writes.d.ts +4 -0
  17. package/dist/cli/messenger/search-answers.js +2 -0
  18. package/dist/cli/model-catalogue-command.d.ts +6 -0
  19. package/dist/cli/model-catalogue-command.js +1 -1
  20. package/dist/cli/oauth-session.d.ts +38 -4
  21. package/dist/cli/oauth-session.js +72 -25
  22. package/dist/cli/shared-command-exports.d.ts +4 -0
  23. package/dist/cli/shared-command-exports.js +6 -0
  24. package/dist/cli/token-session.d.ts +9 -3
  25. package/dist/cli/token-session.js +34 -3
  26. package/dist/domain/domain-lists.d.ts +86 -0
  27. package/dist/domain/domain-lists.js +110 -0
  28. package/dist/domain/free-mail-domains.generated.d.ts +1 -0
  29. package/dist/domain/free-mail-domains.generated.js +4 -0
  30. package/dist/domain/models.d.ts +5 -0
  31. package/dist/domain/organization-sectors.d.ts +9 -3
  32. package/dist/domain/organization-sectors.generated.d.ts +1 -0
  33. package/dist/domain/organization-sectors.generated.js +1 -0
  34. package/dist/domain/organization-sectors.js +16 -3
  35. package/dist/domain/person-kinds.d.ts +6 -1
  36. package/dist/domain/person-kinds.js +5 -0
  37. package/dist/entities/contact-context.d.ts +4 -0
  38. package/dist/entities/conversation-results.d.ts +4 -0
  39. package/dist/entities/domain-list.d.ts +27 -0
  40. package/dist/entities/domain-list.js +28 -0
  41. package/dist/entities/evidence.d.ts +16 -0
  42. package/dist/entities/index.d.ts +56 -2
  43. package/dist/entities/index.js +3 -1
  44. package/dist/entities/knowledge-lists.d.ts +1 -1
  45. package/dist/entities/listener.d.ts +8 -0
  46. package/dist/entities/message-change.d.ts +2 -0
  47. package/dist/entities/message-context.d.ts +6 -0
  48. package/dist/entities/message-write.d.ts +8 -0
  49. package/dist/entities/message.d.ts +4 -0
  50. package/dist/entities/message.js +4 -0
  51. package/dist/entities/store-records.d.ts +2 -0
  52. package/dist/errors/reasons.js +20 -2
  53. package/dist/mail/cli/index.js +1 -1
  54. package/dist/mail/headers.d.ts +2 -0
  55. package/dist/mail/headers.js +2 -1
  56. package/dist/mail/mail-types.d.ts +48 -0
  57. package/dist/mail/mail-types.js +218 -0
  58. package/dist/mail/read.js +1 -0
  59. package/dist/mail/sort-rules.d.ts +58 -0
  60. package/dist/mail/sort-rules.js +79 -0
  61. package/dist/oauth/index.d.ts +1 -1
  62. package/dist/oauth/storage.d.ts +10 -2
  63. package/dist/oauth/storage.js +23 -9
  64. package/dist/search/lucene/registry.js +24 -0
  65. package/dist/services/domain-lists-download.d.ts +26 -0
  66. package/dist/services/domain-lists-download.js +155 -0
  67. package/dist/services/messages-search.js +1 -1
  68. package/dist/services/metadata.d.ts +1 -1
  69. package/dist/store/areas.d.ts +3 -1
  70. package/dist/store/areas.js +2 -0
  71. package/dist/store/index.d.ts +2 -2
  72. package/dist/store/index.js +1 -1
  73. package/dist/store/people.d.ts +18 -9
  74. package/dist/store/people.js +8 -7
  75. package/dist/store/public.d.ts +1 -1
  76. package/dist/store/public.js +1 -1
  77. package/dist/store/queries.js +9 -2
  78. package/dist/store/sqlite/accounts.js +3 -1
  79. package/dist/store/sqlite/domain-organizations.d.ts +7 -4
  80. package/dist/store/sqlite/domain-organizations.js +94 -36
  81. package/dist/store/sqlite/email-types.d.ts +87 -0
  82. package/dist/store/sqlite/email-types.js +296 -0
  83. package/dist/store/sqlite/emails.d.ts +14 -2
  84. package/dist/store/sqlite/emails.js +32 -12
  85. package/dist/store/sqlite/identities.d.ts +4 -1
  86. package/dist/store/sqlite/identities.js +11 -2
  87. package/dist/store/sqlite/identity-rekey.js +2 -0
  88. package/dist/store/sqlite/lucene-fields.d.ts +6 -0
  89. package/dist/store/sqlite/lucene-fields.js +10 -0
  90. package/dist/store/sqlite/lucene.js +6 -0
  91. package/dist/store/sqlite/mail-sorting.d.ts +122 -0
  92. package/dist/store/sqlite/mail-sorting.js +482 -0
  93. package/dist/store/sqlite/manifest.js +6 -0
  94. package/dist/store/sqlite/merged-persons.d.ts +3 -2
  95. package/dist/store/sqlite/merged-persons.js +5 -3
  96. package/dist/store/sqlite/migrations.generated.js +76 -0
  97. package/dist/store/sqlite/people-list.d.ts +1 -6
  98. package/dist/store/sqlite/people-list.js +97 -42
  99. package/dist/store/sqlite/person-links.js +13 -3
  100. package/dist/store/sqlite/person-match-scan.js +5 -2
  101. package/dist/store/sqlite/schema/mail-sorting.d.ts +384 -0
  102. package/dist/store/sqlite/schema/mail-sorting.js +31 -0
  103. package/dist/store/sqlite/schema/sender-bots.d.ts +56 -0
  104. package/dist/store/sqlite/schema/sender-bots.js +9 -1
  105. package/dist/store/sqlite/schema.d.ts +66 -1
  106. package/dist/store/sqlite/schema.js +9 -1
  107. package/dist/store/sqlite/sender-bots.d.ts +89 -15
  108. package/dist/store/sqlite/sender-bots.js +417 -136
  109. package/dist/store/sqlite/sender-signals.d.ts +11 -4
  110. package/dist/store/sqlite/sender-signals.js +14 -10
  111. package/package.json +2 -2
@@ -9,8 +9,9 @@ export declare const SEPARATIONS: readonly ["unlink", "split", "undo-merge"];
9
9
  */
10
10
  export declare const mergeSql: (event: string) => string;
11
11
  /**
12
- * A person every identity left by a merge, so another person holds them now. The row stays so that undoing the merge
13
- * gives the uid back; a person added by name has no identity and no move, and stays visible.
12
+ * A person every identity left by a merge or a move to a sender bot, so another person or a bot holds them now. The
13
+ * row stays so that undoing the merge or the move gives the uid back; a person added by name has no identity and no
14
+ * move, and stays visible.
14
15
  */
15
16
  export declare const mergedAwaySql: (person: string) => string;
16
17
  /** The person `pk` is now: itself, or where its identities went, by the latest merge of each merged-away person. */
@@ -17,11 +17,13 @@ export const mergeSql = (event) => `(${event}.from_person_id IS NOT NULL AND ${e
17
17
  `AND went.id = (SELECT min(w.id) FROM identity_link_events w WHERE w.identity_id = stay.identity_id ` +
18
18
  `AND w.id > ${event}.id))))`;
19
19
  /**
20
- * A person every identity left by a merge, so another person holds them now. The row stays so that undoing the merge
21
- * gives the uid back; a person added by name has no identity and no move, and stays visible.
20
+ * A person every identity left by a merge or a move to a sender bot, so another person or a bot holds them now. The
21
+ * row stays so that undoing the merge or the move gives the uid back; a person added by name has no identity and no
22
+ * move, and stays visible.
22
23
  */
23
24
  export const mergedAwaySql = (person) => `(${person}.owner = 0 AND NOT EXISTS (SELECT 1 FROM identity_links ml WHERE ml.person_id = ${person}.id) ` +
24
- `AND EXISTS (SELECT 1 FROM identity_link_events me WHERE me.from_person_id = ${person}.id AND ${mergeSql("me")}))`;
25
+ `AND (EXISTS (SELECT 1 FROM identity_link_events me WHERE me.from_person_id = ${person}.id AND ${mergeSql("me")}) ` +
26
+ `OR EXISTS (SELECT 1 FROM sender_bot_moves mb WHERE mb.from_person_id = ${person}.id AND mb.to_bot_id IS NOT NULL)))`;
25
27
  const LATEST_MOVE = (person) => `(SELECT e.to_person_id FROM identity_link_events e WHERE e.from_person_id = ${person}.id AND ${mergeSql("e")}
26
28
  ORDER BY e.id DESC LIMIT 1)`;
27
29
  /** The person `pk` is now: itself, or where its identities went, by the latest merge of each merged-away person. */
@@ -2114,5 +2114,81 @@ export const GENERATED = [
2114
2114
  "CREATE TRIGGER person_kind_sender_bot_au AFTER UPDATE OF person_id, author, name ON sender_bots BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (OLD.person_id, NEW.person_id);\nEND;",
2115
2115
  "CREATE TRIGGER person_kind_sender_bot_move_ai AFTER INSERT ON sender_bot_moves BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = NEW.identity_id);\nEND;"
2116
2116
  ]
2117
+ },
2118
+ {
2119
+ "name": "20261125111113_version-75-bot-identities",
2120
+ "statements": [
2121
+ "CREATE TABLE `sender_bot_identities` (\n\t`identity_id` integer PRIMARY KEY,\n\t`bot_id` integer NOT NULL,\n\t`created_at` integer NOT NULL\n);",
2122
+ "CREATE INDEX `sender_bot_identities_by_bot_id` ON `sender_bot_identities` (`bot_id`);",
2123
+ "CREATE INDEX `sender_bot_moves_by_from_person_id` ON `sender_bot_moves` (`from_person_id`);"
2124
+ ]
2125
+ },
2126
+ {
2127
+ "name": "20261125111118_version-75-bot-identities-moved",
2128
+ "statements": [
2129
+ "-- A bot of version 74 is a person row holding the bot's identities. Each identity moves to the bot, the move is logged\n-- with the bot's author, and the person row stays, emptied and hidden, so a move back gives its uid back.\nINSERT INTO sender_bot_identities (identity_id, bot_id, created_at)\nSELECT l.identity_id, b.id, CAST(unixepoch('subsec') * 1000 AS INTEGER)\nFROM sender_bots b JOIN identity_links l ON l.person_id = b.person_id;",
2130
+ "INSERT INTO sender_bot_moves (identity_id, from_person_id, from_bot_id, to_person_id, to_bot_id, author, reason, created_at)\nSELECT s.identity_id, b.person_id, NULL, NULL, b.id, b.author, 'store version 75: a bot holds its own identities',\n CAST(unixepoch('subsec') * 1000 AS INTEGER)\nFROM sender_bot_identities s JOIN sender_bots b ON b.id = s.bot_id;",
2131
+ "DELETE FROM identity_links WHERE identity_id IN (SELECT identity_id FROM sender_bot_identities);",
2132
+ "-- Negative: a build before 75 reads a bot as its person row, and this names none.\nUPDATE sender_bots SET person_id = -id;",
2133
+ "-- Stored as a merge's emptied person is, so every build's people list leaves it out.\nCREATE TRIGGER person_kind_sender_bot_origin_au AFTER UPDATE OF kind ON persons\nWHEN NEW.kind IS NOT 'merged' AND NEW.owner = 0\n AND NOT EXISTS (SELECT 1 FROM identity_links WHERE person_id = NEW.id)\n AND EXISTS (SELECT 1 FROM sender_bot_moves WHERE from_person_id = NEW.id AND to_bot_id IS NOT NULL) BEGIN\n UPDATE persons SET kind = 'merged' WHERE id = NEW.id;\nEND;",
2134
+ "UPDATE persons SET kind = 'merged' WHERE owner = 0\n AND NOT EXISTS (SELECT 1 FROM identity_links WHERE person_id = persons.id)\n AND EXISTS (SELECT 1 FROM sender_bot_moves WHERE from_person_id = persons.id AND to_bot_id IS NOT NULL);",
2135
+ "-- An older build's sync links an identity with no person to a new one: a bot's identity gets none.\nCREATE TRIGGER sender_bot_identity_link_bi BEFORE INSERT ON identity_links\nWHEN EXISTS (SELECT 1 FROM sender_bot_identities WHERE identity_id = NEW.identity_id) BEGIN\n SELECT RAISE(IGNORE);\nEND;",
2136
+ "-- A re-key moves a person's link onto an identity a bot holds: the bot keeps it, and the move is logged.\nCREATE TRIGGER sender_bot_identity_link_au AFTER UPDATE OF identity_id ON identity_links\nWHEN EXISTS (SELECT 1 FROM sender_bot_identities WHERE identity_id = NEW.identity_id) BEGIN\n INSERT INTO sender_bot_moves (identity_id, from_person_id, from_bot_id, to_person_id, to_bot_id, author, reason, created_at)\n SELECT NEW.identity_id, NEW.person_id, NULL, NULL, s.bot_id, 'rules', 'the source re-keyed the identity',\n CAST(unixepoch('subsec') * 1000 AS INTEGER)\n FROM sender_bot_identities s WHERE s.identity_id = NEW.identity_id;\n DELETE FROM identity_links WHERE identity_id = NEW.identity_id;\nEND;",
2137
+ "-- ...and the person row it made for it, with its log row, goes again.\nCREATE TRIGGER sender_bot_identity_person_ai AFTER INSERT ON identity_link_events\nWHEN NEW.from_person_id IS NULL\n AND EXISTS (SELECT 1 FROM sender_bot_identities WHERE identity_id = NEW.identity_id)\n AND NOT EXISTS (SELECT 1 FROM identity_links WHERE person_id = NEW.to_person_id) BEGIN\n DELETE FROM identity_link_events WHERE id = NEW.id;\n DELETE FROM persons WHERE id = NEW.to_person_id AND owner = 0\n AND NOT EXISTS (SELECT 1 FROM identity_link_events WHERE from_person_id = NEW.to_person_id OR to_person_id = NEW.to_person_id);\nEND;",
2138
+ "CREATE TRIGGER sender_bot_identities_linked_bi BEFORE INSERT ON sender_bot_identities\nWHEN EXISTS (SELECT 1 FROM identity_links WHERE identity_id = NEW.identity_id) BEGIN\n SELECT RAISE(ABORT, 'sender_bot_identities: the identity is linked to a person; unlink it first');\nEND;",
2139
+ "-- An older build gives a bot back by deleting its row; one that still holds identities stays.\nCREATE TRIGGER sender_bots_holding_bd BEFORE DELETE ON sender_bots\nWHEN EXISTS (SELECT 1 FROM sender_bot_identities WHERE bot_id = OLD.id) BEGIN\n SELECT RAISE(IGNORE);\nEND;",
2140
+ "CREATE TRIGGER sender_bot_identities_identity_ad AFTER DELETE ON identities BEGIN\n DELETE FROM sender_bot_identities WHERE identity_id = OLD.id;\nEND;",
2141
+ "CREATE TRIGGER sender_bots_emptied_ad AFTER DELETE ON sender_bot_identities\nWHEN NOT EXISTS (SELECT 1 FROM sender_bot_identities WHERE bot_id = OLD.bot_id) BEGIN\n DELETE FROM sender_bots WHERE id = OLD.bot_id;\nEND;",
2142
+ "CREATE TRIGGER sender_bots_emptied_au AFTER UPDATE OF bot_id ON sender_bot_identities\nWHEN NOT EXISTS (SELECT 1 FROM sender_bot_identities WHERE bot_id = OLD.bot_id) BEGIN\n DELETE FROM sender_bots WHERE id = OLD.bot_id;\nEND;"
2143
+ ]
2144
+ },
2145
+ {
2146
+ "name": "20261125183530_version-76-mail-types",
2147
+ "statements": [
2148
+ "ALTER TABLE `emails` ADD `mail_type` text;",
2149
+ "ALTER TABLE `emails` ADD `reach` text;",
2150
+ "ALTER TABLE `emails` ADD `type_signal` text;",
2151
+ "CREATE INDEX `emails_by_mail_type` ON `emails` (`mail_type`);",
2152
+ "CREATE INDEX `emails_type_to_work_out` ON `emails` (`id`) WHERE mail_type IS NULL;"
2153
+ ]
2154
+ },
2155
+ {
2156
+ "name": "20261125183555_version-76-mail-type-triggers",
2157
+ "statements": [
2158
+ "CREATE TRIGGER mail_type_email_au AFTER UPDATE OF from_address, from_identity_id, subject, headers, metadata, outgoing, body_html ON emails\nWHEN OLD.from_address IS NOT NEW.from_address OR OLD.from_identity_id IS NOT NEW.from_identity_id OR OLD.subject IS NOT NEW.subject OR OLD.headers IS NOT NEW.headers OR OLD.metadata IS NOT NEW.metadata OR OLD.outgoing IS NOT NEW.outgoing OR OLD.body_html IS NOT NEW.body_html BEGIN\n UPDATE emails SET mail_type = NULL, reach = NULL, type_signal = NULL WHERE mail_type IS NOT NULL AND id = NEW.id;\nEND;",
2159
+ "CREATE TRIGGER mail_type_outgoing_au AFTER UPDATE OF outgoing ON emails\nWHEN NEW.outgoing IS 1 AND OLD.outgoing IS NOT 1 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 email_recipients WHERE email_id = NEW.id AND identity_id IS NOT NULL);\nEND;",
2160
+ "CREATE TRIGGER mail_type_list_ai AFTER INSERT ON emails\nWHEN coalesce(json_extract(NEW.headers, '$.\"list-id\"'), json_extract(NEW.metadata, '$.listId')) IS NOT NULL AND NOT EXISTS (SELECT 1 FROM emails o WHERE coalesce(json_extract(o.headers, '$.\"list-id\"'), json_extract(o.metadata, '$.listId')) = coalesce(json_extract(NEW.headers, '$.\"list-id\"'), json_extract(NEW.metadata, '$.listId')) AND o.from_address IS NEW.from_address AND o.id <> NEW.id) BEGIN\n UPDATE emails SET mail_type = NULL, reach = NULL, type_signal = NULL WHERE mail_type IS NOT NULL AND coalesce(json_extract(headers, '$.\"list-id\"'), json_extract(metadata, '$.listId')) = coalesce(json_extract(NEW.headers, '$.\"list-id\"'), json_extract(NEW.metadata, '$.listId'));\nEND;",
2161
+ "CREATE TRIGGER mail_type_recipient_ai AFTER INSERT ON email_recipients BEGIN\n UPDATE emails SET mail_type = NULL, reach = NULL, type_signal = NULL WHERE mail_type IS NOT NULL AND id = NEW.email_id;\n UPDATE emails SET mail_type = NULL, reach = NULL, type_signal = NULL WHERE mail_type IS NOT NULL AND NEW.identity_id IS NOT NULL AND from_identity_id = NEW.identity_id\n AND (SELECT outgoing FROM emails WHERE id = NEW.email_id) IS 1\n AND NOT EXISTS (SELECT 1 FROM email_recipients r JOIN emails o ON o.id = r.email_id WHERE r.identity_id = NEW.identity_id AND o.outgoing = 1 AND r.email_id <> NEW.email_id);\nEND;",
2162
+ "CREATE TRIGGER mail_type_recipient_ad AFTER DELETE ON email_recipients BEGIN\n UPDATE emails SET mail_type = NULL, reach = NULL, type_signal = NULL WHERE mail_type IS NOT NULL AND id = OLD.email_id;\nEND;",
2163
+ "CREATE TRIGGER mail_type_recipient_au AFTER UPDATE OF email_id, identity_id, address, role ON email_recipients\nWHEN OLD.email_id IS NOT NEW.email_id OR OLD.identity_id IS NOT NEW.identity_id OR OLD.address IS NOT NEW.address OR OLD.role IS NOT NEW.role BEGIN\n UPDATE emails SET mail_type = NULL, reach = NULL, type_signal = NULL WHERE mail_type IS NOT NULL AND id IN (OLD.email_id, NEW.email_id);\nEND;",
2164
+ "CREATE TRIGGER mail_type_attachment_ai AFTER INSERT ON attachments\nWHEN NEW.attachable_type = 'email' AND lower(NEW.mime) IN ('text/calendar', 'application/ics', 'message/delivery-status', 'message/disposition-notification') BEGIN\n UPDATE emails SET mail_type = NULL, reach = NULL, type_signal = NULL WHERE mail_type IS NOT NULL AND id = NEW.attachable_id;\nEND;",
2165
+ "CREATE TRIGGER mail_type_attachment_ad AFTER DELETE ON attachments\nWHEN OLD.attachable_type = 'email' AND lower(OLD.mime) IN ('text/calendar', 'application/ics', 'message/delivery-status', 'message/disposition-notification') BEGIN\n UPDATE emails SET mail_type = NULL, reach = NULL, type_signal = NULL WHERE mail_type IS NOT NULL AND id = OLD.attachable_id;\nEND;",
2166
+ "CREATE TRIGGER mail_type_attachment_au AFTER UPDATE OF mime ON attachments\nWHEN NEW.attachable_type = 'email' AND OLD.mime IS NOT NEW.mime BEGIN\n UPDATE emails SET mail_type = NULL, reach = NULL, type_signal = NULL WHERE mail_type IS NOT NULL AND id = NEW.attachable_id;\nEND;",
2167
+ "CREATE TRIGGER mail_type_bot_ai AFTER INSERT ON sender_bot_identities BEGIN\n UPDATE emails SET mail_type = NULL, reach = NULL, type_signal = NULL WHERE mail_type IS NOT NULL AND from_identity_id = NEW.identity_id;\nEND;",
2168
+ "CREATE TRIGGER mail_type_bot_ad AFTER DELETE ON sender_bot_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;",
2169
+ "CREATE TRIGGER mail_type_organization_ai AFTER INSERT 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 = NEW.identity_id;\nEND;",
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
+ "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
+ ]
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
+ ]
2117
2193
  }
2118
2194
  ];
@@ -38,13 +38,8 @@ export interface ListedPerson {
38
38
  messagesFrom: number;
39
39
  /** The newest of their messages, their mail and their one-to-one chat's last message, as ISO time. */
40
40
  lastContact: string | null;
41
- /** Why they are shown; empty for someone hidden by default, and for a bot. */
41
+ /** Why they are shown; empty for someone hidden by default. */
42
42
  ties: ShownBecause[];
43
- /**
44
- * The sender bot this row is (`sender-bot:<id>`), listed as `automated` under its person row's ref; `null` for a
45
- * person.
46
- */
47
- bot: string | null;
48
43
  /** How their messages reached the owner (`senderSignalsOf`); `null` when nothing says. Worked out for the page. */
49
44
  reach: Reach | null;
50
45
  /** What their mail and addresses show about who writes and how it reached the owner. Worked out for the page. */
@@ -8,8 +8,8 @@ import { fold } from "../normalize.js";
8
8
  import { groupByDomain } from "./domain-organizations.js";
9
9
  import { mergedAwaySql } from "./merged-persons.js";
10
10
  import { ALWAYS_SHOWN, shownReasons } from "./person-ties.js";
11
- import { ownerPeopleOf, ruleMove, SENDER_BOT_PREFIX, senderBotsOf } from "./sender-bots.js";
12
- import { senderSignalsOf, sentMailOf } from "./sender-signals.js";
11
+ import { hasLegacyBots, NEWSLETTER_ONLY, newsletterBotsMail, ownerPeopleOf, ruleBotsBack, ruleToBot, settleLegacyBots, settleNewsletterBots, } from "./sender-bots.js";
12
+ import { LIST_ID, senderSignalsOf, sentMailOf } from "./sender-signals.js";
13
13
  import { mergedAssignees } from "./task-board.js";
14
14
  import { hiddenTestPeople } from "./test-people.js";
15
15
  import { read, writeBatch } from "./transaction.js";
@@ -50,12 +50,16 @@ const IDENTITY_MAIL_COUNTS = (scope) => `SELECT from_identity_id AS identity, co
50
50
  const TWO_WAY = "SELECT DISTINCT s.sender_identity_id AS identity_id FROM messages s WHERE s.outgoing IS NOT 1 " +
51
51
  "AND s.sender_identity_id IS NOT NULL AND s.chat_id IN (SELECT c.id FROM chats c WHERE c.kind = 'dialog' " +
52
52
  "AND EXISTS (SELECT 1 FROM messages o WHERE o.chat_id = c.id AND o.outgoing = 1))";
53
- const MAIL_COUNTS = (scope) => "SELECT l.person_id AS person, count(*) AS n, sum(EXISTS (SELECT 1 FROM email_mailboxes m " +
54
- "JOIN mailboxes b ON b.id = m.mailbox_id WHERE m.email_id = e.id AND b.kind = 'bulk')) AS bulk, " +
55
- "sum(json_extract(e.headers, '$.\"auto-submitted\"') IS NOT NULL) AS auto, " +
56
- "sum(json_extract(e.headers, '$.\"null-return-path\"') IS 1) AS null_return " +
53
+ const MAIL_COUNTS = (scope) => "SELECT person, count(*) AS n, sum(bulk) AS bulk, sum(auto) AS auto, sum(null_return) AS null_return, " +
54
+ "sum(bulk OR listed) AS listed FROM (SELECT l.person_id AS person, EXISTS (SELECT 1 FROM email_mailboxes m " +
55
+ "JOIN mailboxes b ON b.id = m.mailbox_id WHERE m.email_id = e.id AND b.kind = 'bulk') AS bulk, " +
56
+ "json_extract(e.headers, '$.\"auto-submitted\"') IS NOT NULL AS auto, " +
57
+ "json_extract(e.headers, '$.\"null-return-path\"') IS 1 AS null_return, " +
58
+ `${LIST_ID} IS NOT NULL OR json_extract(e.headers, '$."list-unsubscribe"') IS 1 ` +
59
+ "OR json_extract(e.headers, '$.\"list-unsubscribe-post\"') IS 1 OR json_extract(e.headers, '$.\"feedback-id\"') IS 1 " +
60
+ "OR json_extract(e.headers, '$.precedence') IN ('bulk', 'junk') AS listed " +
57
61
  "FROM emails e JOIN identity_links l ON l.identity_id = e.from_identity_id " +
58
- `WHERE e.outgoing IS NOT 1 AND e.deleted_at IS NULL AND ${IN_SCOPE(scope, "l.person_id")} GROUP BY 1`;
62
+ `WHERE e.outgoing IS NOT 1 AND e.deleted_at IS NULL AND ${IN_SCOPE(scope, "l.person_id")}) GROUP BY 1`;
59
63
  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 " +
60
64
  `FROM identity_links l JOIN identities i ON i.id = l.identity_id WHERE ${IN_SCOPE(scope, "l.person_id")} ORDER BY i.id`;
61
65
  /** Few identities have these; one pass each beats a lookup per identity. */
@@ -112,6 +116,7 @@ const factsOf = (database, scope) => {
112
116
  messages: 0,
113
117
  identities: held.length,
114
118
  programIdentities: 0,
119
+ notMail: 0,
115
120
  };
116
121
  const source = (row) => ({
117
122
  provider: String(row.provider),
@@ -133,6 +138,8 @@ const factsOf = (database, scope) => {
133
138
  one.organization ||= owned.has(identity);
134
139
  one.twoWay ||= twoWay.has(identity);
135
140
  one.messages += messages.get(identity) ?? 0;
141
+ if (row.provider !== "email")
142
+ one.notMail += 1;
136
143
  if (Number(row.bot) === 1 || (email !== null && (isNoReplyAddress(email) || isNotificationAddress(email))))
137
144
  one.programIdentities += 1;
138
145
  }
@@ -162,7 +169,10 @@ const lastContacts = (database, scope) => new Map(database
162
169
  .map((row) => [Number(row.person), Number(row.at)]));
163
170
  /** One misfiled letter is no newsletter. */
164
171
  const BULK_MIN = 3;
165
- /** A program writes: enough to move a sender to a bot. A name or a bulk mailbox alone may be a human's newsletter. */
172
+ /**
173
+ * A program writes: enough to move a sender to a bot. A name or a bulk mailbox alone does not; a sender all of whose
174
+ * mail a list sent becomes a bot by `NEWSLETTER_ONLY` instead, which a 1-to-1 mail gives back.
175
+ */
166
176
  const PROGRAM_SIGNALS = [
167
177
  "bot",
168
178
  "no-reply",
@@ -172,11 +182,12 @@ const PROGRAM_SIGNALS = [
172
182
  "bulk-never-replied",
173
183
  ];
174
184
  /** The first rule that holds; the list's contract in the people-clients-digests plan names the same order. */
175
- const kindOf = (shown, facts, ties, mail, test, held) => {
185
+ const kindOf = (shown, facts, ties, mail, test, keptByOwner = false, newsletterOnly = false) => {
176
186
  if (test)
177
187
  return { kind: "test", signals: ["test-data"] };
178
188
  const emails = facts?.emails ?? [];
179
189
  const automated = [
190
+ ...(newsletterOnly ? [NEWSLETTER_ONLY] : []),
180
191
  ...(facts?.bot ? ["bot"] : []),
181
192
  ...(emails.some(isNoReplyAddress) ? ["no-reply"] : []),
182
193
  ...(emails.some(isNotificationAddress) ? ["notification-address"] : []),
@@ -189,13 +200,11 @@ const kindOf = (shown, facts, ties, mail, test, held) => {
189
200
  ? ["null-return-path"]
190
201
  : []),
191
202
  ];
192
- if (held === "bot")
193
- return { kind: "automated", signals: automated.length > 0 ? automated : ["owner-choice"] };
194
203
  const always = ties.filter((tie) => ALWAYS_SHOWN.includes(tie));
195
204
  if (always.length > 0)
196
205
  return { kind: "person", signals: ties };
197
206
  // One mailbox's newsletter signal must not hide someone the owner talks to in a private chat.
198
- if (held !== "person" && automated.length > 0 && (facts?.bot || !facts?.twoWay))
207
+ if (!keptByOwner && automated.length > 0 && (facts?.bot || !facts?.twoWay))
199
208
  return { kind: "automated", signals: automated };
200
209
  const organization = [
201
210
  ...(facts?.organization ? ["organization"] : []),
@@ -221,12 +230,28 @@ const isProgram = ({ kind, signals }, facts, ties) => kind === "automated" &&
221
230
  signals.some((signal) => PROGRAM_SIGNALS.includes(signal)) &&
222
231
  (facts.bot || (!facts.twoWay && !ties.includes("mail"))) &&
223
232
  (facts.identities === 1 || facts.programIdentities === facts.identities);
224
- const moveOf = (bot, program) => bot === undefined ? (program ? "bot" : undefined) : bot.author === "rules" && !program ? "person" : undefined;
233
+ /**
234
+ * The owner ruled on 2026-11-25 that a sender who only sends a newsletter is a bot, a human author too: all their mail
235
+ * came as a list's, and they and the owner never exchanged a word. Any tie keeps them a person.
236
+ */
237
+ const mayBeNewsletterOnly = (facts, ties, mail) => facts !== undefined &&
238
+ mail !== undefined &&
239
+ ties.length === 0 &&
240
+ !facts.bot &&
241
+ !facts.twoWay &&
242
+ facts.messages === 0 &&
243
+ facts.notMail === 0 &&
244
+ mail.n > 0 &&
245
+ mail.listed === mail.n;
246
+ /** A candidate whose mail came through a discussion list writes to a group, not to subscribers. */
247
+ const newsletterOnlyOf = (database, candidates) => {
248
+ const sent = sentMailOf(database, candidates);
249
+ return new Set(candidates.filter((id) => (sent.get(id) ?? []).every((one) => !one.discussionList)));
250
+ };
225
251
  /** Each person with their kind, contact and counts; the last contact is added for the page alone. */
226
252
  const classified = (database, people, scope, reasons = shownReasons(database, scope === "all" ? undefined : scope)) => {
227
253
  const facts = factsOf(database, scope);
228
254
  const test = hiddenTestPeople(database);
229
- const bots = senderBotsOf(database);
230
255
  const ownerPeople = ownerPeopleOf(database);
231
256
  const tasks = countsOf(database, TASK_COUNTS, mergedAssignees(database));
232
257
  const mail = new Map(database
@@ -234,26 +259,40 @@ const classified = (database, people, scope, reasons = shownReasons(database, sc
234
259
  .all(...scopeParams(scope))
235
260
  .map((row) => [
236
261
  Number(row.person),
237
- { n: Number(row.n), bulk: Number(row.bulk), auto: Number(row.auto), nullReturn: Number(row.null_return) },
262
+ {
263
+ n: Number(row.n),
264
+ bulk: Number(row.bulk),
265
+ auto: Number(row.auto),
266
+ nullReturn: Number(row.null_return),
267
+ listed: Number(row.listed),
268
+ },
238
269
  ]));
270
+ const newsletters = newsletterOnlyOf(database, people.flatMap(({ id, owner }) => !owner &&
271
+ !ownerPeople.has(id) &&
272
+ !test.has(id) &&
273
+ mayBeNewsletterOnly(facts.get(id), reasons.get(id) ?? [], mail.get(id))
274
+ ? [id]
275
+ : []));
239
276
  return people.map(({ id, name, owner }) => {
240
277
  const own = facts.get(id);
241
278
  const contact = { username: own?.username ?? null, phone: own?.phone ?? null, email: own?.email ?? null };
242
279
  const shown = displayName(name, { ...contact, name: own?.name ?? null });
243
280
  const ties = reasons.get(id) ?? [];
244
- const bot = bots.get(id);
245
- const held = bot?.author === "owner" ? "bot" : ownerPeople.has(id) && bot === undefined ? "person" : undefined;
246
- const worked = kindOf(shown, own, ties, mail.get(id), test.has(id), held);
247
- const move = held === undefined && !owner && worked.kind !== "test" ? moveOf(bot, isProgram(worked, own, ties)) : undefined;
248
- const isBot = (bot !== undefined && move !== "person") || move === "bot";
249
- const named = bot?.name ?? shown;
281
+ const kept = ownerPeople.has(id);
282
+ const worked = kindOf(shown, own, ties, mail.get(id), test.has(id), kept, newsletters.has(id));
283
+ const program = !kept && !owner && worked.kind !== "test" && isProgram(worked, own, ties);
284
+ const botReason = program
285
+ ? worked.signals.filter((signal) => signal !== NEWSLETTER_ONLY).join(", ")
286
+ : newsletters.has(id)
287
+ ? NEWSLETTER_ONLY
288
+ : undefined;
250
289
  return {
251
290
  id,
252
- ...(move === undefined ? {} : { move }),
253
- nameOrder: nameOrderOf(named),
291
+ ...(botReason === undefined ? {} : { move: "bot", botReason }),
292
+ nameOrder: nameOrderOf(shown),
254
293
  person: `person:${id}`,
255
294
  name,
256
- displayName: named,
295
+ displayName: shown,
257
296
  kind: worked.kind,
258
297
  kindSignals: worked.signals,
259
298
  owner,
@@ -262,8 +301,7 @@ const classified = (database, people, scope, reasons = shownReasons(database, sc
262
301
  ...contact,
263
302
  usernameSource: own?.usernameSource ?? null,
264
303
  messagesFrom: (own?.messages ?? 0) + (mail.get(id)?.n ?? 0),
265
- ties: isBot ? [] : ties,
266
- bot: bot !== undefined && move !== "person" ? `${SENDER_BOT_PREFIX}${bot.id}` : null,
304
+ ties,
267
305
  emails: own?.emails ?? [],
268
306
  twoWay: own?.twoWay ?? false,
269
307
  };
@@ -273,7 +311,7 @@ const withLastContact = (database, people, known) => {
273
311
  const at = known ??
274
312
  lastContacts(database, people.map(({ id }) => id));
275
313
  const sent = sentMailOf(database, people.map(({ id }) => id));
276
- return people.map(({ id, nameOrder: _, emails, twoWay, move: __, ...person }) => {
314
+ return people.map(({ id, nameOrder: _, emails, twoWay, move: __, botReason: ___, ...person }) => {
277
315
  const time = at.get(id);
278
316
  const { ties } = person;
279
317
  return {
@@ -294,7 +332,7 @@ const byName = (a, b) => a.nameOrder < b.nameOrder ? -1 : a.nameOrder > b.nameOr
294
332
  * Bump when what decides a kind, a name's order or a count changes in code (the word lists, `BULK_MIN`, the ties):
295
333
  * every stored one is worked out again on the next list.
296
334
  */
297
- const KIND_RULES = "9";
335
+ const KIND_RULES = "10";
298
336
  const RULES_KEY = "people.kind_rules";
299
337
  /** Past this many people to work out, one pass over everyone beats a lookup per person. */
300
338
  const WHOLE_PASS = 20_000;
@@ -335,21 +373,32 @@ const workOut = (database, all, most) => {
335
373
  };
336
374
  const keep = (database, worked) => {
337
375
  const at = Date.now();
338
- // Before the kinds: a move clears the person's kind through its triggers.
376
+ settleLegacyBots(database, at);
377
+ ruleBotsBack(database, at);
378
+ const bots = [];
339
379
  for (const person of worked)
340
- if (person.move !== undefined && person.kind !== MERGED)
341
- ruleMove(database, person.id, person.move, person.kindSignals.join(", "), at);
380
+ if (person.move === "bot" && person.kind !== MERGED) {
381
+ bots.push({
382
+ id: ruleToBot(database, person.id, person.botReason ?? person.kindSignals.join(", "), at),
383
+ displayName: person.displayName,
384
+ holds: true,
385
+ bot: true,
386
+ });
387
+ person.kind = MERGED;
388
+ }
342
389
  const keptAsPeople = ownerPeopleOf(database);
343
- groupByDomain(database, worked
344
- .filter((person) => !person.owner && person.kind !== MERGED && person.kind !== "test")
345
- .map((person) => ({
346
- id: person.id,
347
- displayName: person.displayName,
348
- holds: !keptAsPeople.has(person.id) &&
349
- (person.bot !== null ||
350
- person.move === "bot" ||
351
- (person.kind === "organization" && person.kindSignals.includes("role-address"))),
352
- })), at);
390
+ groupByDomain(database, [
391
+ ...bots,
392
+ ...worked
393
+ .filter((person) => !person.owner && person.kind !== MERGED && person.kind !== "test")
394
+ .map((person) => ({
395
+ id: person.id,
396
+ displayName: person.displayName,
397
+ holds: !keptAsPeople.has(person.id) &&
398
+ person.kind === "organization" &&
399
+ person.kindSignals.includes("role-address"),
400
+ })),
401
+ ], at);
353
402
  const row = database.prepare("UPDATE persons SET kind = ?, name_order = ?, messages_from = ?, task_count = ?, last_contact = ? WHERE id = ?");
354
403
  for (const person of worked)
355
404
  row.run(person.kind, person.nameOrder, person.messagesFrom, person.tasks, person.lastContact ?? null, person.id);
@@ -365,6 +414,12 @@ const keep = (database, worked) => {
365
414
  * Answers whether every stored one is current.
366
415
  */
367
416
  export const storeKinds = (database) => {
417
+ // A 1.0 build keeps the kinds of the people it sorts onto a bot, so nothing else would bring their bot here.
418
+ if (!isQueryOnly(database) && hasLegacyBots(database))
419
+ writeBatch(database, () => settleLegacyBots(database, Date.now()));
420
+ const newest = isQueryOnly(database) ? undefined : newsletterBotsMail(database);
421
+ if (newest !== undefined)
422
+ writeBatch(database, () => settleNewsletterBots(database, newest, Date.now()));
368
423
  if (isQueryOnly(database))
369
424
  return (rulesOf(database) === KIND_RULES &&
370
425
  database.prepare("SELECT 1 FROM persons WHERE kind IS NULL LIMIT 1").get() === undefined);
@@ -552,7 +607,7 @@ export const similarPeople = (database, typed, limit) => {
552
607
  }));
553
608
  const byId = new Map(people.map((person) => [person.id, person]));
554
609
  const ordered = [...sameName.keys()].flatMap((id) => byId.get(id) ?? []);
555
- const rows = classified(database, ordered, [...sameName.keys()], ties).filter(({ kind, bot }) => kind !== "test" && bot === null);
610
+ const rows = classified(database, ordered, [...sameName.keys()], ties).filter(({ kind, move }) => kind !== "test" && move === undefined);
556
611
  const same = rows.map(({ id }) => sameName.get(id) === true);
557
612
  return withLastContact(database, rows).map((person, at) => ({ ...person, sameName: same[at] === true }));
558
613
  };
@@ -1,6 +1,7 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { isEmailAddress, isRoleAddress } from "../../domain/addresses.js";
3
3
  import { displayName, noFallbacks, takeFallbacks } from "../../domain/display-names.js";
4
+ import { SENDER_BOT_PREFIX } from "../../domain/person-kinds.js";
4
5
  import { and, eq, inArray, isNull, sql } from "./drizzle/core.js";
5
6
  import { identityOf } from "./identities.js";
6
7
  import { rejectedEvidence, settleLinks } from "./identity-link-rows.js";
@@ -17,9 +18,18 @@ const identityRow = ({ orm }, { provider, id }) => orm
17
18
  .get();
18
19
  export const required = (context, ref) => {
19
20
  const found = identityRow(context, ref);
20
- if (!found)
21
- throw new CliError("not_found", `no ${ref.provider} person ${ref.id} in the store`);
22
- return found;
21
+ if (found)
22
+ return found;
23
+ const bot = context.database
24
+ .prepare("SELECT s.bot_id FROM sender_bot_identities s JOIN identities i ON i.id = s.identity_id " +
25
+ "WHERE i.provider = ? AND i.external_id = ?")
26
+ .get(ref.provider, ref.id);
27
+ if (bot !== undefined)
28
+ throw new CliError("validation_error", `${ref.provider} ${ref.id} is ${SENDER_BOT_PREFIX}${bot.bot_id}, not a person`, {
29
+ reason: "sender-bot.not-a-person",
30
+ reference: `${SENDER_BOT_PREFIX}${bot.bot_id}`,
31
+ });
32
+ throw new CliError("not_found", `no ${ref.provider} person ${ref.id} in the store`);
23
33
  };
24
34
  /** Every phone and address an identity holds: the source's lists, else the one `phone` and `email`. */
25
35
  const contactListsOf = ({ phone, email }, metadata) => {
@@ -233,9 +233,12 @@ const touchesOwner = ({ context, result }, from, to, signal) => {
233
233
  result.skipped.push({ persons: [String(from), String(to)], signal, reason: "identity.owner" });
234
234
  return true;
235
235
  };
236
- /** A sender bot is never proposed as the same person, by any signal; the owner moves it by hand. */
236
+ /** A person every identity left for a sender bot is never proposed as the same person; the owner moves it by hand. */
237
237
  const touchesBot = ({ context, result }, from, to, signal) => {
238
- const held = context.database.prepare("SELECT 1 FROM sender_bots WHERE person_id IN (?, ?) LIMIT 1").get(from, to);
238
+ const held = context.database
239
+ .prepare("SELECT 1 FROM sender_bot_moves m WHERE m.from_person_id IN (?, ?) AND m.to_bot_id IS NOT NULL " +
240
+ "AND NOT EXISTS (SELECT 1 FROM identity_links l WHERE l.person_id = m.from_person_id) LIMIT 1")
241
+ .get(from, to);
239
242
  if (held === undefined)
240
243
  return false;
241
244
  result.skipped.push({ persons: [String(from), String(to)], signal, reason: "identity.not-a-person" });