@wirecat/cli-core 1.0.0-rc.0 → 1.1.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 (96) hide show
  1. package/CHANGELOG.md +186 -0
  2. package/THIRD_PARTY_NOTICES +47 -0
  3. package/dist/cli/account-rename.js +1 -1
  4. package/dist/cli/bot/api-input.d.ts +5 -0
  5. package/dist/cli/bot/api-input.js +6 -1
  6. package/dist/cli/bot/api.js +7 -1
  7. package/dist/cli/domain-lists-command.d.ts +16 -0
  8. package/dist/cli/domain-lists-command.js +88 -0
  9. package/dist/cli/index.d.ts +4 -3
  10. package/dist/cli/index.js +3 -2
  11. package/dist/cli/model-catalogue-command.d.ts +6 -0
  12. package/dist/cli/model-catalogue-command.js +1 -1
  13. package/dist/cli/oauth-session.d.ts +38 -4
  14. package/dist/cli/oauth-session.js +66 -22
  15. package/dist/cli/service-api.js +3 -1
  16. package/dist/cli/shared-command-exports.d.ts +2 -0
  17. package/dist/cli/shared-command-exports.js +3 -0
  18. package/dist/cli/token-session.d.ts +9 -0
  19. package/dist/cli/token-session.js +29 -2
  20. package/dist/crm/manifest/map.d.ts +5 -2
  21. package/dist/crm/manifest/map.js +14 -2
  22. package/dist/domain/domain-lists.d.ts +86 -0
  23. package/dist/domain/domain-lists.js +110 -0
  24. package/dist/domain/free-mail-domains.generated.d.ts +1 -0
  25. package/dist/domain/free-mail-domains.generated.js +4 -0
  26. package/dist/domain/organization-sectors.d.ts +16 -0
  27. package/dist/domain/organization-sectors.generated.d.ts +12 -0
  28. package/dist/domain/organization-sectors.generated.js +15 -0
  29. package/dist/domain/organization-sectors.js +22 -0
  30. package/dist/domain/person-kinds.d.ts +5 -0
  31. package/dist/domain/person-kinds.js +5 -0
  32. package/dist/entities/domain-list.d.ts +27 -0
  33. package/dist/entities/domain-list.js +28 -0
  34. package/dist/entities/index.d.ts +20 -1
  35. package/dist/entities/index.js +3 -1
  36. package/dist/entities/knowledge-lists.d.ts +1 -0
  37. package/dist/entities/knowledge-lists.js +2 -0
  38. package/dist/errors/reasons.js +14 -3
  39. package/dist/mail/mail-types.d.ts +48 -0
  40. package/dist/mail/mail-types.js +218 -0
  41. package/dist/mail/score.d.ts +2 -0
  42. package/dist/mail/score.js +9 -2
  43. package/dist/oauth/index.d.ts +1 -1
  44. package/dist/oauth/storage.d.ts +10 -2
  45. package/dist/oauth/storage.js +23 -9
  46. package/dist/services/domain-lists-download.d.ts +26 -0
  47. package/dist/services/domain-lists-download.js +155 -0
  48. package/dist/services/search-all-rank.d.ts +44 -0
  49. package/dist/services/search-all-rank.js +112 -0
  50. package/dist/services/search-all-tracker.d.ts +58 -0
  51. package/dist/services/search-all-tracker.js +155 -0
  52. package/dist/services/search-all.d.ts +1 -8
  53. package/dist/services/search-all.js +18 -199
  54. package/dist/services/tracker-meaning.js +1 -1
  55. package/dist/store/areas.d.ts +1 -0
  56. package/dist/store/index.d.ts +2 -1
  57. package/dist/store/index.js +1 -1
  58. package/dist/store/people.d.ts +30 -0
  59. package/dist/store/people.js +16 -1
  60. package/dist/store/sqlite/accounts.js +3 -1
  61. package/dist/store/sqlite/domain-organizations.d.ts +36 -0
  62. package/dist/store/sqlite/domain-organizations.js +288 -0
  63. package/dist/store/sqlite/email-types.d.ts +79 -0
  64. package/dist/store/sqlite/email-types.js +261 -0
  65. package/dist/store/sqlite/emails.d.ts +11 -2
  66. package/dist/store/sqlite/emails.js +18 -7
  67. package/dist/store/sqlite/identities.d.ts +4 -1
  68. package/dist/store/sqlite/identities.js +11 -2
  69. package/dist/store/sqlite/identity-rekey.js +2 -0
  70. package/dist/store/sqlite/knowledge.d.ts +2 -9
  71. package/dist/store/sqlite/manifest.js +6 -0
  72. package/dist/store/sqlite/merged-persons.d.ts +3 -2
  73. package/dist/store/sqlite/merged-persons.js +5 -3
  74. package/dist/store/sqlite/migrations.generated.js +77 -0
  75. package/dist/store/sqlite/organizations.d.ts +12 -1
  76. package/dist/store/sqlite/organizations.js +9 -1
  77. package/dist/store/sqlite/people-list.js +69 -11
  78. package/dist/store/sqlite/person-links.js +13 -3
  79. package/dist/store/sqlite/person-match-scan.js +14 -1
  80. package/dist/store/sqlite/schema/sender-bots.d.ts +344 -0
  81. package/dist/store/sqlite/schema/sender-bots.js +30 -0
  82. package/dist/store/sqlite/schema.d.ts +49 -0
  83. package/dist/store/sqlite/schema.js +7 -0
  84. package/dist/store/sqlite/sender-bots.d.ts +108 -0
  85. package/dist/store/sqlite/sender-bots.js +431 -0
  86. package/dist/store/sqlite/sender-signals.d.ts +13 -3
  87. package/dist/store/sqlite/sender-signals.js +17 -13
  88. package/dist/store/sqlite/tracker.d.ts +11 -9
  89. package/dist/store/sqlite/tracker.js +27 -12
  90. package/dist/store/sqlite/work-tasks.js +2 -0
  91. package/dist/tracker/cli/index.d.ts +1 -1
  92. package/dist/tracker/cli/index.js +83 -24
  93. package/dist/tracker/sync.js +43 -20
  94. package/dist/tracker/writes.d.ts +28 -0
  95. package/dist/tracker/writes.js +141 -19
  96. package/package.json +3 -3
@@ -1,13 +1,16 @@
1
1
  import type { Message } from "../../domain/models.js";
2
+ import type { MailType } from "../../mail/mail-types.js";
2
3
  import type { Attachment, Metadata } from "../../meetings/index.js";
3
4
  import type { Stemmer, Stemmers } from "../../search/stem.js";
4
5
  import type { CacheDatabase } from "../driver.js";
5
6
  import type { ConversationSummary, StoredHit } from "../types.js";
6
7
  import { type MailActivityStore } from "./email-activity.js";
7
8
  import { type EmailLocationInput, type FolderEmail, type PartialMailStore } from "./email-locations.js";
9
+ import { type MailTypeStore, type TypeFilter } from "./email-types.js";
8
10
  import { type MailRulesStore } from "./mail-rules.js";
9
11
  import { type AttachmentInput } from "./meetings.js";
10
12
  import type { StoreContext } from "./open.js";
13
+ import type { Reach } from "./sender-signals.js";
11
14
  import { type SyncStateSave } from "./sync.js";
12
15
  import { type ThreadFilter } from "./thread-columns.js";
13
16
  export type { EmailLocationInput, FolderEmail, PartialEmail } from "./email-locations.js";
@@ -115,6 +118,12 @@ export interface Email {
115
118
  headers: Metadata;
116
119
  metadata: Metadata;
117
120
  mailRuleId: number | null;
121
+ /** What it is, apart from who sent it (docs/dev/GLOSSARY.md, "mail type"). @experimental */
122
+ mailType: MailType | null;
123
+ /** How it reached the owner. @experimental */
124
+ reach: Reach | null;
125
+ /** What decided `mailType`, such as `list-id`. @experimental */
126
+ typeSignal: string | null;
118
127
  recipients: EmailRecipient[];
119
128
  mailboxes: Mailbox[];
120
129
  attachments: EmailAttachment[];
@@ -150,7 +159,7 @@ export interface MailFilter {
150
159
  limit?: number;
151
160
  offset?: number;
152
161
  }
153
- export interface EmailFilter extends MailFilter {
162
+ export interface EmailFilter extends MailFilter, TypeFilter {
154
163
  threadExternalId?: string;
155
164
  /** An address in From, To, Cc, Bcc or Reply-To. */
156
165
  participant?: string;
@@ -206,7 +215,7 @@ export interface SenderScore {
206
215
  demoted?: boolean;
207
216
  }
208
217
  /** Mail in tables of its own: threads, emails, recipients and mailboxes, keyed by account and Message-ID. */
209
- export interface MailStore extends PartialMailStore, MailActivityStore {
218
+ export interface MailStore extends PartialMailStore, MailActivityStore, MailTypeStore {
210
219
  saveThread(input: ThreadSave): Promise<ThreadDetails>;
211
220
  /** Several threads and sync state in one transaction: a slice of mail commits with its resume point, or not at all. */
212
221
  saveThreads(inputs: ThreadSave[], states?: SyncStateSave[]): Promise<ThreadDetails[]>;
@@ -5,6 +5,7 @@ import { mailActivity, threadEmailIds } from "./email-activity.js";
5
5
  import { chunkAttachments, drainEmailIndex, dropAttachmentChunks, MAIL_PIECES, queueThreads, threadPieces, titleOf, } from "./email-index.js";
6
6
  import { backfillSentAt, folderEmails, forgetLocations, locate, partialMail, setLocations, storedWhole, } from "./email-locations.js";
7
7
  import { markEmailsDeleted, markEmailsRestored, markOwnMail, recountEmailThread as recount, setEmailFlags, } from "./email-state.js";
8
+ import { mailTypeStore, typeWhere, withTypes } from "./email-types.js";
8
9
  import { EMAIL_ENRICHMENT, enrichmentText } from "./enrichments.js";
9
10
  import { bool, flag, fromJson, int, page, str, toJson } from "./events.js";
10
11
  import { folded } from "./folded.js";
@@ -93,6 +94,9 @@ const emailOf = (database, row) => ({
93
94
  headers: fromJson(row.headers),
94
95
  metadata: fromJson(row.metadata),
95
96
  mailRuleId: int(row.mail_rule_id),
97
+ mailType: str(row.mail_type),
98
+ reach: str(row.reach),
99
+ typeSignal: str(row.type_signal),
96
100
  recipients: database
97
101
  .prepare("SELECT * FROM email_recipients WHERE email_id = ? ORDER BY position")
98
102
  .all(Number(row.id))
@@ -290,7 +294,7 @@ const saveThread = (database, orm, input) => {
290
294
  queueThreads(database, moved);
291
295
  return threadId;
292
296
  };
293
- const emailWhere = (filter) => {
297
+ const emailWhere = (database, filter) => {
294
298
  const where = ["(? OR e.deleted_at IS NULL)"];
295
299
  const params = [filter.includeDeleted ? 1 : 0];
296
300
  const add = (sql, ...values) => {
@@ -321,6 +325,11 @@ const emailWhere = (filter) => {
321
325
  AND extraction_error IN (${filter.attachmentErrors.map(() => "?").join(",") || "NULL"}))`, ...filter.attachmentErrors);
322
326
  if (filter.externalIds !== undefined)
323
327
  add("e.external_id IN (SELECT value FROM json_each(?))", JSON.stringify(filter.externalIds));
328
+ const typed = typeWhere(database, filter);
329
+ for (const sql of typed.sql)
330
+ add(sql);
331
+ for (const value of typed.params)
332
+ params.push(value);
324
333
  return [where.join(" AND "), params];
325
334
  };
326
335
  /** An email as a message of its thread, the shape mail had when it was stored as messages. */
@@ -450,19 +459,20 @@ export const mailStoreOver = ({ database, orm, now }, stemmerFor = stemmerCache(
450
459
  const row = database
451
460
  .prepare("SELECT * FROM emails WHERE account_id = ? AND external_id = ?")
452
461
  .get(accountId, externalId);
453
- return row ? emailOf(database, row) : null;
462
+ return row ? withTypes(database, [emailOf(database, row)])[0] : null;
454
463
  },
455
464
  async emails(filter = {}) {
456
465
  const [limit, offset] = page(filter);
457
- const [where, params] = emailWhere(filter);
458
- return database
466
+ const [where, params] = emailWhere(database, filter);
467
+ const emails = database
459
468
  .prepare(`SELECT e.* FROM emails e WHERE ${where}
460
469
  ORDER BY coalesce(e.sent_at, e.received_at) DESC, e.id DESC LIMIT ? OFFSET ?`)
461
470
  .all(...params, limit, offset)
462
471
  .map((row) => emailOf(database, row));
472
+ return withTypes(database, emails);
463
473
  },
464
474
  async emailRefs(filter = {}) {
465
- const [where, params] = emailWhere(filter);
475
+ const [where, params] = emailWhere(database, filter);
466
476
  return database
467
477
  .prepare(`SELECT e.external_id, e.deleted_at IS NOT NULL AS deleted,
468
478
  (SELECT json_group_array(json_object('externalId', b.external_id, 'kind', b.kind))
@@ -477,8 +487,9 @@ export const mailStoreOver = ({ database, orm, now }, stemmerFor = stemmerCache(
477
487
  },
478
488
  ...partialMail(database),
479
489
  ...mailActivity(database),
490
+ ...mailTypeStore(database),
480
491
  async emailFacts(filter = {}) {
481
- const [where, params] = emailWhere(filter);
492
+ const [where, params] = emailWhere(database, filter);
482
493
  return database
483
494
  .prepare(`SELECT e.external_id, e.from_address, e.from_name, e.subject, coalesce(e.received_at, e.sent_at) AS at, e.size,
484
495
  e.read, e.flagged,
@@ -641,7 +652,7 @@ export const mailStoreOver = ({ database, orm, now }, stemmerFor = stemmerCache(
641
652
  return [];
642
653
  const [limit, offset] = page(filter);
643
654
  drainEmailIndex(database, stemmerFor);
644
- const [where, params] = emailWhere({ ...filter, includeDeleted: false });
655
+ const [where, params] = emailWhere(database, { ...filter, includeDeleted: false });
645
656
  return database
646
657
  .prepare(`SELECT e.* FROM email_words w JOIN emails e ON e.id = w.rowid
647
658
  WHERE email_words MATCH ? AND ${where}
@@ -13,7 +13,10 @@ export interface SavedIdentity {
13
13
  /** The profile differs from an earlier one written. */
14
14
  revised: boolean;
15
15
  }
16
- /** A new identity's own person, as ingest gives every identity; one already linked keeps its person. */
16
+ /**
17
+ * A new identity's own person, as ingest gives every identity; one already linked keeps its person, and a sender
18
+ * bot's has none.
19
+ */
17
20
  export declare const ensurePerson: (orm: Orm, identity: number, name: string | null, at: number) => void;
18
21
  /** Every new identity gets its own person; linking two is a later, recorded act. */
19
22
  export declare const identityOf: (context: StoreContext, provider: Provider, nativeId: Id, name: string | null, facts?: Facts) => number;
@@ -6,7 +6,7 @@ import { folded } from "./folded.js";
6
6
  import { holdingText } from "./note-index.js";
7
7
  import { resolvePersonLinks } from "./person-resolution.js";
8
8
  import { bound } from "./query-filter.js";
9
- import { accountIdentities, accounts, aliases, chatMembers, chats, identities, identityLinkEvents, identityLinks, identityRevisions, messages, persons, } from "./schema.js";
9
+ import { accountIdentities, accounts, aliases, chatMembers, chats, identities, identityLinkEvents, identityLinks, identityRevisions, messages, persons, senderBotIdentities, } from "./schema.js";
10
10
  import { trigramPart } from "./trigram-match.js";
11
11
  import { toIso } from "./values.js";
12
12
  /** The source's every phone and address as a JSON patch of `metadata`; `undefined` when it gave no list. */
@@ -94,10 +94,19 @@ const revise = (orm, identity, next, at, before) => {
94
94
  writeRevision(orm, identity, { ...next, marks }, at);
95
95
  return last !== undefined;
96
96
  };
97
- /** A new identity's own person, as ingest gives every identity; one already linked keeps its person. */
97
+ /**
98
+ * A new identity's own person, as ingest gives every identity; one already linked keeps its person, and a sender
99
+ * bot's has none.
100
+ */
98
101
  export const ensurePerson = (orm, identity, name, at) => {
99
102
  if (orm.select({ id: identityLinks.identityId }).from(identityLinks).where(eq(identityLinks.identityId, identity)).get())
100
103
  return;
104
+ if (orm
105
+ .select({ id: senderBotIdentities.identityId })
106
+ .from(senderBotIdentities)
107
+ .where(eq(senderBotIdentities.identityId, identity))
108
+ .get())
109
+ return;
101
110
  const person = Number(orm.insert(persons).values({ name, createdAt: at, updatedAt: at }).returning({ pk: persons.id }).get()?.pk);
102
111
  orm
103
112
  .insert(identityLinks)
@@ -2,6 +2,7 @@ import { CliError } from "@wirecat/cli-base";
2
2
  import { pointerPairs } from "./entity-types.js";
3
3
  import { settleLinks } from "./identity-link-rows.js";
4
4
  import { mergePerson } from "./person-links.js";
5
+ import { rekeyIntoBot } from "./sender-bots.js";
5
6
  import { write } from "./transaction.js";
6
7
  const quoted = (name) => `"${name.replace(/"/g, '""')}"`;
7
8
  const columnsOf = (database, table) => database.prepare("SELECT name, pk, type FROM pragma_table_info(?)").all(table);
@@ -144,6 +145,7 @@ export const rekeyIdentity = (context, provider, { from, to, phone }, by) => {
144
145
  return "renamed";
145
146
  }
146
147
  const keptId = Number(kept.id);
148
+ rekeyIntoBot(database, oldId, keptId, context.now());
147
149
  const [mine, theirs] = [personOfIdentity(database, oldId), personOfIdentity(database, keptId)];
148
150
  if (mine !== undefined && theirs !== undefined && mine !== theirs)
149
151
  persons.push(mergePerson(context, mine, theirs, { method: "identity-rekey", by }));
@@ -6,7 +6,7 @@ import { type MeetingProjectsStore } from "./meeting-projects.js";
6
6
  import type { Author } from "./memories.js";
7
7
  import { type Link } from "./notes.js";
8
8
  import type { StoreContext } from "./open.js";
9
- import { type OrganizationsStore } from "./organizations.js";
9
+ import { type Organization, type OrganizationsStore } from "./organizations.js";
10
10
  import type { ProposedAction } from "./proposed-actions.js";
11
11
  import { type KnowledgeRelation, type LinkDecision, type RelateInput, type RelationUpdate, type Scored } from "./relation-proposals.js";
12
12
  import { type RelationReads } from "./relation-reads.js";
@@ -74,14 +74,7 @@ export interface Annotation {
74
74
  export declare const ORGANIZATION_KINDS: readonly ["company", "team", "family", "community"];
75
75
  export declare const PROJECT_TYPES: readonly ["work", "client", "personal", "oss", "other"];
76
76
  export declare const SCOPES: readonly ["personal", "work"];
77
- export interface Organization {
78
- id: string;
79
- ref: string;
80
- kind: (typeof ORGANIZATION_KINDS)[number];
81
- name: string;
82
- scope: (typeof SCOPES)[number];
83
- createdAt: string;
84
- }
77
+ export type { Organization } from "./organizations.js";
85
78
  export interface Project {
86
79
  id: string;
87
80
  ref: string;
@@ -247,6 +247,12 @@ export const MANIFEST = [
247
247
  { name: "20261123022342_version-72-document-history", version: 72, minCompatible: 56 },
248
248
  { name: "20261123022347_version-72-document-changes-trigger", version: 72, minCompatible: 56 },
249
249
  { name: "20261123230507_version-73-autoincrement", version: 73, minCompatible: 73, tables: V73_TABLES },
250
+ { name: "20261125025700_version-74-sender-bots", version: 74, minCompatible: 73 },
251
+ { name: "20261125025709_version-74-sender-bot-triggers", version: 74, minCompatible: 73 },
252
+ { name: "20261125111113_version-75-bot-identities", version: 75, minCompatible: 73 },
253
+ { name: "20261125111118_version-75-bot-identities-moved", version: 75, minCompatible: 73 },
254
+ { name: "20261125183530_version-76-mail-types", version: 76, minCompatible: 73 },
255
+ { name: "20261125183555_version-76-mail-type-triggers", version: 76, minCompatible: 73 },
250
256
  ];
251
257
  export const generatedMigrations = (manifest = MANIFEST, generated = GENERATED) => {
252
258
  const migrations = [];
@@ -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. */
@@ -2093,5 +2093,82 @@ export const GENERATED = [
2093
2093
  "CREATE INDEX `transaction_splits_by_category_folded` ON `transaction_splits` (`category_folded`);",
2094
2094
  "CREATE INDEX `transaction_splits_by_project_id` ON `transaction_splits` (`project_id`);"
2095
2095
  ]
2096
+ },
2097
+ {
2098
+ "name": "20261125025700_version-74-sender-bots",
2099
+ "statements": [
2100
+ "CREATE TABLE `sender_bot_moves` (\n\t`id` integer PRIMARY KEY AUTOINCREMENT,\n\t`identity_id` integer NOT NULL,\n\t`from_person_id` integer,\n\t`from_bot_id` integer,\n\t`to_person_id` integer,\n\t`to_bot_id` integer,\n\t`author` text NOT NULL,\n\t`reason` text,\n\t`created_at` integer NOT NULL\n);",
2101
+ "CREATE TABLE `sender_bots` (\n\t`id` integer PRIMARY KEY AUTOINCREMENT,\n\t`person_id` integer NOT NULL UNIQUE,\n\t`name` text,\n\t`organization_id` integer,\n\t`author` text NOT NULL,\n\t`reason` text,\n\t`created_at` integer NOT NULL,\n\t`updated_at` integer NOT NULL\n);",
2102
+ "CREATE INDEX `emails_by_list_id` ON `emails` (coalesce(json_extract(headers, '$.\"list-id\"'), json_extract(metadata, '$.listId')));",
2103
+ "CREATE INDEX `sender_bot_moves_by_identity_id` ON `sender_bot_moves` (`identity_id`);"
2104
+ ]
2105
+ },
2106
+ {
2107
+ "name": "20261125025709_version-74-sender-bot-triggers",
2108
+ "statements": [
2109
+ "-- No foreign keys on the bot tables, so an older build that erases a person or an organization, or purges an account,\n-- still can; these drop or clear their rows with it.\nCREATE TRIGGER sender_bots_person_ad AFTER DELETE ON persons BEGIN\n DELETE FROM sender_bots WHERE person_id = OLD.id;\nEND;",
2110
+ "CREATE TRIGGER sender_bots_organization_ad AFTER DELETE ON organizations BEGIN\n UPDATE sender_bots SET organization_id = NULL WHERE organization_id = OLD.id;\nEND;",
2111
+ "CREATE TRIGGER sender_bot_moves_identity_ad AFTER DELETE ON identities BEGIN\n DELETE FROM sender_bot_moves WHERE identity_id = OLD.id;\nEND;",
2112
+ "CREATE TRIGGER person_kind_sender_bot_ai AFTER INSERT ON sender_bots BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id = NEW.person_id;\nEND;",
2113
+ "CREATE TRIGGER person_kind_sender_bot_ad AFTER DELETE ON sender_bots BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id = OLD.person_id;\nEND;",
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
+ "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
+ ]
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
+ ]
2096
2173
  }
2097
2174
  ];
@@ -1,10 +1,21 @@
1
1
  import { type QueryAst } from "@wirecat/cli-base/query";
2
+ import type { Sector } from "../../domain/organization-sectors.js";
2
3
  import type { Decider } from "../decisions.js";
3
- import type { Organization } from "./knowledge.js";
4
+ import type { ORGANIZATION_KINDS, SCOPES } from "./knowledge.js";
4
5
  import type { StoreContext } from "./open.js";
5
6
  import { type OrganizationFilter } from "./organization-categories.js";
6
7
  import { type OrganizationErasure } from "./organization-erase.js";
7
8
  type Row = Record<string, unknown>;
9
+ export interface Organization {
10
+ id: string;
11
+ ref: string;
12
+ kind: (typeof ORGANIZATION_KINDS)[number];
13
+ name: string;
14
+ scope: (typeof SCOPES)[number];
15
+ /** What it does, from the company domains it holds (`domain-organizations.ts`); none for most. */
16
+ sector: Sector | null;
17
+ createdAt: string;
18
+ }
8
19
  export declare const organizationOf: (row: Row) => Organization;
9
20
  export interface OrganizationsStore {
10
21
  /** At most 500, by name; with `filter.category`, only that category's, chosen in SQL. */
@@ -1,6 +1,7 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { evaluate, timezoneOf, walkQuery } from "@wirecat/cli-base/query";
3
3
  import { ORGANIZATIONS_QUERY } from "../knowledge-query.js";
4
+ import { refuseDomainsOf } from "./domain-organizations.js";
4
5
  import { categorySql } from "./organization-categories.js";
5
6
  import { eraseOrganization } from "./organization-erase.js";
6
7
  import { queryFilter } from "./query-filter.js";
@@ -12,10 +13,17 @@ export const organizationOf = (row) => ({
12
13
  kind: row.kind,
13
14
  name: String(row.name),
14
15
  scope: row.scope,
16
+ sector: JSON.parse(String(row.metadata ?? "{}")).sector ?? null,
15
17
  createdAt: new Date(Number(row.created_at)).toISOString(),
16
18
  });
17
19
  export const organizationsStoreOver = (context) => ({
18
- eraseOrganization: async (organization, by, { apply }) => write(context.database, () => eraseOrganization(context, organization, by, apply)),
20
+ eraseOrganization: async (organization, by, { apply }) => write(context.database, () => {
21
+ const id = Number(/([1-9]\d*)$/u.exec(organization.trim())?.[1]);
22
+ // Read before the erase takes the addresses; kept only if the erase goes through.
23
+ if (apply && Number.isInteger(id))
24
+ refuseDomainsOf(context.database, id, context.now());
25
+ return eraseOrganization(context, organization, by, apply);
26
+ }),
19
27
  ...organizationsReadsOver(context),
20
28
  });
21
29
  const organizationsReadsOver = ({ database, now }) => ({
@@ -5,8 +5,10 @@ import { spellings, variantKey } from "../../domain/name-variants.js";
5
5
  import { isAutomatedName, isCompanyName, PERSON_KINDS, } from "../../domain/person-kinds.js";
6
6
  import { isQueryOnly } from "../driver.js";
7
7
  import { fold } from "../normalize.js";
8
+ import { groupByDomain } from "./domain-organizations.js";
8
9
  import { mergedAwaySql } from "./merged-persons.js";
9
10
  import { ALWAYS_SHOWN, shownReasons } from "./person-ties.js";
11
+ import { hasLegacyBots, ownerPeopleOf, ruleBotsBack, ruleToBot, settleLegacyBots } from "./sender-bots.js";
10
12
  import { senderSignalsOf, sentMailOf } from "./sender-signals.js";
11
13
  import { mergedAssignees } from "./task-board.js";
12
14
  import { hiddenTestPeople } from "./test-people.js";
@@ -108,6 +110,8 @@ const factsOf = (database, scope) => {
108
110
  organization: false,
109
111
  twoWay: false,
110
112
  messages: 0,
113
+ identities: held.length,
114
+ programIdentities: 0,
111
115
  };
112
116
  const source = (row) => ({
113
117
  provider: String(row.provider),
@@ -129,6 +133,8 @@ const factsOf = (database, scope) => {
129
133
  one.organization ||= owned.has(identity);
130
134
  one.twoWay ||= twoWay.has(identity);
131
135
  one.messages += messages.get(identity) ?? 0;
136
+ if (Number(row.bot) === 1 || (email !== null && (isNoReplyAddress(email) || isNotificationAddress(email))))
137
+ one.programIdentities += 1;
132
138
  }
133
139
  const contact = noFallbacks();
134
140
  // Stable: equal counts keep the identities' stored order.
@@ -156,13 +162,19 @@ const lastContacts = (database, scope) => new Map(database
156
162
  .map((row) => [Number(row.person), Number(row.at)]));
157
163
  /** One misfiled letter is no newsletter. */
158
164
  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. */
166
+ const PROGRAM_SIGNALS = [
167
+ "bot",
168
+ "no-reply",
169
+ "notification-address",
170
+ "auto-submitted",
171
+ "null-return-path",
172
+ "bulk-never-replied",
173
+ ];
159
174
  /** The first rule that holds; the list's contract in the people-clients-digests plan names the same order. */
160
- const kindOf = (shown, facts, ties, mail, test) => {
175
+ const kindOf = (shown, facts, ties, mail, test, keptByOwner = false) => {
161
176
  if (test)
162
177
  return { kind: "test", signals: ["test-data"] };
163
- const always = ties.filter((tie) => ALWAYS_SHOWN.includes(tie));
164
- if (always.length > 0)
165
- return { kind: "person", signals: ties };
166
178
  const emails = facts?.emails ?? [];
167
179
  const automated = [
168
180
  ...(facts?.bot ? ["bot"] : []),
@@ -177,8 +189,11 @@ const kindOf = (shown, facts, ties, mail, test) => {
177
189
  ? ["null-return-path"]
178
190
  : []),
179
191
  ];
192
+ const always = ties.filter((tie) => ALWAYS_SHOWN.includes(tie));
193
+ if (always.length > 0)
194
+ return { kind: "person", signals: ties };
180
195
  // One mailbox's newsletter signal must not hide someone the owner talks to in a private chat.
181
- if (automated.length > 0 && (facts?.bot || !facts?.twoWay))
196
+ if (!keptByOwner && automated.length > 0 && (facts?.bot || !facts?.twoWay))
182
197
  return { kind: "automated", signals: automated };
183
198
  const organization = [
184
199
  ...(facts?.organization ? ["organization"] : []),
@@ -195,10 +210,20 @@ const kindOf = (shown, facts, ties, mail, test) => {
195
210
  return { kind: "stranger", signals: ["no-tie"] };
196
211
  return { kind: "person", signals: ties };
197
212
  };
213
+ /**
214
+ * A program's signal the owner never wrote against, on a person whose every identity is the program's: a person who
215
+ * also has a human's identity linked stays a person with the mark.
216
+ */
217
+ const isProgram = ({ kind, signals }, facts, ties) => kind === "automated" &&
218
+ facts !== undefined &&
219
+ signals.some((signal) => PROGRAM_SIGNALS.includes(signal)) &&
220
+ (facts.bot || (!facts.twoWay && !ties.includes("mail"))) &&
221
+ (facts.identities === 1 || facts.programIdentities === facts.identities);
198
222
  /** Each person with their kind, contact and counts; the last contact is added for the page alone. */
199
223
  const classified = (database, people, scope, reasons = shownReasons(database, scope === "all" ? undefined : scope)) => {
200
224
  const facts = factsOf(database, scope);
201
225
  const test = hiddenTestPeople(database);
226
+ const ownerPeople = ownerPeopleOf(database);
202
227
  const tasks = countsOf(database, TASK_COUNTS, mergedAssignees(database));
203
228
  const mail = new Map(database
204
229
  .prepare(MAIL_COUNTS(scope))
@@ -212,15 +237,18 @@ const classified = (database, people, scope, reasons = shownReasons(database, sc
212
237
  const contact = { username: own?.username ?? null, phone: own?.phone ?? null, email: own?.email ?? null };
213
238
  const shown = displayName(name, { ...contact, name: own?.name ?? null });
214
239
  const ties = reasons.get(id) ?? [];
215
- const { kind, signals } = kindOf(shown, own, ties, mail.get(id), test.has(id));
240
+ const kept = ownerPeople.has(id);
241
+ const worked = kindOf(shown, own, ties, mail.get(id), test.has(id), kept);
242
+ const toBot = !kept && !owner && worked.kind !== "test" && isProgram(worked, own, ties);
216
243
  return {
217
244
  id,
245
+ ...(toBot ? { move: "bot" } : {}),
218
246
  nameOrder: nameOrderOf(shown),
219
247
  person: `person:${id}`,
220
248
  name,
221
249
  displayName: shown,
222
- kind,
223
- kindSignals: signals,
250
+ kind: worked.kind,
251
+ kindSignals: worked.signals,
224
252
  owner,
225
253
  tasks: tasks.get(id) ?? 0,
226
254
  contact: contact.phone ?? contact.email ?? (contact.username === null ? null : `@${contact.username.replace(/^@/, "")}`),
@@ -237,7 +265,7 @@ const withLastContact = (database, people, known) => {
237
265
  const at = known ??
238
266
  lastContacts(database, people.map(({ id }) => id));
239
267
  const sent = sentMailOf(database, people.map(({ id }) => id));
240
- return people.map(({ id, nameOrder: _, emails, twoWay, ...person }) => {
268
+ return people.map(({ id, nameOrder: _, emails, twoWay, move: __, ...person }) => {
241
269
  const time = at.get(id);
242
270
  const { ties } = person;
243
271
  return {
@@ -258,7 +286,7 @@ const byName = (a, b) => a.nameOrder < b.nameOrder ? -1 : a.nameOrder > b.nameOr
258
286
  * Bump when what decides a kind, a name's order or a count changes in code (the word lists, `BULK_MIN`, the ties):
259
287
  * every stored one is worked out again on the next list.
260
288
  */
261
- const KIND_RULES = "6";
289
+ const KIND_RULES = "9";
262
290
  const RULES_KEY = "people.kind_rules";
263
291
  /** Past this many people to work out, one pass over everyone beats a lookup per person. */
264
292
  const WHOLE_PASS = 20_000;
@@ -298,6 +326,33 @@ const workOut = (database, all, most) => {
298
326
  }));
299
327
  };
300
328
  const keep = (database, worked) => {
329
+ const at = Date.now();
330
+ settleLegacyBots(database, at);
331
+ ruleBotsBack(database, at);
332
+ const bots = [];
333
+ for (const person of worked)
334
+ if (person.move === "bot" && person.kind !== MERGED) {
335
+ bots.push({
336
+ id: ruleToBot(database, person.id, person.kindSignals.join(", "), at),
337
+ displayName: person.displayName,
338
+ holds: true,
339
+ bot: true,
340
+ });
341
+ person.kind = MERGED;
342
+ }
343
+ const keptAsPeople = ownerPeopleOf(database);
344
+ groupByDomain(database, [
345
+ ...bots,
346
+ ...worked
347
+ .filter((person) => !person.owner && person.kind !== MERGED && person.kind !== "test")
348
+ .map((person) => ({
349
+ id: person.id,
350
+ displayName: person.displayName,
351
+ holds: !keptAsPeople.has(person.id) &&
352
+ person.kind === "organization" &&
353
+ person.kindSignals.includes("role-address"),
354
+ })),
355
+ ], at);
301
356
  const row = database.prepare("UPDATE persons SET kind = ?, name_order = ?, messages_from = ?, task_count = ?, last_contact = ? WHERE id = ?");
302
357
  for (const person of worked)
303
358
  row.run(person.kind, person.nameOrder, person.messagesFrom, person.tasks, person.lastContact ?? null, person.id);
@@ -313,6 +368,9 @@ const keep = (database, worked) => {
313
368
  * Answers whether every stored one is current.
314
369
  */
315
370
  export const storeKinds = (database) => {
371
+ // A 1.0 build keeps the kinds of the people it sorts onto a bot, so nothing else would bring their bot here.
372
+ if (!isQueryOnly(database) && hasLegacyBots(database))
373
+ writeBatch(database, () => settleLegacyBots(database, Date.now()));
316
374
  if (isQueryOnly(database))
317
375
  return (rulesOf(database) === KIND_RULES &&
318
376
  database.prepare("SELECT 1 FROM persons WHERE kind IS NULL LIMIT 1").get() === undefined);
@@ -500,7 +558,7 @@ export const similarPeople = (database, typed, limit) => {
500
558
  }));
501
559
  const byId = new Map(people.map((person) => [person.id, person]));
502
560
  const ordered = [...sameName.keys()].flatMap((id) => byId.get(id) ?? []);
503
- const rows = classified(database, ordered, [...sameName.keys()], ties).filter(({ kind }) => kind !== "test");
561
+ const rows = classified(database, ordered, [...sameName.keys()], ties).filter(({ kind, move }) => kind !== "test" && move === undefined);
504
562
  const same = rows.map(({ id }) => sameName.get(id) === true);
505
563
  return withLastContact(database, rows).map((person, at) => ({ ...person, sameName: same[at] === true }));
506
564
  };
@@ -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) => {